33 lines
2.5 KiB
C#
33 lines
2.5 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,Microsoft.Extensions.Options.IOptions<PlotLine.Models.StoryIntelligenceOptions>? options=null)
|
|
{
|
|
private readonly object gate=new();
|
|
private readonly Dictionary<(int,Guid),Entry> jobs=[];
|
|
private readonly SemaphoreSlim workers=new(Math.Max(1,Math.Min(2,options?.Value.MaxGlobalConcurrentAiRequests??2)));
|
|
public Task<AiChapterResult> Run(int user,Guid id,string hash,Func<CancellationToken,Task<AiChapterResult>> work,int book=0)
|
|
{
|
|
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|| (book>0&&jobs.Values.Count(j=>j.Book==book&&!j.Task.IsCompleted)>=Math.Max(1,options?.Value.MaxConcurrentAiRequestsPerBook??2)))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,book);
|
|
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,int book)
|
|
{public int Book=book;public string Hash=hash;public DateTimeOffset Expires=expires;public CancellationTokenSource Stop=stop;public Task<AiChapterResult> Task=System.Threading.Tasks.Task.FromResult(new AiChapterResult());}
|
|
}
|