@hatk/hatk 0.0.1-alpha.10 → 0.0.1-alpha.100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. package/dist/adapter.d.ts +19 -0
  2. package/dist/adapter.d.ts.map +1 -0
  3. package/dist/adapter.js +113 -0
  4. package/dist/backfill.d.ts +32 -2
  5. package/dist/backfill.d.ts.map +1 -1
  6. package/dist/backfill.js +154 -51
  7. package/dist/car.d.ts +20 -0
  8. package/dist/car.d.ts.map +1 -1
  9. package/dist/car.js +108 -0
  10. package/dist/cli.js +247 -1043
  11. package/dist/config.d.ts +145 -1
  12. package/dist/config.d.ts.map +1 -1
  13. package/dist/config.js +61 -8
  14. package/dist/database/adapter-factory.d.ts +6 -0
  15. package/dist/database/adapter-factory.d.ts.map +1 -0
  16. package/dist/database/adapter-factory.js +20 -0
  17. package/dist/database/adapters/duckdb-search.d.ts +12 -0
  18. package/dist/database/adapters/duckdb-search.d.ts.map +1 -0
  19. package/dist/database/adapters/duckdb-search.js +27 -0
  20. package/dist/database/adapters/duckdb.d.ts +25 -0
  21. package/dist/database/adapters/duckdb.d.ts.map +1 -0
  22. package/dist/database/adapters/duckdb.js +161 -0
  23. package/dist/database/adapters/sqlite-search.d.ts +16 -0
  24. package/dist/database/adapters/sqlite-search.d.ts.map +1 -0
  25. package/dist/database/adapters/sqlite-search.js +76 -0
  26. package/dist/database/adapters/sqlite.d.ts +18 -0
  27. package/dist/database/adapters/sqlite.d.ts.map +1 -0
  28. package/dist/database/adapters/sqlite.js +88 -0
  29. package/dist/{db.d.ts → database/db.d.ts} +94 -6
  30. package/dist/database/db.d.ts.map +1 -0
  31. package/dist/database/db.js +1833 -0
  32. package/dist/database/dialect.d.ts +45 -0
  33. package/dist/database/dialect.d.ts.map +1 -0
  34. package/dist/database/dialect.js +72 -0
  35. package/dist/{fts.d.ts → database/fts.d.ts} +7 -0
  36. package/dist/database/fts.d.ts.map +1 -0
  37. package/dist/{fts.js → database/fts.js} +122 -34
  38. package/dist/database/index.d.ts +7 -0
  39. package/dist/database/index.d.ts.map +1 -0
  40. package/dist/database/index.js +6 -0
  41. package/dist/database/ports.d.ts +50 -0
  42. package/dist/database/ports.d.ts.map +1 -0
  43. package/dist/database/ports.js +1 -0
  44. package/dist/database/schema.d.ts +91 -0
  45. package/dist/database/schema.d.ts.map +1 -0
  46. package/dist/{schema.js → database/schema.js} +153 -54
  47. package/dist/dev-entry.d.ts +8 -0
  48. package/dist/dev-entry.d.ts.map +1 -0
  49. package/dist/dev-entry.js +126 -0
  50. package/dist/feeds.d.ts +26 -8
  51. package/dist/feeds.d.ts.map +1 -1
  52. package/dist/feeds.js +72 -16
  53. package/dist/hooks.d.ts +102 -0
  54. package/dist/hooks.d.ts.map +1 -0
  55. package/dist/hooks.js +186 -0
  56. package/dist/hydrate.d.ts +55 -6
  57. package/dist/hydrate.d.ts.map +1 -1
  58. package/dist/hydrate.js +21 -20
  59. package/dist/indexer.d.ts +194 -3
  60. package/dist/indexer.d.ts.map +1 -1
  61. package/dist/indexer.js +620 -92
  62. package/dist/jetstream.d.ts +118 -0
  63. package/dist/jetstream.d.ts.map +1 -0
  64. package/dist/jetstream.js +238 -0
  65. package/dist/labels.d.ts +36 -0
  66. package/dist/labels.d.ts.map +1 -1
  67. package/dist/labels.js +71 -6
  68. package/dist/lex-types.d.ts +2 -0
  69. package/dist/lex-types.d.ts.map +1 -1
  70. package/dist/lexicon-resolve.d.ts.map +1 -1
  71. package/dist/lexicon-resolve.js +27 -112
  72. package/dist/lexicons/com/atproto/label/defs.json +75 -0
  73. package/dist/lexicons/com/atproto/moderation/defs.json +30 -0
  74. package/dist/lexicons/com/atproto/repo/strongRef.json +21 -0
  75. package/dist/lexicons/dev/hatk/applyWrites.json +87 -0
  76. package/dist/lexicons/dev/hatk/createRecord.json +40 -0
  77. package/dist/lexicons/dev/hatk/createReport.json +48 -0
  78. package/dist/lexicons/dev/hatk/deleteRecord.json +25 -0
  79. package/dist/lexicons/dev/hatk/describeCollections.json +41 -0
  80. package/dist/lexicons/dev/hatk/describeFeeds.json +29 -0
  81. package/dist/lexicons/dev/hatk/describeLabels.json +45 -0
  82. package/dist/lexicons/dev/hatk/getFeed.json +30 -0
  83. package/dist/lexicons/dev/hatk/getPreferences.json +19 -0
  84. package/dist/lexicons/dev/hatk/getRecord.json +26 -0
  85. package/dist/lexicons/dev/hatk/getRecords.json +32 -0
  86. package/dist/lexicons/dev/hatk/putPreference.json +28 -0
  87. package/dist/lexicons/dev/hatk/putRecord.json +41 -0
  88. package/dist/lexicons/dev/hatk/searchRecords.json +32 -0
  89. package/dist/lexicons/dev/hatk/uploadBlob.json +23 -0
  90. package/dist/logger.d.ts +29 -0
  91. package/dist/logger.d.ts.map +1 -1
  92. package/dist/logger.js +29 -0
  93. package/dist/main.js +196 -75
  94. package/dist/mst.d.ts +15 -0
  95. package/dist/mst.d.ts.map +1 -1
  96. package/dist/mst.js +13 -0
  97. package/dist/oauth/db.d.ts +27 -1
  98. package/dist/oauth/db.d.ts.map +1 -1
  99. package/dist/oauth/db.js +80 -19
  100. package/dist/oauth/discovery.d.ts +10 -0
  101. package/dist/oauth/discovery.d.ts.map +1 -1
  102. package/dist/oauth/discovery.js +54 -2
  103. package/dist/oauth/server.d.ts +131 -1
  104. package/dist/oauth/server.d.ts.map +1 -1
  105. package/dist/oauth/server.js +504 -39
  106. package/dist/oauth/service-describe.d.ts +42 -0
  107. package/dist/oauth/service-describe.d.ts.map +1 -0
  108. package/dist/oauth/service-describe.js +108 -0
  109. package/dist/oauth/session.d.ts +32 -0
  110. package/dist/oauth/session.d.ts.map +1 -0
  111. package/dist/oauth/session.js +131 -0
  112. package/dist/opengraph.d.ts +10 -0
  113. package/dist/opengraph.d.ts.map +1 -1
  114. package/dist/opengraph.js +94 -42
  115. package/dist/pds-proxy.d.ts +92 -0
  116. package/dist/pds-proxy.d.ts.map +1 -0
  117. package/dist/pds-proxy.js +396 -0
  118. package/dist/private-collections.d.ts +13 -0
  119. package/dist/private-collections.d.ts.map +1 -0
  120. package/dist/private-collections.js +27 -0
  121. package/dist/push.d.ts +54 -0
  122. package/dist/push.d.ts.map +1 -0
  123. package/dist/push.js +367 -0
  124. package/dist/renderer.d.ts +27 -0
  125. package/dist/renderer.d.ts.map +1 -0
  126. package/dist/renderer.js +46 -0
  127. package/dist/resolve-hatk.d.ts +6 -0
  128. package/dist/resolve-hatk.d.ts.map +1 -0
  129. package/dist/resolve-hatk.js +20 -0
  130. package/dist/response.d.ts +16 -0
  131. package/dist/response.d.ts.map +1 -0
  132. package/dist/response.js +69 -0
  133. package/dist/scanner.d.ts +21 -0
  134. package/dist/scanner.d.ts.map +1 -0
  135. package/dist/scanner.js +88 -0
  136. package/dist/seed.d.ts +19 -0
  137. package/dist/seed.d.ts.map +1 -1
  138. package/dist/seed.js +43 -4
  139. package/dist/server-init.d.ts +8 -0
  140. package/dist/server-init.d.ts.map +1 -0
  141. package/dist/server-init.js +62 -0
  142. package/dist/server.d.ts +34 -3
  143. package/dist/server.d.ts.map +1 -1
  144. package/dist/server.js +1033 -649
  145. package/dist/setup.d.ts +28 -1
  146. package/dist/setup.d.ts.map +1 -1
  147. package/dist/setup.js +50 -3
  148. package/dist/spaces/blob.d.ts +112 -0
  149. package/dist/spaces/blob.d.ts.map +1 -0
  150. package/dist/spaces/blob.js +460 -0
  151. package/dist/spaces/credential.d.ts +62 -0
  152. package/dist/spaces/credential.d.ts.map +1 -0
  153. package/dist/spaces/credential.js +184 -0
  154. package/dist/spaces/engine.d.ts +97 -0
  155. package/dist/spaces/engine.d.ts.map +1 -0
  156. package/dist/spaces/engine.js +559 -0
  157. package/dist/spaces/guard.d.ts +41 -0
  158. package/dist/spaces/guard.d.ts.map +1 -0
  159. package/dist/spaces/guard.js +79 -0
  160. package/dist/spaces/identity.d.ts +37 -0
  161. package/dist/spaces/identity.d.ts.map +1 -0
  162. package/dist/spaces/identity.js +88 -0
  163. package/dist/spaces/index.d.ts +55 -0
  164. package/dist/spaces/index.d.ts.map +1 -0
  165. package/dist/spaces/index.js +133 -0
  166. package/dist/spaces/notify.d.ts +51 -0
  167. package/dist/spaces/notify.d.ts.map +1 -0
  168. package/dist/spaces/notify.js +121 -0
  169. package/dist/spaces/records.d.ts +37 -0
  170. package/dist/spaces/records.d.ts.map +1 -0
  171. package/dist/spaces/records.js +63 -0
  172. package/dist/spaces/store.d.ts +51 -0
  173. package/dist/spaces/store.d.ts.map +1 -0
  174. package/dist/spaces/store.js +99 -0
  175. package/dist/spaces/uri.d.ts +60 -0
  176. package/dist/spaces/uri.d.ts.map +1 -0
  177. package/dist/spaces/uri.js +97 -0
  178. package/dist/spaces/verify.d.ts +46 -0
  179. package/dist/spaces/verify.d.ts.map +1 -0
  180. package/dist/spaces/verify.js +94 -0
  181. package/dist/spaces/viewer.d.ts +51 -0
  182. package/dist/spaces/viewer.d.ts.map +1 -0
  183. package/dist/spaces/viewer.js +167 -0
  184. package/dist/spaces/visibility.d.ts +57 -0
  185. package/dist/spaces/visibility.d.ts.map +1 -0
  186. package/dist/spaces/visibility.js +81 -0
  187. package/dist/templates/feed.tpl +18 -0
  188. package/dist/templates/hook.tpl +5 -0
  189. package/dist/templates/label.tpl +15 -0
  190. package/dist/templates/og.tpl +17 -0
  191. package/dist/templates/seed.tpl +11 -0
  192. package/dist/templates/setup.tpl +5 -0
  193. package/dist/templates/test-feed.tpl +19 -0
  194. package/dist/templates/test-xrpc.tpl +19 -0
  195. package/dist/templates/xrpc.tpl +53 -0
  196. package/dist/test.d.ts +3 -1
  197. package/dist/test.d.ts.map +1 -1
  198. package/dist/test.js +60 -36
  199. package/dist/views.js +1 -1
  200. package/dist/vite-plugin.d.ts +1 -1
  201. package/dist/vite-plugin.d.ts.map +1 -1
  202. package/dist/vite-plugin.js +254 -66
  203. package/dist/xrpc.d.ts +122 -12
  204. package/dist/xrpc.d.ts.map +1 -1
  205. package/dist/xrpc.js +270 -55
  206. package/package.json +28 -9
  207. package/public/admin-auth.js +271 -306
  208. package/public/admin.html +177 -61
  209. package/dist/db.d.ts.map +0 -1
  210. package/dist/db.js +0 -1361
  211. package/dist/fts.d.ts.map +0 -1
  212. package/dist/oauth/hooks.d.ts +0 -10
  213. package/dist/oauth/hooks.d.ts.map +0 -1
  214. package/dist/oauth/hooks.js +0 -40
  215. package/dist/schema.d.ts +0 -51
  216. package/dist/schema.d.ts.map +0 -1
  217. package/dist/test-browser.d.ts +0 -14
  218. package/dist/test-browser.d.ts.map +0 -1
  219. package/dist/test-browser.js +0 -26
