@hatk/hatk 0.0.1-alpha.9 → 0.0.1-alpha.90

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