PlotDirector/PlotLine.Tests/ProjectTransferDatabaseTests.cs

130 lines
14 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Data;
using System.Diagnostics;
using System.Reflection;
using System.Text.Json;
using Dapper;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging.Abstractions;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.ViewModels;
// Explicit specialist mode. Never connects for writes to the running Development database.
internal static class ProjectTransferDatabaseTests
{
const string Database = "PlotDirector_Phase2_20261103_2305";
static void Check(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); }
static T Proxy<T>(Func<string, object?[]?, object?> handler) where T : class
{ var proxy=DispatchProxy.Create<T,StoryPointProxy>();((StoryPointProxy)(object)proxy).Handler=handler;return proxy; }
public static async Task RunAsync(string target, bool applyMigrations = false, bool requireWritingPlans = false)
{
Check(target==Database,"An explicitly named Phase 2 synthetic database is required.");
var start=new ProcessStartInfo("sudo"){RedirectStandardOutput=true,RedirectStandardError=true};
foreach(var arg in new[]{"-n","cat","/etc/plotdirector/plotdirector.env"})start.ArgumentList.Add(arg);
using var process=Process.Start(start)!;var settings=await process.StandardOutput.ReadToEndAsync();await process.WaitForExitAsync();
Check(process.ExitCode==0,"Development connection configuration unavailable.");
var configured=settings.Split('\n').Single(x=>x.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=',2)[1].Trim().Trim('"','\'');
var builder=new SqlConnectionStringBuilder(configured);Check(builder.InitialCatalog=="PlotDirector_Development","Unexpected source configuration.");
builder.InitialCatalog=target;using var db=new SqlConnection(builder.ConnectionString);await db.OpenAsync();
Check(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()") == Database,"Synthetic target identity failed.");
var marker=await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM sys.extended_properties WHERE class=0 AND name=N'PlotDirector.Phase2.SyntheticOnly' AND CONVERT(nvarchar(20),value)=N'true'");
if(marker==0)
{
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects")==0 && await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.AppUser")==0,"Refusing to initialise a populated database.");
await db.ExecuteAsync("EXEC sys.sp_addextendedproperty @name=N'PlotDirector.Phase2.SyntheticOnly',@value=N'true';");
}
if(applyMigrations)
{
foreach(var file in new[]{"PlotLine/Sql/213_ProjectBackupBookContext.sql"})
foreach(var batch in System.Text.RegularExpressions.Regex.Split(await File.ReadAllTextAsync(file), @"^\s*GO\s*$", System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.IgnoreCase))
if(!string.IsNullOrWhiteSpace(batch)) await db.ExecuteAsync(batch,commandTimeout:180);
Console.WriteLine("Applied required migrations to the verified synthetic database only.");
}
var user=await db.ExecuteScalarAsync<int>("INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(CONVERT(nvarchar(36),NEWID())+N'@phase2-synthetic.invalid',N'Synthetic author',N'not-an-authentication-credential');SELECT CONVERT(int,SCOPE_IDENTITY());");
var level=await db.ExecuteScalarAsync<int>("IF NOT EXISTS(SELECT 1 FROM dbo.SubscriptionLevel WHERE Name=N'Phase2Synthetic') INSERT dbo.SubscriptionLevel(Name,DisplayName,MaxBooks,MaxChaptersPerBook,MaxScenesPerBook,MaxCharactersPerProject,MaxStorageMB,MaxCollaborators,SortOrder,RequiresStripeSubscription) VALUES(N'Phase2Synthetic',N'Synthetic test only',1000,1000,10000,10000,10000,100,0,0);SELECT TOP(1) SubscriptionLevelID FROM dbo.SubscriptionLevel WHERE Name=N'Phase2Synthetic';");
await db.ExecuteAsync("INSERT dbo.UserSubscription(UserID,SubscriptionLevelID,IsActive,IsTrial,TrialExpiryDateUTC) VALUES(@user,@level,1,1,'2030-01-01');",new{user,level});
var revision=await db.ExecuteScalarAsync<int>("IF NOT EXISTS(SELECT 1 FROM dbo.RevisionStatuses WHERE StatusName=N'Outlined') INSERT dbo.RevisionStatuses(StatusName,SortOrder) VALUES(N'Outlined',0);SELECT TOP(1) RevisionStatusID FROM dbo.RevisionStatuses WHERE StatusName=N'Outlined';");
var timeMode=await db.ExecuteScalarAsync<int>("IF NOT EXISTS(SELECT 1 FROM dbo.TimeModes WHERE TimeModeName=N'Exact') INSERT dbo.TimeModes(TimeModeName,SortOrder) VALUES(N'Exact',0);SELECT TOP(1) TimeModeID FROM dbo.TimeModes WHERE TimeModeName=N'Exact';");
var confidence=await db.ExecuteScalarAsync<int>("IF NOT EXISTS(SELECT 1 FROM dbo.TimeConfidences WHERE TimeConfidenceName=N'Known') INSERT dbo.TimeConfidences(TimeConfidenceName,SortOrder) VALUES(N'Known',0);SELECT TOP(1) TimeConfidenceID FROM dbo.TimeConfidences WHERE TimeConfidenceName=N'Known';");
var configuration=new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?>{{"ConnectionStrings:DefaultConnection",builder.ConnectionString}}).Build();
var factory=new SqlConnectionFactory(configuration);var repository=new ImportRepository(factory);var backups=new ProjectBackupRepository(factory);
var project=await repository.CreateProjectShellAsync("Synthetic transfer – 雨 and café", "Synthetic data only: dialogue “Hello”—and Unicode 🖋.", user);
var book=await db.ExecuteScalarAsync<int>("INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder,Subtitle,StoryEra,PrimaryLocaleCode) VALUES(@project,N'Book Ω',1,1,N'Subtitle é',N'Future era',N'en-GB');SELECT CONVERT(int,SCOPE_IDENTITY());",new{project});
var chapter=await db.ExecuteScalarAsync<int>("INSERT dbo.Chapters(BookID,ChapterNumber,ChapterTitle,SortOrder,RevisionStatusID) VALUES(@book,1.5,N'Chapter 雨',1,@revision);SELECT CONVERT(int,SCOPE_IDENTITY());",new{book,revision});
var scene=await db.ExecuteScalarAsync<int>("INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,Summary,SortOrder,RevisionStatusID,TimeModeID,TimeConfidenceID) VALUES(@chapter,1.25,N'Scene café',N'“Hello”—雪 🖋',1,@revision,@timeMode,@confidence);SELECT CONVERT(int,SCOPE_IDENTITY());",new{chapter,revision,timeMode,confidence});
var map=await db.ExecuteScalarAsync<int>("INSERT dbo.StoryMaps(ProjectID,Name,Kind,AppearanceJson) VALUES(@project,N'Synthetic map 雨',N'World',N'{\"preset\":\"paper\"}');SELECT CONVERT(int,SCOPE_IDENTITY());",new{project});
var maps=new MapRepository(factory);
var image=await maps.AddImageAsync(project,user,MapReferenceImageService.Normalize(MapAppearanceTests.Image(),"synthetic-reference.png"));
var sourceImageBytes=(await maps.GetImageAsync(project,user,image.ImageID))!.ImageData!;
var document=(await maps.GetAsync(project,map,user))!;
document.Map.ReferenceJson=JsonSerializer.Serialize(new MapReferencePlacement { ImageID=image.ImageID, X=15, Y=25, Width=640, Height=480, Rotation=12, Opacity=.45 });
var first=new MapFeature { MapID=map, Name="Port Ω", Type="Town", X=12, Y=34, LabelX=5, LabelY=6, Notes="Unicode 雨", GeometryJson="{}" };
var second=new MapFeature { MapID=map, Name="Island 雪", GeometryClass="Area", Type="Island", X=56, Y=78, Width=160, Height=80, GeometryJson="{\"points\":[[0,0],[1,1],[0,1]]}" };
document.Features=[first,second];
document.Relationships=[new() { MapID=map, SourceID=first.FeatureID, TargetID=second.FeatureID, Direction="NE", MeasuredDistance=12.5m, Unit="km", Notes="Synthetic relationship café" }];
await maps.SaveAsync(document,user);
await maps.CreateAsync(new() { ProjectID=project, Name="Child map 雨", Kind="Region", ParentMapID=map, ParentFeatureID=first.FeatureID },user);
var plan=await db.ExecuteScalarAsync<int>("INSERT dbo.WritingPlans(UserID,ProjectID,BookID,PlanName,GoalType,StartDate,DeadlineDate,AvailableDaysJson,SessionLengthMinutes) VALUES(@user,@project,@book,N'Synthetic drafting plan',N'Draft','2026-11-01','2026-12-01',N'[1,3,5]',45);SELECT CONVERT(int,SCOPE_IDENTITY());",new{user,project,book});
await db.ExecuteAsync("INSERT dbo.WritingScheduleItems(WritingPlanID,SceneID,ScheduledDate,TaskType,ScheduleStatus,Notes) VALUES(@plan,@scene,'2026-11-03',N'Draft',N'Pending',N'Synthetic task café');",new{plan,scene});
var before=(await backups.GetProjectBackupAsync(project,user))!;Check(before.Project is not null,"Fixture project exported.");
Check(before.Data.Books.Single().BookTitle=="Book Ω" && before.Data.Scenes.Single().Summary=="“Hello”—雪 🖋","Core Unicode export content.");
Console.WriteLine($"Synthetic project {project}: core, map and writing schedule populated; {before.Diagnostics.IncludedEntitySets.Count} advertised backup sets.");
var userService=Proxy<ICurrentUserService>((name,args)=>name switch {"get_UserId"=>(int?)user,"get_IsAuthenticated"=>true,"get_Email"=>"phase2-synthetic@example.invalid","get_DisplayName"=>"Synthetic author",_=>throw new NotSupportedException(name)});
var subscription=Proxy<ISubscriptionService>((name,args)=>name switch {"CanUseResourcesAsync"=>Task.FromResult(new EntitlementDecision{Allowed=true}),"ReserveBookSlotsAsync"=>Task.FromResult(new BookSlotReservation{Allowed=true}),_=>throw new NotSupportedException(name)});
var service=new ImportService(repository,userService,subscription,NullLogger<ImportService>.Instance);
var baselineProjectCount=await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects");
var sourceJson=JsonSerializer.Serialize(before);
var invalidPayloads=new List<string>{"null","[]","42"};
foreach(var mutation in new Action<System.Text.Json.Nodes.JsonObject>[] {
root=>root["Data"]=null,
root=>root["Data"]!["StoryMaps"]=null,
root=>root["Data"]!["MapFeatures"]![0]=null,
root=>root["Data"]!["StoryMaps"]![0]!["ProjectID"]=-1,
root=>root["Data"]!["StoryMaps"]![0]!["ParentMapID"]=-1,
root=>root["Data"]!["MapFeatures"]![0]!["MapID"]=-1,
root=>root["Data"]!["Scenes"]![0]!["ChapterID"]=-12345,
root=>root["Data"]!["MapReferenceImages"]![0]!["ImageData"]="",
root=>root["FormatVersion"]="999.0"
})
{
var invalid=System.Text.Json.Nodes.JsonNode.Parse(sourceJson)!.AsObject();mutation(invalid);invalidPayloads.Add(invalid.ToJsonString());
}
foreach(var payload in invalidPayloads)
{
var preview=await service.PreviewAsync(new(){JsonText=payload});
Check(preview.Preview is not null && !preview.Preview.Validation.IsValid,"Invalid map/data payload must fail preview validation.");
}
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects")==baselineProjectCount,"Invalid previews create no project shells.");
Console.WriteLine($"PASS {invalidPayloads.Count} invalid JSON/map/data/version preview cases before allocation.");
var invalidReference=System.Text.Json.Nodes.JsonNode.Parse(sourceJson)!.AsObject();
var duplicateImage=invalidReference["Data"]!["MapReferenceImages"]![0]!.DeepClone();
duplicateImage["ImageID"]=Guid.NewGuid().ToString();
invalidReference["Data"]!["MapReferenceImages"]!.AsArray().Add(duplicateImage);
var failed=await service.ImportAsync(new(){JsonText=invalidReference.ToJsonString(),ConfirmImport=true,AcknowledgeWarnings=true,AllowDuplicateProjectTitle=true});
Check(!failed.Succeeded,"Invalid cross-entity reference must fail import.");
var afterFailure=await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects");
Console.WriteLine($"Failure rollback: projects before={baselineProjectCount}, after={afterFailure}.");
Check(afterFailure==baselineProjectCount,"Failed backup import must not retain an empty project shell.");
var result=await service.ImportAsync(new ImportIndexViewModel {JsonText=JsonSerializer.Serialize(before),ConfirmImport=true,AcknowledgeWarnings=true,AllowDuplicateProjectTitle=true});
Console.WriteLine($"Import result: {result.Succeeded}; {result.Message}; {result.TechnicalDetail}");
Check(result.Succeeded,"Full project backup import must preserve a synthetic map and core structure.");
var after=(await backups.GetProjectBackupAsync(result.ProjectID!.Value,user))!;
Check(after.Data.StoryMaps.Count==2,"Restored maps are present.");
var restoredMap=after.Data.StoryMaps.Single(x=>x.Name=="Synthetic map 雨");
Check(restoredMap.MapID!=map && after.Data.StoryMaps.Single(x=>x.Name=="Child map 雨").ParentMapID==restoredMap.MapID,"Map hierarchy is remapped.");
Check(after.Data.MapFeatures.Count==2 && after.Data.MapFeatures.Single(x=>x.Name=="Island 雪").GeometryJson==second.GeometryJson,"Map shapes and Unicode retained.");
Check(after.Data.MapRelationships.Single().MeasuredDistance==12.5m && after.Data.MapRelationships.Single().MapID==restoredMap.MapID,"Map relationship content and map reference retained.");
var restoredImage=after.Data.MapReferenceImages.Single();
Check(restoredImage.ImageID!=image.ImageID && restoredImage.ImageData!.SequenceEqual(sourceImageBytes),"Embedded image ID remapped and exact bytes retained.");
Check(MapAppearanceJson.Read<MapReferencePlacement>(restoredMap.ReferenceJson).ImageID==restoredImage.ImageID,"Map image placement references the new embedded asset.");
Check((await maps.GetAsync(project,map,user))!.Map.Name=="Synthetic map 雨","Original project remains unchanged.");
Check(after.Data.Books.Single().StoryEra=="Future era" && after.Data.Books.Single().PrimaryLocaleCode=="en-GB","Book era and locale preserved.");
var restoredPlans=await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.WritingPlans WHERE ProjectID=@id",new{id=result.ProjectID});
Console.WriteLine($"Writing plan coverage: source=1, imported={restoredPlans}; separate coverage gate.");
if(requireWritingPlans) Check(restoredPlans==1,"Persistent writing plan restored.");
Console.WriteLine("PASS isolated SQL maps/assets/hierarchy and book-context backup/import comparison; other entity coverage remains pending.");
}
}