package/dist/indexer.js CHANGED
@@ -1,23 +1,43 @@
1
+ import { reshapeRow } from "./database/db.js";
2
+ import { unfilteredQuerySQL } from "./spaces/guard.js";
3
+ import { rkeyOf } from "./spaces/uri.js";
1
4
  import { cborDecode } from "./cbor.js";
2
5
  import { parseCarFrame } from "./car.js";
3
- import { insertRecord, deleteRecord, setCursor, setRepoStatus, getRepoRetryInfo, listAllRepoStatuses } from "./db.js";
6
+ import { isPrivateCollection } from "./private-collections.js";
7
+ import { insertRecord, deleteRecord, setCursor, setRepoStatus, getRepoStatus, purgeRepoRecords, getRepoRetryInfo, listAllRepoStatuses, getDatabasePort, updateRepoHandle, } from "./database/db.js";
4
8
  import { backfillRepo } from "./backfill.js";
5
- import { rebuildAllIndexes } from "./fts.js";
9
+ import { rebuildAllIndexes } from "./database/fts.js";
6
10
  import { log, emit, timer } from "./logger.js";
7
11
  import { runLabelRules } from "./labels.js";
8
- import { getLexiconArray } from "./schema.js";
12
+ import { fireOnCommitHooks } from "./hooks.js";
13
+ import { getLexiconArray } from "./database/schema.js";
9
14
  import { validateRecord } from '@bigmoves/lexicon';
