fix: preserve image versions and roll back rejected persistence
This commit is contained in:
parent
c18bc24996
commit
0ef44ec3bf
@ -26,16 +26,16 @@ Route,FileName,Actor,Antiforgery,SourceImageID,HTTP
|
||||
"/Maps/UploadReference","no-token.png","Owner","Absent","","400"
|
||||
"/Maps/UploadReference","corrupt.png","Owner","Present when authenticated","","400"
|
||||
"/Maps/UploadReference","missing.png","Owner","Present when authenticated","","400"
|
||||
"/Characters/SaveAvatar","","Other author","Present when authenticated","32412","404"
|
||||
"/Characters/SaveAvatar","","Anonymous","Present when authenticated","32412","401"
|
||||
"/Characters/SaveAvatar","","Owner","Absent","32412","400"
|
||||
"/Characters/SaveAvatar","","Other author","Present when authenticated","33497","404"
|
||||
"/Characters/SaveAvatar","","Anonymous","Present when authenticated","33497","401"
|
||||
"/Characters/SaveAvatar","","Owner","Absent","33497","400"
|
||||
"/Characters/DeleteImage","","Other author","Present when authenticated","","404"
|
||||
"/Characters/DeleteImage","","Anonymous","Present when authenticated","","401"
|
||||
"/Characters/DeleteImage","","Owner","Absent","","400"
|
||||
"/Characters/RemoveAvatar","","Other author","Present when authenticated","","404"
|
||||
"/Characters/RemoveAvatar","","Anonymous","Present when authenticated","","401"
|
||||
"/Characters/RemoveAvatar","","Owner","Absent","","400"
|
||||
"/Characters/SaveAvatar","","Owner","Present when authenticated","32412","302"
|
||||
"/Characters/SaveAvatar","","Owner","Present when authenticated","33497","302"
|
||||
"/Characters/SaveAvatar","","Owner","Present when authenticated","0","302"
|
||||
"/Characters/DeleteImage","","Owner","Present when authenticated","","302"
|
||||
"/Characters/RemoveAvatar","","Owner","Present when authenticated","","302"
|
||||
|
||||
|
18
Docs/Sprints/2026-11-03-phase2-image-integrity-coverage.csv
Normal file
18
Docs/Sprints/2026-11-03-phase2-image-integrity-coverage.csv
Normal file
@ -0,0 +1,18 @@
|
||||
Workflow,Scenario,Execution,Verified,Evidence
|
||||
Avatar,SQL/file replacement interleaving,Production services + actual SQL/files,Original bytes retained or stale capture explicitly refused; fresh capture succeeds,/tmp/plotdirector-phase2-image-persistence-final.log
|
||||
Avatar,Two requests with one old model,Production services + actual SQL/files,Exactly current file paths remain active in owner storage ledger,/tmp/plotdirector-phase2-image-persistence-final.log
|
||||
Asset,SQL/file replacement interleaving,Production services + actual SQL/files,Original bytes retained or stale capture explicitly refused; fresh capture succeeds,/tmp/plotdirector-phase2-image-persistence-final.log
|
||||
Asset,Two requests with one old model,Production services + actual SQL/files,Exactly current file paths remain active in owner storage ledger,/tmp/plotdirector-phase2-image-persistence-final.log
|
||||
Cover,SQL/file replacement interleaving,Production services + actual SQL/files,Original bytes retained or stale capture explicitly refused; fresh capture succeeds,/tmp/plotdirector-phase2-image-persistence-final.log
|
||||
Cover,Two requests with one old model,Production services + actual SQL/files,Exactly current file paths remain active in owner storage ledger,/tmp/plotdirector-phase2-image-persistence-final.log
|
||||
Asset,Reference write refused by owned synthetic SQL trigger,Actual stored procedures + transaction + files,Original SQL and file bytes unchanged; no new orphan files; trigger removed,/tmp/plotdirector-phase2-image-persistence-final.log
|
||||
Asset,Ledger insert refused by owned synthetic SQL trigger,Actual stored procedures + transaction + files,Original SQL and file bytes unchanged; no new orphan files; trigger removed,/tmp/plotdirector-phase2-image-persistence-final.log
|
||||
Cover,Reference write refused by owned synthetic SQL trigger,Actual stored procedures + transaction + files,Original SQL and file bytes unchanged; no new orphan files; trigger removed,/tmp/plotdirector-phase2-image-persistence-final.log
|
||||
Cover,Ledger insert refused by owned synthetic SQL trigger,Actual stored procedures + transaction + files,Original SQL and file bytes unchanged; no new orphan files; trigger removed,/tmp/plotdirector-phase2-image-persistence-final.log
|
||||
Gallery,Reference write refused by owned synthetic SQL trigger,Actual stored procedures + transaction + files,Original SQL and file bytes unchanged; no new orphan files; trigger removed,/tmp/plotdirector-phase2-image-persistence-final.log
|
||||
Gallery,Ledger insert refused by owned synthetic SQL trigger,Actual stored procedures + transaction + files,Original SQL and file bytes unchanged; no new orphan files; trigger removed,/tmp/plotdirector-phase2-image-persistence-final.log
|
||||
Avatar,Reference write refused by owned synthetic SQL trigger,Actual stored procedures + transaction + files,Original SQL and file bytes unchanged; no new orphan files; trigger removed,/tmp/plotdirector-phase2-image-persistence-final.log
|
||||
Avatar,Ledger insert refused by owned synthetic SQL trigger,Actual stored procedures + transaction + files,Original SQL and file bytes unchanged; no new orphan files; trigger removed,/tmp/plotdirector-phase2-image-persistence-final.log
|
||||
Cover and gallery,Outer transaction rollback,Actual SQL/System.Transactions/files,Original files retained until commit; rollback removes new versions and rows,/tmp/plotdirector-phase2-image-persistence-final.log
|
||||
Project export,One changed-file capture,Production export/repository/files,Whole SQL/file read retried once; successful result uses fresh avatar path; one success activity call,/tmp/plotdirector-phase2-image-persistence-final.log
|
||||
Project export,Persistent unavailable file,Production export/repository; typed failure fixture,Stops after two capture attempts; no success activity call,/tmp/plotdirector-phase2-image-persistence-final.log
|
||||
|
@ -360,3 +360,19 @@ The four actual repository selectors now share one explicit serializable read tr
|
||||
Consistent-read checkpoint: controlled writer passed (`/tmp/plotdirector-phase2-backup-consistent-read.log`); writer stayed blocked during the split read, both values remained at the before version, and the writer then committed the after version. Complete 103-collection copy/in-place/rollback/account/guard matrix passed (`/tmp/plotdirector-phase2-transfer-consistent-read.log`). Build zero warnings/errors; full regression harness is running. Next isolated test checks fixed-path image replacement between SQL snapshot and file capture; do not claim filesystem consistency until that separate test passes.
|
||||
|
||||
Consistent SQL read regression checkpoint: full 405-check harness passed, exit 0 (`/tmp/plotdirector-phase2-tests-consistent-read.log`). No Development/Production writes or deployment; no database option/permission changes. Separate file replacement interleaving check remains next.
|
||||
|
||||
## Image version identity across SQL/file capture — 4 November (in progress)
|
||||
|
||||
Reproduced a second independent backup defect: after SQL metadata was captured, an avatar replacement overwrote the same `avatar.webp` path. Later file capture silently inserted the newer bytes into the older snapshot (`/tmp/plotdirector-phase2-backup-image-consistency-before.log`). Asset and cover writers use the same fixed-path pattern. New replacement filenames now include their existing generated version GUIDs; all legacy stored paths remain readable. A stale reference to a removed version now refuses capture instead of silently substituting new bytes. Missing-during-capture errors have a dedicated exception, and project export retries the entire SQL/file read once; persistent missing files still fail without success audit or a partial archive.
|
||||
|
||||
Initial versioning checks passed stale/fresh avatar, asset and cover capture, then exposed stale-model cleanup: two requests loading the same old model could leave an unreferenced version active in the storage ledger (`/tmp/plotdirector-phase2-image-versioning-stale-before.log`). Avatar create/remove and asset create/remove now share their entity lock and reload current paths inside it; cover upload reloads inside the existing book lock. Current tests also verify exact active ledger paths and bounded fresh-read retry. Keep this repair open pending full image/HTTP, persistence-failure cleanup, transfer and regression checks; no Development/Production writes or deployment.
|
||||
|
||||
Image-version checkpoint: all three stale/fresh snapshot interleavings, all three stale-model ledger checks and both bounded export retry cases passed. Eight actual SQL trigger refusals cover reference and ledger writes for asset, cover, gallery and avatar; all original rows/file bytes remained identical with no new orphan files. Temporary own synthetic triggers were removed in finally. An actual outer transaction rollback across cover/gallery writes also passed: old cover retained until commit; rollback removed new files and SQL/accounting changes. New image persistence helper groups existing stored-procedure writes in an ambient-aware transaction and defers physical cleanup to its final outcome; uncertain transaction outcomes retain both versions. No migration, inline application SQL or permission changes. Evidence `/tmp/plotdirector-phase2-image-persistence-final.log`; 17 scenario inventory `2026-11-03-phase2-image-integrity-coverage.csv` supplements the 28 format/crop and 40 HTTP inventories.
|
||||
|
||||
Final data/regression checkpoint for image versions: build zero warnings/errors (`/tmp/plotdirector-phase2-build-image-versions-final.log`); complete 103-collection copy/in-place/safety/rollback/account/guard matrix passed (`/tmp/plotdirector-phase2-transfer-image-versions.log`); full 405 checks passed (`/tmp/plotdirector-phase2-tests-image-versions.log`). Final real HTTP/SQL export run passed all eight packet types × five formats/aliases, owner/missing/anonymous boundaries and complete backup/restore-point downloads (`/tmp/plotdirector-phase2-exports-final.log`).
|
||||
|
||||
Browser refresh uses the database-free loopback command `dotnet run --no-build --project PlotLine.Tests/PlotLine.Tests.csproj -- --toolbar-browser-host`, port 5238. The old fixture host had exited. This flag must not be confused with `--maps-story-dev-fixture`, which writes Development data and was not run. Playwright/SignalR dependencies resolve from `PlotLine.Tests/Browser/node_modules`. Fresh current-assembly Writer/goal browser smoke and final restart gate remain next.
|
||||
|
||||
Fresh browser checkpoint: current-assembly database-free full-layout Writer/real-Hub browser/PWA recovery/windows/navigation passed (`/tmp/plotdirector-phase2-writer-final.log`); chapter goal guard/controller/anti-forgery/Unicode/save-failure-retry/concurrent-edit cases passed (`/tmp/plotdirector-phase2-writer-goals-final.log`). The owned fixture host was stopped afterward; no Development host was restarted. This remains fixture verification, not authenticated live acceptance.
|
||||
|
||||
Next confirmed code-path concern to reproduce: RestoreAsync deserializes old snapshots into default-empty DTO collections and serializes them again for SQL. Existing SQL omission guards distinguish absent collections from empty arrays; normalization may therefore defeat the intended protection. Exercise actual restore service, not only direct stored-procedure guard calls, before closing transfer work.
|
||||
|
||||
59
PlotLine.Tests/ImagePersistenceFailureTests.cs
Normal file
59
PlotLine.Tests/ImagePersistenceFailureTests.cs
Normal file
@ -0,0 +1,59 @@
|
||||
using Dapper;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Services;
|
||||
using SkiaSharp;
|
||||
|
||||
internal static class ImagePersistenceFailureTests
|
||||
{
|
||||
private static void Check(bool condition,string message){if(!condition)throw new InvalidOperationException(message);}
|
||||
internal static async Task RunAsync(ISqlConnectionFactory factory,IUploadStorageService uploads,VisualIdentityImageService visual,BookCoverService covers,int project,int characterID,int assetID,int bookID,Func<Task<string>> state)
|
||||
{
|
||||
using var db=factory.CreateConnection();
|
||||
Check(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()") == "PlotDirector_Phase2_20261103_2305" && 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'")==1,"Image rejection fixture requires marked synthetic database.");
|
||||
byte[] bytes;
|
||||
using(var bitmap=new SKBitmap(31,27)){bitmap.Erase(SKColors.Blue);using var image=SKImage.FromBitmap(bitmap);using var data=image.Encode(SKEncodedImageFormat.Png,100);bytes=data.ToArray();}
|
||||
Microsoft.AspNetCore.Http.IFormFile Upload()=>new Microsoft.AspNetCore.Http.FormFile(new MemoryStream(bytes),0,bytes.Length,"image","Persistence failure Ω.png");
|
||||
async Task<Character> Character()=>await db.QuerySingleAsync<Character>("SELECT * FROM dbo.Characters WHERE CharacterID=@characterID AND ProjectID=@project",new{characterID,project});
|
||||
var cases=new (string Name,string Table,string Event,string Column,int ID,string Condition,Func<Task> Action)[]{
|
||||
("Asset","StoryAssets","UPDATE","StoryAssetID",assetID,"UPDATE(ImagePath)",async()=>Check(!(await visual.UploadAssetImageAsync(await db.QuerySingleAsync<StoryAsset>("SELECT * FROM dbo.StoryAssets WHERE StoryAssetID=@assetID",new{assetID}),Upload())).Succeeded,"Rejected asset reports failure.")),
|
||||
("Cover","Books","UPDATE","BookID",bookID,"UPDATE(CoverStandardPath)",async()=>Check(!(await covers.UploadCoverAsync(await db.QuerySingleAsync<Book>("SELECT * FROM dbo.Books WHERE BookID=@bookID",new{bookID}),Upload())).Succeeded,"Rejected cover reports failure.")),
|
||||
("Gallery","CharacterImages","INSERT","CharacterID",characterID,"1=1",async()=>Check(!(await visual.UploadCharacterGalleryImageAsync(await Character(),Upload(),"Rejected source")).Succeeded,"Rejected gallery reports failure.")),
|
||||
("Avatar","Characters","UPDATE","CharacterID",characterID,"UPDATE(AvatarImagePath)",async()=>
|
||||
{
|
||||
var character=await Character();var source=(await new CharacterRepository(factory).GetCharacterImageAsync(character.AvatarSourceCharacterImageID!.Value))!;
|
||||
try{Check(!(await visual.CreateCharacterAvatarAsync(character,source,0,0,24)).Succeeded,"Rejected avatar reports failure.");}
|
||||
catch(SqlException ex) when(ex.Number==51098){}
|
||||
})
|
||||
};
|
||||
foreach(var item in cases)
|
||||
foreach(var ledger in new[]{false,true})
|
||||
{
|
||||
var before=await state();var trigger="Phase2ImageReject_"+Guid.NewGuid().ToString("N");
|
||||
try
|
||||
{
|
||||
var table=ledger ? "UserFile" : item.Table;var operation=ledger ? "INSERT" : item.Event;
|
||||
var entityType=item.Name switch {"Asset"=>"StoryAssetImage","Cover"=>"BookCover","Gallery"=>"CharacterImage",_=>"CharacterAvatar"};
|
||||
var condition=ledger ? $"EXISTS(SELECT 1 FROM inserted WHERE ProjectID={project} AND EntityType=N'{entityType}')" : $"({item.Condition}) AND EXISTS(SELECT 1 FROM inserted WHERE [{item.Column}]={item.ID})";
|
||||
await db.ExecuteAsync($"CREATE TRIGGER dbo.[{trigger}] ON dbo.[{table}] AFTER {operation} AS BEGIN SET NOCOUNT ON;IF {condition} THROW 51098,'Synthetic image persistence refusal.',1;END;");
|
||||
await item.Action();
|
||||
Check(before==await state(),"Rejected "+item.Name+(ledger ? " ledger" : " reference")+" persistence preserves every original SQL/file byte and leaves no new orphan files.");
|
||||
}
|
||||
finally{await db.ExecuteAsync($"DROP TRIGGER IF EXISTS dbo.[{trigger}]");}
|
||||
}
|
||||
var originalBook=await db.QuerySingleAsync<Book>("SELECT * FROM dbo.Books WHERE BookID=@bookID",new{bookID});
|
||||
var beforeOuter=await state();
|
||||
using(var rollback=new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required,
|
||||
new System.Transactions.TransactionOptions{IsolationLevel=System.Transactions.IsolationLevel.ReadCommitted,Timeout=TimeSpan.FromSeconds(30)},System.Transactions.TransactionScopeAsyncFlowOption.Enabled))
|
||||
{
|
||||
Check((await covers.UploadCoverAsync(originalBook,Upload())).Succeeded,"Nested cover upload completes its local work.");
|
||||
Check((await visual.UploadCharacterGalleryImageAsync(await Character(),Upload(),"Outer rollback source")).Succeeded,"Nested gallery upload completes its local work.");
|
||||
Check(File.Exists(uploads.TryResolvePublicPath(originalBook.CoverStandardPath,"uploads/books")),"Old cover remains available until the owning transaction commits.");
|
||||
// Deliberately omit Complete: both SQL and newly staged files must roll back.
|
||||
}
|
||||
Check(beforeOuter==await state(),"Outer transaction rollback restores SQL/accounting and removes new cover/gallery files without deleting originals.");
|
||||
Console.WriteLine("PASS image outer rollback: deferred old-file cleanup and removal of uncommitted cover/gallery versions.");
|
||||
Console.WriteLine("PASS eight actual SQL image persistence refusals (references and ledger): source rows/files unchanged and no new orphan files; all owned synthetic triggers removed.");
|
||||
}
|
||||
}
|
||||
@ -83,6 +83,8 @@ internal static class ImageTransferDatabaseTests
|
||||
Console.WriteLine("PASS supported image/crop source "+extension);
|
||||
coverage.Add($"Character avatar,{extension},Production service + real SQL/files,256x256 WebP crop and gallery source identity,Geometry clamping intentional; physical UI acceptance separate");
|
||||
}
|
||||
await ProjectBackupImageConsistencyTests.RunAsync(factory,uploads,visual,covers,owner,project,characterID,assetID,bookID);
|
||||
await ImagePersistenceFailureTests.RunAsync(factory,uploads,visual,covers,project,characterID,assetID,bookID,StateAsync);
|
||||
var tracked=(await db.QueryAsync<UserFile>("SELECT * FROM dbo.UserFile WHERE ProjectID=@project AND IsDeleted=0",new{project})).ToList();
|
||||
foreach(var file in tracked.Where(x=>x.EntityType!="MapReferenceImage"))
|
||||
Check(file.UserID==owner && File.Exists(Physical(file.StoragePath)) && new FileInfo(Physical(file.StoragePath)).Length==file.FileSizeBytes,"Active ledger uses project owner and actual stored bytes: "+file.StoragePath);
|
||||
|
||||
93
PlotLine.Tests/ProjectBackupImageConsistencyTests.cs
Normal file
93
PlotLine.Tests/ProjectBackupImageConsistencyTests.cs
Normal file
@ -0,0 +1,93 @@
|
||||
using Dapper;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Services;
|
||||
using SkiaSharp;
|
||||
|
||||
internal static class ProjectBackupImageConsistencyTests
|
||||
{
|
||||
private static void Check(bool condition,string message){if(!condition)throw new InvalidOperationException(message);}
|
||||
private static T Proxy<T>(Func<string,object?[]?,object?> handler) where T:class
|
||||
{var result=DispatchProxy.Create<T,StoryPointProxy>();((StoryPointProxy)(object)result).Handler=handler;return result;}
|
||||
internal static async Task RunAsync(ISqlConnectionFactory factory,IUploadStorageService uploads,VisualIdentityImageService visual,BookCoverService covers,int owner,int project,int characterID,int assetID,int bookID)
|
||||
{
|
||||
using var db=factory.CreateConnection();
|
||||
Check(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()") == "PlotDirector_Phase2_20261103_2305" && 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'")==1,"File consistency fixture requires marked synthetic database.");
|
||||
var files=new ProjectBackupFiles(uploads);var backups=new ProjectBackupRepository(factory);var characters=new CharacterRepository(factory);
|
||||
async Task<Character> Character()=>await db.QuerySingleAsync<Character>("SELECT * FROM dbo.Characters WHERE CharacterID=@characterID AND ProjectID=@project",new{characterID,project});
|
||||
byte[] replacement;
|
||||
using(var bitmap=new SKBitmap(37,43)){bitmap.Erase(SKColors.Red);using var image=SKImage.FromBitmap(bitmap);using var data=image.Encode(SKEncodedImageFormat.Png,100);replacement=data.ToArray();}
|
||||
Microsoft.AspNetCore.Http.IFormFile Upload()=>new Microsoft.AspNetCore.Http.FormFile(new MemoryStream(replacement),0,replacement.Length,"image","Changed image 雨.png");
|
||||
var operations=new (string Name,Func<ProjectBackupExport,string?> Path,Func<Task> Replace)[]{
|
||||
("Avatar",backup=>backup.Data.Characters.Single(x=>x.CharacterID==characterID).AvatarImagePath,async()=>
|
||||
{
|
||||
var character=await Character();var source=(await characters.GetCharacterImageAsync(character.AvatarSourceCharacterImageID!.Value))!;
|
||||
Check((await visual.CreateCharacterAvatarAsync(character,source,12,10,32)).Succeeded,"Synthetic avatar changed successfully.");
|
||||
}),
|
||||
("Asset",backup=>backup.Data.StoryAssets.Single(x=>x.StoryAssetID==assetID).ImagePath,async()=>
|
||||
{
|
||||
var asset=await db.QuerySingleAsync<StoryAsset>("SELECT * FROM dbo.StoryAssets WHERE StoryAssetID=@assetID AND ProjectID=@project",new{assetID,project});
|
||||
Check((await visual.UploadAssetImageAsync(asset,Upload())).Succeeded,"Synthetic asset image changed successfully.");
|
||||
}),
|
||||
("Cover",backup=>backup.Data.Books.Single(x=>x.BookID==bookID).CoverStandardPath,async()=>
|
||||
{
|
||||
var book=await db.QuerySingleAsync<Book>("SELECT * FROM dbo.Books WHERE BookID=@bookID AND ProjectID=@project",new{bookID,project});
|
||||
Check((await covers.UploadCoverAsync(book,Upload())).Succeeded,"Synthetic book cover changed successfully.");
|
||||
})
|
||||
};
|
||||
foreach(var operation in operations)
|
||||
{
|
||||
var stale=(await backups.GetProjectBackupAsync(project,owner))!;await files.CaptureAsync(stale);
|
||||
var oldPath=operation.Path(stale)!;var oldHash=stale.Files.Single(x=>x.Path==oldPath).Sha256;
|
||||
await operation.Replace();
|
||||
var fresh=(await backups.GetProjectBackupAsync(project,owner))!;await files.CaptureAsync(fresh);
|
||||
Check(fresh.Files.Single(x=>x.Path==operation.Path(fresh)).Sha256!=oldHash,"Replacement fixture actually changes encoded bytes: "+operation.Name);
|
||||
var refused=false;
|
||||
try{await files.CaptureAsync(stale);}
|
||||
catch(ProjectBackupFileUnavailableException){refused=true;}
|
||||
Check(refused || stale.Files.Single(x=>x.Path==oldPath).Sha256==oldHash,"Backup silently substituted a newer "+operation.Name+" file into an older SQL snapshot.");
|
||||
Console.WriteLine("PASS "+operation.Name+" replacement: stale capture retains original bytes or explicitly refuses; fresh SQL/file capture succeeds.");
|
||||
}
|
||||
// Two requests may load the same entity before either reaches its upload lock.
|
||||
var staleCharacter=await Character();
|
||||
var gallery=(await characters.GetCharacterImageAsync(staleCharacter.AvatarSourceCharacterImageID!.Value))!;
|
||||
Check((await visual.CreateCharacterAvatarAsync(staleCharacter,gallery,0,0,16)).Succeeded && (await visual.CreateCharacterAvatarAsync(staleCharacter,gallery,4,8,24)).Succeeded,"Repeated stale-model avatar uploads succeed.");
|
||||
var currentCharacter=await Character();
|
||||
var avatarPaths=(await db.QueryAsync<string>("SELECT StoragePath FROM dbo.UserFile WHERE ProjectID=@project AND EntityID=@characterID AND EntityType=N'CharacterAvatar' AND IsDeleted=0",new{project,characterID})).ToHashSet();
|
||||
Check(avatarPaths.SetEquals([currentCharacter.AvatarImagePath!]),"Stale-model avatar replacement leaves only the current avatar active in storage accounting.");
|
||||
var staleAsset=await db.QuerySingleAsync<StoryAsset>("SELECT * FROM dbo.StoryAssets WHERE StoryAssetID=@assetID AND ProjectID=@project",new{assetID,project});
|
||||
Check((await visual.UploadAssetImageAsync(staleAsset,Upload())).Succeeded && (await visual.UploadAssetImageAsync(staleAsset,Upload())).Succeeded,"Repeated stale-model asset uploads succeed.");
|
||||
var currentAsset=await db.QuerySingleAsync<StoryAsset>("SELECT * FROM dbo.StoryAssets WHERE StoryAssetID=@assetID",new{assetID});
|
||||
var assetPaths=(await db.QueryAsync<string>("SELECT StoragePath FROM dbo.UserFile WHERE ProjectID=@project AND EntityID=@assetID AND EntityType=N'StoryAssetImage' AND IsDeleted=0",new{project,assetID})).ToHashSet();
|
||||
Check(assetPaths.SetEquals([currentAsset.ImagePath!,currentAsset.ThumbnailPath!]),"Stale-model asset replacement leaves only current files active in storage accounting.");
|
||||
var staleBook=await db.QuerySingleAsync<Book>("SELECT * FROM dbo.Books WHERE BookID=@bookID AND ProjectID=@project",new{bookID,project});
|
||||
Check((await covers.UploadCoverAsync(staleBook,Upload())).Succeeded && (await covers.UploadCoverAsync(staleBook,Upload())).Succeeded,"Repeated stale-model cover uploads succeed.");
|
||||
var currentBook=await db.QuerySingleAsync<Book>("SELECT * FROM dbo.Books WHERE BookID=@bookID",new{bookID});
|
||||
var coverPaths=(await db.QueryAsync<string>("SELECT StoragePath FROM dbo.UserFile WHERE ProjectID=@project AND EntityID=@bookID AND EntityType=N'BookCover' AND IsDeleted=0",new{project,bookID})).ToHashSet();
|
||||
Check(coverPaths.SetEquals([currentBook.CoverStandardPath!,currentBook.CoverThumbnailPath!]),"Stale-model cover replacement leaves only current files active in storage accounting.");
|
||||
Console.WriteLine("PASS stale-model replacement: avatar/asset/cover retain exactly their current active file ledger paths.");
|
||||
var captures=0;var activities=0;
|
||||
async Task CaptureWithChange(ProjectBackupExport snapshot)
|
||||
{
|
||||
if(++captures==1)await operations[0].Replace();
|
||||
await files.CaptureAsync(snapshot);
|
||||
}
|
||||
var changing=Proxy<IProjectBackupFiles>((name,args)=>name=="CaptureAsync" ? CaptureWithChange((ProjectBackupExport)args![0]!) : throw new NotSupportedException(name));
|
||||
var user=Proxy<ICurrentUserService>((name,args)=>name=="get_UserId" ? (int?)owner : throw new NotSupportedException(name));
|
||||
var activity=Proxy<IProjectActivityService>((name,args)=>name=="RecordAsync" ? Recorded() : throw new NotSupportedException(name));
|
||||
Task Recorded(){activities++;return Task.CompletedTask;}
|
||||
var exported=await new ProjectExportService(backups,activity,user,NullLogger<ProjectExportService>.Instance,changing).ExportAsync(project);
|
||||
var restored=JsonSerializer.Deserialize<ProjectBackupExport>(exported!.Json,new JsonSerializerOptions{PropertyNameCaseInsensitive=true})!;
|
||||
Check(captures==2 && activities==1 && restored.Data.Characters.Single(x=>x.CharacterID==characterID).AvatarImagePath==(await Character()).AvatarImagePath,"Changed file retries the whole SQL/file export once and records only the successful export.");
|
||||
captures=0;
|
||||
var unavailable=Proxy<IProjectBackupFiles>((name,args)=>name=="CaptureAsync" ? Missing() : throw new NotSupportedException(name));
|
||||
Task Missing(){captures++;return Task.FromException(new ProjectBackupFileUnavailableException("Synthetic permanently unavailable file."));}
|
||||
try{await new ProjectExportService(backups,activity,user,NullLogger<ProjectExportService>.Instance,unavailable).ExportAsync(project);throw new InvalidOperationException("Persistent file failure was hidden.");}
|
||||
catch(ProjectBackupFileUnavailableException){}
|
||||
Check(captures==2 && activities==1,"Persistent file failure stops after one retry without claiming export success.");
|
||||
Console.WriteLine("PASS export file retry: actual replacement forces fresh SQL capture; persistent failure remains bounded and creates no success audit.");
|
||||
}
|
||||
}
|
||||
@ -594,7 +594,7 @@ internal static class ProjectTransferDatabaseTests
|
||||
var refusedSafety=await missingSafety.RestoreAsync(result.ProjectID.Value,copiedPoint.ProjectRestorePointID);
|
||||
Check(!refusedSafety.Succeeded && refusedSafety.SafetyBackup is null,"Missing active files abort restore cleanly when a complete safety backup cannot be made.");
|
||||
var missingFileRejected=false;
|
||||
try {await copiedExport.ExportAsync(result.ProjectID.Value);}catch(InvalidDataException){missingFileRejected=true;}
|
||||
try {await copiedExport.ExportAsync(result.ProjectID.Value);}catch(ProjectBackupFileUnavailableException){missingFileRejected=true;}
|
||||
Check(missingFileRejected,"Export refuses a backup with a missing active file instead of reporting complete success.");
|
||||
var coverage=new List<string>{"Collection,SourceRows,CopyRows,InPlaceRows,Verification"};
|
||||
foreach(var property in typeof(ProjectBackupData).GetProperties())
|
||||
|
||||
@ -23,8 +23,6 @@ public sealed class BookCoverService(
|
||||
{
|
||||
public const string PlaceholderPath = "/images/placeholders/book-cover.svg";
|
||||
private const long MaxUploadBytes = 10L * 1024L * 1024L;
|
||||
private const string ThumbnailFileName = "cover-thumb.webp";
|
||||
private const string StandardFileName = "cover-standard.webp";
|
||||
private static readonly HashSet<string> SupportedExtensions = new(StringComparer.OrdinalIgnoreCase) { ".jpg", ".jpeg", ".png", ".webp" };
|
||||
private static readonly ConcurrentDictionary<int, SemaphoreSlim> BookLocks = new();
|
||||
|
||||
@ -34,7 +32,8 @@ public sealed class BookCoverService(
|
||||
await uploadLock.WaitAsync();
|
||||
try
|
||||
{
|
||||
return await UploadCoverCoreAsync(book, upload);
|
||||
var current=await books.GetAsync(book.BookID);
|
||||
return current is null ? new(false,"Book not found.") : await UploadCoverCoreAsync(current,upload);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@ -106,11 +105,14 @@ public sealed class BookCoverService(
|
||||
var version = Guid.NewGuid().ToString("N");
|
||||
var thumbnailTemp = Path.Combine(uploadRoot, $"cover-thumb-{version}.tmp");
|
||||
var standardTemp = Path.Combine(uploadRoot, $"cover-standard-{version}.tmp");
|
||||
var thumbnailPath = Path.Combine(uploadRoot, ThumbnailFileName);
|
||||
var standardPath = Path.Combine(uploadRoot, StandardFileName);
|
||||
var thumbnailStoragePath = uploadStorage.GetPublicPath("books", book.BookID.ToString(), ThumbnailFileName);
|
||||
var standardStoragePath = uploadStorage.GetPublicPath("books", book.BookID.ToString(), StandardFileName);
|
||||
var thumbnailName = $"cover-thumb-{version}.webp";
|
||||
var standardName = $"cover-standard-{version}.webp";
|
||||
var thumbnailPath = Path.Combine(uploadRoot, thumbnailName);
|
||||
var standardPath = Path.Combine(uploadRoot, standardName);
|
||||
var thumbnailStoragePath = uploadStorage.GetPublicPath("books", book.BookID.ToString(), thumbnailName);
|
||||
var standardStoragePath = uploadStorage.GetPublicPath("books", book.BookID.ToString(), standardName);
|
||||
|
||||
var persistenceHandled=false;
|
||||
try
|
||||
{
|
||||
SaveWebpVariant(bitmap, thumbnailTemp, 400, 600, 72);
|
||||
@ -121,22 +123,31 @@ public sealed class BookCoverService(
|
||||
|
||||
var oldThumbnailPath = book.CoverThumbnailPath;
|
||||
var oldStandardPath = book.CoverStandardPath;
|
||||
await books.UpdateCoverAsync(book.BookID, thumbnailStoragePath, standardStoragePath);
|
||||
await MarkPreviousLedgerRowsAsync(oldThumbnailPath);
|
||||
await MarkPreviousLedgerRowsAsync(oldStandardPath);
|
||||
await TrackCoverAsync(ownerUserId.Value, book.ProjectID, book.BookID, thumbnailStoragePath, "Book cover thumbnail", new FileInfo(thumbnailPath).Length);
|
||||
await TrackCoverAsync(ownerUserId.Value, book.ProjectID, book.BookID, standardStoragePath, "Book cover standard", new FileInfo(standardPath).Length);
|
||||
DeletePreviousPhysicalFile(oldThumbnailPath, thumbnailStoragePath);
|
||||
DeletePreviousPhysicalFile(oldStandardPath, standardStoragePath);
|
||||
persistenceHandled=true;
|
||||
await ImagePersistenceTransaction.RunAsync(async()=>
|
||||
{
|
||||
await books.UpdateCoverAsync(book.BookID, thumbnailStoragePath, standardStoragePath);
|
||||
await MarkPreviousLedgerRowsAsync(oldThumbnailPath);
|
||||
await MarkPreviousLedgerRowsAsync(oldStandardPath);
|
||||
await TrackCoverAsync(ownerUserId.Value, book.ProjectID, book.BookID, thumbnailStoragePath, "Book cover thumbnail", new FileInfo(thumbnailPath).Length);
|
||||
await TrackCoverAsync(ownerUserId.Value, book.ProjectID, book.BookID, standardStoragePath, "Book cover standard", new FileInfo(standardPath).Length);
|
||||
},()=>
|
||||
{
|
||||
DeletePreviousPhysicalFile(oldThumbnailPath, thumbnailStoragePath);
|
||||
DeletePreviousPhysicalFile(oldStandardPath, standardStoragePath);
|
||||
},()=>{TryDeleteFile(thumbnailPath);TryDeleteFile(standardPath);},logger);
|
||||
return new(true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
TryDeleteFile(thumbnailTemp);
|
||||
TryDeleteFile(standardTemp);
|
||||
logger.LogWarning(ex, "Book cover upload failed for book {BookID}.", book.BookID);
|
||||
return new(false, "Cover image could not be processed. Try another image.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
TryDeleteFile(thumbnailTemp);TryDeleteFile(standardTemp);
|
||||
if(!persistenceHandled){TryDeleteFile(thumbnailPath);TryDeleteFile(standardPath);}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
38
PlotLine/Services/ImagePersistenceTransaction.cs
Normal file
38
PlotLine/Services/ImagePersistenceTransaction.cs
Normal file
@ -0,0 +1,38 @@
|
||||
using System.Transactions;
|
||||
|
||||
namespace PlotLine.Services;
|
||||
|
||||
// Keep SQL references/accounting atomic; versioned files make commit/rollback cleanup safe.
|
||||
internal static class ImagePersistenceTransaction
|
||||
{
|
||||
internal static async Task RunAsync(Func<Task> write,Action? committed,Action rolledBack,ILogger logger)
|
||||
{
|
||||
var registered=false;
|
||||
void Cleanup(Action? action)
|
||||
{
|
||||
if(action is null)return;
|
||||
try{action();}catch(Exception ex){logger.LogWarning(ex,"Image transaction file cleanup failed; retained files require cleanup.");}
|
||||
}
|
||||
try
|
||||
{
|
||||
using var scope=new TransactionScope(TransactionScopeOption.Required,
|
||||
new TransactionOptions{IsolationLevel=Transaction.Current?.IsolationLevel ?? IsolationLevel.ReadCommitted,Timeout=TimeSpan.FromSeconds(30)},TransactionScopeAsyncFlowOption.Enabled);
|
||||
var transaction=Transaction.Current!;
|
||||
transaction.TransactionCompleted+=(_,args)=>
|
||||
{
|
||||
var status=args.Transaction?.TransactionInformation.Status;
|
||||
if(status==TransactionStatus.Committed)Cleanup(committed);
|
||||
else if(status==TransactionStatus.Aborted)Cleanup(rolledBack);
|
||||
else logger.LogWarning("Image transaction ended with status {Status}; retaining both file versions.",status);
|
||||
};
|
||||
registered=true;
|
||||
await write();
|
||||
scope.Complete();
|
||||
}
|
||||
catch
|
||||
{
|
||||
if(!registered)Cleanup(rolledBack);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -3,6 +3,9 @@ using PlotLine.Models;
|
||||
|
||||
namespace PlotLine.Services;
|
||||
|
||||
public sealed class ProjectBackupFileUnavailableException(string message, Exception? innerException=null) : IOException(message,innerException);
|
||||
|
||||
|
||||
public interface IProjectBackupFiles
|
||||
{
|
||||
Task CaptureAsync(ProjectBackupExport backup);
|
||||
@ -94,8 +97,11 @@ public sealed class ProjectBackupFiles(IUploadStorageService storage) : IProject
|
||||
if(!ValidPath(reference))throw new InvalidDataException("A project file path does not belong to its owning entity.");
|
||||
if(files.Any(file=>file.Path==reference.Path))continue;
|
||||
var physical=storage.TryResolvePublicPath(reference.Path,"uploads/"+reference.Folder);
|
||||
if(physical is null || !File.Exists(physical))throw new InvalidDataException("A referenced project file is missing. The backup was not created.");
|
||||
var bytes=await File.ReadAllBytesAsync(physical);
|
||||
if(physical is null || !File.Exists(physical))throw new ProjectBackupFileUnavailableException("A referenced project file is missing. The backup was not created.");
|
||||
byte[] bytes;
|
||||
try{bytes=await File.ReadAllBytesAsync(physical);}
|
||||
catch(Exception ex) when(ex is FileNotFoundException or DirectoryNotFoundException)
|
||||
{throw new ProjectBackupFileUnavailableException("A referenced project file changed during capture. The backup was not created.",ex);}
|
||||
files.Add(new(){Path=reference.Path!,Data=bytes,Sha256=Convert.ToHexString(SHA256.HashData(bytes))});
|
||||
}
|
||||
backup.Files=files;
|
||||
|
||||
@ -22,7 +22,9 @@ public sealed class ProjectExportService(
|
||||
WriteIndented = true
|
||||
};
|
||||
|
||||
public async Task<ProjectBackupResult?> ExportAsync(int projectId)
|
||||
public Task<ProjectBackupResult?> ExportAsync(int projectId) => ExportCoreAsync(projectId,true);
|
||||
|
||||
private async Task<ProjectBackupResult?> ExportCoreAsync(int projectId,bool retryFileCapture)
|
||||
{
|
||||
if (!currentUser.UserId.HasValue)
|
||||
{
|
||||
@ -36,7 +38,12 @@ public sealed class ProjectExportService(
|
||||
return null;
|
||||
}
|
||||
|
||||
await files.CaptureAsync(backup);
|
||||
try{await files.CaptureAsync(backup);}
|
||||
catch(ProjectBackupFileUnavailableException) when(retryFileCapture)
|
||||
{
|
||||
logger.LogInformation("Project files were unavailable during backup capture for {ProjectID}; retrying once from fresh SQL data.",projectId);
|
||||
return await ExportCoreAsync(projectId,false);
|
||||
}
|
||||
var json = JsonSerializer.Serialize(backup, JsonOptions);
|
||||
var fileName = BuildFileName(backup.Project.ProjectName, backup.ExportedAtUtc);
|
||||
|
||||
|
||||
@ -48,6 +48,18 @@ public sealed class VisualIdentityImageService(
|
||||
(imagePath, thumbnailPath) => characters.UpdateCharacterImageAsync(character.CharacterID, imagePath, thumbnailPath));
|
||||
|
||||
public async Task RemoveCharacterAvatarAsync(Character character)
|
||||
{
|
||||
var avatarLock=EntityLocks.GetOrAdd($"character-avatar:{character.CharacterID}",_=>new SemaphoreSlim(1,1));
|
||||
await avatarLock.WaitAsync();
|
||||
try
|
||||
{
|
||||
var current=await characters.GetCharacterAsync(character.CharacterID);
|
||||
if(current is not null)await RemoveCharacterAvatarCoreAsync(current);
|
||||
}
|
||||
finally{avatarLock.Release();}
|
||||
}
|
||||
|
||||
private async Task RemoveCharacterAvatarCoreAsync(Character character)
|
||||
{
|
||||
await characters.UpdateCharacterAvatarAsync(character.CharacterID, null, null, null);
|
||||
await MarkPreviousLedgerRowsAsync(character.AvatarImagePath);
|
||||
@ -66,6 +78,18 @@ public sealed class VisualIdentityImageService(
|
||||
}
|
||||
|
||||
public async Task<VisualIdentityImageResult> CreateCharacterAvatarAsync(Character character, CharacterImage sourceImage, int cropX, int cropY, int cropSize)
|
||||
{
|
||||
var avatarLock=EntityLocks.GetOrAdd($"character-avatar:{character.CharacterID}",_=>new SemaphoreSlim(1,1));
|
||||
await avatarLock.WaitAsync();
|
||||
try
|
||||
{
|
||||
var current=await characters.GetCharacterAsync(character.CharacterID);
|
||||
return current is null ? new(false,"Character not found.") : await CreateCharacterAvatarCoreAsync(current,sourceImage,cropX,cropY,cropSize);
|
||||
}
|
||||
finally{avatarLock.Release();}
|
||||
}
|
||||
|
||||
private async Task<VisualIdentityImageResult> CreateCharacterAvatarCoreAsync(Character character, CharacterImage sourceImage, int cropX, int cropY, int cropSize)
|
||||
{
|
||||
if (sourceImage.CharacterID != character.CharacterID)
|
||||
{
|
||||
@ -90,6 +114,8 @@ public sealed class VisualIdentityImageService(
|
||||
return new(false, storageLimit.Message);
|
||||
}
|
||||
|
||||
string? avatarTemp=null,avatarPath=null;
|
||||
var persistenceHandled=false;
|
||||
try
|
||||
{
|
||||
using var bitmap = SKBitmap.Decode(sourcePath) ?? throw new InvalidDataException();
|
||||
@ -100,68 +126,65 @@ public sealed class VisualIdentityImageService(
|
||||
|
||||
var uploadRoot = uploadStorage.GetDirectory("characters", character.CharacterID.ToString());
|
||||
var version = Guid.NewGuid().ToString("N");
|
||||
var avatarTemp = Path.Combine(uploadRoot, $"avatar-{version}.tmp");
|
||||
var avatarPath = Path.Combine(uploadRoot, "avatar.webp");
|
||||
var avatarStoragePath = uploadStorage.GetPublicPath("characters", character.CharacterID.ToString(), "avatar.webp");
|
||||
avatarTemp = Path.Combine(uploadRoot, $"avatar-{version}.tmp");
|
||||
var avatarName = $"avatar-{version}.webp";
|
||||
avatarPath = Path.Combine(uploadRoot, avatarName);
|
||||
var avatarStoragePath = uploadStorage.GetPublicPath("characters", character.CharacterID.ToString(), avatarName);
|
||||
|
||||
SaveWebp(bitmap, avatarTemp, new SKRect(cropX, cropY, cropX + size, cropY + size), 256, 256, 82);
|
||||
ReplaceFile(avatarTemp, avatarPath);
|
||||
|
||||
await characters.UpdateCharacterAvatarAsync(character.CharacterID, sourceImage.CharacterImageID, avatarStoragePath, avatarStoragePath);
|
||||
await MarkPreviousLedgerRowsAsync(character.AvatarImagePath);
|
||||
await MarkPreviousLedgerRowsAsync(character.AvatarThumbnailPath);
|
||||
await TrackImageAsync(ownerUserId.Value, character.ProjectID, character.CharacterID, "CharacterAvatar", avatarStoragePath, "Character avatar", new FileInfo(avatarPath).Length);
|
||||
DeletePreviousPhysicalFile(character.AvatarImagePath, avatarStoragePath, "uploads/characters");
|
||||
DeletePreviousPhysicalFile(character.AvatarThumbnailPath, avatarStoragePath, "uploads/characters");
|
||||
persistenceHandled=true;
|
||||
await ImagePersistenceTransaction.RunAsync(async()=>
|
||||
{
|
||||
await characters.UpdateCharacterAvatarAsync(character.CharacterID, sourceImage.CharacterImageID, avatarStoragePath, avatarStoragePath);
|
||||
await MarkPreviousLedgerRowsAsync(character.AvatarImagePath);
|
||||
await MarkPreviousLedgerRowsAsync(character.AvatarThumbnailPath);
|
||||
await TrackImageAsync(ownerUserId.Value, character.ProjectID, character.CharacterID, "CharacterAvatar", avatarStoragePath, "Character avatar", new FileInfo(avatarPath).Length);
|
||||
},()=>
|
||||
{
|
||||
DeletePreviousPhysicalFile(character.AvatarImagePath, avatarStoragePath, "uploads/characters");
|
||||
DeletePreviousPhysicalFile(character.AvatarThumbnailPath, avatarStoragePath, "uploads/characters");
|
||||
},()=>TryDeleteFile(avatarPath!),logger);
|
||||
return new(true);
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidDataException or IOException or ArgumentException)
|
||||
catch (Exception ex) when (ex is InvalidDataException or IOException or ArgumentException or Microsoft.Data.SqlClient.SqlException or System.Transactions.TransactionException)
|
||||
{
|
||||
logger.LogWarning(ex, "Character avatar crop failed for Character {CharacterID}.", character.CharacterID);
|
||||
return new(false, "Avatar could not be generated. Try another crop or source image.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if(avatarTemp is not null)TryDeleteFile(avatarTemp);
|
||||
if(!persistenceHandled && avatarPath is not null)TryDeleteFile(avatarPath);
|
||||
}
|
||||
}
|
||||
|
||||
public Task<VisualIdentityImageResult> UploadAssetImageAsync(StoryAsset asset, IFormFile upload)
|
||||
=> UploadAsync(
|
||||
$"asset:{asset.StoryAssetID}",
|
||||
asset.ProjectID,
|
||||
asset.StoryAssetID,
|
||||
asset.ImagePath,
|
||||
asset.ThumbnailPath,
|
||||
"story-assets",
|
||||
"StoryAssetImage",
|
||||
(imagePath, thumbnailPath) => assets.UpdateAssetImageAsync(asset.StoryAssetID, imagePath, thumbnailPath),
|
||||
upload);
|
||||
|
||||
public Task RemoveAssetImageAsync(StoryAsset asset)
|
||||
=> RemoveAsync(
|
||||
asset.ImagePath,
|
||||
asset.ThumbnailPath,
|
||||
"uploads/story-assets",
|
||||
(imagePath, thumbnailPath) => assets.UpdateAssetImageAsync(asset.StoryAssetID, imagePath, thumbnailPath));
|
||||
|
||||
private async Task<VisualIdentityImageResult> UploadAsync(
|
||||
string lockKey,
|
||||
int projectId,
|
||||
int entityId,
|
||||
string? oldImagePath,
|
||||
string? oldThumbnailPath,
|
||||
string folderName,
|
||||
string entityType,
|
||||
Func<string?, string?, Task> updateImage,
|
||||
IFormFile upload)
|
||||
public async Task<VisualIdentityImageResult> UploadAssetImageAsync(StoryAsset asset,IFormFile upload)
|
||||
{
|
||||
var uploadLock = EntityLocks.GetOrAdd(lockKey, _ => new SemaphoreSlim(1, 1));
|
||||
var uploadLock=EntityLocks.GetOrAdd($"asset:{asset.StoryAssetID}",_=>new SemaphoreSlim(1,1));
|
||||
await uploadLock.WaitAsync();
|
||||
try
|
||||
{
|
||||
return await UploadCoreAsync(projectId, entityId, oldImagePath, oldThumbnailPath, folderName, entityType, updateImage, upload);
|
||||
var current=await assets.GetAssetAsync(asset.StoryAssetID);
|
||||
if(current is null)return new(false,"Asset not found.");
|
||||
return await UploadCoreAsync(current.ProjectID,current.StoryAssetID,current.ImagePath,current.ThumbnailPath,"story-assets","StoryAssetImage",
|
||||
(imagePath,thumbnailPath)=>assets.UpdateAssetImageAsync(current.StoryAssetID,imagePath,thumbnailPath),upload);
|
||||
}
|
||||
finally
|
||||
finally{uploadLock.Release();}
|
||||
}
|
||||
|
||||
public async Task RemoveAssetImageAsync(StoryAsset asset)
|
||||
{
|
||||
var uploadLock=EntityLocks.GetOrAdd($"asset:{asset.StoryAssetID}",_=>new SemaphoreSlim(1,1));
|
||||
await uploadLock.WaitAsync();
|
||||
try
|
||||
{
|
||||
uploadLock.Release();
|
||||
var current=await assets.GetAssetAsync(asset.StoryAssetID);
|
||||
if(current is not null)await RemoveAsync(current.ImagePath,current.ThumbnailPath,"uploads/story-assets",
|
||||
(imagePath,thumbnailPath)=>assets.UpdateAssetImageAsync(current.StoryAssetID,imagePath,thumbnailPath));
|
||||
}
|
||||
finally{uploadLock.Release();}
|
||||
}
|
||||
|
||||
private async Task<VisualIdentityImageResult> UploadCoreAsync(
|
||||
@ -235,11 +258,14 @@ public sealed class VisualIdentityImageService(
|
||||
var version = Guid.NewGuid().ToString("N");
|
||||
var imageTemp = Path.Combine(uploadRoot, $"image-{version}.tmp");
|
||||
var thumbnailTemp = Path.Combine(uploadRoot, $"thumb-{version}.tmp");
|
||||
var imagePath = Path.Combine(uploadRoot, "image.webp");
|
||||
var thumbnailPath = Path.Combine(uploadRoot, "thumb.webp");
|
||||
var imageStoragePath = uploadStorage.GetPublicPath(folderName, entityId.ToString(), "image.webp");
|
||||
var thumbnailStoragePath = uploadStorage.GetPublicPath(folderName, entityId.ToString(), "thumb.webp");
|
||||
var imageName = $"image-{version}.webp";
|
||||
var thumbnailName = $"thumb-{version}.webp";
|
||||
var imagePath = Path.Combine(uploadRoot, imageName);
|
||||
var thumbnailPath = Path.Combine(uploadRoot, thumbnailName);
|
||||
var imageStoragePath = uploadStorage.GetPublicPath(folderName, entityId.ToString(), imageName);
|
||||
var thumbnailStoragePath = uploadStorage.GetPublicPath(folderName, entityId.ToString(), thumbnailName);
|
||||
|
||||
var persistenceHandled=false;
|
||||
try
|
||||
{
|
||||
SaveContainedWebp(bitmap, imageTemp, StandardMaxSize, 82);
|
||||
@ -248,22 +274,31 @@ public sealed class VisualIdentityImageService(
|
||||
ReplaceFile(imageTemp, imagePath);
|
||||
ReplaceFile(thumbnailTemp, thumbnailPath);
|
||||
|
||||
await updateImage(imageStoragePath, thumbnailStoragePath);
|
||||
await MarkPreviousLedgerRowsAsync(oldImagePath);
|
||||
await MarkPreviousLedgerRowsAsync(oldThumbnailPath);
|
||||
await TrackImageAsync(ownerUserId.Value, projectId, entityId, entityType, imageStoragePath, upload.FileName, new FileInfo(imagePath).Length);
|
||||
await TrackImageAsync(ownerUserId.Value, projectId, entityId, entityType, thumbnailStoragePath, "Thumbnail: " + upload.FileName, new FileInfo(thumbnailPath).Length);
|
||||
DeletePreviousPhysicalFile(oldImagePath, imageStoragePath, $"uploads/{folderName}");
|
||||
DeletePreviousPhysicalFile(oldThumbnailPath, thumbnailStoragePath, $"uploads/{folderName}");
|
||||
persistenceHandled=true;
|
||||
await ImagePersistenceTransaction.RunAsync(async()=>
|
||||
{
|
||||
await updateImage(imageStoragePath, thumbnailStoragePath);
|
||||
await MarkPreviousLedgerRowsAsync(oldImagePath);
|
||||
await MarkPreviousLedgerRowsAsync(oldThumbnailPath);
|
||||
await TrackImageAsync(ownerUserId.Value, projectId, entityId, entityType, imageStoragePath, upload.FileName, new FileInfo(imagePath).Length);
|
||||
await TrackImageAsync(ownerUserId.Value, projectId, entityId, entityType, thumbnailStoragePath, "Thumbnail: " + upload.FileName, new FileInfo(thumbnailPath).Length);
|
||||
},()=>
|
||||
{
|
||||
DeletePreviousPhysicalFile(oldImagePath, imageStoragePath, $"uploads/{folderName}");
|
||||
DeletePreviousPhysicalFile(oldThumbnailPath, thumbnailStoragePath, $"uploads/{folderName}");
|
||||
},()=>{TryDeleteFile(imagePath);TryDeleteFile(thumbnailPath);},logger);
|
||||
return new(true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
TryDeleteFile(imageTemp);
|
||||
TryDeleteFile(thumbnailTemp);
|
||||
logger.LogWarning(ex, "Visual identity image upload failed for {EntityType} {EntityID}.", entityType, entityId);
|
||||
return new(false, "Image could not be processed. Try another image.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
TryDeleteFile(imageTemp);TryDeleteFile(thumbnailTemp);
|
||||
if(!persistenceHandled){TryDeleteFile(imagePath);TryDeleteFile(thumbnailPath);}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -339,6 +374,7 @@ public sealed class VisualIdentityImageService(
|
||||
var imageStoragePath = uploadStorage.GetPublicPath("characters", character.CharacterID.ToString(), "gallery", version, "image.webp");
|
||||
var thumbnailStoragePath = uploadStorage.GetPublicPath("characters", character.CharacterID.ToString(), "gallery", version, "thumb.webp");
|
||||
|
||||
var persistenceHandled=false;
|
||||
try
|
||||
{
|
||||
SaveContainedWebp(bitmap, imageTemp, StandardMaxSize, 82);
|
||||
@ -347,31 +383,39 @@ public sealed class VisualIdentityImageService(
|
||||
ReplaceFile(imageTemp, imagePath);
|
||||
ReplaceFile(thumbnailTemp, thumbnailPath);
|
||||
|
||||
var characterImageId = await characters.CreateCharacterImageAsync(new CharacterImage
|
||||
var characterImageId=0;
|
||||
persistenceHandled=true;
|
||||
await ImagePersistenceTransaction.RunAsync(async()=>
|
||||
{
|
||||
CharacterID = character.CharacterID,
|
||||
ProjectID = character.ProjectID,
|
||||
ImagePath = imageStoragePath,
|
||||
ThumbnailPath = thumbnailStoragePath,
|
||||
Caption = caption
|
||||
});
|
||||
characterImageId = await characters.CreateCharacterImageAsync(new CharacterImage
|
||||
{
|
||||
CharacterID = character.CharacterID,
|
||||
ProjectID = character.ProjectID,
|
||||
ImagePath = imageStoragePath,
|
||||
ThumbnailPath = thumbnailStoragePath,
|
||||
Caption = caption
|
||||
});
|
||||
|
||||
if (updateLegacyImage || string.IsNullOrWhiteSpace(character.ImagePath))
|
||||
{
|
||||
await characters.UpdateCharacterImageAsync(character.CharacterID, imageStoragePath, thumbnailStoragePath);
|
||||
}
|
||||
if (updateLegacyImage || string.IsNullOrWhiteSpace(character.ImagePath))
|
||||
{
|
||||
await characters.UpdateCharacterImageAsync(character.CharacterID, imageStoragePath, thumbnailStoragePath);
|
||||
}
|
||||
|
||||
await TrackImageAsync(ownerUserId.Value, character.ProjectID, characterImageId, "CharacterImage", imageStoragePath, upload.FileName, new FileInfo(imagePath).Length);
|
||||
await TrackImageAsync(ownerUserId.Value, character.ProjectID, characterImageId, "CharacterImage", thumbnailStoragePath, "Thumbnail: " + upload.FileName, new FileInfo(thumbnailPath).Length);
|
||||
await TrackImageAsync(ownerUserId.Value, character.ProjectID, characterImageId, "CharacterImage", imageStoragePath, upload.FileName, new FileInfo(imagePath).Length);
|
||||
await TrackImageAsync(ownerUserId.Value, character.ProjectID, characterImageId, "CharacterImage", thumbnailStoragePath, "Thumbnail: " + upload.FileName, new FileInfo(thumbnailPath).Length);
|
||||
},null,()=>{TryDeleteFile(imagePath);TryDeleteFile(thumbnailPath);},logger);
|
||||
return new(true, CharacterImageID: characterImageId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
TryDeleteFile(imageTemp);
|
||||
TryDeleteFile(thumbnailTemp);
|
||||
logger.LogWarning(ex, "Character gallery image upload failed for Character {CharacterID}.", character.CharacterID);
|
||||
return new(false, "Image could not be processed. Try another image.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
TryDeleteFile(imageTemp);TryDeleteFile(thumbnailTemp);
|
||||
if(!persistenceHandled){TryDeleteFile(imagePath);TryDeleteFile(thumbnailPath);}
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user