using Microsoft.Extensions.ObjectPool;
namespace AyCode.Services.SignalRs;
///
/// Request model for tracking pending SignalR requests.
/// Poolable to reduce allocations in high-throughput scenarios.
///
public class SignalRRequestModel : IResettable
{
public DateTime RequestDateTime;
public DateTime ResponseDateTime;
public object? ResponseByRequestId;
public SignalRRequestModel()
{
RequestDateTime = DateTime.UtcNow;
}
public SignalRRequestModel(object responseByRequestId) : this()
{
ResponseByRequestId = responseByRequestId;
}
///
/// Resets the model for reuse from the pool.
///
public bool TryReset()
{
RequestDateTime = default;
ResponseDateTime = default;
ResponseByRequestId = null;
return true;
}
///
/// Initializes the model with a callback for reuse from the pool.
///
public void Initialize(object? responseByRequestId = null)
{
RequestDateTime = DateTime.UtcNow;
ResponseDateTime = default;
ResponseByRequestId = responseByRequestId;
}
}
///
/// Object pool for SignalRRequestModel to reduce allocations.
/// Thread-safe and optimized for concurrent access.
///
public static class SignalRRequestModelPool
{
private static readonly ObjectPool Pool =
new DefaultObjectPoolProvider().Create();
///
/// Gets a SignalRRequestModel from the pool and initializes it.
///
public static SignalRRequestModel Get()
{
var model = Pool.Get();
model.Initialize();
return model;
}
///
/// Gets a SignalRRequestModel from the pool and initializes it with a callback.
///
public static SignalRRequestModel Get(object responseByRequestId)
{
var model = Pool.Get();
model.Initialize(responseByRequestId);
return model;
}
///
/// Returns a SignalRRequestModel to the pool for reuse.
///
public static void Return(SignalRRequestModel model) => Pool.Return(model);
}