35 lines
2.3 KiB
C#

using PlotDirector.Companion.Protocol;
using PlotDirector.Companion.Protocol.Manuscript;
namespace PlotDirector.Companion.Agent;
// Value snapshots only. No plaintext disk queue and no identities shared across account contexts.
public sealed class ParagraphSnapshotCache
{
private sealed record Entry(Guid Authentication,Guid Manuscript,long Revision,string Hash,ParagraphOccurrence[] Rows);
private readonly Dictionary<Guid,Entry> entries=[];
private readonly object gate=new();
public ParagraphOccurrence[] Prepare(Guid session,Guid authentication,ManuscriptCapture capture,long revision,string baseHash)
{
var rows=ParagraphReconciliation.Assemble(capture.Paragraphs,capture.End);
lock(gate){
entries.TryGetValue(session,out var entry);
if(entry!=null&&entry.Authentication==authentication&&entry.Manuscript==capture.ManuscriptId&&entry.Hash==baseHash){
rows=ParagraphReconciliation.Compare(entry.Rows,rows).Current;
capture.Delta=ParagraphDeltaCodec.Create(revision,entry.Rows,rows);capture.Paragraphs=[];
}else rows=ParagraphReconciliation.Compare([],rows).Current;
capture.ParagraphIds=rows.Select(p=>p.Id).ToArray();return rows;
}
}
public void Accept(Guid session,Guid authentication,Guid manuscript,ParagraphOccurrence[] rows,NativePresence reply)
{
var ids=reply.CanonicalParagraphIds;if(ids==null||ids.Length!=rows.Length||ids.Any(id=>id==Guid.Empty)||ids.Distinct().Count()!=ids.Length)throw new InvalidDataException("Paragraph acknowledgement is incomplete.");
lock(gate){
foreach(var key in entries.Where(p=>p.Value.Authentication!=authentication).Select(p=>p.Key).ToArray())entries.Remove(key);
for(int i=0;i<rows.Length;i++)rows[i].Id=ids[i];
entries.Remove(session);
while(entries.Count>=8||entries.Values.Sum(e=>e.Rows.Sum(p=>(long)p.Text.Length))+rows.Sum(p=>(long)p.Text.Length)>32*1024*1024){if(entries.Count==0)return;entries.Remove(entries.Keys.First());}
entries[session]=new(authentication,manuscript,reply.ParagraphRevision,ParagraphReconciliation.SnapshotFingerprint(rows),rows);
}
}
public void Remove(Guid session){lock(gate)entries.Remove(session);}
}