143 lines
7.7 KiB
C#

using System.IO;
using System.IO.Pipes;
using System.Threading;
using System.Threading.Tasks;
using PlotDirector.Companion.Protocol;
namespace PlotDirector.Companion.Client;
public sealed class AgentLink : IDisposable
{
private readonly string pipeName;
private readonly Guid instanceId;
private readonly Func<NamedPipeClientStream, bool> verifyServer;
private readonly Action? startAgent;
private readonly object gate = new();
private readonly Dictionary<Guid, DocumentDescriptor> documents = new();
private readonly CancellationTokenSource stop = new();
private readonly BoundedMailbox mailbox = new();
private long sequence;
private int disposed;
private int resetRequested;
private Task? worker;
private DateTime lastLaunch;
public int QueueDepth => mailbox.Depth;
public event Action<Message>? Received;
public event Action<string>? StateChanged;
public AgentLink(string pipeName, Guid instanceId, Func<NamedPipeClientStream, bool> verifyServer, Action? startAgent = null)
{ this.pipeName = pipeName; this.instanceId = instanceId; this.verifyServer = verifyServer; this.startAgent = startAgent; }
public void Start() { lock (gate) { if (worker == null) worker = Task.Run(RunAsync); } }
public bool Register(DocumentDescriptor descriptor)
{
lock (gate)
{
if (!documents.ContainsKey(descriptor.SessionId) && documents.Count >= ProtocolVersion.MaxDocuments) return false;
documents[descriptor.SessionId] = descriptor;
}
var accepted = TryPost(new Message { Kind = "document", Documents = new[] { descriptor } });
if (!accepted) Reset();
return accepted;
}
public void Retire(Guid sessionId)
{
lock (gate) documents.Remove(sessionId);
// If lifecycle delivery is backpressured, force a reconciled connection.
if (!TryPost(new Message { Kind = "close", SessionId = sessionId })) Reset();
}
private NamedPipeClientStream? activePipe;
public void Reset()
{
// Even handle cancellation/closure stays off the Office callback thread.
if (Interlocked.Exchange(ref resetRequested,1) != 0) return;
_ = Task.Run(() => {
try { NamedPipeClientStream? pipe; lock (gate) pipe = activePipe; try { pipe?.Dispose(); } catch (IOException) { } }
finally { Volatile.Write(ref resetRequested,0); }
});
}
public bool TryPost(Message message)
{
if (Volatile.Read(ref disposed) != 0 || stop.IsCancellationRequested) return false;
message.WordInstanceId = instanceId;
return mailbox.TryPost(message);
}
private Message Reconcile()
{
lock (gate) return new Message { Kind = "reconcile", WordInstanceId = instanceId, Sequence = Interlocked.Increment(ref sequence), Documents = documents.Values.ToArray() };
}
private async Task ExchangeAsync(Stream pipe, Message message, CancellationToken cancellation)
{
using (var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation))
{
timeout.CancelAfter(TimeSpan.FromSeconds(3));
if (message.Kind != "hello") message.Sequence = Interlocked.Increment(ref sequence);
// Framework pipe cancellation can depend on the underlying operation. Closing
// the pipe on expiry is the final bound, and runs off Word's UI thread.
using (timeout.Token.Register(() => { try { pipe.Dispose(); } catch (IOException) { } }))
{
await FrameCodec.WriteAsync(pipe, message, timeout.Token).ConfigureAwait(false);
var response = await FrameCodec.ReadAsync(pipe, timeout.Token).ConfigureAwait(false);
if (response.CorrelationId != message.CorrelationId || response.Version != ProtocolVersion.Current)
throw new InvalidDataException("IPC response identity/version mismatch.");
if (response.Status == "unsupported-version" || (message.Kind == "hello" && (response.Status != "ready" || !ProtocolVersion.SupportsRequiredCapabilities(response.Capabilities))))
throw new InvalidDataException("Incompatible agent protocol/capabilities.");
Received?.Invoke(response);
}
}
}
private async Task RunAsync()
{
var attempt = 0;
while (!stop.IsCancellationRequested)
{
try
{
using (var pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous))
{
lock (gate) activePipe = pipe;
await pipe.ConnectAsync(700, stop.Token).ConfigureAwait(false);
if (!verifyServer(pipe)) throw new UnauthorizedAccessException("Unexpected agent owner.");
await ExchangeAsync(pipe, new Message { Kind = "hello", WordInstanceId = instanceId, Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability+","+ProtocolVersion.CaptureCapability+","+ProtocolVersion.MaintenanceCapability+","+ProtocolVersion.ParagraphCapability }, stop.Token).ConfigureAwait(false);
mailbox.Clear(); // Reconcile authoritative open documents; never replay stale extraction fragments.
await ExchangeAsync(pipe, Reconcile(), stop.Token).ConfigureAwait(false);
attempt = 0; StateChanged?.Invoke("connected");
var lastExchange = DateTime.UtcNow;
while (!stop.IsCancellationRequested)
{
if (mailbox.TryTake(out var message))
{
await ExchangeAsync(pipe, message!, stop.Token).ConfigureAwait(false);
lastExchange = DateTime.UtcNow;
}
else if (DateTime.UtcNow - lastExchange > TimeSpan.FromSeconds(1))
{
await ExchangeAsync(pipe,new Message { Kind="ping", WordInstanceId=instanceId },stop.Token).ConfigureAwait(false);
lastExchange = DateTime.UtcNow;
}
else await Task.Delay(25, stop.Token).ConfigureAwait(false);
}
}
}
catch (Exception ex) when (ex is IOException || ex is InvalidDataException || ex is TimeoutException || ex is OperationCanceledException || ex is UnauthorizedAccessException || ex is ObjectDisposedException || ex is System.Runtime.Serialization.SerializationException)
{
if (stop.IsCancellationRequested) break;
StateChanged?.Invoke("offline");
if (DateTime.UtcNow - lastLaunch > TimeSpan.FromSeconds(30))
{
lastLaunch = DateTime.UtcNow;
try { startAgent?.Invoke(); } catch (Exception launchError) when (launchError is IOException || launchError is System.ComponentModel.Win32Exception || launchError is InvalidOperationException) { }
}
try { await Task.Delay(Math.Min(5000, 250 * ++attempt), stop.Token).ConfigureAwait(false); } catch (OperationCanceledException) { }
}
finally { lock (gate) activePipe = null; }
}
}
// Never join the worker from an Office callback or hold the Word thread for shutdown.
public void Dispose()
{
if (Interlocked.Exchange(ref disposed,1) != 0) return;
mailbox.Clear(); _ = Task.Run(() => { stop.Cancel(); Reset(); });
}
public Task Completion => worker ?? Task.CompletedTask;
}