| | | 1 | | using Microsoft.Extensions.Logging; |
| | | 2 | | using System.Runtime.CompilerServices; |
| | | 3 | | using System.Text.Json; |
| | | 4 | | using System.Text.Json.Serialization.Metadata; |
| | | 5 | | |
| | | 6 | | namespace AsyncResponse.Channels.PostgreSQL; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// PostgreSQL implementation of <see cref="IRecoveryStateStore"/> and |
| | | 10 | | /// <see cref="IRecoveryStateScanner"/>. |
| | | 11 | | /// </summary> |
| | 383 | 12 | | internal sealed class PostgreSqlRecoveryStateStore( |
| | 383 | 13 | | PostgreSqlChannelSql _sql, |
| | 383 | 14 | | ILogger<PostgreSqlRecoveryStateStore> _logger) : IRecoveryStateStore, IRecoveryStateScanner |
| | | 15 | | { |
| | | 16 | | /// <inheritdoc /> |
| | | 17 | | public async Task SaveAsync(string correlationId, RecoveryState state, TimeSpan ttl, CancellationToken cancellationT |
| | | 18 | | { |
| | 430 | 19 | | ArgumentException.ThrowIfNullOrWhiteSpace(correlationId); |
| | 430 | 20 | | ArgumentNullException.ThrowIfNull(state); |
| | 430 | 21 | | if (ttl <= TimeSpan.Zero) |
| | 2 | 22 | | throw new ArgumentOutOfRangeException(nameof(ttl), "TTL must be greater than zero."); |
| | 428 | 23 | | if (!string.Equals(state.CorrelationId, correlationId, StringComparison.Ordinal)) |
| | 2 | 24 | | throw new ArgumentException("The recovery-state correlation id must match the store key.", nameof(state)); |
| | 426 | 25 | | if (state.SchemaVersion != RecoveryStateSchema.Current) |
| | 2 | 26 | | throw new ArgumentException("The recovery state must use the current schema version.", nameof(state)); |
| | | 27 | | |
| | 424 | 28 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 424 | 29 | | if (state.RegistrationId == Guid.Empty) |
| | 6 | 30 | | state.RegistrationId = Guid.NewGuid(); |
| | | 31 | | |
| | 424 | 32 | | await _sql.SaveRecoveryStateAsync(correlationId, state, ttl, cancellationToken).ConfigureAwait(false); |
| | 424 | 33 | | } |
| | | 34 | | |
| | | 35 | | /// <inheritdoc /> |
| | | 36 | | public async Task<IReadOnlyList<RecoveryState>> GetAllAsync(string correlationId, CancellationToken cancellationToke |
| | | 37 | | { |
| | 37 | 38 | | ArgumentException.ThrowIfNullOrWhiteSpace(correlationId); |
| | 37 | 39 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 40 | | |
| | 37 | 41 | | var jsonStates = await _sql.LoadRecoveryStatesAsync(correlationId, cancellationToken).ConfigureAwait(false); |
| | 37 | 42 | | return DeserializeStates(jsonStates, correlationId); |
| | 35 | 43 | | } |
| | | 44 | | |
| | | 45 | | /// <inheritdoc /> |
| | | 46 | | public Task<bool> TryDeleteAsync(string correlationId, Guid registrationId, CancellationToken cancellationToken = de |
| | | 47 | | { |
| | 429 | 48 | | ArgumentException.ThrowIfNullOrWhiteSpace(correlationId); |
| | 429 | 49 | | if (registrationId == Guid.Empty) |
| | 2 | 50 | | throw new ArgumentException("Registration id cannot be empty.", nameof(registrationId)); |
| | 427 | 51 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 427 | 52 | | return _sql.DeleteRecoveryStateAsync(correlationId, registrationId, cancellationToken); |
| | | 53 | | } |
| | | 54 | | |
| | | 55 | | /// <inheritdoc /> |
| | | 56 | | public async IAsyncEnumerable<RecoveryState> ScanAsync([EnumeratorCancellation] CancellationToken cancellationToken |
| | | 57 | | { |
| | 4 | 58 | | await foreach (var json in _sql.ScanRecoveryStateJsonAsync(cancellationToken).ConfigureAwait(false)) |
| | | 59 | | { |
| | 1 | 60 | | var ignored = 0; |
| | 1 | 61 | | var state = DeserializeState(json, correlationId: null, ref ignored); |
| | 1 | 62 | | if (state is not null) |
| | 1 | 63 | | yield return state; |
| | | 64 | | } |
| | 1 | 65 | | } |
| | | 66 | | |
| | | 67 | | private IReadOnlyList<RecoveryState> DeserializeStates(IReadOnlyList<string> jsonStates, string correlationId) |
| | | 68 | | { |
| | 37 | 69 | | if (jsonStates.Count == 0) |
| | 12 | 70 | | return []; |
| | | 71 | | |
| | 25 | 72 | | var states = new List<RecoveryState>(jsonStates.Count); |
| | 25 | 73 | | var unreadable = 0; |
| | 100 | 74 | | foreach (var json in jsonStates) |
| | | 75 | | { |
| | 25 | 76 | | var state = DeserializeState(json, correlationId, ref unreadable); |
| | 25 | 77 | | if (state is not null) |
| | 23 | 78 | | states.Add(state); |
| | | 79 | | } |
| | | 80 | | |
| | | 81 | | // Rows existed and none of them survived materialization. Returning an empty list here told |
| | | 82 | | // the dispatcher "no recovery callback was ever armed", which it answers by acknowledging |
| | | 83 | | // the response — so a corrupt or newer-schema registration silently consumed a terminal |
| | | 84 | | // response its callback never saw. Fail instead, and let redelivery reach a build that can |
| | | 85 | | // read it. A PARTIALLY readable batch deliberately does not throw: see |
| | | 86 | | // RecoveryStateUnreadableException. |
| | | 87 | | // Only rows this build could not INTERPRET count. A row rejected for belonging to another |
| | | 88 | | // correlation id is perfectly readable — it surfaced because a legacy case-insensitive |
| | | 89 | | // collation matched the wrong key, and refusing it is the ordinal re-check doing its job. |
| | | 90 | | // For the id actually asked about, that is absence, not corruption, and absence must stay |
| | | 91 | | // an empty list. |
| | 25 | 92 | | if (states.Count == 0 && unreadable > 0) |
| | 2 | 93 | | throw new RecoveryStateUnreadableException(correlationId, unreadable); |
| | | 94 | | |
| | 23 | 95 | | return states; |
| | | 96 | | } |
| | | 97 | | |
| | | 98 | | /// <summary>The registration's metadata off the library's resolver — case-sensitive matching, as before.</summary> |
| | 3 | 99 | | private static readonly JsonTypeInfo<RecoveryState> _stateTypeInfo = |
| | 3 | 100 | | AsyncResponseJson.GetTypeInfo<RecoveryState>(AsyncResponseJson.Default); |
| | | 101 | | |
| | | 102 | | private RecoveryState? DeserializeState(string json, string? correlationId, ref int unreadable) |
| | | 103 | | { |
| | | 104 | | try |
| | | 105 | | { |
| | | 106 | | // Through JsonSafety, not the raw reader: the exception logged below is the body-free |
| | | 107 | | // rebuild (size and position). The reader's own appends `Path: $.Context['<key>']` |
| | | 108 | | // built from the stored registration's context keys — tenant and auth baggage — which |
| | | 109 | | // the warning then carried into the application log. |
| | 58 | 110 | | var state = JsonSafety.SafeDeserialize(json, _stateTypeInfo); |
| | 49 | 111 | | if (state is null) |
| | | 112 | | { |
| | 4 | 113 | | unreadable++; |
| | 4 | 114 | | return null; |
| | | 115 | | } |
| | | 116 | | |
| | 45 | 117 | | if (state.RegistrationId == Guid.Empty || string.IsNullOrWhiteSpace(state.CorrelationId)) |
| | | 118 | | { |
| | 6 | 119 | | _logger.LogWarning( |
| | 6 | 120 | | "PostgreSQL recovery state for correlationId {CorrelationId} has an incomplete identity; rejecting i |
| | 6 | 121 | | correlationId ?? state.CorrelationId); |
| | 6 | 122 | | unreadable++; |
| | 6 | 123 | | return null; |
| | | 124 | | } |
| | | 125 | | |
| | 39 | 126 | | if (!RecoveryStateSchema.IsReadable(state.SchemaVersion)) |
| | | 127 | | { |
| | 3 | 128 | | _logger.LogWarning( |
| | 3 | 129 | | "PostgreSQL recovery state for correlationId {CorrelationId} has unsupported schema version {SchemaV |
| | 3 | 130 | | correlationId ?? state.CorrelationId, |
| | 3 | 131 | | state.SchemaVersion, |
| | 3 | 132 | | RecoveryStateSchema.Current); |
| | 3 | 133 | | unreadable++; |
| | 3 | 134 | | return null; |
| | | 135 | | } |
| | | 136 | | |
| | 36 | 137 | | if (!string.IsNullOrWhiteSpace(correlationId) |
| | 36 | 138 | | && !string.Equals(state.CorrelationId, correlationId, StringComparison.Ordinal)) |
| | | 139 | | { |
| | 6 | 140 | | _logger.LogWarning( |
| | 6 | 141 | | "PostgreSQL recovery state has correlationId {StoredCorrelationId}, expected {CorrelationId}; reject |
| | 6 | 142 | | state.CorrelationId, correlationId); |
| | 6 | 143 | | return null; |
| | | 144 | | } |
| | | 145 | | |
| | 30 | 146 | | return state; |
| | | 147 | | } |
| | 9 | 148 | | catch (Exception ex) when (ex is JsonException or InvalidDataException) |
| | | 149 | | { |
| | 9 | 150 | | _logger.LogWarning(ex, "Unreadable PostgreSQL recovery state for correlationId {CorrelationId}; skipping.", |
| | 9 | 151 | | unreadable++; |
| | 9 | 152 | | return null; |
| | | 153 | | } |
| | 58 | 154 | | } |
| | | 155 | | } |