@crvouga/mockingbird-service-redis 2.2.0 → 2.4.0

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.
@@ -0,0 +1,943 @@
1
+ import {
2
+ RedisConnectionError,
3
+ RespParser,
4
+ asCommand,
5
+ createRedis,
6
+ encodeReply
7
+ } from "./chunk-Z3XQGVTX.js";
8
+
9
+ // src/server.ts
10
+ import { createConnection, createServer } from "node:net";
11
+
12
+ // ../core/dist/clock.js
13
+ var createClock = (source = Date.now) => {
14
+ let offsetMs = 0;
15
+ let frozenAt;
16
+ const now = () => frozenAt ?? source() + offsetMs;
17
+ return {
18
+ now,
19
+ set: (epochMs) => {
20
+ if (frozenAt !== void 0)
21
+ frozenAt = epochMs;
22
+ else
23
+ offsetMs = epochMs - source();
24
+ },
25
+ advance: (deltaMs) => {
26
+ if (frozenAt !== void 0)
27
+ frozenAt += deltaMs;
28
+ else
29
+ offsetMs += deltaMs;
30
+ },
31
+ freeze: () => {
32
+ frozenAt = now();
33
+ },
34
+ unfreeze: () => {
35
+ if (frozenAt === void 0)
36
+ return;
37
+ offsetMs = frozenAt - source();
38
+ frozenAt = void 0;
39
+ },
40
+ reset: () => {
41
+ offsetMs = 0;
42
+ frozenAt = void 0;
43
+ },
44
+ // A frozen clock does not follow its source, so it has no offset to report.
45
+ state: () => ({
46
+ now: now(),
47
+ frozen: frozenAt !== void 0,
48
+ offsetMs: frozenAt !== void 0 ? 0 : offsetMs
49
+ })
50
+ };
51
+ };
52
+ var restoreClock = (clock, state) => {
53
+ clock.freeze();
54
+ clock.set(state.now);
55
+ if (!state.frozen)
56
+ clock.unfreeze();
57
+ };
58
+
59
+ // ../core/dist/controls.js
60
+ var ControlError = class extends RangeError {
61
+ constructor(message) {
62
+ super(message);
63
+ this.name = "ControlError";
64
+ }
65
+ };
66
+ var UNITS = {
67
+ ms: 1,
68
+ s: 1e3,
69
+ m: 6e4,
70
+ h: 36e5,
71
+ d: 864e5
72
+ };
73
+ var parseDuration = (value) => {
74
+ if (typeof value === "number")
75
+ return Number.isFinite(value) ? value : void 0;
76
+ if (typeof value !== "string")
77
+ return void 0;
78
+ const match = /^(-?\d+(?:\.\d+)?)\s*(ms|s|m|h|d)?$/.exec(value.trim());
79
+ if (!match)
80
+ return void 0;
81
+ return Number(match[1]) * UNITS[match[2] ?? "ms"];
82
+ };
83
+ var parseInstant = (value) => {
84
+ if (typeof value === "number")
85
+ return Number.isFinite(value) ? value : void 0;
86
+ if (typeof value !== "string")
87
+ return void 0;
88
+ const text = value.trim();
89
+ if (/^-?\d+$/.test(text))
90
+ return Number(text);
91
+ const parsed = Date.parse(text);
92
+ return Number.isNaN(parsed) ? void 0 : parsed;
93
+ };
94
+ var durationMs = (value, label, negative = false) => {
95
+ const parsed = parseDuration(value);
96
+ if (parsed === void 0)
97
+ throw new ControlError(`${label}: expected milliseconds or a duration like "250ms" or "15m"`);
98
+ if (!negative && parsed < 0)
99
+ throw new ControlError(`${label}: must not be negative`);
100
+ return parsed;
101
+ };
102
+ var instantMs = (value, label) => {
103
+ const parsed = parseInstant(value);
104
+ if (parsed === void 0)
105
+ throw new ControlError(`${label}: expected epoch ms or ISO-8601`);
106
+ return parsed;
107
+ };
108
+ var normalizeSeed = (seed, label = "seed") => {
109
+ if (typeof seed === "number" && Number.isFinite(seed))
110
+ return seed;
111
+ if (typeof seed === "string" && seed !== "")
112
+ return /^\d+$/.test(seed) ? Number(seed) : seed;
113
+ throw new ControlError(`${label}: expected a number or a non-empty string`);
114
+ };
115
+ var SNAPSHOT_FORMAT = "mockingbird.snapshot/v1";
116
+ var NAMESPACE_KEYS = /* @__PURE__ */ new Set(["seed", "clock", "virtualTime", "latency", "faults", "snapshot"]);
117
+ var MOCK_KEYS = /* @__PURE__ */ new Set([...NAMESPACE_KEYS, "credentials", "namespaces"]);
118
+ var REPORTED_KEYS = /* @__PURE__ */ new Set(["namespace", "snapshots"]);
119
+ var REPORTED_CLOCK_KEYS = /* @__PURE__ */ new Set(["iso", "offsetMs"]);
120
+ var KEY_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
121
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
122
+ var unknownKeys = (value, known, label, reported) => {
123
+ for (const key of Object.keys(value)) {
124
+ if (!known.has(key) && !reported?.has(key))
125
+ throw new ControlError(`${label}: unknown control ${JSON.stringify(key)}; expected ${[...known].join(", ")}`);
126
+ }
127
+ };
128
+ var latencyRule = (value, label) => {
129
+ if (!isRecord(value))
130
+ return { delayMs: durationMs(value, label), jitterMs: 0 };
131
+ unknownKeys(value, /* @__PURE__ */ new Set(["delay", "jitter", "delayMs", "jitterMs", "operations"]), label);
132
+ return {
133
+ delayMs: durationMs(value.delay ?? value.delayMs ?? 0, `${label}.delay`),
134
+ jitterMs: durationMs(value.jitter ?? value.jitterMs ?? 0, `${label}.jitter`)
135
+ };
136
+ };
137
+ var normalizeLatency = (value, label = "latency") => {
138
+ const base = latencyRule(value, label);
139
+ const operations = {};
140
+ if (isRecord(value) && value.operations !== void 0) {
141
+ if (!isRecord(value.operations))
142
+ throw new ControlError(`${label}.operations: expected an object keyed by operationId`);
143
+ for (const [operationId, rule] of Object.entries(value.operations)) {
144
+ if (isRecord(rule) && rule.operations !== void 0)
145
+ throw new ControlError(`${label}.operations.${operationId}: cannot nest operations`);
146
+ operations[operationId] = latencyRule(rule, `${label}.operations.${operationId}`);
147
+ }
148
+ }
149
+ return { ...base, operations };
150
+ };
151
+ var normalizeClock = (value, label = "clock") => {
152
+ if (!isRecord(value))
153
+ throw new ControlError(`${label}: expected an object`);
154
+ unknownKeys(value, /* @__PURE__ */ new Set(["now", "set", "frozen", "freeze", "autoAdvance", "autoAdvanceMs"]), label, REPORTED_CLOCK_KEYS);
155
+ const plan = {};
156
+ const now = value.now ?? value.set;
157
+ if (now !== void 0)
158
+ plan.now = instantMs(now, `${label}.now`);
159
+ const frozen = value.frozen ?? value.freeze;
160
+ if (frozen !== void 0) {
161
+ if (typeof frozen !== "boolean")
162
+ throw new ControlError(`${label}.frozen: expected a boolean`);
163
+ plan.frozen = frozen;
164
+ }
165
+ const auto = value.autoAdvance ?? value.autoAdvanceMs;
166
+ if (auto !== void 0)
167
+ plan.autoAdvanceMs = durationMs(auto, `${label}.autoAdvance`);
168
+ return plan;
169
+ };
170
+ var assertSnapshotDocument = (value, label = "snapshot") => {
171
+ if (!isRecord(value))
172
+ throw new ControlError(`${label}: expected a snapshot document`);
173
+ if (value.format !== SNAPSHOT_FORMAT)
174
+ throw new ControlError(`${label}.format: expected ${JSON.stringify(SNAPSHOT_FORMAT)}`);
175
+ if (!Array.isArray(value.records))
176
+ throw new ControlError(`${label}.records: expected a list`);
177
+ value.records.forEach((row, index) => {
178
+ if (!isRecord(row) || typeof row.collection !== "string" || typeof row.id !== "string" || row.value === void 0 && typeof row.raw !== "string" || row.seq !== void 0 && !Number.isSafeInteger(row.seq))
179
+ throw new ControlError(`${label}.records[${index}]: expected {collection, id, value, seq?}`);
180
+ });
181
+ if (value.sequences !== void 0) {
182
+ if (!Array.isArray(value.sequences))
183
+ throw new ControlError(`${label}.sequences: expected a list`);
184
+ value.sequences.forEach((row, index) => {
185
+ if (!isRecord(row) || typeof row.name !== "string" || typeof row.kind !== "string" || !Number.isSafeInteger(row.value))
186
+ throw new ControlError(`${label}.sequences[${index}]: expected {name, kind, value}`);
187
+ });
188
+ }
189
+ if (value.clock !== void 0) {
190
+ if (!isRecord(value.clock) || typeof value.clock.now !== "number" || !Number.isFinite(value.clock.now) || typeof value.clock.frozen !== "boolean")
191
+ throw new ControlError(`${label}.clock: expected {now, frozen}`);
192
+ }
193
+ return value;
194
+ };
195
+ var normalizeControls = (value, label = "controls") => {
196
+ if (!isRecord(value))
197
+ throw new ControlError(`${label}: expected an object`);
198
+ unknownKeys(value, NAMESPACE_KEYS, label, REPORTED_KEYS);
199
+ const plan = {};
200
+ if (value.seed !== void 0)
201
+ plan.seed = normalizeSeed(value.seed, `${label}.seed`);
202
+ if (value.clock !== void 0)
203
+ plan.clock = normalizeClock(value.clock, `${label}.clock`);
204
+ if (value.virtualTime !== void 0) {
205
+ if (typeof value.virtualTime !== "boolean")
206
+ throw new ControlError(`${label}.virtualTime: expected a boolean`);
207
+ plan.virtualTime = value.virtualTime;
208
+ }
209
+ if (value.latency !== void 0)
210
+ plan.latency = normalizeLatency(value.latency, `${label}.latency`);
211
+ if (value.faults !== void 0) {
212
+ if (!Array.isArray(value.faults) || !value.faults.every(isRecord))
213
+ throw new ControlError(`${label}.faults: expected a list of fault rules`);
214
+ plan.faults = value.faults;
215
+ }
216
+ if (value.snapshot !== void 0)
217
+ plan.snapshot = assertSnapshotDocument(value.snapshot, `${label}.snapshot`);
218
+ return plan;
219
+ };
220
+ var normalizeBootControls = (value, label = "controls") => {
221
+ if (value === void 0)
222
+ return { shared: {}, namespaces: {}, credentials: {} };
223
+ if (!isRecord(value))
224
+ throw new ControlError(`${label}: expected an object`);
225
+ unknownKeys(value, MOCK_KEYS, label);
226
+ const { credentials, namespaces, ...shared } = value;
227
+ const plan = {
228
+ shared: normalizeControls(shared, label),
229
+ namespaces: {},
230
+ credentials: {}
231
+ };
232
+ if (namespaces !== void 0) {
233
+ if (!isRecord(namespaces))
234
+ throw new ControlError(`${label}.namespaces: expected an object`);
235
+ for (const [name2, each] of Object.entries(namespaces)) {
236
+ if (!KEY_PATTERN.test(name2))
237
+ throw new ControlError(`${label}.namespaces: bad namespace ${JSON.stringify(name2)}`);
238
+ plan.namespaces[name2] = normalizeControls(each, `${label}.namespaces.${name2}`);
239
+ }
240
+ }
241
+ if (credentials !== void 0) {
242
+ if (!isRecord(credentials))
243
+ throw new ControlError(`${label}.credentials: expected an object`);
244
+ for (const [credential, namespace] of Object.entries(credentials)) {
245
+ if (typeof namespace !== "string" || !KEY_PATTERN.test(namespace))
246
+ throw new ControlError(`${label}.credentials: bad namespace for a credential`);
247
+ plan.credentials[credential] = namespace;
248
+ }
249
+ }
250
+ return plan;
251
+ };
252
+ var CONTROL_HEADERS = {
253
+ namespace: "x-mockingbird-namespace",
254
+ adminKey: "x-mockingbird-admin-key",
255
+ branch: "x-mockingbird-branch",
256
+ at: "x-mockingbird-at",
257
+ reset: "x-mockingbird-reset",
258
+ restore: "x-mockingbird-restore",
259
+ seed: "x-mockingbird-seed",
260
+ time: "x-mockingbird-time",
261
+ advance: "x-mockingbird-advance",
262
+ virtualTime: "x-mockingbird-virtual-time",
263
+ fault: "x-mockingbird-fault",
264
+ delay: "x-mockingbird-delay",
265
+ timeout: "x-mockingbird-timeout",
266
+ snapshot: "x-mockingbird-snapshot"
267
+ };
268
+ var CONTROL_HEADER_REFERENCE = [
269
+ {
270
+ header: CONTROL_HEADERS.namespace,
271
+ value: "<key>",
272
+ scope: "select",
273
+ guarded: false,
274
+ summary: "Isolation key. Each key has its own records, clock, random streams, faults, latency, journal and snapshots."
275
+ },
276
+ {
277
+ header: CONTROL_HEADERS.branch,
278
+ value: "<name>",
279
+ scope: "select",
280
+ guarded: false,
281
+ summary: "Read and write a named copy-on-write branch of the namespace's history."
282
+ },
283
+ {
284
+ header: CONTROL_HEADERS.at,
285
+ value: "<checkpoint>",
286
+ scope: "select",
287
+ guarded: false,
288
+ summary: "Read the namespace as it was at a checkpoint. With a branch, start the branch there."
289
+ },
290
+ {
291
+ header: CONTROL_HEADERS.reset,
292
+ value: "true",
293
+ scope: "namespace",
294
+ guarded: true,
295
+ summary: "Reset the namespace to its boot state before the request is handled."
296
+ },
297
+ {
298
+ header: CONTROL_HEADERS.restore,
299
+ value: "<snapshot>",
300
+ scope: "namespace",
301
+ guarded: true,
302
+ summary: "Restore a snapshot before the request is handled."
303
+ },
304
+ {
305
+ header: CONTROL_HEADERS.seed,
306
+ value: "<seed>",
307
+ scope: "namespace",
308
+ guarded: true,
309
+ summary: "Restart the namespace's random streams from this seed."
310
+ },
311
+ {
312
+ header: CONTROL_HEADERS.time,
313
+ value: "<epoch ms | ISO-8601>",
314
+ scope: "namespace",
315
+ guarded: true,
316
+ summary: "Freeze the namespace clock at this instant."
317
+ },
318
+ {
319
+ header: CONTROL_HEADERS.advance,
320
+ value: "<duration>",
321
+ scope: "namespace",
322
+ guarded: true,
323
+ summary: "Move the namespace clock by this much, forward or (negative) back."
324
+ },
325
+ {
326
+ header: CONTROL_HEADERS.virtualTime,
327
+ value: "true | false",
328
+ scope: "namespace",
329
+ guarded: true,
330
+ summary: "Spend injected waits on the mock clock (true) or the wall clock (false)."
331
+ },
332
+ {
333
+ header: CONTROL_HEADERS.delay,
334
+ value: "<duration>",
335
+ scope: "request",
336
+ guarded: true,
337
+ summary: "Hold this response back this long, on top of the namespace's latency."
338
+ },
339
+ {
340
+ header: CONTROL_HEADERS.timeout,
341
+ value: "<duration>",
342
+ scope: "request",
343
+ guarded: true,
344
+ summary: "Never answer this request: hold it this long, then drop the connection."
345
+ },
346
+ {
347
+ header: CONTROL_HEADERS.fault,
348
+ value: '<status> | drop | <preset> | key=value; \u2026 | {"status": 503, \u2026}',
349
+ scope: "request",
350
+ guarded: true,
351
+ summary: "Fault this request only. Stored fault rules are not consulted when it answers."
352
+ },
353
+ {
354
+ header: CONTROL_HEADERS.snapshot,
355
+ value: "<name>",
356
+ scope: "namespace",
357
+ guarded: true,
358
+ summary: "Snapshot the namespace after the request is handled. Echoed on the response."
359
+ }
360
+ ];
361
+ var flag = (value, header) => {
362
+ const text = value.trim().toLowerCase();
363
+ if (text === "true" || text === "1")
364
+ return true;
365
+ if (text === "false" || text === "0")
366
+ return false;
367
+ throw new ControlError(`${header}: expected true or false`);
368
+ };
369
+ var name = (value, header) => {
370
+ const text = value.trim();
371
+ if (!KEY_PATTERN.test(text))
372
+ throw new ControlError(`${header}: must match ${KEY_PATTERN}`);
373
+ return text;
374
+ };
375
+ var FAULT_PAIRS = /* @__PURE__ */ new Set([
376
+ "status",
377
+ "delay",
378
+ "jitter",
379
+ "timeout",
380
+ "drop",
381
+ "truncate",
382
+ "effect",
383
+ "preset",
384
+ "body"
385
+ ]);
386
+ var parseFaultHeader = (value, header = CONTROL_HEADERS.fault) => {
387
+ const text = value.trim();
388
+ if (text === "")
389
+ throw new ControlError(`${header}: expected a fault`);
390
+ if (text.startsWith("{")) {
391
+ let parsed;
392
+ try {
393
+ parsed = JSON.parse(text);
394
+ } catch {
395
+ throw new ControlError(`${header}: not valid JSON`);
396
+ }
397
+ if (!isRecord(parsed))
398
+ throw new ControlError(`${header}: expected a JSON object`);
399
+ return parsed;
400
+ }
401
+ const rule = {};
402
+ const headers = {};
403
+ for (const [index, raw] of text.split(";").entries()) {
404
+ const part = raw.trim();
405
+ if (part === "")
406
+ continue;
407
+ const equals = part.indexOf("=");
408
+ if (equals < 0) {
409
+ if (index > 0 && part !== "drop")
410
+ throw new ControlError(`${header}: expected key=value, got ${JSON.stringify(part)}`);
411
+ if (/^\d{3}$/.test(part))
412
+ rule.status = Number(part);
413
+ else if (part === "drop")
414
+ rule.drop = true;
415
+ else
416
+ rule.preset = name(part, header);
417
+ continue;
418
+ }
419
+ const key = part.slice(0, equals).trim().toLowerCase();
420
+ const item = part.slice(equals + 1).trim();
421
+ if (key.startsWith("header."))
422
+ headers[key.slice("header.".length)] = item;
423
+ else if (!FAULT_PAIRS.has(key))
424
+ throw new ControlError(`${header}: unknown key ${JSON.stringify(key)}; expected ${[...FAULT_PAIRS].join(", ")} or header.<name>`);
425
+ else if (key === "status" || key === "truncate") {
426
+ if (!/^\d+$/.test(item))
427
+ throw new ControlError(`${header}: ${key} must be a number`);
428
+ rule[key] = Number(item);
429
+ } else if (key === "drop")
430
+ rule.drop = flag(item, `${header} drop`);
431
+ else
432
+ rule[key] = item;
433
+ }
434
+ if (Object.keys(headers).length > 0)
435
+ rule.headers = headers;
436
+ if (Object.keys(rule).length === 0)
437
+ throw new ControlError(`${header}: expected a fault`);
438
+ return rule;
439
+ };
440
+ var GUARDED = CONTROL_HEADER_REFERENCE.filter((each) => each.guarded).map((each) => each.header);
441
+
442
+ // ../core/dist/control.js
443
+ var ADMIN_PREFIX = "/__admin";
444
+ var resolveAdminPrefix = (prefix = ADMIN_PREFIX) => {
445
+ if (!/^\/[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*$/.test(prefix)) {
446
+ throw new Error("adminPrefix must be an absolute non-root path of literal segments, without a trailing slash");
447
+ }
448
+ return prefix;
449
+ };
450
+ var isAdminPath = (path, prefix) => path === prefix || path.startsWith(`${prefix}/`);
451
+ var matchNamespacePath = (path, prefix) => /^\/ns\/([^/]+)(\/.*)?$/.exec(isAdminPath(path, prefix) ? path.slice(prefix.length) : "");
452
+ var ADMIN_KEY_HEADER = CONTROL_HEADERS.adminKey;
453
+ var NAMESPACE_HEADER = CONTROL_HEADERS.namespace;
454
+ var ADMIN_CONTROL_PAGES = [
455
+ {
456
+ page: "namespaces",
457
+ title: "Namespaces",
458
+ routes: ["/namespaces", "/credentials"],
459
+ headers: [CONTROL_HEADERS.namespace]
460
+ },
461
+ { page: "reset", title: "Reset", routes: ["/reset"], headers: [CONTROL_HEADERS.reset] },
462
+ {
463
+ page: "snapshot-and-restore",
464
+ title: "Snapshot and restore",
465
+ routes: ["/snapshots"],
466
+ headers: [CONTROL_HEADERS.restore, CONTROL_HEADERS.snapshot]
467
+ },
468
+ {
469
+ page: "clock",
470
+ title: "Clock",
471
+ routes: ["/clock"],
472
+ headers: [CONTROL_HEADERS.time, CONTROL_HEADERS.advance]
473
+ },
474
+ {
475
+ page: "checkpoints-and-branches",
476
+ title: "Checkpoints and branches",
477
+ routes: ["/timeline", "/checkpoints", "/branches"],
478
+ headers: [CONTROL_HEADERS.branch, CONTROL_HEADERS.at]
479
+ },
480
+ { page: "faults", title: "Faults", routes: ["/faults"], headers: [CONTROL_HEADERS.fault] },
481
+ {
482
+ page: "latency-and-timeouts",
483
+ title: "Latency and timeouts",
484
+ routes: ["/latency"],
485
+ headers: [CONTROL_HEADERS.delay, CONTROL_HEADERS.timeout, CONTROL_HEADERS.virtualTime]
486
+ },
487
+ {
488
+ page: "seed-and-determinism",
489
+ title: "Seed and determinism",
490
+ routes: [],
491
+ headers: [CONTROL_HEADERS.seed]
492
+ },
493
+ { page: "control-document", title: "The control document", routes: ["/controls"], headers: [] },
494
+ { page: "boot", title: "Boot", routes: [], headers: [] },
495
+ { page: "request-headers", title: "Request headers", routes: [], headers: [] },
496
+ {
497
+ page: "journal-and-state",
498
+ title: "Journal, metrics and state",
499
+ routes: ["/requests", "/metrics", "/state", "/ui"],
500
+ headers: []
501
+ },
502
+ {
503
+ page: "reference",
504
+ title: "Reference",
505
+ routes: ["/", "/health"],
506
+ headers: [CONTROL_HEADERS.adminKey]
507
+ }
508
+ ];
509
+
510
+ // ../core/dist/outbound.js
511
+ function ownedTransport(policy) {
512
+ if (!["offline", "allowlist"].includes(policy.mode) || policy.origins?.some((origin) => {
513
+ try {
514
+ return new URL(origin).origin !== origin;
515
+ } catch {
516
+ return true;
517
+ }
518
+ }))
519
+ throw new Error("invalid outbound transport policy");
520
+ const reject = (namespace, reason) => {
521
+ try {
522
+ policy.onReject?.({ namespace, policy: policy.mode, reason });
523
+ } catch {
524
+ }
525
+ throw new Error(`outbound policy ${policy.mode}: ${reason}`);
526
+ };
527
+ return async (request, namespace, send) => {
528
+ if (policy.mode === "offline")
529
+ return reject(namespace, "delivery disabled");
530
+ const allowed = (url2) => ["http:", "https:"].includes(url2.protocol) && !url2.username && !url2.password && (policy.origins ?? []).includes(url2.origin);
531
+ let url = new URL(request.url);
532
+ if (!allowed(url))
533
+ return reject(namespace, "destination not allowed");
534
+ const max = policy.maxBodyBytes ?? 1024 * 1024;
535
+ const chunks = [];
536
+ let size = 0;
537
+ const reader = request.body?.getReader();
538
+ if (reader)
539
+ try {
540
+ for (; ; ) {
541
+ const item = await reader.read();
542
+ if (item.done)
543
+ break;
544
+ size += item.value.length;
545
+ if (size > max)
546
+ return reject(namespace, "body limit exceeded");
547
+ chunks.push(item.value);
548
+ }
549
+ } finally {
550
+ void reader.cancel().catch(() => {
551
+ });
552
+ reader.releaseLock();
553
+ }
554
+ const body = new Uint8Array(size);
555
+ let offset = 0;
556
+ for (const chunk of chunks) {
557
+ body.set(chunk, offset);
558
+ offset += chunk.length;
559
+ }
560
+ let method = request.method, headers = new Headers(request.headers);
561
+ for (let redirects = 0; ; redirects++) {
562
+ if (!allowed(url))
563
+ return reject(namespace, "redirect destination not allowed");
564
+ const response = await send(new Request(url, {
565
+ method,
566
+ headers,
567
+ ...method !== "GET" && method !== "HEAD" ? { body } : {},
568
+ redirect: "manual",
569
+ signal: request.signal
570
+ }));
571
+ if (![301, 302, 303, 307, 308].includes(response.status))
572
+ return response;
573
+ const location = response.headers.get("location");
574
+ if (!location)
575
+ return response;
576
+ await response.body?.cancel();
577
+ if (redirects >= (policy.maxRedirects ?? 5))
578
+ return reject(namespace, "redirect limit exceeded");
579
+ const next = new URL(location, url);
580
+ if (next.origin !== url.origin) {
581
+ headers = new Headers(headers);
582
+ for (const key of ["authorization", "cookie", "proxy-authorization"])
583
+ headers.delete(key);
584
+ }
585
+ if (response.status === 303 || (response.status === 301 || response.status === 302) && method === "POST") {
586
+ method = "GET";
587
+ headers.delete("content-length");
588
+ headers.delete("content-type");
589
+ }
590
+ url = next;
591
+ }
592
+ };
593
+ }
594
+
595
+ // src/server.ts
596
+ var DEFAULT_PORT = 8827;
597
+ function serve(redis, options = {}) {
598
+ const host = options.host ?? "127.0.0.1";
599
+ const port = options.port ?? 6379;
600
+ const sockets = /* @__PURE__ */ new Set();
601
+ const server = createServer({ keepAlive: true }, (socket) => {
602
+ if (options.admit && !options.admit()) {
603
+ socket.destroy();
604
+ return;
605
+ }
606
+ sockets.add(socket);
607
+ attach(redis, socket, () => sockets.delete(socket), options.controlPrivileged ?? false);
608
+ });
609
+ return new Promise((resolve, reject) => {
610
+ const fail = (error) => reject(error);
611
+ server.once("error", fail);
612
+ server.listen(port, host, () => {
613
+ server.off("error", fail);
614
+ const address = server.address();
615
+ const actual = address && typeof address === "object" ? address.port : port;
616
+ resolve({
617
+ get listening() {
618
+ return server.listening;
619
+ },
620
+ host,
621
+ port: actual,
622
+ close: () => shutdown(server, sockets, redis, options.closeEngine !== false)
623
+ });
624
+ });
625
+ });
626
+ }
627
+ function attach(redis, socket, onGone, controlPrivileged = false) {
628
+ const session = redis.createSession();
629
+ session.controlPrivileged = controlPrivileged;
630
+ const parser = new RespParser();
631
+ const pending = [];
632
+ let pumping = false;
633
+ const write = (reply) => {
634
+ if (!socket.destroyed) socket.write(encodeReply(reply, session.protocol));
635
+ };
636
+ session.onPush = write;
637
+ const stop = redis.onDisconnect((dropped) => {
638
+ if (dropped === session) socket.destroy();
639
+ });
640
+ const finish = () => {
641
+ redis.disconnect(session);
642
+ stop();
643
+ onGone();
644
+ };
645
+ socket.on("data", (chunk) => {
646
+ for (const reply of parser.push(chunk)) {
647
+ const command = asCommand(reply);
648
+ if ("t" in command) {
649
+ write(command);
650
+ continue;
651
+ }
652
+ pending.push(command);
653
+ }
654
+ void pump();
655
+ });
656
+ const pump = async () => {
657
+ if (pumping) return;
658
+ pumping = true;
659
+ try {
660
+ while (pending.length > 0) {
661
+ const command = pending.shift();
662
+ if (!command) break;
663
+ try {
664
+ const reply = await redis.perform(session, command.name, command.args);
665
+ write(reply);
666
+ if (session.quit) {
667
+ socket.end();
668
+ break;
669
+ }
670
+ } catch (error) {
671
+ if (error instanceof RedisConnectionError) {
672
+ socket.destroy();
673
+ break;
674
+ }
675
+ socket.destroy();
676
+ break;
677
+ }
678
+ }
679
+ } finally {
680
+ pumping = false;
681
+ if (pending.length > 0 && !socket.destroyed) void pump();
682
+ }
683
+ };
684
+ socket.on("close", finish);
685
+ socket.on("error", finish);
686
+ }
687
+ function shutdown(server, sockets, redis, closeEngine = true) {
688
+ if (closeEngine) redis.close();
689
+ for (const socket of sockets) socket.destroy();
690
+ return new Promise((resolve) => {
691
+ server.close(() => resolve());
692
+ });
693
+ }
694
+ var isHealth = (pathname, adminPrefix) => {
695
+ const path = pathname.replace(/\/+$/, "") || "/";
696
+ return path === `${adminPrefix}/health` || matchNamespacePath(path, adminPrefix)?.[2] === `${adminPrefix}/health`;
697
+ };
698
+ var serveTarget = {
699
+ name: "redis",
700
+ protocol: "redis",
701
+ defaultPort: 6379,
702
+ start: startProtocol,
703
+ async create(_values = {}, common = {}) {
704
+ const redis = createRedis();
705
+ const tcp = await serve(redis, { host: "127.0.0.1", port: 0 });
706
+ const runtime = {
707
+ respPort: tcp.port,
708
+ close: () => tcp.close(),
709
+ fetch: async (request) => {
710
+ if (request.method === "GET" && isHealth(new URL(request.url).pathname, resolveAdminPrefix(common.adminPrefix))) {
711
+ return Response.json({ status: "ok", service: "redis" });
712
+ }
713
+ return new Response("not found", { status: 404 });
714
+ }
715
+ };
716
+ return runtime;
717
+ },
718
+ banner(runtime) {
719
+ return [`resp: redis://127.0.0.1:${runtime.respPort}`];
720
+ }
721
+ };
722
+ async function startProtocol(entry) {
723
+ const namespaces = /* @__PURE__ */ new Map();
724
+ const selectors = { default: 0, ...entry.namespaces };
725
+ if (entry.seed !== void 0 && (!String(entry.seed).trim() || !Number.isFinite(Number(entry.seed))))
726
+ throw new Error("Redis seed must be a finite number");
727
+ let admission;
728
+ const boot = normalizeBootControls(entry.adminControls);
729
+ const create = async (name2, database, port = 0) => {
730
+ if (!/^[A-Za-z0-9_.-]{1,64}$/.test(name2)) throw new Error("invalid Redis namespace");
731
+ if (!Number.isInteger(database) || database < 0 || database > 15)
732
+ throw new Error("invalid Redis database index");
733
+ const redis = createRedis({
734
+ ...entry.password !== void 0 ? { password: entry.password } : {},
735
+ ...entry.seed !== void 0 ? { seed: Number(entry.seed) } : {}
736
+ });
737
+ const control = { ...boot.shared.clock, ...boot.namespaces[name2]?.clock };
738
+ if (control.frozen) redis.clock.freeze();
739
+ if (control.now !== void 0) redis.clock.set(control.now);
740
+ const listener = await serve(redis, {
741
+ host: entry.host ?? "127.0.0.1",
742
+ port,
743
+ admit: () => admission?.(name2) !== false
744
+ });
745
+ namespaces.set(name2, { redis, listener, database });
746
+ };
747
+ try {
748
+ for (const [name2, database] of Object.entries(selectors))
749
+ await create(name2, database, name2 === "default" ? entry.port ?? 6379 : 0);
750
+ } catch (error) {
751
+ await Promise.allSettled([...namespaces.values()].map(({ listener }) => listener.close()));
752
+ throw error;
753
+ }
754
+ const get = (name2) => {
755
+ const found = namespaces.get(name2);
756
+ if (!found) throw new Error(`Redis namespace ${name2} is not configured`);
757
+ return found;
758
+ };
759
+ const url = (name2, privateUrl = false) => {
760
+ const { listener, database } = get(name2);
761
+ const host = listener.host.includes(":") ? `[${listener.host}]` : listener.host;
762
+ const auth = privateUrl && entry.password !== void 0 ? `:${encodeURIComponent(entry.password)}@` : "";
763
+ return `redis://${auth}${host}:${listener.port}/${database}`;
764
+ };
765
+ return {
766
+ protocol: "redis",
767
+ url: url("default"),
768
+ connection: url("default", true),
769
+ get connections() {
770
+ return Object.fromEntries([...namespaces.keys()].map((name2) => [name2, url(name2, true)]));
771
+ },
772
+ get namespaces() {
773
+ return {
774
+ mechanism: "endpoint",
775
+ endpoints: Object.fromEntries([...namespaces.keys()].map((name2) => [name2, url(name2)]))
776
+ };
777
+ },
778
+ async createNamespace(name2) {
779
+ if (namespaces.has(name2)) throw new Error("namespace already exists");
780
+ await create(name2, 0);
781
+ },
782
+ async deleteNamespace(name2) {
783
+ const { redis, listener } = get(name2);
784
+ if (redis.activeCommands() || redis.waiterCount() || redis.activeJobs() || redis.connections())
785
+ throw new Error("Redis namespace has active clients or work");
786
+ await listener.close();
787
+ namespaces.delete(name2);
788
+ },
789
+ async exportCheckpoint(name2, point) {
790
+ return get(name2).redis.exportSnapshot(point);
791
+ },
792
+ async importCheckpoint(name2, document) {
793
+ return (namespaces.get(name2) ?? get("default")).redis.importSnapshot(document);
794
+ },
795
+ async inspect(name2, { offset, limit, collection }) {
796
+ const { redis, database } = get(name2);
797
+ const keys = redis.inspect(database);
798
+ return {
799
+ total: keys.length,
800
+ keys: keys.filter((key) => collection === void 0 || key.key === collection).slice(offset, offset + limit),
801
+ pendingJobs: redis.pendingJobs(),
802
+ activeJobs: redis.activeJobs()
803
+ };
804
+ },
805
+ async initializationAccess() {
806
+ const listeners = [];
807
+ const connections = {};
808
+ try {
809
+ for (const [name2, { redis, database }] of namespaces) {
810
+ const seed = await serve(redis, {
811
+ port: 0,
812
+ host: "127.0.0.1",
813
+ closeEngine: false,
814
+ controlPrivileged: true
815
+ });
816
+ listeners.push(seed);
817
+ connections[name2] = `redis://${entry.password ? `:${encodeURIComponent(entry.password)}@` : ""}127.0.0.1:${seed.port}/${database}`;
818
+ }
819
+ } catch (error) {
820
+ await Promise.allSettled(listeners.map((l) => l.close()));
821
+ throw error;
822
+ }
823
+ return {
824
+ connections,
825
+ close: async () => {
826
+ await Promise.all(listeners.map((l) => l.close()));
827
+ }
828
+ };
829
+ },
830
+ setAdmission(allow) {
831
+ admission = allow;
832
+ },
833
+ async ready() {
834
+ if (admission) return [...namespaces.values()].every(({ listener }) => listener.listening);
835
+ const ready = (await Promise.all(
836
+ [...namespaces.values()].map(
837
+ ({ listener, database }) => probe(listener, database, entry.password)
838
+ )
839
+ )).every(Boolean);
840
+ const deadline = Date.now() + 2e3;
841
+ while ([...namespaces.values()].some(({ redis }) => redis.connections() > 0) && Date.now() < deadline)
842
+ await new Promise((resolve) => setTimeout(resolve, 1));
843
+ return ready;
844
+ },
845
+ async close() {
846
+ await Promise.all([...namespaces.values()].map(({ listener }) => listener.close()));
847
+ },
848
+ lock: (name2) => get(name2).redis.fence(),
849
+ diagnostics(name2) {
850
+ const { redis } = get(name2);
851
+ return {
852
+ activeRequests: redis.activeCommands(),
853
+ activeConnections: redis.connections(),
854
+ blockedCommands: redis.waiterCount(),
855
+ pendingJobs: redis.pendingJobs(),
856
+ activeJobs: redis.activeJobs(),
857
+ pendingWebhooks: 0,
858
+ unmatchedRequests: 0
859
+ };
860
+ },
861
+ async checkpoint(name2) {
862
+ return get(name2).redis.snapshot();
863
+ },
864
+ async restore(name2, point) {
865
+ get(name2).redis.restore(point);
866
+ },
867
+ async reset(name2) {
868
+ const { redis } = get(name2);
869
+ redis.reset();
870
+ const control = { ...boot.shared.clock, ...boot.namespaces[name2]?.clock };
871
+ if (control.frozen) redis.clock.freeze();
872
+ if (control.now !== void 0) redis.clock.set(control.now);
873
+ },
874
+ nextEvent: (name2) => get(name2).redis.nextEvent(),
875
+ async settle(name2) {
876
+ get(name2).redis.settleTimers();
877
+ },
878
+ clock: (name2) => get(name2).redis.clock
879
+ };
880
+ }
881
+ function probe(listener, database, password) {
882
+ return new Promise((resolve) => {
883
+ const socket = createConnection({ host: listener.host, port: listener.port });
884
+ const parser = new RespParser();
885
+ const commands = [
886
+ ...password !== void 0 ? [["AUTH", password]] : [],
887
+ ["SELECT", String(database)],
888
+ ["PING"]
889
+ ];
890
+ const expected = commands.map((command) => command[0] === "PING" ? "PONG" : "OK");
891
+ let result = false;
892
+ const finish = (ok) => {
893
+ result = ok;
894
+ socket.destroy();
895
+ };
896
+ const timeout = setTimeout(() => finish(false), 2e3);
897
+ socket.once("close", () => {
898
+ clearTimeout(timeout);
899
+ resolve(result);
900
+ });
901
+ socket.on("error", () => finish(false));
902
+ socket.once("connect", () => {
903
+ for (const command of commands)
904
+ socket.write(
905
+ `*${command.length}\r
906
+ ${command.map((arg) => `$${Buffer.byteLength(arg)}\r
907
+ ${arg}\r
908
+ `).join("")}`
909
+ );
910
+ });
911
+ socket.on("data", (data) => {
912
+ try {
913
+ for (const reply of parser.push(data)) {
914
+ if (reply.t !== "simple" || reply.v !== expected.shift()) {
915
+ finish(false);
916
+ return;
917
+ }
918
+ if (expected.length === 0) {
919
+ finish(true);
920
+ return;
921
+ }
922
+ }
923
+ } catch {
924
+ finish(false);
925
+ }
926
+ });
927
+ });
928
+ }
929
+
930
+ export {
931
+ createClock,
932
+ restoreClock,
933
+ parseDuration,
934
+ normalizeControls,
935
+ normalizeBootControls,
936
+ parseFaultHeader,
937
+ resolveAdminPrefix,
938
+ ownedTransport,
939
+ DEFAULT_PORT,
940
+ serve,
941
+ serveTarget
942
+ };
943
+ //# sourceMappingURL=chunk-LHUY4G3I.js.map