PlotDirector/PlotDirector.NativeCompanion/Agent/CloudGateway.Notifications.cs

57 lines
5.4 KiB
C#

using Microsoft.AspNetCore.SignalR.Client;
namespace PlotDirector.Companion.Agent;
public sealed partial class CloudGateway
{
private readonly Func<Uri,Func<Task<string?>>,HubConnection> notificationFactory;
private int notificationRunner;
private volatile string notificationState="Disconnected";
public string NotificationState=>notificationState;
public Action<string>? NotificationTrace {get;set;}
// Authentication generation, exact instance, exact document session. Empty instance/session reconciles all owned documents.
public event Action<Guid,Guid,Guid>? NativeCommandAvailable;
private void NotificationLog(string message){try{NotificationTrace?.Invoke("native-signalr "+message);}catch{/* Diagnostics cannot authorise or prevent execution. */}}
private void Notify(Guid context,Guid instance,Guid session)
{lock(gate){if(disposed||context!=authenticationContext||token==null)return;}NativeCommandAvailable?.Invoke(context,instance,session);}
private static HubConnection CreateNotificationConnection(Uri site,Func<Task<string?>> access)=>new HubConnectionBuilder()
.WithUrl(new Uri(site,"hubs/native-companion-agent"),options=>{options.AccessTokenProvider=access;options.HttpMessageHandlerFactory=handler=>{if(handler is HttpClientHandler client){client.AllowAutoRedirect=false;client.UseCookies=false;}return new NotificationOriginHandler(site,handler);};})
.WithAutomaticReconnect([TimeSpan.Zero,TimeSpan.FromSeconds(2),TimeSpan.FromSeconds(10),TimeSpan.FromSeconds(30)]).Build();
// The approved HTTPS site is also the notification authority; no HTTP or negotiation redirect to another site.
internal sealed class NotificationOriginHandler(Uri site,HttpMessageHandler inner):DelegatingHandler(inner)
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellation)
{
var uri=request.RequestUri;const string path="/hubs/native-companion-agent";
if(uri==null||uri.Scheme!="https"||uri.Authority!=site.Authority||(uri.AbsolutePath!=path&&!uri.AbsolutePath.StartsWith(path+"/",StringComparison.Ordinal)))throw new HttpRequestException("Native notification endpoint left its approved site.");
return base.SendAsync(request,cancellation);
}
}
private bool NotificationSnapshot(out Uri? site,out Guid context,out string? access)
{lock(gate){site=origin;context=authenticationContext;access=token;return !disposed&&site!=null&&access!=null&&health.Authentication=="verified";}}
private bool NotificationCurrent(Uri site,Guid context,string access)
{lock(gate)return !disposed&&origin==site&&authenticationContext==context&&token==access;}
private async Task<string?> NotificationAccess(Uri site,Guid context)
{await EnsureAccess(context);lock(gate){Expire();if(disposed||origin!=site||authenticationContext!=context||token==null)throw new InvalidOperationException("Native notification authentication changed.");return token;}}
public async Task RunCommandNotifications(CancellationToken cancellation)
{
if(Interlocked.CompareExchange(ref notificationRunner,1,0)!=0)throw new InvalidOperationException("Only one native notification connection loop is permitted.");
using var stop=CancellationTokenSource.CreateLinkedTokenSource(cancellation,lifetime.Token);var failures=0;
try{while(!stop.IsCancellationRequested){
if(!NotificationSnapshot(out var site,out var context,out var access)){await Task.Delay(1000,stop.Token);continue;}
try{
await using var connection=notificationFactory(site!,()=>NotificationAccess(site!,context));
var closed=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
connection.On<Guid,Guid,Guid>("NativeCommandAvailable",(instance,session,id)=>{if(instance==Guid.Empty||session==Guid.Empty)return;NotificationLog($"hint Id={id}");Notify(context,instance,session);});
connection.Reconnecting+=_=>{notificationState="Reconnecting";NotificationLog("reconnecting; Presence fallback retained");return Task.CompletedTask;};
connection.Reconnected+=_=>{notificationState="Connected";NotificationLog("reconnected");Notify(context,Guid.Empty,Guid.Empty);return Task.CompletedTask;};
connection.Closed+=_=>{closed.TrySetResult();return Task.CompletedTask;};
await connection.StartAsync(stop.Token);notificationState="Connected";failures=0;NotificationLog("connected");Notify(context,Guid.Empty,Guid.Empty);
try{while(!closed.Task.IsCompleted&&NotificationCurrent(site!,context,access!))await Task.WhenAny(closed.Task,Task.Delay(1000,stop.Token)).WaitAsync(stop.Token);}
finally{notificationState="Disconnected";using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(3));try{await connection.StopAsync(timeout.Token);}catch(OperationCanceledException){}}
}catch(Exception e)when(!stop.IsCancellationRequested){notificationState="Fallback";NotificationLog("unavailable ("+e.GetType().Name+"); Presence fallback retained");}
if(!stop.IsCancellationRequested)await Task.Delay(TimeSpan.FromMilliseconds(Math.Min(30000,1000*Math.Pow(2,Math.Min(failures++,5)))+Random.Shared.Next(250)),stop.Token);
}}catch(OperationCanceledException)when(stop.IsCancellationRequested){}
finally{notificationState="Disconnected";Volatile.Write(ref notificationRunner,0);}
}
}