146 lines
18 KiB
C#
146 lines
18 KiB
C#
using PlotDirector.Companion.Protocol.Manuscript;
|
|
using PlotLine.Data;
|
|
using PlotLine.Models;
|
|
using PlotLine.Services.NativeCompanion;
|
|
namespace PlotLine.Services.Manuscript;
|
|
public sealed class ChapterSyncService(IParagraphManuscriptRepository manuscripts,IChapterSyncRepository checkpoints,IWordCompanionRepository access,ParagraphManuscriptService reconciliation,NativePresenceStore presence,TimeProvider clock,ILogger<ChapterSyncService>? logger=null)
|
|
{
|
|
private void RequireFeature(){if(!reconciliation.Enabled)throw new InvalidOperationException("Paragraph synchronisation is not enabled on this server.");}
|
|
public async Task<ChapterManifest> Manifest(int user,int book,Guid session,long wordRevision)
|
|
{
|
|
RequireFeature();
|
|
if(await access.GetBookStructureAsync(book,user)==null)throw new UnauthorizedAccessException();
|
|
var state=await manuscripts.Get(user,book)??throw new InvalidOperationException("Finish the existing manuscript import first; no saved index is available.");
|
|
var live=await checkpoints.List(user,book,session,wordRevision);var sources=ChapterCheckpointEngine.Build(state,state.Revision);
|
|
var manifest=new ChapterManifest(){CheckpointReuseSupported=true,NativePositionsSupported=true,BookId=book,ManuscriptId=state.ManuscriptId,Revision=state.Revision,Mode=state.Mode,Chapters=ChapterCheckpointEngine.Parts(state).Select(part=>{
|
|
var source=sources.Single(c=>c.ChapterId==part.Chapter.CanonicalId);var accepted=live.FirstOrDefault(c=>c.ChapterID==source.ChapterId&&c.ContentHash==source.ContentHash&&c.IdentityHash==source.IdentityHash&&c.MappingHash==source.MappingHash);
|
|
var durable=state.ChapterCheckpoints.FirstOrDefault(c=>c.ChapterId==source.ChapterId&&c.Status=="Synchronised"&&c.ContentHash==source.ContentHash&&c.IdentityHash==source.IdentityHash&&c.MappingHash==source.MappingHash&&c.NextHeadingId==source.NextHeadingId&&c.Algorithm==ChapterFingerprint.Version);
|
|
return new ChapterManifestItem{DurableAccepted=durable!=null&&source.Status!="Needs review",Algorithm=source.Algorithm,AcceptedRevision=source.AcceptedRevision,Order=source.Order,MappingHash=source.MappingHash,PositionHash=source.PositionHash,NextHeadingId=source.NextHeadingId,ChapterId=source.ChapterId,Title=part.Chapter.Title,HeadingNativeId=source.NativeHeadingId,ContentHash=source.ContentHash,IdentityHash=source.IdentityHash,Start=accepted?.StartPosition??part.Rows[0].Occurrence.Start,End=accepted?.EndPosition??part.Rows[^1].Occurrence.End,ParagraphCount=source.ParagraphCount,State=accepted!=null&&source.Status!="Needs review"?"Synchronised":source.Status};
|
|
}).ToArray()};
|
|
var lease=presence.Read(user,book).SingleOrDefault(l=>l.Session==session&&l.Position.Revision==wordRevision&&l.Position.CanChapterSync);
|
|
if(lease!=null){var count=manifest.Chapters.Count(c=>c.State=="Synchronised");presence.RecordChapterProgress(user,book,lease.Instance,session,wordRevision,new(){Total=manifest.Chapters.Length,Checked=count,Matching=count,Repaired=presence.RepairedChapters(user,book,lease.Instance,session,wordRevision),State="Checking",Message=$"{count}/{manifest.Chapters.Length} chapter mappings accepted for this session."});}
|
|
return manifest;
|
|
}
|
|
public async Task<ChapterReuseReply> Reuse(int user,string grant,int book,ChapterReuseRequest request)
|
|
{
|
|
RequireFeature();var timer=System.Diagnostics.Stopwatch.StartNew();
|
|
var proofs=request?.Chapters??[];
|
|
if(proofs.Length==0||proofs.Length>256||proofs.Any(p=>p==null||p.Paragraphs==null||p.Paragraphs.Length==0||p.Paragraphs.Length>ChapterFingerprint.MaxParagraphs||p.Paragraphs.Any(r=>r==null||r.Text!=null)||p.Reconcile)||proofs.Sum(p=>(long)p.Paragraphs.Length)>100000||proofs.Select(p=>p.ChapterId).Distinct().Count()!=proofs.Length||proofs.Select(p=>p.RequestId).Distinct().Count()!=proofs.Length)throw new ArgumentException("Complete bounded metadata-only reuse proofs are required.");
|
|
if(await access.GetBookStructureAsync(book,user)==null)throw new UnauthorizedAccessException();
|
|
var status=await manuscripts.Status(user,book);if(status?.CanWrite!=true)throw new UnauthorizedAccessException();if(status.Paused)throw new InvalidOperationException("Existing import or analysis is active.");
|
|
void RequireLease()
|
|
{
|
|
if(proofs.Any(p=>!presence.Read(user,book).Any(l=>l.Grant==grant&&l.Instance==p.InstanceId&&l.Session==p.SessionId&&l.Position.CanChapterSync&&l.Position.WordAvailable&&l.Position.WordSaved==true&&l.Position.ManuscriptId==p.ManuscriptId&&l.Position.Revision==p.WordRevision)))throw new InvalidOperationException("Word document changed or disconnected during checkpoint reuse.");
|
|
}
|
|
RequireLease();var state=await manuscripts.Get(user,book)??throw new InvalidOperationException("Missing manuscript.");
|
|
var first=proofs[0];
|
|
if(proofs.Any(p=>p.InstanceId!=first.InstanceId||p.SessionId!=first.SessionId||p.WordRevision!=first.WordRevision||p.ManuscriptId!=state.ManuscriptId||p.BaseRevision!=state.Revision))throw new InvalidOperationException("Stale or mixed-session checkpoint reuse.");
|
|
var readMs=timer.Elapsed.TotalMilliseconds;var processing=System.Diagnostics.Stopwatch.StartNew();
|
|
var index=new ChapterValidationIndex(state);var validated=new List<ChapterValidationResult>();
|
|
foreach(var proof in proofs)
|
|
{
|
|
var source=index.Checkpoints.SingleOrDefault(c=>c.ChapterId==proof.ChapterId)??throw new InvalidOperationException("Unknown chapter.");
|
|
var durable=state.ChapterCheckpoints.SingleOrDefault(c=>c.ChapterId==proof.ChapterId);
|
|
if(durable==null||durable.Status!="Synchronised"||source.Status=="Needs review"||durable.Algorithm!=proof.Algorithm||source.ContentHash!=proof.ContentHash||source.IdentityHash!=proof.IdentityHash||durable.ContentHash!=source.ContentHash||durable.IdentityHash!=source.IdentityHash||durable.MappingHash!=source.MappingHash||durable.NextHeadingId!=proof.NextHeadingId||durable.PositionHash!=proof.PositionHash)throw new InvalidOperationException("Checkpoint changed or needs detailed validation; refresh the manifest.");
|
|
var value=ChapterCheckpointEngine.Validate(state,proof,clock.GetUtcNow().UtcDateTime,index);
|
|
if(value.Bindings.Length!=0||value.Checkpoint.Status!="Synchronised")throw new InvalidOperationException("Checkpoint requires detailed acceptance.");
|
|
validated.Add(value);
|
|
}
|
|
var ordered=validated.Select(v=>(Start:v.Positions[0].Start,End:v.Positions[^1].End)).OrderBy(v=>v.Start).ToArray();
|
|
for(var i=1;i<ordered.Length;i++)if(ordered[i].Start<ordered[i-1].End)throw new InvalidOperationException("Overlapping chapter evidence.");
|
|
var processingMs=processing.Elapsed.TotalMilliseconds;RequireLease();var validation=timer.Elapsed.TotalMilliseconds;timer.Restart();
|
|
await checkpoints.Reuse(user,book,state,proofs,validated.ToArray());
|
|
RequireLease();
|
|
logger?.LogInformation("Chapter checkpoint reuse Book={Book} Session={Session} Count={Count} ValidationMs={ValidationMs} PersistenceMs={PersistenceMs}",book,first.SessionId,proofs.Length,validation,timer.Elapsed.TotalMilliseconds);
|
|
return new(){ChapterIds=proofs.Select(p=>p.ChapterId).ToArray(),Revision=state.Revision,ReadMs=readMs,ProcessingMs=processingMs,ValidationMs=validation,PersistenceMs=timer.Elapsed.TotalMilliseconds};
|
|
}
|
|
|
|
public async Task<ChapterSyncProgress> Finish(int user,string grant,int book,ChapterFinish completion)
|
|
{
|
|
RequireFeature();
|
|
var lease=presence.Read(user,book).SingleOrDefault(l=>l.Grant==grant&&l.Instance==completion.InstanceId&&l.Session==completion.SessionId&&l.Position.Revision==completion.WordRevision&&l.Position.CanChapterSync&&l.Position.WordSaved==true)??throw new InvalidOperationException("The live document changed before completion.");
|
|
if(completion.OperationId!=Guid.Empty&&!presence.CanRepairChapter(user,lease,completion.OperationId))throw new UnauthorizedAccessException();
|
|
var status=await manuscripts.Status(user,book);if(status?.CanWrite!=true)throw new UnauthorizedAccessException();if(status.Paused)throw new InvalidOperationException("Existing import or analysis is active; completion is paused and accepted checkpoints are retained.");
|
|
var manifest=await Manifest(user,book,completion.SessionId,completion.WordRevision);
|
|
if(completion.HasIssues&&manifest.Chapters.Length>0){var ids=(completion.ReviewChapterIds??[]).Where(id=>manifest.Chapters.Any(c=>c.ChapterId==id)).Distinct().Take(256).ToArray();foreach(var id in ids)await checkpoints.FlagReview(user,book,id,manifest.Revision);manifest=await Manifest(user,book,completion.SessionId,completion.WordRevision);}
|
|
var accepted=manifest.Chapters.Count(c=>c.State=="Synchronised");var complete=accepted==manifest.Chapters.Length&&accepted>0&&!completion.HasIssues;
|
|
var progress=new ChapterSyncProgress{Total=manifest.Chapters.Length,Checked=manifest.Chapters.Length,Matching=accepted,Repaired=presence.RepairedChapters(user,book,completion.InstanceId,completion.SessionId,completion.WordRevision),NeedsReview=complete?0:Math.Max(1,manifest.Chapters.Length-accepted),State=complete?"Synchronised":"Needs review",Message=complete?$"All {accepted} chapter mappings are accepted for this Word session.":$"{accepted}/{manifest.Chapters.Length} chapters accepted; remaining structure needs review. Successfully accepted repairs are retained."};
|
|
presence.RecordChapterProgress(user,book,completion.InstanceId,completion.SessionId,completion.WordRevision,progress);
|
|
logger?.LogInformation("Chapter synchronisation finish Book={Book} Session={Session} WordRevision={WordRevision} State={State} Accepted={Accepted} Total={Total}",book,completion.SessionId,completion.WordRevision,progress.State,accepted,manifest.Chapters.Length);
|
|
return progress;
|
|
}
|
|
public async Task<Guid> Repair(int user,int book,Guid? instance,Guid? session,long? expectedWordRevision=null)
|
|
{
|
|
RequireFeature();
|
|
var status=await manuscripts.Status(user,book)??throw new InvalidOperationException("The accepted snapshot is missing; finish the existing import, do not reimport an already indexed book.");
|
|
if(!status.CanWrite)throw new UnauthorizedAccessException();if(status.Paused)throw new InvalidOperationException("Existing import or analysis is active. Accepted checkpoints are preserved.");
|
|
if(instance.HasValue!=session.HasValue)throw new InvalidOperationException("Choose a complete Word session.");
|
|
var live=presence.Read(user,book).Where(l=>l.Position.WordAvailable&&l.Position.CanChapterSync&&l.Position.WordSaved==true).ToArray();
|
|
var selected=instance.HasValue?live.SingleOrDefault(l=>l.Instance==instance&&l.Session==session):live.Count(l=>l.Position.Active)==1?live.Single(l=>l.Position.Active):live.Length==1?live[0]:null;
|
|
if(selected==null)throw new InvalidOperationException("Open and save the intended manuscript with a chapter-capable Companion, then select its document connection.");
|
|
if(expectedWordRevision.HasValue&&selected.Position.Revision!=expectedWordRevision)throw new InvalidOperationException("Word changed before the explicit repair request arrived. Request again from the current document.");
|
|
if(selected.Position.ManuscriptId!=status.ManuscriptId)throw new InvalidOperationException("This document has a different manuscript identity. No existing import was changed.");
|
|
var source=await manuscripts.Get(user,book)??throw new InvalidOperationException("No accepted source snapshot.");if(ChapterCheckpointEngine.Parts(source).Length==0)throw new InvalidOperationException("No reversible chapter boundaries are recorded. Use the existing bounded full snapshot reader or review structure; the import does not need to be recreated.");
|
|
var id=Guid.NewGuid();if(!presence.RequestChapterRepair(user,selected,id))throw new InvalidOperationException("Word is busy with another request. Accepted chapter checkpoints are preserved.");return id;
|
|
}
|
|
public async Task<ChapterSyncReply> Accept(int user,string grant,int book,ChapterObservation proof)
|
|
{
|
|
var stage="protocol";
|
|
var elapsed=System.Diagnostics.Stopwatch.StartNew();
|
|
try
|
|
{
|
|
if(proof==null||proof.Paragraphs==null||proof.Paragraphs.Length==0||proof.Paragraphs.Length>ChapterFingerprint.MaxParagraphs||proof.Paragraphs.Any(p=>p==null))throw new ArgumentException("Complete bounded chapter evidence is required.");
|
|
RequireFeature();
|
|
ChapterWordPositions.Validate(proof.Paragraphs,proof.Start,proof.End,proof.PositionHash);
|
|
stage="access";
|
|
if(await access.GetBookStructureAsync(book,user)==null)throw new UnauthorizedAccessException();
|
|
var status=await manuscripts.Status(user,book)??throw new InvalidOperationException("No accepted manuscript index.");
|
|
if(!status.CanWrite)throw new UnauthorizedAccessException();if(status.Paused)throw new InvalidOperationException("Existing import or analysis is active; chapter acceptance is paused.");
|
|
stage="session";
|
|
var lease=presence.Read(user,book).SingleOrDefault(l=>l.Instance==proof.InstanceId&&l.Session==proof.SessionId&&l.Grant==grant&&l.Position.CanChapterSync&&l.Position.WordAvailable&&l.Position.WordSaved==true&&l.Position.ManuscriptId==proof.ManuscriptId&&l.Position.Revision==proof.WordRevision);
|
|
if(lease==null)throw new InvalidOperationException("Word document closed, changed, became unsaved or was disconnected; no stale checkpoint was accepted.");
|
|
var permitted=status.Mode=="OnSave"||presence.CanRepairChapter(user,lease,proof.OperationId);
|
|
stage="snapshot";
|
|
var state=await manuscripts.Get(user,book)??throw new InvalidOperationException("Missing accepted snapshot.");
|
|
var source=ChapterCheckpointEngine.Build(state,state.Revision).SingleOrDefault(c=>c.ChapterId==proof.ChapterId)??throw new InvalidOperationException("Unknown accepted chapter.");
|
|
var changed=source.ContentHash!=proof.ContentHash;
|
|
if(changed){
|
|
if(!permitted||proof.Paragraphs.Any(p=>p.Text==null))return new(){State="Changed",ChapterId=proof.ChapterId,Revision=state.Revision,AllowText=permitted,Message=permitted?"Changed chapter; submit this chapter only for existing paragraph reconciliation.":"Changed chapter. Use Synchronise or Repair to authorise chapter reconciliation; no prose was uploaded."};
|
|
if(presence.Read(user,book).Count(l=>l.Position.WordAvailable&&l.Position.ManuscriptId==proof.ManuscriptId)>1)throw new InvalidOperationException("Competing Word copies are connected to this book. Close the other copy before reconciling changed prose; existing mappings are preserved.");
|
|
stage="reconciliation";
|
|
state=await reconciliation.ReconcileChapter(user,book,proof);proof.BaseRevision=state.Revision;
|
|
logger?.LogInformation("Chapter reconciliation persisted Book={Book} Chapter={Chapter} Request={Request} Session={Session} Revision={Revision} ElapsedMs={ElapsedMs}",book,proof.ChapterId,proof.RequestId,proof.SessionId,state.Revision,elapsed.ElapsedMilliseconds);
|
|
}
|
|
// Native adoption is explicit repair only; ordinary hash checks cannot mint trust.
|
|
proof.Reconcile=presence.CanRepairChapter(user,lease,proof.OperationId);
|
|
stage="validation";
|
|
var validated=ChapterCheckpointEngine.Validate(state,proof,clock.GetUtcNow().UtcDateTime);
|
|
logger?.LogInformation("Chapter validation completed Book={Book} Chapter={Chapter} Request={Request} Session={Session} ElapsedMs={ElapsedMs}",book,proof.ChapterId,proof.RequestId,proof.SessionId,elapsed.ElapsedMilliseconds);
|
|
stage="persistence";
|
|
var acceptedState=await checkpoints.Accept(user,book,proof,validated);
|
|
logger?.LogInformation("Chapter checkpoint persisted Book={Book} Chapter={Chapter} Request={Request} Session={Session} Revision={Revision} ElapsedMs={ElapsedMs}",book,proof.ChapterId,proof.RequestId,proof.SessionId,state.Revision,elapsed.ElapsedMilliseconds);
|
|
if(changed||validated.Bindings.Length>0)presence.RecordChapterRepair(user,book,proof.InstanceId,proof.SessionId,proof.WordRevision,proof.ChapterId);
|
|
try
|
|
{
|
|
var live=await checkpoints.List(user,book,proof.SessionId,proof.WordRevision);
|
|
var count=live.Count(v=>acceptedState.ChapterCheckpoints.Any(c=>c.ChapterId==v.ChapterID&&c.Status!="Needs review"&&c.ContentHash==v.ContentHash&&c.IdentityHash==v.IdentityHash&&c.MappingHash==v.MappingHash));
|
|
var total=ChapterCheckpointEngine.Parts(acceptedState).Length;
|
|
presence.RecordChapterProgress(user,book,proof.InstanceId,proof.SessionId,proof.WordRevision,new(){Total=total,Checked=count,Matching=count,Repaired=presence.RepairedChapters(user,book,proof.InstanceId,proof.SessionId,proof.WordRevision),State="Checking",Message=$"{count}/{total} chapter mappings accepted for this session."});
|
|
}
|
|
catch(Microsoft.Data.SqlClient.SqlException e)
|
|
{
|
|
logger?.LogWarning("Chapter committed; progress refresh unavailable Book={Book} Chapter={Chapter} Request={Request} SqlNumber={SqlNumber}",book,proof.ChapterId,proof.RequestId,e.Number);
|
|
}
|
|
// The transaction is the acceptance boundary. A later manifest refresh must
|
|
// not turn a durable commit into a failed validation response.
|
|
return new(){Accepted=true,State=validated.Checkpoint.Message.Contains("order needs review")?"Needs review":"Synchronised",ChapterId=proof.ChapterId,Revision=state.Revision,Message=validated.Checkpoint.Message};
|
|
}
|
|
catch(Exception e) when(e is UnauthorizedAccessException or ArgumentException or InvalidOperationException or Microsoft.Data.SqlClient.SqlException)
|
|
{
|
|
// Deliberately omit exception text, payloads and grant material.
|
|
logger?.LogWarning("Chapter checkpoint rejected Stage={Stage} Book={Book} Chapter={Chapter} Request={Request} Session={Session} Category={Category} SqlNumber={SqlNumber} ElapsedMs={ElapsedMs}",stage,book,proof?.ChapterId,proof?.RequestId,proof?.SessionId,e.GetType().Name,(e as Microsoft.Data.SqlClient.SqlException)?.Number,elapsed.ElapsedMilliseconds);
|
|
throw;
|
|
}
|
|
}
|
|
}
|