10
15
  let buffer = [];
11
16
  let flushTimer = null;
12
17
  let lastSeq = null;
18
+ let lastPersistedSeq = null;
19
+ let cursorCheckpointTimer = null;
20
+ /**
21
+ * Which `_cursor` row this process persists its stream position to.
22
+ *
23
+ * The relay's `subscribeRepos` seq and Jetstream's seq are different
24
+ * coordinate systems — resuming one from the other's value would either skip
25
+ * a swathe of the stream or replay from a nonsense offset. So is one Jetstream
26
+ * instance's seq against another's, which is why the key names the instance
27
+ * rather than the kind. Each source owns its own key so switching between them
28
+ * (or back) is safe.
29
+ */
30
+ let cursorKey = 'relay';
13
31
  const BATCH_SIZE = 100;
14
32
  const FLUSH_INTERVAL_MS = 500;
33
+ const CURSOR_CHECKPOINT_INTERVAL_MS = 5_000;
15
34
  let writesSinceRebuild = 0;
16
35
  let ftsRebuildInterval = 500;
17
36
  // Event buffer for DIDs mid-backfill
18
37
  const pendingBuffers = new Map();
19
38
  // Track in-flight backfills to avoid duplicates
20
39
  const backfillInFlight = new Set();
40
+ const backfillPromises = new Map();
21
41
  const pendingReschedule = new Set();
22
42
  // In-memory cache of repo status to avoid flooding the DB read queue
23
43
  const repoStatusCache = new Map();
@@ -27,29 +47,62 @@ let indexerSignalCollections;
27
47
  let indexerPinnedRepos = null;
28
48
  let indexerFetchTimeout;
29
49
  let indexerMaxRetries;
50
+ let indexerPlcUrl;
30
51
  let maxConcurrentBackfills = 3;
