using System.Collections.Concurrent; using System.Runtime.CompilerServices; using System.Threading.Channels; using Febe.Web.Connection; namespace Febe.Tests.Server.Support; /// A remote view without browser: the test writes what goes to the page and reads what comes back. internal sealed class FakeRemoteViewHost : IRemoteViewHost { private readonly Lock _gate = new(); private readonly List _opened = []; /// /// The views opened so far, copied under the lock the server writes with: the tests read it from their own thread /// while the server may be adding to it (#46). /// public IReadOnlyList Opened { get { lock (_gate) { return [.. _opened]; } } } public bool Unavailable { get; set; } public Task OpenAsync(CancellationToken ct) { if (Unavailable) { throw new RemoteViewUnavailableException("Il browser di prova non c'รจ."); } var connection = new FakeRemoteViewConnection(); lock (_gate) { if (_opened.LastOrDefault() is { Disposed: false } previous) { previous.End(RemoteViewEnd.Replaced); } _opened.Add(connection); } return Task.FromResult(connection); } } internal sealed class FakeRemoteViewConnection : IRemoteViewConnection { private readonly Channel _output = Channel.CreateUnbounded(); private volatile bool _disposed; private volatile object? _ended; public ConcurrentQueue Inputs { get; } = new(); /// Set by the server's thread, read by the test's: volatile. public bool Disposed { get => _disposed; private set => _disposed = value; } public RemoteViewEnd? Ended { get => (RemoteViewEnd?)_ended; private set => _ended = value; } public void Write(RemoteViewOutput output) => _output.Writer.TryWrite(output); public void End(RemoteViewEnd reason) { Ended = reason; _output.Writer.TryComplete(); } public async IAsyncEnumerable ReadAsync([EnumeratorCancellation] CancellationToken ct) { await foreach (var output in _output.Reader.ReadAllAsync(ct)) { yield return output; } } public Task MouseAsync(RemoteViewMouse input, CancellationToken ct) { Inputs.Enqueue(input); return Task.CompletedTask; } public Task KeyAsync(RemoteViewKey input, CancellationToken ct) { Inputs.Enqueue(input); return Task.CompletedTask; } public Task NavigateAsync(RemoteViewNavigation action, CancellationToken ct) { Inputs.Enqueue(action); return Task.CompletedTask; } public ValueTask DisposeAsync() { Disposed = true; _output.Writer.TryComplete(); return ValueTask.CompletedTask; } }