-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMartenConfigurationExtensions.cs
More file actions
273 lines (234 loc) · 12.6 KB
/
MartenConfigurationExtensions.cs
File metadata and controls
273 lines (234 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
using BookStore.ApiService.Infrastructure.Tenant;
using BookStore.ApiService.Models;
using BookStore.ApiService.Projections;
using BookStore.Shared.Infrastructure.Json;
using BookStore.Shared.Models;
using JasperFx;
using JasperFx.Core;
using JasperFx.Events;
using JasperFx.Events.Daemon;
using JasperFx.Events.Projections;
using Marten;
using Marten.Events.Daemon;
using Marten.Events.Projections;
using Marten.Schema;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Weasel.Core;
using Weasel.Postgresql;
using Wolverine;
using Wolverine.Marten;
namespace BookStore.ApiService.Infrastructure.Extensions;
/// <summary>
/// Extension methods for configuring Marten event store
/// </summary>
public static class MartenConfigurationExtensions
{
/// <summary>
/// Configures Marten for event sourcing with projections and indexes
/// </summary>
public static IServiceCollection AddMartenEventStore(
this IServiceCollection services,
IConfiguration configuration)
{
_ = services.AddMarten(sp =>
{
// Get connection string from Aspire
var connectionString = configuration.GetConnectionString(BookStore.ServiceDefaults.ResourceNames.BookStoreDb);
if (string.IsNullOrEmpty(connectionString))
{
throw new InvalidOperationException($"Connection string '{BookStore.ServiceDefaults.ResourceNames.BookStoreDb}' not found. Please ensure the '{BookStore.ServiceDefaults.ResourceNames.Postgres}' resource is correctly referenced.");
}
var env = sp.GetRequiredService<IHostEnvironment>();
var options = new StoreOptions();
options.Connection(connectionString);
// 50% improvement in throughput, less "event skipping"
options.Events.AppendMode = EventAppendMode.Rich;
options.Events.UseArchivedStreamPartitioning = true;
// These cause some database changes, so can't be defaults,
// but these might help "heal" systems that have problems later
options.Events.EnableAdvancedAsyncTracking = true;
// Enables you to mark events as just plain bad so they are skipped
// in projections from here on out.
options.Events.EnableEventSkippingInProjectionsOrSubscriptions = true;
// This will optimize the usage of Inline projections, but will force
// you to treat your aggregate projection "write models" as being
// immutable in your command handler code
options.Events.UseIdentityMapForAggregates = true;
// Future proofing a bit. Will help with some future optimizations
// for rebuild optimizations
options.Events.UseMandatoryStreamTypeDeclaration = true;
// This is just annoying anyway
options.DisableNpgsqlLogging = true;
// Configure automatic schema creation/updates based on environment
// Development: All - creates/updates/drops schema objects as needed
// Production: CreateOnly - only creates missing objects, never modifies existing
options.AutoCreateSchemaObjects = env.IsDevelopment()
? AutoCreate.All
: AutoCreate.CreateOnly;
ConfigureEventMetadata(options);
ConfigureJsonSerialization(options);
RegisterEventTypes(options);
RegisterProjections(options);
ConfigureIndexes(options);
RegisterChangeListeners(options, sp);
// Enable Multi-Tenancy (Conjoined - same DB, different tenant_id column)
options.Events.TenancyStyle = Marten.Storage.TenancyStyle.Conjoined;
// Enforce multi-tenancy on all documents
_ = options.Policies.AllDocumentsAreMultiTenanted();
// Tenant documents are excluded from multi-tenancy via [DoNotPartition] attribute
return options;
})
.UseLightweightSessions()
.AddAsyncDaemon(DaemonMode.Solo)
.PublishEventsToWolverine("marten")
.IntegrateWithWolverine(x =>
// Let Wolverine do the load distribution better than what Marten by itself can do
x.UseWolverineManagedEventSubscriptionDistribution = true);
// Register IDocumentSession with proper tenant scoping
// Since we use Marten's "*DEFAULT*" for the default tenant,
// we can pass tenant ID directly to LightweightSession
_ = services.AddScoped<IDocumentSession>(sp =>
{
var store = sp.GetRequiredService<IDocumentStore>();
// If running within a Wolverine message handler, use the envelope's tenant ID
var messageContext = sp.GetService<IMessageContext>();
if (messageContext?.TenantId != null)
{
return store.LightweightSession(messageContext.TenantId);
}
// Otherwise fall back to ASP.NET Core tenant context
var tenantContext = sp.GetRequiredService<ITenantContext>();
return store.LightweightSession(tenantContext.TenantId);
});
// Also register IQuerySession just in case
_ = services.AddScoped<IQuerySession>(sp => sp.GetRequiredService<IDocumentSession>());
return services;
}
static void ConfigureEventMetadata(StoreOptions options)
{
// Enable metadata storage for correlation/causation tracking
options.Events.MetadataConfig.CorrelationIdEnabled = true;
options.Events.MetadataConfig.CausationIdEnabled = true;
options.Events.MetadataConfig.HeadersEnabled = true;
}
static void ConfigureJsonSerialization(StoreOptions options)
// Configure JSON serialization for Marten (database storage)
// Enums stored as strings for readability and camelCase for JSON properties
=> options.UseSystemTextJsonForSerialization(
EnumStorage.AsString,
Casing.CamelCase,
configure: settings =>
// Add custom converter for PartialDate to handle nullable values properly
settings.Converters.Add(new PartialDateJsonConverter()));
static void RegisterEventTypes(StoreOptions options)
{
// Book events
_ = options.Events.AddEventType<Events.BookAdded>();
_ = options.Events.AddEventType<Events.BookUpdated>();
_ = options.Events.AddEventType<Events.BookSoftDeleted>();
_ = options.Events.AddEventType<Events.BookRestored>();
_ = options.Events.AddEventType<Events.BookCoverUpdated>();
_ = options.Events.AddEventType<Events.BookDiscountUpdated>();
// Sale events
_ = options.Events.AddEventType<Events.BookSaleScheduled>();
_ = options.Events.AddEventType<Events.BookSaleCancelled>();
// Author events
_ = options.Events.AddEventType<Events.AuthorAdded>();
_ = options.Events.AddEventType<Events.AuthorUpdated>();
_ = options.Events.AddEventType<Events.AuthorSoftDeleted>();
_ = options.Events.AddEventType<Events.AuthorRestored>();
// Category events
_ = options.Events.AddEventType<Events.CategoryAdded>();
_ = options.Events.AddEventType<Events.CategoryUpdated>();
_ = options.Events.AddEventType<Events.CategorySoftDeleted>();
_ = options.Events.AddEventType<Events.CategoryRestored>();
// Publisher events
_ = options.Events.AddEventType<Events.PublisherAdded>();
_ = options.Events.AddEventType<Events.PublisherUpdated>();
_ = options.Events.AddEventType<Events.PublisherSoftDeleted>();
_ = options.Events.AddEventType<Events.PublisherRestored>();
// Order events
_ = options.Events.AddEventType<Events.OrderPlaced>();
_ = options.Events.AddEventType<Events.PaymentSimulated>();
// User events
_ = options.Events.AddEventType<BookStore.Shared.Messages.Events.UserProfileCreated>();
_ = options.Events.AddEventType<BookStore.Shared.Messages.Events.BookAddedToFavorites>();
_ = options.Events.AddEventType<BookStore.Shared.Messages.Events.BookRemovedFromFavorites>();
_ = options.Events.AddEventType<BookStore.Shared.Messages.Events.BookRated>();
_ = options.Events.AddEventType<BookStore.Shared.Messages.Events.BookRatingRemoved>();
_ = options.Events.AddEventType<BookStore.Shared.Messages.Events.BookAddedToCart>();
_ = options.Events.AddEventType<BookStore.Shared.Messages.Events.BookRemovedFromCart>();
_ = options.Events.AddEventType<BookStore.Shared.Messages.Events.CartItemQuantityUpdated>();
_ = options.Events.AddEventType<BookStore.Shared.Messages.Events.ShoppingCartCleared>();
_ = options.Events.AddEventType<BookStore.Shared.Messages.Events.AnonymousCartMerged>();
}
static void RegisterProjections(StoreOptions options)
{
// Configure projections using SingleStreamProjection pattern
// Simple projections use Async lifecycle for eventual consistency
_ = options.Projections.Snapshot<CategoryProjection>(SnapshotLifecycle.Async);
_ = options.Projections.Snapshot<AuthorProjection>(SnapshotLifecycle.Async);
_ = options.Projections.Snapshot<BookSearchProjection>(SnapshotLifecycle.Async);
_ = options.Projections.Snapshot<PublisherProjection>(SnapshotLifecycle.Async);
_ = options.Projections.Snapshot<UserProfile>(SnapshotLifecycle.Async);
_ = options.Projections.Snapshot<OrderSummaryProjection>(SnapshotLifecycle.Async);
options.Projections.Add<BookStatisticsProjection>(ProjectionLifecycle.Async);
options.Projections.Add<AuthorStatisticsProjectionBuilder>(ProjectionLifecycle.Async);
options.Projections.Add<CategoryStatisticsProjectionBuilder>(ProjectionLifecycle.Async);
options.Projections.Add<PublisherStatisticsProjectionBuilder>(ProjectionLifecycle.Async);
}
static void ConfigureIndexes(StoreOptions options)
{
// Configure indexes for search performance
// Note: Trigram indexes for fuzzy search will be created via SQL migration
// BookSearchProjection indexes
_ = options.Schema.For<BookSearchProjection>()
.Index(x => x.PublisherId!) // Standard B-tree index for exact matches
.Index(x => x.Title) // B-tree index for sorting
.GinIndexJsonData() // GIN index for JSON fields
.NgramIndex(x => x.Title) // NGram search on title
.NgramIndex(x => x.AuthorNames) // NGram search on authors
.Index(x => x.Deleted); // Index for soft-delete filtering
// AuthorProjection indexes
_ = options.Schema.For<AuthorProjection>()
.Index(x => x.Name) // B-tree index for sorting
.NgramIndex(x => x.Name) // NGram search on author name
.Index(x => x.Deleted); // Index for soft-delete filtering
// CategoryProjection indexes
_ = options.Schema.For<CategoryProjection>()
.Index(x => x.Deleted); // Index for soft-delete filtering
// PublisherProjection indexes
_ = options.Schema.For<PublisherProjection>()
.Index(x => x.Name) // B-tree index for sorting
.NgramIndex(x => x.Name) // NGram search on publisher name
.Index(x => x.Deleted); // Index for soft-delete filtering
// OrderSummaryProjection indexes
_ = options.Schema.For<OrderSummaryProjection>()
.Index(x => x.UserId!)
.Index(x => x.PlacedAt);
// ApplicationUser indexes (Identity)
_ = options.Schema.For<ApplicationUser>()
.UniqueIndex(UniqueIndexType.Computed, x => x.NormalizedEmail!)
.UniqueIndex(UniqueIndexType.Computed, x => x.NormalizedUserName!)
.Index(x => x.NormalizedEmail)
.Index(x => x.NormalizedUserName)
.GinIndexJsonData()
.NgramIndex(x => x.Email!)
.Index(x => x.CreatedAt)
.Index(x => x.CreatedAt, idx =>
{
idx.Predicate = "data ->> 'EmailConfirmed' = 'false'";
idx.Name = "idx_application_user_unverified_created_at";
});
}
static void RegisterChangeListeners(StoreOptions options, IServiceProvider sp)
{
// Register commit listener for cache invalidation and SSE notifications
// This ensures actions are taken AFTER read models are updated
var listener = sp.GetRequiredService<ProjectionCommitListener>();
options.Listeners.Add(listener);
options.Projections.AsyncListeners.Add(listener);
}
}