58 lines
2.8 KiB
C#

using System.Text.Json;
using PlotDirector.Companion.Protocol;
namespace PlotDirector.Companion.Agent;
// Phase 1 durable scheduling foundation, deliberately not attached to a server
// sender until native authentication/revision contracts exist. Contains no prose.
public sealed record DeferredWork(Guid ManuscriptId,int SceneId,long Revision,Guid SnapshotId,
ProseSynchronizationMode Mode,string IdempotencyKey,DateTime NotBeforeUtc);
public sealed class DeferredWorkQueue
{
private readonly string path;
private readonly object gate=new();
private readonly Dictionary<(Guid,int),DeferredWork> work=[];
public const int Capacity=128;
public int Count {get{lock(gate)return work.Count;}}
public DeferredWorkQueue(string directory)
{
Directory.CreateDirectory(directory);path=Path.Combine(directory,"deferred-work.json");
if(!File.Exists(path))return;
if(new FileInfo(path).Length>128*1024)throw new InvalidDataException("Offline queue file exceeds limit.");
foreach(var entry in JsonSerializer.Deserialize<DeferredWork[]>(File.ReadAllText(path))??[])
{Validate(entry);if(work.Count>=Capacity)throw new InvalidDataException("Offline queue exceeds capacity.");work[(entry.ManuscriptId,entry.SceneId)]=entry;}
}
public bool TryEnqueue(DeferredWork entry)
{
Validate(entry);lock(gate)
{
var key=(entry.ManuscriptId,entry.SceneId);
if(work.TryGetValue(key,out var old)&&old.Revision>=entry.Revision)return old.IdempotencyKey==entry.IdempotencyKey;
if(!work.ContainsKey(key)&&work.Count>=Capacity)return false;
var replacement=new Dictionary<(Guid,int),DeferredWork>(work){[key]=entry};Persist(replacement.Values);
work[key]=entry;return true;
}
}
public DeferredWork[] Ready(ProseSynchronizationMode trigger,DateTime now)
{lock(gate)return work.Values.Where(w=>w.Mode==trigger&&w.NotBeforeUtc<=now).ToArray();}
public void Acknowledge(string idempotencyKey)
{
lock(gate)
{
var pending=work.Where(p=>p.Value.IdempotencyKey!=idempotencyKey).ToDictionary();
Persist(pending.Values);work.Clear();foreach(var p in pending)work.Add(p.Key,p.Value);
}
}
private void Persist(IEnumerable<DeferredWork> entries)
{
var temp=path+".new";
File.WriteAllText(temp,JsonSerializer.Serialize(entries));File.Move(temp,path,true);
}
private static void Validate(DeferredWork entry)
{
if(entry.ManuscriptId==Guid.Empty||entry.SceneId<=0||entry.Revision<0||entry.SnapshotId==Guid.Empty
||string.IsNullOrWhiteSpace(entry.IdempotencyKey)||entry.IdempotencyKey.Length>128||!Enum.IsDefined(entry.Mode)||entry.NotBeforeUtc.Kind!=DateTimeKind.Utc)
throw new InvalidDataException("Invalid deferred synchronization work.");
}
}