@powerhousedao/reactor 6.2.3-dev.5 → 6.2.3-dev.51
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/dist/document-indexer-3fkVWCaN.js +1856 -0
- package/dist/document-indexer-3fkVWCaN.js.map +1 -0
- package/dist/drive-container-types-BAfFzBOf.js +3892 -0
- package/dist/drive-container-types-BAfFzBOf.js.map +1 -0
- package/dist/entry.d.ts +2 -1
- package/dist/entry.js +111 -7
- package/dist/entry.js.map +1 -1
- package/dist/{errors-D3S6Eysd.js → errors-BM_ULVWd.js} +9 -1
- package/dist/{errors-D3S6Eysd.js.map → errors-BM_ULVWd.js.map} +1 -1
- package/dist/forwarding-logger-B9LLXItm.js +3667 -0
- package/dist/forwarding-logger-B9LLXItm.js.map +1 -0
- package/dist/index-dDm0fUBT.d.ts +6833 -0
- package/dist/index-dDm0fUBT.d.ts.map +1 -0
- package/dist/index.d.ts +1912 -5584
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7937 -1436
- package/dist/index.js.map +1 -1
- package/dist/load-spec-ZLjuyhxz.js +246 -0
- package/dist/load-spec-ZLjuyhxz.js.map +1 -0
- package/dist/projection-entry.d.ts +2 -1
- package/dist/projection-entry.js +99 -21
- package/dist/projection-entry.js.map +1 -1
- package/dist/{projection-shard-manager-CPQc5XHL.js → projection-shard-manager-Drl9w8Eo.js} +25 -15
- package/dist/projection-shard-manager-Drl9w8Eo.js.map +1 -0
- package/dist/{projection-worker-wI4PwcV2.js → projection-worker-D8uNFdwX.js} +1 -1
- package/dist/{projection-worker-wI4PwcV2.js.map → projection-worker-D8uNFdwX.js.map} +1 -1
- package/dist/rpc.d.ts +358 -0
- package/dist/rpc.d.ts.map +1 -0
- package/dist/rpc.js +575 -0
- package/dist/rpc.js.map +1 -0
- package/dist/{transport-CuogVKN_.js → transport-B3G50KVd.js} +1 -1
- package/dist/{transport-CuogVKN_.js.map → transport-B3G50KVd.js.map} +1 -1
- package/dist/{transport-ByGviWdZ.js → transport-CZDHzfvy.js} +1 -1
- package/dist/{transport-ByGviWdZ.js.map → transport-CZDHzfvy.js.map} +1 -1
- package/dist/{worker-handle-CrERzl8s.js → worker-handle-Nso8i5eU.js} +30 -17
- package/dist/worker-handle-Nso8i5eU.js.map +1 -0
- package/dist/worker-pool-router-BROOEQSE.js +35 -0
- package/dist/worker-pool-router-BROOEQSE.js.map +1 -0
- package/package.json +34 -18
- package/dist/build-worker-executor-DnU3ZU4H.js +0 -83
- package/dist/build-worker-executor-DnU3ZU4H.js.map +0 -1
- package/dist/document-indexer-C5Gsa1B3.js +0 -958
- package/dist/document-indexer-C5Gsa1B3.js.map +0 -1
- package/dist/drive-container-types-yZrksiJR.js +0 -5310
- package/dist/drive-container-types-yZrksiJR.js.map +0 -1
- package/dist/error-info-Cpu4OY3o.js +0 -62
- package/dist/error-info-Cpu4OY3o.js.map +0 -1
- package/dist/forwarding-logger-BBkMSxuJ.js +0 -85
- package/dist/forwarding-logger-BBkMSxuJ.js.map +0 -1
- package/dist/projection-shard-manager-CPQc5XHL.js.map +0 -1
- package/dist/types-DMKLa0Ok.js +0 -33
- package/dist/types-DMKLa0Ok.js.map +0 -1
- package/dist/worker-HPysBfhx.js +0 -22
- package/dist/worker-HPysBfhx.js.map +0 -1
- package/dist/worker-handle-CrERzl8s.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as
|
|
1
|
+
import { Ct as ReactorEventTypes, i as fromErrorInfo } from "./forwarding-logger-B9LLXItm.js";
|
|
2
|
+
import { t as bucketFor } from "./worker-pool-router-BROOEQSE.js";
|
|
3
3
|
import { childLogger } from "document-model";
|
|
4
4
|
import { randomUUID } from "node:crypto";
|
|
5
5
|
//#region src/projection/projection-shard-manager.ts
|
|
@@ -7,17 +7,6 @@ const DEFAULT_INIT_TIMEOUT_MS = 3e4;
|
|
|
7
7
|
const DEFAULT_SHUTDOWN_GRACE_MS = 5e3;
|
|
8
8
|
const DEFAULT_DRAIN_TIMEOUT_MS = 3e4;
|
|
9
9
|
const DEFAULT_CHAIN_DEPTH_REPORT_INTERVAL_MS = 250;
|
|
10
|
-
const FNV_OFFSET_BASIS = 2166136261;
|
|
11
|
-
const FNV_PRIME = 16777619;
|
|
12
|
-
function bucketFor(documentId, numWorkers) {
|
|
13
|
-
if (numWorkers < 1) throw new Error(`bucketFor: numWorkers must be >= 1 (got ${numWorkers})`);
|
|
14
|
-
let hash = FNV_OFFSET_BASIS;
|
|
15
|
-
for (let i = 0; i < documentId.length; i++) {
|
|
16
|
-
hash ^= documentId.charCodeAt(i);
|
|
17
|
-
hash = Math.imul(hash, FNV_PRIME);
|
|
18
|
-
}
|
|
19
|
-
return (hash >>> 0) % numWorkers;
|
|
20
|
-
}
|
|
21
10
|
/**
|
|
22
11
|
* Maps operations to the coordinates a consistency tracker is keyed by.
|
|
23
12
|
* Same shape `BaseReadModel.updateConsistencyTracker` produces in-process.
|
|
@@ -123,7 +112,9 @@ var ProjectionShardManager = class {
|
|
|
123
112
|
models: this.config.models,
|
|
124
113
|
preReadyKinds: this.config.preReadyKinds,
|
|
125
114
|
postReadyKinds: this.config.postReadyKinds,
|
|
126
|
-
chainDepthReportIntervalMs: reportIntervalMs
|
|
115
|
+
chainDepthReportIntervalMs: reportIntervalMs,
|
|
116
|
+
indexing: this.config.indexing,
|
|
117
|
+
catchUp: this.config.catchUp
|
|
127
118
|
};
|
|
128
119
|
transport.postMessage(init);
|
|
129
120
|
initPromises.push(initPromise);
|
|
@@ -175,11 +166,20 @@ var ProjectionShardManager = class {
|
|
|
175
166
|
emitReadReady(event) {
|
|
176
167
|
return this.hostBus.emit(ReactorEventTypes.JOB_READ_READY, event);
|
|
177
168
|
}
|
|
169
|
+
indexedReadModels() {
|
|
170
|
+
return [];
|
|
171
|
+
}
|
|
178
172
|
getChainDepth() {
|
|
179
173
|
let total = 0;
|
|
180
174
|
for (const shard of this.shards) total += shard.lastDepth;
|
|
181
175
|
return total;
|
|
182
176
|
}
|
|
177
|
+
/** The last catch-up status each ready shard reported. */
|
|
178
|
+
catchUpStatuses() {
|
|
179
|
+
const statuses = [];
|
|
180
|
+
for (const shard of this.shards) if (shard.catchUpStatus) statuses.push(shard.catchUpStatus);
|
|
181
|
+
return statuses;
|
|
182
|
+
}
|
|
183
183
|
getShardDepths() {
|
|
184
184
|
return this.shards.map((shard) => ({
|
|
185
185
|
shardId: shard.shardId,
|
|
@@ -317,6 +317,16 @@ var ProjectionShardManager = class {
|
|
|
317
317
|
case "log":
|
|
318
318
|
this.handleLog(shard, msg);
|
|
319
319
|
return;
|
|
320
|
+
case "readmodel-swept":
|
|
321
|
+
this.trackersByReadModelName.get(msg.readModelName)?.update(msg.coordinates);
|
|
322
|
+
this.hostBus.emit(ReactorEventTypes.CATCHUP_SWEPT, {
|
|
323
|
+
...msg.result,
|
|
324
|
+
thread: "projection"
|
|
325
|
+
}).catch(() => {});
|
|
326
|
+
return;
|
|
327
|
+
case "catchup-status":
|
|
328
|
+
shard.catchUpStatus = msg.status;
|
|
329
|
+
return;
|
|
320
330
|
default: return;
|
|
321
331
|
}
|
|
322
332
|
}
|
|
@@ -437,4 +447,4 @@ var ProjectionShardManager = class {
|
|
|
437
447
|
//#endregion
|
|
438
448
|
export { ProjectionShardManager };
|
|
439
449
|
|
|
440
|
-
//# sourceMappingURL=projection-shard-manager-
|
|
450
|
+
//# sourceMappingURL=projection-shard-manager-Drl9w8Eo.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"projection-shard-manager-Drl9w8Eo.js","names":[],"sources":["../src/projection/projection-shard-manager.ts"],"sourcesContent":["import type { OperationWithContext } from \"@powerhousedao/shared/document-model\";\nimport { childLogger, type ILogger } from \"document-model\";\nimport { randomUUID } from \"node:crypto\";\nimport type { CatchUpConfig, CatchUpStatus } from \"../catch-up/types.js\";\nimport { fromErrorInfo } from \"../executor/worker/error-info.js\";\nimport type { IEventBus } from \"../events/interfaces.js\";\nimport {\n ReactorEventTypes,\n type JobReadReadyEvent,\n type JobWriteReadyEvent,\n type ReadModelBatchCompletedEvent,\n type ReadModelIndexedEvent,\n type Unsubscribe,\n} from \"../events/types.js\";\nimport type {\n IReadModel,\n IReadModelCoordinator,\n} from \"../read-models/interfaces.js\";\nimport type { IConsistencyTracker } from \"../shared/consistency-tracker.js\";\nimport type { ConsistencyCoordinate } from \"../shared/types.js\";\nimport type { ForwardingPoolInstrumentation } from \"../storage/pool-instrumentation.js\";\nimport type {\n BuiltInReadModelKind,\n ChainDepthReport,\n DbConfig,\n ModelManifestEntry,\n ProjectionDrainedMessage,\n ProjectionInitMessage,\n ProjectionParentMessage,\n ProjectionPoolAcquireSamplesMessage,\n ProjectionReadModelIndexedMessage,\n ProjectionWorkerMessage,\n ReadModelIndexingConfig,\n} from \"./protocol.js\";\nimport type { IProjectionTransport } from \"./transport.js\";\nimport { bucketFor } from \"../executor/worker-pool-router.js\";\n\nconst DEFAULT_INIT_TIMEOUT_MS = 30_000;\nconst DEFAULT_SHUTDOWN_GRACE_MS = 5_000;\nconst DEFAULT_DRAIN_TIMEOUT_MS = 30_000;\nconst DEFAULT_CHAIN_DEPTH_REPORT_INTERVAL_MS = 250;\n\n/**\n * Maps operations to the coordinates a consistency tracker is keyed by.\n * Same shape `BaseReadModel.updateConsistencyTracker` produces in-process.\n */\nfunction toConsistencyCoordinates(\n operations: OperationWithContext[],\n): ConsistencyCoordinate[] {\n const coordinates: ConsistencyCoordinate[] = [];\n for (let i = 0; i < operations.length; i++) {\n const item = operations[i]!;\n coordinates.push({\n documentId: item.context.documentId,\n scope: item.context.scope,\n branch: item.context.branch,\n operationIndex: item.operation.index,\n });\n }\n return coordinates;\n}\n\n/**\n * Factory that builds one projection-worker transport. Mirrors\n * `WorkerFactory` from the executor pool: lets tests inject fake\n * transports without spawning real worker threads.\n */\nexport type ProjectionWorkerFactory = (\n shardIndex: number,\n shardId: string,\n) => IProjectionTransport;\n\nexport type ProjectionShardHooks = {\n /** Takes over the host-bus JOB_READ_READY emit; call `emitReadReady` to emit. */\n onReadReady?: (event: JobReadReadyEvent) => void;\n /**\n * Fired when a shard errors, when it exits after having been ready, and\n * for every JOB_WRITE_READY dropped because its shard is not ready.\n *\n * There is no respawn path: once a shard stops being ready it never\n * projects again, so buffering the dropped work would only grow without\n * bound. A host that cares wires this to its shutdown path, so the process\n * restarts and each read model catches up from `ViewState.lastOrdinal` in\n * `BaseReadModel.init`. May fire repeatedly — handlers must be idempotent.\n */\n onShardFatal?: (shardId: string, reason: Error) => void;\n};\n\nexport type ProjectionShardManagerConfig = ProjectionShardHooks & {\n shardCount: number;\n db: DbConfig;\n models: ModelManifestEntry[];\n preReadyKinds: BuiltInReadModelKind[];\n postReadyKinds: BuiltInReadModelKind[];\n /**\n * Chunking bounds the shards' read models index under. Comes from the same\n * host config the in-process read models get, so the two paths cannot drift.\n */\n indexing: ReadModelIndexingConfig;\n catchUp: CatchUpConfig;\n factory: ProjectionWorkerFactory;\n logger: ILogger;\n hostBus: IEventBus;\n initTimeoutMs?: number;\n shutdownGraceMs?: number;\n drainTimeoutMs?: number;\n chainDepthReportIntervalMs?: number;\n /**\n * Host-side forwarding instrumentations indexed by shard index. The\n * manager routes each shard's `pool-acquire-samples` message to the\n * matching forwarder so the host's OpenTelemetry instrumentation records\n * acquire-wait latencies as if each shard's pg.Pool were local.\n */\n poolInstrumentations?: ForwardingPoolInstrumentation[];\n /**\n * The host's consistency trackers for the built-in read models the shards\n * run, keyed by kind. The keys double as read-model names (see\n * `DOCUMENT_VIEW_READ_MODEL` / `DOCUMENT_INDEXER_READ_MODEL` in\n * `read-models/names.js`), which is how a relayed `readmodel-indexed`\n * message is matched to a tracker.\n *\n * The host's copies of these read models are never fed an operation under\n * sharding, so without this every read carrying a consistency token waits\n * on a tracker that can never advance — `ConsistencyTracker.waitFor` arms\n * no timer when `timeoutMs` is undefined, which is what every\n * `document-view` call site passes. The worker committed those rows to the\n * same tables the host reads from, so advancing here is exact, not a fudge.\n */\n consistencyTrackers?: Partial<\n Record<BuiltInReadModelKind, IConsistencyTracker>\n >;\n};\n\ntype ShardState = {\n shardIndex: number;\n shardId: string;\n transport: IProjectionTransport;\n ready: boolean;\n lastDepth: number;\n lastDepthAt: number;\n poolInstrumentation?: ForwardingPoolInstrumentation;\n /**\n * Consistency coordinates of the jobs this shard is still projecting,\n * keyed by jobId. Relayed `readmodel-indexed` messages carry only a count,\n * so the host keeps the coordinates here to advance its trackers from\n * them; the operations themselves are not retained. Empty unless\n * `consistencyTrackers` is configured; entries live from dispatch to\n * `readmodel-batch-completed`, and are dropped when the shard exits.\n */\n pendingCoordinates: Map<string, ConsistencyCoordinate[]>;\n catchUpStatus?: CatchUpStatus;\n /**\n * Correlation id of this shard's `init` while it is unsettled; cleared once\n * the shard reports ready, fails, or dies. Lets a transport error or a\n * premature exit settle the shard's own pending init instead of leaving\n * `startup()` to time out on a worker that will never answer.\n */\n initCorrelationId?: string;\n onMessage: (msg: ProjectionWorkerMessage) => void;\n onError: (err: Error) => void;\n onExit: (code: number) => void;\n};\n\ntype PendingDrain = {\n resolve: () => void;\n reject: (err: Error) => void;\n remaining: Set<string>;\n timer: NodeJS.Timeout;\n};\n\n/**\n * Host-side coordinator for N sharded projection workers.\n *\n * Implements {@link IReadModelCoordinator} so it slots into the same\n * `readModelCoordinator` field on the reactor module as the in-process\n * {@link ReadModelCoordinator}. The host subscribes to JOB_WRITE_READY\n * exactly once; events are routed to a single shard by\n * `bucketFor(documentId, shardCount)`. Each worker maintains the\n * per-queueKey serial chain locally and forwards JOB_READ_READY and\n * READMODEL_* events back to the host for the rest of the reactor (sync\n * manager, awaiters, observers) to consume on the host bus.\n *\n * @see Sharded projection workers sub-feature brief\n * (Powerhouse board wiki id: eb26f01f-8f68-4918-a6f6-ac7a4679b533)\n */\nexport class ProjectionShardManager implements IReadModelCoordinator {\n readonly readModels: IReadModel[] = [];\n\n private readonly config: ProjectionShardManagerConfig;\n private readonly logger: ILogger;\n private readonly hostBus: IEventBus;\n private readonly shards: ShardState[] = [];\n private readonly initPromises = new Map<\n string,\n { resolve: () => void; reject: (err: Error) => void; timer: NodeJS.Timeout }\n >();\n private readonly pendingDrains = new Map<string, PendingDrain>();\n private readonly trackersByReadModelName = new Map<\n string,\n IConsistencyTracker\n >();\n private hostSubscription?: Unsubscribe;\n private isRunning = false;\n private started = false;\n private isShuttingDown = false;\n\n constructor(config: ProjectionShardManagerConfig) {\n if (config.shardCount < 1) {\n throw new Error(\n `ProjectionShardManager: shardCount must be >= 1 (got ${config.shardCount})`,\n );\n }\n this.config = config;\n this.logger = childLogger([\"reactor\", \"projection-shard-manager\"]);\n this.hostBus = config.hostBus;\n const trackers = config.consistencyTrackers ?? {};\n for (const kind of Object.keys(trackers) as BuiltInReadModelKind[]) {\n const tracker = trackers[kind];\n if (tracker) {\n this.trackersByReadModelName.set(kind, tracker);\n }\n }\n }\n\n async startup(): Promise<void> {\n if (this.started) {\n return;\n }\n this.started = true;\n const initTimeoutMs = this.config.initTimeoutMs ?? DEFAULT_INIT_TIMEOUT_MS;\n const reportIntervalMs =\n this.config.chainDepthReportIntervalMs ??\n DEFAULT_CHAIN_DEPTH_REPORT_INTERVAL_MS;\n\n const initPromises: Promise<void>[] = [];\n for (let i = 0; i < this.config.shardCount; i++) {\n const shardId = `projection-shard-${i}`;\n const transport = this.config.factory(i, shardId);\n const state: ShardState = {\n shardIndex: i,\n shardId,\n transport,\n ready: false,\n lastDepth: 0,\n lastDepthAt: 0,\n poolInstrumentation: this.config.poolInstrumentations?.[i],\n pendingCoordinates: new Map(),\n onMessage: (msg) => this.handleWorkerMessage(state, msg),\n onError: (err) => this.handleTransportError(state, err),\n onExit: (code) => this.handleTransportExit(state, code),\n };\n transport.on(\"message\", state.onMessage);\n transport.on(\"error\", state.onError);\n transport.on(\"exit\", state.onExit);\n this.shards.push(state);\n\n const correlationId = randomUUID();\n state.initCorrelationId = correlationId;\n const initPromise = new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.initPromises.delete(correlationId);\n reject(\n new Error(\n `projection shard ${shardId} did not become ready within ${initTimeoutMs}ms`,\n ),\n );\n }, initTimeoutMs);\n this.initPromises.set(correlationId, { resolve, reject, timer });\n });\n\n const init: ProjectionInitMessage = {\n type: \"init\",\n correlationId,\n shardId,\n shardIndex: i,\n shardCount: this.config.shardCount,\n db: this.config.db,\n models: this.config.models,\n preReadyKinds: this.config.preReadyKinds,\n postReadyKinds: this.config.postReadyKinds,\n chainDepthReportIntervalMs: reportIntervalMs,\n indexing: this.config.indexing,\n catchUp: this.config.catchUp,\n };\n transport.postMessage(init);\n initPromises.push(initPromise);\n }\n\n await Promise.all(initPromises);\n this.logger.info(\n \"projection shard manager ready: @count shards\",\n this.shards.length,\n );\n }\n\n start(): void {\n if (this.isRunning) {\n return;\n }\n this.hostSubscription = this.hostBus.subscribe(\n ReactorEventTypes.JOB_WRITE_READY,\n (_t: number, event: JobWriteReadyEvent) => {\n this.routeWriteReady(event);\n },\n );\n this.isRunning = true;\n }\n\n stop(): void {\n if (!this.isRunning) {\n return;\n }\n if (this.hostSubscription) {\n this.hostSubscription();\n this.hostSubscription = undefined;\n }\n this.isRunning = false;\n }\n\n /** Waits on ready shards only; `handleTransportExit` releases one that dies. */\n async drain(): Promise<void> {\n const readyShards = this.shards.filter((s) => s.ready);\n if (readyShards.length === 0) {\n return;\n }\n const drainTimeoutMs =\n this.config.drainTimeoutMs ?? DEFAULT_DRAIN_TIMEOUT_MS;\n const correlationId = randomUUID();\n const remaining = new Set(readyShards.map((s) => s.shardId));\n const promise = new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.pendingDrains.delete(correlationId);\n reject(\n new Error(\n `projection shards did not drain within ${drainTimeoutMs}ms (remaining: ${[\n ...remaining,\n ].join(\", \")})`,\n ),\n );\n }, drainTimeoutMs);\n this.pendingDrains.set(correlationId, {\n resolve,\n reject,\n remaining,\n timer,\n });\n });\n for (const shard of readyShards) {\n shard.transport.postMessage({ type: \"drain\", correlationId });\n }\n await promise;\n }\n\n /** Emits JOB_READ_READY on the host bus; an `onReadReady` hook awaits this. */\n emitReadReady(event: JobReadReadyEvent): Promise<void> {\n return this.hostBus.emit(ReactorEventTypes.JOB_READ_READY, event);\n }\n\n indexedReadModels(): readonly IReadModel[] {\n return [];\n }\n\n getChainDepth(): number {\n let total = 0;\n for (const shard of this.shards) {\n total += shard.lastDepth;\n }\n return total;\n }\n\n /** The last catch-up status each ready shard reported. */\n catchUpStatuses(): CatchUpStatus[] {\n const statuses: CatchUpStatus[] = [];\n for (const shard of this.shards) {\n if (shard.catchUpStatus) statuses.push(shard.catchUpStatus);\n }\n return statuses;\n }\n\n getShardDepths(): ChainDepthReport[] {\n return this.shards.map((shard) => ({\n shardId: shard.shardId,\n depth: shard.lastDepth,\n timestamp: shard.lastDepthAt,\n }));\n }\n\n async shutdown(): Promise<void> {\n // Workers exit as a consequence of this call, so their `exit` events are\n // expected from here on and must not be reported as fatal.\n this.isShuttingDown = true;\n this.stop();\n // An init timer left armed by a shard that never reported keeps the\n // process alive for the whole init timeout after shutdown returns.\n for (const shard of this.shards) {\n this.failPendingInit(\n shard,\n new Error(\n `projection shard ${shard.shardId} was shut down before becoming ready`,\n ),\n );\n }\n const graceMs = this.config.shutdownGraceMs ?? DEFAULT_SHUTDOWN_GRACE_MS;\n const correlationId = randomUUID();\n for (const shard of this.shards) {\n try {\n const msg: ProjectionParentMessage = {\n type: \"shutdown\",\n correlationId,\n graceMs,\n };\n shard.transport.postMessage(msg);\n } catch (err) {\n this.logger.warn(\n \"projection shard postMessage(shutdown) failed for @shardId: @error\",\n shard.shardId,\n err,\n );\n }\n }\n const terminationDeadline = Date.now() + graceMs;\n while (\n this.shards.some((s) => s.ready) &&\n Date.now() < terminationDeadline\n ) {\n await new Promise<void>((resolve) => setTimeout(resolve, 25));\n }\n for (const shard of this.shards) {\n try {\n await shard.transport.terminate();\n } catch (err) {\n this.logger.warn(\n \"projection shard terminate failed for @shardId: @error\",\n shard.shardId,\n err,\n );\n }\n shard.transport.off(\"message\", shard.onMessage);\n shard.transport.off(\"error\", shard.onError);\n shard.transport.off(\"exit\", shard.onExit);\n }\n this.shards.length = 0;\n }\n\n private routeWriteReady(event: JobWriteReadyEvent): void {\n if (event.operations.length === 0) {\n // No shard can be selected (there is no documentId) and no read model\n // has work to do, but JOB_READ_READY is the job's terminal signal:\n // InMemoryJobTracker and every JobAwaiter hang without it. Mirrors\n // ReadModelCoordinator.emitEmptyReadReady.\n this.relayReadReady({ jobId: event.jobId, operations: [] });\n this.relayBatchCompleted({\n jobId: event.jobId,\n batchSize: 0,\n chainWaitDurationMs: 0,\n preReadyDurationMs: 0,\n emitDurationMs: 0,\n postReadyDurationMs: 0,\n });\n return;\n }\n const documentId = event.operations[0]!.context.documentId;\n const index = bucketFor(documentId, this.shards.length);\n const shard = this.shards[index]!;\n if (!shard.ready) {\n this.dropWriteReady(shard, event, documentId);\n return;\n }\n if (this.trackersByReadModelName.size > 0) {\n shard.pendingCoordinates.set(\n event.jobId,\n toConsistencyCoordinates(event.operations),\n );\n }\n shard.transport.postMessage({\n type: \"write-ready\",\n jobId: event.jobId,\n operations: event.operations,\n jobMeta: event.jobMeta,\n collectionMemberships: event.collectionMemberships,\n });\n }\n\n /**\n * A shard stops being ready only when it dies, and nothing respawns it, so\n * this job's projection is genuinely lost. Buffering would grow without\n * bound behind a shard that never comes back, so the batch is dropped —\n * loudly, naming the job and document, and through `onShardFatal` so a host\n * can restart rather than serve stale read models.\n *\n * JOB_FAILED is deliberately not emitted: every other emitter uses it for a\n * job whose operations were *not* written (see\n * `executor/job-result-handler.ts`), and these were written and are\n * durable. Marking the job FAILED would invite the caller to re-submit a\n * write that already landed.\n */\n private dropWriteReady(\n shard: ShardState,\n event: JobWriteReadyEvent,\n documentId: string,\n ): void {\n const reason = new Error(\n `projection shard ${shard.shardId} is not ready: JOB_WRITE_READY for job ${event.jobId} ` +\n `(document ${documentId}, ${event.operations.length} operation(s)) was dropped and will ` +\n `never be projected; the operations are written and durable, but this shard's read models ` +\n `are now behind`,\n );\n this.logger.error(\n \"dropping JOB_WRITE_READY for job @jobId on shard @shardId: @error\",\n event.jobId,\n shard.shardId,\n reason,\n );\n this.config.onShardFatal?.(shard.shardId, reason);\n }\n\n private handleWorkerMessage(\n shard: ShardState,\n msg: ProjectionWorkerMessage,\n ): void {\n switch (msg.type) {\n case \"ready\":\n this.handleReady(shard, msg.correlationId);\n return;\n case \"init-failed\":\n this.logger.error(\n \"projection shard @shardId failed to initialize: @error\",\n shard.shardId,\n msg.error.message,\n );\n this.failPendingInit(shard, fromErrorInfo(msg.error));\n return;\n case \"read-ready\":\n this.relayReadReady({\n jobId: msg.jobId,\n operations: msg.operations,\n });\n return;\n case \"readmodel-indexed\":\n this.advanceConsistencyTrackers(shard, msg);\n this.relayReadModelIndexed({\n jobId: msg.jobId,\n readModelName: msg.readModelName,\n stage: msg.stage,\n durationMs: msg.durationMs,\n operationCount: msg.operationCount,\n success: msg.success,\n });\n return;\n case \"readmodel-batch-completed\":\n shard.pendingCoordinates.delete(msg.jobId);\n this.relayBatchCompleted({\n jobId: msg.jobId,\n batchSize: msg.batchSize,\n chainWaitDurationMs: msg.chainWaitDurationMs,\n preReadyDurationMs: msg.preReadyDurationMs,\n emitDurationMs: msg.emitDurationMs,\n postReadyDurationMs: msg.postReadyDurationMs,\n });\n return;\n case \"chain-depth\":\n shard.lastDepth = msg.depth;\n shard.lastDepthAt = msg.timestamp;\n return;\n case \"pool-acquire-samples\":\n this.handlePoolAcquireSamples(shard, msg);\n return;\n case \"drained\":\n this.handleDrained(msg);\n return;\n case \"log\":\n this.handleLog(shard, msg);\n return;\n case \"readmodel-swept\":\n this.trackersByReadModelName\n .get(msg.readModelName)\n ?.update(msg.coordinates);\n void this.hostBus\n .emit(ReactorEventTypes.CATCHUP_SWEPT, {\n ...msg.result,\n thread: \"projection\",\n })\n .catch(() => {});\n return;\n case \"catchup-status\":\n shard.catchUpStatus = msg.status;\n return;\n default: {\n const exhaustive: never = msg;\n void exhaustive;\n return;\n }\n }\n }\n\n /**\n * Advances the host's tracker for the read model the shard just indexed.\n *\n * The shard writes to the same tables the host reads, so once it reports a\n * successful index the host's read path really is consistent to those\n * coordinates. Gated on `success` for parity with\n * `BaseReadModel.indexOperations`, which updates its tracker only after\n * `commitOperations` returns. The worker posts this before its\n * JOB_READ_READY, matching the in-process ordering.\n */\n private advanceConsistencyTrackers(\n shard: ShardState,\n msg: ProjectionReadModelIndexedMessage,\n ): void {\n if (!msg.success) {\n return;\n }\n const tracker = this.trackersByReadModelName.get(msg.readModelName);\n if (!tracker) {\n return;\n }\n const coordinates = shard.pendingCoordinates.get(msg.jobId);\n if (!coordinates || coordinates.length === 0) {\n return;\n }\n tracker.update(coordinates);\n }\n\n private handlePoolAcquireSamples(\n shard: ShardState,\n msg: ProjectionPoolAcquireSamplesMessage,\n ): void {\n if (!shard.poolInstrumentation) {\n return;\n }\n shard.poolInstrumentation.updateStats({\n size: msg.size,\n idle: msg.idle,\n waiting: msg.waiting,\n });\n shard.poolInstrumentation.pushSamples(msg.durations);\n }\n\n /**\n * Settles a shard's unresolved `init` with `error`, clearing its timer.\n * Returns false when the shard has no init outstanding, which is every\n * failure after startup. `startup()` awaits all init promises together, so\n * the rejection is always attached.\n */\n private failPendingInit(shard: ShardState, error: Error): boolean {\n const correlationId = shard.initCorrelationId;\n if (correlationId === undefined) {\n return false;\n }\n shard.initCorrelationId = undefined;\n const pending = this.initPromises.get(correlationId);\n if (!pending) {\n return false;\n }\n this.initPromises.delete(correlationId);\n clearTimeout(pending.timer);\n pending.reject(error);\n return true;\n }\n\n private handleReady(shard: ShardState, correlationId: string): void {\n shard.ready = true;\n shard.initCorrelationId = undefined;\n const pending = this.initPromises.get(correlationId);\n if (!pending) {\n return;\n }\n this.initPromises.delete(correlationId);\n clearTimeout(pending.timer);\n pending.resolve();\n }\n\n private handleDrained(msg: ProjectionDrainedMessage): void {\n const pending = this.pendingDrains.get(msg.correlationId);\n if (!pending) {\n return;\n }\n this.releaseDrain(msg.correlationId, pending, msg.shardId);\n }\n\n /** Removes `shardId` from a pending drain and settles it once no shard remains. */\n private releaseDrain(\n correlationId: string,\n pending: PendingDrain,\n shardId: string,\n ): void {\n pending.remaining.delete(shardId);\n if (pending.remaining.size > 0) {\n return;\n }\n this.pendingDrains.delete(correlationId);\n clearTimeout(pending.timer);\n pending.resolve();\n }\n\n private handleLog(\n shard: ShardState,\n msg: Extract<ProjectionWorkerMessage, { type: \"log\" }>,\n ): void {\n switch (msg.level) {\n case \"debug\":\n this.logger.debug(msg.message, ...msg.args);\n return;\n case \"info\":\n this.logger.info(msg.message, ...msg.args);\n return;\n case \"warn\":\n this.logger.warn(msg.message, ...msg.args);\n return;\n case \"error\":\n this.logger.error(msg.message, ...msg.args);\n return;\n default: {\n const exhaustive: never = msg.level;\n void exhaustive;\n }\n }\n void shard;\n }\n\n private handleTransportError(shard: ShardState, err: Error): void {\n this.logger.error(\n \"projection shard transport error @shardId: @error\",\n shard.shardId,\n err,\n );\n // A shard that dies during startup is reported through `startup()`, not\n // through the fatal hook: the host is still building and its shutdown\n // path (which the hook usually triggers) does not exist yet.\n if (this.failPendingInit(shard, err)) {\n return;\n }\n if (!this.isShuttingDown) {\n this.config.onShardFatal?.(shard.shardId, err);\n }\n }\n\n private handleTransportExit(shard: ShardState, code: number): void {\n const wasReady = shard.ready;\n shard.ready = false;\n // Nothing respawns the shard, so every job it had in flight is lost with\n // it. Release them rather than pin their operations for the process's\n // remaining life.\n const abandoned = [...shard.pendingCoordinates.keys()];\n shard.pendingCoordinates.clear();\n for (const [correlationId, pending] of this.pendingDrains) {\n this.releaseDrain(correlationId, pending, shard.shardId);\n }\n if (\n this.failPendingInit(\n shard,\n new Error(\n `projection shard ${shard.shardId} exited with code ${code} before becoming ready`,\n ),\n )\n ) {\n return;\n }\n if (!wasReady || this.isShuttingDown) {\n return;\n }\n this.logger.error(\n \"projection shard exited unexpectedly @shardId code=@code, abandoning @count in-flight job(s): @jobIds\",\n shard.shardId,\n code,\n abandoned.length,\n abandoned.join(\", \"),\n );\n this.config.onShardFatal?.(\n shard.shardId,\n new Error(\n `projection shard ${shard.shardId} exited with code ${code}; ` +\n `${abandoned.length} in-flight job(s) will never be projected` +\n (abandoned.length > 0 ? `: ${abandoned.join(\", \")}` : \"\"),\n ),\n );\n }\n\n private relayReadReady(event: JobReadReadyEvent): void {\n const hook = this.config.onReadReady;\n if (hook) {\n hook(event);\n return;\n }\n void this.emitReadReady(event).catch((err: unknown) =>\n this.logger.error(\n \"host JOB_READ_READY emit failed for job @jobId: @error\",\n event.jobId,\n err,\n ),\n );\n }\n\n private relayReadModelIndexed(event: ReadModelIndexedEvent): void {\n void this.hostBus\n .emit(ReactorEventTypes.READMODEL_INDEXED, event)\n .catch((err: unknown) =>\n this.logger.error(\n \"host READMODEL_INDEXED emit failed for job @jobId: @error\",\n event.jobId,\n err,\n ),\n );\n }\n\n private relayBatchCompleted(event: ReadModelBatchCompletedEvent): void {\n void this.hostBus\n .emit(ReactorEventTypes.READMODEL_BATCH_COMPLETED, event)\n .catch((err: unknown) =>\n this.logger.error(\n \"host READMODEL_BATCH_COMPLETED emit failed for job @jobId: @error\",\n event.jobId,\n err,\n ),\n );\n }\n}\n"],"mappings":";;;;;AAqCA,MAAM,0BAA0B;AAChC,MAAM,4BAA4B;AAClC,MAAM,2BAA2B;AACjC,MAAM,yCAAyC;;;;;AAM/C,SAAS,yBACP,YACyB;CACzB,MAAM,cAAuC,CAAC;CAC9C,KAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KAAK;EAC1C,MAAM,OAAO,WAAW;EACxB,YAAY,KAAK;GACf,YAAY,KAAK,QAAQ;GACzB,OAAO,KAAK,QAAQ;GACpB,QAAQ,KAAK,QAAQ;GACrB,gBAAgB,KAAK,UAAU;EACjC,CAAC;CACH;CACA,OAAO;AACT;;;;;;;;;;;;;;;;AA6HA,IAAa,yBAAb,MAAqE;CACnE,aAAoC,CAAC;CAErC;CAC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,yBACN,IAAI,MACF,oBAAoB,MAAM,QAAQ,oBAAoB,KAAK,IACtD,UAAU,OAAO,8CACnB,UAAU,SAAS,IAAI,KAAK,UAAU,KAAK,IAAI,MAAM,GAC1D,CACF;CACF;CAEA,eAAuB,OAAgC;EACrD,MAAM,OAAO,KAAK,OAAO;EACzB,IAAI,MAAM;GACR,KAAK,KAAK;GACV;EACF;EACA,KAAU,cAAc,KAAK,CAAC,CAAC,OAAO,QACpC,KAAK,OAAO,MACV,0DACA,MAAM,OACN,GACF,CACF;CACF;CAEA,sBAA8B,OAAoC;EAChE,KAAU,QACP,KAAK,kBAAkB,mBAAmB,KAAK,CAAC,CAChD,OAAO,QACN,KAAK,OAAO,MACV,6DACA,MAAM,OACN,GACF,CACF;CACJ;CAEA,oBAA4B,OAA2C;EACrE,KAAU,QACP,KAAK,kBAAkB,2BAA2B,KAAK,CAAC,CACxD,OAAO,QACN,KAAK,OAAO,MACV,qEACA,MAAM,OACN,GACF,CACF;CACJ;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"projection-worker-
|
|
1
|
+
{"version":3,"file":"projection-worker-D8uNFdwX.js","names":[],"sources":["../src/projection/projection-worker/index.ts"],"sourcesContent":["function resolveProjectionWorkerEntryPath(): string {\n const url = new URL(\"./projection-entry.js\", import.meta.url);\n if (url.protocol !== \"file:\") {\n return url.href;\n }\n let pathname = decodeURIComponent(url.pathname);\n if (/^\\/[A-Za-z]:[/\\\\]/.test(pathname)) {\n pathname = pathname.slice(1);\n }\n return pathname;\n}\n\nexport const projectionWorkerEntryPath = resolveProjectionWorkerEntryPath();\n"],"mappings":";AAAA,SAAS,mCAA2C;CAClD,MAAM,MAAM,IAAI,IAAI,yBAAyB,YAAY,GAAG;CAC5D,IAAI,IAAI,aAAa,SACnB,OAAO,IAAI;CAEb,IAAI,WAAW,mBAAmB,IAAI,QAAQ;CAC9C,IAAI,oBAAoB,KAAK,QAAQ,GACnC,WAAW,SAAS,MAAM,CAAC;CAE7B,OAAO;AACT;AAEA,MAAa,4BAA4B,iCAAiC"}
|
package/dist/rpc.d.ts
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
import { Pt as IReactorClient, ji as IDocumentModelRegistry, s as loadDocumentModelSpec, t as DocumentModelRegistry, za as RemoteFilter } from "./index-dDm0fUBT.js";
|
|
2
|
+
//#region src/rpc/protocol.d.ts
|
|
3
|
+
type CorrelationId = string;
|
|
4
|
+
type ErrorInfo = {
|
|
5
|
+
name: string;
|
|
6
|
+
message: string;
|
|
7
|
+
stack?: string;
|
|
8
|
+
cause?: ErrorInfo;
|
|
9
|
+
};
|
|
10
|
+
type RpcRequest = {
|
|
11
|
+
k: "req";
|
|
12
|
+
id: CorrelationId;
|
|
13
|
+
method: string;
|
|
14
|
+
args: unknown[];
|
|
15
|
+
abortAt?: number;
|
|
16
|
+
};
|
|
17
|
+
type RpcResponse = {
|
|
18
|
+
k: "res";
|
|
19
|
+
id: CorrelationId;
|
|
20
|
+
value: unknown;
|
|
21
|
+
};
|
|
22
|
+
type RpcError = {
|
|
23
|
+
k: "err";
|
|
24
|
+
id: CorrelationId;
|
|
25
|
+
error: ErrorInfo;
|
|
26
|
+
};
|
|
27
|
+
/** Failed document subscribe; routed to the change-subscription registry. */
|
|
28
|
+
type RpcSubError = {
|
|
29
|
+
k: "sub-err";
|
|
30
|
+
id: CorrelationId;
|
|
31
|
+
error: ErrorInfo;
|
|
32
|
+
};
|
|
33
|
+
/** Failed live query; routed to the live-query registry. */
|
|
34
|
+
type RpcLiveError = {
|
|
35
|
+
k: "live-err";
|
|
36
|
+
id: CorrelationId;
|
|
37
|
+
error: ErrorInfo;
|
|
38
|
+
};
|
|
39
|
+
type RpcAbort = {
|
|
40
|
+
k: "abort";
|
|
41
|
+
targetId: CorrelationId;
|
|
42
|
+
};
|
|
43
|
+
type RpcSubscribe = {
|
|
44
|
+
k: "sub";
|
|
45
|
+
id: CorrelationId;
|
|
46
|
+
search: unknown;
|
|
47
|
+
view?: unknown;
|
|
48
|
+
};
|
|
49
|
+
type RpcEvent = {
|
|
50
|
+
k: "event";
|
|
51
|
+
id: CorrelationId;
|
|
52
|
+
change: unknown;
|
|
53
|
+
};
|
|
54
|
+
type RpcUnsub = {
|
|
55
|
+
k: "unsub";
|
|
56
|
+
id: CorrelationId;
|
|
57
|
+
};
|
|
58
|
+
type RpcNextPage = {
|
|
59
|
+
k: "page";
|
|
60
|
+
id: CorrelationId;
|
|
61
|
+
token: string;
|
|
62
|
+
};
|
|
63
|
+
export declare const RPC_PROTOCOL_VERSION = 3;
|
|
64
|
+
/**
|
|
65
|
+
* A package the worker loads by URL rather than by registry spec: local
|
|
66
|
+
* project packages, whose models the registry does not serve. The URL must be
|
|
67
|
+
* a worker-importable models entry - the dev server's transformed
|
|
68
|
+
* `document-models/index.js` in dev, a prebuilt bundle under
|
|
69
|
+
* `__reactor_worker__/packages/` in production.
|
|
70
|
+
*/
|
|
71
|
+
type WorkerPackageSource = {
|
|
72
|
+
name: string;
|
|
73
|
+
version?: string;
|
|
74
|
+
url: string;
|
|
75
|
+
};
|
|
76
|
+
type VersionFingerprint = {
|
|
77
|
+
appBuildId: string;
|
|
78
|
+
rpcProtocolVersion: number;
|
|
79
|
+
models: {
|
|
80
|
+
id: string;
|
|
81
|
+
version: number;
|
|
82
|
+
}[];
|
|
83
|
+
featureFlags?: string;
|
|
84
|
+
};
|
|
85
|
+
type RpcHello = {
|
|
86
|
+
k: "hello";
|
|
87
|
+
id: CorrelationId;
|
|
88
|
+
version: VersionFingerprint;
|
|
89
|
+
construct?: unknown;
|
|
90
|
+
packages?: string[];
|
|
91
|
+
};
|
|
92
|
+
type RpcRegisterPackages = {
|
|
93
|
+
k: "register-packages";
|
|
94
|
+
id: CorrelationId;
|
|
95
|
+
specs: string[];
|
|
96
|
+
/** URL-addressed packages; the worker REPLACES a source it already loaded. */
|
|
97
|
+
sources?: WorkerPackageSource[];
|
|
98
|
+
};
|
|
99
|
+
type RpcUnregisterPackages = {
|
|
100
|
+
k: "unregister-packages";
|
|
101
|
+
id: CorrelationId;
|
|
102
|
+
names: string[];
|
|
103
|
+
};
|
|
104
|
+
type RpcReload = {
|
|
105
|
+
k: "reload";
|
|
106
|
+
reason: string;
|
|
107
|
+
workerGen?: string;
|
|
108
|
+
};
|
|
109
|
+
type RpcAdmin = {
|
|
110
|
+
k: "admin";
|
|
111
|
+
id: CorrelationId;
|
|
112
|
+
method: "info" | "restart" | "clearStorage" | "migrate";
|
|
113
|
+
};
|
|
114
|
+
type WorkerMigrationState = {
|
|
115
|
+
status: "idle" | "needed" | "migrating" | "failed";
|
|
116
|
+
legacyMajor?: number;
|
|
117
|
+
phase?: "clone" | "dump" | "restore";
|
|
118
|
+
error?: string;
|
|
119
|
+
};
|
|
120
|
+
type RpcMigration = {
|
|
121
|
+
k: "migration";
|
|
122
|
+
state: WorkerMigrationState;
|
|
123
|
+
};
|
|
124
|
+
type WorkerInspectorInfo = {
|
|
125
|
+
namespace: string;
|
|
126
|
+
ownerId: string;
|
|
127
|
+
bootedAtMs: number;
|
|
128
|
+
connectedClients: number;
|
|
129
|
+
appBuildId: string;
|
|
130
|
+
rpcProtocolVersion: number;
|
|
131
|
+
/** Flags this worker is enforcing, from the fingerprint that built it. */
|
|
132
|
+
featureFlags?: string;
|
|
133
|
+
};
|
|
134
|
+
type ReactorIdentity = {
|
|
135
|
+
address: string;
|
|
136
|
+
chainId: number;
|
|
137
|
+
networkId: string;
|
|
138
|
+
};
|
|
139
|
+
type RpcIdentity = {
|
|
140
|
+
k: "identity";
|
|
141
|
+
user: ReactorIdentity | null;
|
|
142
|
+
};
|
|
143
|
+
type RpcBusEvent = {
|
|
144
|
+
k: "bus-event";
|
|
145
|
+
eventType: number;
|
|
146
|
+
event: unknown;
|
|
147
|
+
};
|
|
148
|
+
type OpKind = "sync-op" | "db-op" | "inspector-op";
|
|
149
|
+
type MethodCallMessage<K extends OpKind> = {
|
|
150
|
+
k: K;
|
|
151
|
+
id: CorrelationId;
|
|
152
|
+
method: string;
|
|
153
|
+
args: unknown[];
|
|
154
|
+
};
|
|
155
|
+
type RpcSyncOp = MethodCallMessage<"sync-op">;
|
|
156
|
+
type RpcDbOp = MethodCallMessage<"db-op">;
|
|
157
|
+
type RpcInspectorOp = MethodCallMessage<"inspector-op">;
|
|
158
|
+
/**
|
|
159
|
+
* Hands the host one end of a brokered `MessageChannel` and asks it to adopt
|
|
160
|
+
* the peer as a local remote. Post it with `port` in the transfer list.
|
|
161
|
+
*/
|
|
162
|
+
type RpcAdoptSyncPeer = {
|
|
163
|
+
k: "adopt-sync-peer";
|
|
164
|
+
id: CorrelationId;
|
|
165
|
+
peerId: string;
|
|
166
|
+
channelName: string;
|
|
167
|
+
/** `DriveCollectionId.key`; the class does not survive structured clone. */
|
|
168
|
+
collectionIdKey: string;
|
|
169
|
+
remoteName: string;
|
|
170
|
+
filter: RemoteFilter;
|
|
171
|
+
port: MessagePort;
|
|
172
|
+
};
|
|
173
|
+
/** Removes an adopted local peer and closes its port in the host's registry. */
|
|
174
|
+
type RpcRemoveSyncPeer = {
|
|
175
|
+
k: "remove-sync-peer";
|
|
176
|
+
id: CorrelationId;
|
|
177
|
+
peerId: string;
|
|
178
|
+
channelName: string;
|
|
179
|
+
remoteName: string;
|
|
180
|
+
};
|
|
181
|
+
type RpcLiveSubscribe = {
|
|
182
|
+
k: "sub-live";
|
|
183
|
+
id: CorrelationId;
|
|
184
|
+
sql: string;
|
|
185
|
+
params: unknown[];
|
|
186
|
+
};
|
|
187
|
+
type RpcLiveEvent = {
|
|
188
|
+
k: "event-live";
|
|
189
|
+
id: CorrelationId;
|
|
190
|
+
results: unknown;
|
|
191
|
+
};
|
|
192
|
+
type RpcLiveUnsub = {
|
|
193
|
+
k: "unsub-live";
|
|
194
|
+
id: CorrelationId;
|
|
195
|
+
};
|
|
196
|
+
type RpcPing = {
|
|
197
|
+
k: "ping";
|
|
198
|
+
id: CorrelationId;
|
|
199
|
+
};
|
|
200
|
+
type RpcPong = {
|
|
201
|
+
k: "pong";
|
|
202
|
+
id: CorrelationId;
|
|
203
|
+
ownerId: string;
|
|
204
|
+
bootedAtMs: number;
|
|
205
|
+
};
|
|
206
|
+
type ClientMessage = RpcRequest | RpcAbort | RpcSubscribe | RpcUnsub | RpcNextPage | RpcHello | RpcRegisterPackages | RpcUnregisterPackages | RpcIdentity | RpcAdmin | RpcSyncOp | RpcDbOp | RpcInspectorOp | RpcAdoptSyncPeer | RpcRemoveSyncPeer | RpcLiveSubscribe | RpcLiveUnsub | RpcPing;
|
|
207
|
+
type OwnerMessage = RpcResponse | RpcError | RpcSubError | RpcLiveError | RpcEvent | RpcReload | RpcBusEvent | RpcLiveEvent | RpcMigration | RpcPong;
|
|
208
|
+
type RpcMessage = ClientMessage | OwnerMessage;
|
|
209
|
+
//#endregion
|
|
210
|
+
//#region src/rpc/rpc-correlator.d.ts
|
|
211
|
+
type RpcRequestOptions = {
|
|
212
|
+
/** Reject if no response arrives within this many ms; omit for no timeout. */
|
|
213
|
+
timeoutMs?: number;
|
|
214
|
+
/** Maps a successful response value (e.g. paged-result rehydration). */
|
|
215
|
+
transform?: (value: unknown) => unknown;
|
|
216
|
+
/** Runs after the post; may return a cleanup invoked when the request settles. */
|
|
217
|
+
setup?: (id: CorrelationId) => (() => void) | void;
|
|
218
|
+
/** Moved, not cloned, with the request message. */
|
|
219
|
+
transfer?: Transferable[];
|
|
220
|
+
};
|
|
221
|
+
/** Anything that can send a client message (the router). */
|
|
222
|
+
type RpcPoster = {
|
|
223
|
+
post(message: ClientMessage, transfer?: Transferable[]): void;
|
|
224
|
+
};
|
|
225
|
+
/**
|
|
226
|
+
* Request/response correlation shared by every RPC proxy: one pending map,
|
|
227
|
+
* res/err settlement, and per-request timeout/transform/cleanup.
|
|
228
|
+
*/
|
|
229
|
+
export declare class RpcCorrelator {
|
|
230
|
+
private readonly poster;
|
|
231
|
+
private readonly prefix;
|
|
232
|
+
private counter;
|
|
233
|
+
private readonly pending;
|
|
234
|
+
constructor(poster: RpcPoster, prefix?: string);
|
|
235
|
+
nextId(): CorrelationId;
|
|
236
|
+
/** Settle the pending request a res/err refers to; a missing id is a no-op. */
|
|
237
|
+
handleMessage(message: OwnerMessage): void;
|
|
238
|
+
/** Send a request, resolving on its res/err. `build` stamps the generated id. */
|
|
239
|
+
request(build: (id: CorrelationId) => ClientMessage, options?: RpcRequestOptions): Promise<unknown>;
|
|
240
|
+
}
|
|
241
|
+
//#endregion
|
|
242
|
+
//#region src/rpc/transport.d.ts
|
|
243
|
+
interface IRpcTransport {
|
|
244
|
+
/** `transfer` moves its entries, such as a MessagePort, instead of cloning them. */
|
|
245
|
+
post(message: RpcMessage, transfer?: Transferable[]): void;
|
|
246
|
+
onMessage(listener: (message: RpcMessage) => void): () => void;
|
|
247
|
+
close(): void;
|
|
248
|
+
}
|
|
249
|
+
export declare function createPortTransport(port: MessagePort): IRpcTransport;
|
|
250
|
+
//#endregion
|
|
251
|
+
//#region src/rpc/message-router.d.ts
|
|
252
|
+
type OwnerKind = OwnerMessage["k"];
|
|
253
|
+
/**
|
|
254
|
+
* Owns the single transport.onMessage and dispatches each message to the one
|
|
255
|
+
* consumer that owns its kind. Composes the shared RpcCorrelator (res/err) and
|
|
256
|
+
* exposes request/nextId; attach/detach swap the transport for reconnect.
|
|
257
|
+
*/
|
|
258
|
+
export declare class MessageRouter {
|
|
259
|
+
private readonly handlers;
|
|
260
|
+
private readonly correlator;
|
|
261
|
+
private transport;
|
|
262
|
+
private detachTransport;
|
|
263
|
+
constructor(prefix?: string);
|
|
264
|
+
attach(transport: IRpcTransport): void;
|
|
265
|
+
detach(): void;
|
|
266
|
+
post(message: ClientMessage, transfer?: Transferable[]): void;
|
|
267
|
+
/** Register the sole owner of a message kind; throws on a duplicate. */
|
|
268
|
+
on<K extends OwnerKind>(kind: K, handler: (message: Extract<OwnerMessage, {
|
|
269
|
+
k: K;
|
|
270
|
+
}>) => void): () => void;
|
|
271
|
+
request(build: (id: CorrelationId) => ClientMessage, options?: RpcRequestOptions): Promise<unknown>;
|
|
272
|
+
nextId(): CorrelationId;
|
|
273
|
+
}
|
|
274
|
+
//#endregion
|
|
275
|
+
//#region src/rpc/client-proxy.d.ts
|
|
276
|
+
type ReactorClientProxyOptions = {
|
|
277
|
+
onReload?: (reason: string, workerGen?: string) => void;
|
|
278
|
+
/** Tab-local registry for module lookups (reducers/editors can't cross the worker boundary). */
|
|
279
|
+
registry?: IDocumentModelRegistry;
|
|
280
|
+
};
|
|
281
|
+
export declare function createReactorClientProxy(router: MessageRouter, options?: ReactorClientProxyOptions): IReactorClient;
|
|
282
|
+
//#endregion
|
|
283
|
+
//#region src/rpc/error-info.d.ts
|
|
284
|
+
export declare function toErrorInfo(err: unknown, depth?: number): ErrorInfo;
|
|
285
|
+
export declare function fromErrorInfo(info: ErrorInfo): Error;
|
|
286
|
+
//#endregion
|
|
287
|
+
//#region src/rpc/host-reply.d.ts
|
|
288
|
+
interface IHostResponder {
|
|
289
|
+
ok(id: CorrelationId, value?: unknown): void;
|
|
290
|
+
err(id: CorrelationId, error: unknown): void;
|
|
291
|
+
errForKind(message: ClientMessage, error: unknown): void;
|
|
292
|
+
run(id: CorrelationId, body: () => Promise<unknown>, mapOk?: (value: unknown) => unknown): Promise<void>;
|
|
293
|
+
}
|
|
294
|
+
export declare function hostResponder(transport: IRpcTransport): IHostResponder;
|
|
295
|
+
//#endregion
|
|
296
|
+
//#region src/rpc/host-server.d.ts
|
|
297
|
+
export declare class ReactorHostServer {
|
|
298
|
+
private readonly client;
|
|
299
|
+
private readonly transport;
|
|
300
|
+
private readonly reply;
|
|
301
|
+
private readonly aborters;
|
|
302
|
+
private readonly subscriptions;
|
|
303
|
+
private readonly pages;
|
|
304
|
+
private pageCounter;
|
|
305
|
+
private detach;
|
|
306
|
+
constructor(client: IReactorClient, transport: IRpcTransport);
|
|
307
|
+
start(): void;
|
|
308
|
+
stop(): void;
|
|
309
|
+
handleMessage(message: ClientMessage): Promise<void>;
|
|
310
|
+
private handleRequest;
|
|
311
|
+
private handlePage;
|
|
312
|
+
private handleSubscribe;
|
|
313
|
+
private prepareResult;
|
|
314
|
+
private resolveMethod;
|
|
315
|
+
}
|
|
316
|
+
//#endregion
|
|
317
|
+
//#region src/rpc/listeners.d.ts
|
|
318
|
+
export declare class KeyedListeners<K, A extends unknown[] = []> {
|
|
319
|
+
private readonly map;
|
|
320
|
+
add(key: K, fn: (...a: A) => void): () => void;
|
|
321
|
+
emit(key: K, ...a: A): void;
|
|
322
|
+
emitAll(...a: A): void;
|
|
323
|
+
}
|
|
324
|
+
export declare class Listeners<A extends unknown[] = []> {
|
|
325
|
+
private readonly keyed;
|
|
326
|
+
add(fn: (...a: A) => void): () => void;
|
|
327
|
+
emit(...a: A): void;
|
|
328
|
+
}
|
|
329
|
+
//#endregion
|
|
330
|
+
//#region src/rpc/subscription.d.ts
|
|
331
|
+
export declare class SubscriptionStore {
|
|
332
|
+
private readonly map;
|
|
333
|
+
set(id: CorrelationId, unsubscribe: () => void): void;
|
|
334
|
+
get(id: CorrelationId): (() => void) | undefined;
|
|
335
|
+
delete(id: CorrelationId): void;
|
|
336
|
+
end(id: CorrelationId): void;
|
|
337
|
+
drain(): void;
|
|
338
|
+
}
|
|
339
|
+
interface ICorrelatedSubscriptions<Sub> {
|
|
340
|
+
subscribe(sub: Sub, open: (id: CorrelationId) => ClientMessage): () => void;
|
|
341
|
+
}
|
|
342
|
+
interface CorrelatedConfig<Sub, EK extends OwnerMessage["k"], ErrK extends OwnerMessage["k"]> {
|
|
343
|
+
idPrefix: string;
|
|
344
|
+
eventKind: EK;
|
|
345
|
+
errKind: ErrK;
|
|
346
|
+
onEvent: (sub: Sub, message: Extract<OwnerMessage, {
|
|
347
|
+
k: EK;
|
|
348
|
+
}>) => void;
|
|
349
|
+
onError: (sub: Sub, message: Extract<OwnerMessage, {
|
|
350
|
+
k: ErrK;
|
|
351
|
+
}>) => void;
|
|
352
|
+
close: (id: CorrelationId) => ClientMessage;
|
|
353
|
+
}
|
|
354
|
+
export declare function createCorrelatedSubscriptions<Sub, EK extends OwnerMessage["k"], ErrK extends OwnerMessage["k"]>(router: MessageRouter, config: CorrelatedConfig<Sub, EK, ErrK>): ICorrelatedSubscriptions<Sub>;
|
|
355
|
+
//#endregion
|
|
356
|
+
export { type ClientMessage, type CorrelationId, DocumentModelRegistry, type ErrorInfo, type ICorrelatedSubscriptions, type IDocumentModelRegistry, type IHostResponder, type IRpcTransport, type MethodCallMessage, type OpKind, type OwnerMessage, type ReactorIdentity, type RpcAbort, type RpcAdmin, type RpcAdoptSyncPeer, type RpcBusEvent, type RpcDbOp, type RpcError, type RpcEvent, type RpcHello, type RpcIdentity, type RpcInspectorOp, type RpcLiveError, type RpcLiveEvent, type RpcLiveSubscribe, type RpcLiveUnsub, type RpcMessage, type RpcMigration, type RpcNextPage, type RpcPing, type RpcPong, type RpcPoster, type RpcRegisterPackages, type RpcReload, type RpcRemoveSyncPeer, type RpcRequest, type RpcRequestOptions, type RpcResponse, type RpcSubError, type RpcSubscribe, type RpcSyncOp, type RpcUnregisterPackages, type RpcUnsub, type VersionFingerprint, type WorkerInspectorInfo, type WorkerMigrationState, type WorkerPackageSource, loadDocumentModelSpec };
|
|
357
|
+
export {};
|
|
358
|
+
//# sourceMappingURL=rpc.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rpc.d.ts","names":[],"sources":["../src/rpc/protocol.ts","../src/rpc/rpc-correlator.ts","../src/rpc/transport.ts","../src/rpc/message-router.ts","../src/rpc/client-proxy.ts","../src/rpc/error-info.ts","../src/rpc/host-reply.ts","../src/rpc/host-server.ts","../src/rpc/listeners.ts","../src/rpc/subscription.ts"],"mappings":";;KAEY;KAEA;EACV;EACA;EACA;EACA,QAAQ;;KAGE;EACV;EACA,IAAI;EACJ;EACA;EACA;;KAGU;EAAgB;EAAU,IAAI;EAAe;;KAE7C;EAAa;EAAU,IAAI;EAAe,OAAO;;;KAGjD;EAAgB;EAAc,IAAI;EAAe,OA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