52
+ /**
53
+ * Flush the write buffer — apply all buffered puts and deletes in arrival
54
+ * order, update the relay cursor, run label rules on inserted records, and
55
+ * trigger FTS rebuilds when the write threshold is reached. Emits a wide event
56
+ * with batch stats.
57
+ */
31
58
  async function flushBuffer() {
32
59
  if (buffer.length === 0)
33
60
  return;
34
61
  const elapsed = timer();
35
62
  const batch = buffer.splice(0);
36
63
  let insertedCount = 0;
64
+ let deletedCount = 0;
37
65
  const errors = [];
38
66
  let cursorError;
39
67
  const inserted = [];
68
+ const applied = [];
69
+ // Strictly sequential: two writes to the same URI in one batch must land in
70
+ // the order they arrived, so nothing here may run concurrently.
40
71
  for (const item of batch) {
41
72
  try {
42
- await insertRecord(item.collection, item.uri, item.cid, item.authorDid, item.record);
43
- insertedCount++;
44
- inserted.push(item);
73
+ if (item.action === 'delete') {
74
+ await deleteRecord(item.collection, item.uri);
75
+ deletedCount++;
76
+ applied.push({
77
+ action: 'delete',
78
+ collection: item.collection,
79
+ uri: item.uri,
80
+ authorDid: item.authorDid,
81
+ record: null,
82
+ });
83
+ }
84
+ else {
85
+ await insertRecord(item.collection, item.uri, item.cid, item.authorDid, item.record);
86
+ insertedCount++;
87
+ inserted.push(item);
88
+ applied.push({
89
+ action: 'create',
90
+ collection: item.collection,
91
+ uri: item.uri,
92
+ authorDid: item.authorDid,
93
+ record: item.record,
94
+ });
95
+ }
45
96
  }
46
97
  catch (err) {
47
98
  errors.push(err.message);
48
99
  }
49
100
  }
50
101
  if (lastSeq !== null) {
102
+ const seq = lastSeq;
51
103
  try {
52
- await setCursor('relay', String(lastSeq));
104
+ await setCursor(cursorKey, String(seq));
105
+ lastPersistedSeq = seq;
53
106
  }
54
107
  catch (err) {
55
108
  cursorError = err.message;
@@ -65,6 +118,9 @@ async function flushBuffer() {
65
118
  value: item.record,
66
119
  }).catch(() => { });
67
120
  }
121
+ // Fire on-commit hooks for everything the batch applied, in the order it was
122
+ // applied (async, non-blocking)
123
+ fireOnCommitHooks(applied);
68
124
  // Aggregate collection counts and unique DIDs for wide event
69
125
  const collections = {};
70
126
  const dids = new Set();
@@ -75,6 +131,7 @@ async function flushBuffer() {
75
131
  emit('indexer', 'flush', {
76
132
  batch_size: batch.length,
77
133
  inserted_count: insertedCount,
134
+ deleted_count: deletedCount,
78
135
  error_count: errors.length,
79
136
  cursor_seq: lastSeq,
80
137
  duration_ms: elapsed(),
@@ -87,17 +144,39 @@ async function flushBuffer() {
87
144
  writesSinceRebuild += batch.length;
88
145
  if (writesSinceRebuild >= ftsRebuildInterval) {
89
146
  writesSinceRebuild = 0;
90
- rebuildAllIndexes([...indexerCollections]).catch(() => { });
147
+ // Skip periodic full rebuild for SQLite — it uses incremental FTS updates
148
+ const port = getDatabasePort();
149
+ if (port.dialect !== 'sqlite') {
150
+ rebuildAllIndexes([...indexerCollections]).catch(() => { });
151
+ }
91
152
  }
92
153
  }
154
+ /**
155
+ * Run a flush once every flush already queued has finished.
156
+ *
157
+ * Nothing awaits the flush a full batch triggers, and the interval timer can
158
+ * fire while that flush is still waiting on the database. Two flushes in flight
159
+ * hold disjoint batches but interleave their awaits, so a write in the later
160
+ * batch can reach the database before one in the earlier batch — which would
161
+ * give back exactly the cross-batch reordering the single buffer removes.
162
+ * Chaining them costs nothing on an idle indexer and keeps the queue global.
163
+ */
164
+ let flushChain = Promise.resolve();
165
+ function enqueueFlush() {
166
+ const next = flushChain.then(() => flushBuffer(), () => flushBuffer());
167
+ flushChain = next;
168
+ return next;
169
+ }
170
+ /** Schedule a flush after FLUSH_INTERVAL_MS if one isn't already pending. */
93
171
  function scheduleFlush() {
94
172
  if (flushTimer)
95
173
  return;
96
- flushTimer = setTimeout(async () => {
174
+ flushTimer = setTimeout(() => {
97
175
  flushTimer = null;
98
- await flushBuffer();
176
+ void enqueueFlush().catch(() => { });
99
177
  }, FLUSH_INTERVAL_MS);
100
178
  }
179
+ /** Add a write to the buffer. Flushes immediately if BATCH_SIZE is reached. */
101
180
  function bufferWrite(item) {
102
181
  buffer.push(item);
103
182
  if (buffer.length >= BATCH_SIZE) {
@@ -105,12 +184,185 @@ function bufferWrite(item) {
105
184
  clearTimeout(flushTimer);
106
185
  flushTimer = null;
107
186
  }
108
- flushBuffer();
187
+ void enqueueFlush().catch(() => { });
109
188
  }
110
189
  else {
111
190
  scheduleFlush();
112
191
  }
113
192
  }
193
+ /** Record the latest firehose sequence seen. Source of truth for cursor persistence and reconnect resume. */
194
+ export function noteSeq(seq) {
195
+ lastSeq = seq;
196
+ }
197
+ /** The highest seq this process has seen, or null before the first event. */
198
+ export function getLastSeq() {
199
+ return lastSeq;
200
+ }
201
+ /**
202
+ * Persist the latest firehose sequence when it has advanced past the stored
203
+ * cursor. Runs on a timer independent of the write path: an app whose
204
+ * collections rarely appear on the firehose never flushes a batch, so the
205
+ * flush-path cursor write alone leaves the stored cursor frozen — and a frozen
206
+ * cursor makes the relay replay its whole retention window at line rate
207
+ * (~135 GB/hour observed against bsky.network) on every boot and reconnect.
208
+ */
209
+ export async function checkpointCursor() {
210
+ if (lastSeq === null || lastSeq === lastPersistedSeq)
211
+ return;
212
+ const seq = lastSeq;
213
+ try {
214
+ await setCursor(cursorKey, String(seq));
215
+ lastPersistedSeq = seq;
216
+ }
217
+ catch (err) {
218
+ emit('indexer', 'cursor_checkpoint_error', { cursor_seq: seq, error: err.message });
219
+ }
220
+ }
221
+ /** Point cursor persistence at a stream's own `_cursor` row. See {@link cursorKey}. */
222
+ export function setCursorKey(key) {
223
+ cursorKey = key;
224
+ }
225
+ /**
226
+ * The cursor a reconnect should resume from: the latest seq this process has
227
+ * seen, falling back to the boot-time cursor before any message has arrived.
228
+ * Reusing the boot-time cursor on every reconnect would replay everything
229
+ * received since the process started.
230
+ */
231
+ export function resumeCursor(liveSeq, bootCursor) {
232
+ return liveSeq !== null ? String(liveSeq) : bootCursor;
233
+ }
234
+ /** Reset module cursor state between tests. */
235
+ export function _resetCursorStateForTests() {
236
+ lastSeq = null;
237
+ lastPersistedSeq = null;
238
+ cursorKey = 'relay';
239
+ }
240
+ /**
241
+ * Forget which repos this process is tracking.
242
+ *
243
+ * The status cache is deliberately process-global — it is what keeps the
244
+ * commit hot path off the database — and it outlives any table a test
245
+ * truncates. A suite that clears `_repos` between cases and does not clear
246
+ * this sees the second case behave as though the first one's repos were
247
+ * still known, which is how the seam between tracking and backfill went
248
+ * untested.
249
+ */
250
+ export function _resetRepoTrackingForTests() {
251
+ repoStatusCache.clear();
252
+ backfillInFlight.clear();
253
+ backfillPromises.clear();
254
+ pendingReschedule.clear();
255
+ pendingBuffers.clear();
256
+ }
257
+ /**
258
+ * Drain the write buffer instead of waiting out FLUSH_INTERVAL_MS. Lets
259
+ * end-to-end tests assert on rows immediately after feeding a frame — deletes
260
+ * included, since they are buffered alongside puts and so are covered by the
261
+ * same await.
262
+ */
263
+ export async function _flushForTests() {
264
+ if (flushTimer) {
265
+ clearTimeout(flushTimer);
266
+ flushTimer = null;
267
+ }
268
+ await enqueueFlush();
269
+ }
270
+ /**
271
+ * Auto-backfill a DID's repo when first seen on the firehose.
272
+ *
273
+ * Fetches the full repo via CAR export, inserts all records, then replays any
274
+ * firehose events that arrived during the backfill. Concurrency is capped at
275
+ * `maxConcurrentBackfills`. Failed backfills retry with exponential delay up
276
+ * to `maxRetries`.
277
+ */
278
+ /** Wait for a DID's backfill to complete if one is in flight. */
279
+ export function awaitBackfill(did) {
280
+ const entry = backfillPromises.get(did);
281
+ return entry ? entry.promise : Promise.resolve();
282
+ }
283
+ /**
284
+ * Track a repo no signal collection will ever point at.
285
+ *
286
+ * Backfill and the stream find repos by what they write into the signal
287
+ * collections. A writer in a followed space is wanted for another reason:
288
+ * their public profile is what puts a name and a face on everything they
289
+ * wrote there, and an app that only indexes the community's own records
290
+ * would render every member as a DID. So the space engine names them here,
291
+ * and an unknown one is backfilled like a repo the stream just surfaced.
292
+ * Idempotent and cheap: a repo already known is a map lookup.
293
+ */
294
+ let indexerReferences = [];
295
+ /** Follow a dot path into a record; `$rkey` names the record key itself. */
296
+ function referencedDid(record, rkey, field) {
297
+ if (field === '$rkey')
298
+ return rkey.startsWith('did:') ? rkey : null;
299
+ let cur = record;
300
+ for (const part of field.split('.')) {
301
+ if (!cur || typeof cur !== 'object')
302
+ return null;
303
+ cur = cur[part];
304
+ }
305
+ return typeof cur === 'string' && cur.startsWith('did:') ? cur : null;
306
+ }
307
+ /**
308
+ * Track every repo a record names, per the configured references.
309
+ *
310
+ * Called wherever a record enters the index — the stream, a backfill, a
311
+ * space sync — so a roster read any of those ways brings its members' repos
312
+ * with it.
313
+ */
314
+ export function noteReferencedRepos(collection, rkey, record) {
315
+ for (const ref of indexerReferences) {
316
+ if (ref.collection !== collection)
317
+ continue;
318
+ const did = referencedDid(record, rkey, ref.field);
319
+ if (did)
320
+ trackRepo(did);
321
+ }
322
+ }
323
+ /**
324
+ * Apply the references to what is already indexed.
325
+ *
326
+ * A reference fires as a record comes in. Rows indexed before the reference
327
+ * was configured — or before this instance had it — would otherwise never
328
+ * name their repos until the record was written again. Run once at boot;
329
+ * a table of a few thousand rows is a moment, and the roster is what these
330
+ * point at, not the firehose.
331
+ */
332
+ export async function sweepReferences() {
333
+ let named = 0;
334
+ for (const ref of indexerReferences) {
335
+ let rows;
336
+ try {
337
+ rows = await unfilteredQuerySQL(`SELECT * FROM "${ref.collection}"`);
338
+ }
339
+ catch {
340
+ continue; // no table for this collection on this instance
341
+ }
342
+ for (const raw of rows) {
343
+ const row = reshapeRow(raw);
344
+ if (!row)
345
+ continue;
346
+ const did = referencedDid(row.value, rkeyOf(row.uri), ref.field);
347
+ if (!did)
348
+ continue;
349
+ named++;
350
+ trackRepo(did);
351
+ }
352
+ }
353
+ if (named > 0)
354
+ emit('indexer', 'references_swept', { named });
355
+ return named;
356
+ }
357
+ export function trackRepo(did) {
358
+ if (indexerPinnedRepos && !indexerPinnedRepos.has(did))
359
+ return;
360
+ const status = repoStatusCache.get(did);
361
+ if (status && status !== 'unknown')
362
+ return;
363
+ repoStatusCache.set(did, 'pending');
364
+ void triggerAutoBackfill(did);
365
+ }
114
366
  export async function triggerAutoBackfill(did, attempt = 0) {
115
367
  if (backfillInFlight.has(did))
116
368
  return;
@@ -126,6 +378,13 @@ export async function triggerAutoBackfill(did, attempt = 0) {
126
378
  }
127
379
  backfillInFlight.add(did);
128
380
  pendingBuffers.set(did, []);
381
+ if (!backfillPromises.has(did)) {
382
+ let resolveBackfill;
383
+ const promise = new Promise((r) => {
384
+ resolveBackfill = r;
385
+ });
386
+ backfillPromises.set(did, { promise, resolve: resolveBackfill });
387
+ }
129
388
  if (attempt === 0)
130
389
  await setRepoStatus(did, 'pending');
131
390
  const elapsed = timer();
@@ -146,7 +405,14 @@ export async function triggerAutoBackfill(did, attempt = 0) {
146
405
  backfillInFlight.delete(did);
147
406
  for (const item of buffered) {
148
407
  try {
149
- await insertRecord(item.collection, item.uri, item.cid, item.authorDid, item.record);
408
+ if (item.action === 'delete') {
409
+ // A delete that arrived mid-backfill has to be replayed after the CAR
410
+ // export lands, or the export's snapshot of the record outlives it.
411
+ await deleteRecord(item.collection, item.uri);
412
+ }
413
+ else {
414
+ await insertRecord(item.collection, item.uri, item.cid, item.authorDid, item.record);
415
+ }
150
416
  }
151
417
  catch {
152
418
  replayErrors++;
@@ -165,6 +431,12 @@ export async function triggerAutoBackfill(did, attempt = 0) {
165
431
  error,
166
432
  retry_count: currentRetryCount,
167
433
  });
434
+ // Resolve awaiting callers (e.g. on-login hooks)
435
+ const entry = backfillPromises.get(did);
436
+ if (entry) {
437
+ entry.resolve();
438
+ backfillPromises.delete(did);
439
+ }
168
440
  if (status === 'error' && currentRetryCount < indexerMaxRetries) {
169
441
  const delaySecs = Math.min(currentRetryCount * 60, 3600);
170
442
  const delayMs = Math.max(delaySecs, 60) * 1000;
@@ -173,37 +445,26 @@ export async function triggerAutoBackfill(did, attempt = 0) {
173
445
  }, delayMs);
174
446
  }
175
447
  }
176
- // Periodic memory diagnostics
177
- function startMemoryDiagnostics() {
178
- setInterval(() => {
179
- const mem = process.memoryUsage();
180
- let pendingBufferItems = 0;
181
- for (const [, items] of pendingBuffers) {
182
- pendingBufferItems += items.length;
183
- }
184
- emit('diagnostics', 'memory', {
185
- heap_used_mb: Math.round(mem.heapUsed / 1024 / 1024),
186
- heap_total_mb: Math.round(mem.heapTotal / 1024 / 1024),
187
- rss_mb: Math.round(mem.rss / 1024 / 1024),
188
- external_mb: Math.round(mem.external / 1024 / 1024),
189
- array_buffers_mb: Math.round(mem.arrayBuffers / 1024 / 1024),
190
- write_buffer_len: buffer.length,
191
- pending_buffer_dids: pendingBuffers.size,
192
- pending_buffer_items: pendingBufferItems,
193
- backfill_in_flight: backfillInFlight.size,
194
- repo_status_cache_size: repoStatusCache.size,
195
- });
196
- }, 30_000);
197
- }
198
- export async function startIndexer(opts) {
199
- const { relayUrl, collections, cursor, fetchTimeout } = opts;
448
+ /**
449
+ * Connect to the AT Protocol relay firehose and begin indexing.
450
+ *
451
+ * Opens a WebSocket to `subscribeRepos`, processes commit messages synchronously
452
+ * on the event loop to minimize backpressure, and batches writes through
453
+ * {@link flushBuffer}. New DIDs trigger auto-backfill via {@link triggerAutoBackfill}.
454
+ * Reconnects automatically on disconnect after a 3s delay.
455
+ *
456
+ * @returns The WebSocket connection (for shutdown coordination)
457
+ */
458
+ export async function configureIndexer(opts) {
200
459
  if (opts.ftsRebuildInterval != null)
201
460
  ftsRebuildInterval = opts.ftsRebuildInterval;
202
- indexerCollections = collections;
203
- indexerSignalCollections = opts.signalCollections || collections;
461
+ indexerCollections = opts.collections;
462
+ indexerSignalCollections = opts.signalCollections || opts.collections;
463
+ indexerReferences = opts.references ?? [];
204
464
  indexerPinnedRepos = opts.pinnedRepos || null;
205
- indexerFetchTimeout = fetchTimeout;
465
+ indexerFetchTimeout = opts.fetchTimeout;
206
466
  indexerMaxRetries = opts.maxRetries;
467
+ indexerPlcUrl = opts.plcUrl;
207
468
  maxConcurrentBackfills = opts.parallelism ?? 3;
208
469
  // Pre-populate repo status cache from DB so non-signal updates
209
470
  // (e.g. profile changes) are processed for already-tracked DIDs
@@ -214,7 +475,18 @@ export async function startIndexer(opts) {
214
475
  }
215
476
  log(`[indexer] Warmed repo status cache with ${statuses.length} entries`);
216
477
  }
217
- startMemoryDiagnostics();
478
+ // Checkpoint the cursor on a timer regardless of write activity (see
479
+ // checkpointCursor). Guarded so reconnects don't stack intervals; unref'd so
480
+ // it never keeps the process alive.
481
+ if (!cursorCheckpointTimer) {
482
+ cursorCheckpointTimer = setInterval(() => void checkpointCursor(), CURSOR_CHECKPOINT_INTERVAL_MS);
483
+ cursorCheckpointTimer.unref?.();
484
+ }
485
+ }
486
+ export async function startIndexer(opts) {
487
+ const { relayUrl, collections, cursor } = opts;
488
+ setCursorKey('relay');
489
+ await configureIndexer(opts);
218
490
  let wsUrl = `${relayUrl}/xrpc/com.atproto.sync.subscribeRepos`;
219
491
  if (cursor) {
220
492
  wsUrl += `?cursor=${cursor}`;
@@ -232,41 +504,234 @@ export async function startIndexer(opts) {
232
504
  const bytes = new Uint8Array(event.data);
233
505
  processMessage(bytes, collections);
234
506
  }
235
- catch {
236
- // Skip unparseable firehose messages silently
507
+ catch (err) {
508
+ emit('indexer', 'decode_error', { error: err instanceof Error ? err.message : String(err) });
237
509
  }
238
510
  });
239
511
  ws.addEventListener('open', () => log('[indexer] Connected to relay'));
240
512
  ws.addEventListener('close', () => {
241
513
  log('[indexer] Disconnected, reconnecting in 3s...');
242
- setTimeout(() => startIndexer(opts), 3000);
514
+ setTimeout(() => startIndexer({ ...opts, cursor: resumeCursor(lastSeq, opts.cursor) }), 3000);
243
515
  });
244
516
  return ws;
245
517
  }
246
- function processMessage(bytes, collections) {
247
- const header = cborDecode(bytes, 0);
248
- const body = cborDecode(bytes, header.offset);
249
- if (header.value.op !== 1 || header.value.t !== '#commit')
518
+ /** The `_cursor` row an auxiliary firehose persists its position to. */
519
+ export function auxCursorKey(relayUrl) {
520
+ return `relay:${relayUrl}`;
521
+ }
522
+ /**
523
+ * The `_cursor` row a Jetstream instance persists its position to.
524
+ *
525
+ * Named for the instance, because a Jetstream sequence means nothing on
526
+ * another one. Pointed at a second instance — a region swap, an outage
527
+ * worked around — a shared row would hand over a number from somewhere else,
528
+ * and the stream would resume at whatever that happens to address there:
529
+ * no error, no refusal, just a silent jump past whatever fell in between.
530
+ */
531
+ export function jetstreamCursorKey(jetstreamUrl) {
532
+ return `jetstream:${jetstreamUrl}`;
533
+ }
534
+ /**
535
+ * Tail a second `subscribeRepos` alongside the primary stream.
536
+ *
537
+ * A relay is one coordinate system; a PDS tailed directly is another. Nothing
538
+ * below the wire cares which socket a frame arrived on — `processMessage`
539
+ * decodes it and `applyCommit` indexes it — so the only state an extra source
540
+ * needs of its own is a seq and a cursor row. Both live in this closure,
541
+ * keyed by URL, so an aux stream never advances (or resumes from) the primary
542
+ * cursor. Use this when a repo's PDS is not behind the relay being tailed —
543
+ * a self-hosted network, a dev stack with more than one PDS — rather than
544
+ * standing up a relay just to merge two streams.
545
+ *
546
+ * Must be called after {@link configureIndexer} (or {@link startIndexer}),
547
+ * which owns the shared indexer configuration.
548
+ */
549
+ export function startAuxIndexer(opts) {
550
+ const { relayUrl, collections } = opts;
551
+ const cursorKey = auxCursorKey(relayUrl);
552
+ let seq = null;
553
+ let persistedSeq = null;
554
+ const checkpoint = async () => {
555
+ if (seq === null || seq === persistedSeq)
556
+ return;
557
+ const s = seq;
558
+ try {
559
+ await setCursor(cursorKey, String(s));
560
+ persistedSeq = s;
561
+ }
562
+ catch (err) {
563
+ emit('indexer', 'cursor_checkpoint_error', { source: relayUrl, cursor_seq: s, error: err.message });
564
+ }
565
+ };
566
+ const timer = setInterval(() => void checkpoint(), CURSOR_CHECKPOINT_INTERVAL_MS);
567
+ timer.unref?.();
568
+ const connect = (cursor) => {
569
+ let wsUrl = `${relayUrl}/xrpc/com.atproto.sync.subscribeRepos`;
570
+ if (cursor) {
571
+ wsUrl += `?cursor=${cursor}`;
572
+ log(`[indexer:aux] Resuming ${relayUrl} from cursor ${cursor}`);
573
+ }
574
+ log(`[indexer:aux] Connecting to ${relayUrl}...`);
575
+ const ws = new WebSocket(wsUrl);
576
+ ws.binaryType = 'arraybuffer';
577
+ ws.addEventListener('message', (event) => {
578
+ try {
579
+ if (!(event.data instanceof ArrayBuffer))
580
+ return;
581
+ processMessage(new Uint8Array(event.data), collections, (s) => {
582
+ seq = s;
583
+ });
584
+ }
585
+ catch (err) {
586
+ emit('indexer', 'decode_error', { source: relayUrl, error: err instanceof Error ? err.message : String(err) });
587
+ }
588
+ });
589
+ ws.addEventListener('open', () => log(`[indexer:aux] Connected to ${relayUrl}`));
590
+ ws.addEventListener('close', () => {
591
+ log(`[indexer:aux] Disconnected from ${relayUrl}, reconnecting in 3s...`);
592
+ setTimeout(() => connect(resumeCursor(seq, opts.cursor)), 3000);
593
+ });
594
+ return ws;
595
+ };
596
+ return connect(opts.cursor);
597
+ }
598
+ /**
599
+ * Handle a `#identity` firehose event for a DID. The `handle` field on the
600
+ * event is optional per the lexicon, and some emitters omit it (signalling
601
+ * "re-resolve"). When absent, we re-resolve from the PLC directory so handle
602
+ * renames propagate even when the relay payload is sparse.
603
+ *
604
+ * Only updates DIDs we already track (present in repoStatusCache) to avoid
605
+ * writing rows for the entire network.
606
+ */
607
+ export async function handleIdentityEvent(did, payloadHandle) {
608
+ if (!repoStatusCache.has(did))
250
609
  return;
251
- if (!body.value.blocks || !body.value.ops)
610
+ let handle = payloadHandle;
611
+ const payloadHadHandle = handle !== undefined;
612
+ if (!handle) {
613
+ try {
614
+ // Bound the PLC fetch so a slow plc.directory can't pile up unbounded
615
+ // promises during an identity-event burst (fire-and-forget caller).
616
+ const res = await fetch(`${indexerPlcUrl}/${did}`, {
617
+ signal: AbortSignal.timeout(indexerFetchTimeout * 1000),
618
+ });
619
+ if (res.ok) {
620
+ const doc = (await res.json());
621
+ // First at:// entry is the canonical handle (per @atproto/identity convention)
622
+ const aka = doc.alsoKnownAs?.find((u) => u.startsWith('at://'));
623
+ handle = aka ? aka.slice('at://'.length) : undefined;
624
+ }
625
+ else {
626
+ emit('indexer', 'identity_resolve_error', { did, status: res.status });
627
+ }
628
+ }
629
+ catch (err) {
630
+ emit('indexer', 'identity_resolve_error', {
631
+ did,
632
+ error: err instanceof Error ? err.message : String(err),
633
+ });
634
+ }
635
+ }
636
+ if (!handle) {
637
+ emit('indexer', 'identity_no_handle', { did, payload_had_handle: payloadHadHandle });
252
638
  return;
253
- // Track sequence number for cursor
254
- if (body.value.seq)
255
- lastSeq = body.value.seq;
256
- const did = body.value.repo;
257
- if (!did)
639
+ }
640
+ try {
641
+ await updateRepoHandle(did, handle);
642
+ emit('indexer', 'identity_handle_update', { did, handle, payload_had_handle: payloadHadHandle });
643
+ }
644
+ catch (err) {
645
+ emit('indexer', 'identity_update_error', {
646
+ did,
647
+ handle,
648
+ error: err instanceof Error ? err.message : String(err),
649
+ });
650
+ }
651
+ }
652
+ /**
653
+ * Handle an `#account` event: the network saying an account is active again,
654
+ * or is not — deactivated, suspended, taken down by its host, or deleted.
655
+ *
656
+ * - deleted: every record it holds here is removed, and it is marked
657
+ * `deleted`.
658
+ * - deactivated, suspended, taken down by its host: marked `deactivated`. Its
659
+ * records stay, and no read serves them (see HIDDEN_REPO_STATUSES), so an
660
+ * account that comes back is whole again at once.
661
+ * - active again, after either: marked `pending` and backfilled, since it may
662
+ * have changed while it was gone.
663
+ *
664
+ * An admin's own takedown here wins over all of it: only reverse-takedown
665
+ * lifts that. Statuses that say nothing about the account itself (a relay's
666
+ * `desynchronized` or `throttled`) change nothing. Like identity events, only
667
+ * DIDs already tracked are touched.
668
+ */
669
+ export async function handleAccountEvent(did, active, status) {
670
+ if (!repoStatusCache.has(did))
671
+ return;
672
+ try {
673
+ const current = await getRepoStatus(did);
674
+ if (current === null || current === 'takendown')
675
+ return;
676
+ if (!active && status === 'deleted') {
677
+ const removed = await purgeRepoRecords(did);
678
+ await setRepoStatus(did, 'deleted');
679
+ repoStatusCache.set(did, 'deleted');
680
+ emit('indexer', 'account_deleted', { did, removed });
681
+ return;
682
+ }
683
+ if (!active && status && INACTIVE_ACCOUNT_STATUSES.has(status)) {
684
+ if (current === 'deactivated')
685
+ return;
686
+ await setRepoStatus(did, 'deactivated');
687
+ repoStatusCache.set(did, 'deactivated');
688
+ emit('indexer', 'account_deactivated', { did, status });
689
+ return;
690
+ }
691
+ if (active && (current === 'deactivated' || current === 'deleted')) {
692
+ await setRepoStatus(did, 'pending');
693
+ repoStatusCache.set(did, 'pending');
694
+ emit('indexer', 'account_reactivated', { did, was: current });
695
+ void triggerAutoBackfill(did);
696
+ }
697
+ }
698
+ catch (err) {
699
+ emit('indexer', 'account_event_error', {
700
+ did,
701
+ error: err instanceof Error ? err.message : String(err),
702
+ });
703
+ }
704
+ }
705
+ /** `#account` statuses that mean the account itself is not there. */
706
+ const INACTIVE_ACCOUNT_STATUSES = new Set(['deactivated', 'suspended', 'takendown']);
707
+ /**
708
+ * Whether a collection's records may be written from network data.
709
+ *
710
+ * Private collections are AppView-authoritative: nothing on the network may
711
+ * write or delete their rows, so stream ops naming them are spoofed by
712
+ * definition and must be dropped regardless of which source delivered them.
713
+ */
714
+ export function isIndexableCollection(collection, collections) {
715
+ return collections.has(collection) && !isPrivateCollection(collection);
716
+ }
717
+ /**
718
+ * Apply a repo's commit ops to the index.
719
+ *
720
+ * Wire-agnostic: the relay path reaches here after CBOR/CAR decoding, the
721
+ * Jetstream path after parsing JSON. Callers must have already filtered `ops`
722
+ * through {@link isIndexableCollection}.
723
+ *
724
+ * Handles auto-backfill signalling, buffering for DIDs mid-backfill, lexicon
725
+ * validation, and delete/put routing.
726
+ */
727
+ export function applyCommit(did, ops) {
728
+ if (ops.length === 0)
258
729
  return;
259
730
  // When repos are pinned, only process events from those DIDs
260
731
  if (indexerPinnedRepos && !indexerPinnedRepos.has(did))
261
732
  return;
262
- // Check if any ops in this commit are for collections we care about
263
- const relevantOps = body.value.ops.filter((op) => collections.has(op.path.split('/')[0]));
264
- if (relevantOps.length === 0)
265
- return;
266
- // Copy blocks out of the original buffer before it can be GC'd
267
- const { blocks } = parseCarFrame(new Uint8Array(body.value.blocks));
268
733
  // Only auto-backfill when we see activity in a signal collection
269
- const hasSignalOp = relevantOps.some((op) => indexerSignalCollections.has(op.path.split('/')[0]));
734
+ const hasSignalOp = ops.some((op) => indexerSignalCollections.has(op.collection));
270
735
  // Use in-memory cache only — never hit DB from the hot path.
271
736
  // Unknown DIDs stay unknown until backfill or auto-backfill discovers them.
272
737
  // The cache is populated by triggerAutoBackfill and setRepoStatus calls.
@@ -275,7 +740,7 @@ function processMessage(bytes, collections) {
275
740
  if (cachedStatus === undefined) {
276
741
  repoStatusCache.set(did, 'unknown');
277
742
  }
278
- if (hasSignalOp && (!indexerPinnedRepos || indexerPinnedRepos.has(did))) {
743
+ if (hasSignalOp) {
279
744
  if (repoStatus === null && backfillInFlight.size < maxConcurrentBackfills) {
280
745
  repoStatusCache.set(did, 'pending');
281
746
  triggerAutoBackfill(did);
@@ -286,43 +751,106 @@ function processMessage(bytes, collections) {
286
751
  }
287
752
  }
288
753
  // For non-signal ops (e.g. profile updates), only process if this DID is already tracked
289
- if (!hasSignalOp) {
290
- if (repoStatus === null)
291
- return;
754
+ if (!hasSignalOp && repoStatus === null)
755
+ return;
756
+ /** Queue a write behind anything already queued for this DID. */
757
+ const enqueue = (item) => {
758
+ // If DID is mid-backfill, buffer instead of writing directly
759
+ if (pendingBuffers.has(did))
760
+ pendingBuffers.get(did).push(item);
761
+ else
762
+ bufferWrite(item);
763
+ };
764
+ for (const op of ops) {
765
+ const uri = `at://${did}/${op.collection}/${op.rkey}`;
766
+ if (op.action === 'delete') {
767
+ // Buffered, not applied here: see {@link WriteBuffer}. The on-commit hook
768
+ // fires from the flush too, so a handler never sees a delete announced
769
+ // before the row is actually gone.
770
+ enqueue({ action: 'delete', collection: op.collection, uri, authorDid: did });
771
+ continue;
772
+ }
773
+ const record = op.record;
774
+ if (!op.cid || !record)
775
+ continue;
776
+ if (record.$type !== op.collection)
777
+ continue;
778
+ const validationError = validateRecord(getLexiconArray(), op.collection, record);
779
+ if (validationError) {
780
+ emit('indexer', 'validation_skip', {
781
+ uri,
782
+ collection: op.collection,
783
+ path: validationError.path,
784
+ error: validationError.message,
785
+ });
786
+ continue;
787
+ }
788
+ noteReferencedRepos(op.collection, op.rkey, record);
789
+ enqueue({ action: 'put', collection: op.collection, uri, cid: op.cid, authorDid: did, record });
292
790
  }
791
+ }
792
+ /**
793
+ * Process a single firehose message. Decodes the CBOR header/body, filters
794
+ * for relevant collections, validates records against lexicons, and routes
795
+ * writes to the buffer (or pending buffer if the DID is mid-backfill).
796
+ */
797
+ export function processMessage(bytes, collections, onSeq = noteSeq) {
798
+ const header = cborDecode(bytes, 0);
799
+ const body = cborDecode(bytes, header.offset);
800
+ // Handle identity events (handle changes). Fire-and-forget — keeps
801
+ // processMessage synchronous so the WS event loop drains without backpressure.
802
+ if (header.value.t === '#identity') {
803
+ const did = typeof body.value.did === 'string' ? body.value.did : undefined;
804
+ const handle = typeof body.value.handle === 'string' ? body.value.handle : undefined;
805
+ if (did)
806
+ handleIdentityEvent(did, handle);
807
+ return;
808
+ }
809
+ // Account status changes (deactivated, deleted, back again). Fire-and-forget,
810
+ // like identity.
811
+ if (header.value.t === '#account') {
812
+ const did = typeof body.value.did === 'string' ? body.value.did : undefined;
813
+ const status = typeof body.value.status === 'string' ? body.value.status : undefined;
814
+ if (did)
815
+ void handleAccountEvent(did, body.value.active === true, status);
816
+ return;
817
+ }
818
+ if (header.value.op !== 1 || header.value.t !== '#commit')
819
+ return;
820
+ if (!body.value.blocks || !body.value.ops)
821
+ return;
822
+ // Track sequence number for cursor
823
+ if (body.value.seq)
824
+ onSeq(body.value.seq);
825
+ const did = body.value.repo;
826
+ if (!did)
827
+ return;
828
+ // Check if any ops in this commit are for collections we care about, before
829
+ // paying for the CAR parse below.
830
+ const relevantOps = body.value.ops.filter((op) => isIndexableCollection(op.path.split('/')[0], collections));
831
+ if (relevantOps.length === 0)
832
+ return;
833
+ // Copy blocks out of the original buffer before it can be GC'd
834
+ const { blocks } = parseCarFrame(new Uint8Array(body.value.blocks));
835
+ const ops = [];
293
836
  for (const op of relevantOps) {
294
837
  const collection = op.path.split('/')[0];
295
- const uri = `at://${did}/${op.path}`;
838
+ const rkey = op.path.split('/').slice(1).join('/');
296
839
  if (op.action === 'delete') {
297
- deleteRecord(collection, uri);
840
+ ops.push({ action: 'delete', collection, rkey });
298
841
  continue;
299
842
  }
300
- for (const [cid, data] of blocks) {
301
- try {
302
- const { value: record } = cborDecode(data);
303
- if (record?.$type === collection) {
304
- const validationError = validateRecord(getLexiconArray(), collection, record);
305
- if (validationError) {
306
- emit('indexer', 'validation_skip', {
307
- uri,
308
- collection,
309
- path: validationError.path,
310
- error: validationError.message,
311
- });
312
- break;
313
- }
314
- const item = { collection, uri, cid, authorDid: did, record };
315
- // If DID is mid-backfill, buffer instead of writing directly
316
- if (pendingBuffers.has(did)) {
317
- pendingBuffers.get(did).push(item);
318
- }
319
- else {
320
- bufferWrite(item);
321
- }
322
- break;
323
- }
324
- }
325
- catch { }
843
+ const opCid = typeof op.cid === 'string' ? op.cid : op.cid?.$link;
844
+ if (!opCid)
845
+ continue;
846
+ const data = blocks.get(opCid);
847
+ if (!data)
848
+ continue;
849
+ try {
850
+ const { value: record } = cborDecode(data);
851
+ ops.push({ action: op.action === 'update' ? 'update' : 'create', collection, rkey, cid: opCid, record });
326
852
  }
853
+ catch { }
327
854
  }
855
+ applyCommit(did, ops);
328
856
  }