PlotDirector/PlotLine/Services/NativeCompanion/NativeCommandNotifications.cs

73 lines
5.6 KiB
C#

using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Channels;
using Microsoft.AspNetCore.SignalR;
using PlotLine.Data;
using PlotLine.Hubs;
namespace PlotLine.Services.NativeCompanion;
// Hints only. A full channel drops a wake-up, never a command; normal Presence reconciles it.
public sealed record NativeCommandWake(int User,string Grant,Guid Instance,Guid Session,Guid Id);
public sealed class NativeCommandWakeQueue
{
private readonly object gate=new();
private readonly Dictionary<(int,string,Guid,Guid),NativeCommandWake> pending=[];
private readonly Channel<(int,string,Guid,Guid)> channel=Channel.CreateBounded<(int,string,Guid,Guid)>(new BoundedChannelOptions(256){FullMode=BoundedChannelFullMode.Wait,SingleReader=true});
public int PendingCount {get{lock(gate)return pending.Count;}}
public bool Signal(NativeCommandWake wake)
{
lock(gate){var key=(wake.User,wake.Grant,wake.Instance,wake.Session);if(pending.ContainsKey(key)){pending[key]=wake;return true;}if(pending.Count>=256)return false;pending.Add(key,wake);if(channel.Writer.TryWrite(key))return true;pending.Remove(key);return false;}
}
public async ValueTask<NativeCommandWake> Read(CancellationToken cancellation)
{var key=await channel.Reader.ReadAsync(cancellation);lock(gate){pending.Remove(key,out var wake);return wake!;}}
}
public sealed record NativeAgentConnection(string Id,int User,Guid Stamp,string Grant,Guid? Installation,Guid? Process,DateTimeOffset Expires,Action Abort);
public sealed class NativeAgentConnections(TimeProvider clock)
{
private readonly object gate=new();private readonly Dictionary<string,NativeAgentConnection> connections=[];
public static string Group(int user,string grant)=>$"native-agent:{user}:"+Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(grant)));
public NativeAgentConnection[] Snapshot(){lock(gate)return connections.Values.ToArray();}
public bool Add(NativeAgentConnection entry)
{lock(gate){if(entry.Expires<=clock.GetUtcNow()||connections.Count>=4096||connections.Values.Count(x=>x.User==entry.User)>=16)return false;connections[entry.Id]=entry;return true;}}
public bool Contains(string id){lock(gate)return connections.ContainsKey(id);}
public void Remove(string id){lock(gate)connections.Remove(id);}
public void Abort(string id){NativeAgentConnection? entry;lock(gate)connections.Remove(id,out entry);try{entry?.Abort();}catch{/* The subscription is already removed; a transport abort cannot restore authority. */}}
public void Revoke(int user,string grant){foreach(var entry in Snapshot().Where(x=>x.User==user&&x.Grant==grant))Abort(entry.Id);}
public async Task<bool> Validate(NativeAgentConnection entry,IServiceProvider services)
{
if(entry.Expires<=clock.GetUtcNow())return false;
var user=await services.GetRequiredService<IUserRepository>().GetByIdAsync(entry.User);
if(user==null||user.SecurityStamp!=entry.Stamp||(user.IsLocked&&(!user.LockoutEndUtc.HasValue||user.LockoutEndUtc>clock.GetUtcNow().UtcDateTime)))return false;
return !entry.Installation.HasValue||(entry.Process.HasValue&&await services.GetRequiredService<INativeInstallationRepository>().Validate(entry.Installation.Value,entry.User,entry.Stamp,entry.Process.Value));
}
}
public sealed class NativeCommandNotificationDispatcher(NativeCommandWakeQueue queue,NativePresenceStore presence,NativeAgentConnections connections,IHubContext<NativeAgentCommandHub> hub,IServiceScopeFactory scopes,ILogger<NativeCommandNotificationDispatcher> logger):BackgroundService
{
private void LogFailure(string phase,Exception error){try{logger.LogWarning("Native notification {Phase} unavailable ({ErrorType}); authenticated HTTP recovery remains authoritative",phase,error.GetType().Name);}catch{/* Notification diagnostics cannot stop HTTP recovery. */}}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)=>await Task.WhenAll(Dispatch(stoppingToken),Revalidate(stoppingToken));
private async Task Dispatch(CancellationToken stop)
{
try{while(!stop.IsCancellationRequested){var wake=await queue.Read(stop);try{
if(!presence.HasPendingCommand(wake))continue;
using var scope=scopes.CreateScope();var recipients=new List<string>();
foreach(var entry in connections.Snapshot().Where(x=>x.User==wake.User&&x.Grant==wake.Grant)){
if(await connections.Validate(entry,scope.ServiceProvider)&&connections.Contains(entry.Id))recipients.Add(entry.Id);else connections.Abort(entry.Id);
}
if(recipients.Count==0||!presence.HasPendingCommand(wake))continue;
using var timeout=CancellationTokenSource.CreateLinkedTokenSource(stop);timeout.CancelAfter(TimeSpan.FromSeconds(2));
await hub.Clients.Clients(recipients).SendCoreAsync("NativeCommandAvailable",[wake.Instance,wake.Session,wake.Id],timeout.Token);
}catch(Exception e)when(!stop.IsCancellationRequested){LogFailure("hint",e);}}}
catch(OperationCanceledException)when(stop.IsCancellationRequested){}
}
private async Task Revalidate(CancellationToken stop)
{
try{using var timer=new PeriodicTimer(TimeSpan.FromSeconds(15));while(await timer.WaitForNextTickAsync(stop)){
using var scope=scopes.CreateScope();foreach(var entry in connections.Snapshot())try{if(!await connections.Validate(entry,scope.ServiceProvider))connections.Abort(entry.Id);}catch(Exception e)when(!stop.IsCancellationRequested){connections.Abort(entry.Id);LogFailure("authentication",e);}
}}catch(OperationCanceledException)when(stop.IsCancellationRequested){}
}
}