39 lines
1.5 KiB
C#
39 lines
1.5 KiB
C#
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;
|
|
}
|
|
}
|
|
}
|