@rocicorp/zero 1.7.0 → 1.8.0-canary.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.
- package/out/zero/package.js +1 -1
- package/out/zero/package.js.map +1 -1
- package/out/zero-cache/src/config/normalize.d.ts.map +1 -1
- package/out/zero-cache/src/config/normalize.js +2 -0
- package/out/zero-cache/src/config/normalize.js.map +1 -1
- package/out/zero-cache/src/config/zero-config.d.ts +45 -0
- package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
- package/out/zero-cache/src/config/zero-config.js +54 -1
- package/out/zero-cache/src/config/zero-config.js.map +1 -1
- package/out/zero-cache/src/custom/fetch.d.ts.map +1 -1
- package/out/zero-cache/src/custom/fetch.js +1 -14
- package/out/zero-cache/src/custom/fetch.js.map +1 -1
- package/out/zero-cache/src/custom-queries/transform-query.d.ts.map +1 -1
- package/out/zero-cache/src/custom-queries/transform-query.js +5 -6
- package/out/zero-cache/src/custom-queries/transform-query.js.map +1 -1
- package/out/zero-cache/src/server/backup-watermark-reader.js +35 -0
- package/out/zero-cache/src/server/backup-watermark-reader.js.map +1 -0
- package/out/zero-cache/src/server/change-streamer.d.ts.map +1 -1
- package/out/zero-cache/src/server/change-streamer.js +15 -7
- package/out/zero-cache/src/server/change-streamer.js.map +1 -1
- package/out/zero-cache/src/server/syncer.d.ts.map +1 -1
- package/out/zero-cache/src/server/syncer.js +1 -0
- package/out/zero-cache/src/server/syncer.js.map +1 -1
- package/out/zero-cache/src/server/worker-urls.d.ts +1 -0
- package/out/zero-cache/src/server/worker-urls.d.ts.map +1 -1
- package/out/zero-cache/src/server/worker-urls.js +2 -1
- package/out/zero-cache/src/server/worker-urls.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.js +13 -2
- package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.d.ts +18 -0
- package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.js +17 -0
- package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/backup-monitor.d.ts +4 -89
- package/out/zero-cache/src/services/change-streamer/backup-monitor.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/litestream3-backup-monitor.d.ts +93 -0
- package/out/zero-cache/src/services/change-streamer/litestream3-backup-monitor.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/{backup-monitor.js → litestream3-backup-monitor.js} +7 -7
- package/out/zero-cache/src/services/change-streamer/{backup-monitor.js.map → litestream3-backup-monitor.js.map} +1 -1
- package/out/zero-cache/src/services/change-streamer/replica-monitor.d.ts +2 -2
- package/out/zero-cache/src/services/change-streamer/replica-monitor.js +2 -2
- package/out/zero-cache/src/services/change-streamer/replica-monitor.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/storer.d.ts +2 -1
- package/out/zero-cache/src/services/change-streamer/storer.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/storer.js +44 -4
- package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/vfs-backup-monitor.d.ts +25 -0
- package/out/zero-cache/src/services/change-streamer/vfs-backup-monitor.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/vfs-backup-monitor.js +140 -0
- package/out/zero-cache/src/services/change-streamer/vfs-backup-monitor.js.map +1 -0
- package/out/zero-cache/src/services/litestream/commands.js.map +1 -1
- package/out/zero-cache/src/services/litestream/vfs-watermark-reader.d.ts +44 -0
- package/out/zero-cache/src/services/litestream/vfs-watermark-reader.d.ts.map +1 -0
- package/out/zero-cache/src/services/litestream/vfs-watermark-reader.js +65 -0
- package/out/zero-cache/src/services/litestream/vfs-watermark-reader.js.map +1 -0
- package/out/zero-cache/src/services/litestream/vfs-watermark-worker-source.d.ts +11 -0
- package/out/zero-cache/src/services/litestream/vfs-watermark-worker-source.d.ts.map +1 -0
- package/out/zero-cache/src/services/litestream/vfs-watermark-worker-source.js +74 -0
- package/out/zero-cache/src/services/litestream/vfs-watermark-worker-source.js.map +1 -0
- package/out/zero-cache/src/services/litestream/vfs-watermark-worker.d.ts +42 -0
- package/out/zero-cache/src/services/litestream/vfs-watermark-worker.d.ts.map +1 -0
- package/out/zero-cache/src/services/litestream/vfs-watermark-worker.js +117 -0
- package/out/zero-cache/src/services/litestream/vfs-watermark-worker.js.map +1 -0
- package/out/zero-cache/src/services/replicator/incremental-sync.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.js +9 -2
- package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
- package/out/zero-cache/src/services/replicator/notifier.d.ts +1 -0
- package/out/zero-cache/src/services/replicator/notifier.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/notifier.js +7 -1
- package/out/zero-cache/src/services/replicator/notifier.js.map +1 -1
- package/out/zero-cache/src/services/replicator/replicator.d.ts +11 -1
- package/out/zero-cache/src/services/replicator/replicator.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/replicator.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/client-handler.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/client-handler.js +6 -2
- package/out/zero-cache/src/services/view-syncer/client-handler.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/connection-context-manager.d.ts +3 -1
- package/out/zero-cache/src/services/view-syncer/connection-context-manager.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/connection-context-manager.js +12 -8
- package/out/zero-cache/src/services/view-syncer/connection-context-manager.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts +4 -0
- package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.js +14 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
- package/out/zero-cache/src/types/processes.d.ts +25 -0
- package/out/zero-cache/src/types/processes.d.ts.map +1 -1
- package/out/zero-cache/src/types/processes.js +35 -2
- package/out/zero-cache/src/types/processes.js.map +1 -1
- package/out/zero-cache/src/workers/connect-params.d.ts +2 -1
- package/out/zero-cache/src/workers/connect-params.d.ts.map +1 -1
- package/out/zero-cache/src/workers/connect-params.js +15 -1
- package/out/zero-cache/src/workers/connect-params.js.map +1 -1
- package/out/zero-cache/src/workers/replicator.d.ts +2 -2
- package/out/zero-cache/src/workers/replicator.d.ts.map +1 -1
- package/out/zero-cache/src/workers/replicator.js +5 -2
- package/out/zero-cache/src/workers/replicator.js.map +1 -1
- package/out/zero-cache/src/workers/syncer.d.ts +17 -0
- package/out/zero-cache/src/workers/syncer.d.ts.map +1 -1
- package/out/zero-cache/src/workers/syncer.js +116 -1
- package/out/zero-cache/src/workers/syncer.js.map +1 -1
- package/out/zero-client/src/client/query-manager.d.ts +10 -0
- package/out/zero-client/src/client/query-manager.d.ts.map +1 -1
- package/out/zero-client/src/client/query-manager.js +19 -2
- package/out/zero-client/src/client/query-manager.js.map +1 -1
- package/out/zero-client/src/client/version.js +1 -1
- package/out/zero-client/src/client/zero.d.ts.map +1 -1
- package/out/zero-client/src/client/zero.js +5 -1
- package/out/zero-client/src/client/zero.js.map +1 -1
- package/out/zero-server/src/adapters/drizzle.d.ts +30 -7
- package/out/zero-server/src/adapters/drizzle.d.ts.map +1 -1
- package/out/zero-server/src/adapters/drizzle.js +4 -2
- package/out/zero-server/src/adapters/drizzle.js.map +1 -1
- package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
- package/out/zql/src/ivm/memory-source.js +11 -0
- package/out/zql/src/ivm/memory-source.js.map +1 -1
- package/package.json +1 -1
|
@@ -15,6 +15,8 @@ export declare const MESSAGE_TYPES: {
|
|
|
15
15
|
readonly subscribe: "subscribe";
|
|
16
16
|
readonly notify: "notify";
|
|
17
17
|
readonly ready: "ready";
|
|
18
|
+
readonly backupWatermarkRequest: "backupWatermarkRequest";
|
|
19
|
+
readonly backupWatermarkResponse: "backupWatermarkResponse";
|
|
18
20
|
};
|
|
19
21
|
export type Message<Payload> = [keyof typeof MESSAGE_TYPES, Payload];
|
|
20
22
|
export interface Sender {
|
|
@@ -47,11 +49,34 @@ export interface Worker extends Subprocess, Receiver {
|
|
|
47
49
|
export declare const parentWorker: Worker | null;
|
|
48
50
|
export declare function singleProcessMode(): boolean;
|
|
49
51
|
export declare function setSingleProcessMode(enabled?: boolean): void;
|
|
52
|
+
/**
|
|
53
|
+
* Determines whether a module loaded as a worker process entry point should
|
|
54
|
+
* start its worker.
|
|
55
|
+
*
|
|
56
|
+
* Most workers are launched via {@link childWorker}, which in single-process
|
|
57
|
+
* mode runs them in-process (no real fork) by invoking their exported
|
|
58
|
+
* `runWorker` directly; those entry points must therefore *not* self-start in
|
|
59
|
+
* single-process mode, or they would run twice.
|
|
60
|
+
*
|
|
61
|
+
* A worker launched via {@link forkChildWorker}, however, is *always* a real
|
|
62
|
+
* forked OS process — even in single-process mode — and it inherits the
|
|
63
|
+
* parent's `SINGLE_PROCESS` env. So {@link singleProcessMode} alone would
|
|
64
|
+
* wrongly suppress its startup, leaving the parent to spin re-forking a child
|
|
65
|
+
* that immediately exits. Such a forked child has a non-null
|
|
66
|
+
* {@link parentWorker} (`process.send` is defined), which is the signal to
|
|
67
|
+
* start regardless. A standalone direct launch (no parent, not single-process)
|
|
68
|
+
* also starts.
|
|
69
|
+
*
|
|
70
|
+
* @param parent The entry point's {@link parentWorker} (non-null iff forked).
|
|
71
|
+
* @param isSingleProcessMode The result of {@link singleProcessMode}.
|
|
72
|
+
*/
|
|
73
|
+
export declare function shouldStartWorker(parent: Worker | null, isSingleProcessMode: boolean): boolean;
|
|
50
74
|
/**
|
|
51
75
|
*
|
|
52
76
|
* @param modulePath Path to the module file, relative to zero-cache/src/, or an absolute file:// URL
|
|
53
77
|
*/
|
|
54
78
|
export declare function childWorker(moduleUrl: URL, env?: NodeJS.ProcessEnv, ...args: string[]): Worker;
|
|
79
|
+
export declare function forkChildWorker(moduleUrl: URL, env?: NodeJS.ProcessEnv, ...args: string[]): Worker;
|
|
55
80
|
/**
|
|
56
81
|
* Creates two connected `Worker` instances such that messages sent to one
|
|
57
82
|
* via the {@link Worker.send()} method are received by the other's
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"processes.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/types/processes.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,UAAU,EAEhB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,YAAY,MAAM,aAAa,CAAC;AAIvC;;;;;;;;GAQG;AACH,eAAO,MAAM,aAAa
|
|
1
|
+
{"version":3,"file":"processes.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/types/processes.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,UAAU,EAEhB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,YAAY,MAAM,aAAa,CAAC;AAIvC;;;;;;;;GAQG;AACH,eAAO,MAAM,aAAa;;;;;;;;CAQhB,CAAC;AAEX,MAAM,MAAM,OAAO,CAAC,OAAO,IAAI,CAAC,MAAM,OAAO,aAAa,EAAE,OAAO,CAAC,CAAC;AAwCrE,MAAM,WAAW,MAAM;IACrB,IAAI,CAAC,CAAC,SAAS,OAAO,CAAC,OAAO,CAAC,EAC7B,OAAO,EAAE,CAAC,EACV,UAAU,CAAC,EAAE,UAAU,EACvB,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,KAAK,IAAI,GACvC,OAAO,CAAC;IAEX,IAAI,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC,OAAO,GAAG,IAAI,CAAC;CACrC;AAED,MAAM,WAAW,UAAW,SAAQ,M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ER;AAuBD;;;;;;;;GAQG;AACH,wBAAgB,aAAa,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CA+BhD"}
|
|
@@ -53,11 +53,35 @@ function singleProcessMode() {
|
|
|
53
53
|
return singleProcessOverride || (process.env[SINGLE_PROCESS] ?? "0") !== "0";
|
|
54
54
|
}
|
|
55
55
|
/**
|
|
56
|
+
* Determines whether a module loaded as a worker process entry point should
|
|
57
|
+
* start its worker.
|
|
58
|
+
*
|
|
59
|
+
* Most workers are launched via {@link childWorker}, which in single-process
|
|
60
|
+
* mode runs them in-process (no real fork) by invoking their exported
|
|
61
|
+
* `runWorker` directly; those entry points must therefore *not* self-start in
|
|
62
|
+
* single-process mode, or they would run twice.
|
|
63
|
+
*
|
|
64
|
+
* A worker launched via {@link forkChildWorker}, however, is *always* a real
|
|
65
|
+
* forked OS process — even in single-process mode — and it inherits the
|
|
66
|
+
* parent's `SINGLE_PROCESS` env. So {@link singleProcessMode} alone would
|
|
67
|
+
* wrongly suppress its startup, leaving the parent to spin re-forking a child
|
|
68
|
+
* that immediately exits. Such a forked child has a non-null
|
|
69
|
+
* {@link parentWorker} (`process.send` is defined), which is the signal to
|
|
70
|
+
* start regardless. A standalone direct launch (no parent, not single-process)
|
|
71
|
+
* also starts.
|
|
72
|
+
*
|
|
73
|
+
* @param parent The entry point's {@link parentWorker} (non-null iff forked).
|
|
74
|
+
* @param isSingleProcessMode The result of {@link singleProcessMode}.
|
|
75
|
+
*/
|
|
76
|
+
function shouldStartWorker(parent, isSingleProcessMode) {
|
|
77
|
+
return parent !== null || !isSingleProcessMode;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
56
80
|
*
|
|
57
81
|
* @param modulePath Path to the module file, relative to zero-cache/src/, or an absolute file:// URL
|
|
58
82
|
*/
|
|
59
83
|
function childWorker(moduleUrl, env, ...args) {
|
|
60
|
-
args
|
|
84
|
+
args = workerArgs(args);
|
|
61
85
|
if (singleProcessMode()) {
|
|
62
86
|
const [parent, child] = inProcChannel();
|
|
63
87
|
import(moduleUrl.href).then(async ({ default: runWorker }) => {
|
|
@@ -72,6 +96,15 @@ function childWorker(moduleUrl, env, ...args) {
|
|
|
72
96
|
}).catch((err) => child.emit("error", err));
|
|
73
97
|
return child;
|
|
74
98
|
}
|
|
99
|
+
return forkChildWorkerWithArgs(moduleUrl, env, args);
|
|
100
|
+
}
|
|
101
|
+
function forkChildWorker(moduleUrl, env, ...args) {
|
|
102
|
+
return forkChildWorkerWithArgs(moduleUrl, env, workerArgs(args));
|
|
103
|
+
}
|
|
104
|
+
function workerArgs(args) {
|
|
105
|
+
return [...args, ...process.argv.slice(2)];
|
|
106
|
+
}
|
|
107
|
+
function forkChildWorkerWithArgs(moduleUrl, env, args) {
|
|
75
108
|
return wrap(fork(moduleUrl, args, {
|
|
76
109
|
detached: platform() !== "win32",
|
|
77
110
|
serialization: "advanced",
|
|
@@ -107,6 +140,6 @@ function inProcChannel() {
|
|
|
107
140
|
}))];
|
|
108
141
|
}
|
|
109
142
|
//#endregion
|
|
110
|
-
export { childWorker, parentWorker, singleProcessMode };
|
|
143
|
+
export { childWorker, forkChildWorker, parentWorker, shouldStartWorker, singleProcessMode };
|
|
111
144
|
|
|
112
145
|
//# sourceMappingURL=processes.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"processes.js","names":[],"sources":["../../../../../zero-cache/src/types/processes.ts"],"sourcesContent":["import {\n type ChildProcess,\n fork,\n type SendHandle,\n type Serializable,\n} from 'node:child_process';\nimport EventEmitter from 'node:events';\nimport {platform} from 'node:os';\nimport {pid} from 'node:process';\n\n/**\n * Central registry of message type names, which are used to identify\n * the payload in {@link Message} objects sent between processes. The\n * payloads themselves are implementation specific and defined in each\n * component; only the type name is reserved here to avoid collisions.\n *\n * Receiving logic can call {@link getMessage()} with the name of\n * the message of interest to filter messages to those of interest.\n */\nexport const MESSAGE_TYPES = {\n handoff: 'handoff',\n status: 'status',\n subscribe: 'subscribe',\n notify: 'notify',\n ready: 'ready',\n} as const;\n\nexport type Message<Payload> = [keyof typeof MESSAGE_TYPES, Payload];\n\nfunction getMessage<M extends Message<unknown>>(\n type: M[0],\n data: unknown,\n): M[1] | null {\n if (Array.isArray(data) && data.length === 2 && data[0] === type) {\n return data[1] as M[1];\n }\n return null;\n}\n\nfunction onMessageType<M extends Message<unknown>>(\n e: EventEmitter,\n type: M[0],\n handler: (msg: M[1], sendHandle?: SendHandle) => void,\n) {\n return e.on('message', (data, sendHandle) => {\n const msg = getMessage(type, data);\n if (msg) {\n handler(msg, sendHandle);\n }\n });\n}\n\nfunction onceMessageType<M extends Message<unknown>>(\n e: EventEmitter,\n type: M[0],\n handler: (msg: M[1], sendHandle?: SendHandle) => void,\n) {\n const listener = (data: unknown, sendHandle: SendHandle) => {\n const msg = getMessage(type, data);\n if (msg) {\n e.off('message', listener);\n handler(msg, sendHandle);\n }\n };\n return e.on('message', listener);\n}\n\nexport interface Sender {\n send<M extends Message<unknown>>(\n message: M,\n sendHandle?: SendHandle,\n callback?: (error: Error | null) => void,\n ): boolean;\n\n kill(signal?: NodeJS.Signals): void;\n}\n\nexport interface Subprocess extends Sender, EventEmitter {\n pid?: number | undefined;\n}\n\nexport interface Receiver extends EventEmitter {\n /**\n * The receiving side of {@link Sender.send()} that is a wrapper around\n * {@link on}('message', ...) that invokes the `handler` for messages of\n * the specified `type`.\n */\n onMessageType<M extends Message<unknown>>(\n type: M[0],\n handler: (msg: M[1], sendHandle?: SendHandle) => void,\n ): this;\n\n /**\n * The receiving side of {@link Sender.send()} that behaves like\n * {@link once}('message', ...) that invokes the `handler` for the next\n * message of the specified `type` and then unsubscribes.\n */\n onceMessageType<M extends Message<unknown>>(\n type: M[0],\n handler: (msg: M[1], sendHandle?: SendHandle) => void,\n ): this;\n}\n\nexport interface Worker extends Subprocess, Receiver {}\n\n/**\n * Adds the {@link Receiver.onMessageType()} and {@link Receiver.onceMessageType()}\n * methods to convert the given `EventEmitter` to a `Receiver`.\n */\nfunction wrap<P extends EventEmitter>(proc: P): P & Receiver {\n return new Proxy(proc, {\n get(target: P, prop: string | symbol, receiver: unknown) {\n switch (prop) {\n case 'onMessageType':\n return (\n type: keyof typeof MESSAGE_TYPES,\n handler: (msg: unknown, sendHandle?: SendHandle) => void,\n ) => {\n onMessageType(target, type, handler);\n return receiver; // this\n };\n case 'onceMessageType':\n return (\n type: keyof typeof MESSAGE_TYPES,\n handler: (msg: unknown, sendHandle?: SendHandle) => void,\n ) => {\n onceMessageType(target, type, handler);\n return receiver; // this\n };\n }\n return Reflect.get(target, prop, receiver);\n },\n }) as P & Receiver;\n}\n\ntype Proc = Pick<ChildProcess, 'send' | 'kill' | 'pid'> & EventEmitter;\n\n/**\n * The parentWorker for forked processes, or `null` if the process was not forked.\n * (Analogous to the `parentPort: MessagePort | null` of the `\"workers\"` library).\n */\nexport const parentWorker: Worker | null = process.send\n ? wrap(process as Proc)\n : null;\n\nconst SINGLE_PROCESS = 'SINGLE_PROCESS';\nlet singleProcessOverride = false;\nexport function singleProcessMode(): boolean {\n return singleProcessOverride || (process.env[SINGLE_PROCESS] ?? '0') !== '0';\n}\n\nexport function setSingleProcessMode(enabled: boolean = true): void {\n singleProcessOverride = enabled;\n}\n\n/**\n *\n * @param modulePath Path to the module file, relative to zero-cache/src/, or an absolute file:// URL\n */\nexport function childWorker(\n moduleUrl: URL,\n env?: NodeJS.ProcessEnv,\n ...args: string[]\n): Worker {\n args.push(...process.argv.slice(2));\n\n if (singleProcessMode()) {\n const [parent, child] = inProcChannel();\n import(moduleUrl.href)\n .then(async ({default: runWorker}) => {\n try {\n await runWorker(parent, env ?? process.env, ...args);\n child.emit('close', 0);\n return;\n } catch (err) {\n child.emit('error', err);\n child.emit('close', -1);\n }\n })\n .catch(err => child.emit('error', err));\n return child;\n }\n const child = fork(moduleUrl, args, {\n // For production / non-windows, set `detached` to `true` so that SIGINT is\n // not automatically propagated and graceful shutdown happens as intended.\n // For Win32, detached: true causes all subprocesses to open in separate\n // terminals and breaks inter-process kill signals, so set it to false.\n detached: platform() !== 'win32',\n serialization: 'advanced', // use structured clone for IPC\n env,\n });\n return wrap(child);\n}\n\n/**\n * Creates two connected `Worker` instances such that messages sent to one\n * via the {@link Worker.send()} method are received by the other's\n * `on('message', ...)` handler.\n *\n * This is analogous to the two `MessagePort`s of a `MessageChannel`, and\n * is useful for executing code written for inter-process communication\n * in a single process.\n */\nexport function inProcChannel(): [Worker, Worker] {\n const worker1 = new EventEmitter();\n const worker2 = new EventEmitter();\n\n const sendTo =\n (dest: EventEmitter) =>\n (\n message: Serializable,\n sendHandle?: SendHandle,\n callback?: (error: Error | null) => void,\n ) => {\n dest.emit('message', message, sendHandle);\n if (callback) {\n callback(null);\n }\n return true;\n };\n\n const kill =\n (dest: EventEmitter) =>\n (signal: NodeJS.Signals = 'SIGTERM') =>\n dest.emit(signal, signal);\n\n return [\n wrap(\n Object.assign(worker1, {send: sendTo(worker2), kill: kill(worker2), pid}),\n ),\n wrap(\n Object.assign(worker2, {send: sendTo(worker1), kill: kill(worker1), pid}),\n ),\n ];\n}\n"],"mappings":";;;;;AA6BA,SAAS,WACP,MACA,MACa;CACb,IAAI,MAAM,QAAQ,IAAI,KAAK,KAAK,WAAW,KAAK,KAAK,OAAO,MAC1D,OAAO,KAAK;CAEd,OAAO;AACT;AAEA,SAAS,cACP,GACA,MACA,SACA;CACA,OAAO,EAAE,GAAG,YAAY,MAAM,eAAe;EAC3C,MAAM,MAAM,WAAW,MAAM,IAAI;EACjC,IAAI,KACF,QAAQ,KAAK,UAAU;CAE3B,CAAC;AACH;AAEA,SAAS,gBACP,GACA,MACA,SACA;CACA,MAAM,YAAY,MAAe,eAA2B;EAC1D,MAAM,MAAM,WAAW,MAAM,IAAI;EACjC,IAAI,KAAK;GACP,EAAE,IAAI,WAAW,QAAQ;GACzB,QAAQ,KAAK,UAAU;EACzB;CACF;CACA,OAAO,EAAE,GAAG,WAAW,QAAQ;AACjC;;;;;AA4CA,SAAS,KAA6B,MAAuB;CAC3D,OAAO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I,UACF,SAAS,IAAI;EAEf,OAAO;CACT;CAEF,MAAM,QACH,UACA,SAAyB,cACxB,KAAK,KAAK,QAAQ,MAAM;CAE5B,OAAO,CACL,KACE,OAAO,OAAO,SAAS;EAAC,MAAM,OAAO,OAAO;EAAG,MAAM,KAAK,OAAO;EAAG;CAAG,CAAC,CAC1E,GACA,KACE,OAAO,OAAO,SAAS;EAAC,MAAM,OAAO,OAAO;EAAG,MAAM,KAAK,OAAO;EAAG;CAAG,CAAC,CAC1E,CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"processes.js","names":[],"sources":["../../../../../zero-cache/src/types/processes.ts"],"sourcesContent":["import {\n type ChildProcess,\n fork,\n type SendHandle,\n type Serializable,\n} from 'node:child_process';\nimport EventEmitter from 'node:events';\nimport {platform} from 'node:os';\nimport {pid} from 'node:process';\n\n/**\n * Central registry of message type names, which are used to identify\n * the payload in {@link Message} objects sent between processes. The\n * payloads themselves are implementation specific and defined in each\n * component; only the type name is reserved here to avoid collisions.\n *\n * Receiving logic can call {@link getMessage()} with the name of\n * the message of interest to filter messages to those of interest.\n */\nexport const MESSAGE_TYPES = {\n handoff: 'handoff',\n status: 'status',\n subscribe: 'subscribe',\n notify: 'notify',\n ready: 'ready',\n backupWatermarkRequest: 'backupWatermarkRequest',\n backupWatermarkResponse: 'backupWatermarkResponse',\n} as const;\n\nexport type Message<Payload> = [keyof typeof MESSAGE_TYPES, Payload];\n\nfunction getMessage<M extends Message<unknown>>(\n type: M[0],\n data: unknown,\n): M[1] | null {\n if (Array.isArray(data) && data.length === 2 && data[0] === type) {\n return data[1] as M[1];\n }\n return null;\n}\n\nfunction onMessageType<M extends Message<unknown>>(\n e: EventEmitter,\n type: M[0],\n handler: (msg: M[1], sendHandle?: SendHandle) => void,\n) {\n return e.on('message', (data, sendHandle) => {\n const msg = getMessage(type, data);\n if (msg) {\n handler(msg, sendHandle);\n }\n });\n}\n\nfunction onceMessageType<M extends Message<unknown>>(\n e: EventEmitter,\n type: M[0],\n handler: (msg: M[1], sendHandle?: SendHandle) => void,\n) {\n const listener = (data: unknown, sendHandle: SendHandle) => {\n const msg = getMessage(type, data);\n if (msg) {\n e.off('message', listener);\n handler(msg, sendHandle);\n }\n };\n return e.on('message', listener);\n}\n\nexport interface Sender {\n send<M extends Message<unknown>>(\n message: M,\n sendHandle?: SendHandle,\n callback?: (error: Error | null) => void,\n ): boolean;\n\n kill(signal?: NodeJS.Signals): void;\n}\n\nexport interface Subprocess extends Sender, EventEmitter {\n pid?: number | undefined;\n}\n\nexport interface Receiver extends EventEmitter {\n /**\n * The receiving side of {@link Sender.send()} that is a wrapper around\n * {@link on}('message', ...) that invokes the `handler` for messages of\n * the specified `type`.\n */\n onMessageType<M extends Message<unknown>>(\n type: M[0],\n handler: (msg: M[1], sendHandle?: SendHandle) => void,\n ): this;\n\n /**\n * The receiving side of {@link Sender.send()} that behaves like\n * {@link once}('message', ...) that invokes the `handler` for the next\n * message of the specified `type` and then unsubscribes.\n */\n onceMessageType<M extends Message<unknown>>(\n type: M[0],\n handler: (msg: M[1], sendHandle?: SendHandle) => void,\n ): this;\n}\n\nexport interface Worker extends Subprocess, Receiver {}\n\n/**\n * Adds the {@link Receiver.onMessageType()} and {@link Receiver.onceMessageType()}\n * methods to convert the given `EventEmitter` to a `Receiver`.\n */\nfunction wrap<P extends EventEmitter>(proc: P): P & Receiver {\n return new Proxy(proc, {\n get(target: P, prop: string | symbol, receiver: unknown) {\n switch (prop) {\n case 'onMessageType':\n return (\n type: keyof typeof MESSAGE_TYPES,\n handler: (msg: unknown, sendHandle?: SendHandle) => void,\n ) => {\n onMessageType(target, type, handler);\n return receiver; // this\n };\n case 'onceMessageType':\n return (\n type: keyof typeof MESSAGE_TYPES,\n handler: (msg: unknown, sendHandle?: SendHandle) => void,\n ) => {\n onceMessageType(target, type, handler);\n return receiver; // this\n };\n }\n return Reflect.get(target, prop, receiver);\n },\n }) as P & Receiver;\n}\n\ntype Proc = Pick<ChildProcess, 'send' | 'kill' | 'pid'> & EventEmitter;\n\n/**\n * The parentWorker for forked processes, or `null` if the process was not forked.\n * (Analogous to the `parentPort: MessagePort | null` of the `\"workers\"` library).\n */\nexport const parentWorker: Worker | null = process.send\n ? wrap(process as Proc)\n : null;\n\nconst SINGLE_PROCESS = 'SINGLE_PROCESS';\nlet singleProcessOverride = false;\nexport function singleProcessMode(): boolean {\n return singleProcessOverride || (process.env[SINGLE_PROCESS] ?? '0') !== '0';\n}\n\nexport function setSingleProcessMode(enabled: boolean = true): void {\n singleProcessOverride = enabled;\n}\n\n/**\n * Determines whether a module loaded as a worker process entry point should\n * start its worker.\n *\n * Most workers are launched via {@link childWorker}, which in single-process\n * mode runs them in-process (no real fork) by invoking their exported\n * `runWorker` directly; those entry points must therefore *not* self-start in\n * single-process mode, or they would run twice.\n *\n * A worker launched via {@link forkChildWorker}, however, is *always* a real\n * forked OS process — even in single-process mode — and it inherits the\n * parent's `SINGLE_PROCESS` env. So {@link singleProcessMode} alone would\n * wrongly suppress its startup, leaving the parent to spin re-forking a child\n * that immediately exits. Such a forked child has a non-null\n * {@link parentWorker} (`process.send` is defined), which is the signal to\n * start regardless. A standalone direct launch (no parent, not single-process)\n * also starts.\n *\n * @param parent The entry point's {@link parentWorker} (non-null iff forked).\n * @param isSingleProcessMode The result of {@link singleProcessMode}.\n */\nexport function shouldStartWorker(\n parent: Worker | null,\n isSingleProcessMode: boolean,\n): boolean {\n return parent !== null || !isSingleProcessMode;\n}\n\n/**\n *\n * @param modulePath Path to the module file, relative to zero-cache/src/, or an absolute file:// URL\n */\nexport function childWorker(\n moduleUrl: URL,\n env?: NodeJS.ProcessEnv,\n ...args: string[]\n): Worker {\n args = workerArgs(args);\n\n if (singleProcessMode()) {\n const [parent, child] = inProcChannel();\n import(moduleUrl.href)\n .then(async ({default: runWorker}) => {\n try {\n await runWorker(parent, env ?? process.env, ...args);\n child.emit('close', 0);\n return;\n } catch (err) {\n child.emit('error', err);\n child.emit('close', -1);\n }\n })\n .catch(err => child.emit('error', err));\n return child;\n }\n return forkChildWorkerWithArgs(moduleUrl, env, args);\n}\n\nexport function forkChildWorker(\n moduleUrl: URL,\n env?: NodeJS.ProcessEnv,\n ...args: string[]\n): Worker {\n return forkChildWorkerWithArgs(moduleUrl, env, workerArgs(args));\n}\n\nfunction workerArgs(args: string[]): string[] {\n return [...args, ...process.argv.slice(2)];\n}\n\nfunction forkChildWorkerWithArgs(\n moduleUrl: URL,\n env: NodeJS.ProcessEnv | undefined,\n args: string[],\n): Worker {\n const child = fork(moduleUrl, args, {\n // For production / non-windows, set `detached` to `true` so that SIGINT is\n // not automatically propagated and graceful shutdown happens as intended.\n // For Win32, detached: true causes all subprocesses to open in separate\n // terminals and breaks inter-process kill signals, so set it to false.\n detached: platform() !== 'win32',\n serialization: 'advanced', // use structured clone for IPC\n env,\n });\n return wrap(child);\n}\n\n/**\n * Creates two connected `Worker` instances such that messages sent to one\n * via the {@link Worker.send()} method are received by the other's\n * `on('message', ...)` handler.\n *\n * This is analogous to the two `MessagePort`s of a `MessageChannel`, and\n * is useful for executing code written for inter-process communication\n * in a single process.\n */\nexport function inProcChannel(): [Worker, Worker] {\n const worker1 = new EventEmitter();\n const worker2 = new EventEmitter();\n\n const sendTo =\n (dest: EventEmitter) =>\n (\n message: Serializable,\n sendHandle?: SendHandle,\n callback?: (error: Error | null) => void,\n ) => {\n dest.emit('message', message, sendHandle);\n if (callback) {\n callback(null);\n }\n return true;\n };\n\n const kill =\n (dest: EventEmitter) =>\n (signal: NodeJS.Signals = 'SIGTERM') =>\n dest.emit(signal, signal);\n\n return [\n wrap(\n Object.assign(worker1, {send: sendTo(worker2), kill: kill(worker2), pid}),\n ),\n wrap(\n Object.assign(worker2, {send: sendTo(worker1), kill: kill(worker1), pid}),\n ),\n ];\n}\n"],"mappings":";;;;;AA+BA,SAAS,WACP,MACA,MACa;CACb,IAAI,MAAM,QAAQ,IAAI,KAAK,KAAK,WAAW,KAAK,KAAK,OAAO,MAC1D,OAAO,KAAK;CAEd,O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,QAAQ,OAAO,QAAQ,KAAK,GAAG,IAAI;IACnD,MAAM,KAAK,SAAS,CAAC;IACrB;GACF,SAAS,KAAK;IACZ,MAAM,KAAK,SAAS,GAAG;IACvB,MAAM,KAAK,SAAS,EAAE;GACxB;EACF,CAAC,EACA,OAAM,QAAO,MAAM,KAAK,SAAS,GAAG,CAAC;EACxC,OAAO;CACT;CACA,OAAO,wBAAwB,WAAW,KAAK,IAAI;AACrD;AAEA,SAAgB,gBACd,WACA,KACA,GAAG,MACK;CACR,OAAO,wBAAwB,WAAW,KAAK,WAAW,IAAI,CAAC;AACjE;AAEA,SAAS,WAAW,MAA0B;CAC5C,OAAO,CAAC,GAAG,MAAM,GAAG,QAAQ,KAAK,MAAM,CAAC,CAAC;AAC3C;AAEA,SAAS,wBACP,WACA,KACA,MACQ;CAUR,OAAO,KATO,KAAK,WAAW,MAAM;EAKlC,UAAU,SAAS,MAAM;EACzB,eAAe;EACf;CACF,CACY,CAAK;AACnB;;;;;;;;;;AAWA,SAAgB,gBAAkC;CAChD,MAAM,UAAU,IAAI,aAAa;CACjC,MAAM,UAAU,IAAI,aAAa;CAEjC,MAAM,UACH,UAEC,SACA,YACA,aACG;EACH,KAAK,KAAK,WAAW,SAAS,UAAU;EACxC,IAAI,UACF,SAAS,IAAI;EAEf,OAAO;CACT;CAEF,MAAM,QACH,UACA,SAAyB,cACxB,KAAK,KAAK,QAAQ,MAAM;CAE5B,OAAO,CACL,KACE,OAAO,OAAO,SAAS;EAAC,MAAM,OAAO,OAAO;EAAG,MAAM,KAAK,OAAO;EAAG;CAAG,CAAC,CAC1E,GACA,KACE,OAAO,OAAO,SAAS;EAAC,MAAM,OAAO,OAAO;EAAG,MAAM,KAAK,OAAO;EAAG;CAAG,CAAC,CAC1E,CACF;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { IncomingHttpHeaders } from 'node:
|
|
1
|
+
import type { IncomingHttpHeaders } from 'node:http';
|
|
2
2
|
import { type InitConnectionMessage } from '../../../zero-protocol/src/connect.ts';
|
|
3
3
|
export type ConnectParams = {
|
|
4
4
|
readonly protocolVersion: number;
|
|
@@ -15,6 +15,7 @@ export type ConnectParams = {
|
|
|
15
15
|
readonly initConnectionMsg: InitConnectionMessage | undefined;
|
|
16
16
|
readonly httpCookie: string | undefined;
|
|
17
17
|
readonly origin: string | undefined;
|
|
18
|
+
readonly requestHeaders?: Readonly<Record<string, string>> | undefined;
|
|
18
19
|
};
|
|
19
20
|
export declare function getConnectParams(protocolVersion: number, url: URL, headers: IncomingHttpHeaders): {
|
|
20
21
|
params: ConnectParams;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect-params.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/workers/connect-params.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,mBAAmB,EAAC,MAAM,
|
|
1
|
+
{"version":3,"file":"connect-params.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/workers/connect-params.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,mBAAmB,EAAC,MAAM,WAAW,CAAC;AAEnD,OAAO,EAEL,KAAK,qBAAqB,EAC3B,MAAM,uCAAuC,CAAC;AAG/C,MAAM,MAAM,aAAa,GAAG;IAC1B,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IACjC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,QAAQ,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IACnC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;IAC5B,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IAClC,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IACpC,QAAQ,CAAC,iBAAiB,EAAE,qBAAqB,GAAG,SAAS,CAAC;IAC9D,QAAQ,CAAC,UAAU,EAAE,MAAM,GAAG,SAAS,CAAC;IACxC,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IACpC,QAAQ,CAAC,cAAc,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GAAG,SAAS,CAAC;CACxE,CAAC;AAoBF,wBAAgB,gBAAgB,CAC9B,eAAe,EAAE,MAAM,EACvB,GAAG,EAAE,GAAG,EACR,OAAO,EAAE,mBAAmB,GAE1B;IACE,MAAM,EAAE,aAAa,CAAC;IACtB,KAAK,EAAE,IAAI,CAAC;CACb,GACD;IACE,MAAM,EAAE,IAAI,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;CACf,CA2CJ"}
|
|
@@ -2,6 +2,19 @@ import { must } from "../../../shared/src/must.js";
|
|
|
2
2
|
import { decodeSecProtocols } from "../../../zero-protocol/src/connect.js";
|
|
3
3
|
import { URLParams } from "../types/url-params.js";
|
|
4
4
|
//#region ../zero-cache/src/workers/connect-params.ts
|
|
5
|
+
/**
|
|
6
|
+
* Normalizes Node's {@link IncomingHttpHeaders} (whose values are
|
|
7
|
+
* `string | string[] | undefined`) into a plain `Record<string, string>`,
|
|
8
|
+
* joining array values with `, ` and dropping `undefined` values.
|
|
9
|
+
*/
|
|
10
|
+
function normalizeHeaders(headers) {
|
|
11
|
+
const normalized = {};
|
|
12
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
13
|
+
if (value === void 0) continue;
|
|
14
|
+
normalized[key] = Array.isArray(value) ? value.join(", ") : value;
|
|
15
|
+
}
|
|
16
|
+
return normalized;
|
|
17
|
+
}
|
|
5
18
|
function getConnectParams(protocolVersion, url, headers) {
|
|
6
19
|
const params = new URLParams(url);
|
|
7
20
|
try {
|
|
@@ -30,7 +43,8 @@ function getConnectParams(protocolVersion, url, headers) {
|
|
|
30
43
|
auth: authToken,
|
|
31
44
|
userID,
|
|
32
45
|
httpCookie: headers.cookie,
|
|
33
|
-
origin: headers.origin
|
|
46
|
+
origin: headers.origin,
|
|
47
|
+
requestHeaders: normalizeHeaders(headers)
|
|
34
48
|
},
|
|
35
49
|
error: null
|
|
36
50
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect-params.js","names":[],"sources":["../../../../../zero-cache/src/workers/connect-params.ts"],"sourcesContent":["import type {IncomingHttpHeaders} from 'node:
|
|
1
|
+
{"version":3,"file":"connect-params.js","names":[],"sources":["../../../../../zero-cache/src/workers/connect-params.ts"],"sourcesContent":["import type {IncomingHttpHeaders} from 'node:http';\nimport {must} from '../../../shared/src/must.ts';\nimport {\n decodeSecProtocols,\n type InitConnectionMessage,\n} from '../../../zero-protocol/src/connect.ts';\nimport {URLParams} from '../types/url-params.ts';\n\nexport type ConnectParams = {\n readonly protocolVersion: number;\n readonly clientID: string;\n readonly clientGroupID: string;\n readonly profileID: string | null;\n readonly baseCookie: string | null;\n readonly timestamp: number;\n readonly lmID: number;\n readonly wsID: string;\n readonly debugPerf: boolean;\n readonly auth: string | undefined;\n readonly userID: string | undefined;\n readonly initConnectionMsg: InitConnectionMessage | undefined;\n readonly httpCookie: string | undefined;\n readonly origin: string | undefined;\n readonly requestHeaders?: Readonly<Record<string, string>> | undefined;\n};\n\n/**\n * Normalizes Node's {@link IncomingHttpHeaders} (whose values are\n * `string | string[] | undefined`) into a plain `Record<string, string>`,\n * joining array values with `, ` and dropping `undefined` values.\n */\nfunction normalizeHeaders(\n headers: IncomingHttpHeaders,\n): Record<string, string> {\n const normalized: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n if (value === undefined) {\n continue;\n }\n normalized[key] = Array.isArray(value) ? value.join(', ') : value;\n }\n return normalized;\n}\n\nexport function getConnectParams(\n protocolVersion: number,\n url: URL,\n headers: IncomingHttpHeaders,\n):\n | {\n params: ConnectParams;\n error: null;\n }\n | {\n params: null;\n error: string;\n } {\n const params = new URLParams(url);\n\n try {\n const clientID = params.get('clientID', true);\n const clientGroupID = params.get('clientGroupID', true);\n const profileID = params.get('profileID', false);\n const baseCookie = params.get('baseCookie', false);\n const timestamp = params.getInteger('ts', true);\n const lmID = params.getInteger('lmid', true);\n const wsID = params.get('wsid', false) ?? '';\n const userID = params.get('userID', false) ?? undefined;\n const debugPerf = params.getBoolean('debugPerf');\n const {initConnectionMessage, authToken} = decodeSecProtocols(\n must(headers['sec-websocket-protocol']),\n );\n\n return {\n params: {\n protocolVersion,\n clientID,\n clientGroupID,\n profileID,\n baseCookie,\n timestamp,\n lmID,\n wsID,\n debugPerf,\n initConnectionMsg: initConnectionMessage,\n auth: authToken,\n userID,\n httpCookie: headers.cookie,\n origin: headers.origin,\n requestHeaders: normalizeHeaders(headers),\n },\n error: null,\n };\n } catch (e) {\n return {\n params: null,\n error: e instanceof Error ? e.message : String(e),\n };\n }\n}\n"],"mappings":";;;;;;;;;AA+BA,SAAS,iBACP,SACwB;CACxB,MAAM,aAAqC,CAAC;CAC5C,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,GAAG;EAClD,IAAI,UAAU,KAAA,GACZ;EAEF,WAAW,OAAO,MAAM,QAAQ,KAAK,IAAI,MAAM,KAAK,IAAI,IAAI;CAC9D;CACA,OAAO;AACT;AAEA,SAAgB,iBACd,iBACA,KACA,SASI;CACJ,MAAM,SAAS,IAAI,UAAU,GAAG;CAEhC,IAAI;EACF,MAAM,WAAW,OAAO,IAAI,YAAY,IAAI;EAC5C,MAAM,gBAAgB,OAAO,IAAI,iBAAiB,IAAI;EACtD,MAAM,YAAY,OAAO,IAAI,aAAa,KAAK;EAC/C,MAAM,aAAa,OAAO,IAAI,cAAc,KAAK;EACjD,MAAM,YAAY,OAAO,WAAW,MAAM,IAAI;EAC9C,MAAM,OAAO,OAAO,WAAW,QAAQ,IAAI;EAC3C,MAAM,OAAO,OAAO,IAAI,QAAQ,KAAK,KAAK;EAC1C,MAAM,SAAS,OAAO,IAAI,UAAU,KAAK,KAAK,KAAA;EAC9C,MAAM,YAAY,OAAO,WAAW,WAAW;EAC/C,MAAM,EAAC,uBAAuB,cAAa,mBACzC,KAAK,QAAQ,yBAAyB,CACxC;EAEA,OAAO;GACL,QAAQ;IACN;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,mBAAmB;IACnB,MAAM;IACN;IACA,YAAY,QAAQ;IACpB,QAAQ,QAAQ;IAChB,gBAAgB,iBAAiB,OAAO;GAC1C;GACA,OAAO;EACT;CACF,SAAS,GAAG;EACV,OAAO;GACL,QAAQ;GACR,OAAO,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC;EAClD;CACF;AACF"}
|
|
@@ -2,7 +2,7 @@ import type { LogContext } from '@rocicorp/logger';
|
|
|
2
2
|
import * as v from '../../../shared/src/valita.ts';
|
|
3
3
|
import type { ReplicaOptions } from '../config/zero-config.ts';
|
|
4
4
|
import { Notifier } from '../services/replicator/notifier.ts';
|
|
5
|
-
import type { ReplicaStateNotifier, Replicator } from '../services/replicator/replicator.ts';
|
|
5
|
+
import type { ReplicaState, ReplicaStateNotifier, Replicator } from '../services/replicator/replicator.ts';
|
|
6
6
|
import { type PragmaConfig } from '../services/replicator/write-worker-client.ts';
|
|
7
7
|
import type { Worker } from '../types/processes.ts';
|
|
8
8
|
export declare const replicaFileModeSchema: v.Type<"backup" | "serving" | "serving-copy">;
|
|
@@ -26,6 +26,6 @@ export declare function handleSubscriptionsFrom(lc: LogContext, subscriber: Work
|
|
|
26
26
|
* This does not send the initial subscription message. Use {@link subscribeTo}
|
|
27
27
|
* to initiate the subscription.
|
|
28
28
|
*/
|
|
29
|
-
export declare function createNotifierFrom(_lc: LogContext, source: Worker): Notifier;
|
|
29
|
+
export declare function createNotifierFrom(_lc: LogContext, source: Worker, onNotify?: (state: ReplicaState) => void): Notifier;
|
|
30
30
|
export declare function subscribeTo(_lc: LogContext, source: Worker): void;
|
|
31
31
|
//# sourceMappingURL=replicator.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"replicator.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/workers/replicator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,KAAK,CAAC,MAAM,+BAA+B,CAAC;AAEnD,OAAO,KAAK,EAAC,cAAc,EAAC,MAAM,0BAA0B,CAAC;AAG7D,OAAO,EAAC,QAAQ,EAAC,MAAM,oCAAoC,CAAC;AAC5D,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"replicator.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/workers/replicator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,KAAK,CAAC,MAAM,+BAA+B,CAAC;AAEnD,OAAO,KAAK,EAAC,cAAc,EAAC,MAAM,0BAA0B,CAAC;AAG7D,OAAO,EAAC,QAAQ,EAAC,MAAM,oCAAoC,CAAC;AAC5D,OAAO,KAAK,EACV,YAAY,EACZ,oBAAoB,EACpB,UAAU,EACX,MAAM,sCAAsC,CAAC;AAK9C,OAAO,EAEL,KAAK,YAAY,EAClB,MAAM,+CAA+C,CAAC;AACvD,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,uBAAuB,CAAC;AAElD,eAAO,MAAM,qBAAqB,+CAIjC,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAEpE,MAAM,MAAM,OAAO,GAAG,KAAK,GAAG,MAAM,CAAC;AAErC,wBAAgB,eAAe,CAAC,WAAW,EAAE,MAAM,EAAE,IAAI,EAAE,eAAe,UAEzE;AA0FD;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,eAAe,GAAG,YAAY,CAMnE;AAED,wBAAgB,YAAY,CAC1B,EAAE,EAAE,UAAU,EACd,IAAI,EAAE,eAAe,EACrB,cAAc,EAAE,cAAc;UAhGd,MAAM;aAAW,OAAO;GA+HzC;AAED,wBAAgB,oBAAoB,CAClC,EAAE,EAAE,UAAU,EACd,UAAU,EAAE,UAAU,EACtB,MAAM,EAAE,MAAM,QAGf;AAID,wBAAgB,uBAAuB,CACrC,EAAE,EAAE,UAAU,EACd,UAAU,EAAE,MAAM,EAClB,QAAQ,EAAE,oBAAoB,QA8B/B;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAChC,GAAG,EAAE,UAAU,EACf,MAAM,EAAE,MAAM,EACd,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI,GACvC,QAAQ,CAOV;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,QAE1D"}
|
|
@@ -120,9 +120,12 @@ function handleSubscriptionsFrom(lc, subscriber, notifier) {
|
|
|
120
120
|
* This does not send the initial subscription message. Use {@link subscribeTo}
|
|
121
121
|
* to initiate the subscription.
|
|
122
122
|
*/
|
|
123
|
-
function createNotifierFrom(_lc, source) {
|
|
123
|
+
function createNotifierFrom(_lc, source, onNotify) {
|
|
124
124
|
const notifier = new Notifier();
|
|
125
|
-
source.onMessageType("notify", (msg) =>
|
|
125
|
+
source.onMessageType("notify", (msg) => {
|
|
126
|
+
onNotify?.(msg);
|
|
127
|
+
notifier.notifySubscribers(msg);
|
|
128
|
+
});
|
|
126
129
|
return notifier;
|
|
127
130
|
}
|
|
128
131
|
function subscribeTo(_lc, source) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"replicator.js","names":[],"sources":["../../../../../zero-cache/src/workers/replicator.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {sleep} from '../../../shared/src/sleep.ts';\nimport * as v from '../../../shared/src/valita.ts';\nimport {Database} from '../../../zqlite/src/db.ts';\nimport type {ReplicaOptions} from '../config/zero-config.ts';\nimport {deleteLiteDB} from '../db/delete-lite-db.ts';\nimport {upgradeReplica} from '../services/change-source/common/replica-schema.ts';\nimport {Notifier} from '../services/replicator/notifier.ts';\nimport type {\n ReplicaState,\n ReplicaStateNotifier,\n Replicator,\n} from '../services/replicator/replicator.ts';\nimport {\n getAscendingEvents,\n recordEvent,\n} from '../services/replicator/schema/replication-state.ts';\nimport {\n applyPragmas,\n type PragmaConfig,\n} from '../services/replicator/write-worker-client.ts';\nimport type {Worker} from '../types/processes.ts';\n\nexport const replicaFileModeSchema = v.literalUnion(\n 'serving',\n 'serving-copy',\n 'backup',\n);\n\nexport type ReplicaFileMode = v.Infer<typeof replicaFileModeSchema>;\n\nexport type WalMode = 'wal' | 'wal2';\n\nexport function replicaFileName(replicaFile: string, mode: ReplicaFileMode) {\n return mode === 'serving-copy' ? `${replicaFile}-serving-copy` : replicaFile;\n}\n\nconst MILLIS_PER_HOUR = 1000 * 60 * 60;\nconst MB = 1024 * 1024;\n\nasync function prepare(\n lc: LogContext,\n {file, vacuumIntervalHours}: ReplicaOptions,\n walMode: WalMode,\n mode: ReplicaFileMode,\n): Promise<{file: string; walMode: WalMode}> {\n const replica = new Database(lc, file);\n\n // Perform any upgrades to the replica in case the backup is an\n // earlier version.\n await upgradeReplica(lc, `${mode}-replica`, file);\n\n // Start by folding any (e.g. restored) WAL(2) files into the main db.\n await setJournalMode(lc, replica, 'delete');\n\n const [{page_size: pageSize}] = replica.pragma<{page_size: number}>(\n 'page_size',\n );\n const [{page_count: pageCount}] = replica.pragma<{page_count: number}>(\n 'page_count',\n );\n const [{freelist_count: freelistCount}] = replica.pragma<{\n freelist_count: number;\n }>('freelist_count');\n\n const dbSize = ((pageCount * pageSize) / MB).toFixed(2);\n const freelistSize = ((freelistCount * pageSize) / MB).toFixed(2);\n\n // TODO: Consider adding a freelist size or ratio based vacuum trigger.\n lc.info?.(`Size of db ${file}: ${dbSize} MB (${freelistSize} MB freeable)`);\n\n // Check for the VACUUM threshold.\n const events = getAscendingEvents(replica);\n lc.debug?.(`Runtime events for db ${file}`, {events});\n if (vacuumIntervalHours !== undefined) {\n const millisSinceLastEvent =\n Date.now() - (events.at(-1)?.timestamp.getTime() ?? 0);\n if (millisSinceLastEvent / MILLIS_PER_HOUR > vacuumIntervalHours) {\n lc.info?.(`Performing maintenance cleanup on ${file}`);\n const t0 = performance.now();\n replica.unsafeMode(true);\n replica.pragma('journal_mode = OFF');\n replica.exec('VACUUM');\n recordEvent(replica, 'vacuum');\n replica.unsafeMode(false);\n const t1 = performance.now();\n lc.info?.(`VACUUM completed (${t1 - t0} ms)`);\n }\n }\n\n await setJournalMode(lc, replica, walMode);\n\n const pragmas = getPragmaConfig(mode);\n applyPragmas(replica, pragmas);\n\n replica.pragma('optimize = 0x10002');\n lc.info?.(`optimized ${file}`);\n replica.close();\n return {file, walMode};\n}\n\n// Setting the journal_mode requires an exclusive lock on the replica.\n// Add resilience against random replica reads (for stats, etc.) by\n// retrying if the database is locked. Note that the busy_timeout doesn't\n// work here.\nasync function setJournalMode(\n lc: LogContext,\n replica: Database,\n mode: 'delete' | 'wal' | 'wal2',\n) {\n lc.info?.(`setting ${replica.name} to ${mode} mode`);\n let err: unknown;\n for (let i = 0; i < 5; i++) {\n try {\n replica.pragma(`journal_mode = ${mode}`);\n return;\n } catch (e) {\n lc.warn?.(`error setting journal_mode to ${mode} (attempt ${i + 1})`, e);\n err = e;\n }\n await sleep(500);\n }\n throw err;\n}\n\n/**\n * Returns the PragmaConfig for a given replica file mode.\n * This is used by both the main thread (setupReplica) and\n * the write worker thread to apply the same pragma settings.\n */\nexport function getPragmaConfig(mode: ReplicaFileMode): PragmaConfig {\n return {\n busyTimeout: 30000,\n analysisLimit: 1000,\n walAutocheckpoint: mode === 'backup' ? 0 : undefined,\n };\n}\n\nexport function setupReplica(\n lc: LogContext,\n mode: ReplicaFileMode,\n replicaOptions: ReplicaOptions,\n) {\n lc.info?.(`setting up ${mode} replica`);\n\n switch (mode) {\n case 'backup':\n return prepare(lc, replicaOptions, 'wal', mode);\n\n case 'serving-copy': {\n // In 'serving-copy' mode, the original file is being used for 'backup'\n // mode, so we make a copy for servicing sync requests.\n const {file} = replicaOptions;\n const copyLocation = replicaFileName(file, mode);\n deleteLiteDB(copyLocation);\n\n const start = Date.now();\n lc.info?.(`copying ${file} to ${copyLocation}`);\n const replica = new Database(lc, file);\n replica.prepare(`VACUUM INTO ?`).run(copyLocation);\n replica.close();\n lc.info?.(`finished copy (${Date.now() - start} ms)`);\n\n return prepare(lc, {...replicaOptions, file: copyLocation}, 'wal2', mode);\n }\n\n case 'serving':\n return prepare(lc, replicaOptions, 'wal2', mode);\n\n default:\n throw new Error(`Invalid ReplicaMode ${mode}`);\n }\n}\n\nexport function setUpMessageHandlers(\n lc: LogContext,\n replicator: Replicator,\n parent: Worker,\n) {\n handleSubscriptionsFrom(lc, parent, replicator);\n}\n\ntype Notification = ['notify', ReplicaState];\n\nexport function handleSubscriptionsFrom(\n lc: LogContext,\n subscriber: Worker,\n notifier: ReplicaStateNotifier,\n) {\n subscriber.onMessageType('subscribe', async () => {\n const subscription = notifier.subscribe();\n\n subscriber.on('close', () => {\n lc.debug?.(`closing replication subscription from ${subscriber.pid}`);\n subscription.cancel();\n });\n\n for await (const msg of subscription) {\n try {\n subscriber.send<Notification>(['notify', msg]);\n } catch (e) {\n const log =\n e instanceof Error &&\n 'code' in e &&\n // This can happen in a race condition if the subscribing process\n // is closed before the 'close' message is processed.\n e.code === 'ERR_IPC_CHANNEL_CLOSED'\n ? 'warn'\n : 'error';\n\n lc[log]?.(\n `error sending replicator notification to ${subscriber.pid}: ${String(e)}`,\n e,\n );\n }\n }\n });\n}\n\n/**\n * Creates a Notifier to relay notifications the notifier of another Worker.\n * This does not send the initial subscription message. Use {@link subscribeTo}\n * to initiate the subscription.\n */\nexport function createNotifierFrom(_lc: LogContext, source: Worker): Notifier {\n const notifier = new Notifier();\n source.onMessageType<Notification>('notify', msg =>\n notifier.notifySubscribers(msg),\n );\n return notifier;\n}\n\nexport function subscribeTo(_lc: LogContext, source: Worker) {\n source.send(['subscribe', {}]);\n}\n"],"mappings":";;;;;;;;;AAuBA,IAAa,wBAAwB,aACnC,WACA,gBACA,QACF;AAMA,SAAgB,gBAAgB,aAAqB,MAAuB;CAC1E,OAAO,SAAS,iBAAiB,GAAG,YAAY,iBAAiB;AACnE;AAEA,IAAM,kBAAkB,MAAO,KAAK;AACpC,IAAM,KAAK,OAAO;AAElB,eAAe,QACb,IACA,EAAC,MAAM,uBACP,SACA,MAC2C;CAC3C,MAAM,UAAU,IAAI,SAAS,IAAI,IAAI;CAIrC,MAAM,eAAe,IAAI,GAAG,KAAK,WAAW,IAAI;CAGhD,MAAM,eAAe,IAAI,SAAS,QAAQ;CAE1C,MAAM,CAAC,EAAC,WAAW,cAAa,QAAQ,OACtC,WACF;CACA,MAAM,CAAC,EAAC,YAAY,eAAc,QAAQ,OACxC,YACF;CACA,MAAM,CAAC,EAAC,gBAAgB,mBAAkB,QAAQ,OAE/C,gBAAgB;CAEnB,MAAM,UAAW,YAAY,WAAY,IAAI,QAAQ,CAAC;CACtD,MAAM,gBAAiB,gBAAgB,WAAY,IAAI,QAAQ,CAAC;CAGhE,GAAG,OAAO,cAAc,KAAK,IAAI,OAAO,OAAO,aAAa,cAAc;CAG1E,MAAM,SAAS,mBAAmB,OAAO;CACzC,GAAG,QAAQ,yBAAyB,QAAQ,EAAC,OAAM,CAAC;CACpD,IAAI,wBAAwB,KAAA;OAExB,KAAK,IAAI,KAAK,OAAO,GAAG,EAAE,GAAG,UAAU,QAAQ,KAAK,MAC3B,kBAAkB,qBAAqB;GAChE,GAAG,OAAO,qCAAqC,MAAM;GACrD,MAAM,KAAK,YAAY,IAAI;GAC3B,QAAQ,WAAW,IAAI;GACvB,QAAQ,OAAO,oBAAoB;GACnC,QAAQ,KAAK,QAA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AAkB,KAAK,IAAI,IAAI,MAAM,KAAK;GAEpD,OAAO,QAAQ,IAAI;IAAC,GAAG;IAAgB,MAAM;GAAY,GAAG,QAAQ,IAAI;EAC1E;EAEA,KAAK,WACH,OAAO,QAAQ,IAAI,gBAAgB,QAAQ,IAAI;EAEjD,SACE,MAAM,IAAI,MAAM,uBAAuB,MAAM;CACjD;AACF;AAEA,SAAgB,qBACd,IACA,YACA,QACA;CACA,wBAAwB,IAAI,QAAQ,UAAU;AAChD;AAIA,SAAgB,wBACd,IACA,YACA,UACA;CACA,WAAW,cAAc,aAAa,YAAY;EAChD,MAAM,eAAe,SAAS,UAAU;EAExC,WAAW,GAAG,eAAe;GAC3B,GAAG,QAAQ,yCAAyC,WAAW,KAAK;GACpE,aAAa,OAAO;EACtB,CAAC;EAED,WAAW,MAAM,OAAO,cACtB,IAAI;GACF,WAAW,KAAmB,CAAC,UAAU,GAAG,CAAC;EAC/C,SAAS,GAAG;GAUV,GARE,aAAa,SACb,UAAU,KAGV,EAAE,SAAS,2BACP,SACA,WAGJ,4CAA4C,WAAW,IAAI,IAAI,OAAO,CAAC,KACvE,CACF;EACF;CAEJ,CAAC;AACH;;;;;;AAOA,SAAgB,mBAAmB,KAAiB,QAA0B;CAC5E,MAAM,WAAW,IAAI,SAAS;CAC9B,OAAO,cAA4B,WAAU,QAC3C,SAAS,kBAAkB,GAAG,CAChC;CACA,OAAO;AACT;AAEA,SAAgB,YAAY,KAAiB,QAAgB;CAC3D,OAAO,KAAK,CAAC,aAAa,CAAC,CAAC,CAAC;AAC/B"}
|
|
1
|
+
{"version":3,"file":"replicator.js","names":[],"sources":["../../../../../zero-cache/src/workers/replicator.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {sleep} from '../../../shared/src/sleep.ts';\nimport * as v from '../../../shared/src/valita.ts';\nimport {Database} from '../../../zqlite/src/db.ts';\nimport type {ReplicaOptions} from '../config/zero-config.ts';\nimport {deleteLiteDB} from '../db/delete-lite-db.ts';\nimport {upgradeReplica} from '../services/change-source/common/replica-schema.ts';\nimport {Notifier} from '../services/replicator/notifier.ts';\nimport type {\n ReplicaState,\n ReplicaStateNotifier,\n Replicator,\n} from '../services/replicator/replicator.ts';\nimport {\n getAscendingEvents,\n recordEvent,\n} from '../services/replicator/schema/replication-state.ts';\nimport {\n applyPragmas,\n type PragmaConfig,\n} from '../services/replicator/write-worker-client.ts';\nimport type {Worker} from '../types/processes.ts';\n\nexport const replicaFileModeSchema = v.literalUnion(\n 'serving',\n 'serving-copy',\n 'backup',\n);\n\nexport type ReplicaFileMode = v.Infer<typeof replicaFileModeSchema>;\n\nexport type WalMode = 'wal' | 'wal2';\n\nexport function replicaFileName(replicaFile: string, mode: ReplicaFileMode) {\n return mode === 'serving-copy' ? `${replicaFile}-serving-copy` : replicaFile;\n}\n\nconst MILLIS_PER_HOUR = 1000 * 60 * 60;\nconst MB = 1024 * 1024;\n\nasync function prepare(\n lc: LogContext,\n {file, vacuumIntervalHours}: ReplicaOptions,\n walMode: WalMode,\n mode: ReplicaFileMode,\n): Promise<{file: string; walMode: WalMode}> {\n const replica = new Database(lc, file);\n\n // Perform any upgrades to the replica in case the backup is an\n // earlier version.\n await upgradeReplica(lc, `${mode}-replica`, file);\n\n // Start by folding any (e.g. restored) WAL(2) files into the main db.\n await setJournalMode(lc, replica, 'delete');\n\n const [{page_size: pageSize}] = replica.pragma<{page_size: number}>(\n 'page_size',\n );\n const [{page_count: pageCount}] = replica.pragma<{page_count: number}>(\n 'page_count',\n );\n const [{freelist_count: freelistCount}] = replica.pragma<{\n freelist_count: number;\n }>('freelist_count');\n\n const dbSize = ((pageCount * pageSize) / MB).toFixed(2);\n const freelistSize = ((freelistCount * pageSize) / MB).toFixed(2);\n\n // TODO: Consider adding a freelist size or ratio based vacuum trigger.\n lc.info?.(`Size of db ${file}: ${dbSize} MB (${freelistSize} MB freeable)`);\n\n // Check for the VACUUM threshold.\n const events = getAscendingEvents(replica);\n lc.debug?.(`Runtime events for db ${file}`, {events});\n if (vacuumIntervalHours !== undefined) {\n const millisSinceLastEvent =\n Date.now() - (events.at(-1)?.timestamp.getTime() ?? 0);\n if (millisSinceLastEvent / MILLIS_PER_HOUR > vacuumIntervalHours) {\n lc.info?.(`Performing maintenance cleanup on ${file}`);\n const t0 = performance.now();\n replica.unsafeMode(true);\n replica.pragma('journal_mode = OFF');\n replica.exec('VACUUM');\n recordEvent(replica, 'vacuum');\n replica.unsafeMode(false);\n const t1 = performance.now();\n lc.info?.(`VACUUM completed (${t1 - t0} ms)`);\n }\n }\n\n await setJournalMode(lc, replica, walMode);\n\n const pragmas = getPragmaConfig(mode);\n applyPragmas(replica, pragmas);\n\n replica.pragma('optimize = 0x10002');\n lc.info?.(`optimized ${file}`);\n replica.close();\n return {file, walMode};\n}\n\n// Setting the journal_mode requires an exclusive lock on the replica.\n// Add resilience against random replica reads (for stats, etc.) by\n// retrying if the database is locked. Note that the busy_timeout doesn't\n// work here.\nasync function setJournalMode(\n lc: LogContext,\n replica: Database,\n mode: 'delete' | 'wal' | 'wal2',\n) {\n lc.info?.(`setting ${replica.name} to ${mode} mode`);\n let err: unknown;\n for (let i = 0; i < 5; i++) {\n try {\n replica.pragma(`journal_mode = ${mode}`);\n return;\n } catch (e) {\n lc.warn?.(`error setting journal_mode to ${mode} (attempt ${i + 1})`, e);\n err = e;\n }\n await sleep(500);\n }\n throw err;\n}\n\n/**\n * Returns the PragmaConfig for a given replica file mode.\n * This is used by both the main thread (setupReplica) and\n * the write worker thread to apply the same pragma settings.\n */\nexport function getPragmaConfig(mode: ReplicaFileMode): PragmaConfig {\n return {\n busyTimeout: 30000,\n analysisLimit: 1000,\n walAutocheckpoint: mode === 'backup' ? 0 : undefined,\n };\n}\n\nexport function setupReplica(\n lc: LogContext,\n mode: ReplicaFileMode,\n replicaOptions: ReplicaOptions,\n) {\n lc.info?.(`setting up ${mode} replica`);\n\n switch (mode) {\n case 'backup':\n return prepare(lc, replicaOptions, 'wal', mode);\n\n case 'serving-copy': {\n // In 'serving-copy' mode, the original file is being used for 'backup'\n // mode, so we make a copy for servicing sync requests.\n const {file} = replicaOptions;\n const copyLocation = replicaFileName(file, mode);\n deleteLiteDB(copyLocation);\n\n const start = Date.now();\n lc.info?.(`copying ${file} to ${copyLocation}`);\n const replica = new Database(lc, file);\n replica.prepare(`VACUUM INTO ?`).run(copyLocation);\n replica.close();\n lc.info?.(`finished copy (${Date.now() - start} ms)`);\n\n return prepare(lc, {...replicaOptions, file: copyLocation}, 'wal2', mode);\n }\n\n case 'serving':\n return prepare(lc, replicaOptions, 'wal2', mode);\n\n default:\n throw new Error(`Invalid ReplicaMode ${mode}`);\n }\n}\n\nexport function setUpMessageHandlers(\n lc: LogContext,\n replicator: Replicator,\n parent: Worker,\n) {\n handleSubscriptionsFrom(lc, parent, replicator);\n}\n\ntype Notification = ['notify', ReplicaState];\n\nexport function handleSubscriptionsFrom(\n lc: LogContext,\n subscriber: Worker,\n notifier: ReplicaStateNotifier,\n) {\n subscriber.onMessageType('subscribe', async () => {\n const subscription = notifier.subscribe();\n\n subscriber.on('close', () => {\n lc.debug?.(`closing replication subscription from ${subscriber.pid}`);\n subscription.cancel();\n });\n\n for await (const msg of subscription) {\n try {\n subscriber.send<Notification>(['notify', msg]);\n } catch (e) {\n const log =\n e instanceof Error &&\n 'code' in e &&\n // This can happen in a race condition if the subscribing process\n // is closed before the 'close' message is processed.\n e.code === 'ERR_IPC_CHANNEL_CLOSED'\n ? 'warn'\n : 'error';\n\n lc[log]?.(\n `error sending replicator notification to ${subscriber.pid}: ${String(e)}`,\n e,\n );\n }\n }\n });\n}\n\n/**\n * Creates a Notifier to relay notifications the notifier of another Worker.\n * This does not send the initial subscription message. Use {@link subscribeTo}\n * to initiate the subscription.\n */\nexport function createNotifierFrom(\n _lc: LogContext,\n source: Worker,\n onNotify?: (state: ReplicaState) => void,\n): Notifier {\n const notifier = new Notifier();\n source.onMessageType<Notification>('notify', msg => {\n onNotify?.(msg);\n void notifier.notifySubscribers(msg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,MAAM;GAAY,GAAG,QAAQ,IAAI;EAC1E;EAEA,KAAK,WACH,OAAO,QAAQ,IAAI,gBAAgB,QAAQ,IAAI;EAEjD,SACE,MAAM,IAAI,MAAM,uBAAuB,MAAM;CACjD;AACF;AAEA,SAAgB,qBACd,IACA,YACA,QACA;CACA,wBAAwB,IAAI,QAAQ,UAAU;AAChD;AAIA,SAAgB,wBACd,IACA,YACA,UACA;CACA,WAAW,cAAc,aAAa,YAAY;EAChD,MAAM,eAAe,SAAS,UAAU;EAExC,WAAW,GAAG,eAAe;GAC3B,GAAG,QAAQ,yCAAyC,WAAW,KAAK;GACpE,aAAa,OAAO;EACtB,CAAC;EAED,WAAW,MAAM,OAAO,cACtB,IAAI;GACF,WAAW,KAAmB,CAAC,UAAU,GAAG,CAAC;EAC/C,SAAS,GAAG;GAUV,GARE,aAAa,SACb,UAAU,KAGV,EAAE,SAAS,2BACP,SACA,WAGJ,4CAA4C,WAAW,IAAI,IAAI,OAAO,CAAC,KACvE,CACF;EACF;CAEJ,CAAC;AACH;;;;;;AAOA,SAAgB,mBACd,KACA,QACA,UACU;CACV,MAAM,WAAW,IAAI,SAAS;CAC9B,OAAO,cAA4B,WAAU,QAAO;EAClD,WAAW,GAAG;EACd,SAAc,kBAAkB,GAAG;CACrC,CAAC;CACD,OAAO;AACT;AAEA,SAAgB,YAAY,KAAiB,QAAgB;CAC3D,OAAO,KAAK,CAAC,aAAa,CAAC,CAAC,CAAC;AAC/B"}
|
|
@@ -14,6 +14,23 @@ import type { Subscription } from '../types/subscription.ts';
|
|
|
14
14
|
export type SyncerWorkerData = {
|
|
15
15
|
replicatorPort: MessagePort;
|
|
16
16
|
};
|
|
17
|
+
export type ReplicaReadyState = {
|
|
18
|
+
readonly watermark: string;
|
|
19
|
+
readonly replicaReadyTimeMs: number;
|
|
20
|
+
};
|
|
21
|
+
export type ServingLagViewSyncer = Pick<ViewSyncer, 'createdAtMs' | 'servedVersion'>;
|
|
22
|
+
export type ServingLagStats = {
|
|
23
|
+
readonly activeClientGroups: number;
|
|
24
|
+
readonly laggingClientGroups: number;
|
|
25
|
+
readonly minMs: number;
|
|
26
|
+
readonly p50Ms: number;
|
|
27
|
+
readonly p75Ms: number;
|
|
28
|
+
readonly p99Ms: number;
|
|
29
|
+
readonly maxMs: number;
|
|
30
|
+
};
|
|
31
|
+
export declare const MAX_REPLICA_READY_STATES = 10000;
|
|
32
|
+
export declare function computeServingLagStatsMs(now: number, replicaReadyStates: ReplicaReadyState[], viewSyncers: Iterable<ServingLagViewSyncer>): ServingLagStats;
|
|
33
|
+
export declare function computeMaxServingLagMs(now: number, replicaReadyStates: ReplicaReadyState[], viewSyncers: Iterable<ServingLagViewSyncer>): number;
|
|
17
34
|
/**
|
|
18
35
|
* The Syncer worker receives websocket handoffs for "/sync" connections
|
|
19
36
|
* from the Dispatcher in the main thread, and creates websocket
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncer.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/workers/syncer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,WAAW,EAAC,MAAM,qBAAqB,CAAC;AACrD,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAUjD,OAAO,EAAyB,KAAK,iBAAiB,EAAC,MAAM,iBAAiB,CAAC;AAE/E,OAAO,EAAC,KAAK,UAAU,EAAC,MAAM,0BAA0B,CAAC;AAOzD,OAAO,KAAK,EAAC,OAAO,EAAC,MAAM,gCAAgC,CAAC;AAC5D,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,+BAA+B,CAAC;AAC1D,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,sCAAsC,CAAC;AAEvE,OAAO,KAAK,EACV,oBAAoB,EACpB,OAAO,EACP,gBAAgB,EACjB,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EAAC,wBAAwB,EAAC,MAAM,uDAAuD,CAAC;AACpG,OAAO,EAAC,gBAAgB,EAAC,MA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AO,CAAC,GAAG,SAAS,EAC/D,aAAa,EACT,CAAC,CACC,EAAE,EAAE,MAAM,EACV,kBAAkB,EAAE,wBAAwB,KACzC,MAAM,GAAG,OAAO,CAAC,GACtB,SAAS,EACb,MAAM,EAAE,MAAM,EACd,iBAAiB,EAAE,iBAAiB,GAAG,SAAS;IA2TlD,GAAG;IAIH;;;;;OAKG;IACG,KAAK;IAqBX,IAAI;CAKL"}
|
|
@@ -17,6 +17,71 @@ import { resolver } from "@rocicorp/resolver";
|
|
|
17
17
|
import { WebSocketServer } from "ws";
|
|
18
18
|
import { pid } from "node:process";
|
|
19
19
|
//#region ../zero-cache/src/workers/syncer.ts
|
|
20
|
+
var MAX_REPLICA_READY_STATES = 1e4;
|
|
21
|
+
function boundReplicaReadyStates(replicaReadyStates) {
|
|
22
|
+
if (replicaReadyStates.length > 1e4) replicaReadyStates.splice(0, replicaReadyStates.length - MAX_REPLICA_READY_STATES);
|
|
23
|
+
}
|
|
24
|
+
function pruneReplicaReadyStates(replicaReadyStates, firstNeededIndex) {
|
|
25
|
+
if (firstNeededIndex > 0) replicaReadyStates.splice(0, firstNeededIndex);
|
|
26
|
+
boundReplicaReadyStates(replicaReadyStates);
|
|
27
|
+
}
|
|
28
|
+
function lowerBoundReplicaReadyTimeMs(replicaReadyStates, replicaReadyTimeMs) {
|
|
29
|
+
let low = 0;
|
|
30
|
+
let high = replicaReadyStates.length;
|
|
31
|
+
while (low < high) {
|
|
32
|
+
const mid = low + Math.floor((high - low) / 2);
|
|
33
|
+
if (replicaReadyStates[mid].replicaReadyTimeMs < replicaReadyTimeMs) low = mid + 1;
|
|
34
|
+
else high = mid;
|
|
35
|
+
}
|
|
36
|
+
return low;
|
|
37
|
+
}
|
|
38
|
+
function upperBoundWatermark(replicaReadyStates, watermark) {
|
|
39
|
+
let low = 0;
|
|
40
|
+
let high = replicaReadyStates.length;
|
|
41
|
+
while (low < high) {
|
|
42
|
+
const mid = low + Math.floor((high - low) / 2);
|
|
43
|
+
if (replicaReadyStates[mid].watermark <= watermark) low = mid + 1;
|
|
44
|
+
else high = mid;
|
|
45
|
+
}
|
|
46
|
+
return low;
|
|
47
|
+
}
|
|
48
|
+
function findFirstUnservedIndex(replicaReadyStates, viewSyncer) {
|
|
49
|
+
const firstReadyAfterCreation = lowerBoundReplicaReadyTimeMs(replicaReadyStates, viewSyncer.createdAtMs);
|
|
50
|
+
const firstAfterServedVersion = viewSyncer.servedVersion === null ? 0 : upperBoundWatermark(replicaReadyStates, viewSyncer.servedVersion);
|
|
51
|
+
const firstUnservedIndex = Math.max(firstReadyAfterCreation, firstAfterServedVersion);
|
|
52
|
+
return firstUnservedIndex < replicaReadyStates.length ? firstUnservedIndex : -1;
|
|
53
|
+
}
|
|
54
|
+
function percentileNearestRank(sortedValues, percentile) {
|
|
55
|
+
if (sortedValues.length === 0) return 0;
|
|
56
|
+
return sortedValues[Math.min(sortedValues.length - 1, Math.max(0, Math.ceil(percentile / 100 * sortedValues.length) - 1))];
|
|
57
|
+
}
|
|
58
|
+
function computeServingLagStatsMs(now, replicaReadyStates, viewSyncers) {
|
|
59
|
+
const lags = [];
|
|
60
|
+
let laggingClientGroups = 0;
|
|
61
|
+
let firstNeededIndex = replicaReadyStates.length;
|
|
62
|
+
for (const viewSyncer of viewSyncers) {
|
|
63
|
+
const firstUnservedIndex = findFirstUnservedIndex(replicaReadyStates, viewSyncer);
|
|
64
|
+
if (firstUnservedIndex === -1) {
|
|
65
|
+
lags.push(0);
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
firstNeededIndex = Math.min(firstNeededIndex, firstUnservedIndex);
|
|
69
|
+
const lagMs = Math.max(0, now - replicaReadyStates[firstUnservedIndex].replicaReadyTimeMs);
|
|
70
|
+
lags.push(lagMs);
|
|
71
|
+
if (lagMs > 0) laggingClientGroups++;
|
|
72
|
+
}
|
|
73
|
+
pruneReplicaReadyStates(replicaReadyStates, firstNeededIndex);
|
|
74
|
+
lags.sort((a, b) => a - b);
|
|
75
|
+
return {
|
|
76
|
+
activeClientGroups: lags.length,
|
|
77
|
+
laggingClientGroups,
|
|
78
|
+
minMs: lags[0] ?? 0,
|
|
79
|
+
p50Ms: percentileNearestRank(lags, 50),
|
|
80
|
+
p75Ms: percentileNearestRank(lags, 75),
|
|
81
|
+
p99Ms: percentileNearestRank(lags, 99),
|
|
82
|
+
maxMs: lags.at(-1) ?? 0
|
|
83
|
+
};
|
|
84
|
+
}
|
|
20
85
|
function getWebSocketServerOptions(config) {
|
|
21
86
|
const options = {
|
|
22
87
|
noServer: true,
|
|
@@ -52,10 +117,13 @@ var Syncer = class {
|
|
|
52
117
|
#stopped = resolver();
|
|
53
118
|
#config;
|
|
54
119
|
#validateLegacyJWT;
|
|
120
|
+
#replicaReadyStates = [];
|
|
121
|
+
#servingLagStatsCache;
|
|
122
|
+
#servingLagStatsCacheClearQueued = false;
|
|
55
123
|
constructor(lc, config, viewSyncerFactory, mutagenFactory, pusherFactory, parent, validateLegacyJWT) {
|
|
56
124
|
this.#config = config;
|
|
57
125
|
this.#validateLegacyJWT = validateLegacyJWT;
|
|
58
|
-
const notifier = createNotifierFrom(lc, parent);
|
|
126
|
+
const notifier = createNotifierFrom(lc, parent, (state) => this.#recordReplicaReadyState(state));
|
|
59
127
|
subscribeTo(lc, parent);
|
|
60
128
|
this.#lc = lc;
|
|
61
129
|
this.#viewSyncers = new ServiceRunner(lc, (id) => viewSyncerFactory(id, notifier.subscribe(), this.#drainCoordinator), (v) => v.keepalive());
|
|
@@ -76,6 +144,53 @@ var Syncer = class {
|
|
|
76
144
|
for (const vs of this.#viewSyncers.getServices()) total += vs.rowCount;
|
|
77
145
|
result.observe(total);
|
|
78
146
|
});
|
|
147
|
+
getOrCreateGauge("sync", "serving-lag", {
|
|
148
|
+
description: "Maximum time active ViewSyncer client groups have had unserved replica changes. A change is served after IVM advancement, CVR flush, and pokeEnd.",
|
|
149
|
+
unit: "millisecond"
|
|
150
|
+
}).addCallback((result) => {
|
|
151
|
+
result.observe(this.#computeServingLagStats().maxMs);
|
|
152
|
+
});
|
|
153
|
+
getOrCreateGauge("sync", "serving-lag-stats", {
|
|
154
|
+
description: "Distribution of time active ViewSyncer client groups have had unserved replica changes. A change is served after IVM advancement, CVR flush, and pokeEnd.",
|
|
155
|
+
unit: "millisecond"
|
|
156
|
+
}).addCallback((result) => {
|
|
157
|
+
const stats = this.#computeServingLagStats();
|
|
158
|
+
result.observe(stats.minMs, { stat: "min" });
|
|
159
|
+
result.observe(stats.p50Ms, { stat: "p50" });
|
|
160
|
+
result.observe(stats.p75Ms, { stat: "p75" });
|
|
161
|
+
result.observe(stats.p99Ms, { stat: "p99" });
|
|
162
|
+
result.observe(stats.maxMs, { stat: "max" });
|
|
163
|
+
});
|
|
164
|
+
getOrCreateGauge("sync", "serving-lagging-client-groups", "Number of active client groups with unserved replica changes").addCallback((result) => {
|
|
165
|
+
result.observe(this.#computeServingLagStats().laggingClientGroups);
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
#computeServingLagStats() {
|
|
169
|
+
if (this.#servingLagStatsCache) return this.#servingLagStatsCache;
|
|
170
|
+
const stats = computeServingLagStatsMs(Date.now(), this.#replicaReadyStates, this.#viewSyncers.getServices());
|
|
171
|
+
this.#servingLagStatsCache = stats;
|
|
172
|
+
if (!this.#servingLagStatsCacheClearQueued) {
|
|
173
|
+
this.#servingLagStatsCacheClearQueued = true;
|
|
174
|
+
queueMicrotask(() => {
|
|
175
|
+
this.#servingLagStatsCache = void 0;
|
|
176
|
+
this.#servingLagStatsCacheClearQueued = false;
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
return stats;
|
|
180
|
+
}
|
|
181
|
+
#recordReplicaReadyState(state) {
|
|
182
|
+
if (state.watermark === void 0 || state.replicaReadyTimeMs === void 0) return;
|
|
183
|
+
const last = this.#replicaReadyStates.at(-1);
|
|
184
|
+
if (last && last.watermark >= state.watermark) return;
|
|
185
|
+
this.#replicaReadyStates.push({
|
|
186
|
+
watermark: state.watermark,
|
|
187
|
+
replicaReadyTimeMs: state.replicaReadyTimeMs
|
|
188
|
+
});
|
|
189
|
+
if (this.#viewSyncers.size === 0) {
|
|
190
|
+
this.#replicaReadyStates.length = 0;
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
boundReplicaReadyStates(this.#replicaReadyStates);
|
|
79
194
|
}
|
|
80
195
|
#createConnection = async (ws, params) => {
|
|
81
196
|
this.#lc.debug?.("creating connection", params.clientGroupID, params.clientID);
|