|
| 1 | +using System.Runtime.InteropServices; |
| 2 | +using System.Text.Json; |
| 3 | +using System.Text.Json.Serialization; |
| 4 | +using Microsoft.Data.Sqlite; |
| 5 | + |
| 6 | +namespace EchoHub.Server.Services; |
| 7 | + |
| 8 | +/// <summary> |
| 9 | +/// Persists and exposes the EchoHubSpace directory claim — the opaque token issued on first |
| 10 | +/// registration and the row's stable <c>ServerId</c>. Also surfaces ephemeral registration |
| 11 | +/// status (success/failure code, conflicting hosts) for operator-facing endpoints. |
| 12 | +/// |
| 13 | +/// Persistence uses atomic write (tmp + rename). Treat the file contents as a secret. |
| 14 | +/// </summary> |
| 15 | +public sealed class DirectoryClaimStore |
| 16 | +{ |
| 17 | + private static readonly JsonSerializerOptions JsonOptions = new() |
| 18 | + { |
| 19 | + WriteIndented = true, |
| 20 | + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, |
| 21 | + }; |
| 22 | + |
| 23 | + private readonly string _filePath; |
| 24 | + private readonly ILogger<DirectoryClaimStore> _logger; |
| 25 | + private readonly SemaphoreSlim _writeLock = new(1, 1); |
| 26 | + |
| 27 | + private PersistedClaim _persisted = new(null, null); |
| 28 | + private RegistrationStatus _status = new(false, null, null, null, null); |
| 29 | + |
| 30 | + public DirectoryClaimStore(IConfiguration configuration, ILogger<DirectoryClaimStore> logger) |
| 31 | + { |
| 32 | + _logger = logger; |
| 33 | + _filePath = ResolveFilePath(configuration); |
| 34 | + Load(); |
| 35 | + } |
| 36 | + |
| 37 | + public string FilePath => _filePath; |
| 38 | + |
| 39 | + public string? ClaimToken => Volatile.Read(ref _persisted).ClaimToken; |
| 40 | + public Guid? ServerId => Volatile.Read(ref _persisted).ServerId; |
| 41 | + |
| 42 | + public RegistrationStatus Status => Volatile.Read(ref _status); |
| 43 | + |
| 44 | + /// <summary> |
| 45 | + /// Persist a freshly-issued claim token alongside the server's stable ServerId. |
| 46 | + /// Called exactly once per row's lifetime — on first claim. Atomic on-disk swap. |
| 47 | + /// </summary> |
| 48 | + public async Task SaveClaimAsync(string claimToken, Guid serverId, CancellationToken ct = default) |
| 49 | + { |
| 50 | + await _writeLock.WaitAsync(ct); |
| 51 | + try |
| 52 | + { |
| 53 | + var next = new PersistedClaim(claimToken, serverId); |
| 54 | + await WriteAtomicAsync(next, ct); |
| 55 | + Volatile.Write(ref _persisted, next); |
| 56 | + _logger.LogInformation("Persisted directory claim token for ServerId {ServerId} at {Path}", serverId, _filePath); |
| 57 | + } |
| 58 | + finally |
| 59 | + { |
| 60 | + _writeLock.Release(); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + /// <summary> |
| 65 | + /// Update only the ServerId — used when re-registering with an existing token (Success path, |
| 66 | + /// hub returns ServerId again but no fresh token). No-op if the value is unchanged. |
| 67 | + /// </summary> |
| 68 | + public async Task UpdateServerIdAsync(Guid serverId, CancellationToken ct = default) |
| 69 | + { |
| 70 | + var current = Volatile.Read(ref _persisted); |
| 71 | + if (current.ServerId == serverId) |
| 72 | + return; |
| 73 | + |
| 74 | + await _writeLock.WaitAsync(ct); |
| 75 | + try |
| 76 | + { |
| 77 | + var next = current with { ServerId = serverId }; |
| 78 | + await WriteAtomicAsync(next, ct); |
| 79 | + Volatile.Write(ref _persisted, next); |
| 80 | + } |
| 81 | + finally |
| 82 | + { |
| 83 | + _writeLock.Release(); |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + public void SetSuccess(Guid serverId) |
| 88 | + { |
| 89 | + Volatile.Write(ref _status, new RegistrationStatus( |
| 90 | + IsRegistered: true, |
| 91 | + ServerId: serverId, |
| 92 | + LastRegisteredAt: DateTimeOffset.UtcNow, |
| 93 | + LastError: null, |
| 94 | + ConflictingHosts: null)); |
| 95 | + } |
| 96 | + |
| 97 | + public void SetFailure(string errorCode, string[]? conflictingHosts) |
| 98 | + { |
| 99 | + var current = Volatile.Read(ref _status); |
| 100 | + Volatile.Write(ref _status, current with |
| 101 | + { |
| 102 | + IsRegistered = false, |
| 103 | + LastError = errorCode, |
| 104 | + ConflictingHosts = conflictingHosts, |
| 105 | + }); |
| 106 | + } |
| 107 | + |
| 108 | + private void Load() |
| 109 | + { |
| 110 | + if (!File.Exists(_filePath)) |
| 111 | + return; |
| 112 | + |
| 113 | + try |
| 114 | + { |
| 115 | + using var stream = File.OpenRead(_filePath); |
| 116 | + var loaded = JsonSerializer.Deserialize<PersistedClaim>(stream, JsonOptions); |
| 117 | + if (loaded is not null) |
| 118 | + { |
| 119 | + _persisted = loaded; |
| 120 | + _logger.LogInformation("Loaded directory claim from {Path} (ServerId {ServerId})", _filePath, loaded.ServerId); |
| 121 | + } |
| 122 | + } |
| 123 | + catch (Exception ex) |
| 124 | + { |
| 125 | + // Don't crash startup over a corrupt state file — log and proceed as if no claim exists. |
| 126 | + // Operator will see HostAlreadyClaimed on next register and can intervene. |
| 127 | + _logger.LogError(ex, "Failed to read directory claim file at {Path} — treating as unclaimed", _filePath); |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + private async Task WriteAtomicAsync(PersistedClaim claim, CancellationToken ct) |
| 132 | + { |
| 133 | + var dir = Path.GetDirectoryName(_filePath); |
| 134 | + if (!string.IsNullOrEmpty(dir)) |
| 135 | + Directory.CreateDirectory(dir); |
| 136 | + |
| 137 | + var tmpPath = _filePath + ".tmp"; |
| 138 | + |
| 139 | + await using (var stream = new FileStream( |
| 140 | + tmpPath, |
| 141 | + FileMode.Create, |
| 142 | + FileAccess.Write, |
| 143 | + FileShare.None, |
| 144 | + bufferSize: 4096, |
| 145 | + useAsync: true)) |
| 146 | + { |
| 147 | + await JsonSerializer.SerializeAsync(stream, claim, JsonOptions, ct); |
| 148 | + await stream.FlushAsync(ct); |
| 149 | + } |
| 150 | + |
| 151 | + // 0600 on Unix — the file holds a secret. No-op on Windows. |
| 152 | + if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) |
| 153 | + { |
| 154 | + try |
| 155 | + { |
| 156 | + File.SetUnixFileMode(tmpPath, UnixFileMode.UserRead | UnixFileMode.UserWrite); |
| 157 | + } |
| 158 | + catch (Exception ex) |
| 159 | + { |
| 160 | + _logger.LogWarning(ex, "Failed to set restrictive permissions on {Path}", tmpPath); |
| 161 | + } |
| 162 | + } |
| 163 | + |
| 164 | + File.Move(tmpPath, _filePath, overwrite: true); |
| 165 | + } |
| 166 | + |
| 167 | + private static string ResolveFilePath(IConfiguration configuration) |
| 168 | + { |
| 169 | + var configured = configuration["Server:DirectoryClaimPath"]; |
| 170 | + if (!string.IsNullOrWhiteSpace(configured)) |
| 171 | + return configured; |
| 172 | + |
| 173 | + // Co-locate with the SQLite database so a single data-directory backup captures both. |
| 174 | + var connectionString = configuration.GetConnectionString("DefaultConnection"); |
| 175 | + if (!string.IsNullOrWhiteSpace(connectionString)) |
| 176 | + { |
| 177 | + try |
| 178 | + { |
| 179 | + var builder = new SqliteConnectionStringBuilder(connectionString); |
| 180 | + if (!string.IsNullOrWhiteSpace(builder.DataSource)) |
| 181 | + { |
| 182 | + var dir = Path.GetDirectoryName(Path.GetFullPath(builder.DataSource)); |
| 183 | + if (!string.IsNullOrWhiteSpace(dir)) |
| 184 | + return Path.Combine(dir, "directory-claim.json"); |
| 185 | + } |
| 186 | + } |
| 187 | + catch |
| 188 | + { |
| 189 | + // Fall through to default |
| 190 | + } |
| 191 | + } |
| 192 | + |
| 193 | + return Path.Combine(AppContext.BaseDirectory, "directory-claim.json"); |
| 194 | + } |
| 195 | + |
| 196 | + private sealed record PersistedClaim(string? ClaimToken, Guid? ServerId); |
| 197 | +} |
| 198 | + |
| 199 | +public sealed record RegistrationStatus( |
| 200 | + bool IsRegistered, |
| 201 | + Guid? ServerId, |
| 202 | + DateTimeOffset? LastRegisteredAt, |
| 203 | + string? LastError, |
| 204 | + string[]? ConflictingHosts); |
0 commit comments