@crvouga/mockingbird-service-redis 2.2.0 → 2.3.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,766 @@
1
+ import {
2
+ RedisConnectionError,
3
+ RespParser,
4
+ asCommand,
5
+ createRedis,
6
+ encodeReply
7
+ } from "./chunk-IWEHAJ2L.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" || 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
+ // src/server.ts
511
+ var DEFAULT_PORT = 8827;
512
+ function serve(redis, options = {}) {
513
+ const host = options.host ?? "127.0.0.1";
514
+ const port = options.port ?? 6379;
515
+ const sockets = /* @__PURE__ */ new Set();
516
+ const server = createServer({ keepAlive: true }, (socket) => {
517
+ sockets.add(socket);
518
+ attach(redis, socket, () => sockets.delete(socket));
519
+ });
520
+ return new Promise((resolve, reject) => {
521
+ const fail = (error) => reject(error);
522
+ server.once("error", fail);
523
+ server.listen(port, host, () => {
524
+ server.off("error", fail);
525
+ const address = server.address();
526
+ const actual = address && typeof address === "object" ? address.port : port;
527
+ resolve({
528
+ host,
529
+ port: actual,
530
+ close: () => shutdown(server, sockets, redis)
531
+ });
532
+ });
533
+ });
534
+ }
535
+ function attach(redis, socket, onGone) {
536
+ const session = redis.createSession();
537
+ const parser = new RespParser();
538
+ const pending = [];
539
+ let pumping = false;
540
+ const write = (reply) => {
541
+ if (!socket.destroyed) socket.write(encodeReply(reply, session.protocol));
542
+ };
543
+ session.onPush = write;
544
+ const stop = redis.onDisconnect((dropped) => {
545
+ if (dropped === session) socket.destroy();
546
+ });
547
+ const finish = () => {
548
+ redis.disconnect(session);
549
+ stop();
550
+ onGone();
551
+ };
552
+ socket.on("data", (chunk) => {
553
+ for (const reply of parser.push(chunk)) {
554
+ const command = asCommand(reply);
555
+ if ("t" in command) {
556
+ write(command);
557
+ continue;
558
+ }
559
+ pending.push(command);
560
+ }
561
+ void pump();
562
+ });
563
+ const pump = async () => {
564
+ if (pumping) return;
565
+ pumping = true;
566
+ try {
567
+ while (pending.length > 0) {
568
+ const command = pending.shift();
569
+ if (!command) break;
570
+ try {
571
+ const reply = await redis.perform(session, command.name, command.args);
572
+ write(reply);
573
+ if (session.quit) {
574
+ socket.end();
575
+ break;
576
+ }
577
+ } catch (error) {
578
+ if (error instanceof RedisConnectionError) {
579
+ socket.destroy();
580
+ break;
581
+ }
582
+ socket.destroy();
583
+ break;
584
+ }
585
+ }
586
+ } finally {
587
+ pumping = false;
588
+ if (pending.length > 0 && !socket.destroyed) void pump();
589
+ }
590
+ };
591
+ socket.on("close", finish);
592
+ socket.on("error", finish);
593
+ }
594
+ function shutdown(server, sockets, redis) {
595
+ redis.close();
596
+ for (const socket of sockets) socket.destroy();
597
+ return new Promise((resolve) => {
598
+ server.close(() => resolve());
599
+ });
600
+ }
601
+ var isHealth = (pathname, adminPrefix) => {
602
+ const path = pathname.replace(/\/+$/, "") || "/";
603
+ return path === `${adminPrefix}/health` || matchNamespacePath(path, adminPrefix)?.[2] === `${adminPrefix}/health`;
604
+ };
605
+ var serveTarget = {
606
+ name: "redis",
607
+ protocol: "redis",
608
+ defaultPort: 6379,
609
+ start: startProtocol,
610
+ async create(_values = {}, common = {}) {
611
+ const redis = createRedis();
612
+ const tcp = await serve(redis, { host: "127.0.0.1", port: 0 });
613
+ const runtime = {
614
+ respPort: tcp.port,
615
+ close: () => tcp.close(),
616
+ fetch: async (request) => {
617
+ if (request.method === "GET" && isHealth(new URL(request.url).pathname, resolveAdminPrefix(common.adminPrefix))) {
618
+ return Response.json({ status: "ok", service: "redis" });
619
+ }
620
+ return new Response("not found", { status: 404 });
621
+ }
622
+ };
623
+ return runtime;
624
+ },
625
+ banner(runtime) {
626
+ return [`resp: redis://127.0.0.1:${runtime.respPort}`];
627
+ }
628
+ };
629
+ async function startProtocol(entry) {
630
+ const namespaces = /* @__PURE__ */ new Map();
631
+ const selectors = { default: 0, ...entry.namespaces };
632
+ try {
633
+ for (const [name2, database] of Object.entries(selectors)) {
634
+ if (!/^[A-Za-z0-9_.-]{1,64}$/.test(name2)) throw new Error("invalid Redis namespace");
635
+ if (typeof database !== "number" || !Number.isInteger(database) || database < 0 || database > 15)
636
+ throw new Error("invalid Redis database index");
637
+ const redis = createRedis({
638
+ ...entry.password !== void 0 ? { password: entry.password } : {},
639
+ ...entry.seed !== void 0 ? { seed: Number(entry.seed) } : {}
640
+ });
641
+ const listener = await serve(redis, {
642
+ host: entry.host ?? "127.0.0.1",
643
+ port: name2 === "default" ? entry.port ?? 6379 : 0
644
+ });
645
+ namespaces.set(name2, { redis, listener, database });
646
+ }
647
+ } catch (error) {
648
+ await Promise.allSettled([...namespaces.values()].map(({ listener }) => listener.close()));
649
+ throw error;
650
+ }
651
+ const get = (name2) => {
652
+ const found = namespaces.get(name2);
653
+ if (!found) throw new Error(`Redis namespace ${name2} is not configured`);
654
+ return found;
655
+ };
656
+ const url = (name2, privateUrl = false) => {
657
+ const { listener, database } = get(name2);
658
+ const host = listener.host.includes(":") ? `[${listener.host}]` : listener.host;
659
+ const auth = privateUrl && entry.password !== void 0 ? `:${encodeURIComponent(entry.password)}@` : "";
660
+ return `redis://${auth}${host}:${listener.port}/${database}`;
661
+ };
662
+ return {
663
+ protocol: "redis",
664
+ url: url("default"),
665
+ connection: url("default", true),
666
+ connections: Object.fromEntries([...namespaces.keys()].map((name2) => [name2, url(name2, true)])),
667
+ namespaces: {
668
+ mechanism: "endpoint",
669
+ endpoints: Object.fromEntries([...namespaces.keys()].map((name2) => [name2, url(name2)]))
670
+ },
671
+ async ready() {
672
+ return (await Promise.all(
673
+ [...namespaces.values()].map(
674
+ ({ listener, database }) => probe(listener, database, entry.password)
675
+ )
676
+ )).every(Boolean);
677
+ },
678
+ async close() {
679
+ await Promise.all([...namespaces.values()].map(({ listener }) => listener.close()));
680
+ },
681
+ lock: (name2) => get(name2).redis.fence(),
682
+ diagnostics(name2) {
683
+ const { redis } = get(name2);
684
+ return {
685
+ activeRequests: redis.activeCommands(),
686
+ activeConnections: redis.connections(),
687
+ blockedCommands: redis.waiterCount(),
688
+ pendingJobs: redis.pendingJobs(),
689
+ activeJobs: redis.activeJobs(),
690
+ pendingWebhooks: 0,
691
+ unmatchedRequests: 0
692
+ };
693
+ },
694
+ async checkpoint(name2) {
695
+ return get(name2).redis.snapshot();
696
+ },
697
+ async restore(name2, point) {
698
+ get(name2).redis.restore(point);
699
+ },
700
+ async reset(name2) {
701
+ get(name2).redis.reset();
702
+ },
703
+ clock: (name2) => get(name2).redis.clock
704
+ };
705
+ }
706
+ function probe(listener, database, password) {
707
+ return new Promise((resolve) => {
708
+ const socket = createConnection({ host: listener.host, port: listener.port });
709
+ const parser = new RespParser();
710
+ const commands = [
711
+ ...password !== void 0 ? [["AUTH", password]] : [],
712
+ ["SELECT", String(database)],
713
+ ["PING"]
714
+ ];
715
+ const expected = commands.map((command) => command[0] === "PING" ? "PONG" : "OK");
716
+ let result = false;
717
+ const finish = (ok) => {
718
+ result = ok;
719
+ socket.destroy();
720
+ };
721
+ const timeout = setTimeout(() => finish(false), 2e3);
722
+ socket.once("close", () => {
723
+ clearTimeout(timeout);
724
+ resolve(result);
725
+ });
726
+ socket.on("error", () => finish(false));
727
+ socket.once("connect", () => {
728
+ for (const command of commands)
729
+ socket.write(
730
+ `*${command.length}\r
731
+ ${command.map((arg) => `$${Buffer.byteLength(arg)}\r
732
+ ${arg}\r
733
+ `).join("")}`
734
+ );
735
+ });
736
+ socket.on("data", (data) => {
737
+ try {
738
+ for (const reply of parser.push(data)) {
739
+ if (reply.t !== "simple" || reply.v !== expected.shift()) {
740
+ finish(false);
741
+ return;
742
+ }
743
+ if (expected.length === 0) {
744
+ finish(true);
745
+ return;
746
+ }
747
+ }
748
+ } catch {
749
+ finish(false);
750
+ }
751
+ });
752
+ });
753
+ }
754
+
755
+ export {
756
+ createClock,
757
+ restoreClock,
758
+ parseDuration,
759
+ normalizeBootControls,
760
+ parseFaultHeader,
761
+ resolveAdminPrefix,
762
+ DEFAULT_PORT,
763
+ serve,
764
+ serveTarget
765
+ };
766
+ //# sourceMappingURL=chunk-LHM64CLD.js.map