| | | 1 | | using Npgsql; |
| | | 2 | | using NpgsqlTypes; |
| | | 3 | | using System.Text; |
| | | 4 | | |
| | | 5 | | namespace AsyncResponse.Channels.PostgreSQL; |
| | | 6 | | |
| | | 7 | | internal readonly record struct PostgreSqlChannelMessage( |
| | | 8 | | Guid Id, |
| | | 9 | | string CorrelationId, |
| | | 10 | | string EnvelopeJson, |
| | | 11 | | DateTimeOffset CreatedAtUtc, |
| | | 12 | | DateTimeOffset? AckedAtUtc = null); |
| | | 13 | | |
| | | 14 | | /// <summary>SQL helper for the PostgreSQL channel tables and notification channel.</summary> |
| | | 15 | | internal sealed class PostgreSqlChannelSql |
| | | 16 | | { |
| | | 17 | | // PostgreSQL rejects a NOTIFY payload of 8000 bytes or more; stay well under it. A correlation |
| | | 18 | | // id longer than this is sent as an empty payload, which the listener treats as "scan all". |
| | | 19 | | private const int MaxNotifyPayloadBytes = 7000; |
| | | 20 | | |
| | | 21 | | private readonly NpgsqlDataSource _dataSource; |
| | | 22 | | private readonly PostgreSqlAsyncResponseChannelOptions _options; |
| | 3 | 23 | | private readonly SemaphoreSlim _ensureGate = new(1, 1); |
| | | 24 | | private bool _created; |
| | | 25 | | private readonly long _schemaLockKey; |
| | | 26 | | private long _lastRecoveryPruneTicks; |
| | | 27 | | private long _lastMessagePruneTicks; |
| | | 28 | | private long _lastSubscriberPruneTicks; |
| | | 29 | | |
| | 3 | 30 | | public PostgreSqlChannelSql(NpgsqlDataSource dataSource, Microsoft.Extensions.Options.IOptions<PostgreSqlAsyncRespon |
| | | 31 | | { |
| | 3 | 32 | | _dataSource = dataSource; |
| | 3 | 33 | | _options = options.Value; |
| | 3 | 34 | | _options.Validate(); |
| | | 35 | | |
| | 3 | 36 | | Schema = Quote(_options.SchemaName); |
| | 3 | 37 | | RecoveryTable = $"{Schema}.{Quote(_options.RecoveryStateTable)}"; |
| | 3 | 38 | | MessageTable = $"{Schema}.{Quote(_options.MessageTable)}"; |
| | 3 | 39 | | SubscriberTable = $"{Schema}.{Quote(_options.SubscriberTable)}"; |
| | 3 | 40 | | _schemaLockKey = SchemaAdvisoryLockKey(_options.SchemaName); |
| | 3 | 41 | | } |
| | | 42 | | |
| | | 43 | | public string Schema { get; } |
| | | 44 | | public string RecoveryTable { get; } |
| | | 45 | | public string MessageTable { get; } |
| | | 46 | | public string SubscriberTable { get; } |
| | 1 | 47 | | public string NotificationChannel => _options.NotificationChannel; |
| | | 48 | | |
| | | 49 | | public async Task EnsureCreatedAsync(CancellationToken cancellationToken = default) |
| | | 50 | | { |
| | 3 | 51 | | if (_created || !_options.AutoCreateSchema) |
| | 3 | 52 | | return; |
| | | 53 | | |
| | 3 | 54 | | await _ensureGate.WaitAsync(cancellationToken).ConfigureAwait(false); |
| | | 55 | | try |
| | | 56 | | { |
| | 3 | 57 | | if (_created) |
| | 1 | 58 | | return; |
| | | 59 | | |
| | 3 | 60 | | await using var connection = await _dataSource.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 61 | | await using var transaction = await connection.BeginTransactionAsync(cancellationToken).ConfigureAwait(false |
| | | 62 | | |
| | | 63 | | // Serialize schema creation across processes. CREATE ... IF NOT EXISTS is not atomic against a |
| | | 64 | | // concurrent create of the same object: two instances starting together both pass the existence |
| | | 65 | | // check and collide on the system catalog ("duplicate key ... pg_type_typname_nsp_index"). A |
| | | 66 | | // transaction-scoped advisory lock (keyed by schema, shared with the transport store) lets one |
| | | 67 | | // instance build the schema while the rest wait and then find it already present. |
| | 1 | 68 | | await using (var lockCommand = connection.CreateCommand()) |
| | | 69 | | { |
| | 1 | 70 | | lockCommand.Transaction = transaction; |
| | 1 | 71 | | lockCommand.CommandText = "SELECT pg_advisory_xact_lock(@lock_key);"; |
| | 1 | 72 | | lockCommand.Parameters.AddWithValue("lock_key", _schemaLockKey); |
| | 1 | 73 | | await lockCommand.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); |
| | | 74 | | } |
| | | 75 | | |
| | 1 | 76 | | await using var command = connection.CreateCommand(); |
| | 1 | 77 | | command.Transaction = transaction; |
| | 1 | 78 | | command.CommandText = |
| | 1 | 79 | | $""" |
| | 1 | 80 | | CREATE SCHEMA IF NOT EXISTS {Schema}; |
| | 1 | 81 | | |
| | 1 | 82 | | CREATE TABLE IF NOT EXISTS {RecoveryTable} ( |
| | 1 | 83 | | correlation_id text NOT NULL, |
| | 1 | 84 | | registration_id uuid NOT NULL, |
| | 1 | 85 | | state_json jsonb NOT NULL, |
| | 1 | 86 | | expires_at timestamptz NOT NULL, |
| | 1 | 87 | | registered_at timestamptz NOT NULL DEFAULT now(), |
| | 1 | 88 | | PRIMARY KEY (correlation_id, registration_id) |
| | 1 | 89 | | ); |
| | 1 | 90 | | CREATE INDEX IF NOT EXISTS {Quote(IndexName(_options.RecoveryStateTable, "expires"))} |
| | 1 | 91 | | ON {RecoveryTable} (expires_at); |
| | 1 | 92 | | |
| | 1 | 93 | | CREATE TABLE IF NOT EXISTS {MessageTable} ( |
| | 1 | 94 | | id uuid PRIMARY KEY, |
| | 1 | 95 | | correlation_id text NOT NULL, |
| | 1 | 96 | | envelope_json jsonb NOT NULL, |
| | 1 | 97 | | created_at timestamptz NOT NULL DEFAULT now(), |
| | 1 | 98 | | expires_at timestamptz NOT NULL, |
| | 1 | 99 | | acked_at timestamptz NULL, |
| | 1 | 100 | | recovery_claimed boolean NOT NULL DEFAULT false |
| | 1 | 101 | | ); |
| | 1 | 102 | | ALTER TABLE {MessageTable} ADD COLUMN IF NOT EXISTS recovery_claimed boolean NOT NULL DEFAULT false; |
| | 1 | 103 | | CREATE INDEX IF NOT EXISTS {Quote(IndexName(_options.MessageTable, "correlation_created"))} |
| | 1 | 104 | | ON {MessageTable} (correlation_id, created_at); |
| | 1 | 105 | | CREATE INDEX IF NOT EXISTS {Quote(IndexName(_options.MessageTable, "expires"))} |
| | 1 | 106 | | ON {MessageTable} (expires_at); |
| | 1 | 107 | | |
| | 1 | 108 | | CREATE TABLE IF NOT EXISTS {SubscriberTable} ( |
| | 1 | 109 | | correlation_id text NOT NULL, |
| | 1 | 110 | | registration_id uuid NOT NULL, |
| | 1 | 111 | | instance_id text NOT NULL, |
| | 1 | 112 | | expires_at timestamptz NOT NULL, |
| | 1 | 113 | | PRIMARY KEY (correlation_id, registration_id) |
| | 1 | 114 | | ); |
| | 1 | 115 | | CREATE INDEX IF NOT EXISTS {Quote(IndexName(_options.SubscriberTable, "expires"))} |
| | 1 | 116 | | ON {SubscriberTable} (expires_at); |
| | 1 | 117 | | """; |
| | 1 | 118 | | await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 119 | | await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 120 | | _created = true; |
| | 1 | 121 | | } |
| | | 122 | | finally |
| | | 123 | | { |
| | 3 | 124 | | _ensureGate.Release(); |
| | | 125 | | } |
| | 3 | 126 | | } |
| | | 127 | | |
| | | 128 | | public async Task SaveRecoveryStateAsync(string correlationId, RecoveryState state, TimeSpan ttl, CancellationToken |
| | | 129 | | { |
| | 1 | 130 | | await EnsureCreatedAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 131 | | await using var connection = await _dataSource.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 132 | | await using var command = connection.CreateCommand(); |
| | 1 | 133 | | command.CommandText = |
| | 1 | 134 | | $""" |
| | 1 | 135 | | INSERT INTO {RecoveryTable} (correlation_id, registration_id, state_json, expires_at, registered_at) |
| | 1 | 136 | | VALUES (@correlation_id, @registration_id, @state_json, now() + @ttl, now()) |
| | 1 | 137 | | ON CONFLICT (correlation_id, registration_id) |
| | 1 | 138 | | DO UPDATE SET state_json = EXCLUDED.state_json, |
| | 1 | 139 | | expires_at = EXCLUDED.expires_at, |
| | 1 | 140 | | registered_at = EXCLUDED.registered_at; |
| | 1 | 141 | | """; |
| | 1 | 142 | | command.Parameters.AddWithValue("correlation_id", correlationId); |
| | 1 | 143 | | command.Parameters.AddWithValue("registration_id", state.RegistrationId); |
| | 1 | 144 | | command.Parameters.Add("state_json", NpgsqlDbType.Jsonb).Value = AsyncResponseJson.Serialize(state); |
| | 1 | 145 | | command.Parameters.AddWithValue("ttl", ttl); |
| | 1 | 146 | | await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 147 | | } |
| | | 148 | | |
| | | 149 | | public async Task<IReadOnlyList<string>> LoadRecoveryStatesAsync(string correlationId, CancellationToken cancellatio |
| | | 150 | | { |
| | 1 | 151 | | await EnsureCreatedAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 152 | | if (ShouldPrune(ref _lastRecoveryPruneTicks)) |
| | 1 | 153 | | await PruneExpiredRecoveryAsync(correlationId, cancellationToken).ConfigureAwait(false); |
| | | 154 | | |
| | 1 | 155 | | await using var connection = await _dataSource.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 156 | | await using var command = connection.CreateCommand(); |
| | 1 | 157 | | command.CommandText = |
| | 1 | 158 | | $""" |
| | 1 | 159 | | SELECT state_json::text |
| | 1 | 160 | | FROM {RecoveryTable} |
| | 1 | 161 | | WHERE correlation_id = @correlation_id AND expires_at > now() |
| | 1 | 162 | | ORDER BY registered_at; |
| | 1 | 163 | | """; |
| | 1 | 164 | | command.Parameters.AddWithValue("correlation_id", correlationId); |
| | | 165 | | |
| | 1 | 166 | | var states = new List<string>(); |
| | 1 | 167 | | await using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 168 | | while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) |
| | 1 | 169 | | states.Add(reader.GetString(0)); |
| | 1 | 170 | | return states; |
| | 1 | 171 | | } |
| | | 172 | | |
| | | 173 | | public async Task<bool> DeleteRecoveryStateAsync(string correlationId, Guid registrationId, CancellationToken cancel |
| | | 174 | | { |
| | 1 | 175 | | await EnsureCreatedAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 176 | | await using var connection = await _dataSource.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 177 | | await using var command = connection.CreateCommand(); |
| | 1 | 178 | | command.CommandText = $"DELETE FROM {RecoveryTable} WHERE correlation_id = @correlation_id AND registration_id = |
| | 1 | 179 | | command.Parameters.AddWithValue("correlation_id", correlationId); |
| | 1 | 180 | | command.Parameters.AddWithValue("registration_id", registrationId); |
| | 1 | 181 | | return await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false) > 0; |
| | 1 | 182 | | } |
| | | 183 | | |
| | | 184 | | public async IAsyncEnumerable<string> ScanRecoveryStateJsonAsync([System.Runtime.CompilerServices.EnumeratorCancella |
| | | 185 | | { |
| | 1 | 186 | | await EnsureCreatedAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 187 | | await PruneExpiredRecoveryAsync(null, cancellationToken).ConfigureAwait(false); |
| | | 188 | | |
| | 1 | 189 | | await using var connection = await _dataSource.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 190 | | await using var command = connection.CreateCommand(); |
| | 1 | 191 | | command.CommandText = |
| | 1 | 192 | | $""" |
| | 1 | 193 | | SELECT state_json::text |
| | 1 | 194 | | FROM {RecoveryTable} |
| | 1 | 195 | | WHERE expires_at > now() |
| | 1 | 196 | | ORDER BY registered_at; |
| | 1 | 197 | | """; |
| | 1 | 198 | | await using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 199 | | while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) |
| | 1 | 200 | | yield return reader.GetString(0); |
| | 1 | 201 | | } |
| | | 202 | | |
| | | 203 | | /// <summary> |
| | | 204 | | /// Inserts a response envelope row and notifies listeners. The caller supplies the message id so |
| | | 205 | | /// the insert is idempotent under retry (<c>ON CONFLICT DO NOTHING</c>); the NOTIFY still fires so |
| | | 206 | | /// a retried publish never strands an active waiter. Returns the row's server-stamped |
| | | 207 | | /// <c>created_at</c> (the original row's on a duplicate) so the same-process fast path compares |
| | | 208 | | /// against subscription watermarks on the server clock rather than the app clock. |
| | | 209 | | /// </summary> |
| | | 210 | | public Task<DateTimeOffset> InsertMessageAsync(Guid id, string correlationId, string envelopeJson, TimeSpan retentio |
| | 1 | 211 | | => AsyncResponseRetry.ExecuteAsync( |
| | 1 | 212 | | token => InsertMessageOnceAsync(id, correlationId, envelopeJson, retention, token), |
| | 1 | 213 | | IsTransient, |
| | 1 | 214 | | _options.PublishMaxAttempts, |
| | 1 | 215 | | _options.PublishRetryBaseDelay, |
| | 1 | 216 | | _options.PublishRetryMaxDelay, |
| | 1 | 217 | | cancellationToken); |
| | | 218 | | |
| | | 219 | | private async Task<DateTimeOffset> InsertMessageOnceAsync(Guid id, string correlationId, string envelopeJson, TimeSp |
| | | 220 | | { |
| | 1 | 221 | | await EnsureCreatedAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 222 | | if (ShouldPrune(ref _lastMessagePruneTicks)) |
| | 1 | 223 | | await PruneExpiredMessagesAsync(cancellationToken).ConfigureAwait(false); |
| | | 224 | | |
| | 1 | 225 | | await using var connection = await _dataSource.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 226 | | await using var command = connection.CreateCommand(); |
| | | 227 | | // Single statement: the final SELECT both fires the NOTIFY exactly once and returns the |
| | | 228 | | // server-stamped created_at — the fresh row's via RETURNING, or the original row's when |
| | | 229 | | // the idempotent insert hit a duplicate. |
| | 1 | 230 | | command.CommandText = |
| | 1 | 231 | | $""" |
| | 1 | 232 | | WITH inserted AS ( |
| | 1 | 233 | | INSERT INTO {MessageTable} (id, correlation_id, envelope_json, expires_at) |
| | 1 | 234 | | VALUES (@id, @correlation_id, @envelope_json, now() + @retention) |
| | 1 | 235 | | ON CONFLICT (id) DO NOTHING |
| | 1 | 236 | | RETURNING created_at |
| | 1 | 237 | | ) |
| | 1 | 238 | | SELECT COALESCE( |
| | 1 | 239 | | (SELECT created_at FROM inserted), |
| | 1 | 240 | | (SELECT created_at FROM {MessageTable} WHERE id = @id)) AS created_at, |
| | 1 | 241 | | pg_notify(@channel, @payload); |
| | 1 | 242 | | """; |
| | 1 | 243 | | command.Parameters.AddWithValue("id", id); |
| | 1 | 244 | | command.Parameters.AddWithValue("correlation_id", correlationId); |
| | 1 | 245 | | command.Parameters.Add("envelope_json", NpgsqlDbType.Jsonb).Value = envelopeJson; |
| | 1 | 246 | | command.Parameters.AddWithValue("retention", retention); |
| | 1 | 247 | | command.Parameters.AddWithValue("channel", NotificationChannel); |
| | 1 | 248 | | command.Parameters.AddWithValue("payload", NotifyPayload(correlationId)); |
| | | 249 | | DateTimeOffset? createdAt; |
| | 1 | 250 | | await using (var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false)) |
| | | 251 | | { |
| | 1 | 252 | | await reader.ReadAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 253 | | createdAt = reader.IsDBNull(0) ? null : reader.GetFieldValue<DateTimeOffset>(0); |
| | | 254 | | } |
| | | 255 | | |
| | 1 | 256 | | if (createdAt is { } stamped) |
| | 1 | 257 | | return stamped; |
| | | 258 | | |
| | | 259 | | // NULL is (almost always) a CONCURRENT idempotent publish, not a missing row: ON CONFLICT |
| | | 260 | | // detects the other transaction's row against latest data, but the same-statement fallback |
| | | 261 | | // subquery reads under this statement's snapshot, which predates that commit — so the row |
| | | 262 | | // exists and is invisible here (reproduced on PostgreSQL 16). A fresh statement gets a |
| | | 263 | | // fresh read-committed snapshot and resolves it deterministically; no retry loop needed. |
| | 1 | 264 | | await using var lookup = connection.CreateCommand(); |
| | 1 | 265 | | lookup.CommandText = $"SELECT created_at FROM {MessageTable} WHERE id = @id;"; |
| | 1 | 266 | | lookup.Parameters.AddWithValue("id", id); |
| | 1 | 267 | | var existing = await lookup.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false); |
| | | 268 | | |
| | 1 | 269 | | return existing switch |
| | 1 | 270 | | { |
| | 1 | 271 | | DateTimeOffset offset => offset, |
| | 1 | 272 | | DateTime dateTime => new DateTimeOffset(dateTime, TimeSpan.Zero), |
| | 1 | 273 | | |
| | 1 | 274 | | // Only reachable when the duplicate's original row is genuinely gone (pruned |
| | 1 | 275 | | // mid-publish): the message is not persisted, and reporting success with a fabricated |
| | 1 | 276 | | // app-clock timestamp would both lie about persistence and feed a client clock into |
| | 1 | 277 | | // the server-clock watermark. |
| | 1 | 278 | | _ => throw new InvalidOperationException( |
| | 1 | 279 | | $"PostgreSQL response insert for message {id} found no row after a duplicate: the original no longer exi |
| | 1 | 280 | | }; |
| | 1 | 281 | | } |
| | | 282 | | |
| | | 283 | | public async Task<IReadOnlyList<PostgreSqlChannelMessage>> LoadMessagesAsync( |
| | | 284 | | string correlationId, |
| | | 285 | | DateTimeOffset sinceUtc, |
| | | 286 | | int batchSize, |
| | | 287 | | DateTimeOffset? afterCreatedAtUtc, |
| | | 288 | | Guid? afterId, |
| | | 289 | | CancellationToken cancellationToken) |
| | | 290 | | { |
| | 3 | 291 | | await EnsureCreatedAsync(cancellationToken).ConfigureAwait(false); |
| | 3 | 292 | | await using var connection = await _dataSource.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 293 | | await using var command = connection.CreateCommand(); |
| | 1 | 294 | | command.CommandText = |
| | 1 | 295 | | $""" |
| | 1 | 296 | | SELECT id, correlation_id, envelope_json::text, created_at, acked_at |
| | 1 | 297 | | FROM {MessageTable} |
| | 1 | 298 | | WHERE correlation_id = @correlation_id |
| | 1 | 299 | | AND created_at >= @since |
| | 1 | 300 | | AND expires_at > now() |
| | 1 | 301 | | {(afterCreatedAtUtc is null ? "" : "AND (created_at > @after_created_at OR (created_at = @after_created_at |
| | 1 | 302 | | ORDER BY created_at, id |
| | 1 | 303 | | LIMIT @limit; |
| | 1 | 304 | | """; |
| | 1 | 305 | | command.Parameters.AddWithValue("correlation_id", correlationId); |
| | 1 | 306 | | command.Parameters.AddWithValue("since", sinceUtc); |
| | 1 | 307 | | command.Parameters.AddWithValue("limit", batchSize); |
| | 1 | 308 | | if (afterCreatedAtUtc is not null) |
| | | 309 | | { |
| | 1 | 310 | | command.Parameters.AddWithValue("after_created_at", afterCreatedAtUtc.Value); |
| | 1 | 311 | | command.Parameters.AddWithValue("after_id", afterId ?? throw new ArgumentNullException(nameof(afterId))); |
| | | 312 | | } |
| | | 313 | | |
| | 1 | 314 | | var messages = new List<PostgreSqlChannelMessage>(batchSize); |
| | 1 | 315 | | await using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 316 | | while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) |
| | 1 | 317 | | messages.Add(new PostgreSqlChannelMessage( |
| | 1 | 318 | | reader.GetGuid(0), |
| | 1 | 319 | | reader.GetString(1), |
| | 1 | 320 | | reader.GetString(2), |
| | 1 | 321 | | reader.GetFieldValue<DateTimeOffset>(3), |
| | 1 | 322 | | reader.IsDBNull(4) ? null : reader.GetFieldValue<DateTimeOffset>(4))); |
| | 1 | 323 | | return messages; |
| | 1 | 324 | | } |
| | | 325 | | |
| | | 326 | | /// <summary> |
| | | 327 | | /// Atomically claims a message for live delivery: sets <c>acked_at</c> unless the publisher has |
| | | 328 | | /// already routed it to the lost-subscriber path (<c>recovery_claimed</c>). Returns <c>false</c> |
| | | 329 | | /// when recovery owns the message, so a slow-but-live waiter does not deliver a response the |
| | | 330 | | /// recovery callback already handled. Multiple processes may each win this claim, preserving |
| | | 331 | | /// cross-process fan-out, because it gates only on <c>recovery_claimed</c>, not on <c>acked_at</c>. |
| | | 332 | | /// </summary> |
| | | 333 | | public async Task<bool> TryClaimForDeliveryAsync(Guid messageId, CancellationToken cancellationToken) |
| | | 334 | | { |
| | 3 | 335 | | await EnsureCreatedAsync(cancellationToken).ConfigureAwait(false); |
| | 3 | 336 | | await using var connection = await _dataSource.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 337 | | await using var command = connection.CreateCommand(); |
| | 1 | 338 | | command.CommandText = |
| | 1 | 339 | | $""" |
| | 1 | 340 | | UPDATE {MessageTable} |
| | 1 | 341 | | SET acked_at = COALESCE(acked_at, now()) |
| | 1 | 342 | | WHERE id = @id AND NOT recovery_claimed AND expires_at > now() |
| | 1 | 343 | | RETURNING id; |
| | 1 | 344 | | """; |
| | 1 | 345 | | command.Parameters.AddWithValue("id", messageId); |
| | 1 | 346 | | var result = await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 347 | | return result is not null and not DBNull; |
| | 1 | 348 | | } |
| | | 349 | | |
| | | 350 | | /// <summary> |
| | | 351 | | /// Atomically claims a message for the lost-subscriber path: sets <c>recovery_claimed</c> only |
| | | 352 | | /// while no waiter has delivered (<c>acked_at IS NULL</c>). Returns <c>true</c> when recovery wins; |
| | | 353 | | /// <c>false</c> means a live waiter already took the message, so the publisher must not also fire |
| | | 354 | | /// the recovery callback. Row-level locking serializes this against <see cref="TryClaimForDeliveryAsync"/>. |
| | | 355 | | /// </summary> |
| | | 356 | | public async Task<bool> TryClaimForRecoveryAsync(Guid messageId, CancellationToken cancellationToken) |
| | | 357 | | { |
| | 1 | 358 | | await EnsureCreatedAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 359 | | await using var connection = await _dataSource.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 360 | | await using var command = connection.CreateCommand(); |
| | 1 | 361 | | command.CommandText = |
| | 1 | 362 | | $""" |
| | 1 | 363 | | UPDATE {MessageTable} |
| | 1 | 364 | | SET recovery_claimed = true |
| | 1 | 365 | | WHERE id = @id AND acked_at IS NULL |
| | 1 | 366 | | RETURNING id; |
| | 1 | 367 | | """; |
| | 1 | 368 | | command.Parameters.AddWithValue("id", messageId); |
| | 1 | 369 | | var result = await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 370 | | return result is not null and not DBNull; |
| | 1 | 371 | | } |
| | | 372 | | |
| | | 373 | | /// <summary>Returns the database server's current UTC time, used as a clock-safe delivery watermark.</summary> |
| | | 374 | | public async Task<DateTimeOffset> GetServerTimeUtcAsync(CancellationToken cancellationToken) |
| | | 375 | | { |
| | 3 | 376 | | await EnsureCreatedAsync(cancellationToken).ConfigureAwait(false); |
| | 3 | 377 | | await using var connection = await _dataSource.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 378 | | await using var command = connection.CreateCommand(); |
| | 1 | 379 | | command.CommandText = "SELECT now();"; |
| | 1 | 380 | | var result = await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 381 | | return result switch |
| | 1 | 382 | | { |
| | 1 | 383 | | DateTimeOffset dto => dto.ToUniversalTime(), |
| | 1 | 384 | | DateTime dt => new DateTimeOffset(DateTime.SpecifyKind(dt, DateTimeKind.Utc), TimeSpan.Zero), |
| | 1 | 385 | | _ => DateTimeOffset.UtcNow |
| | 1 | 386 | | }; |
| | 1 | 387 | | } |
| | | 388 | | |
| | | 389 | | public async Task<bool> IsMessageAcknowledgedAsync(Guid messageId, CancellationToken cancellationToken) |
| | | 390 | | { |
| | 3 | 391 | | await EnsureCreatedAsync(cancellationToken).ConfigureAwait(false); |
| | 3 | 392 | | await using var connection = await _dataSource.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 393 | | await using var command = connection.CreateCommand(); |
| | 1 | 394 | | command.CommandText = $"SELECT acked_at IS NOT NULL FROM {MessageTable} WHERE id = @id AND expires_at > now();"; |
| | 1 | 395 | | command.Parameters.AddWithValue("id", messageId); |
| | 1 | 396 | | var result = await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 397 | | return result is bool acknowledged && acknowledged; |
| | 1 | 398 | | } |
| | | 399 | | |
| | | 400 | | public async Task UpsertSubscriberAsync(string correlationId, Guid registrationId, string instanceId, TimeSpan ttl, |
| | | 401 | | { |
| | 1 | 402 | | await EnsureCreatedAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 403 | | if (ShouldPrune(ref _lastSubscriberPruneTicks)) |
| | 1 | 404 | | await PruneExpiredSubscribersAsync(correlationId, cancellationToken).ConfigureAwait(false); |
| | | 405 | | |
| | 1 | 406 | | await using var connection = await _dataSource.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 407 | | await using var command = connection.CreateCommand(); |
| | 1 | 408 | | command.CommandText = |
| | 1 | 409 | | $""" |
| | 1 | 410 | | INSERT INTO {SubscriberTable} (correlation_id, registration_id, instance_id, expires_at) |
| | 1 | 411 | | VALUES (@correlation_id, @registration_id, @instance_id, now() + @ttl) |
| | 1 | 412 | | ON CONFLICT (correlation_id, registration_id) |
| | 1 | 413 | | DO UPDATE SET instance_id = EXCLUDED.instance_id, |
| | 1 | 414 | | expires_at = EXCLUDED.expires_at; |
| | 1 | 415 | | """; |
| | 1 | 416 | | command.Parameters.AddWithValue("correlation_id", correlationId); |
| | 1 | 417 | | command.Parameters.AddWithValue("registration_id", registrationId); |
| | 1 | 418 | | command.Parameters.AddWithValue("instance_id", instanceId); |
| | 1 | 419 | | command.Parameters.AddWithValue("ttl", ttl); |
| | 1 | 420 | | await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 421 | | } |
| | | 422 | | |
| | | 423 | | public async Task HeartbeatSubscribersAsync( |
| | | 424 | | string instanceId, |
| | | 425 | | IReadOnlyCollection<(string CorrelationId, Guid RegistrationId)> registrations, |
| | | 426 | | TimeSpan ttl, |
| | | 427 | | CancellationToken cancellationToken) |
| | | 428 | | { |
| | 3 | 429 | | if (registrations.Count == 0) |
| | 1 | 430 | | return; |
| | | 431 | | |
| | 3 | 432 | | await EnsureCreatedAsync(cancellationToken).ConfigureAwait(false); |
| | 3 | 433 | | await using var connection = await _dataSource.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 434 | | await using var command = connection.CreateCommand(); |
| | | 435 | | |
| | | 436 | | // UPSERT rather than a bare UPDATE: the caller only heartbeats registrations that are live |
| | | 437 | | // in this process, so a missing row means the pruner deleted it (e.g. after a >timeout |
| | | 438 | | // stall) — re-creating it here is what brings the waiter back from "permanently invisible". |
| | 1 | 439 | | var correlationIds = new string[registrations.Count]; |
| | 1 | 440 | | var registrationIds = new Guid[registrations.Count]; |
| | 1 | 441 | | var index = 0; |
| | 1 | 442 | | foreach (var (correlationId, registrationId) in registrations) |
| | | 443 | | { |
| | 1 | 444 | | correlationIds[index] = correlationId; |
| | 1 | 445 | | registrationIds[index] = registrationId; |
| | 1 | 446 | | index++; |
| | | 447 | | } |
| | | 448 | | |
| | 1 | 449 | | command.CommandText = |
| | 1 | 450 | | $""" |
| | 1 | 451 | | INSERT INTO {SubscriberTable} (correlation_id, registration_id, instance_id, expires_at) |
| | 1 | 452 | | SELECT correlation_id, registration_id, @instance_id, now() + @ttl |
| | 1 | 453 | | FROM unnest(@correlation_ids, @registration_ids) AS live (correlation_id, registration_id) |
| | 1 | 454 | | ON CONFLICT (correlation_id, registration_id) |
| | 1 | 455 | | DO UPDATE SET instance_id = EXCLUDED.instance_id, |
| | 1 | 456 | | expires_at = EXCLUDED.expires_at; |
| | 1 | 457 | | """; |
| | 1 | 458 | | command.Parameters.AddWithValue("instance_id", instanceId); |
| | 1 | 459 | | command.Parameters.AddWithValue("correlation_ids", NpgsqlDbType.Array | NpgsqlDbType.Text, correlationIds); |
| | 1 | 460 | | command.Parameters.AddWithValue("registration_ids", NpgsqlDbType.Array | NpgsqlDbType.Uuid, registrationIds); |
| | 1 | 461 | | command.Parameters.AddWithValue("ttl", ttl); |
| | 1 | 462 | | await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 463 | | } |
| | | 464 | | |
| | | 465 | | public async Task DeleteSubscriberAsync(string correlationId, Guid registrationId, CancellationToken cancellationTok |
| | | 466 | | { |
| | 3 | 467 | | await EnsureCreatedAsync(cancellationToken).ConfigureAwait(false); |
| | 3 | 468 | | await using var connection = await _dataSource.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 469 | | await using var command = connection.CreateCommand(); |
| | 1 | 470 | | command.CommandText = $"DELETE FROM {SubscriberTable} WHERE correlation_id = @correlation_id AND registration_id |
| | 1 | 471 | | command.Parameters.AddWithValue("correlation_id", correlationId); |
| | 1 | 472 | | command.Parameters.AddWithValue("registration_id", registrationId); |
| | 1 | 473 | | await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 474 | | } |
| | | 475 | | |
| | | 476 | | public async Task<long> CountActiveSubscribersAsync(string correlationId, CancellationToken cancellationToken) |
| | | 477 | | { |
| | 3 | 478 | | await EnsureCreatedAsync(cancellationToken).ConfigureAwait(false); |
| | 3 | 479 | | if (ShouldPrune(ref _lastSubscriberPruneTicks)) |
| | 3 | 480 | | await PruneExpiredSubscribersAsync(correlationId, cancellationToken).ConfigureAwait(false); |
| | | 481 | | |
| | 3 | 482 | | await using var connection = await _dataSource.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 483 | | await using var command = connection.CreateCommand(); |
| | 1 | 484 | | command.CommandText = |
| | 1 | 485 | | $""" |
| | 1 | 486 | | SELECT count(*)::bigint |
| | 1 | 487 | | FROM {SubscriberTable} |
| | 1 | 488 | | WHERE correlation_id = @correlation_id AND expires_at > now(); |
| | 1 | 489 | | """; |
| | 1 | 490 | | command.Parameters.AddWithValue("correlation_id", correlationId); |
| | 1 | 491 | | var result = await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 492 | | return result is long count ? count : 0L; |
| | 1 | 493 | | } |
| | | 494 | | |
| | | 495 | | public async Task ExecuteListenAsync(Func<string?, Task> onNotification, CancellationToken cancellationToken) |
| | | 496 | | { |
| | 3 | 497 | | await EnsureCreatedAsync(cancellationToken).ConfigureAwait(false); |
| | 3 | 498 | | await using var connection = await _dataSource.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 499 | | connection.Notification += (_, args) => _ = onNotification(args.Payload); |
| | 1 | 500 | | await using (var command = connection.CreateCommand()) |
| | | 501 | | { |
| | 1 | 502 | | command.CommandText = $"LISTEN {Quote(NotificationChannel)};"; |
| | 1 | 503 | | await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); |
| | | 504 | | } |
| | | 505 | | |
| | 1 | 506 | | while (!cancellationToken.IsCancellationRequested) |
| | 1 | 507 | | await connection.WaitAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 508 | | } |
| | | 509 | | |
| | | 510 | | private async Task PruneExpiredRecoveryAsync(string? correlationId, CancellationToken cancellationToken) |
| | | 511 | | { |
| | 1 | 512 | | await using var connection = await _dataSource.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 513 | | await using var command = connection.CreateCommand(); |
| | 1 | 514 | | command.CommandText = correlationId is null |
| | 1 | 515 | | ? $"DELETE FROM {RecoveryTable} WHERE expires_at <= now();" |
| | 1 | 516 | | : $"DELETE FROM {RecoveryTable} WHERE correlation_id = @correlation_id AND expires_at <= now();"; |
| | 1 | 517 | | if (correlationId is not null) |
| | 1 | 518 | | command.Parameters.AddWithValue("correlation_id", correlationId); |
| | 1 | 519 | | await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 520 | | } |
| | | 521 | | |
| | | 522 | | private async Task PruneExpiredMessagesAsync(CancellationToken cancellationToken) |
| | | 523 | | { |
| | 1 | 524 | | await using var connection = await _dataSource.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 525 | | await using var command = connection.CreateCommand(); |
| | 1 | 526 | | command.CommandText = $"DELETE FROM {MessageTable} WHERE expires_at <= now();"; |
| | 1 | 527 | | await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 528 | | } |
| | | 529 | | |
| | | 530 | | private async Task PruneExpiredSubscribersAsync(string? correlationId, CancellationToken cancellationToken) |
| | | 531 | | { |
| | 3 | 532 | | await using var connection = await _dataSource.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 533 | | await using var command = connection.CreateCommand(); |
| | 1 | 534 | | command.CommandText = correlationId is null |
| | 1 | 535 | | ? $"DELETE FROM {SubscriberTable} WHERE expires_at <= now();" |
| | 1 | 536 | | : $"DELETE FROM {SubscriberTable} WHERE correlation_id = @correlation_id AND expires_at <= now();"; |
| | 1 | 537 | | if (correlationId is not null) |
| | 1 | 538 | | command.Parameters.AddWithValue("correlation_id", correlationId); |
| | 1 | 539 | | await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 540 | | } |
| | | 541 | | |
| | | 542 | | public static void ValidateIdentifier(string? value, string name) |
| | | 543 | | { |
| | 3 | 544 | | if (string.IsNullOrWhiteSpace(value)) |
| | 3 | 545 | | throw new InvalidOperationException($"{nameof(PostgreSqlAsyncResponseChannelOptions)}.{name} must be configu |
| | 3 | 546 | | if (!IsIdentifier(value)) |
| | 3 | 547 | | throw new InvalidOperationException( |
| | 3 | 548 | | $"{nameof(PostgreSqlAsyncResponseChannelOptions)}.{name} '{value}' must be a simple PostgreSQL identifie |
| | 3 | 549 | | } |
| | | 550 | | |
| | | 551 | | private static bool IsIdentifier(string value) |
| | | 552 | | { |
| | 3 | 553 | | if (value.Length == 0 || !(char.IsAsciiLetter(value[0]) || value[0] == '_')) |
| | 3 | 554 | | return false; |
| | | 555 | | |
| | 3 | 556 | | foreach (var c in value) |
| | | 557 | | { |
| | 3 | 558 | | if (!(char.IsAsciiLetterOrDigit(c) || c == '_')) |
| | 3 | 559 | | return false; |
| | | 560 | | } |
| | | 561 | | |
| | 3 | 562 | | return true; |
| | | 563 | | } |
| | | 564 | | |
| | 3 | 565 | | private static string Quote(string identifier) => "\"" + identifier + "\""; |
| | | 566 | | |
| | | 567 | | private static string IndexName(string table, string suffix) |
| | | 568 | | { |
| | 3 | 569 | | var name = $"{table}_{suffix}_idx"; |
| | 3 | 570 | | return name.Length <= 63 ? name : name[..63]; |
| | | 571 | | } |
| | | 572 | | |
| | | 573 | | /// <summary>NOTIFY payload for a publish: the correlation id, or empty when it is too long to carry.</summary> |
| | | 574 | | private static string NotifyPayload(string correlationId) |
| | 3 | 575 | | => Encoding.UTF8.GetByteCount(correlationId) <= MaxNotifyPayloadBytes ? correlationId : string.Empty; |
| | | 576 | | |
| | | 577 | | internal static bool IsTransient(Exception exception) |
| | 3 | 578 | | => exception is not OperationCanceledException |
| | 3 | 579 | | && (exception is NpgsqlException { IsTransient: true } || exception is TimeoutException); |
| | | 580 | | |
| | | 581 | | /// <summary> |
| | | 582 | | /// Stable 64-bit advisory-lock key for serializing schema creation. Uses FNV-1a over a |
| | | 583 | | /// schema-scoped discriminator: it must be deterministic across processes (so |
| | | 584 | | /// <see cref="string.GetHashCode()"/>, which is per-process randomized, is unusable) and identical |
| | | 585 | | /// to the transport store's key for the same schema so both serialize their shared CREATE SCHEMA. |
| | | 586 | | /// </summary> |
| | | 587 | | internal static long SchemaAdvisoryLockKey(string schemaName) |
| | | 588 | | { |
| | | 589 | | const ulong offset = 14695981039346656037UL; |
| | | 590 | | const ulong prime = 1099511628211UL; |
| | 3 | 591 | | var hash = offset; |
| | 3 | 592 | | foreach (var b in Encoding.UTF8.GetBytes($"asyncresponse:ddl:{schemaName}")) |
| | | 593 | | { |
| | 3 | 594 | | hash ^= b; |
| | 3 | 595 | | hash *= prime; |
| | | 596 | | } |
| | | 597 | | |
| | 3 | 598 | | return unchecked((long)hash); |
| | | 599 | | } |
| | | 600 | | |
| | | 601 | | /// <summary> |
| | | 602 | | /// Time-gates opportunistic pruning so the housekeeping DELETE runs at most once per |
| | | 603 | | /// <see cref="PostgreSqlAsyncResponseChannelOptions.PruneInterval"/> instead of on every operation. |
| | | 604 | | /// Read queries already filter on <c>expires_at</c>, so throttling pruning never affects correctness. |
| | | 605 | | /// </summary> |
| | | 606 | | private bool ShouldPrune(ref long lastTicks) |
| | | 607 | | { |
| | 3 | 608 | | var interval = _options.PruneInterval; |
| | 3 | 609 | | if (interval <= TimeSpan.Zero) |
| | 3 | 610 | | return true; |
| | | 611 | | |
| | 3 | 612 | | var now = DateTime.UtcNow.Ticks; |
| | 3 | 613 | | var last = Interlocked.Read(ref lastTicks); |
| | 3 | 614 | | return now - last >= interval.Ticks |
| | 3 | 615 | | && Interlocked.CompareExchange(ref lastTicks, now, last) == last; |
| | | 616 | | } |
| | | 617 | | } |