133 lines
16 KiB
C#
133 lines
16 KiB
C#
using System.Text;
|
|
using PlotDirector.Companion.Protocol;
|
|
using PlotDirector.Companion.Protocol.Manuscript;
|
|
namespace PlotDirector.Companion.Agent;
|
|
public sealed partial class TrayCoordinator
|
|
{
|
|
private sealed class ChapterWork
|
|
{
|
|
public int Book;public Guid Manuscript;public long Revision;public Guid Context,Operation,Command;public bool Busy,Supported,Processing,Begun;public long FailedRevision=-1;public DateTime Started,RetryAfter;
|
|
public ChapterManifest? Manifest;public readonly Dictionary<int,(int Start,int End)> Checked=[];
|
|
public StringBuilder Text=new(),Xml=new();public int Start,End,DocumentEnd,FirstStart=-1;public bool Finished;public bool Wrapped;public readonly HashSet<int> Reviewed=[];public readonly HashSet<int> Visited=[];public string Next="";
|
|
}
|
|
private readonly Dictionary<Guid,ChapterWork> chapterWork=[];
|
|
private readonly SemaphoreSlim chapterProcessing=new(2,2);
|
|
private string ChapterIssue(TrayDocument doc){lock(gate)return chapterWork.TryGetValue(doc.Session,out var work)&&work.FailedRevision==doc.Revision?"needs_review":"";}
|
|
private bool ChapterCapable(Guid instance){lock(gate)return chapterInstances.Contains(instance);}
|
|
private readonly HashSet<Guid> ribbonRequests=[];
|
|
private async Task RequestChapterFromRibbon(TrayDocument doc,long revision)
|
|
{
|
|
int book;Guid context,instance,session;
|
|
lock(gate){if(ribbonRequests.Count>=32||!ribbonRequests.Add(doc.Session))return;book=doc.Book;context=doc.Authentication;instance=doc.Instance;session=doc.Session;}
|
|
try{if(!cloud.Allows(context,book))throw new InvalidOperationException("Connect and select an authorised book first.");var reply=await cloud.RequestChapterRepair(book,new(){InstanceId=instance,SessionId=session,WordRevision=revision},context);lock(gate)if(documents.GetValueOrDefault(session)==doc&&doc.Revision==revision&&doc.Authentication==context){doc.Status=reply.Message;doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;}}
|
|
catch(Exception e)when(NetworkFailure(e)){lock(gate)if(documents.GetValueOrDefault(session)==doc)doc.Status="Chapter request was not accepted: "+e.Message;}
|
|
finally{lock(gate)ribbonRequests.Remove(session);}
|
|
}
|
|
private bool IsChapterCommand(TrayDocument doc,Guid id)=>chapterWork.TryGetValue(doc.Session,out var work)&&id!=Guid.Empty&&work.Command==id;
|
|
private void CancelChapterWork(TrayDocument doc){if(chapterWork.TryGetValue(doc.Session,out var work)){work.Command=Guid.Empty;work.Operation=Guid.Empty;work.Text=new();work.Xml=new();doc.ChapterProgress=null;work.Busy=false;work.FailedRevision=doc.Revision;}}
|
|
private void BeginChapterRepair(TrayDocument doc,Guid operation)
|
|
{
|
|
if(!ChapterCapable(doc.Instance))return;
|
|
var work=GetChapterWork(doc);work.Operation=operation;work.FailedRevision=-1;work.Manifest=null;work.Checked.Clear();work.Reviewed.Clear();work.Visited.Clear();work.Wrapped=false;work.FirstStart=-1;work.Finished=false;work.Command=Guid.Empty;work.Busy=false;
|
|
doc.Status="Repairing existing chapter mappings; accepted scenes and author decisions are retained.";work.Busy=true;work.Started=DateTime.UtcNow;_ = LoadChapterManifest(doc,work);
|
|
}
|
|
private ChapterWork GetChapterWork(TrayDocument doc)
|
|
{
|
|
if(!chapterWork.TryGetValue(doc.Session,out var work)||work.Context!=doc.Authentication||work.Revision!=doc.Revision||work.Book!=doc.Book||work.Manuscript!=doc.Manuscript)chapterWork[doc.Session]=work=new(){Book=doc.Book,Manuscript=doc.Manuscript,Revision=doc.Revision,Context=doc.Authentication};return work;
|
|
}
|
|
private void ObserveChapterPresence(TrayDocument doc,NativePresence reply)
|
|
{
|
|
if(!ChapterCapable(doc.Instance))return;
|
|
lock(gate){if(documents.GetValueOrDefault(doc.Session)!=doc)return;var work=GetChapterWork(doc);work.Supported=reply.ChapterSyncSupported;
|
|
if(work.Manifest!=null&&reply.ParagraphRevision>0&&work.Manifest.Revision!=reply.ParagraphRevision){work.Manifest=null;work.Checked.Clear();work.Visited.Clear();work.Reviewed.Clear();work.Command=Guid.Empty;work.Finished=false;work.Busy=false;work.Wrapped=false;work.FirstStart=-1;work.FailedRevision=-1;}
|
|
if(DateTime.UtcNow<work.RetryAfter||work.Finished||!work.Supported||doc.WordSaved!=true||doc.Book<=0||work.FailedRevision==doc.Revision||doc.Capture!=null)return;
|
|
if(work.Busy){if(work.Command!=Guid.Empty&&work.End>work.Start&&doc.Active&&!work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor<p.Value.End)&&(doc.Cursor<work.Start||doc.Cursor>=work.End)){QueueChapter(doc,work,doc.Cursor);return;}if(DateTime.UtcNow-work.Started>TimeSpan.FromMinutes(2)){work.Busy=false;work.FailedRevision=doc.Revision;doc.Status="Chapter validation timed out. Accepted checkpoints are retained; request Repair to resume.";}return;}
|
|
if(work.Manifest==null){work.Busy=true;work.Started=DateTime.UtcNow;_ = LoadChapterManifest(doc,work);return;}
|
|
var here=work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor<p.Value.End);
|
|
if(!here){QueueChapter(doc,work,doc.Cursor);return;}
|
|
var next=work.Manifest.Chapters.FirstOrDefault(c=>!work.Checked.ContainsKey(c.ChapterId)&&!work.Reviewed.Contains(c.ChapterId)&&(c.State!="Needs review"||work.Operation!=Guid.Empty));
|
|
if(next!=null)QueueChapter(doc,work,next.Start);
|
|
}
|
|
}
|
|
private async Task LoadChapterManifest(TrayDocument doc,ChapterWork work)
|
|
{
|
|
try{var manifest=await cloud.ChapterManifest(doc.Book,doc.Session,doc.Revision,doc.Authentication);
|
|
lock(gate){if(!CurrentChapterWork(doc,work))return;if(manifest.ManuscriptId!=doc.Manuscript)throw new InvalidOperationException("Saved manuscript identity does not match this Word document.");work.Manifest=manifest;work.Busy=false;if(manifest.Mode=="Off"&&work.Operation==Guid.Empty){work.Finished=true;doc.Status="Automatic synchronisation is off. Use Synchronise or Repair for an explicit chapter check.";return;}foreach(var chapter in manifest.Chapters.Where(c=>c.State=="Synchronised"))work.Checked[chapter.ChapterId]=(chapter.Start,chapter.End);doc.Status=$"Chapter index ready: {work.Checked.Count}/{manifest.Chapters.Length} accepted for this Word session.";if(manifest.Chapters.Length>0&&work.Checked.Count==manifest.Chapters.Length){CompleteChapters(doc,work);}else if(manifest.Chapters.Length>0&&!work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor<p.Value.End))QueueChapter(doc,work,doc.Cursor);else{var next=manifest.Chapters.FirstOrDefault(c=>!work.Checked.ContainsKey(c.ChapterId));if(next!=null)QueueChapter(doc,work,next.Start);}}
|
|
}catch(Exception e)when(NetworkFailure(e)){lock(gate)if(CurrentChapterWork(doc,work)){work.Busy=false;doc.Status="Chapter index unavailable: "+e.Message+" Existing import is retained; no full extraction was started.";}}
|
|
}
|
|
private bool CurrentChapterWork(TrayDocument doc,ChapterWork work)=>documents.GetValueOrDefault(doc.Session)==doc&&chapterWork.GetValueOrDefault(doc.Session)==work&&doc.Revision==work.Revision&&doc.Authentication==work.Context&&doc.Book==work.Book&&doc.Manuscript==work.Manuscript;
|
|
private void QueueChapter(TrayDocument doc,ChapterWork work,int position)
|
|
{
|
|
if(chapterWork.Values.Count(w=>w!=work&&w.Busy&&w.Command!=Guid.Empty)>=2){
|
|
if(!doc.Active)return;
|
|
var background=chapterWork.FirstOrDefault(p=>p.Value!=work&&p.Value.Busy&&p.Value.Command!=Guid.Empty&&documents.TryGetValue(p.Key,out var candidate)&&!candidate.Active);
|
|
if(background.Value==null||!documents.TryGetValue(background.Key,out var backgroundDoc))return;
|
|
Queue(backgroundDoc,new(){Kind="chapter-cancel"});background.Value.Command=Guid.Empty;background.Value.Busy=false;background.Value.Text=new();background.Value.Xml=new();
|
|
}
|
|
var command=new AdapterCommand{Kind="chapter-check",OperationId=work.Operation,BookId=doc.Book,Chapter=new(){Start=position}};
|
|
if(Queue(doc,command)){work.Command=command.Id;work.Busy=true;work.Processing=false;work.Begun=false;work.Start=work.End=0;work.Started=DateTime.UtcNow;work.Text.Clear();work.Xml.Clear();doc.Status=$"Checking chapter positions ({work.Checked.Count}/{work.Manifest!.Chapters.Length} accepted); Word prose is unchanged.";}
|
|
}
|
|
private void ChapterFrame(TrayDocument doc,Message message,Message answer)
|
|
{
|
|
if(!chapterWork.TryGetValue(doc.Session,out var work)||!CurrentChapterWork(doc,work)||work.Command!=message.SnapshotId)return;
|
|
if(message.Kind=="adapter-result"&&message.OperationMessage!="ok"){work.Busy=false;work.FailedRevision=doc.Revision;doc.Status=message.OperationMessage;return;}
|
|
if(!message.Kind.StartsWith("chapter-",StringComparison.Ordinal))return;
|
|
if(answer.Status!="ok"){work.Busy=false;work.FailedRevision=doc.Revision;doc.Status="Chapter reading was rejected; accepted checkpoints are unchanged.";return;}
|
|
if(message.Kind=="chapter-begin"){if(work.Begun)return;work.Begun=true;work.Start=message.Start;if(work.FirstStart<0)work.FirstStart=message.Start;work.End=message.End;work.DocumentEnd=message.DocumentEnd;work.Next=message.ChapterTitle;work.Text.Clear();work.Xml.Clear();return;}
|
|
if(message.Kind=="chapter-chunk"){if(!work.Begun||work.Processing)return;
|
|
var value=message.Action=="text"?work.Text:work.Xml;var limit=message.Action=="text"?ChapterFingerprint.MaxCharacters:8*1024*1024;
|
|
if(message.Start!=value.Length||value.Length+message.OperationMessage.Length>limit){work.Busy=false;work.FailedRevision=doc.Revision;doc.Status="Incomplete or oversized chapter frames; no checkpoint accepted.";return;}value.Append(message.OperationMessage);return;
|
|
}
|
|
if(message.Kind=="chapter-end"){if(!work.Begun||work.Processing)return;work.Processing=true;var text=work.Text.ToString();var xml=work.Xml.ToString();work.Text=new();work.Xml=new();_ = ProcessChapter(doc,work,text,xml,work.Command,work.Start,work.End,work.Next,work.Operation);}
|
|
}
|
|
private void AdvanceChapter(TrayDocument doc,ChapterWork work)
|
|
{
|
|
if(work.Manifest==null)return;
|
|
var next=work.End;
|
|
for(int count=0;count<work.Manifest.Chapters.Length+1;count++){
|
|
if(work.Wrapped&&next==work.FirstStart){CompleteChapters(doc,work);return;}
|
|
var cached=work.Checked.FirstOrDefault(p=>p.Value.Start==next&&p.Value.End>next);
|
|
if(cached.Value.End>next){next=cached.Value.End;continue;}
|
|
break;
|
|
}
|
|
if(work.FirstStart==0&&next>=work.DocumentEnd){CompleteChapters(doc,work);return;}
|
|
if(next<work.DocumentEnd){QueueChapter(doc,work,next);return;}
|
|
if(!work.Wrapped){work.Wrapped=true;QueueChapter(doc,work,0);return;}
|
|
CompleteChapters(doc,work);
|
|
}
|
|
private void CompleteChapters(TrayDocument doc,ChapterWork work)
|
|
{
|
|
var expected=work.Manifest!.Chapters.Select(c=>c.ChapterId).Where(work.Checked.ContainsKey).ToArray();var actual=work.Checked.OrderBy(p=>p.Value.Start).Select(p=>p.Key).ToArray();for(int i=0;i<Math.Min(expected.Length,actual.Length);i++)if(expected[i]!=actual[i]){work.Reviewed.Add(expected[i]);work.Reviewed.Add(actual[i]);}
|
|
work.Busy=true;work.Finished=true;work.Started=DateTime.UtcNow;_ = CompleteChapterOperation(doc,work);
|
|
}
|
|
private async Task CompleteChapterOperation(TrayDocument doc,ChapterWork work)
|
|
{
|
|
try{var result=await cloud.FinishChapters(doc.Book,new(){InstanceId=doc.Instance,SessionId=doc.Session,WordRevision=work.Revision,OperationId=work.Operation,ReviewChapterIds=work.Reviewed.Where(id=>id>0).ToArray(),HasIssues=work.Reviewed.Count>0||work.Manifest!.Chapters.Any(c=>!work.Checked.ContainsKey(c.ChapterId))},work.Context);lock(gate)if(CurrentChapterWork(doc,work)){work.Busy=false;doc.Status=result.Message;}}
|
|
catch(Exception e)when(NetworkFailure(e)){lock(gate)if(CurrentChapterWork(doc,work)){work.Busy=false;work.Finished=false;work.Manifest=null;work.RetryAfter=DateTime.UtcNow.AddSeconds(15);doc.Status="Accepted checkpoints are retained; final chapter status will be retried after reconnect: "+e.Message;}}
|
|
}
|
|
private async Task ProcessChapter(TrayDocument doc,ChapterWork work,string text,string xml,Guid command,int start,int end,string nextHeading,Guid operation)
|
|
{
|
|
if(!await chapterProcessing.WaitAsync(0)){lock(gate)if(CurrentChapterWork(doc,work)&&work.Command==command){work.Busy=false;work.Command=Guid.Empty;work.RetryAfter=DateTime.UtcNow.AddSeconds(1);doc.Status="Waiting for bounded chapter processing; accepted checkpoints are retained.";}return;}
|
|
try{
|
|
lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;if(work.Wrapped&&start==work.FirstStart){CompleteChapters(doc,work);return;}}
|
|
var rows=await Task.Run(()=>ChapterFingerprint.ReadXml(xml,text));xml="";text="";
|
|
ChapterManifest manifest;lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;manifest=work.Manifest!;}
|
|
var hash=ChapterFingerprint.Content(rows.Select(p=>p.Text!));
|
|
var candidates=manifest.Chapters.Where(c=>c.HeadingNativeId==rows[0].NativeId).ToArray();
|
|
if(candidates.Length==0&&work.Operation!=Guid.Empty)candidates=manifest.Chapters.Where(c=>c.HeadingNativeId==""&&c.ContentHash==hash&&c.ParagraphCount==rows.Length).ToArray();
|
|
if(candidates.Length!=1){lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.Busy=false;work.Reviewed.Add(-work.Start-1);doc.Status="An unrecognised or ambiguous chapter needs review; no chapter was guessed by name.";AdvanceChapter(doc,work);}return;}
|
|
var chapter=candidates[0];lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;if(!work.Visited.Add(chapter.ChapterId)){work.Busy=false;if(!work.Checked.TryGetValue(chapter.ChapterId,out var earlier)||earlier.Start!=start||earlier.End!=end){work.Reviewed.Add(chapter.ChapterId);work.Checked.Remove(chapter.ChapterId);doc.Status="Duplicate chapter identity at another position; existing canonical structure is retained for review.";}AdvanceChapter(doc,work);return;}}var proof=new ChapterObservation{RequestId=command,OperationId=operation,InstanceId=doc.Instance,SessionId=doc.Session,ManuscriptId=doc.Manuscript,WordRevision=doc.Revision,BaseRevision=manifest.Revision,ChapterId=chapter.ChapterId,Start=start,End=end,NextHeadingId=nextHeading,ContentHash=hash,IdentityHash=ChapterFingerprint.Identity(rows),Paragraphs=rows.Select(p=>new ChapterParagraph{NativeId=p.NativeId,Length=p.Length,Outline=p.Outline}).ToArray()};
|
|
var result=await cloud.ValidateChapter(doc.Book,proof,doc.Authentication);
|
|
if(!result.Accepted&&result.State=="Changed"&&result.AllowText){proof.Reconcile=true;proof.Paragraphs=rows;result=await cloud.ValidateChapter(doc.Book,proof,doc.Authentication);}
|
|
lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.Busy=false;
|
|
if(result.Accepted){work.Checked[chapter.ChapterId]=(start,end);manifest.Revision=result.Revision;if(result.State=="Needs review")work.Reviewed.Add(chapter.ChapterId);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;doc.Status=$"{work.Checked.Count}/{manifest.Chapters.Length} chapters accepted · "+result.Message;AdvanceChapter(doc,work);}
|
|
else{work.Reviewed.Add(chapter.ChapterId);doc.Status=result.Message+" Accepted chapter repairs are retained.";AdvanceChapter(doc,work);}
|
|
}
|
|
}catch(Exception e)when(NetworkFailure(e)||e is ArgumentException or System.Xml.XmlException){lock(gate)if(CurrentChapterWork(doc,work)&&work.Command==command){work.Busy=false;
|
|
if(e is HttpRequestException or OperationCanceledException||cloud.Status().Health?.Authentication!="verified"){work.Manifest=null;work.Command=Guid.Empty;work.Visited.Clear();work.RetryAfter=DateTime.UtcNow.AddSeconds(15);doc.Status="Chapter connection interrupted; accepted checkpoints are retained and validation will resume after reconnect.";}
|
|
else if(e is ArgumentException or System.Xml.XmlException&&end>start){work.Reviewed.Add(-start-1);doc.Status="Chapter content needs review: "+e.Message+" Other chapters can continue.";AdvanceChapter(doc,work);}
|
|
else{work.FailedRevision=doc.Revision;doc.Status="Chapter needs review: "+e.Message+" Existing import is unchanged.";}}}
|
|
finally{chapterProcessing.Release();}
|
|
}
|
|
}
|