using System.IO;
|
using System.Text.Json;
|
using System.Text.Json.Serialization;
|
using Moli.Desktop.Diagnostics;
|
using Moli.Desktop.Host;
|
|
namespace Moli.Desktop.Configuration;
|
|
public sealed class JsonConfigurationService : IConfigurationService
|
{
|
private readonly DesktopPaths _paths;
|
private readonly IDiagnosticsService _diagnostics;
|
private readonly JsonSerializerOptions _jsonOptions = new()
|
{
|
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
PropertyNameCaseInsensitive = true,
|
WriteIndented = true,
|
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
};
|
|
public JsonConfigurationService(DesktopPaths paths, IDiagnosticsService diagnostics)
|
{
|
_paths = paths;
|
_diagnostics = diagnostics;
|
}
|
|
public Task<AppSettingsDocument> LoadAppSettingsAsync(CancellationToken cancellationToken = default)
|
=> LoadDocumentAsync("appsettings.json", () => new AppSettingsDocument(), cancellationToken);
|
|
public Task SaveAppSettingsAsync(AppSettingsDocument document, CancellationToken cancellationToken = default)
|
=> SaveDocumentAsync("appsettings.json", document, cancellationToken);
|
|
public Task<PluginRegistryDocument> LoadPluginRegistryAsync(CancellationToken cancellationToken = default)
|
=> LoadDocumentAsync("plugins.json", () => new PluginRegistryDocument(), cancellationToken);
|
|
public Task SavePluginRegistryAsync(PluginRegistryDocument document, CancellationToken cancellationToken = default)
|
=> SaveDocumentAsync("plugins.json", document, cancellationToken);
|
|
public Task<LayoutDocument> LoadLayoutAsync(CancellationToken cancellationToken = default)
|
=> LoadDocumentAsync("layout.json", () => new LayoutDocument(), cancellationToken);
|
|
public Task SaveLayoutAsync(LayoutDocument document, CancellationToken cancellationToken = default)
|
=> SaveDocumentAsync("layout.json", document, cancellationToken);
|
|
public async Task<ConfigurationSnapshot> LoadAllAsync(CancellationToken cancellationToken = default)
|
{
|
return new ConfigurationSnapshot
|
{
|
AppSettings = await LoadAppSettingsAsync(cancellationToken).ConfigureAwait(false),
|
Plugins = await LoadPluginRegistryAsync(cancellationToken).ConfigureAwait(false),
|
Layout = await LoadLayoutAsync(cancellationToken).ConfigureAwait(false)
|
};
|
}
|
|
public async Task SaveAllAsync(ConfigurationSnapshot snapshot, CancellationToken cancellationToken = default)
|
{
|
await SaveAppSettingsAsync(snapshot.AppSettings, cancellationToken).ConfigureAwait(false);
|
await SavePluginRegistryAsync(snapshot.Plugins, cancellationToken).ConfigureAwait(false);
|
await SaveLayoutAsync(snapshot.Layout, cancellationToken).ConfigureAwait(false);
|
}
|
|
private async Task<T> LoadDocumentAsync<T>(string fileName, Func<T> createDefault, CancellationToken cancellationToken)
|
{
|
Directory.CreateDirectory(_paths.ConfigDirectory);
|
var path = Path.Combine(_paths.ConfigDirectory, fileName);
|
|
if (!File.Exists(path))
|
{
|
var created = createDefault();
|
await SaveDocumentAsync(fileName, created, cancellationToken).ConfigureAwait(false);
|
return created;
|
}
|
|
try
|
{
|
await using var stream = File.OpenRead(path);
|
var document = await JsonSerializer.DeserializeAsync<T>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
|
if (document is null || GetSchemaVersion(document) <= 0)
|
{
|
throw new JsonException("Configuration document is empty or missing schemaVersion.");
|
}
|
|
_diagnostics.Record(DiagnosticSeverity.Info, DiagnosticCodes.ConfigurationLoaded, $"Loaded {fileName}.");
|
return document;
|
}
|
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
|
{
|
BackupInvalidFile(path);
|
var recovered = createDefault();
|
await SaveDocumentAsync(fileName, recovered, cancellationToken).ConfigureAwait(false);
|
_diagnostics.Record(
|
DiagnosticSeverity.Warning,
|
DiagnosticCodes.ConfigurationRecovered,
|
$"Recovered {fileName} from invalid configuration.",
|
new Dictionary<string, string> { ["exception"] = ex.GetType().Name });
|
return recovered;
|
}
|
}
|
|
private async Task SaveDocumentAsync<T>(string fileName, T document, CancellationToken cancellationToken)
|
{
|
Directory.CreateDirectory(_paths.ConfigDirectory);
|
var path = Path.Combine(_paths.ConfigDirectory, fileName);
|
var tempPath = path + ".tmp";
|
var backupPath = path + ".bak";
|
|
try
|
{
|
await using (var stream = File.Create(tempPath))
|
{
|
await JsonSerializer.SerializeAsync(stream, document, _jsonOptions, cancellationToken).ConfigureAwait(false);
|
}
|
|
if (File.Exists(path))
|
{
|
File.Copy(path, backupPath, overwrite: true);
|
}
|
|
File.Move(tempPath, path, overwrite: true);
|
}
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
{
|
_diagnostics.Record(
|
DiagnosticSeverity.Error,
|
DiagnosticCodes.ConfigurationSaveFailed,
|
$"Failed to save {fileName}.",
|
new Dictionary<string, string> { ["exception"] = ex.GetType().Name });
|
throw;
|
}
|
}
|
|
private static int GetSchemaVersion<T>(T document)
|
{
|
var property = typeof(T).GetProperty("SchemaVersion");
|
return property?.GetValue(document) is int version ? version : 0;
|
}
|
|
private static void BackupInvalidFile(string path)
|
{
|
if (!File.Exists(path))
|
{
|
return;
|
}
|
|
var timestamp = DateTimeOffset.Now.ToString("yyyyMMddHHmmss");
|
var invalidPath = Path.Combine(
|
Path.GetDirectoryName(path)!,
|
$"{Path.GetFileNameWithoutExtension(path)}.invalid.{timestamp}{Path.GetExtension(path)}");
|
File.Move(path, invalidPath, overwrite: true);
|
}
|
}
|