using System.Diagnostics.CodeAnalysis; using System.Text.Json; using System.Text.Json.Serialization.Metadata; namespace Titano.Data.Repositories; /// Who a setting belongs to. public enum SettingScope { /// The installation (client app or server); no scope id. App, /// One archive; the scope id is the archive id. Archive, /// One user; the scope id is the user id. User, } /// Typed key/value settings stored as JSON (BRIEF §5 Setting). public sealed class SettingsRepository { private static readonly string UpsertSql = SqlDialect.Upsert("settings", ["scope", "scope_id", "key", "value_json", "updated_at"], 3); private readonly DbAccess _db; internal SettingsRepository(DbAccess db) => _db = db; /// The raw JSON of a setting, or null when unset. public Task GetJsonAsync(SettingScope scope, Guid? scopeId, string key, CancellationToken cancellationToken = default) => _db.ScalarAsync("SELECT value_json FROM settings WHERE scope = $1 AND scope_id = $2 AND key = $3", [ScopeName(scope), ScopeId(scope, scopeId), key], cancellationToken); /// Stores a JSON value; malformed JSON is rejected on both dialects. public async Task SetJsonAsync(SettingScope scope, Guid? scopeId, string key, string json, CancellationToken cancellationToken = default) { using (JsonDocument.Parse(json)) { } await _db.ExecuteAsync(UpsertSql, [ScopeName(scope), ScopeId(scope, scopeId), key, DbParam.Json(json), DateTimeOffset.UtcNow], cancellationToken) .ConfigureAwait(false); } /// Reads a setting with source-generated metadata (trim/AOT safe); default when unset. public async Task GetAsync(SettingScope scope, Guid? scopeId, string key, JsonTypeInfo typeInfo, CancellationToken cancellationToken = default) => await GetJsonAsync(scope, scopeId, key, cancellationToken).ConfigureAwait(false) is { } json ? JsonSerializer.Deserialize(json, typeInfo) : default; public Task SetAsync(SettingScope scope, Guid? scopeId, string key, T value, JsonTypeInfo typeInfo, CancellationToken cancellationToken = default) => SetJsonAsync(scope, scopeId, key, JsonSerializer.Serialize(value, typeInfo), cancellationToken); /// Reads a setting through reflection-based serialization; default when unset. [RequiresUnreferencedCode("Reflection-based JSON; use the JsonTypeInfo overload in trimmed builds.")] [RequiresDynamicCode("Reflection-based JSON; use the JsonTypeInfo overload in AOT builds.")] public async Task GetAsync(SettingScope scope, Guid? scopeId, string key, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) => await GetJsonAsync(scope, scopeId, key, cancellationToken).ConfigureAwait(false) is { } json ? JsonSerializer.Deserialize(json, options) : default; [RequiresUnreferencedCode("Reflection-based JSON; use the JsonTypeInfo overload in trimmed builds.")] [RequiresDynamicCode("Reflection-based JSON; use the JsonTypeInfo overload in AOT builds.")] public Task SetAsync(SettingScope scope, Guid? scopeId, string key, T value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) => SetJsonAsync(scope, scopeId, key, JsonSerializer.Serialize(value, options), cancellationToken); public async Task DeleteAsync(SettingScope scope, Guid? scopeId, string key, CancellationToken cancellationToken = default) => await _db.ExecuteAsync("DELETE FROM settings WHERE scope = $1 AND scope_id = $2 AND key = $3", [ScopeName(scope), ScopeId(scope, scopeId), key], cancellationToken).ConfigureAwait(false) > 0; /// Every setting of a scope as key → JSON. public async Task> ListAsync(SettingScope scope, Guid? scopeId, CancellationToken cancellationToken = default) { var rows = await _db.ListAsync("SELECT key, value_json FROM settings WHERE scope = $1 AND scope_id = $2 ORDER BY key", [ScopeName(scope), ScopeId(scope, scopeId)], r => KeyValuePair.Create(r.GetString(0), r.GetString(1)), cancellationToken).ConfigureAwait(false); return new Dictionary(rows, StringComparer.Ordinal); } private static string ScopeName(SettingScope scope) => scope switch { SettingScope.App => "app", SettingScope.Archive => "archive", SettingScope.User => "user", _ => throw new ArgumentOutOfRangeException(nameof(scope), scope, null), }; private static string ScopeId(SettingScope scope, Guid? scopeId) => (scope, scopeId) switch { (SettingScope.App, null) => string.Empty, (SettingScope.App, _) => throw new ArgumentException("App settings have no scope id.", nameof(scopeId)), (_, { } id) => TextValues.FormatGuid(id), _ => throw new ArgumentException($"{scope} settings need a scope id.", nameof(scopeId)), }; }