|
| 1 | +using System.Runtime.CompilerServices; |
| 2 | +using System.Text.Json; |
| 3 | +using BbQ.Events.Events; |
| 4 | +using BbQ.Events.PostgreSql.Internal; |
| 5 | +using Npgsql; |
| 6 | + |
| 7 | +namespace BbQ.Events.PostgreSql.Events; |
| 8 | + |
| 9 | +/// <summary> |
| 10 | +/// PostgreSQL implementation of IEventStore. |
| 11 | +/// </summary> |
| 12 | +/// <remarks> |
| 13 | +/// This implementation provides: |
| 14 | +/// - Durable event persistence in PostgreSQL |
| 15 | +/// - Sequential position tracking per stream |
| 16 | +/// - Atomic append operations |
| 17 | +/// - Efficient event replay via streaming reads |
| 18 | +/// - JSON serialization of event data |
| 19 | +/// - Support for event metadata |
| 20 | +/// |
| 21 | +/// Connection handling: |
| 22 | +/// - Each operation opens a new connection (connection pooling is handled by Npgsql) |
| 23 | +/// - Operations are fully async for optimal scalability |
| 24 | +/// - Connections are properly disposed in all code paths |
| 25 | +/// |
| 26 | +/// Prerequisites: |
| 27 | +/// - bbq_events table must exist (see Schema/CreateEventsTable.sql) |
| 28 | +/// - bbq_streams table must exist (see Schema/CreateStreamsTable.sql) |
| 29 | +/// </remarks> |
| 30 | +public class PostgreSqlEventStore : IEventStore |
| 31 | +{ |
| 32 | + private readonly PostgreSqlEventStoreOptions _options; |
| 33 | + private readonly JsonSerializerOptions _jsonOptions; |
| 34 | + private static readonly string MachineName = Environment.MachineName; |
| 35 | + |
| 36 | + /// <summary> |
| 37 | + /// Creates a new PostgreSQL event store. |
| 38 | + /// </summary> |
| 39 | + /// <param name="options">Configuration options</param> |
| 40 | + /// <exception cref="ArgumentNullException">Thrown when options is null</exception> |
| 41 | + /// <exception cref="ArgumentException">Thrown when connection string is null or empty</exception> |
| 42 | + public PostgreSqlEventStore(PostgreSqlEventStoreOptions options) |
| 43 | + { |
| 44 | + _options = options ?? throw new ArgumentNullException(nameof(options)); |
| 45 | + |
| 46 | + if (string.IsNullOrWhiteSpace(_options.ConnectionString)) |
| 47 | + { |
| 48 | + throw new ArgumentException("Connection string cannot be null or empty", nameof(options)); |
| 49 | + } |
| 50 | + |
| 51 | + _jsonOptions = _options.JsonSerializerOptions ?? new JsonSerializerOptions |
| 52 | + { |
| 53 | + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, |
| 54 | + WriteIndented = false |
| 55 | + }; |
| 56 | + } |
| 57 | + |
| 58 | + /// <summary> |
| 59 | + /// Appends an event to a stream. |
| 60 | + /// </summary> |
| 61 | + /// <typeparam name="TEvent">The type of event</typeparam> |
| 62 | + /// <param name="stream">The stream name</param> |
| 63 | + /// <param name="event">The event to append</param> |
| 64 | + /// <param name="ct">Cancellation token</param> |
| 65 | + /// <returns>The position of the appended event</returns> |
| 66 | + /// <exception cref="ArgumentException">Thrown when stream name is null or empty</exception> |
| 67 | + /// <exception cref="ArgumentNullException">Thrown when event is null</exception> |
| 68 | + public async Task<long> AppendAsync<TEvent>(string stream, TEvent @event, CancellationToken ct = default) |
| 69 | + { |
| 70 | + if (string.IsNullOrWhiteSpace(stream)) |
| 71 | + { |
| 72 | + throw new ArgumentException("Stream name cannot be null or empty", nameof(stream)); |
| 73 | + } |
| 74 | + |
| 75 | + if (@event == null) |
| 76 | + { |
| 77 | + throw new ArgumentNullException(nameof(@event)); |
| 78 | + } |
| 79 | + |
| 80 | + await using var connection = new NpgsqlConnection(_options.ConnectionString); |
| 81 | + await connection.OpenAsync(ct); |
| 82 | + |
| 83 | + await using var command = connection.CreateCommand(); |
| 84 | + command.CommandText = PostgreSqlConstants.AppendEventSqlSimplified; |
| 85 | + |
| 86 | + var eventType = typeof(TEvent).FullName ?? typeof(TEvent).Name; |
| 87 | + var eventData = PostgreSqlHelpers.SerializeToJson(@event, _jsonOptions); |
| 88 | + |
| 89 | + command.AddParameter("@stream_name", stream); |
| 90 | + command.AddParameter("@event_type", eventType); |
| 91 | + command.AddParameter("@event_data", eventData); |
| 92 | + command.AddParameter("@metadata", _options.IncludeMetadata ? CreateMetadata() : null); |
| 93 | + |
| 94 | + var result = await command.ExecuteScalarAsync(ct); |
| 95 | + return Convert.ToInt64(result); |
| 96 | + } |
| 97 | + |
| 98 | + /// <summary> |
| 99 | + /// Reads events from a stream starting at a given position. |
| 100 | + /// </summary> |
| 101 | + /// <typeparam name="TEvent">The type of events to read</typeparam> |
| 102 | + /// <param name="stream">The stream name</param> |
| 103 | + /// <param name="fromPosition">The position to start reading from (inclusive)</param> |
| 104 | + /// <param name="ct">Cancellation token</param> |
| 105 | + /// <returns>An async enumerable of events with their positions</returns> |
| 106 | + /// <exception cref="ArgumentException">Thrown when stream name is null or empty</exception> |
| 107 | + public async IAsyncEnumerable<StoredEvent<TEvent>> ReadAsync<TEvent>( |
| 108 | + string stream, |
| 109 | + long fromPosition = 0, |
| 110 | + [EnumeratorCancellation] CancellationToken ct = default) |
| 111 | + { |
| 112 | + if (string.IsNullOrWhiteSpace(stream)) |
| 113 | + { |
| 114 | + throw new ArgumentException("Stream name cannot be null or empty", nameof(stream)); |
| 115 | + } |
| 116 | + |
| 117 | + await using var connection = new NpgsqlConnection(_options.ConnectionString); |
| 118 | + await connection.OpenAsync(ct); |
| 119 | + |
| 120 | + await using var command = connection.CreateCommand(); |
| 121 | + command.CommandText = PostgreSqlConstants.ReadEventsSql; |
| 122 | + command.AddParameter("@stream_name", stream); |
| 123 | + command.AddParameter("@from_position", fromPosition); |
| 124 | + |
| 125 | + await using var reader = await command.ExecuteReaderAsync(ct); |
| 126 | + |
| 127 | + while (await reader.ReadAsync(ct)) |
| 128 | + { |
| 129 | + var position = reader.GetLong(PostgreSqlConstants.Position); |
| 130 | + var eventType = reader.GetString(reader.GetOrdinal(PostgreSqlConstants.EventType)); |
| 131 | + var eventData = reader.GetString(reader.GetOrdinal(PostgreSqlConstants.EventData)); |
| 132 | + |
| 133 | + // Only deserialize if the event type matches |
| 134 | + // This allows for type filtering when reading from streams with multiple event types |
| 135 | + var expectedType = typeof(TEvent).FullName ?? typeof(TEvent).Name; |
| 136 | + if (eventType == expectedType) |
| 137 | + { |
| 138 | + var @event = PostgreSqlHelpers.DeserializeFromJson<TEvent>(eventData, _jsonOptions); |
| 139 | + yield return new StoredEvent<TEvent>(position, @event); |
| 140 | + } |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + /// <summary> |
| 145 | + /// Gets the current position (last event position) in a stream. |
| 146 | + /// </summary> |
| 147 | + /// <param name="stream">The stream name</param> |
| 148 | + /// <param name="ct">Cancellation token</param> |
| 149 | + /// <returns>The current position, or null if the stream doesn't exist</returns> |
| 150 | + /// <exception cref="ArgumentException">Thrown when stream name is null or empty</exception> |
| 151 | + public async Task<long?> GetStreamPositionAsync(string stream, CancellationToken ct = default) |
| 152 | + { |
| 153 | + if (string.IsNullOrWhiteSpace(stream)) |
| 154 | + { |
| 155 | + throw new ArgumentException("Stream name cannot be null or empty", nameof(stream)); |
| 156 | + } |
| 157 | + |
| 158 | + await using var connection = new NpgsqlConnection(_options.ConnectionString); |
| 159 | + await connection.OpenAsync(ct); |
| 160 | + |
| 161 | + await using var command = connection.CreateCommand(); |
| 162 | + command.CommandText = PostgreSqlConstants.GetStreamPositionSql; |
| 163 | + command.AddParameter("@stream_name", stream); |
| 164 | + |
| 165 | + var result = await command.ExecuteScalarAsync(ct); |
| 166 | + |
| 167 | + return result == null || result == DBNull.Value |
| 168 | + ? null |
| 169 | + : Convert.ToInt64(result); |
| 170 | + } |
| 171 | + |
| 172 | + /// <summary> |
| 173 | + /// Creates metadata for an event. |
| 174 | + /// </summary> |
| 175 | + private string CreateMetadata() |
| 176 | + { |
| 177 | + var metadata = new Dictionary<string, object> |
| 178 | + { |
| 179 | + ["timestamp"] = DateTime.UtcNow, |
| 180 | + ["server"] = MachineName |
| 181 | + }; |
| 182 | + |
| 183 | + return PostgreSqlHelpers.SerializeToJson(metadata, _jsonOptions); |
| 184 | + } |
| 185 | +} |
0 commit comments