PlotDirector/PlotLine/Services/ProjectRestoreService.cs

159 lines
7.2 KiB
C#

using System.Text.Json;
using PlotLine.Data;
using PlotLine.Models;
namespace PlotLine.Services;
public interface IProjectRestoreService
{
Task<ProjectRestoreResult> RestoreAsync(int projectId, int projectRestorePointId);
}
public sealed class ProjectRestoreService(
IProjectRestorePointRepository restorePointRepository,
IProjectRestorePointService restorePointService,
ILogger<ProjectRestoreService> logger,
IProjectBackupFiles files) : IProjectRestoreService
{
private static readonly JsonSerializerOptions ReadOptions = new()
{
PropertyNameCaseInsensitive = true,
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true
};
private static readonly JsonSerializerOptions RestoreSqlOptions = new()
{
WriteIndented = false
};
public async Task<ProjectRestoreResult> RestoreAsync(int projectId, int projectRestorePointId)
{
var restorePoint = await restorePointRepository.GetAsync(projectRestorePointId, projectId);
if (restorePoint?.JsonData is null)
{
return Failure("Restore point could not be found.");
}
ProjectBackupExport? backup;
try
{
backup = JsonSerializer.Deserialize<ProjectBackupExport>(restorePoint.JsonData, ReadOptions);
}
catch (JsonException ex)
{
logger.LogWarning(ex, "Restore point {ProjectRestorePointID} contains invalid JSON.", projectRestorePointId);
return Failure("Restore point JSON is invalid. No project data was changed.");
}
var validationMessage=ProjectBackupCollectionPresence.ValidateRequiredShape(restorePoint.JsonData);
if(validationMessage is null)
{
var missingFields=ProjectBackupStoredFieldContract.Missing(restorePoint.JsonData);
if(missingFields.Count>0)
{
logger.LogWarning("Restore point {RestorePointID} omits stored fields {Fields}; refusing inferred defaults.",projectRestorePointId,string.Join(", ",missingFields));
validationMessage="This older restore point omits stored project fields. Restore was aborted rather than guessing their values. No project data was changed.";
}
}
validationMessage ??= ValidateBackup(projectId,backup);
if (validationMessage is not null)
{
return Failure(validationMessage);
}
ProjectRestorePoint? safetyBackup;
try { safetyBackup=await restorePointService.CreatePreRestoreAsync(projectId,restorePoint.RestorePointName); }
catch(Exception ex)
{
logger.LogError(ex,"Safety backup failed for project {ProjectID}; restore aborted.",projectId);
return Failure("A complete safety backup could not be created. Check that referenced uploaded files are available. No project data was changed.");
}
if (safetyBackup is null)
{
logger.LogError("PreRestore backup creation failed for project {ProjectID}. Restore was aborted.", projectId);
return Failure("A safety backup could not be created. Restore was aborted and no project data was changed.");
}
try
{
var completeSafety=await restorePointRepository.GetAsync(safetyBackup.ProjectRestorePointID,projectId);
if(completeSafety?.JsonData is null)throw new InvalidDataException("The complete safety backup could not be verified.");
var missing=ProjectBackupCollectionPresence.MissingPersistentCollections(restorePoint.JsonData,completeSafety.JsonData,projectId);
if(missing.Count>0)
{
logger.LogWarning("Restore point {RestorePointID} omits existing persistent collections {Collections}; restore aborted.",projectRestorePointId,string.Join(", ",missing));
return new ProjectRestoreResult{Succeeded=false,SafetyBackup=safetyBackup,
Message="This older restore point omits existing project information. Restore was aborted to protect it. Your safety backup has been kept."};
}
using var fileStage=await files.StageAsync(backup!,importingCopy:false);
var restoreJson = ProjectBackupCollectionPresence.PreserveOmissions(restorePoint.JsonData,JsonSerializer.Serialize(backup, RestoreSqlOptions));
await restorePointRepository.RestoreAsync(projectId, projectRestorePointId, safetyBackup.ProjectRestorePointID, restoreJson);
fileStage.Commit();
logger.LogInformation("Project {ProjectID} restored from restore point {ProjectRestorePointID}. Safety backup {SafetyRestorePointID} was created first.",
projectId,
projectRestorePointId,
safetyBackup.ProjectRestorePointID);
return new ProjectRestoreResult
{
Succeeded = true,
Message = "Project restored. A safety backup of the previous state was created first.",
SafetyBackup = safetyBackup
};
}
catch (Exception ex)
{
logger.LogError(ex, "Project restore failed for project {ProjectID} from restore point {ProjectRestorePointID}. Safety backup {SafetyRestorePointID} was retained.",
projectId,
projectRestorePointId,
safetyBackup.ProjectRestorePointID);
return new ProjectRestoreResult
{
Succeeded = false,
// These application-defined preflight errors contain fixed, actionable messages.
// Unexpected SQL errors still use the generic response below.
Message = ex is Microsoft.Data.SqlClient.SqlException { Number: >= 51006 and <= 51024 } refusal
? refusal.Message + " The safety backup was retained."
: "Restore failed. The safety backup was created, and the project data was left unchanged.",
SafetyBackup = safetyBackup
};
}
}
private static string? ValidateBackup(int projectId, ProjectBackupExport? backup)
{
if (backup is null)
{
return "Restore point JSON is invalid. No project data was changed.";
}
if (!string.Equals(backup.Format, "PlotDirector.ProjectBackup", StringComparison.Ordinal))
{
return "Restore point format is not recognised. No project data was changed.";
}
if (backup.FormatVersion is not ("1.0" or "1.1" or "1.2" or "1.3"))
{
return "Restore point format version is not supported. No project data was changed.";
}
if (backup.Project?.ProjectID != projectId)
{
return "This restore point does not belong to the selected project. No project data was changed.";
}
var graphError = ProjectBackupMapValidation.Validate(backup) ?? ProjectBackupGraphValidation.Validate(backup) ?? ProjectBackupFiles.Validate(backup);
if (graphError is not null) return graphError + " No project data was changed.";
return null;
}
private static ProjectRestoreResult Failure(string message) => new()
{
Succeeded = false,
Message = message
};
}