@prosopo/database 3.15.19 → 3.15.21

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 (38) hide show
  1. package/.turbo/turbo-build$colon$cjs.log +20 -17
  2. package/.turbo/turbo-build$colon$tsc.log +16 -16
  3. package/.turbo/turbo-build.log +21 -18
  4. package/CHANGELOG.md +24 -0
  5. package/dist/_virtual/_rolldown/runtime.js +3 -0
  6. package/dist/base/index.js +1 -4
  7. package/dist/base/mongo.js +133 -137
  8. package/dist/base/mongoMemory.js +21 -21
  9. package/dist/cjs/_virtual/_rolldown/runtime.cjs +23 -0
  10. package/dist/cjs/base/index.cjs +4 -6
  11. package/dist/cjs/base/mongo.cjs +140 -143
  12. package/dist/cjs/base/mongoMemory.cjs +22 -22
  13. package/dist/cjs/databases/captcha.cjs +220 -256
  14. package/dist/cjs/databases/centralDbStreamer.cjs +148 -170
  15. package/dist/cjs/databases/client.cjs +46 -62
  16. package/dist/cjs/databases/index.cjs +19 -19
  17. package/dist/cjs/databases/provider.cjs +1827 -2251
  18. package/dist/cjs/index.cjs +25 -23
  19. package/dist/cjs/mongooseOptions.cjs +59 -58
  20. package/dist/cjs/redisCache.cjs +432 -474
  21. package/dist/databases/captcha.d.ts.map +1 -1
  22. package/dist/databases/captcha.js +217 -253
  23. package/dist/databases/captcha.js.map +1 -1
  24. package/dist/databases/centralDbStreamer.js +147 -169
  25. package/dist/databases/client.js +44 -60
  26. package/dist/databases/index.js +10 -14
  27. package/dist/databases/provider.d.ts +4 -4
  28. package/dist/databases/provider.d.ts.map +1 -1
  29. package/dist/databases/provider.js +1823 -2247
  30. package/dist/databases/provider.js.map +1 -1
  31. package/dist/index.js +9 -18
  32. package/dist/mongooseOptions.js +59 -59
  33. package/dist/redisCache.js +432 -474
  34. package/dist/tests/integration/saveCaptchasSessionUpsert.integration.test.d.ts +2 -0
  35. package/dist/tests/integration/saveCaptchasSessionUpsert.integration.test.d.ts.map +1 -0
  36. package/dist/tests/integration/saveCaptchasSessionUpsert.integration.test.js +64 -0
  37. package/dist/tests/integration/saveCaptchasSessionUpsert.integration.test.js.map +1 -0
  38. package/package.json +14 -14
