83 lines
14 KiB
C#
83 lines
14 KiB
C#
using System.Data;
|
|
using System.Text.Json;
|
|
using Dapper;
|
|
using Microsoft.Data.SqlClient;
|
|
using PlotLine.Models;
|
|
using PlotLine.Services;
|
|
using PlotLine.Services.Manuscript;
|
|
using PlotDirector.Companion.Protocol.Manuscript;
|
|
internal static class SharedFocusDatabaseTests
|
|
{
|
|
internal sealed record Fixture(int user,int project,int book,int chapter1,int chapter2,int scene1,int scene2,int scene3,Guid paragraph1,Guid paragraph2,Guid paragraph3,Guid manuscript,Guid session,int character1,int character2,int relationship,int relationshipEvent);
|
|
public static async Task Concurrent(bool cleanup=false)
|
|
{
|
|
var fixture=JsonSerializer.Deserialize<Fixture>(File.ReadAllText("/tmp/shared-focus-browser-scope.json"))!;
|
|
var line=File.ReadLines("/etc/plotdirector/plotdirector.env").Single(s=>s.StartsWith("ConnectionStrings__DefaultConnection="));
|
|
var connection=new SqlConnectionStringBuilder(line[(line.IndexOf('=')+1)..].Trim().Trim('"','\''));
|
|
if(connection.InitialCatalog!="PlotDirector_Development")throw new Exception("Development only");
|
|
await using var db=new SqlConnection(connection.ConnectionString);await db.OpenAsync();
|
|
if(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()")!="PlotDirector_Development")throw new Exception("Wrong effective database");
|
|
if(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects p JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID JOIN dbo.AppUser u ON u.UserID=a.UserID WHERE p.ProjectID=@project AND p.ProjectName=N'Disposable shared-focus integration' AND a.UserID=@user AND u.Email LIKE N'pwa-browser-%'",fixture)!=1)throw new Exception("Disposable fixture scope required");
|
|
if(cleanup){await db.ExecuteAsync("UPDATE dbo.Books SET IsArchived=1 WHERE BookID=@book AND ProjectID=@project;UPDATE dbo.Characters SET IsArchived=1 WHERE ProjectID=@project;UPDATE dbo.Projects SET IsArchived=1 WHERE ProjectID=@project;",fixture);Console.WriteLine("PASS isolated browser fixture archived; no real project/content changed.");return;}
|
|
async Task<SharedFocusPosition> Run(SqlConnection sql,string action,Guid window,int scene)=>await sql.QuerySingleAsync<SharedFocusPosition>("dbo.NarrativeFocus_Coordinate",new{Action=action,UserID=fixture.user,ProjectID=fixture.project,BookID=fixture.book,WindowID=window,Sequence=1,SceneID=scene},commandType:CommandType.StoredProcedure);
|
|
var before=await Run(db,"read",Guid.NewGuid(),fixture.scene1);
|
|
var pending=Enumerable.Range(0,16).Select(async index=>{await using var sql=new SqlConnection(connection.ConnectionString);await sql.OpenAsync();return await Run(sql,"publish",Guid.NewGuid(),index%2==0?fixture.scene1:fixture.scene3);}).ToArray();
|
|
var results=await Task.WhenAll(pending);var after=await Run(db,"read",Guid.NewGuid(),fixture.scene1);var changed=results.Where(r=>r.Changed).Select(r=>r.Version).Order().ToArray();
|
|
if(changed.Length<2||!changed.SequenceEqual(Enumerable.Range(1,changed.Length).Select(n=>before.Version+n))||after.Version!=changed.Last())throw new Exception("Concurrent publications lost/duplicated revision order");
|
|
Console.WriteLine("PASS sixteen real concurrent SQL connections: accepted changes receive contiguous unique revisions, final durable read equals highest accepted revision.");
|
|
await SharedFocusNativeDeliveryTests.Run(connection.ConnectionString,fixture);
|
|
}
|
|
public static async Task Run(string scopePath,bool persist=false)
|
|
{
|
|
var line=File.ReadLines("/etc/plotdirector/plotdirector.env").Single(s=>s.StartsWith("ConnectionStrings__DefaultConnection="));var builder=new SqlConnectionStringBuilder(line[(line.IndexOf('=')+1)..].Trim().Trim('"','\''));if(builder.InitialCatalog!="PlotDirector_Development")throw new Exception("Development only");await using var db=new SqlConnection(builder.ConnectionString);await db.OpenAsync();if(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()")!="PlotDirector_Development")throw new Exception("Wrong effective database");var scope=JsonDocument.Parse(File.ReadAllText(scopePath)).RootElement;int project=scope.GetProperty("project").GetInt32(),user=scope.GetProperty("user").GetInt32();if(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.ProjectUserAccess a JOIN dbo.AppUser u ON u.UserID=a.UserID WHERE a.ProjectID=@project AND a.UserID=@user AND a.AccessRole=N'Owner' AND a.IsActive=1 AND u.Email LIKE N'pwa-browser-%'",new{project,user})!=1)throw new Exception("Explicit disposable account required");
|
|
using var tx=db.BeginTransaction();
|
|
try{
|
|
// Isolated collaborator fixture: no existing project/content or subscription is modified.
|
|
project=await db.QuerySingleAsync<int>("INSERT dbo.Projects(ProjectName) VALUES(N'Disposable shared-focus integration');SELECT CAST(SCOPE_IDENTITY() AS int)",transaction:tx);
|
|
await db.ExecuteAsync("INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole) VALUES(@project,@user,N'Collaborator')",new{project,user},tx);
|
|
var ids=await db.QuerySingleAsync<(int Book,int C1,int C2,int S1,int S2,int S3)>("""
|
|
DECLARE @revision int=(SELECT TOP(1) RevisionStatusID FROM dbo.RevisionStatuses ORDER BY RevisionStatusID),@time int=(SELECT TOP(1) TimeModeID FROM dbo.TimeModes),@confidence int=(SELECT TOP(1) TimeConfidenceID FROM dbo.TimeConfidences);
|
|
INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@project,N'Shared focus disposable fixture',999999,999999);DECLARE @book int=SCOPE_IDENTITY();
|
|
INSERT dbo.Chapters(BookID,ChapterNumber,ChapterTitle,SortOrder,RevisionStatusID) VALUES(@book,2,N'Focus fixture first',10,@revision);DECLARE @c1 int=SCOPE_IDENTITY();
|
|
INSERT dbo.Chapters(BookID,ChapterNumber,ChapterTitle,SortOrder,RevisionStatusID) VALUES(@book,1,N'Focus fixture second',20,@revision);DECLARE @c2 int=SCOPE_IDENTITY();
|
|
INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,SortOrder,TimeModeID,TimeConfidenceID,RevisionStatusID) VALUES(@c1,200,N'Focus fixture early',10,@time,@confidence,@revision);DECLARE @s1 int=SCOPE_IDENTITY();
|
|
INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,SortOrder,TimeModeID,TimeConfidenceID,RevisionStatusID) VALUES(@c1,1,N'Focus fixture late',20,@time,@confidence,@revision);DECLARE @s2 int=SCOPE_IDENTITY();
|
|
INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,SortOrder,TimeModeID,TimeConfidenceID,RevisionStatusID) VALUES(@c2,1,N'Focus fixture next chapter',10,@time,@confidence,@revision);DECLARE @s3 int=SCOPE_IDENTITY();
|
|
SELECT @book Book,@c1 C1,@c2 C2,@s1 S1,@s2 S2,@s3 S3;
|
|
""",new{project},tx);
|
|
Guid manuscript=Guid.NewGuid(),session=Guid.NewGuid(),p1=Guid.NewGuid(),p2=Guid.NewGuid(),p3=Guid.NewGuid(),sk1=Guid.NewGuid(),sk2=Guid.NewGuid(),sk3=Guid.NewGuid();string hash=new('A',64);
|
|
var state=new ParagraphManuscript{BookId=ids.Book,ProjectId=project,ManuscriptId=manuscript,SessionId=session,WordRevision=1,Revision=1,LastRequestId=Guid.NewGuid(),UpdatedUtc=DateTime.UtcNow,Paragraphs=[new(){ChapterId=ids.C1,SceneId=sk1,Story=true,PositionVerified=true,Occurrence=new(){Id=p1,Start=10,End=20,Text="Isolated focus paragraph one."}},new(){ChapterId=ids.C1,SceneId=sk2,Story=true,PositionVerified=true,Occurrence=new(){Id=p2,Start=20,End=30,Text="Isolated focus paragraph two."}},new(){ChapterId=ids.C2,SceneId=sk3,Story=true,PositionVerified=true,Occurrence=new(){Id=p3,Start=40,End=50,Text="Isolated focus paragraph three."}}],Scenes=[new(){Id=sk1,CanonicalId=ids.S1,ChapterId=ids.C1},new(){Id=sk2,CanonicalId=ids.S2,ChapterId=ids.C1},new(){Id=sk3,CanonicalId=ids.S3,ChapterId=ids.C2}],ChapterCheckpoints=[new(){ChapterId=ids.C1,ContentHash=hash,IdentityHash=hash,MappingHash=hash},new(){ChapterId=ids.C2,ContentHash=hash,IdentityHash=hash,MappingHash=hash}]};
|
|
await db.ExecuteAsync("INSERT dbo.BookParagraphManuscripts(BookID,ManuscriptID,Revision,RequestID,Payload) VALUES(@book,@manuscript,1,NEWID(),@payload)",new{book=ids.Book,manuscript,payload=JsonSerializer.Serialize(state)},tx);
|
|
foreach(var chapter in new[]{ids.C1,ids.C2})await db.ExecuteAsync("""
|
|
INSERT dbo.BookChapterValidations(BookID,ChapterID,UserID,SessionID,ManuscriptID,WordRevision,RequestID,ContentHash,IdentityHash,MappingHash,Positions,SourceRevision,ValidatedUtc,ExpiresUtc)
|
|
VALUES(@book,@chapter,@user,@session,@manuscript,1,NEWID(),@hash,@hash,@hash,@positions,1,SYSUTCDATETIME(),DATEADD(hour,2,SYSUTCDATETIME()));
|
|
""",new{book=ids.Book,chapter,user,session,manuscript,hash,positions=JsonSerializer.Serialize(state.Paragraphs.Where(p=>p.ChapterId==chapter).Select(p=>new ChapterPosition(p.Occurrence.Id,p.Occurrence.Start,p.Occurrence.End,chapter,state.Scenes.Single(s=>s.Id==p.SceneId).CanonicalId,true)))},tx);
|
|
int ca=await db.QuerySingleAsync<int>("dbo.Character_Save",new{ProjectID=project,CharacterName="Shared focus fixture A "+ids.Book},tx,commandType:CommandType.StoredProcedure),cb=await db.QuerySingleAsync<int>("dbo.Character_Save",new{ProjectID=project,CharacterName="Shared focus fixture B "+ids.Book},tx,commandType:CommandType.StoredProcedure);
|
|
int type=await db.ExecuteScalarAsync<int>("SELECT TOP(1) RelationshipTypeID FROM dbo.RelationshipTypes WHERE TypeName=N'Friend'",transaction:tx),rs=await db.ExecuteScalarAsync<int>("SELECT TOP(1) RelationshipStateID FROM dbo.RelationshipStates ORDER BY SortOrder,RelationshipStateID",transaction:tx);
|
|
int rel=await db.QuerySingleAsync<int>("dbo.Relationship_Save",new{ProjectID=project,CharacterAID=ca,CharacterBID=cb,RelationshipTypeID=type,IsPermanent=true,IsKnownToReader=false,IsInitialRelationship=true,InitialBookID=ids.Book,InitialRelationshipStateID=rs,Notes="Disposable shared focus fixture"},tx,commandType:CommandType.StoredProcedure);
|
|
int ev=await db.QuerySingleAsync<int>("dbo.RelationshipEvent_Save",new{CharacterRelationshipID=rel,SceneID=ids.S1,RelationshipStateID=rs,Intensity=3,IsKnownToOtherCharacter=true,Description="Disposable earlier-scene event"},tx,commandType:CommandType.StoredProcedure);
|
|
await db.ExecuteAsync("""
|
|
DECLARE @role int=(SELECT TOP(1) CharacterRoleInSceneTypeID FROM dbo.CharacterRoleInSceneTypes ORDER BY CharacterRoleInSceneTypeID),@presence int=(SELECT TOP(1) PresenceTypeID FROM dbo.PresenceTypes WHERE TypeName=N'Present');
|
|
INSERT dbo.SceneCharacters(SceneID,CharacterID,RoleInSceneTypeID,PresenceTypeID) SELECT s.ID,c.ID,@role,@presence FROM (VALUES(@s1),(@s2),(@s3))s(ID) CROSS JOIN(VALUES(@ca),(@cb))c(ID);
|
|
""",new{s1=ids.S1,s2=ids.S2,s3=ids.S3,ca,cb},tx);
|
|
var fixture=new Fixture(user,project,ids.Book,ids.C1,ids.C2,ids.S1,ids.S2,ids.S3,p1,p2,p3,manuscript,session,ca,cb,rel,ev);
|
|
if(persist){tx.Commit();File.WriteAllText("/tmp/shared-focus-browser-scope.json",JsonSerializer.Serialize(fixture));Console.WriteLine("PASS isolated shared-focus browser fixture prepared; no real manuscript used.");return;}
|
|
void Check(bool condition,string name){if(!condition)throw new Exception(name);Console.WriteLine("PASS shared focus SQL: "+name);}
|
|
async Task<SharedFocusPosition> Run(string action,Guid? window=null,long sequence=0,int? chapter=null,int? scene=null,Guid? paragraph=null,int direction=0)=>await db.QuerySingleAsync<SharedFocusPosition>("dbo.NarrativeFocus_Coordinate",new{Action=action,UserID=user,ProjectID=project,BookID=ids.Book,WindowID=window,Sequence=sequence,ChapterID=chapter,SceneID=scene,ParagraphID=paragraph,Direction=direction},tx,commandType:CommandType.StoredProcedure);
|
|
var a=Guid.NewGuid();var b=Guid.NewGuid();var empty=await Run("read");Check(empty.Version==0&&!empty.IsValid,"new clients do not manufacture or publish initial focus");
|
|
var first=await Run("publish",a,1,scene:ids.S1);Check(first.Version==1&&first.Changed&&first.ChapterID==ids.C1,"scene resolves its canonical chapter and receives atomic revision one");
|
|
var same=await Run("publish",a,2,scene:ids.S1);Check(!same.Changed&&same.Version==1,"unchanged effective focus does not broadcast or increment revision");
|
|
var second=await Run("publish",b,1,paragraph:p2);Check(second.Version==2&&second.ParagraphID==p2&&second.SceneID==ids.S2,"accepted paragraph resolves canonical chapter and scene without text in the packet");
|
|
var duplicate=await Run("publish",a,1,scene:ids.S1);Check(duplicate.Version==2&&duplicate.ParagraphID==p2&&!duplicate.Changed,"replayed older client sequence cannot overwrite a newer window");
|
|
var held=await Run("resolve",a,3,scene:ids.S3);var still=await Run("read");Check(held.ChapterID==ids.C2&&still.Version==2&&still.ParagraphID==p2,"held local navigation validates without changing shared state");
|
|
var next=await Run("publish",b,2,direction:1);Check(next.SceneID==ids.S3&&next.Version==3,"scene stepping uses canonical sort order across chapter boundaries");
|
|
await db.ExecuteAsync("UPDATE dbo.Scenes SET IsArchived=1 WHERE SceneID=@id",new{id=ids.S3},tx);var invalid=await Run("validate",scene:ids.S3,chapter:ids.C2);Check(!invalid.IsValid&&(await Run("read")).Version==3,"structural invalidation is explicit and never redirects a held reference");
|
|
var mapped=await db.QuerySingleAsync<FocusWordPosition>("dbo.NarrativeFocus_WordPosition",new{Action="position",UserID=user,BookID=ids.Book,ManuscriptID=manuscript,SessionID=session,WordRevision=1,Cursor=12},tx,commandType:CommandType.StoredProcedure);Check(mapped.ParagraphID==p1,"native deliberate selection maps only through exact verified live evidence");
|
|
var missing=await db.QueryAsync<FocusWordPosition>("dbo.NarrativeFocus_WordPosition",new{Action="target",UserID=user,BookID=ids.Book,ManuscriptID=manuscript,SessionID=Guid.NewGuid(),WordRevision=1,ParagraphID=p1},tx,commandType:CommandType.StoredProcedure);Check(!missing.Any(),"a different Word session never receives another session's offsets");
|
|
var bad=await Run("validate",chapter:ids.C2,paragraph:p1);Check(!bad.IsValid,"incompatible paragraph/chapter references are rejected");
|
|
try{await db.QuerySingleAsync<SharedFocusPosition>("dbo.NarrativeFocus_Coordinate",new{Action="read",UserID=-99,ProjectID=project,BookID=ids.Book},tx,commandType:CommandType.StoredProcedure);throw new Exception("Unauthorized scope accepted");}catch(SqlException e)when(e.Number==51000){Check(true,"ownership enforced for every focus read/write");}
|
|
}finally{try{tx.Rollback();}catch(InvalidOperationException){}}
|
|
Console.WriteLine("PASS shared focus fixture completely rolled back.");
|
|
}
|
|
}
|