using System.Collections.Concurrent;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.ScadaBridge.Communication.Grpc;
namespace ZB.MOM.WW.ScadaBridge.Communication.Tests.Grpc;
///
/// Regression tests: the factory's synchronous
/// must not block on the
/// async disposal path (sync-over-async). It must dispose each client through
/// the client's synchronous .
///
public class SiteStreamGrpcClientFactoryDisposeTests
{
///
/// Test client that records whether it was disposed via the sync or async path.
///
private sealed class TrackingClient : SiteStreamGrpcClient
{
/// Gets a value indicating whether the synchronous dispose path was called.
public bool SyncDisposeCalled { get; private set; }
/// Gets a value indicating whether the asynchronous dispose path was called.
public bool AsyncDisposeCalled { get; private set; }
///
public override void Dispose() => SyncDisposeCalled = true;
///
public override ValueTask DisposeAsync()
{
AsyncDisposeCalled = true;
return ValueTask.CompletedTask;
}
}
///
/// Test factory that hands out instances while
/// still exercising the base factory's real caching and disposal machinery.
///
private sealed class TrackingFactory : SiteStreamGrpcClientFactory
{
private readonly ConcurrentBag _created = new();
/// Initializes the factory with a null logger factory.
public TrackingFactory() : base(NullLoggerFactory.Instance) { }
/// Gets the clients this factory has created.
public IReadOnlyCollection Created => _created.ToList();
///
protected override SiteStreamGrpcClient CreateClient(string siteIdentifier, string grpcEndpoint)
{
var client = new TrackingClient();
_created.Add(client);
return client;
}
}
/// Verifies that Dispose disposes clients synchronously and not via the async path.
[Fact]
public void Dispose_DisposesClientsSynchronously_NotViaAsyncPath()
{
var factory = new TrackingFactory();
factory.GetOrCreate("site-a", "http://localhost:5100");
factory.GetOrCreate("site-b", "http://localhost:5200");
factory.Dispose();
Assert.NotEmpty(factory.Created);
Assert.All(factory.Created, c =>
{
Assert.True(c.SyncDisposeCalled, "client should be disposed via synchronous Dispose()");
Assert.False(c.AsyncDisposeCalled, "synchronous Dispose() must not route through DisposeAsync()");
});
}
///
/// Test client whose disposal always throws — stands in for a client whose
/// ReleaseResources hit an on a subscription
/// token source.
///
private sealed class ThrowingClient : SiteStreamGrpcClient
{
///
public override void Dispose() => throw new ObjectDisposedException(nameof(CancellationTokenSource));
///
public override ValueTask DisposeAsync() =>
throw new ObjectDisposedException(nameof(CancellationTokenSource));
}
/// Hands out one throwing client followed by tracking clients.
private sealed class OneThrowingClientFactory : SiteStreamGrpcClientFactory
{
private readonly ConcurrentBag _created = new();
private int _next;
/// Initializes the factory with a null logger factory.
public OneThrowingClientFactory() : base(NullLoggerFactory.Instance) { }
/// Gets the clients this factory has created.
public IReadOnlyCollection Created => _created.ToList();
///
protected override SiteStreamGrpcClient CreateClient(string siteIdentifier, string grpcEndpoint)
{
if (Interlocked.Increment(ref _next) == 1)
{
return new ThrowingClient();
}
var client = new TrackingClient();
_created.Add(client);
return client;
}
}
/// Verifies that DisposeAsync still disposes every other client when one client throws.
/// A task that represents the asynchronous operation.
[Fact]
public async Task DisposeAsync_OneClientThrowing_StillDisposesEveryOtherClient()
{
// The disposal loop used to abort on the first throwing client, leaving every LATER
// client — and its gRPC channel — undisposed for the life of the process.
var factory = new OneThrowingClientFactory();
factory.GetOrCreate("site-a", "http://localhost:5100"); // throwing
factory.GetOrCreate("site-b", "http://localhost:5200");
factory.GetOrCreate("site-c", "http://localhost:5300");
await factory.DisposeAsync();
Assert.Equal(2, factory.Created.Count);
Assert.All(factory.Created, c =>
Assert.True(c.AsyncDisposeCalled, "a throwing client must not strand its peers undisposed"));
}
/// Verifies that Dispose still disposes every other client when one client throws.
[Fact]
public void Dispose_OneClientThrowing_StillDisposesEveryOtherClient()
{
var factory = new OneThrowingClientFactory();
factory.GetOrCreate("site-a", "http://localhost:5100"); // throwing
factory.GetOrCreate("site-b", "http://localhost:5200");
factory.GetOrCreate("site-c", "http://localhost:5300");
factory.Dispose();
Assert.Equal(2, factory.Created.Count);
Assert.All(factory.Created, c =>
Assert.True(c.SyncDisposeCalled, "a throwing client must not strand its peers undisposed"));
}
/// Verifies that Dispose does not deadlock under a single-threaded synchronization context.
[Fact]
public void Dispose_DoesNotDeadlock_UnderSingleThreadedSynchronizationContext()
{
// A strict single-threaded SynchronizationContext: continuations posted to
// it are only pumped by the worker loop. Sync-over-async (blocking the only
// thread on an async continuation that needs that same thread) deadlocks here.
using var ctx = new SingleThreadSyncContext();
Exception? captured = null;
var done = new ManualResetEventSlim();
ctx.Post(_ =>
{
try
{
var factory = new SiteStreamGrpcClientFactory(NullLoggerFactory.Instance);
factory.GetOrCreate("site-a", "http://localhost:5100");
factory.Dispose();
}
catch (Exception ex)
{
captured = ex;
}
finally
{
done.Set();
}
}, null);
Assert.True(done.Wait(TimeSpan.FromSeconds(5)),
"factory.Dispose() did not complete — likely a sync-over-async deadlock");
Assert.Null(captured);
}
/// Minimal single-threaded synchronization context for the deadlock test.
private sealed class SingleThreadSyncContext : SynchronizationContext, IDisposable
{
private readonly BlockingCollection<(SendOrPostCallback cb, object? state)> _queue = new();
private readonly Thread _thread;
/// Initializes the synchronization context.
public SingleThreadSyncContext()
{
_thread = new Thread(Run) { IsBackground = true };
_thread.Start();
}
private void Run()
{
SetSynchronizationContext(this);
foreach (var (cb, state) in _queue.GetConsumingEnumerable())
cb(state);
}
///
public override void Post(SendOrPostCallback d, object? state) => _queue.Add((d, state));
/// Releases the resources held by this instance.
public void Dispose()
{
_queue.CompleteAdding();
_thread.Join(TimeSpan.FromSeconds(2));
}
}
}