Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
703 lines (603 loc) · 26.6 KB
/
Copy pathProgram.cs
File metadata and controls
703 lines (603 loc) · 26.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
using System;
using System.Text.Json.Nodes;
using System.Net.Http.Json;
using MongoDB.Bson;
using MongoDB.Driver;
namespace MatrixIndexer;
public class Program
{
private static readonly HttpClient Http = new();
private static IMongoCollection<BsonDocument>? _eventsCollection;
private static IMongoCollection<BsonDocument>? _backfillCollection;
private static string? _syncToken;
private static string _stateFile = "sync_token.txt";
private static string _indexerId = "default";
// Backfill behavior
private static int _backfillPageSize = 200;
private static int _backfillWorkers = 2;
private static int _claimLeaseMinutes = 15;
// Room discovery behavior
private static int _joinedRoomsPollSeconds = 300;
public static async Task Main(string[] args)
{
Console.WriteLine("Starting Matrix Indexer (.NET)");
// 1. Config
var homeserver = GetEnv("MATRIX_HOMESERVER");
var userId = GetEnv("MATRIX_USER_ID");
var password = GetEnv("MATRIX_PASSWORD");
var mongoUri = GetEnv("MONGODB_URI", "mongodb://localhost:27017");
var mongoDbName = GetEnv("MONGODB_DB", "matrix_index");
_indexerId = GetEnv("INDEXER_ID", userId);
_stateFile = GetEnv("INDEXER_SYNC_TOKEN_PATH", _stateFile);
_backfillPageSize = int.Parse(GetEnv("INDEXER_BACKFILL_PAGE_SIZE", _backfillPageSize.ToString()));
_backfillWorkers = int.Parse(GetEnv("INDEXER_BACKFILL_WORKERS", _backfillWorkers.ToString()));
_claimLeaseMinutes = int.Parse(GetEnv("INDEXER_CLAIM_LEASE_MINUTES", _claimLeaseMinutes.ToString()));
_joinedRoomsPollSeconds = int.Parse(GetEnv("INDEXER_JOINED_ROOMS_POLL_SECONDS", _joinedRoomsPollSeconds.ToString()));
// 2. Mongo
Console.WriteLine($"Connecting to MongoDB: {mongoUri}");
var mongoClient = new MongoClient(mongoUri);
var db = mongoClient.GetDatabase(mongoDbName);
_eventsCollection = db.GetCollection<BsonDocument>("events");
_backfillCollection = db.GetCollection<BsonDocument>("room_backfill");
// Ensure indexes
await EnsureIndexes();
Console.WriteLine("MongoDB indexes ensured.");
// 3. Matrix Login
if (!homeserver.StartsWith("http")) homeserver = "https://" + homeserver;
homeserver = homeserver.TrimEnd('/');
Console.WriteLine($"Logging into Matrix: {homeserver} as {userId} (indexer_id={_indexerId})");
string accessToken;
try
{
var loginData = new
{
type = "m.login.password",
user = userId,
password = password
};
var loginResp = await Http.PostAsJsonAsync($"{homeserver}/_matrix/client/r0/login", loginData);
loginResp.EnsureSuccessStatusCode();
var loginJson = await loginResp.Content.ReadFromJsonAsync<JsonNode>();
accessToken = loginJson?["access_token"]?.ToString() ?? throw new Exception("No access token");
Console.WriteLine("Login successful.");
}
catch (Exception ex)
{
Console.WriteLine($"Login failed: {ex.Message}");
return;
}
// 4. Load state
if (File.Exists(_stateFile))
{
_syncToken = (await File.ReadAllTextAsync(_stateFile)).Trim();
if (!string.IsNullOrEmpty(_syncToken))
Console.WriteLine($"Loaded sync token: {_syncToken}");
}
// 5. Start live sync loop; after first successful sync start background backfill workers
Http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
// Aggressively discover joined rooms (so we seed backfill even for quiet rooms)
try
{
await DiscoverJoinedRoomsAndSeedBackfill(homeserver, reconcileExisting: true);
}
catch (Exception ex)
{
Console.WriteLine($"Initial joined_rooms discovery failed: {ex.Message}");
}
var backfillStarted = false;
Console.WriteLine("Starting sync loop...");
while (true)
{
try
{
var url = $"{homeserver}/_matrix/client/r0/sync?timeout=30000";
if (!string.IsNullOrEmpty(_syncToken)) url += $"&since={_syncToken}";
var syncResp = await Http.GetAsync(url);
if (!syncResp.IsSuccessStatusCode)
{
Console.WriteLine($"Sync failed: {syncResp.StatusCode}");
await Task.Delay(5000);
continue;
}
var root = await syncResp.Content.ReadFromJsonAsync<JsonNode>();
if (root == null) continue;
// Process rooms first; only persist next_batch after successful processing
await ProcessSyncRoomsAndSeedBackfill(root);
// Update token after processing
var nextBatch = root["next_batch"]?.ToString();
if (!string.IsNullOrEmpty(nextBatch))
{
_syncToken = nextBatch;
await AtomicWriteAsync(_stateFile, _syncToken);
}
if (!backfillStarted)
{
backfillStarted = true;
Console.WriteLine($"First successful sync complete. Starting backfill workers: {_backfillWorkers} (pageSize={_backfillPageSize})");
for (var i = 0; i < _backfillWorkers; i++)
{
_ = Task.Run(() => BackfillWorkerLoop(homeserver));
}
Console.WriteLine($"Starting joined_rooms discovery loop (every {_joinedRoomsPollSeconds}s)...");
_ = Task.Run(() => JoinedRoomsDiscoveryLoop(homeserver));
}
}
catch (Exception ex)
{
Console.WriteLine($"Error in sync loop: {ex.Message}");
await Task.Delay(5000);
}
}
}
private static async Task EnsureIndexes()
{
if (_eventsCollection == null || _backfillCollection == null) return;
// Events: unique by event_id (idempotent upsert)
var evKeys = Builders<BsonDocument>.IndexKeys.Ascending("event_id");
var evOptions = new CreateIndexOptions { Unique = true };
await _eventsCollection.Indexes.CreateOneAsync(new CreateIndexModel<BsonDocument>(evKeys, evOptions));
// Backfill state: unique by (indexer_id, room_id) so multiple accounts can share one DB safely.
// Also drop legacy unique {room_id:1} index if present (it blocks multi-account use).
var existingIndexes = await _backfillCollection.Indexes.ListAsync();
var existingIndexDocs = await existingIndexes.ToListAsync();
foreach (var idx in existingIndexDocs)
{
var name = idx.GetValue("name", "").ToString();
var unique = idx.GetValue("unique", false).ToBoolean();
var keyDoc = idx.GetValue("key", new BsonDocument()).AsBsonDocument;
var isLegacyRoomOnlyUnique = unique
&& keyDoc.ElementCount == 1
&& keyDoc.Contains("room_id");
if (isLegacyRoomOnlyUnique && !string.IsNullOrEmpty(name))
{
Console.WriteLine($"Dropping legacy backfill index: {name}");
try
{
await _backfillCollection.Indexes.DropOneAsync(name);
}
catch (Exception ex)
{
Console.WriteLine($"Legacy index drop skipped ({name}): {ex.Message}");
}
}
}
var bfKeys = Builders<BsonDocument>.IndexKeys
.Ascending("indexer_id")
.Ascending("room_id");
var bfOptions = new CreateIndexOptions { Unique = true };
await _backfillCollection.Indexes.CreateOneAsync(new CreateIndexModel<BsonDocument>(bfKeys, bfOptions));
// Helpful query index for each account's queue scanning
var bfQueryKeys = Builders<BsonDocument>.IndexKeys
.Ascending("indexer_id")
.Ascending("done")
.Ascending("updated_at");
await _backfillCollection.Indexes.CreateOneAsync(new CreateIndexModel<BsonDocument>(bfQueryKeys));
}
private static async Task ProcessSyncRoomsAndSeedBackfill(JsonNode root)
{
var join = root["rooms"]?["join"]?.AsObject();
if (join == null) return;
foreach (var room in join)
{
var roomId = room.Key;
var timeline = room.Value?["timeline"];
var events = timeline?["events"]?.AsArray();
if (events != null)
{
await ProcessEvents(roomId, events);
}
// Seed backfill cursor from prev_batch token
var prevBatch = timeline?["prev_batch"]?.ToString();
if (!string.IsNullOrEmpty(prevBatch))
{
await SeedBackfillRoom(roomId, prevBatch, source: "sync.prev_batch");
}
}
}
private static async Task SeedBackfillRoom(string roomId, string cursor, string source)
{
if (_backfillCollection == null) return;
var filter = BackfillRoomFilter(roomId);
var existing = await _backfillCollection.Find(filter).FirstOrDefaultAsync();
if (existing != null) return;
var doc = new BsonDocument
{
{ "indexer_id", _indexerId },
{ "room_id", roomId },
{ "cursor", cursor },
{ "done", false },
{ "claimed", false },
{ "seed_source", source },
{ "created_at", DateTime.UtcNow },
{ "updated_at", DateTime.UtcNow },
{ "error_count", 0 },
};
try
{
await _backfillCollection.InsertOneAsync(doc);
Console.WriteLine($"Seeded backfill cursor for room {roomId} (source={source})");
}
catch
{
// ignore races
}
}
private static async Task JoinedRoomsDiscoveryLoop(string homeserver)
{
while (true)
{
try
{
await DiscoverJoinedRoomsAndSeedBackfill(homeserver, reconcileExisting: false);
}
catch (Exception ex)
{
Console.WriteLine($"joined_rooms discovery error: {ex.Message}");
}
await Task.Delay(TimeSpan.FromSeconds(_joinedRoomsPollSeconds));
}
}
private static async Task DiscoverJoinedRoomsAndSeedBackfill(string homeserver, bool reconcileExisting)
{
if (_backfillCollection == null) return;
var resp = await Http.GetAsync($"{homeserver}/_matrix/client/r0/joined_rooms");
if (!resp.IsSuccessStatusCode)
{
Console.WriteLine($"joined_rooms failed: {(int)resp.StatusCode} {resp.ReasonPhrase}");
return;
}
var json = await resp.Content.ReadFromJsonAsync<JsonNode>();
var rooms = json?["joined_rooms"]?.AsArray();
if (rooms == null) return;
var seeded = 0;
foreach (var r in rooms)
{
var roomId = r?.ToString();
if (string.IsNullOrEmpty(roomId)) continue;
// Already seeded for this indexer account?
var filter = BackfillRoomFilter(roomId);
var existing = await _backfillCollection.Find(filter).FirstOrDefaultAsync();
if (existing != null)
{
if (reconcileExisting)
await SeedReconciliation(homeserver, roomId, existing);
continue;
}
// Get an initial pagination token by asking for 1 event backward from "now".
var cursor = await GetInitialBackfillCursorFromMessages(homeserver, roomId);
if (string.IsNullOrEmpty(cursor))
{
// No history / no permission; mark as done so workers don't spin forever.
await SeedBackfillRoom(roomId, "", source: "joined_rooms.messages.no_cursor");
await MarkBackfillDone(roomId);
continue;
}
await SeedBackfillRoom(roomId, cursor, source: "joined_rooms.messages.end");
seeded++;
}
if (seeded > 0)
Console.WriteLine($"joined_rooms discovery: seeded {seeded} room(s) for backfill");
}
private static async Task SeedReconciliation(string homeserver, string roomId, BsonDocument state)
{
if (_eventsCollection == null || _backfillCollection == null) return;
if (state.GetValue("reconcile_pending", false).ToBoolean()) return;
var latest = await _eventsCollection
.Find(Builders<BsonDocument>.Filter.Eq("room_id", roomId))
.Sort(Builders<BsonDocument>.Sort.Descending("origin_server_ts"))
.Limit(1)
.FirstOrDefaultAsync();
if (latest == null || !latest.TryGetValue("origin_server_ts", out var tsValue) || !tsValue.IsNumeric) return;
var cursor = await GetInitialBackfillCursorFromMessages(homeserver, roomId);
if (string.IsNullOrEmpty(cursor)) return;
var targetTs = state.GetValue("reconcile_target_ts", tsValue).ToInt64();
var update = Builders<BsonDocument>.Update
.Set("reconcile_cursor", cursor)
.Set("reconcile_target_ts", targetTs)
.Set("reconcile_pending", true)
.Set("reconcile_seeded_at", DateTime.UtcNow)
.Set("claimed", false)
.Set("updated_at", DateTime.UtcNow);
await _backfillCollection.UpdateOneAsync(BackfillRoomFilter(roomId), update);
Console.WriteLine($"Seeded outage reconciliation for room {roomId} to overlap ts={targetTs}");
}
private static async Task<string?> GetInitialBackfillCursorFromMessages(string homeserver, string roomId)
{
try
{
var url = $"{homeserver}/_matrix/client/r0/rooms/{Uri.EscapeDataString(roomId)}/messages?dir=b&limit=1";
var resp = await Http.GetAsync(url);
if (!resp.IsSuccessStatusCode) return null;
var json = await resp.Content.ReadFromJsonAsync<JsonNode>();
if (json == null) return null;
// If we got a chunk, store it too.
var chunk = json["chunk"]?.AsArray();
if (chunk != null && chunk.Count > 0)
{
await ProcessEvents(roomId, chunk);
}
return json["end"]?.ToString();
}
catch
{
return null;
}
}
private static async Task BackfillWorkerLoop(string homeserver)
{
if (_backfillCollection == null) return;
while (true)
{
try
{
var room = await ClaimNextBackfillRoom();
if (room == null)
{
// No rooms pending; sleep a bit then try again.
await Task.Delay(TimeSpan.FromMinutes(10));
continue;
}
var roomId = room["room_id"].AsString;
var reconciling = room.GetValue("reconcile_pending", false).ToBoolean();
var cursorField = reconciling ? "reconcile_cursor" : "cursor";
var cursor = room.GetValue(cursorField, BsonNull.Value).ToString();
if (string.IsNullOrEmpty(cursor) || cursor == "BsonNull")
{
if (reconciling) await MarkReconciliationDone(roomId);
else await MarkBackfillDone(roomId);
continue;
}
var url = $"{homeserver}/_matrix/client/r0/rooms/{Uri.EscapeDataString(roomId)}/messages?dir=b&limit={_backfillPageSize}&from={Uri.EscapeDataString(cursor)}";
var resp = await Http.GetAsync(url);
if ((int)resp.StatusCode == 429)
{
var retry = resp.Headers.RetryAfter?.Delta ?? TimeSpan.FromSeconds(10);
await Task.Delay(retry);
await UnclaimRoom(roomId);
continue;
}
if (!resp.IsSuccessStatusCode)
{
await IncrementBackfillError(roomId, $"HTTP {(int)resp.StatusCode}");
await Task.Delay(TimeSpan.FromSeconds(5));
await UnclaimRoom(roomId);
continue;
}
var json = await resp.Content.ReadFromJsonAsync<JsonNode>();
if (json == null)
{
await UnclaimRoom(roomId);
continue;
}
var chunk = json["chunk"]?.AsArray();
var end = json["end"]?.ToString();
var overlapFound = reconciling && chunk != null
&& await ReconciliationOverlapFound(room, chunk);
if (chunk != null && chunk.Count > 0)
{
await ProcessEvents(roomId, chunk);
}
if (reconciling && overlapFound)
{
await MarkReconciliationDone(roomId);
}
else if (string.IsNullOrEmpty(end) || chunk == null || chunk.Count == 0)
{
if (reconciling) await MarkReconciliationDone(roomId);
else await MarkBackfillDone(roomId);
}
else
{
await UpdateBackfillCursor(roomId, end, cursorField);
}
await Task.Delay(250);
}
catch (Exception ex)
{
Console.WriteLine($"Backfill worker error: {ex.Message}");
await Task.Delay(5000);
}
}
}
private static async Task<BsonDocument?> ClaimNextBackfillRoom()
{
if (_backfillCollection == null) return null;
var workPending = Builders<BsonDocument>.Filter.Or(
Builders<BsonDocument>.Filter.Eq("done", false),
Builders<BsonDocument>.Filter.Eq("reconcile_pending", true)
);
var leaseAvailable = Builders<BsonDocument>.Filter.Or(
Builders<BsonDocument>.Filter.Ne("claimed", true),
Builders<BsonDocument>.Filter.Lt("claimed_at", DateTime.UtcNow.AddMinutes(-_claimLeaseMinutes))
);
var filter = Builders<BsonDocument>.Filter.And(
Builders<BsonDocument>.Filter.Eq("indexer_id", _indexerId),
workPending,
leaseAvailable
);
var update = Builders<BsonDocument>.Update
.Set("claimed", true)
.Set("claimed_at", DateTime.UtcNow)
.Set("updated_at", DateTime.UtcNow);
var opts = new FindOneAndUpdateOptions<BsonDocument>
{
Sort = Builders<BsonDocument>.Sort.Ascending("updated_at"),
ReturnDocument = ReturnDocument.After
};
return await _backfillCollection.FindOneAndUpdateAsync(filter, update, opts);
}
private static async Task UnclaimRoom(string roomId)
{
if (_backfillCollection == null) return;
var filter = BackfillRoomFilter(roomId);
var update = Builders<BsonDocument>.Update
.Set("claimed", false)
.Unset("claimed_at")
.Set("updated_at", DateTime.UtcNow);
await _backfillCollection.UpdateOneAsync(filter, update);
}
private static async Task UpdateBackfillCursor(string roomId, string cursor, string cursorField)
{
if (_backfillCollection == null) return;
var filter = BackfillRoomFilter(roomId);
var update = Builders<BsonDocument>.Update
.Set(cursorField, cursor)
.Set("claimed", false)
.Unset("claimed_at")
.Set("updated_at", DateTime.UtcNow);
await _backfillCollection.UpdateOneAsync(filter, update);
}
private static async Task MarkBackfillDone(string roomId)
{
if (_backfillCollection == null) return;
var filter = BackfillRoomFilter(roomId);
var update = Builders<BsonDocument>.Update
.Set("done", true)
.Set("claimed", false)
.Unset("claimed_at")
.Set("updated_at", DateTime.UtcNow);
await _backfillCollection.UpdateOneAsync(filter, update);
Console.WriteLine($"Backfill complete for room {roomId}");
}
private static async Task MarkReconciliationDone(string roomId)
{
if (_backfillCollection == null) return;
var update = Builders<BsonDocument>.Update
.Set("reconcile_pending", false)
.Set("reconcile_completed_at", DateTime.UtcNow)
.Set("claimed", false)
.Unset("claimed_at")
.Unset("reconcile_cursor")
.Unset("reconcile_target_ts")
.Set("updated_at", DateTime.UtcNow);
await _backfillCollection.UpdateOneAsync(BackfillRoomFilter(roomId), update);
Console.WriteLine($"Outage reconciliation complete for room {roomId}");
}
private static async Task<bool> ReconciliationOverlapFound(BsonDocument room, JsonArray events)
{
if (_eventsCollection == null) return false;
var targetTs = room.GetValue("reconcile_target_ts", long.MinValue).ToInt64();
var candidateIds = events
.Where(e => e?["origin_server_ts"]?.GetValue<long>() <= targetTs)
.Select(e => e?["event_id"]?.ToString())
.Where(id => !string.IsNullOrEmpty(id))
.Cast<string>()
.ToList();
if (candidateIds.Count == 0) return false;
var existing = await _eventsCollection.CountDocumentsAsync(
Builders<BsonDocument>.Filter.In("event_id", candidateIds),
new CountOptions { Limit = 1 });
return existing > 0;
}
private static async Task IncrementBackfillError(string roomId, string reason)
{
if (_backfillCollection == null) return;
var filter = BackfillRoomFilter(roomId);
var update = Builders<BsonDocument>.Update
.Inc("error_count", 1)
.Set("last_error", reason)
.Set("updated_at", DateTime.UtcNow)
.Set("claimed", false)
.Unset("claimed_at");
await _backfillCollection.UpdateOneAsync(filter, update);
Console.WriteLine($"Backfill error for room {roomId}: {reason}");
}
private static FilterDefinition<BsonDocument> BackfillRoomFilter(string roomId)
{
return Builders<BsonDocument>.Filter.And(
Builders<BsonDocument>.Filter.Eq("indexer_id", _indexerId),
Builders<BsonDocument>.Filter.Eq("room_id", roomId)
);
}
private static async Task ProcessEvents(string roomId, JsonArray events)
{
if (_eventsCollection == null) return;
var docs = new List<BsonDocument>();
foreach (var ev in events)
{
if (ev == null) continue;
var eventId = ev["event_id"]?.ToString();
if (string.IsNullOrEmpty(eventId)) continue;
var doc = BsonDocument.Parse(ev.ToJsonString());
if (!doc.Contains("room_id")) doc["room_id"] = roomId;
docs.Add(doc);
}
if (docs.Count == 0) return;
foreach (var doc in docs)
{
try
{
await UpsertEventPreservingContent(doc);
}
catch
{
// Ignore duplicates or transient errors.
}
}
Console.WriteLine($"Processed {docs.Count} events from {roomId}");
}
private static async Task UpsertEventPreservingContent(BsonDocument incoming)
{
if (_eventsCollection == null) return;
var eventId = incoming.GetValue("event_id", BsonNull.Value)?.ToString();
if (string.IsNullOrEmpty(eventId) || eventId == "BsonNull") return;
var filter = Builders<BsonDocument>.Filter.Eq("event_id", eventId);
var existing = await _eventsCollection.Find(filter).FirstOrDefaultAsync();
// If this is a redacted copy of a message event, preserve original searchable body/content.
if (IsRedactedMessage(incoming) && existing != null)
{
if (existing.TryGetValue("content", out var existingContent)
&& existingContent.IsBsonDocument
&& (!incoming.TryGetValue("content", out var incomingContent)
|| !incomingContent.IsBsonDocument
|| incomingContent.AsBsonDocument.ElementCount == 0
|| !incomingContent.AsBsonDocument.Contains("body")))
{
incoming["content"] = existingContent.DeepClone().AsBsonDocument;
incoming["retained_redacted_content"] = true;
}
incoming["is_redacted"] = true;
incoming["redacted_at"] = DateTime.UtcNow;
}
// If this is a redaction event, annotate its target message without erasing content.
if (incoming.GetValue("type", "").ToString() == "m.room.redaction"
&& incoming.TryGetValue("redacts", out var redacts)
&& redacts.IsString)
{
var targetId = redacts.AsString;
if (!string.IsNullOrWhiteSpace(targetId))
{
var targetFilter = Builders<BsonDocument>.Filter.Eq("event_id", targetId);
var targetUpdate = Builders<BsonDocument>.Update
.Set("is_redacted", true)
.Set("redacted_by_event_id", eventId)
.Set("redacted_by_sender", incoming.GetValue("sender", BsonNull.Value).ToString())
.Set("redacted_at", DateTime.UtcNow);
await _eventsCollection.UpdateOneAsync(targetFilter, targetUpdate);
}
}
await _eventsCollection.ReplaceOneAsync(filter, incoming, new ReplaceOptions { IsUpsert = true });
}
private static bool IsRedactedMessage(BsonDocument doc)
{
if (doc.GetValue("type", "").ToString() != "m.room.message") return false;
if (!doc.TryGetValue("unsigned", out var unsigned) || !unsigned.IsBsonDocument) return false;
return unsigned.AsBsonDocument.Contains("redacted_because");
}
private static async Task AtomicWriteAsync(string path, string content)
{
var tmp = path + ".tmp";
await File.WriteAllTextAsync(tmp, content);
File.Move(tmp, path, true);
}
private static string GetEnv(string key, string? defaultValue = null)
{
var val = Environment.GetEnvironmentVariable(key);
if (string.IsNullOrEmpty(val))
{
if (defaultValue != null) return defaultValue;
throw new Exception($"Missing environment variable: {key}");
}
return val;
}
}