33 lines
2.2 KiB
C#
33 lines
2.2 KiB
C#
using PlotDirector.Companion.Protocol;
|
|
namespace PlotLine.Services.NativeCompanion;
|
|
|
|
// Bounded process-local idempotency. Restart loses cache: agent never auto-replays after restart.
|
|
public sealed class NativeAnalysisCache(TimeProvider clock)
|
|
{
|
|
private readonly object gate=new();
|
|
private readonly Dictionary<(int,Guid),Entry> jobs=[];
|
|
private readonly SemaphoreSlim workers=new(2);
|
|
public Task<AiChapterResult> Run(int user,Guid id,string hash,Func<CancellationToken,Task<AiChapterResult>> work)
|
|
{
|
|
lock(gate)
|
|
{
|
|
foreach(var key in jobs.Where(j=>j.Value.Task.IsCompleted&&j.Value.Expires<clock.GetUtcNow()).Select(j=>j.Key).ToArray()){jobs[key].Stop.Dispose();jobs.Remove(key);}
|
|
if(jobs.TryGetValue((user,id),out var prior))
|
|
{if(prior.Hash!=hash)throw new ArgumentException("Request ID content mismatch.");return prior.Task;}
|
|
if(jobs.Count>=256||jobs.Count(j=>j.Key.Item1==user&&!j.Value.Task.IsCompleted)>=1)throw new InvalidOperationException("Analysis busy. Wait for the current chapter.");
|
|
var stop=new CancellationTokenSource(TimeSpan.FromMinutes(5));
|
|
var entry=new Entry(hash,clock.GetUtcNow().AddMinutes(30),stop);
|
|
jobs.Add((user,id),entry);entry.Task=Execute();return entry.Task;
|
|
async Task<AiChapterResult> Execute()
|
|
{
|
|
try{await workers.WaitAsync(stop.Token);try{return await work(stop.Token);}finally{workers.Release();}}
|
|
catch(OperationCanceledException){return new(){RequestId=id,State="cancelled",Message="Chapter analysis cancelled or timed out."};}
|
|
catch(Exception){return new(){RequestId=id,State="failed",Message="Chapter analysis failed. Check server configuration or try this chapter again."};}
|
|
}
|
|
}
|
|
}
|
|
public void Cancel(int user,Guid id){lock(gate){if(jobs.TryGetValue((user,id),out var job))job.Stop.Cancel();}}
|
|
private sealed class Entry(string hash,DateTimeOffset expires,CancellationTokenSource stop)
|
|
{public string Hash=hash;public DateTimeOffset Expires=expires;public CancellationTokenSource Stop=stop;public Task<AiChapterResult> Task=System.Threading.Tasks.Task.FromResult(new AiChapterResult());}
|
|
}
|