using System.Diagnostics; namespace Febe.Core.Engine; /// Who uses the one page of Febe's browser. public enum PageUser { /// The engine: a recipe of a session. Engine, /// The profile search (issue #37). Search, } /// /// One page, two users (issue #37): the engine's recipes and the profile search take turns on Febe's single browser /// page. A FIFO queue with one holder at a time; cancellable; no timers. The engine takes a turn at the start of each /// recipe and gives it back before an action that opens a page when the search is waiting (); /// the search takes it for one step (and keeps it while Alberto keeps typing, bounded by the search itself). /// /// The session never stops for a search: the search only slides in between two engine actions. public sealed class PageTurns { private readonly Lock _gate = new(); private readonly LinkedList _queue = new(); private PageTurn? _holder; private PageUser? _lastUser; private bool _searchTouchedPage; private bool _restOwed; private long _generation; private List? _freeWaiters; /// Raised after every rest of the page (the search's photo queue forgets its addresses). public event Action? Rested; /// Raised when the rest of the page is left to the search (). public event Action? RestLeftToSearch; /// /// Changes every time a page is opened or put to rest: what the search typed in the box holds only within one /// generation (the engine may open pages between two search steps without the search seeing it). /// public long Generation { get { lock (_gate) { return _generation; } } } /// /// The engine wanted to rest the page while the search held or waited for it (end of a session, Alberto let go /// of the browser): the search rests it when it is done, no session running. Cleared by a rest, by a page the /// engine opens (the next session rests it), or by . /// public bool RestOwed { get { lock (_gate) { return _restOwed; } } } /// Who opened the page last (null before anyone did, or after a rest). public PageUser? LastUser { get { lock (_gate) { return _lastUser; } } } /// True from a search step until the next page the engine opens: the page state of a recipe may be gone. public bool SearchTouchedPage { get { lock (_gate) { return _searchTouchedPage; } } } /// Who holds the page now, if anyone. public PageUser? Holder { get { lock (_gate) { return _holder?.User; } } } /// True while waits for a turn. public bool IsWaiting(PageUser user) { lock (_gate) { return _queue.Any(w => w.Turn.User == user); } } /// Waits for a turn of ; dispose the result to give it back. public async ValueTask TakeAsync(PageUser user, CancellationToken ct) { var turn = new PageTurn(this, user); await AcquireAsync(turn, ct).ConfigureAwait(false); return turn; } /// /// When the other user waits, gives the page to it and waits to have it back (FIFO, so right after the other's /// step). Returns true when it yielded. Does nothing when does not hold the page. /// public async ValueTask YieldAsync(PageTurn turn, CancellationToken ct) { ArgumentNullException.ThrowIfNull(turn); var other = turn.User == PageUser.Engine ? PageUser.Search : PageUser.Engine; lock (_gate) { if (!ReferenceEquals(_holder, turn) || !_queue.Any(w => w.Turn.User == other)) { return false; } ReleaseLocked(turn); } await AcquireAsync(turn, ct).ConfigureAwait(false); return true; } /// The engine's current turn, for the recipes' yield points; null when the engine holds none. public PageTurn? EngineTurn { get { lock (_gate) { return _holder is { User: PageUser.Engine } turn ? turn : null; } } } /// /// A turn for a navigation of the engine outside its recipes (the rest page, Alberto's login page): at once when /// the page is free. When the search holds or waits for the page, returns null and records that the rest is left to /// the search (): it rests the page itself when it is done. Otherwise waits for the turn. /// public async ValueTask TakeForRestAsync(CancellationToken ct) { var turn = new PageTurn(this, PageUser.Engine); bool leftToSearch; lock (_gate) { if (_holder is null && _queue.Count == 0) { _holder = turn; return turn; } leftToSearch = _holder?.User == PageUser.Search || _queue.Any(w => w.Turn.User == PageUser.Search); if (leftToSearch) { _restOwed = true; } } if (leftToSearch) { RestLeftToSearch?.Invoke(); return null; } await AcquireAsync(turn, ct).ConfigureAwait(false); return turn; } /// The search will not rest the page after all (it stays as it is after a verification, no browser). public void ForgetOwedRest() { lock (_gate) { _restOwed = false; } } /// Completes when nobody holds the page and nobody waits. public Task WhenFreeAsync(CancellationToken ct) { TaskCompletionSource tcs; lock (_gate) { if (_holder is null && _queue.Count == 0) { return Task.CompletedTask; } tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); (_freeWaiters ??= []).Add(tcs); } return tcs.Task.WaitAsync(ct); } /// A page was opened by . public void NoteOpened(PageUser user) { lock (_gate) { _lastUser = user; _searchTouchedPage = user == PageUser.Search; _generation++; if (user == PageUser.Engine) { // A session is on the page again: its end rests it. _restOwed = false; } } } /// The search used the page (typed, opened its panel): the engine's page state may be gone. public void NoteSearchUsedPage() { lock (_gate) { _searchTouchedPage = true; } } /// The page went to rest (spec ยง6.1). public void NoteRested() { lock (_gate) { _lastUser = null; _searchTouchedPage = false; _restOwed = false; _generation++; } Rested?.Invoke(); } internal void Release(PageTurn turn) { lock (_gate) { if (ReferenceEquals(_holder, turn)) { ReleaseLocked(turn); } } } private async ValueTask AcquireAsync(PageTurn turn, CancellationToken ct) { Waiter waiter; lock (_gate) { if (_holder is null && _queue.Count == 0) { _holder = turn; return; } waiter = new Waiter(turn, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)); waiter.Node = _queue.AddLast(waiter); } try { await waiter.Ready.Task.WaitAsync(ct).ConfigureAwait(false); } catch (OperationCanceledException) { lock (_gate) { if (waiter.Node?.List is not null) { _queue.Remove(waiter.Node); NotifyFreeLocked(); throw; } // Granted while being cancelled: give it back at once. if (ReferenceEquals(_holder, turn)) { ReleaseLocked(turn); } } throw; } } private void ReleaseLocked(PageTurn turn) { Debug.Assert(ReferenceEquals(_holder, turn), "Only the holder gives the page back."); _holder = null; if (_queue.First is { } first) { _queue.RemoveFirst(); first.Value.Node = null; _holder = first.Value.Turn; first.Value.Ready.TrySetResult(); return; } NotifyFreeLocked(); } private void NotifyFreeLocked() { if (_holder is not null || _queue.Count > 0 || _freeWaiters is null) { return; } foreach (var waiter in _freeWaiters) { waiter.TrySetResult(); } _freeWaiters = null; } private sealed class Waiter(PageTurn turn, TaskCompletionSource ready) { public PageTurn Turn { get; } = turn; public TaskCompletionSource Ready { get; } = ready; public LinkedListNode? Node { get; set; } } } /// A turn on the page; disposing it gives the page back (to the next in the queue). public sealed class PageTurn : IAsyncDisposable, IDisposable { private readonly PageTurns _owner; internal PageTurn(PageTurns owner, PageUser user) { _owner = owner; User = user; } public PageUser User { get; } public void Dispose() => _owner.Release(this); public ValueTask DisposeAsync() { _owner.Release(this); return ValueTask.CompletedTask; } }