using ZB.MOM.WW.MxGateway.Client;
namespace ZB.MOM.WW.MxGateway.Client.Cli;
///
/// Reuses one CLI client per distinct connection configuration across batch-mode lines so each
/// line does not pay a fresh TCP/TLS/HTTP/2 handshake. Disposing the cache disposes every client.
///
internal sealed class CliClientCache : IAsyncDisposable
{
private readonly Dictionary _clients = [];
/// Gets the cached client for the options' connection settings, creating it on first use.
/// The connection options for this command.
/// Creates a client when none is cached.
/// A lease that does not dispose the shared client.
public Lease Acquire(
MxGatewayClientOptions options,
Func factory)
{
string key = string.Join(
'\n',
options.Endpoint,
options.ApiKey,
options.UseTls,
options.CaCertificatePath,
options.ServerNameOverride,
options.RequireCertificateValidation,
options.ConnectTimeout,
options.DefaultCallTimeout,
options.StreamTimeout,
options.KeepAlivePingDelay,
options.KeepAlivePingTimeout);
if (!_clients.TryGetValue(key, out IMxGatewayCliClient? client))
{
client = factory(options);
_clients[key] = client;
}
return Lease.Shared(client);
}
/// Disposes every cached client.
/// A task that represents the asynchronous operation.
public async ValueTask DisposeAsync()
{
foreach (IMxGatewayCliClient client in _clients.Values)
{
await client.DisposeAsync().ConfigureAwait(false);
}
_clients.Clear();
}
/// A client handed to one command; disposes it only when the command owns it.
internal sealed class Lease : IAsyncDisposable
{
private readonly bool _owned;
private Lease(IMxGatewayCliClient client, bool owned)
{
Client = client;
_owned = owned;
}
/// Gets the leased client.
public IMxGatewayCliClient Client { get; }
/// Wraps a client the command created and must dispose.
/// The client.
/// The lease.
public static Lease Owned(IMxGatewayCliClient client) => new(client, owned: true);
/// Wraps a cache-owned client.
/// The client.
/// The lease.
public static Lease Shared(IMxGatewayCliClient client) => new(client, owned: false);
///
public ValueTask DisposeAsync() => _owned ? Client.DisposeAsync() : ValueTask.CompletedTask;
}
}