PlotDirector/PlotDirector.NativeCompanion/Tests/NativeCaptureUploadTests.cs

68 lines
7.4 KiB
C#

using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using PlotDirector.Companion.Agent;
using PlotDirector.Companion.Protocol;
internal static class NativeCaptureUploadTests
{
public static async Task Run()
{
var handler=new Handler();using var cloud=new CloudGateway(handler,_=>{});cloud.Connect("https://capture.test/");
await Until(()=>cloud.Status().Books.Any(b=>b.BookId==3));await cloud.CheckConnection();
var sessions=new SessionManager();using var ai=new ChapterAiWork(cloud);var tray=new TrayCoordinator(sessions,cloud,ai);var instance=Guid.NewGuid();var lease=Guid.NewGuid();var session=Guid.NewGuid();var manuscript=Guid.NewGuid();long sequence=0;
sessions.Attach(instance,lease);tray.Attach(instance,lease,capture:true,paragraphs:true);
long revision=1;
Message Send(Message request){request.WordInstanceId=instance;request.SessionId=session;request.Sequence=++sequence;request.Revision=revision;return tray.Exchange(instance,request,sessions.Apply(lease,request),lease);}
void Register()=>Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=manuscript,Revision=revision,Title="Synthetic upload.docx"}]});
Register();tray.SelectBook(session,3,false);using var cancel=new CancellationTokenSource();var heartbeats=tray.Heartbeat(cancel.Token);
async Task Request(){handler.Next=Guid.NewGuid();tray.RefreshPresence(session);await Until(()=>tray.Documents.Single().Capture?.RequestId==handler.LastRequest);}
void Frames(){var id=tray.Documents.Single().Capture!.RequestId;Send(new(){Kind="snapshot-begin",SnapshotId=id,End=22});Send(new(){Kind="snapshot-fragment",SnapshotId=id,Fragment=new(){ParagraphIndex=1,Start=0,End=10,OutlineLevel=1,Text="Chapter 1\r",CompletesParagraph=true}});Send(new(){Kind="snapshot-fragment",SnapshotId=id,Fragment=new(){ParagraphIndex=2,Start=10,End=22,OutlineLevel=10,Text="Exact prose\r",CompletesParagraph=true}});Send(new(){Kind="snapshot-end",SnapshotId=id});}
try{
handler.Transient=2;await Request();Frames();await Until(()=>tray.Documents.Single().AcceptedRevision==1);
Check(handler.Bodies.Count==3&&handler.Bodies.Distinct().Count()==1,"Transient capture uploads retry the exact prepared request and canonical-ID proposal, without rereading Word");
handler.Permanent=true;await Request();Frames();await Until(()=>tray.Documents.Single().Status.Contains("retained in Companion memory"));
Check(tray.Documents.Single().Status.Contains("capture_timeout")||tray.Documents.Single().Status.Contains("expired"),"Companion reports bounded server rejection detail instead of generic subscription/access denial");
var before=handler.Bodies.Count;handler.Permanent=false;handler.Next=Guid.NewGuid();tray.RefreshPresence(session);await Until(()=>handler.Bodies.Count==before+1);await Until(()=>tray.Documents.Single().Status.Contains("Manuscript received"));
Check(JsonSerializer.Deserialize<ManuscriptCapture>(handler.Bodies[^1],new JsonSerializerOptions(JsonSerializerDefaults.Web))!.Paragraphs.Length==2,"Fresh explicit wizard authorisation can resubmit retained unchanged raw paragraphs without new Word frames");
handler.Permanent=true;await Request();Frames();await Until(()=>tray.Documents.Single().Status.Contains("retained in Companion memory"));
before=handler.Bodies.Count;revision=2;Register();handler.Permanent=false;await Request();await Task.Delay(800);
Check(handler.Bodies.Count==before,"Document revision change clears the failed upload buffer; old prose is not replayed against new Word state");
handler.Permanent=true;Frames();await Until(()=>tray.Documents.Single().Status.Contains("retained in Companion memory"));
before=handler.Bodies.Count;tray.SelectBook(session,4,false);handler.Book=4;handler.Permanent=false;await Request();await Task.Delay(800);
Check(handler.Bodies.Count==before,"Book association change clears the failed buffer; no prose is replayed into another book");
handler.Permanent=true;Frames();await Until(()=>tray.Documents.Single().Status.Contains("retained in Companion memory"));
before=handler.Bodies.Count;await cloud.SignOutAsync();cloud.Connect("https://capture.test/");await Until(()=>cloud.Status().Books.Any(b=>b.BookId==3));await cloud.CheckConnection();tray.SelectBook(session,4,false);handler.Permanent=false;await Request();await Task.Delay(800);
Check(handler.Bodies.Count==before,"Account context change clears the failed buffer; fresh pairing cannot replay the previous account source");
}finally{cancel.Cancel();try{await heartbeats;}catch(OperationCanceledException){}}
}
private static async Task Until(Func<bool> condition){for(int n=0;n<400;n++){if(condition())return;await Task.Delay(50);}throw new Exception("Capture upload state timed out");}
private static void Check(bool ok,string message){if(!ok)throw new Exception(message);Console.WriteLine("PASS "+message);}
private sealed class Handler:HttpMessageHandler
{
public int Book=3;public int Transient;public bool Permanent;public Guid Next,LastRequest;public List<string> Bodies=[];
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellation)
{
var path=request.RequestUri!.AbsolutePath;
HttpResponseMessage Json(object value,HttpStatusCode status=HttpStatusCode.OK)=>new(status){Content=JsonContent.Create(value)};
if(path.EndsWith("/pair"))return Json(new{code="00112233445566778899AABB"});
if(path.EndsWith("/token"))return Json(new{accessToken="fixture-access"});
if(path.EndsWith("/books"))return Json(new[]{new{bookId=3,title="Synthetic book"},new{bookId=4,title="Other authorised book"}});
if(path.EndsWith("/connection"))return Json(new{state="Connected",authentication="verified",server="online",expiresUtc=DateTime.UtcNow.AddHours(4)});
if(path.EndsWith("/presence")){
var input=await request.Content!.ReadFromJsonAsync<NativePresence>(cancellation);
if(Next!=Guid.Empty){input!.Navigation=new(){Kind="wizard-capture",Id=Next,BookId=Book,SessionId=Guid.Parse(path.Split('/')[6]),Revision=input.Revision,ParagraphTracking=true};LastRequest=Next;Next=Guid.Empty;}
return Json(input!);
}
if(path.EndsWith("/manuscript-capture")){
var body=await request.Content!.ReadAsStringAsync(cancellation);Bodies.Add(body);var capture=JsonSerializer.Deserialize<ManuscriptCapture>(body,new JsonSerializerOptions(JsonSerializerDefaults.Web))!;
if(Transient-->0)return Json(new{code="capture_storage_unavailable",message="Durable save temporarily unavailable",retryable=true},HttpStatusCode.ServiceUnavailable);
if(Permanent)return Json(new{code="capture_timeout",message="Capture authorisation expired; request capture again",retryable=false},HttpStatusCode.Gone);
return Json(new NativePresence{CaptureRequestId=capture.RequestId,Revision=capture.Revision,ParagraphRevision=1,CanonicalParagraphIds=[Guid.Parse("11111111-1111-4111-8111-111111111111"),Guid.Parse("22222222-2222-4222-8222-222222222222")]});
}
if(request.Method==HttpMethod.Delete)return Json(new NativePresence());
return Json(new{},HttpStatusCode.NotFound);
}
}
}