@@ -1,476 +1,434 @@
1
- const BIGINT_TAG = "__bigint__:";
2
- const bigIntReplacer = (_key, value) => "bigint" === typeof value ? `${BIGINT_TAG}${value.toString()}` : value;
3
- const bigIntReviver = (_key, value) => "string" === typeof value && value.startsWith(BIGINT_TAG) ? BigInt(value.slice(BIGINT_TAG.length)) : value;
4
- const SESSION_KEY_PATTERNS = [
5
- "cache:session:*",
6
- "writeq:session:*",
7
- "writeq:session:pending"
1
+ //#region src/redisCache.ts
2
+ var BIGINT_TAG = "__bigint__:";
3
+ /** JSON replacer that tags BigInt values so they can be restored by bigIntReviver. */
4
+ var bigIntReplacer = (_key, value) => "bigint" === typeof value ? `${BIGINT_TAG}${value.toString()}` : value;
5
+ /** JSON reviver that restores tagged BigInt values produced by bigIntReplacer. */
6
+ var bigIntReviver = (_key, value) => "string" === typeof value && value.startsWith(BIGINT_TAG) ? BigInt(value.slice(11)) : value;
7
+ var SESSION_KEY_PATTERNS = [
8
+ "cache:session:*",
9
+ "writeq:session:*",
10
+ "writeq:session:pending"
8
11
  ];
9
- class RedisWriteQueue {
10
- constructor(connection, logger) {
11
- this.flushTimer = null;
12
- this.flushCallback = null;
13
- this.connection = connection;
14
- this.logger = logger;
15
- }
16
- async getClient() {
17
- if (!this.connection.isReady()) {
18
- return null;
19
- }
20
- try {
21
- return await this.connection.getClient();
22
- } catch {
23
- return null;
24
- }
25
- }
26
- // ── Session read cache ──────────────────────────────────────────────
27
- /**
28
- * Cache a session record in Redis for fast lookups, reducing MongoDB reads.
29
- */
30
- async cacheSession(sessionId, sessionData, ttlSeconds = 86400) {
31
- const client = await this.getClient();
32
- if (!client) {
33
- return false;
34
- }
35
- try {
36
- const key = `cache:session:${sessionId}`;
37
- await client.set(key, JSON.stringify(sessionData, bigIntReplacer), {
38
- EX: ttlSeconds
39
- });
40
- return true;
41
- } catch (error) {
42
- this.logger.warn(() => ({
43
- msg: "Failed to cache session in Redis",
44
- err: error,
45
- sessionId
46
- }));
47
- return false;
48
- }
49
- }
50
- /**
51
- * Retrieve a cached session record from Redis.
52
- */
53
- async getCachedSession(sessionId) {
54
- const client = await this.getClient();
55
- if (!client) {
56
- return null;
57
- }
58
- try {
59
- const key = `cache:session:${sessionId}`;
60
- const data = await client.get(key);
61
- if (!data) {
62
- return null;
63
- }
64
- return JSON.parse(data, bigIntReviver);
65
- } catch (error) {
66
- this.logger.warn(() => ({
67
- msg: "Failed to get cached session from Redis",
68
- err: error,
69
- sessionId
70
- }));
71
- return null;
72
- }
73
- }
74
- /**
75
- * Patch the cached session in place — read the existing entry, shallow-
76
- * merge the provided updates, and write it back. No-op on cache miss so
77
- * the next read repopulates from Mongo. Mirrors the field-level Mongo
78
- * patch done by `db.updateSessionRecord`; callers invoke both to keep
79
- * Redis consistent with the DB after every in-request write.
80
- */
81
- async patchCachedSession(sessionId, updates, ttlSeconds = 86400) {
82
- const existing = await this.getCachedSession(sessionId);
83
- if (!existing) return false;
84
- return this.cacheSession(
85
- sessionId,
86
- { ...existing, ...updates, lastUpdatedTimestamp: /* @__PURE__ */ new Date() },
87
- ttlSeconds
88
- );
89
- }
90
- /**
91
- * First-hop-wins SIMD attach on the cache — mirrors the atomic Mongo
92
- * `$ifNull` pipeline update in `db.recordSessionSimdReadingsIfAbsent`.
93
- * Reads the cache; if it doesn't already carry `simdReadings`, merges
94
- * the new readings + stage. No-op on cache miss or when readings are
95
- * already present.
96
- */
97
- async patchCachedSimdReadingsIfAbsent(sessionId, readings, stage, ttlSeconds = 86400) {
98
- const existing = await this.getCachedSession(sessionId);
99
- if (!existing) return false;
100
- if (existing.simdReadings) return false;
101
- return this.cacheSession(
102
- sessionId,
103
- {
104
- ...existing,
105
- simdReadings: readings,
106
- simdReadingsStage: stage,
107
- lastUpdatedTimestamp: /* @__PURE__ */ new Date()
108
- },
109
- ttlSeconds
110
- );
111
- }
112
- /**
113
- * Invalidate a cached session when it's updated.
114
- */
115
- async invalidateCachedSession(sessionId) {
116
- const client = await this.getClient();
117
- if (!client) {
118
- return;
119
- }
120
- try {
121
- await client.del(`cache:session:${sessionId}`);
122
- } catch (error) {
123
- this.logger.warn(() => ({
124
- msg: "Failed to invalidate cached session in Redis",
125
- err: error,
126
- sessionId
127
- }));
128
- }
129
- }
130
- /**
131
- * Invalidate the hash → sessionId mapping used by /frictionless for
132
- * dedup. Must be called alongside `invalidateCachedSession` when a
133
- * session is consumed, otherwise the hash mapping keeps resolving to
134
- * a dead sessionId for the remainder of its 1-hour TTL.
135
- */
136
- async invalidateCachedSessionByHash(userSitekeyIpHash) {
137
- const client = await this.getClient();
138
- if (!client) {
139
- return;
140
- }
141
- try {
142
- await client.del(`cache:session:hash:${userSitekeyIpHash}`);
143
- } catch (error) {
144
- this.logger.warn(() => ({
145
- msg: "Failed to invalidate cached session hash in Redis",
146
- err: error,
147
- userSitekeyIpHash
148
- }));
149
- }
150
- }
151
- // ── Frictionless session deduplication cache ────────────────────────
152
- /**
153
- * Cache a session lookup by userSitekeyIpHash for frictionless deduplication.
154
- * Extends the effective TTL of the cached session, reducing duplicate
155
- * session creation under concurrent requests for the same user+site+IP.
156
- */
157
- async cacheSessionByHash(userSitekeyIpHash, sessionId, ttlSeconds = 3600) {
158
- const client = await this.getClient();
159
- if (!client) {
160
- return false;
161
- }
162
- try {
163
- const key = `cache:session:hash:${userSitekeyIpHash}`;
164
- await client.set(key, sessionId, { EX: ttlSeconds });
165
- return true;
166
- } catch (error) {
167
- this.logger.warn(() => ({
168
- msg: "Failed to cache session hash in Redis",
169
- err: error,
170
- userSitekeyIpHash
171
- }));
172
- return false;
173
- }
174
- }
175
- /**
176
- * Get cached sessionId by userSitekeyIpHash for frictionless deduplication.
177
- */
178
- async getCachedSessionByHash(userSitekeyIpHash) {
179
- const client = await this.getClient();
180
- if (!client) {
181
- return null;
182
- }
183
- try {
184
- const key = `cache:session:hash:${userSitekeyIpHash}`;
185
- return await client.get(key);
186
- } catch (error) {
187
- this.logger.warn(() => ({
188
- msg: "Failed to get cached session hash from Redis",
189
- err: error,
190
- userSitekeyIpHash
191
- }));
192
- return null;
193
- }
194
- }
195
- /**
196
- * Cache an origin → escalation sessionId mapping for the post-PoW
197
- * escalation flow.
198
- *
199
- * Background: when the routing machine returns image/puzzle from the
200
- * postPow phase, `buildEscalation` (`api/captcha/submitPoWCaptchaSolution.ts`)
201
- * mints a new session with a fresh `sessionId` and returns it on the
202
- * `escalation` field. A widget that handles the escalation cleanly
203
- * mounts the next captcha with the new sessionId. But there are
204
- * several real-world paths where the widget keeps using the original
205
- * sessionId for the follow-up `/captcha/{type}` request — bundled SDK
206
- * versions that predate the escalation handler, dapps that hand-roll
207
- * the wrapper, network-glitch retries, or browser-tab races. The
208
- * original session has been consumed and soft-deleted by the
209
- * preceding `/captcha/pow`, so the follow-up gets
210
- * `CAPTCHA.NO_SESSION_FOUND` and the user sees an inline error → FAQ.
211
- *
212
- * This mapping lets `isValidRequest` resolve the original sessionId
213
- * forward to the live escalation session and proceed normally.
214
- *
215
- * TTL is short on purpose: escalation handoffs complete in seconds
216
- * (the user solves the follow-up immediately) and a stale mapping
217
- * pointing at a long-gone session would just produce a different
218
- * shape of NO_SESSION_FOUND.
219
- */
220
- async cacheSessionEscalation(originSessionId, escalationSessionId, ttlSeconds = 600) {
221
- const client = await this.getClient();
222
- if (!client) {
223
- return false;
224
- }
225
- try {
226
- const key = `cache:session:escalation:${originSessionId}`;
227
- await client.set(key, escalationSessionId, { EX: ttlSeconds });
228
- return true;
229
- } catch (error) {
230
- this.logger.warn(() => ({
231
- msg: "Failed to cache session escalation mapping in Redis",
232
- err: error,
233
- originSessionId,
234
- escalationSessionId
235
- }));
236
- return false;
237
- }
238
- }
239
- /**
240
- * Resolve an original sessionId to its escalation sessionId, if one was
241
- * recorded. Returns null when there is no mapping (either no escalation
242
- * happened, or the TTL has elapsed).
243
- */
244
- async getCachedSessionEscalation(originSessionId) {
245
- const client = await this.getClient();
246
- if (!client) {
247
- return null;
248
- }
249
- try {
250
- const key = `cache:session:escalation:${originSessionId}`;
251
- return await client.get(key);
252
- } catch (error) {
253
- this.logger.warn(() => ({
254
- msg: "Failed to get cached session escalation mapping from Redis",
255
- err: error,
256
- originSessionId
257
- }));
258
- return null;
259
- }
260
- }
261
- /**
262
- * Invalidate an escalation mapping. Called when the escalation session
263
- * itself is consumed so subsequent retries on the origin sessionId fall
264
- * through to the standard NO_SESSION_FOUND path rather than chasing a
265
- * second-hand stale pointer.
266
- */
267
- async invalidateCachedSessionEscalation(originSessionId) {
268
- const client = await this.getClient();
269
- if (!client) {
270
- return;
271
- }
272
- try {
273
- const key = `cache:session:escalation:${originSessionId}`;
274
- await client.del(key);
275
- } catch (error) {
276
- this.logger.warn(() => ({
277
- msg: "Failed to invalidate cached session escalation mapping",
278
- err: error,
279
- originSessionId
280
- }));
281
- }
282
- }
283
- // ── Session write queue ─────────────────────────────────────────────
284
- /**
285
- * Queue a session record for batched insertion into MongoDB.
286
- * The session data is also cached in Redis for immediate reads.
287
- */
288
- async queueSessionRecord(sessionId, record, ttlSeconds = 86400) {
289
- const client = await this.getClient();
290
- if (!client) {
291
- return false;
292
- }
293
- try {
294
- const key = `writeq:session:${sessionId}`;
295
- const serialized = JSON.stringify(record, bigIntReplacer);
296
- await client.set(key, serialized, { EX: ttlSeconds });
297
- await client.sAdd("writeq:session:pending", sessionId);
298
- await client.set(`cache:session:${sessionId}`, serialized, {
299
- EX: ttlSeconds
300
- });
301
- this.triggerEarlyFlushIfNeeded();
302
- return true;
303
- } catch (error) {
304
- this.logger.warn(() => ({
305
- msg: "Failed to queue session record in Redis",
306
- err: error,
307
- sessionId
308
- }));
309
- return false;
310
- }
311
- }
312
- /**
313
- * Get all pending session records ready for batch flush.
314
- */
315
- async drainSessionRecords(limit = 500) {
316
- const client = await this.getClient();
317
- if (!client) {
318
- return [];
319
- }
320
- try {
321
- const sessionIds = await client.sMembers("writeq:session:pending");
322
- const batch = sessionIds.slice(0, limit);
323
- const results = [];
324
- for (const sessionId of batch) {
325
- const key = `writeq:session:${sessionId}`;
326
- const data = await client.get(key);
327
- if (data) {
328
- results.push({
329
- sessionId,
330
- record: JSON.parse(data, bigIntReviver)
331
- });
332
- }
333
- await client.sRem("writeq:session:pending", sessionId);
334
- await client.del(key);
335
- }
336
- return results;
337
- } catch (error) {
338
- this.logger.warn(() => ({
339
- msg: "Failed to drain session records from Redis",
340
- err: error
341
- }));
342
- return [];
343
- }
344
- }
345
- // ── Periodic flush ──────────────────────────────────────────────────
346
- /**
347
- * Start periodic background flush of queued records.
348
- * The callback receives this queue instance and should drain + bulk-write records.
349
- *
350
- * When the queue depth exceeds `earlyFlushThreshold`, an early flush is
351
- * triggered on the next `queueSessionRecord` call without waiting for
352
- * the regular interval.
353
- */
354
- startPeriodicFlush(callback, intervalMs = 1e4, earlyFlushThreshold = 50) {
355
- this.stopPeriodicFlush();
356
- this.flushCallback = callback;
357
- this.earlyFlushThreshold = earlyFlushThreshold;
358
- this.flushTimer = setInterval(() => {
359
- this.flushCallback?.(this).catch((error) => {
360
- this.logger.error(() => ({
361
- msg: "Periodic flush failed",
362
- err: error
363
- }));
364
- });
365
- }, intervalMs);
366
- }
367
- /**
368
- * Trigger an early flush if the pending queue exceeds the threshold.
369
- * Called automatically after queueing a record. This avoids large
370
- * batch build-ups between regular interval flushes.
371
- */
372
- triggerEarlyFlushIfNeeded() {
373
- if (!this.flushCallback || !this.earlyFlushThreshold) return;
374
- this.getPendingCount().then((count) => {
375
- if (count >= (this.earlyFlushThreshold ?? 50)) {
376
- return this.flushCallback?.(this);
377
- }
378
- }).catch((error) => {
379
- this.logger.error(() => ({
380
- msg: "Early flush failed",
381
- err: error
382
- }));
383
- });
384
- }
385
- /** Get the number of pending session records awaiting flush. */
386
- async getPendingCount() {
387
- const client = await this.getClient();
388
- if (!client) return 0;
389
- try {
390
- return await client.sCard("writeq:session:pending");
391
- } catch {
392
- return 0;
393
- }
394
- }
395
- /**
396
- * Stop the periodic flush timer.
397
- */
398
- stopPeriodicFlush() {
399
- if (this.flushTimer) {
400
- clearInterval(this.flushTimer);
401
- this.flushTimer = null;
402
- }
403
- this.flushCallback = null;
404
- this.earlyFlushThreshold = void 0;
405
- }
406
- /**
407
- * Drop every session-related key from Redis. Intended for provider
408
- * startup so a fresh process can never inherit stale read-cache,
409
- * dedup-by-hash, or pending-write-queue entries written by an
410
- * earlier (possibly crashed) run.
411
- *
412
- * Uses SCAN — KEYS would block the Redis server on large keyspaces.
413
- *
414
- * Bypasses the `isReady()` fast-path that other methods use because
415
- * this runs during startup, before the Redis client's async
416
- * connect() handshake has had time to flip the flag. We await the
417
- * connection promise directly with a bounded timeout so we don't
418
- * hang the boot sequence when Redis is unreachable.
419
- */
420
- async clearAllSessionRecords(timeoutMs = 5e3) {
421
- this.logger.info(() => ({
422
- msg: "Clearing Redis session records at startup"
423
- }));
424
- let client;
425
- try {
426
- client = await Promise.race([
427
- this.connection.getClient(),
428
- new Promise(
429
- (_, reject) => setTimeout(
430
- () => reject(new Error("Redis connection timeout")),
431
- timeoutMs
432
- )
433
- )
434
- ]);
435
- } catch (error) {
436
- this.logger.warn(() => ({
437
- msg: "Skipped Redis session cleanup — Redis not reachable",
438
- err: error
439
- }));
440
- return;
441
- }
442
- try {
443
- let totalDeleted = 0;
444
- for (const pattern of SESSION_KEY_PATTERNS) {
445
- for await (const key of client.scanIterator({
446
- MATCH: pattern,
447
- COUNT: 500
448
- })) {
449
- const keys = Array.isArray(key) ? key : [key];
450
- if (keys.length > 0) {
451
- await client.del(keys);
452
- totalDeleted += keys.length;
453
- }
454
- }
455
- }
456
- this.logger.info(() => ({
457
- msg: "Cleared Redis session records at startup",
458
- data: { totalDeleted }
459
- }));
460
- } catch (error) {
461
- this.logger.warn(() => ({
462
- msg: "Failed to clear Redis session records at startup",
463
- err: error
464
- }));
465
- }
466
- }
467
- /**
468
- * Check if the underlying Redis connection is ready.
469
- */
470
- isReady() {
471
- return this.connection.isReady();
472
- }
473
- }
474
- export {
475
- RedisWriteQueue
12
+ /**
13
+ * Redis-backed write queue and read cache for reducing MongoDB load.
14
+ *
15
+ * Provides:
16
+ * - Session record caching (reduces MongoDB reads)
17
+ * - Session-by-hash caching for frictionless deduplication
18
+ * - Session write queuing with periodic flush to MongoDB
19
+ *
20
+ * Uses an existing RedisConnection from @prosopo/redis-client rather than
21
+ * creating its own connection.
22
+ */
23
+ var RedisWriteQueue = class {
24
+ constructor(connection, logger) {
25
+ this.flushTimer = null;
26
+ this.flushCallback = null;
27
+ this.connection = connection;
28
+ this.logger = logger;
29
+ }
30
+ async getClient() {
31
+ if (!this.connection.isReady()) return null;
32
+ try {
33
+ return await this.connection.getClient();
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+ /**
39
+ * Cache a session record in Redis for fast lookups, reducing MongoDB reads.
40
+ */
41
+ async cacheSession(sessionId, sessionData, ttlSeconds = 86400) {
42
+ const client = await this.getClient();
43
+ if (!client) return false;
44
+ try {
45
+ const key = `cache:session:${sessionId}`;
46
+ await client.set(key, JSON.stringify(sessionData, bigIntReplacer), { EX: ttlSeconds });
47
+ return true;
48
+ } catch (error) {
49
+ this.logger.warn(() => ({
50
+ msg: "Failed to cache session in Redis",
51
+ err: error,
52
+ sessionId
53
+ }));
54
+ return false;
55
+ }
56
+ }
57
+ /**
58
+ * Retrieve a cached session record from Redis.
59
+ */
60
+ async getCachedSession(sessionId) {
61
+ const client = await this.getClient();
62
+ if (!client) return null;
63
+ try {
64
+ const key = `cache:session:${sessionId}`;
65
+ const data = await client.get(key);
66
+ if (!data) return null;
67
+ return JSON.parse(data, bigIntReviver);
68
+ } catch (error) {
69
+ this.logger.warn(() => ({
70
+ msg: "Failed to get cached session from Redis",
71
+ err: error,
72
+ sessionId
73
+ }));
74
+ return null;
75
+ }
76
+ }
77
+ /**
78
+ * Patch the cached session in place — read the existing entry, shallow-
79
+ * merge the provided updates, and write it back. No-op on cache miss so
80
+ * the next read repopulates from Mongo. Mirrors the field-level Mongo
81
+ * patch done by `db.updateSessionRecord`; callers invoke both to keep
82
+ * Redis consistent with the DB after every in-request write.
83
+ */
84
+ async patchCachedSession(sessionId, updates, ttlSeconds = 86400) {
85
+ const existing = await this.getCachedSession(sessionId);
86
+ if (!existing) return false;
87
+ return this.cacheSession(sessionId, {
88
+ ...existing,
89
+ ...updates,
90
+ lastUpdatedTimestamp: /* @__PURE__ */ new Date()
91
+ }, ttlSeconds);
92
+ }
93
+ /**
94
+ * First-hop-wins SIMD attach on the cache — mirrors the atomic Mongo
95
+ * `$ifNull` pipeline update in `db.recordSessionSimdReadingsIfAbsent`.
96
+ * Reads the cache; if it doesn't already carry `simdReadings`, merges
97
+ * the new readings + stage. No-op on cache miss or when readings are
98
+ * already present.
99
+ */
100
+ async patchCachedSimdReadingsIfAbsent(sessionId, readings, stage, ttlSeconds = 86400) {
101
+ const existing = await this.getCachedSession(sessionId);
102
+ if (!existing) return false;
103
+ if (existing.simdReadings) return false;
104
+ return this.cacheSession(sessionId, {
105
+ ...existing,
106
+ simdReadings: readings,
107
+ simdReadingsStage: stage,
108
+ lastUpdatedTimestamp: /* @__PURE__ */ new Date()
109
+ }, ttlSeconds);
110
+ }
111
+ /**
112
+ * Invalidate a cached session when it's updated.
113
+ */
114
+ async invalidateCachedSession(sessionId) {
115
+ const client = await this.getClient();
116
+ if (!client) return;
117
+ try {
118
+ await client.del(`cache:session:${sessionId}`);
119
+ } catch (error) {
120
+ this.logger.warn(() => ({
121
+ msg: "Failed to invalidate cached session in Redis",
122
+ err: error,
123
+ sessionId
124
+ }));
125
+ }
126
+ }
127
+ /**
128
+ * Invalidate the hash → sessionId mapping used by /frictionless for
129
+ * dedup. Must be called alongside `invalidateCachedSession` when a
130
+ * session is consumed, otherwise the hash mapping keeps resolving to
131
+ * a dead sessionId for the remainder of its 1-hour TTL.
132
+ */
133
+ async invalidateCachedSessionByHash(userSitekeyIpHash) {
134
+ const client = await this.getClient();
135
+ if (!client) return;
136
+ try {
137
+ await client.del(`cache:session:hash:${userSitekeyIpHash}`);
138
+ } catch (error) {
139
+ this.logger.warn(() => ({
140
+ msg: "Failed to invalidate cached session hash in Redis",
141
+ err: error,
142
+ userSitekeyIpHash
143
+ }));
144
+ }
145
+ }
146
+ /**
147
+ * Cache a session lookup by userSitekeyIpHash for frictionless deduplication.
148
+ * Extends the effective TTL of the cached session, reducing duplicate
149
+ * session creation under concurrent requests for the same user+site+IP.
150
+ */
151
+ async cacheSessionByHash(userSitekeyIpHash, sessionId, ttlSeconds = 3600) {
152
+ const client = await this.getClient();
153
+ if (!client) return false;
154
+ try {
155
+ const key = `cache:session:hash:${userSitekeyIpHash}`;
156
+ await client.set(key, sessionId, { EX: ttlSeconds });
157
+ return true;
158
+ } catch (error) {
159
+ this.logger.warn(() => ({
160
+ msg: "Failed to cache session hash in Redis",
161
+ err: error,
162
+ userSitekeyIpHash
163
+ }));
164
+ return false;
165
+ }
166
+ }
167
+ /**
168
+ * Get cached sessionId by userSitekeyIpHash for frictionless deduplication.
169
+ */
170
+ async getCachedSessionByHash(userSitekeyIpHash) {
171
+ const client = await this.getClient();
172
+ if (!client) return null;
173
+ try {
174
+ const key = `cache:session:hash:${userSitekeyIpHash}`;
175
+ return await client.get(key);
176
+ } catch (error) {
177
+ this.logger.warn(() => ({
178
+ msg: "Failed to get cached session hash from Redis",
179
+ err: error,
180
+ userSitekeyIpHash
181
+ }));
182
+ return null;
183
+ }
184
+ }
185
+ /**
186
+ * Cache an origin → escalation sessionId mapping for the post-PoW
187
+ * escalation flow.
188
+ *
189
+ * Background: when the routing machine returns image/puzzle from the
190
+ * postPow phase, `buildEscalation` (`api/captcha/submitPoWCaptchaSolution.ts`)
191
+ * mints a new session with a fresh `sessionId` and returns it on the
192
+ * `escalation` field. A widget that handles the escalation cleanly
193
+ * mounts the next captcha with the new sessionId. But there are
194
+ * several real-world paths where the widget keeps using the original
195
+ * sessionId for the follow-up `/captcha/{type}` request — bundled SDK
196
+ * versions that predate the escalation handler, dapps that hand-roll
197
+ * the wrapper, network-glitch retries, or browser-tab races. The
198
+ * original session has been consumed and soft-deleted by the
199
+ * preceding `/captcha/pow`, so the follow-up gets
200
+ * `CAPTCHA.NO_SESSION_FOUND` and the user sees an inline error → FAQ.
201
+ *
202
+ * This mapping lets `isValidRequest` resolve the original sessionId
203
+ * forward to the live escalation session and proceed normally.
204
+ *
205
+ * TTL is short on purpose: escalation handoffs complete in seconds
206
+ * (the user solves the follow-up immediately) and a stale mapping
207
+ * pointing at a long-gone session would just produce a different
208
+ * shape of NO_SESSION_FOUND.
209
+ */
210
+ async cacheSessionEscalation(originSessionId, escalationSessionId, ttlSeconds = 600) {
211
+ const client = await this.getClient();
212
+ if (!client) return false;
213
+ try {
214
+ const key = `cache:session:escalation:${originSessionId}`;
215
+ await client.set(key, escalationSessionId, { EX: ttlSeconds });
216
+ return true;
217
+ } catch (error) {
218
+ this.logger.warn(() => ({
219
+ msg: "Failed to cache session escalation mapping in Redis",
220
+ err: error,
221
+ originSessionId,
222
+ escalationSessionId
223
+ }));
224
+ return false;
225
+ }
226
+ }
227
+ /**
228
+ * Resolve an original sessionId to its escalation sessionId, if one was
229
+ * recorded. Returns null when there is no mapping (either no escalation
230
+ * happened, or the TTL has elapsed).
231
+ */
232
+ async getCachedSessionEscalation(originSessionId) {
233
+ const client = await this.getClient();
234
+ if (!client) return null;
235
+ try {
236
+ const key = `cache:session:escalation:${originSessionId}`;
237
+ return await client.get(key);
238
+ } catch (error) {
239
+ this.logger.warn(() => ({
240
+ msg: "Failed to get cached session escalation mapping from Redis",
241
+ err: error,
242
+ originSessionId
243
+ }));
244
+ return null;
245
+ }
246
+ }
247
+ /**
248
+ * Invalidate an escalation mapping. Called when the escalation session
249
+ * itself is consumed so subsequent retries on the origin sessionId fall
250
+ * through to the standard NO_SESSION_FOUND path rather than chasing a
251
+ * second-hand stale pointer.
252
+ */
253
+ async invalidateCachedSessionEscalation(originSessionId) {
254
+ const client = await this.getClient();
255
+ if (!client) return;
256
+ try {
257
+ const key = `cache:session:escalation:${originSessionId}`;
258
+ await client.del(key);
259
+ } catch (error) {
260
+ this.logger.warn(() => ({
261
+ msg: "Failed to invalidate cached session escalation mapping",
262
+ err: error,
263
+ originSessionId
264
+ }));
265
+ }
266
+ }
267
+ /**
268
+ * Queue a session record for batched insertion into MongoDB.
269
+ * The session data is also cached in Redis for immediate reads.
270
+ */
271
+ async queueSessionRecord(sessionId, record, ttlSeconds = 86400) {
272
+ const client = await this.getClient();
273
+ if (!client) return false;
274
+ try {
275
+ const key = `writeq:session:${sessionId}`;
276
+ const serialized = JSON.stringify(record, bigIntReplacer);
277
+ await client.set(key, serialized, { EX: ttlSeconds });
278
+ await client.sAdd("writeq:session:pending", sessionId);
279
+ await client.set(`cache:session:${sessionId}`, serialized, { EX: ttlSeconds });
280
+ this.triggerEarlyFlushIfNeeded();
281
+ return true;
282
+ } catch (error) {
283
+ this.logger.warn(() => ({
284
+ msg: "Failed to queue session record in Redis",
285
+ err: error,
286
+ sessionId
287
+ }));
288
+ return false;
289
+ }
290
+ }
291
+ /**
292
+ * Get all pending session records ready for batch flush.
293
+ */
294
+ async drainSessionRecords(limit = 500) {
295
+ const client = await this.getClient();
296
+ if (!client) return [];
297
+ try {
298
+ const batch = (await client.sMembers("writeq:session:pending")).slice(0, limit);
299
+ const results = [];
300
+ for (const sessionId of batch) {
301
+ const key = `writeq:session:${sessionId}`;
302
+ const data = await client.get(key);
303
+ if (data) results.push({
304
+ sessionId,
305
+ record: JSON.parse(data, bigIntReviver)
306
+ });
307
+ await client.sRem("writeq:session:pending", sessionId);
308
+ await client.del(key);
309
+ }
310
+ return results;
311
+ } catch (error) {
312
+ this.logger.warn(() => ({
313
+ msg: "Failed to drain session records from Redis",
314
+ err: error
315
+ }));
316
+ return [];
317
+ }
318
+ }
319
+ /**
320
+ * Start periodic background flush of queued records.
321
+ * The callback receives this queue instance and should drain + bulk-write records.
322
+ *
323
+ * When the queue depth exceeds `earlyFlushThreshold`, an early flush is
324
+ * triggered on the next `queueSessionRecord` call without waiting for
325
+ * the regular interval.
326
+ */
327
+ startPeriodicFlush(callback, intervalMs = 1e4, earlyFlushThreshold = 50) {
328
+ this.stopPeriodicFlush();
329
+ this.flushCallback = callback;
330
+ this.earlyFlushThreshold = earlyFlushThreshold;
331
+ this.flushTimer = setInterval(() => {
332
+ this.flushCallback?.(this).catch((error) => {
333
+ this.logger.error(() => ({
334
+ msg: "Periodic flush failed",
335
+ err: error
336
+ }));
337
+ });
338
+ }, intervalMs);
339
+ }
340
+ /**
341
+ * Trigger an early flush if the pending queue exceeds the threshold.
342
+ * Called automatically after queueing a record. This avoids large
343
+ * batch build-ups between regular interval flushes.
344
+ */
345
+ triggerEarlyFlushIfNeeded() {
346
+ if (!this.flushCallback || !this.earlyFlushThreshold) return;
347
+ this.getPendingCount().then((count) => {
348
+ if (count >= (this.earlyFlushThreshold ?? 50)) return this.flushCallback?.(this);
349
+ }).catch((error) => {
350
+ this.logger.error(() => ({
351
+ msg: "Early flush failed",
352
+ err: error
353
+ }));
354
+ });
355
+ }
356
+ /** Get the number of pending session records awaiting flush. */
357
+ async getPendingCount() {
358
+ const client = await this.getClient();
359
+ if (!client) return 0;
360
+ try {
361
+ return await client.sCard("writeq:session:pending");
362
+ } catch {
363
+ return 0;
364
+ }
365
+ }
366
+ /**
367
+ * Stop the periodic flush timer.
368
+ */
369
+ stopPeriodicFlush() {
370
+ if (this.flushTimer) {
371
+ clearInterval(this.flushTimer);
372
+ this.flushTimer = null;
373
+ }
374
+ this.flushCallback = null;
375
+ this.earlyFlushThreshold = void 0;
376
+ }
377
+ /**
378
+ * Drop every session-related key from Redis. Intended for provider
379
+ * startup so a fresh process can never inherit stale read-cache,
380
+ * dedup-by-hash, or pending-write-queue entries written by an
381
+ * earlier (possibly crashed) run.
382
+ *
383
+ * Uses SCAN — KEYS would block the Redis server on large keyspaces.
384
+ *
385
+ * Bypasses the `isReady()` fast-path that other methods use because
386
+ * this runs during startup, before the Redis client's async
387
+ * connect() handshake has had time to flip the flag. We await the
388
+ * connection promise directly with a bounded timeout so we don't
389
+ * hang the boot sequence when Redis is unreachable.
390
+ */
391
+ async clearAllSessionRecords(timeoutMs = 5e3) {
392
+ this.logger.info(() => ({ msg: "Clearing Redis session records at startup" }));
393
+ let client;
394
+ try {
395
+ client = await Promise.race([this.connection.getClient(), new Promise((_, reject) => setTimeout(() => reject(/* @__PURE__ */ new Error("Redis connection timeout")), timeoutMs))]);
396
+ } catch (error) {
397
+ this.logger.warn(() => ({
398
+ msg: "Skipped Redis session cleanup — Redis not reachable",
399
+ err: error
400
+ }));
401
+ return;
402
+ }
403
+ try {
404
+ let totalDeleted = 0;
405
+ for (const pattern of SESSION_KEY_PATTERNS) for await (const key of client.scanIterator({
406
+ MATCH: pattern,
407
+ COUNT: 500
408
+ })) {
409
+ const keys = Array.isArray(key) ? key : [key];
410
+ if (keys.length > 0) {
411
+ await client.del(keys);
412
+ totalDeleted += keys.length;
413
+ }
414
+ }
415
+ this.logger.info(() => ({
416
+ msg: "Cleared Redis session records at startup",
417
+ data: { totalDeleted }
418
+ }));
419
+ } catch (error) {
420
+ this.logger.warn(() => ({
421
+ msg: "Failed to clear Redis session records at startup",
422
+ err: error
423
+ }));
424
+ }
425
+ }
426
+ /**
427
+ * Check if the underlying Redis connection is ready.
428
+ */
429
+ isReady() {
430
+ return this.connection.isReady();
431
+ }
476
432
  };
433
+ //#endregion
434
+ export { RedisWriteQueue };