@objectstack/service-cluster 9.3.0 → 9.5.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/.turbo/turbo-build.log +10 -10
- package/CHANGELOG.md +23 -0
- package/dist/index.cjs +23 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +25 -1
- package/dist/index.d.ts +25 -1
- package/dist/index.js +22 -0
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
- package/src/cluster-service-plugin.ts +6 -0
- package/src/index.ts +19 -3
- package/src/split-brain-guard.test.ts +61 -0
- package/src/split-brain-guard.ts +78 -0
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
> @objectstack/service-cluster@9.
|
|
2
|
+
> @objectstack/service-cluster@9.5.0 build /home/runner/work/framework/framework/packages/services/service-cluster
|
|
3
3
|
> tsup
|
|
4
4
|
|
|
5
5
|
[34mCLI[39m Building entry: src/index.ts, src/testing.ts
|
|
@@ -10,19 +10,19 @@
|
|
|
10
10
|
[34mCLI[39m Cleaning output folder
|
|
11
11
|
[34mESM[39m Build start
|
|
12
12
|
[34mCJS[39m Build start
|
|
13
|
-
[32mESM[39m [1mdist/index.js [22m[
|
|
13
|
+
[32mESM[39m [1mdist/index.js [22m[32m13.87 KB[39m
|
|
14
14
|
[32mESM[39m [1mdist/testing.js [22m[32m8.60 KB[39m
|
|
15
|
-
[32mESM[39m [1mdist/index.js.map [22m[
|
|
15
|
+
[32mESM[39m [1mdist/index.js.map [22m[32m38.10 KB[39m
|
|
16
16
|
[32mESM[39m [1mdist/testing.js.map [22m[32m18.62 KB[39m
|
|
17
|
-
[32mESM[39m ⚡️ Build success in
|
|
18
|
-
[32mCJS[39m [1mdist/index.cjs [22m[
|
|
17
|
+
[32mESM[39m ⚡️ Build success in 857ms
|
|
18
|
+
[32mCJS[39m [1mdist/index.cjs [22m[32m15.26 KB[39m
|
|
19
19
|
[32mCJS[39m [1mdist/testing.cjs [22m[32m11.60 KB[39m
|
|
20
|
-
[32mCJS[39m [1mdist/index.cjs.map [22m[
|
|
20
|
+
[32mCJS[39m [1mdist/index.cjs.map [22m[32m41.16 KB[39m
|
|
21
21
|
[32mCJS[39m [1mdist/testing.cjs.map [22m[32m14.18 KB[39m
|
|
22
|
-
[32mCJS[39m ⚡️ Build success in
|
|
22
|
+
[32mCJS[39m ⚡️ Build success in 1082ms
|
|
23
23
|
[34mDTS[39m Build start
|
|
24
|
-
[32mDTS[39m ⚡️ Build success in
|
|
25
|
-
[32mDTS[39m [1mdist/index.d.ts [22m[
|
|
24
|
+
[32mDTS[39m ⚡️ Build success in 21212ms
|
|
25
|
+
[32mDTS[39m [1mdist/index.d.ts [22m[32m9.12 KB[39m
|
|
26
26
|
[32mDTS[39m [1mdist/testing.d.ts [22m[32m794.00 B[39m
|
|
27
|
-
[32mDTS[39m [1mdist/index.d.cts [22m[
|
|
27
|
+
[32mDTS[39m [1mdist/index.d.cts [22m[32m9.12 KB[39m
|
|
28
28
|
[32mDTS[39m [1mdist/testing.d.cts [22m[32m794.00 B[39m
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
# @objectstack/service-cluster
|
|
2
2
|
|
|
3
|
+
## 9.5.0
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies [d08551c]
|
|
8
|
+
- Updated dependencies [707aeed]
|
|
9
|
+
- Updated dependencies [7a103d4]
|
|
10
|
+
- Updated dependencies [4b01250]
|
|
11
|
+
- @objectstack/spec@9.5.0
|
|
12
|
+
- @objectstack/core@9.5.0
|
|
13
|
+
|
|
14
|
+
## 9.4.0
|
|
15
|
+
|
|
16
|
+
### Patch Changes
|
|
17
|
+
|
|
18
|
+
- Updated dependencies [060467a]
|
|
19
|
+
- Updated dependencies [0856476]
|
|
20
|
+
- Updated dependencies [b678d8c]
|
|
21
|
+
- Updated dependencies [b678d8c]
|
|
22
|
+
- Updated dependencies [b678d8c]
|
|
23
|
+
- @objectstack/spec@9.4.0
|
|
24
|
+
- @objectstack/core@9.4.0
|
|
25
|
+
|
|
3
26
|
## 9.3.0
|
|
4
27
|
|
|
5
28
|
### Patch Changes
|
package/dist/index.cjs
CHANGED
|
@@ -337,6 +337,25 @@ function generateNodeId() {
|
|
|
337
337
|
return `node-${ts}-${rand}`;
|
|
338
338
|
}
|
|
339
339
|
|
|
340
|
+
// src/split-brain-guard.ts
|
|
341
|
+
var IN_PROCESS_DRIVERS = /* @__PURE__ */ new Set(["memory"]);
|
|
342
|
+
function isTrue(v) {
|
|
343
|
+
return String(v).trim().toLowerCase() === "true";
|
|
344
|
+
}
|
|
345
|
+
function declaresMultiNode(env = process.env) {
|
|
346
|
+
if (isTrue(env.OS_EXPECT_MULTI_NODE)) return true;
|
|
347
|
+
const replicas = Number(env.OS_CLUSTER_REPLICAS);
|
|
348
|
+
return Number.isFinite(replicas) && replicas > 1;
|
|
349
|
+
}
|
|
350
|
+
function assertClusterDriverSafeForTopology(driver, env = process.env) {
|
|
351
|
+
if (!declaresMultiNode(env)) return;
|
|
352
|
+
if (!IN_PROCESS_DRIVERS.has(driver)) return;
|
|
353
|
+
if (isTrue(env.OS_ALLOW_MEMORY_CLUSTER_MULTINODE)) return;
|
|
354
|
+
throw new Error(
|
|
355
|
+
`ClusterServicePlugin: multi-node deployment declared (OS_EXPECT_MULTI_NODE / OS_CLUSTER_REPLICAS>1) but the cluster driver is in-process "${driver}" -- its locks/counters/pub-sub do not coordinate across processes, so multiple replicas silently split-brain. Configure a remote cluster driver (e.g. @objectstack/service-cluster-redis) or a DB-backed driver. To override (replicas declared but cluster primitives unused cross-node), set OS_ALLOW_MEMORY_CLUSTER_MULTINODE=true. See cloud ADR-0010.`
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
|
|
340
359
|
// src/cluster-service-plugin.ts
|
|
341
360
|
var ClusterServicePlugin = class {
|
|
342
361
|
constructor(options = {}) {
|
|
@@ -354,6 +373,7 @@ var ClusterServicePlugin = class {
|
|
|
354
373
|
this.cluster = defineCluster(_nullishCoalesce(this.options.config, () => ( {})));
|
|
355
374
|
this.owned = true;
|
|
356
375
|
}
|
|
376
|
+
assertClusterDriverSafeForTopology(this.cluster.driver);
|
|
357
377
|
ctx.registerService("cluster", this.cluster);
|
|
358
378
|
ctx.logger.info(
|
|
359
379
|
`ClusterServicePlugin: registered "${this.cluster.driver}" driver (node=${this.cluster.nodeId})`
|
|
@@ -440,5 +460,7 @@ var MetadataClusterBridgePlugin = class {
|
|
|
440
460
|
|
|
441
461
|
|
|
442
462
|
|
|
443
|
-
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
exports.ClusterServicePlugin = ClusterServicePlugin; exports.ComposedClusterService = ComposedClusterService; exports.MemoryCounter = MemoryCounter; exports.MemoryKV = MemoryKV; exports.MemoryLock = MemoryLock; exports.MemoryPubSub = MemoryPubSub; exports.MetadataClusterBridgePlugin = MetadataClusterBridgePlugin; exports.VersionMismatchError = VersionMismatchError; exports.assertClusterDriverSafeForTopology = assertClusterDriverSafeForTopology; exports.declaresMultiNode = declaresMultiNode; exports.defineCluster = defineCluster; exports.registerClusterDriver = registerClusterDriver;
|
|
444
466
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/framework/framework/packages/services/service-cluster/dist/index.cjs","../src/cluster.ts","../src/memory/pubsub.ts","../src/memory/lock.ts","../src/memory/kv.ts","../src/memory/counter.ts","../src/cluster-service-plugin.ts","../src/metadata-cluster-bridge-plugin.ts"],"names":[],"mappings":"AAAA;ACUA,kDAA8C;ADR9C;AACA;AE8BO,IAAM,aAAA,EAAN,MAAsC;AAAA,EAMzC,WAAA,CAAY,KAAA,EAA4B,CAAC,CAAA,EAAG;AAL5C,IAAA,IAAA,CAAiB,KAAA,kBAAO,IAAI,GAAA,CAA+B,CAAA;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IAAA;AACA,IAAA;AAIA,IAAA;AAGI,IAAA;AAAe,EAAA;AACnB,EAAA;AAGI,IAAA;AACI,MAAA;AACA,MAAA;AAAa,IAAA;AAEb,MAAA;AACA,MAAA;AAAa,IAAA;AAEjB,IAAA;AACA,IAAA;AAAW,MAAA;AACsF,IAAA;AAGjG,IAAA;AACI,MAAA;AACI,QAAA;AACI,UAAA;AAAyB,QAAA;AAEzB,UAAA;AAAkE,QAAA;AACtE,MAAA;AACJ,IAAA;AACH,EAAA;AAET;ANuSA;AACA;AO5VO;AAAoD,EAAA;AACvD,IAAA;AACA,IAAA;AACA,IAAA;AAAO,EAAA;AAAA,EAAA;AAKH,IAAA;AACI,MAAA;AACA,MAAA;AACA,MAAA;AACI,QAAA;AAAmD,MAAA;AAEnD,QAAA;AAAW,UAAA;AACP,QAAA;AAEJ,QAAA;AAAA,MAAA;AAEJ,MAAA;AACI,QAAA;AAAuC,MAAA;AAEvC,QAAA;AAAW,UAAA;AACP,QAAA;AAEJ,QAAA;AAAA,MAAA;AAGJ,MAAA;AAEA,MAAA;AACI,QAAA;AAAW,UAAA;AACP,QAAA;AAEJ,QAAA;AAAA,MAAA;AAGJ,MAAA;AACI,QAAA;AAIA,QAAA;AAAW,UAAA;AACuF,QAAA;AAClG,MAAA;AAEA,QAAA;AAAW,UAAA;AACP,UAAA;AACA,QAAA;AACJ,MAAA;AACJ,IAAA;AAGJ,IAAA;AACI,MAAA;AACI,wBAAA;AAAc,MAAA;AAEd,QAAA;AAAW,UAAA;AACP,UAAA;AACA,QAAA;AACJ,MAAA;AAEJ,MAAA;AAAc,IAAA;AACjB,EAAA;AAET;APsVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/framework/framework/packages/services/service-cluster/dist/index.cjs","sourcesContent":[null,"// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type {\n IClusterService,\n IPubSub,\n ILock,\n IKV,\n ICounter,\n} from '@objectstack/spec/contracts';\nimport type { ClusterCapabilityConfigInput } from '@objectstack/spec/kernel';\nimport { ClusterCapabilityConfigSchema } from '@objectstack/spec/kernel';\n\nimport { MemoryPubSub } from './memory/pubsub.js';\nimport { MemoryLock } from './memory/lock.js';\nimport { MemoryKV } from './memory/kv.js';\nimport { MemoryCounter } from './memory/counter.js';\n\n/**\n * Compose four cluster primitives into a single `IClusterService` facade.\n * Useful for custom driver authors who want to mix and match.\n */\nexport class ComposedClusterService implements IClusterService {\n constructor(\n public readonly nodeId: string,\n public readonly driver: string,\n public readonly pubsub: IPubSub,\n public readonly lock: ILock,\n public readonly kv: IKV,\n public readonly counter: ICounter,\n ) { }\n\n async close(): Promise<void> {\n // Reverse order, swallow errors so a slow close doesn't block siblings.\n const closers = [this.counter, this.kv, this.lock, this.pubsub];\n for (const c of closers) {\n try {\n await c.close();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[ClusterService] close error:', err);\n }\n }\n }\n}\n\n/**\n * Build an `IClusterService` from a `ClusterCapabilityConfig`. The only\n * driver shipped from this package is `memory`; other drivers (postgres,\n * redis, nats) live in dedicated packages and register themselves via\n * `registerClusterDriver()`.\n *\n * @example\n * const cluster = defineCluster({ driver: 'memory' });\n * await cluster.pubsub.publish('metadata.changed', { id: 'x' });\n */\nexport function defineCluster(\n config: ClusterCapabilityConfigInput = {},\n): IClusterService {\n const parsed = ClusterCapabilityConfigSchema.parse(config);\n const nodeId = parsed.nodeId ?? generateNodeId();\n\n if (parsed.driver === 'memory') {\n return new ComposedClusterService(\n nodeId,\n 'memory',\n new MemoryPubSub({ nodeId }),\n new MemoryLock({ defaultTtlMs: parsed.lockTtlMs }),\n new MemoryKV(),\n new MemoryCounter(),\n );\n }\n\n const factory = driverRegistry.get(parsed.driver);\n if (!factory) {\n throw new Error(\n `Cluster driver \"${parsed.driver}\" is not registered. ` +\n `Did you forget to import @objectstack/service-cluster-${parsed.driver} ` +\n `or call registerClusterDriver()? ` +\n `See content/docs/concepts/cluster-semantics.mdx §6.`,\n );\n }\n return factory({ ...parsed, nodeId });\n}\n\n// ---------------------------------------------------------------------------\n// Driver registry (for postgres/redis/nats/custom drivers)\n// ---------------------------------------------------------------------------\n\nexport interface DriverFactoryConfig {\n driver: string;\n nodeId: string;\n url?: string;\n useExistingPool?: boolean;\n heartbeatMs?: number;\n lockTtlMs?: number;\n tenantIsolation?: string;\n driverOptions?: Record<string, unknown>;\n}\n\nexport type ClusterDriverFactory = (config: DriverFactoryConfig) => IClusterService;\n\nconst driverRegistry = new Map<string, ClusterDriverFactory>();\n\n/**\n * Register a custom cluster driver. Driver packages (e.g.\n * `@objectstack/service-cluster-postgres`) should call this at module\n * load time so `defineCluster({ driver: 'postgres' })` resolves them.\n */\nexport function registerClusterDriver(\n name: string,\n factory: ClusterDriverFactory,\n): void {\n if (name === 'memory') {\n throw new Error('The \"memory\" driver is reserved.');\n }\n driverRegistry.set(name, factory);\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction generateNodeId(): string {\n // Avoid the `crypto` import dance for a single use; this is dev-only\n // randomness and the driver upgrades replace it.\n const rand = Math.random().toString(36).slice(2, 10);\n const ts = Date.now().toString(36);\n return `node-${ts}-${rand}`;\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type {\n IPubSub,\n PubSubHandler,\n PublishOptions,\n SubscribeOptions,\n Unsubscribe,\n} from '@objectstack/spec/contracts';\n\n/**\n * In-memory PubSub for single-process deployments and tests.\n *\n * Behavior:\n * - Synchronous fan-out: every subscriber's handler is invoked in the\n * same tick that `publish()` resolves. Handler errors are swallowed\n * and logged via `onError` (so one bad subscriber can't poison the bus).\n * - At-least-once semantics held vacuously (a single in-process delivery).\n * - No cross-process delivery — use the redis/postgres/nats driver for\n * real multi-node setups.\n */\nexport interface MemoryPubSubOptions {\n /** Optional error sink for handler exceptions. Defaults to console.error. */\n onError?: (err: unknown, channel: string) => void;\n /** Optional node id surfaced as `fromNode` on every message. */\n nodeId?: string;\n}\n\ninterface Subscription {\n channel: string;\n handler: PubSubHandler<unknown>;\n}\n\nexport class MemoryPubSub implements IPubSub {\n private readonly subs = new Map<string, Set<Subscription>>();\n private readonly onError: (err: unknown, channel: string) => void;\n private readonly nodeId?: string;\n private closed = false;\n\n constructor(opts: MemoryPubSubOptions = {}) {\n this.onError =\n opts.onError ??\n ((err, channel) => {\n // eslint-disable-next-line no-console\n console.error(`[MemoryPubSub] handler error on channel \"${channel}\":`, err);\n });\n this.nodeId = opts.nodeId;\n }\n\n async publish<T = unknown>(\n channel: string,\n payload: T,\n _opts?: PublishOptions,\n ): Promise<void> {\n if (this.closed) throw new Error('MemoryPubSub is closed');\n const bucket = this.subs.get(channel);\n if (!bucket || bucket.size === 0) return;\n const publishedAt = Date.now();\n // Snapshot so handler-driven unsubscribes during dispatch are safe.\n const snapshot = Array.from(bucket);\n for (const sub of snapshot) {\n try {\n const result = sub.handler({\n channel,\n payload,\n publishedAt,\n fromNode: this.nodeId,\n });\n if (result && typeof (result as Promise<void>).then === 'function') {\n (result as Promise<void>).catch((err) => this.onError(err, channel));\n }\n } catch (err) {\n this.onError(err, channel);\n }\n }\n }\n\n subscribe<T = unknown>(\n channel: string,\n handler: PubSubHandler<T>,\n _opts?: SubscribeOptions,\n ): Unsubscribe {\n if (this.closed) throw new Error('MemoryPubSub is closed');\n let bucket = this.subs.get(channel);\n if (!bucket) {\n bucket = new Set();\n this.subs.set(channel, bucket);\n }\n const sub: Subscription = { channel, handler: handler as PubSubHandler<unknown> };\n bucket.add(sub);\n let disposed = false;\n return () => {\n if (disposed) return;\n disposed = true;\n const b = this.subs.get(channel);\n if (!b) return;\n b.delete(sub);\n if (b.size === 0) this.subs.delete(channel);\n };\n }\n\n async close(): Promise<void> {\n this.closed = true;\n this.subs.clear();\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type {\n ILock,\n LockAcquireOptions,\n LockHandle,\n} from '@objectstack/spec/contracts';\n\n/**\n * In-memory lock for single-process deployments and tests.\n *\n * Behavior:\n * - Per-key FIFO wait queue (so `waitMs > 0` callers receive the lock\n * in arrival order).\n * - TTL is honored: if a holder doesn't renew before `ttlMs` elapses,\n * the lock is auto-released and the next waiter wakes.\n * - Fencing tokens are process-local monotonic bigints.\n */\n\nconst DEFAULT_TTL_MS = 15_000;\n\nexport interface MemoryLockOptions {\n /** Default TTL for `acquire` when caller doesn't supply one. */\n defaultTtlMs?: number;\n}\n\ninterface Holder {\n fencingToken: bigint;\n expiresAt: number;\n released: boolean;\n timer?: NodeJS.Timeout;\n}\n\ninterface Waiter {\n resolve: (h: LockHandle | null) => void;\n deadline: number;\n opts: LockAcquireOptions;\n timer?: NodeJS.Timeout;\n}\n\nexport class MemoryLock implements ILock {\n private readonly holders = new Map<string, Holder>();\n private readonly queues = new Map<string, Waiter[]>();\n private readonly defaultTtlMs: number;\n private fenceSeq = 0n;\n private closed = false;\n\n constructor(opts: MemoryLockOptions = {}) {\n this.defaultTtlMs = opts.defaultTtlMs ?? DEFAULT_TTL_MS;\n }\n\n async acquire(key: string, opts: LockAcquireOptions = {}): Promise<LockHandle | null> {\n if (this.closed) throw new Error('MemoryLock is closed');\n const ttlMs = opts.ttlMs ?? this.defaultTtlMs;\n const waitMs = opts.waitMs ?? 0;\n\n if (!this.holders.has(key)) {\n return this.grant(key, ttlMs);\n }\n if (waitMs <= 0) return null;\n\n return new Promise<LockHandle | null>((resolve) => {\n const deadline = Date.now() + waitMs;\n const waiter: Waiter = { resolve, deadline, opts };\n const queue = this.queues.get(key) ?? [];\n queue.push(waiter);\n this.queues.set(key, queue);\n waiter.timer = setTimeout(() => {\n const q = this.queues.get(key);\n if (q) {\n const idx = q.indexOf(waiter);\n if (idx >= 0) q.splice(idx, 1);\n }\n resolve(null);\n }, waitMs);\n });\n }\n\n async withLock<T>(\n key: string,\n fn: (h: LockHandle) => Promise<T>,\n opts?: LockAcquireOptions,\n ): Promise<T | null> {\n const handle = await this.acquire(key, opts);\n if (!handle) return null;\n try {\n return await fn(handle);\n } finally {\n await handle.release();\n }\n }\n\n async close(): Promise<void> {\n this.closed = true;\n for (const [, holder] of this.holders) {\n if (holder.timer) clearTimeout(holder.timer);\n holder.released = true;\n }\n this.holders.clear();\n for (const [, q] of this.queues) {\n for (const w of q) {\n if (w.timer) clearTimeout(w.timer);\n w.resolve(null);\n }\n }\n this.queues.clear();\n }\n\n private grant(key: string, ttlMs: number): LockHandle {\n const fencingToken = ++this.fenceSeq;\n const holder: Holder = {\n fencingToken,\n expiresAt: Date.now() + ttlMs,\n released: false,\n };\n holder.timer = setTimeout(() => this.expire(key, holder), ttlMs);\n this.holders.set(key, holder);\n\n const self = this;\n const handle: LockHandle = {\n key,\n fencingToken,\n isHeld: () => !holder.released && self.holders.get(key) === holder,\n async renew(extendMs?: number) {\n if (holder.released || self.holders.get(key) !== holder) {\n throw new Error(`Lock \"${key}\" no longer held (fence=${fencingToken})`);\n }\n const next = extendMs ?? ttlMs;\n holder.expiresAt = Date.now() + next;\n if (holder.timer) clearTimeout(holder.timer);\n holder.timer = setTimeout(() => self.expire(key, holder), next);\n },\n async release() {\n if (holder.released || self.holders.get(key) !== holder) return;\n holder.released = true;\n if (holder.timer) clearTimeout(holder.timer);\n self.holders.delete(key);\n self.handoff(key);\n },\n };\n return handle;\n }\n\n private expire(key: string, holder: Holder): void {\n if (holder.released) return;\n if (this.holders.get(key) !== holder) return;\n holder.released = true;\n this.holders.delete(key);\n this.handoff(key);\n }\n\n private handoff(key: string): void {\n const queue = this.queues.get(key);\n if (!queue || queue.length === 0) return;\n const next = queue.shift()!;\n if (next.timer) clearTimeout(next.timer);\n if (Date.now() > next.deadline) {\n next.resolve(null);\n this.handoff(key);\n return;\n }\n const ttlMs = next.opts.ttlMs ?? this.defaultTtlMs;\n next.resolve(this.grant(key, ttlMs));\n if (queue.length === 0) this.queues.delete(key);\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { IKV, KVEntry, KVSetOptions } from '@objectstack/spec/contracts';\n\ninterface Entry<T = unknown> {\n value: T;\n version: bigint;\n expiresAt?: number;\n timer?: NodeJS.Timeout;\n}\n\n/**\n * In-memory coordination KV. Supports optimistic concurrency via\n * `ifVersion` and TTL via `ttl` (seconds).\n *\n * NOT a cache, NOT a database — intended for small cluster bookkeeping.\n */\nexport class MemoryKV implements IKV {\n private readonly store = new Map<string, Entry>();\n private closed = false;\n\n async get<T = unknown>(key: string): Promise<KVEntry<T> | undefined> {\n const e = this.store.get(key);\n if (!e) return undefined;\n if (e.expiresAt && Date.now() >= e.expiresAt) {\n this.store.delete(key);\n return undefined;\n }\n return {\n key,\n value: e.value as T,\n version: e.version,\n expiresAt: e.expiresAt,\n };\n }\n\n async set<T = unknown>(\n key: string,\n value: T,\n opts: KVSetOptions = {},\n ): Promise<KVEntry<T>> {\n if (this.closed) throw new Error('MemoryKV is closed');\n const existing = this.store.get(key);\n const existingVersion = existing\n ? existing.expiresAt && Date.now() >= existing.expiresAt\n ? 0n\n : existing.version\n : 0n;\n if (opts.ifVersion !== undefined && opts.ifVersion !== existingVersion) {\n throw new VersionMismatchError(key, opts.ifVersion, existingVersion);\n }\n if (existing?.timer) clearTimeout(existing.timer);\n const version = existingVersion + 1n;\n const expiresAt = opts.ttl && opts.ttl > 0 ? Date.now() + opts.ttl * 1000 : undefined;\n const entry: Entry<T> = { value, version, expiresAt };\n if (expiresAt) {\n entry.timer = setTimeout(() => {\n const current = this.store.get(key);\n if (current === (entry as Entry<unknown>)) this.store.delete(key);\n }, expiresAt - Date.now());\n }\n this.store.set(key, entry as Entry<unknown>);\n return { key, value, version, expiresAt };\n }\n\n async delete(key: string, opts: { ifVersion?: bigint } = {}): Promise<boolean> {\n const e = this.store.get(key);\n if (!e) return false;\n if (e.expiresAt && Date.now() >= e.expiresAt) {\n this.store.delete(key);\n return false;\n }\n if (opts.ifVersion !== undefined && opts.ifVersion !== e.version) {\n throw new VersionMismatchError(key, opts.ifVersion, e.version);\n }\n if (e.timer) clearTimeout(e.timer);\n this.store.delete(key);\n return true;\n }\n\n async cas<T = unknown>(\n key: string,\n expectedVersion: bigint,\n next: T,\n opts: Omit<KVSetOptions, 'ifVersion'> = {},\n ): Promise<KVEntry<T> | undefined> {\n try {\n return await this.set(key, next, { ...opts, ifVersion: expectedVersion });\n } catch (err) {\n if (err instanceof VersionMismatchError) return undefined;\n throw err;\n }\n }\n\n async close(): Promise<void> {\n this.closed = true;\n for (const [, e] of this.store) {\n if (e.timer) clearTimeout(e.timer);\n }\n this.store.clear();\n }\n}\n\nexport class VersionMismatchError extends Error {\n constructor(\n public readonly key: string,\n public readonly expected: bigint,\n public readonly actual: bigint,\n ) {\n super(\n `KV version mismatch on \"${key}\": expected v${expected}, found v${actual}`,\n );\n this.name = 'VersionMismatchError';\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ICounter, CounterIncrOptions } from '@objectstack/spec/contracts';\n\n/**\n * In-memory monotonic counter. Single-process only — for cross-node id\n * allocation, use the postgres or redis driver.\n */\nexport class MemoryCounter implements ICounter {\n private readonly counters = new Map<string, bigint>();\n private closed = false;\n\n async incr(key: string, opts: CounterIncrOptions = {}): Promise<bigint> {\n if (this.closed) throw new Error('MemoryCounter is closed');\n const by = BigInt(opts.by ?? 1);\n const current = this.counters.get(key) ?? 0n;\n const next = current + by;\n this.counters.set(key, next);\n return next;\n }\n\n async peek(key: string): Promise<bigint> {\n return this.counters.get(key) ?? 0n;\n }\n\n async reset(key: string, value: bigint = 0n): Promise<void> {\n if (this.closed) throw new Error('MemoryCounter is closed');\n if (value === 0n) this.counters.delete(key);\n else this.counters.set(key, value);\n }\n\n async close(): Promise<void> {\n this.closed = true;\n this.counters.clear();\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Plugin, PluginContext } from '@objectstack/core';\nimport type { IClusterService } from '@objectstack/spec/contracts';\nimport type { ClusterCapabilityConfigInput } from '@objectstack/spec/kernel';\nimport { defineCluster } from './cluster.js';\n\n/**\n * Options for `ClusterServicePlugin`.\n *\n * Pass either a pre-built `cluster` instance (advanced — for tests or\n * custom drivers), or a `config` object that will be passed to\n * `defineCluster()`. If both are omitted, a memory-driver cluster is\n * created with auto-generated nodeId.\n */\nexport interface ClusterServicePluginOptions {\n /** Pre-built cluster service. Wins over `config` when both provided. */\n cluster?: IClusterService;\n /** Config forwarded to `defineCluster()` when `cluster` is absent. */\n config?: ClusterCapabilityConfigInput;\n}\n\n/**\n * Registers an `IClusterService` under the well-known service name\n * `'cluster'`. Plugins consume it via:\n *\n * ```ts\n * import type { IClusterService } from '@objectstack/spec/contracts';\n * const cluster = ctx.getService<IClusterService>('cluster');\n * await cluster.pubsub.publish('metadata.changed', payload);\n * ```\n *\n * The plugin closes the cluster on kernel shutdown.\n *\n * @example default memory driver\n * kernel.use(new ClusterServicePlugin());\n *\n * @example explicit config\n * kernel.use(new ClusterServicePlugin({ config: { driver: 'memory', nodeId: 'web-1' } }));\n */\nexport class ClusterServicePlugin implements Plugin {\n name = 'com.objectstack.service.cluster';\n version = '1.0.0';\n type = 'standard';\n\n private readonly options: ClusterServicePluginOptions;\n private cluster?: IClusterService;\n private owned = false;\n\n constructor(options: ClusterServicePluginOptions = {}) {\n this.options = options;\n }\n\n async init(ctx: PluginContext): Promise<void> {\n if (this.options.cluster) {\n this.cluster = this.options.cluster;\n this.owned = false;\n } else {\n this.cluster = defineCluster(this.options.config ?? {});\n this.owned = true;\n }\n ctx.registerService('cluster', this.cluster);\n ctx.logger.info(\n `ClusterServicePlugin: registered \"${this.cluster.driver}\" driver (node=${this.cluster.nodeId})`,\n );\n\n ctx.hook('kernel:shutdown', async () => {\n if (this.owned && this.cluster) {\n try {\n await this.cluster.close();\n } catch (err) {\n ctx.logger.error('ClusterServicePlugin: close error', err as Error);\n }\n }\n });\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Plugin, PluginContext } from '@objectstack/core';\nimport type { IClusterService } from '@objectstack/spec/contracts';\n\n/**\n * Bridges the cluster pub/sub bus to the metadata service so that\n * metadata mutations on one node invalidate registry caches on peer\n * nodes. Implements the \"first real consumer\" of the cluster API.\n *\n * Implementation detail: this plugin lives in `@objectstack/service-cluster`\n * (not in `@objectstack/metadata`) to avoid forcing every metadata\n * consumer to pull the cluster service. The metadata package only needs\n * the `IPubSub` interface, which lives in `@objectstack/spec/contracts`.\n *\n * Activates only when both services are present and the metadata service\n * exposes `attachClusterPubSub()`. Late binding is achieved via the\n * `kernel:ready` lifecycle hook.\n *\n * Channel: `metadata.changed` — payload shape defined by\n * `ClusterMetadataChangedPayload` in `@objectstack/metadata`.\n *\n * See `content/docs/concepts/cluster-semantics.mdx` §5.\n */\nexport class MetadataClusterBridgePlugin implements Plugin {\n name = 'com.objectstack.service.metadata-cluster-bridge';\n version = '1.0.0';\n type = 'standard';\n\n private detach?: () => void;\n\n async init(ctx: PluginContext): Promise<void> {\n ctx.hook('kernel:ready', async () => {\n let cluster: IClusterService | undefined;\n let md: unknown;\n try {\n cluster = ctx.getService<IClusterService>('cluster');\n } catch {\n ctx.logger.debug(\n 'MetadataClusterBridgePlugin: no \"cluster\" service registered, skipping',\n );\n return;\n }\n try {\n md = ctx.getService<unknown>('metadata');\n } catch {\n ctx.logger.debug(\n 'MetadataClusterBridgePlugin: no \"metadata\" service registered, skipping',\n );\n return;\n }\n\n const attach = (md as { attachClusterPubSub?: unknown })\n .attachClusterPubSub;\n if (typeof attach !== 'function') {\n ctx.logger.warn(\n 'MetadataClusterBridgePlugin: metadata service does not expose attachClusterPubSub(); cross-node cache invalidation disabled',\n );\n return;\n }\n\n try {\n this.detach = (attach as (\n pubsub: IClusterService['pubsub'],\n nodeId: string,\n ) => () => void).call(md, cluster.pubsub, cluster.nodeId);\n ctx.logger.info(\n `MetadataClusterBridgePlugin: bridged metadata.changed → cluster.pubsub (node=${cluster.nodeId})`,\n );\n } catch (err) {\n ctx.logger.error(\n 'MetadataClusterBridgePlugin: attach failed',\n err as Error,\n );\n }\n });\n\n ctx.hook('kernel:shutdown', async () => {\n try {\n this.detach?.();\n } catch (err) {\n ctx.logger.error(\n 'MetadataClusterBridgePlugin: detach error',\n err as Error,\n );\n }\n this.detach = undefined;\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/framework/framework/packages/services/service-cluster/dist/index.cjs","../src/cluster.ts","../src/memory/pubsub.ts","../src/memory/lock.ts","../src/memory/kv.ts","../src/memory/counter.ts","../src/split-brain-guard.ts","../src/cluster-service-plugin.ts","../src/metadata-cluster-bridge-plugin.ts"],"names":[],"mappings":"AAAA;ACUA,kDAA8C;ADR9C;AACA;AE8BO,IAAM,aAAA,EAAN,MAAsC;AAAA,EAMzC,WAAA,CAAY,KAAA,EAA4B,CAAC,CAAA,EAAG;AAL5C,IAAA,IAAA,CAAiB,KAAA,kBAAO,IAAI,GAAA,CAA+B,CAAA;AAG3D,IAAA,IAAA,CAAQ,OAAA,EAAS,KAAA;AAGb,IAAA,IAAA,CAAK,QAAA,mBACD,IAAA,CAAK,OAAA,UAAA,CACJ,CAAC,GAAA,EAAK,OAAA,EAAA,GAAY;AAEf,MAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,yCAAA,EAA4C,OAAO,CAAA,EAAA,CAAA,EAAM,GAAG,CAAA;AAAA,IAC9E,CAAA,GAAA;AACJ,IAAA,IAAA,CAAK,OAAA,EAAS,IAAA,CAAK,MAAA;AAAA,EACvB;AAAA,EAEA,MAAM,OAAA,CACF,OAAA,EACA,OAAA,EACA,KAAA,EACa;AACb,IAAA,GAAA,CAAI,IAAA,CAAK,MAAA,EAAQ,MAAM,IAAI,KAAA,CAAM,wBAAwB,CAAA;AACzD,IAAA,MAAM,OAAA,EAAS,IAAA,CAAK,IAAA,CAAK,GAAA,CAAI,OAAO,CAAA;AACpC,IAAA,GAAA,CAAI,CAAC,OAAA,GAAU,MAAA,CAAO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,MAAA;AACA,MAAA;AACI,QAAA;AAAmD,MAAA;AAEnD,QAAA;AAAW,UAAA;AACP,QAAA;AAEJ,QAAA;AAAA,MAAA;AAEJ,MAAA;AACI,QAAA;AAAuC,MAAA;AAEvC,QAAA;AAAW,UAAA;AACP,QAAA;AAEJ,QAAA;AAAA,MAAA;AAGJ,MAAA;AAEA,MAAA;AACI,QAAA;AAAW,UAAA;AACP,QAAA;AAEJ,QAAA;AAAA,MAAA;AAGJ,MAAA;AACI,QAAA;AAIA,QAAA;AAAW,UAAA;AACuF,QAAA;AAClG,MAAA;AAEA,QAAA;AAAW,UAAA;AACP,UAAA;AACA,QAAA;AACJ,MAAA;AACJ,IAAA;AAGJ,IAAA;AACI,MAAA;AACI,wBAAA;AAAc,MAAA;AAEd,QAAA;AAAW,UAAA;AACP,UAAA;AACA,QAAA;AACJ,MAAA;AAEJ,MAAA;AAAc,IAAA;AACjB,EAAA;AAET;AR0WA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/framework/framework/packages/services/service-cluster/dist/index.cjs","sourcesContent":[null,"// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type {\n IClusterService,\n IPubSub,\n ILock,\n IKV,\n ICounter,\n} from '@objectstack/spec/contracts';\nimport type { ClusterCapabilityConfigInput } from '@objectstack/spec/kernel';\nimport { ClusterCapabilityConfigSchema } from '@objectstack/spec/kernel';\n\nimport { MemoryPubSub } from './memory/pubsub.js';\nimport { MemoryLock } from './memory/lock.js';\nimport { MemoryKV } from './memory/kv.js';\nimport { MemoryCounter } from './memory/counter.js';\n\n/**\n * Compose four cluster primitives into a single `IClusterService` facade.\n * Useful for custom driver authors who want to mix and match.\n */\nexport class ComposedClusterService implements IClusterService {\n constructor(\n public readonly nodeId: string,\n public readonly driver: string,\n public readonly pubsub: IPubSub,\n public readonly lock: ILock,\n public readonly kv: IKV,\n public readonly counter: ICounter,\n ) { }\n\n async close(): Promise<void> {\n // Reverse order, swallow errors so a slow close doesn't block siblings.\n const closers = [this.counter, this.kv, this.lock, this.pubsub];\n for (const c of closers) {\n try {\n await c.close();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[ClusterService] close error:', err);\n }\n }\n }\n}\n\n/**\n * Build an `IClusterService` from a `ClusterCapabilityConfig`. The only\n * driver shipped from this package is `memory`; other drivers (postgres,\n * redis, nats) live in dedicated packages and register themselves via\n * `registerClusterDriver()`.\n *\n * @example\n * const cluster = defineCluster({ driver: 'memory' });\n * await cluster.pubsub.publish('metadata.changed', { id: 'x' });\n */\nexport function defineCluster(\n config: ClusterCapabilityConfigInput = {},\n): IClusterService {\n const parsed = ClusterCapabilityConfigSchema.parse(config);\n const nodeId = parsed.nodeId ?? generateNodeId();\n\n if (parsed.driver === 'memory') {\n return new ComposedClusterService(\n nodeId,\n 'memory',\n new MemoryPubSub({ nodeId }),\n new MemoryLock({ defaultTtlMs: parsed.lockTtlMs }),\n new MemoryKV(),\n new MemoryCounter(),\n );\n }\n\n const factory = driverRegistry.get(parsed.driver);\n if (!factory) {\n throw new Error(\n `Cluster driver \"${parsed.driver}\" is not registered. ` +\n `Did you forget to import @objectstack/service-cluster-${parsed.driver} ` +\n `or call registerClusterDriver()? ` +\n `See content/docs/concepts/cluster-semantics.mdx §6.`,\n );\n }\n return factory({ ...parsed, nodeId });\n}\n\n// ---------------------------------------------------------------------------\n// Driver registry (for postgres/redis/nats/custom drivers)\n// ---------------------------------------------------------------------------\n\nexport interface DriverFactoryConfig {\n driver: string;\n nodeId: string;\n url?: string;\n useExistingPool?: boolean;\n heartbeatMs?: number;\n lockTtlMs?: number;\n tenantIsolation?: string;\n driverOptions?: Record<string, unknown>;\n}\n\nexport type ClusterDriverFactory = (config: DriverFactoryConfig) => IClusterService;\n\nconst driverRegistry = new Map<string, ClusterDriverFactory>();\n\n/**\n * Register a custom cluster driver. Driver packages (e.g.\n * `@objectstack/service-cluster-postgres`) should call this at module\n * load time so `defineCluster({ driver: 'postgres' })` resolves them.\n */\nexport function registerClusterDriver(\n name: string,\n factory: ClusterDriverFactory,\n): void {\n if (name === 'memory') {\n throw new Error('The \"memory\" driver is reserved.');\n }\n driverRegistry.set(name, factory);\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction generateNodeId(): string {\n // Avoid the `crypto` import dance for a single use; this is dev-only\n // randomness and the driver upgrades replace it.\n const rand = Math.random().toString(36).slice(2, 10);\n const ts = Date.now().toString(36);\n return `node-${ts}-${rand}`;\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type {\n IPubSub,\n PubSubHandler,\n PublishOptions,\n SubscribeOptions,\n Unsubscribe,\n} from '@objectstack/spec/contracts';\n\n/**\n * In-memory PubSub for single-process deployments and tests.\n *\n * Behavior:\n * - Synchronous fan-out: every subscriber's handler is invoked in the\n * same tick that `publish()` resolves. Handler errors are swallowed\n * and logged via `onError` (so one bad subscriber can't poison the bus).\n * - At-least-once semantics held vacuously (a single in-process delivery).\n * - No cross-process delivery — use the redis/postgres/nats driver for\n * real multi-node setups.\n */\nexport interface MemoryPubSubOptions {\n /** Optional error sink for handler exceptions. Defaults to console.error. */\n onError?: (err: unknown, channel: string) => void;\n /** Optional node id surfaced as `fromNode` on every message. */\n nodeId?: string;\n}\n\ninterface Subscription {\n channel: string;\n handler: PubSubHandler<unknown>;\n}\n\nexport class MemoryPubSub implements IPubSub {\n private readonly subs = new Map<string, Set<Subscription>>();\n private readonly onError: (err: unknown, channel: string) => void;\n private readonly nodeId?: string;\n private closed = false;\n\n constructor(opts: MemoryPubSubOptions = {}) {\n this.onError =\n opts.onError ??\n ((err, channel) => {\n // eslint-disable-next-line no-console\n console.error(`[MemoryPubSub] handler error on channel \"${channel}\":`, err);\n });\n this.nodeId = opts.nodeId;\n }\n\n async publish<T = unknown>(\n channel: string,\n payload: T,\n _opts?: PublishOptions,\n ): Promise<void> {\n if (this.closed) throw new Error('MemoryPubSub is closed');\n const bucket = this.subs.get(channel);\n if (!bucket || bucket.size === 0) return;\n const publishedAt = Date.now();\n // Snapshot so handler-driven unsubscribes during dispatch are safe.\n const snapshot = Array.from(bucket);\n for (const sub of snapshot) {\n try {\n const result = sub.handler({\n channel,\n payload,\n publishedAt,\n fromNode: this.nodeId,\n });\n if (result && typeof (result as Promise<void>).then === 'function') {\n (result as Promise<void>).catch((err) => this.onError(err, channel));\n }\n } catch (err) {\n this.onError(err, channel);\n }\n }\n }\n\n subscribe<T = unknown>(\n channel: string,\n handler: PubSubHandler<T>,\n _opts?: SubscribeOptions,\n ): Unsubscribe {\n if (this.closed) throw new Error('MemoryPubSub is closed');\n let bucket = this.subs.get(channel);\n if (!bucket) {\n bucket = new Set();\n this.subs.set(channel, bucket);\n }\n const sub: Subscription = { channel, handler: handler as PubSubHandler<unknown> };\n bucket.add(sub);\n let disposed = false;\n return () => {\n if (disposed) return;\n disposed = true;\n const b = this.subs.get(channel);\n if (!b) return;\n b.delete(sub);\n if (b.size === 0) this.subs.delete(channel);\n };\n }\n\n async close(): Promise<void> {\n this.closed = true;\n this.subs.clear();\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type {\n ILock,\n LockAcquireOptions,\n LockHandle,\n} from '@objectstack/spec/contracts';\n\n/**\n * In-memory lock for single-process deployments and tests.\n *\n * Behavior:\n * - Per-key FIFO wait queue (so `waitMs > 0` callers receive the lock\n * in arrival order).\n * - TTL is honored: if a holder doesn't renew before `ttlMs` elapses,\n * the lock is auto-released and the next waiter wakes.\n * - Fencing tokens are process-local monotonic bigints.\n */\n\nconst DEFAULT_TTL_MS = 15_000;\n\nexport interface MemoryLockOptions {\n /** Default TTL for `acquire` when caller doesn't supply one. */\n defaultTtlMs?: number;\n}\n\ninterface Holder {\n fencingToken: bigint;\n expiresAt: number;\n released: boolean;\n timer?: NodeJS.Timeout;\n}\n\ninterface Waiter {\n resolve: (h: LockHandle | null) => void;\n deadline: number;\n opts: LockAcquireOptions;\n timer?: NodeJS.Timeout;\n}\n\nexport class MemoryLock implements ILock {\n private readonly holders = new Map<string, Holder>();\n private readonly queues = new Map<string, Waiter[]>();\n private readonly defaultTtlMs: number;\n private fenceSeq = 0n;\n private closed = false;\n\n constructor(opts: MemoryLockOptions = {}) {\n this.defaultTtlMs = opts.defaultTtlMs ?? DEFAULT_TTL_MS;\n }\n\n async acquire(key: string, opts: LockAcquireOptions = {}): Promise<LockHandle | null> {\n if (this.closed) throw new Error('MemoryLock is closed');\n const ttlMs = opts.ttlMs ?? this.defaultTtlMs;\n const waitMs = opts.waitMs ?? 0;\n\n if (!this.holders.has(key)) {\n return this.grant(key, ttlMs);\n }\n if (waitMs <= 0) return null;\n\n return new Promise<LockHandle | null>((resolve) => {\n const deadline = Date.now() + waitMs;\n const waiter: Waiter = { resolve, deadline, opts };\n const queue = this.queues.get(key) ?? [];\n queue.push(waiter);\n this.queues.set(key, queue);\n waiter.timer = setTimeout(() => {\n const q = this.queues.get(key);\n if (q) {\n const idx = q.indexOf(waiter);\n if (idx >= 0) q.splice(idx, 1);\n }\n resolve(null);\n }, waitMs);\n });\n }\n\n async withLock<T>(\n key: string,\n fn: (h: LockHandle) => Promise<T>,\n opts?: LockAcquireOptions,\n ): Promise<T | null> {\n const handle = await this.acquire(key, opts);\n if (!handle) return null;\n try {\n return await fn(handle);\n } finally {\n await handle.release();\n }\n }\n\n async close(): Promise<void> {\n this.closed = true;\n for (const [, holder] of this.holders) {\n if (holder.timer) clearTimeout(holder.timer);\n holder.released = true;\n }\n this.holders.clear();\n for (const [, q] of this.queues) {\n for (const w of q) {\n if (w.timer) clearTimeout(w.timer);\n w.resolve(null);\n }\n }\n this.queues.clear();\n }\n\n private grant(key: string, ttlMs: number): LockHandle {\n const fencingToken = ++this.fenceSeq;\n const holder: Holder = {\n fencingToken,\n expiresAt: Date.now() + ttlMs,\n released: false,\n };\n holder.timer = setTimeout(() => this.expire(key, holder), ttlMs);\n this.holders.set(key, holder);\n\n const self = this;\n const handle: LockHandle = {\n key,\n fencingToken,\n isHeld: () => !holder.released && self.holders.get(key) === holder,\n async renew(extendMs?: number) {\n if (holder.released || self.holders.get(key) !== holder) {\n throw new Error(`Lock \"${key}\" no longer held (fence=${fencingToken})`);\n }\n const next = extendMs ?? ttlMs;\n holder.expiresAt = Date.now() + next;\n if (holder.timer) clearTimeout(holder.timer);\n holder.timer = setTimeout(() => self.expire(key, holder), next);\n },\n async release() {\n if (holder.released || self.holders.get(key) !== holder) return;\n holder.released = true;\n if (holder.timer) clearTimeout(holder.timer);\n self.holders.delete(key);\n self.handoff(key);\n },\n };\n return handle;\n }\n\n private expire(key: string, holder: Holder): void {\n if (holder.released) return;\n if (this.holders.get(key) !== holder) return;\n holder.released = true;\n this.holders.delete(key);\n this.handoff(key);\n }\n\n private handoff(key: string): void {\n const queue = this.queues.get(key);\n if (!queue || queue.length === 0) return;\n const next = queue.shift()!;\n if (next.timer) clearTimeout(next.timer);\n if (Date.now() > next.deadline) {\n next.resolve(null);\n this.handoff(key);\n return;\n }\n const ttlMs = next.opts.ttlMs ?? this.defaultTtlMs;\n next.resolve(this.grant(key, ttlMs));\n if (queue.length === 0) this.queues.delete(key);\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { IKV, KVEntry, KVSetOptions } from '@objectstack/spec/contracts';\n\ninterface Entry<T = unknown> {\n value: T;\n version: bigint;\n expiresAt?: number;\n timer?: NodeJS.Timeout;\n}\n\n/**\n * In-memory coordination KV. Supports optimistic concurrency via\n * `ifVersion` and TTL via `ttl` (seconds).\n *\n * NOT a cache, NOT a database — intended for small cluster bookkeeping.\n */\nexport class MemoryKV implements IKV {\n private readonly store = new Map<string, Entry>();\n private closed = false;\n\n async get<T = unknown>(key: string): Promise<KVEntry<T> | undefined> {\n const e = this.store.get(key);\n if (!e) return undefined;\n if (e.expiresAt && Date.now() >= e.expiresAt) {\n this.store.delete(key);\n return undefined;\n }\n return {\n key,\n value: e.value as T,\n version: e.version,\n expiresAt: e.expiresAt,\n };\n }\n\n async set<T = unknown>(\n key: string,\n value: T,\n opts: KVSetOptions = {},\n ): Promise<KVEntry<T>> {\n if (this.closed) throw new Error('MemoryKV is closed');\n const existing = this.store.get(key);\n const existingVersion = existing\n ? existing.expiresAt && Date.now() >= existing.expiresAt\n ? 0n\n : existing.version\n : 0n;\n if (opts.ifVersion !== undefined && opts.ifVersion !== existingVersion) {\n throw new VersionMismatchError(key, opts.ifVersion, existingVersion);\n }\n if (existing?.timer) clearTimeout(existing.timer);\n const version = existingVersion + 1n;\n const expiresAt = opts.ttl && opts.ttl > 0 ? Date.now() + opts.ttl * 1000 : undefined;\n const entry: Entry<T> = { value, version, expiresAt };\n if (expiresAt) {\n entry.timer = setTimeout(() => {\n const current = this.store.get(key);\n if (current === (entry as Entry<unknown>)) this.store.delete(key);\n }, expiresAt - Date.now());\n }\n this.store.set(key, entry as Entry<unknown>);\n return { key, value, version, expiresAt };\n }\n\n async delete(key: string, opts: { ifVersion?: bigint } = {}): Promise<boolean> {\n const e = this.store.get(key);\n if (!e) return false;\n if (e.expiresAt && Date.now() >= e.expiresAt) {\n this.store.delete(key);\n return false;\n }\n if (opts.ifVersion !== undefined && opts.ifVersion !== e.version) {\n throw new VersionMismatchError(key, opts.ifVersion, e.version);\n }\n if (e.timer) clearTimeout(e.timer);\n this.store.delete(key);\n return true;\n }\n\n async cas<T = unknown>(\n key: string,\n expectedVersion: bigint,\n next: T,\n opts: Omit<KVSetOptions, 'ifVersion'> = {},\n ): Promise<KVEntry<T> | undefined> {\n try {\n return await this.set(key, next, { ...opts, ifVersion: expectedVersion });\n } catch (err) {\n if (err instanceof VersionMismatchError) return undefined;\n throw err;\n }\n }\n\n async close(): Promise<void> {\n this.closed = true;\n for (const [, e] of this.store) {\n if (e.timer) clearTimeout(e.timer);\n }\n this.store.clear();\n }\n}\n\nexport class VersionMismatchError extends Error {\n constructor(\n public readonly key: string,\n public readonly expected: bigint,\n public readonly actual: bigint,\n ) {\n super(\n `KV version mismatch on \"${key}\": expected v${expected}, found v${actual}`,\n );\n this.name = 'VersionMismatchError';\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ICounter, CounterIncrOptions } from '@objectstack/spec/contracts';\n\n/**\n * In-memory monotonic counter. Single-process only — for cross-node id\n * allocation, use the postgres or redis driver.\n */\nexport class MemoryCounter implements ICounter {\n private readonly counters = new Map<string, bigint>();\n private closed = false;\n\n async incr(key: string, opts: CounterIncrOptions = {}): Promise<bigint> {\n if (this.closed) throw new Error('MemoryCounter is closed');\n const by = BigInt(opts.by ?? 1);\n const current = this.counters.get(key) ?? 0n;\n const next = current + by;\n this.counters.set(key, next);\n return next;\n }\n\n async peek(key: string): Promise<bigint> {\n return this.counters.get(key) ?? 0n;\n }\n\n async reset(key: string, value: bigint = 0n): Promise<void> {\n if (this.closed) throw new Error('MemoryCounter is closed');\n if (value === 0n) this.counters.delete(key);\n else this.counters.set(key, value);\n }\n\n async close(): Promise<void> {\n this.closed = true;\n this.counters.clear();\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Split-brain guard (ADR-0010, path A).\n *\n * The `memory` cluster driver keeps PubSub/Lock/KV/Counter state **per\n * process**. On a single node that is correct; across multiple replicas\n * each process holds its own state, so:\n * - `ILock` is acquired locally by every replica -> no mutual exclusion;\n * - `ICounter`/`IKV` versions diverge per replica;\n * - `IPubSub` does not fan out across processes.\n *\n * This fails silently -- single-node tests and dev pass, only production\n * multi-replica corrupts. The guard turns that silent corruption into a\n * loud startup error when the operator has *declared* a multi-node\n * topology yet wired an in-process driver.\n *\n * Detection is deliberately conservative (path A): it keys off an\n * explicit operator declaration, not active peer discovery (that is the\n * optional path B in ADR-0010). It cannot know at boot whether the\n * cluster primitives are actually used cross-node, so it offers an\n * escape hatch for the rare \"replicas declared but primitives unused\"\n * case.\n */\n\n/** In-process drivers whose state does not coordinate across replicas. */\nconst IN_PROCESS_DRIVERS = new Set(['memory']);\n\n/** Environment inputs the guard reads. */\nexport interface SplitBrainGuardEnv {\n /** `'true'` -> operator declares a multi-node deployment. */\n OS_EXPECT_MULTI_NODE?: string;\n /** Replica count; `> 1` -> multi-node. */\n OS_CLUSTER_REPLICAS?: string;\n /** `'true'` -> bypass the guard (replicas declared but primitives unused cross-node). */\n OS_ALLOW_MEMORY_CLUSTER_MULTINODE?: string;\n}\n\nfunction isTrue(v: string | undefined): boolean {\n return String(v).trim().toLowerCase() === 'true';\n}\n\n/**\n * True when the operator has declared a multi-node topology via\n * `OS_EXPECT_MULTI_NODE=true` or `OS_CLUSTER_REPLICAS` greater than 1.\n */\nexport function declaresMultiNode(env: SplitBrainGuardEnv = process.env): boolean {\n if (isTrue(env.OS_EXPECT_MULTI_NODE)) return true;\n const replicas = Number(env.OS_CLUSTER_REPLICAS);\n return Number.isFinite(replicas) && replicas > 1;\n}\n\n/**\n * Throw if a multi-node topology is declared while the resolved cluster\n * `driver` is in-process (`memory`), unless explicitly allowed via\n * `OS_ALLOW_MEMORY_CLUSTER_MULTINODE=true`.\n *\n * Call this at startup *before* registering the cluster service so a\n * misconfiguration fails fast.\n */\nexport function assertClusterDriverSafeForTopology(\n driver: string,\n env: SplitBrainGuardEnv = process.env,\n): void {\n if (!declaresMultiNode(env)) return;\n if (!IN_PROCESS_DRIVERS.has(driver)) return;\n if (isTrue(env.OS_ALLOW_MEMORY_CLUSTER_MULTINODE)) return;\n\n throw new Error(\n `ClusterServicePlugin: multi-node deployment declared ` +\n `(OS_EXPECT_MULTI_NODE / OS_CLUSTER_REPLICAS>1) but the cluster driver is ` +\n `in-process \"${driver}\" -- its locks/counters/pub-sub do not coordinate across ` +\n `processes, so multiple replicas silently split-brain. Configure a remote cluster ` +\n `driver (e.g. @objectstack/service-cluster-redis) or a DB-backed driver. To override ` +\n `(replicas declared but cluster primitives unused cross-node), set ` +\n `OS_ALLOW_MEMORY_CLUSTER_MULTINODE=true. See cloud ADR-0010.`,\n );\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Plugin, PluginContext } from '@objectstack/core';\nimport type { IClusterService } from '@objectstack/spec/contracts';\nimport type { ClusterCapabilityConfigInput } from '@objectstack/spec/kernel';\nimport { defineCluster } from './cluster.js';\nimport { assertClusterDriverSafeForTopology } from './split-brain-guard.js';\n\n/**\n * Options for `ClusterServicePlugin`.\n *\n * Pass either a pre-built `cluster` instance (advanced — for tests or\n * custom drivers), or a `config` object that will be passed to\n * `defineCluster()`. If both are omitted, a memory-driver cluster is\n * created with auto-generated nodeId.\n */\nexport interface ClusterServicePluginOptions {\n /** Pre-built cluster service. Wins over `config` when both provided. */\n cluster?: IClusterService;\n /** Config forwarded to `defineCluster()` when `cluster` is absent. */\n config?: ClusterCapabilityConfigInput;\n}\n\n/**\n * Registers an `IClusterService` under the well-known service name\n * `'cluster'`. Plugins consume it via:\n *\n * ```ts\n * import type { IClusterService } from '@objectstack/spec/contracts';\n * const cluster = ctx.getService<IClusterService>('cluster');\n * await cluster.pubsub.publish('metadata.changed', payload);\n * ```\n *\n * The plugin closes the cluster on kernel shutdown.\n *\n * @example default memory driver\n * kernel.use(new ClusterServicePlugin());\n *\n * @example explicit config\n * kernel.use(new ClusterServicePlugin({ config: { driver: 'memory', nodeId: 'web-1' } }));\n */\nexport class ClusterServicePlugin implements Plugin {\n name = 'com.objectstack.service.cluster';\n version = '1.0.0';\n type = 'standard';\n\n private readonly options: ClusterServicePluginOptions;\n private cluster?: IClusterService;\n private owned = false;\n\n constructor(options: ClusterServicePluginOptions = {}) {\n this.options = options;\n }\n\n async init(ctx: PluginContext): Promise<void> {\n if (this.options.cluster) {\n this.cluster = this.options.cluster;\n this.owned = false;\n } else {\n this.cluster = defineCluster(this.options.config ?? {});\n this.owned = true;\n }\n // Split-brain guard (ADR-0010): fail fast if a multi-node topology is\n // declared but the resolved driver is in-process. Runs before\n // registration so a misconfiguration never half-wires the service.\n assertClusterDriverSafeForTopology(this.cluster.driver);\n\n ctx.registerService('cluster', this.cluster);\n ctx.logger.info(\n `ClusterServicePlugin: registered \"${this.cluster.driver}\" driver (node=${this.cluster.nodeId})`,\n );\n\n ctx.hook('kernel:shutdown', async () => {\n if (this.owned && this.cluster) {\n try {\n await this.cluster.close();\n } catch (err) {\n ctx.logger.error('ClusterServicePlugin: close error', err as Error);\n }\n }\n });\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Plugin, PluginContext } from '@objectstack/core';\nimport type { IClusterService } from '@objectstack/spec/contracts';\n\n/**\n * Bridges the cluster pub/sub bus to the metadata service so that\n * metadata mutations on one node invalidate registry caches on peer\n * nodes. Implements the \"first real consumer\" of the cluster API.\n *\n * Implementation detail: this plugin lives in `@objectstack/service-cluster`\n * (not in `@objectstack/metadata`) to avoid forcing every metadata\n * consumer to pull the cluster service. The metadata package only needs\n * the `IPubSub` interface, which lives in `@objectstack/spec/contracts`.\n *\n * Activates only when both services are present and the metadata service\n * exposes `attachClusterPubSub()`. Late binding is achieved via the\n * `kernel:ready` lifecycle hook.\n *\n * Channel: `metadata.changed` — payload shape defined by\n * `ClusterMetadataChangedPayload` in `@objectstack/metadata`.\n *\n * See `content/docs/concepts/cluster-semantics.mdx` §5.\n */\nexport class MetadataClusterBridgePlugin implements Plugin {\n name = 'com.objectstack.service.metadata-cluster-bridge';\n version = '1.0.0';\n type = 'standard';\n\n private detach?: () => void;\n\n async init(ctx: PluginContext): Promise<void> {\n ctx.hook('kernel:ready', async () => {\n let cluster: IClusterService | undefined;\n let md: unknown;\n try {\n cluster = ctx.getService<IClusterService>('cluster');\n } catch {\n ctx.logger.debug(\n 'MetadataClusterBridgePlugin: no \"cluster\" service registered, skipping',\n );\n return;\n }\n try {\n md = ctx.getService<unknown>('metadata');\n } catch {\n ctx.logger.debug(\n 'MetadataClusterBridgePlugin: no \"metadata\" service registered, skipping',\n );\n return;\n }\n\n const attach = (md as { attachClusterPubSub?: unknown })\n .attachClusterPubSub;\n if (typeof attach !== 'function') {\n ctx.logger.warn(\n 'MetadataClusterBridgePlugin: metadata service does not expose attachClusterPubSub(); cross-node cache invalidation disabled',\n );\n return;\n }\n\n try {\n this.detach = (attach as (\n pubsub: IClusterService['pubsub'],\n nodeId: string,\n ) => () => void).call(md, cluster.pubsub, cluster.nodeId);\n ctx.logger.info(\n `MetadataClusterBridgePlugin: bridged metadata.changed → cluster.pubsub (node=${cluster.nodeId})`,\n );\n } catch (err) {\n ctx.logger.error(\n 'MetadataClusterBridgePlugin: attach failed',\n err as Error,\n );\n }\n });\n\n ctx.hook('kernel:shutdown', async () => {\n try {\n this.detach?.();\n } catch (err) {\n ctx.logger.error(\n 'MetadataClusterBridgePlugin: detach error',\n err as Error,\n );\n }\n this.detach = undefined;\n });\n }\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -173,6 +173,30 @@ declare class ClusterServicePlugin implements Plugin {
|
|
|
173
173
|
init(ctx: PluginContext): Promise<void>;
|
|
174
174
|
}
|
|
175
175
|
|
|
176
|
+
/** Environment inputs the guard reads. */
|
|
177
|
+
interface SplitBrainGuardEnv {
|
|
178
|
+
/** `'true'` -> operator declares a multi-node deployment. */
|
|
179
|
+
OS_EXPECT_MULTI_NODE?: string;
|
|
180
|
+
/** Replica count; `> 1` -> multi-node. */
|
|
181
|
+
OS_CLUSTER_REPLICAS?: string;
|
|
182
|
+
/** `'true'` -> bypass the guard (replicas declared but primitives unused cross-node). */
|
|
183
|
+
OS_ALLOW_MEMORY_CLUSTER_MULTINODE?: string;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* True when the operator has declared a multi-node topology via
|
|
187
|
+
* `OS_EXPECT_MULTI_NODE=true` or `OS_CLUSTER_REPLICAS` greater than 1.
|
|
188
|
+
*/
|
|
189
|
+
declare function declaresMultiNode(env?: SplitBrainGuardEnv): boolean;
|
|
190
|
+
/**
|
|
191
|
+
* Throw if a multi-node topology is declared while the resolved cluster
|
|
192
|
+
* `driver` is in-process (`memory`), unless explicitly allowed via
|
|
193
|
+
* `OS_ALLOW_MEMORY_CLUSTER_MULTINODE=true`.
|
|
194
|
+
*
|
|
195
|
+
* Call this at startup *before* registering the cluster service so a
|
|
196
|
+
* misconfiguration fails fast.
|
|
197
|
+
*/
|
|
198
|
+
declare function assertClusterDriverSafeForTopology(driver: string, env?: SplitBrainGuardEnv): void;
|
|
199
|
+
|
|
176
200
|
/**
|
|
177
201
|
* Bridges the cluster pub/sub bus to the metadata service so that
|
|
178
202
|
* metadata mutations on one node invalidate registry caches on peer
|
|
@@ -200,4 +224,4 @@ declare class MetadataClusterBridgePlugin implements Plugin {
|
|
|
200
224
|
init(ctx: PluginContext): Promise<void>;
|
|
201
225
|
}
|
|
202
226
|
|
|
203
|
-
export { type ClusterDriverFactory, ClusterServicePlugin, type ClusterServicePluginOptions, ComposedClusterService, type DriverFactoryConfig, MemoryCounter, MemoryKV, MemoryLock, type MemoryLockOptions, MemoryPubSub, type MemoryPubSubOptions, MetadataClusterBridgePlugin, VersionMismatchError, defineCluster, registerClusterDriver };
|
|
227
|
+
export { type ClusterDriverFactory, ClusterServicePlugin, type ClusterServicePluginOptions, ComposedClusterService, type DriverFactoryConfig, MemoryCounter, MemoryKV, MemoryLock, type MemoryLockOptions, MemoryPubSub, type MemoryPubSubOptions, MetadataClusterBridgePlugin, type SplitBrainGuardEnv, VersionMismatchError, assertClusterDriverSafeForTopology, declaresMultiNode, defineCluster, registerClusterDriver };
|
package/dist/index.d.ts
CHANGED
|
@@ -173,6 +173,30 @@ declare class ClusterServicePlugin implements Plugin {
|
|
|
173
173
|
init(ctx: PluginContext): Promise<void>;
|
|
174
174
|
}
|
|
175
175
|
|
|
176
|
+
/** Environment inputs the guard reads. */
|
|
177
|
+
interface SplitBrainGuardEnv {
|
|
178
|
+
/** `'true'` -> operator declares a multi-node deployment. */
|
|
179
|
+
OS_EXPECT_MULTI_NODE?: string;
|
|
180
|
+
/** Replica count; `> 1` -> multi-node. */
|
|
181
|
+
OS_CLUSTER_REPLICAS?: string;
|
|
182
|
+
/** `'true'` -> bypass the guard (replicas declared but primitives unused cross-node). */
|
|
183
|
+
OS_ALLOW_MEMORY_CLUSTER_MULTINODE?: string;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* True when the operator has declared a multi-node topology via
|
|
187
|
+
* `OS_EXPECT_MULTI_NODE=true` or `OS_CLUSTER_REPLICAS` greater than 1.
|
|
188
|
+
*/
|
|
189
|
+
declare function declaresMultiNode(env?: SplitBrainGuardEnv): boolean;
|
|
190
|
+
/**
|
|
191
|
+
* Throw if a multi-node topology is declared while the resolved cluster
|
|
192
|
+
* `driver` is in-process (`memory`), unless explicitly allowed via
|
|
193
|
+
* `OS_ALLOW_MEMORY_CLUSTER_MULTINODE=true`.
|
|
194
|
+
*
|
|
195
|
+
* Call this at startup *before* registering the cluster service so a
|
|
196
|
+
* misconfiguration fails fast.
|
|
197
|
+
*/
|
|
198
|
+
declare function assertClusterDriverSafeForTopology(driver: string, env?: SplitBrainGuardEnv): void;
|
|
199
|
+
|
|
176
200
|
/**
|
|
177
201
|
* Bridges the cluster pub/sub bus to the metadata service so that
|
|
178
202
|
* metadata mutations on one node invalidate registry caches on peer
|
|
@@ -200,4 +224,4 @@ declare class MetadataClusterBridgePlugin implements Plugin {
|
|
|
200
224
|
init(ctx: PluginContext): Promise<void>;
|
|
201
225
|
}
|
|
202
226
|
|
|
203
|
-
export { type ClusterDriverFactory, ClusterServicePlugin, type ClusterServicePluginOptions, ComposedClusterService, type DriverFactoryConfig, MemoryCounter, MemoryKV, MemoryLock, type MemoryLockOptions, MemoryPubSub, type MemoryPubSubOptions, MetadataClusterBridgePlugin, VersionMismatchError, defineCluster, registerClusterDriver };
|
|
227
|
+
export { type ClusterDriverFactory, ClusterServicePlugin, type ClusterServicePluginOptions, ComposedClusterService, type DriverFactoryConfig, MemoryCounter, MemoryKV, MemoryLock, type MemoryLockOptions, MemoryPubSub, type MemoryPubSubOptions, MetadataClusterBridgePlugin, type SplitBrainGuardEnv, VersionMismatchError, assertClusterDriverSafeForTopology, declaresMultiNode, defineCluster, registerClusterDriver };
|
package/dist/index.js
CHANGED
|
@@ -337,6 +337,25 @@ function generateNodeId() {
|
|
|
337
337
|
return `node-${ts}-${rand}`;
|
|
338
338
|
}
|
|
339
339
|
|
|
340
|
+
// src/split-brain-guard.ts
|
|
341
|
+
var IN_PROCESS_DRIVERS = /* @__PURE__ */ new Set(["memory"]);
|
|
342
|
+
function isTrue(v) {
|
|
343
|
+
return String(v).trim().toLowerCase() === "true";
|
|
344
|
+
}
|
|
345
|
+
function declaresMultiNode(env = process.env) {
|
|
346
|
+
if (isTrue(env.OS_EXPECT_MULTI_NODE)) return true;
|
|
347
|
+
const replicas = Number(env.OS_CLUSTER_REPLICAS);
|
|
348
|
+
return Number.isFinite(replicas) && replicas > 1;
|
|
349
|
+
}
|
|
350
|
+
function assertClusterDriverSafeForTopology(driver, env = process.env) {
|
|
351
|
+
if (!declaresMultiNode(env)) return;
|
|
352
|
+
if (!IN_PROCESS_DRIVERS.has(driver)) return;
|
|
353
|
+
if (isTrue(env.OS_ALLOW_MEMORY_CLUSTER_MULTINODE)) return;
|
|
354
|
+
throw new Error(
|
|
355
|
+
`ClusterServicePlugin: multi-node deployment declared (OS_EXPECT_MULTI_NODE / OS_CLUSTER_REPLICAS>1) but the cluster driver is in-process "${driver}" -- its locks/counters/pub-sub do not coordinate across processes, so multiple replicas silently split-brain. Configure a remote cluster driver (e.g. @objectstack/service-cluster-redis) or a DB-backed driver. To override (replicas declared but cluster primitives unused cross-node), set OS_ALLOW_MEMORY_CLUSTER_MULTINODE=true. See cloud ADR-0010.`
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
|
|
340
359
|
// src/cluster-service-plugin.ts
|
|
341
360
|
var ClusterServicePlugin = class {
|
|
342
361
|
constructor(options = {}) {
|
|
@@ -354,6 +373,7 @@ var ClusterServicePlugin = class {
|
|
|
354
373
|
this.cluster = defineCluster(this.options.config ?? {});
|
|
355
374
|
this.owned = true;
|
|
356
375
|
}
|
|
376
|
+
assertClusterDriverSafeForTopology(this.cluster.driver);
|
|
357
377
|
ctx.registerService("cluster", this.cluster);
|
|
358
378
|
ctx.logger.info(
|
|
359
379
|
`ClusterServicePlugin: registered "${this.cluster.driver}" driver (node=${this.cluster.nodeId})`
|
|
@@ -438,6 +458,8 @@ export {
|
|
|
438
458
|
MemoryPubSub,
|
|
439
459
|
MetadataClusterBridgePlugin,
|
|
440
460
|
VersionMismatchError,
|
|
461
|
+
assertClusterDriverSafeForTopology,
|
|
462
|
+
declaresMultiNode,
|
|
441
463
|
defineCluster,
|
|
442
464
|
registerClusterDriver
|
|
443
465
|
};
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cluster.ts","../src/memory/pubsub.ts","../src/memory/lock.ts","../src/memory/kv.ts","../src/memory/counter.ts","../src/cluster-service-plugin.ts","../src/metadata-cluster-bridge-plugin.ts"],"sourcesContent":["// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type {\n IClusterService,\n IPubSub,\n ILock,\n IKV,\n ICounter,\n} from '@objectstack/spec/contracts';\nimport type { ClusterCapabilityConfigInput } from '@objectstack/spec/kernel';\nimport { ClusterCapabilityConfigSchema } from '@objectstack/spec/kernel';\n\nimport { MemoryPubSub } from './memory/pubsub.js';\nimport { MemoryLock } from './memory/lock.js';\nimport { MemoryKV } from './memory/kv.js';\nimport { MemoryCounter } from './memory/counter.js';\n\n/**\n * Compose four cluster primitives into a single `IClusterService` facade.\n * Useful for custom driver authors who want to mix and match.\n */\nexport class ComposedClusterService implements IClusterService {\n constructor(\n public readonly nodeId: string,\n public readonly driver: string,\n public readonly pubsub: IPubSub,\n public readonly lock: ILock,\n public readonly kv: IKV,\n public readonly counter: ICounter,\n ) { }\n\n async close(): Promise<void> {\n // Reverse order, swallow errors so a slow close doesn't block siblings.\n const closers = [this.counter, this.kv, this.lock, this.pubsub];\n for (const c of closers) {\n try {\n await c.close();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[ClusterService] close error:', err);\n }\n }\n }\n}\n\n/**\n * Build an `IClusterService` from a `ClusterCapabilityConfig`. The only\n * driver shipped from this package is `memory`; other drivers (postgres,\n * redis, nats) live in dedicated packages and register themselves via\n * `registerClusterDriver()`.\n *\n * @example\n * const cluster = defineCluster({ driver: 'memory' });\n * await cluster.pubsub.publish('metadata.changed', { id: 'x' });\n */\nexport function defineCluster(\n config: ClusterCapabilityConfigInput = {},\n): IClusterService {\n const parsed = ClusterCapabilityConfigSchema.parse(config);\n const nodeId = parsed.nodeId ?? generateNodeId();\n\n if (parsed.driver === 'memory') {\n return new ComposedClusterService(\n nodeId,\n 'memory',\n new MemoryPubSub({ nodeId }),\n new MemoryLock({ defaultTtlMs: parsed.lockTtlMs }),\n new MemoryKV(),\n new MemoryCounter(),\n );\n }\n\n const factory = driverRegistry.get(parsed.driver);\n if (!factory) {\n throw new Error(\n `Cluster driver \"${parsed.driver}\" is not registered. ` +\n `Did you forget to import @objectstack/service-cluster-${parsed.driver} ` +\n `or call registerClusterDriver()? ` +\n `See content/docs/concepts/cluster-semantics.mdx §6.`,\n );\n }\n return factory({ ...parsed, nodeId });\n}\n\n// ---------------------------------------------------------------------------\n// Driver registry (for postgres/redis/nats/custom drivers)\n// ---------------------------------------------------------------------------\n\nexport interface DriverFactoryConfig {\n driver: string;\n nodeId: string;\n url?: string;\n useExistingPool?: boolean;\n heartbeatMs?: number;\n lockTtlMs?: number;\n tenantIsolation?: string;\n driverOptions?: Record<string, unknown>;\n}\n\nexport type ClusterDriverFactory = (config: DriverFactoryConfig) => IClusterService;\n\nconst driverRegistry = new Map<string, ClusterDriverFactory>();\n\n/**\n * Register a custom cluster driver. Driver packages (e.g.\n * `@objectstack/service-cluster-postgres`) should call this at module\n * load time so `defineCluster({ driver: 'postgres' })` resolves them.\n */\nexport function registerClusterDriver(\n name: string,\n factory: ClusterDriverFactory,\n): void {\n if (name === 'memory') {\n throw new Error('The \"memory\" driver is reserved.');\n }\n driverRegistry.set(name, factory);\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction generateNodeId(): string {\n // Avoid the `crypto` import dance for a single use; this is dev-only\n // randomness and the driver upgrades replace it.\n const rand = Math.random().toString(36).slice(2, 10);\n const ts = Date.now().toString(36);\n return `node-${ts}-${rand}`;\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type {\n IPubSub,\n PubSubHandler,\n PublishOptions,\n SubscribeOptions,\n Unsubscribe,\n} from '@objectstack/spec/contracts';\n\n/**\n * In-memory PubSub for single-process deployments and tests.\n *\n * Behavior:\n * - Synchronous fan-out: every subscriber's handler is invoked in the\n * same tick that `publish()` resolves. Handler errors are swallowed\n * and logged via `onError` (so one bad subscriber can't poison the bus).\n * - At-least-once semantics held vacuously (a single in-process delivery).\n * - No cross-process delivery — use the redis/postgres/nats driver for\n * real multi-node setups.\n */\nexport interface MemoryPubSubOptions {\n /** Optional error sink for handler exceptions. Defaults to console.error. */\n onError?: (err: unknown, channel: string) => void;\n /** Optional node id surfaced as `fromNode` on every message. */\n nodeId?: string;\n}\n\ninterface Subscription {\n channel: string;\n handler: PubSubHandler<unknown>;\n}\n\nexport class MemoryPubSub implements IPubSub {\n private readonly subs = new Map<string, Set<Subscription>>();\n private readonly onError: (err: unknown, channel: string) => void;\n private readonly nodeId?: string;\n private closed = false;\n\n constructor(opts: MemoryPubSubOptions = {}) {\n this.onError =\n opts.onError ??\n ((err, channel) => {\n // eslint-disable-next-line no-console\n console.error(`[MemoryPubSub] handler error on channel \"${channel}\":`, err);\n });\n this.nodeId = opts.nodeId;\n }\n\n async publish<T = unknown>(\n channel: string,\n payload: T,\n _opts?: PublishOptions,\n ): Promise<void> {\n if (this.closed) throw new Error('MemoryPubSub is closed');\n const bucket = this.subs.get(channel);\n if (!bucket || bucket.size === 0) return;\n const publishedAt = Date.now();\n // Snapshot so handler-driven unsubscribes during dispatch are safe.\n const snapshot = Array.from(bucket);\n for (const sub of snapshot) {\n try {\n const result = sub.handler({\n channel,\n payload,\n publishedAt,\n fromNode: this.nodeId,\n });\n if (result && typeof (result as Promise<void>).then === 'function') {\n (result as Promise<void>).catch((err) => this.onError(err, channel));\n }\n } catch (err) {\n this.onError(err, channel);\n }\n }\n }\n\n subscribe<T = unknown>(\n channel: string,\n handler: PubSubHandler<T>,\n _opts?: SubscribeOptions,\n ): Unsubscribe {\n if (this.closed) throw new Error('MemoryPubSub is closed');\n let bucket = this.subs.get(channel);\n if (!bucket) {\n bucket = new Set();\n this.subs.set(channel, bucket);\n }\n const sub: Subscription = { channel, handler: handler as PubSubHandler<unknown> };\n bucket.add(sub);\n let disposed = false;\n return () => {\n if (disposed) return;\n disposed = true;\n const b = this.subs.get(channel);\n if (!b) return;\n b.delete(sub);\n if (b.size === 0) this.subs.delete(channel);\n };\n }\n\n async close(): Promise<void> {\n this.closed = true;\n this.subs.clear();\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type {\n ILock,\n LockAcquireOptions,\n LockHandle,\n} from '@objectstack/spec/contracts';\n\n/**\n * In-memory lock for single-process deployments and tests.\n *\n * Behavior:\n * - Per-key FIFO wait queue (so `waitMs > 0` callers receive the lock\n * in arrival order).\n * - TTL is honored: if a holder doesn't renew before `ttlMs` elapses,\n * the lock is auto-released and the next waiter wakes.\n * - Fencing tokens are process-local monotonic bigints.\n */\n\nconst DEFAULT_TTL_MS = 15_000;\n\nexport interface MemoryLockOptions {\n /** Default TTL for `acquire` when caller doesn't supply one. */\n defaultTtlMs?: number;\n}\n\ninterface Holder {\n fencingToken: bigint;\n expiresAt: number;\n released: boolean;\n timer?: NodeJS.Timeout;\n}\n\ninterface Waiter {\n resolve: (h: LockHandle | null) => void;\n deadline: number;\n opts: LockAcquireOptions;\n timer?: NodeJS.Timeout;\n}\n\nexport class MemoryLock implements ILock {\n private readonly holders = new Map<string, Holder>();\n private readonly queues = new Map<string, Waiter[]>();\n private readonly defaultTtlMs: number;\n private fenceSeq = 0n;\n private closed = false;\n\n constructor(opts: MemoryLockOptions = {}) {\n this.defaultTtlMs = opts.defaultTtlMs ?? DEFAULT_TTL_MS;\n }\n\n async acquire(key: string, opts: LockAcquireOptions = {}): Promise<LockHandle | null> {\n if (this.closed) throw new Error('MemoryLock is closed');\n const ttlMs = opts.ttlMs ?? this.defaultTtlMs;\n const waitMs = opts.waitMs ?? 0;\n\n if (!this.holders.has(key)) {\n return this.grant(key, ttlMs);\n }\n if (waitMs <= 0) return null;\n\n return new Promise<LockHandle | null>((resolve) => {\n const deadline = Date.now() + waitMs;\n const waiter: Waiter = { resolve, deadline, opts };\n const queue = this.queues.get(key) ?? [];\n queue.push(waiter);\n this.queues.set(key, queue);\n waiter.timer = setTimeout(() => {\n const q = this.queues.get(key);\n if (q) {\n const idx = q.indexOf(waiter);\n if (idx >= 0) q.splice(idx, 1);\n }\n resolve(null);\n }, waitMs);\n });\n }\n\n async withLock<T>(\n key: string,\n fn: (h: LockHandle) => Promise<T>,\n opts?: LockAcquireOptions,\n ): Promise<T | null> {\n const handle = await this.acquire(key, opts);\n if (!handle) return null;\n try {\n return await fn(handle);\n } finally {\n await handle.release();\n }\n }\n\n async close(): Promise<void> {\n this.closed = true;\n for (const [, holder] of this.holders) {\n if (holder.timer) clearTimeout(holder.timer);\n holder.released = true;\n }\n this.holders.clear();\n for (const [, q] of this.queues) {\n for (const w of q) {\n if (w.timer) clearTimeout(w.timer);\n w.resolve(null);\n }\n }\n this.queues.clear();\n }\n\n private grant(key: string, ttlMs: number): LockHandle {\n const fencingToken = ++this.fenceSeq;\n const holder: Holder = {\n fencingToken,\n expiresAt: Date.now() + ttlMs,\n released: false,\n };\n holder.timer = setTimeout(() => this.expire(key, holder), ttlMs);\n this.holders.set(key, holder);\n\n const self = this;\n const handle: LockHandle = {\n key,\n fencingToken,\n isHeld: () => !holder.released && self.holders.get(key) === holder,\n async renew(extendMs?: number) {\n if (holder.released || self.holders.get(key) !== holder) {\n throw new Error(`Lock \"${key}\" no longer held (fence=${fencingToken})`);\n }\n const next = extendMs ?? ttlMs;\n holder.expiresAt = Date.now() + next;\n if (holder.timer) clearTimeout(holder.timer);\n holder.timer = setTimeout(() => self.expire(key, holder), next);\n },\n async release() {\n if (holder.released || self.holders.get(key) !== holder) return;\n holder.released = true;\n if (holder.timer) clearTimeout(holder.timer);\n self.holders.delete(key);\n self.handoff(key);\n },\n };\n return handle;\n }\n\n private expire(key: string, holder: Holder): void {\n if (holder.released) return;\n if (this.holders.get(key) !== holder) return;\n holder.released = true;\n this.holders.delete(key);\n this.handoff(key);\n }\n\n private handoff(key: string): void {\n const queue = this.queues.get(key);\n if (!queue || queue.length === 0) return;\n const next = queue.shift()!;\n if (next.timer) clearTimeout(next.timer);\n if (Date.now() > next.deadline) {\n next.resolve(null);\n this.handoff(key);\n return;\n }\n const ttlMs = next.opts.ttlMs ?? this.defaultTtlMs;\n next.resolve(this.grant(key, ttlMs));\n if (queue.length === 0) this.queues.delete(key);\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { IKV, KVEntry, KVSetOptions } from '@objectstack/spec/contracts';\n\ninterface Entry<T = unknown> {\n value: T;\n version: bigint;\n expiresAt?: number;\n timer?: NodeJS.Timeout;\n}\n\n/**\n * In-memory coordination KV. Supports optimistic concurrency via\n * `ifVersion` and TTL via `ttl` (seconds).\n *\n * NOT a cache, NOT a database — intended for small cluster bookkeeping.\n */\nexport class MemoryKV implements IKV {\n private readonly store = new Map<string, Entry>();\n private closed = false;\n\n async get<T = unknown>(key: string): Promise<KVEntry<T> | undefined> {\n const e = this.store.get(key);\n if (!e) return undefined;\n if (e.expiresAt && Date.now() >= e.expiresAt) {\n this.store.delete(key);\n return undefined;\n }\n return {\n key,\n value: e.value as T,\n version: e.version,\n expiresAt: e.expiresAt,\n };\n }\n\n async set<T = unknown>(\n key: string,\n value: T,\n opts: KVSetOptions = {},\n ): Promise<KVEntry<T>> {\n if (this.closed) throw new Error('MemoryKV is closed');\n const existing = this.store.get(key);\n const existingVersion = existing\n ? existing.expiresAt && Date.now() >= existing.expiresAt\n ? 0n\n : existing.version\n : 0n;\n if (opts.ifVersion !== undefined && opts.ifVersion !== existingVersion) {\n throw new VersionMismatchError(key, opts.ifVersion, existingVersion);\n }\n if (existing?.timer) clearTimeout(existing.timer);\n const version = existingVersion + 1n;\n const expiresAt = opts.ttl && opts.ttl > 0 ? Date.now() + opts.ttl * 1000 : undefined;\n const entry: Entry<T> = { value, version, expiresAt };\n if (expiresAt) {\n entry.timer = setTimeout(() => {\n const current = this.store.get(key);\n if (current === (entry as Entry<unknown>)) this.store.delete(key);\n }, expiresAt - Date.now());\n }\n this.store.set(key, entry as Entry<unknown>);\n return { key, value, version, expiresAt };\n }\n\n async delete(key: string, opts: { ifVersion?: bigint } = {}): Promise<boolean> {\n const e = this.store.get(key);\n if (!e) return false;\n if (e.expiresAt && Date.now() >= e.expiresAt) {\n this.store.delete(key);\n return false;\n }\n if (opts.ifVersion !== undefined && opts.ifVersion !== e.version) {\n throw new VersionMismatchError(key, opts.ifVersion, e.version);\n }\n if (e.timer) clearTimeout(e.timer);\n this.store.delete(key);\n return true;\n }\n\n async cas<T = unknown>(\n key: string,\n expectedVersion: bigint,\n next: T,\n opts: Omit<KVSetOptions, 'ifVersion'> = {},\n ): Promise<KVEntry<T> | undefined> {\n try {\n return await this.set(key, next, { ...opts, ifVersion: expectedVersion });\n } catch (err) {\n if (err instanceof VersionMismatchError) return undefined;\n throw err;\n }\n }\n\n async close(): Promise<void> {\n this.closed = true;\n for (const [, e] of this.store) {\n if (e.timer) clearTimeout(e.timer);\n }\n this.store.clear();\n }\n}\n\nexport class VersionMismatchError extends Error {\n constructor(\n public readonly key: string,\n public readonly expected: bigint,\n public readonly actual: bigint,\n ) {\n super(\n `KV version mismatch on \"${key}\": expected v${expected}, found v${actual}`,\n );\n this.name = 'VersionMismatchError';\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ICounter, CounterIncrOptions } from '@objectstack/spec/contracts';\n\n/**\n * In-memory monotonic counter. Single-process only — for cross-node id\n * allocation, use the postgres or redis driver.\n */\nexport class MemoryCounter implements ICounter {\n private readonly counters = new Map<string, bigint>();\n private closed = false;\n\n async incr(key: string, opts: CounterIncrOptions = {}): Promise<bigint> {\n if (this.closed) throw new Error('MemoryCounter is closed');\n const by = BigInt(opts.by ?? 1);\n const current = this.counters.get(key) ?? 0n;\n const next = current + by;\n this.counters.set(key, next);\n return next;\n }\n\n async peek(key: string): Promise<bigint> {\n return this.counters.get(key) ?? 0n;\n }\n\n async reset(key: string, value: bigint = 0n): Promise<void> {\n if (this.closed) throw new Error('MemoryCounter is closed');\n if (value === 0n) this.counters.delete(key);\n else this.counters.set(key, value);\n }\n\n async close(): Promise<void> {\n this.closed = true;\n this.counters.clear();\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Plugin, PluginContext } from '@objectstack/core';\nimport type { IClusterService } from '@objectstack/spec/contracts';\nimport type { ClusterCapabilityConfigInput } from '@objectstack/spec/kernel';\nimport { defineCluster } from './cluster.js';\n\n/**\n * Options for `ClusterServicePlugin`.\n *\n * Pass either a pre-built `cluster` instance (advanced — for tests or\n * custom drivers), or a `config` object that will be passed to\n * `defineCluster()`. If both are omitted, a memory-driver cluster is\n * created with auto-generated nodeId.\n */\nexport interface ClusterServicePluginOptions {\n /** Pre-built cluster service. Wins over `config` when both provided. */\n cluster?: IClusterService;\n /** Config forwarded to `defineCluster()` when `cluster` is absent. */\n config?: ClusterCapabilityConfigInput;\n}\n\n/**\n * Registers an `IClusterService` under the well-known service name\n * `'cluster'`. Plugins consume it via:\n *\n * ```ts\n * import type { IClusterService } from '@objectstack/spec/contracts';\n * const cluster = ctx.getService<IClusterService>('cluster');\n * await cluster.pubsub.publish('metadata.changed', payload);\n * ```\n *\n * The plugin closes the cluster on kernel shutdown.\n *\n * @example default memory driver\n * kernel.use(new ClusterServicePlugin());\n *\n * @example explicit config\n * kernel.use(new ClusterServicePlugin({ config: { driver: 'memory', nodeId: 'web-1' } }));\n */\nexport class ClusterServicePlugin implements Plugin {\n name = 'com.objectstack.service.cluster';\n version = '1.0.0';\n type = 'standard';\n\n private readonly options: ClusterServicePluginOptions;\n private cluster?: IClusterService;\n private owned = false;\n\n constructor(options: ClusterServicePluginOptions = {}) {\n this.options = options;\n }\n\n async init(ctx: PluginContext): Promise<void> {\n if (this.options.cluster) {\n this.cluster = this.options.cluster;\n this.owned = false;\n } else {\n this.cluster = defineCluster(this.options.config ?? {});\n this.owned = true;\n }\n ctx.registerService('cluster', this.cluster);\n ctx.logger.info(\n `ClusterServicePlugin: registered \"${this.cluster.driver}\" driver (node=${this.cluster.nodeId})`,\n );\n\n ctx.hook('kernel:shutdown', async () => {\n if (this.owned && this.cluster) {\n try {\n await this.cluster.close();\n } catch (err) {\n ctx.logger.error('ClusterServicePlugin: close error', err as Error);\n }\n }\n });\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Plugin, PluginContext } from '@objectstack/core';\nimport type { IClusterService } from '@objectstack/spec/contracts';\n\n/**\n * Bridges the cluster pub/sub bus to the metadata service so that\n * metadata mutations on one node invalidate registry caches on peer\n * nodes. Implements the \"first real consumer\" of the cluster API.\n *\n * Implementation detail: this plugin lives in `@objectstack/service-cluster`\n * (not in `@objectstack/metadata`) to avoid forcing every metadata\n * consumer to pull the cluster service. The metadata package only needs\n * the `IPubSub` interface, which lives in `@objectstack/spec/contracts`.\n *\n * Activates only when both services are present and the metadata service\n * exposes `attachClusterPubSub()`. Late binding is achieved via the\n * `kernel:ready` lifecycle hook.\n *\n * Channel: `metadata.changed` — payload shape defined by\n * `ClusterMetadataChangedPayload` in `@objectstack/metadata`.\n *\n * See `content/docs/concepts/cluster-semantics.mdx` §5.\n */\nexport class MetadataClusterBridgePlugin implements Plugin {\n name = 'com.objectstack.service.metadata-cluster-bridge';\n version = '1.0.0';\n type = 'standard';\n\n private detach?: () => void;\n\n async init(ctx: PluginContext): Promise<void> {\n ctx.hook('kernel:ready', async () => {\n let cluster: IClusterService | undefined;\n let md: unknown;\n try {\n cluster = ctx.getService<IClusterService>('cluster');\n } catch {\n ctx.logger.debug(\n 'MetadataClusterBridgePlugin: no \"cluster\" service registered, skipping',\n );\n return;\n }\n try {\n md = ctx.getService<unknown>('metadata');\n } catch {\n ctx.logger.debug(\n 'MetadataClusterBridgePlugin: no \"metadata\" service registered, skipping',\n );\n return;\n }\n\n const attach = (md as { attachClusterPubSub?: unknown })\n .attachClusterPubSub;\n if (typeof attach !== 'function') {\n ctx.logger.warn(\n 'MetadataClusterBridgePlugin: metadata service does not expose attachClusterPubSub(); cross-node cache invalidation disabled',\n );\n return;\n }\n\n try {\n this.detach = (attach as (\n pubsub: IClusterService['pubsub'],\n nodeId: string,\n ) => () => void).call(md, cluster.pubsub, cluster.nodeId);\n ctx.logger.info(\n `MetadataClusterBridgePlugin: bridged metadata.changed → cluster.pubsub (node=${cluster.nodeId})`,\n );\n } catch (err) {\n ctx.logger.error(\n 'MetadataClusterBridgePlugin: attach failed',\n err as Error,\n );\n }\n });\n\n ctx.hook('kernel:shutdown', async () => {\n try {\n this.detach?.();\n } catch (err) {\n ctx.logger.error(\n 'MetadataClusterBridgePlugin: detach error',\n err as Error,\n );\n }\n this.detach = undefined;\n });\n }\n}\n"],"mappings":";AAUA,SAAS,qCAAqC;;;ACuBvC,IAAM,eAAN,MAAsC;AAAA,EAMzC,YAAY,OAA4B,CAAC,GAAG;AAL5C,SAAiB,OAAO,oBAAI,IAA+B;AAG3D,SAAQ,SAAS;AAGb,SAAK,UACD,KAAK,YACJ,CAAC,KAAK,YAAY;AAEf,cAAQ,MAAM,4CAA4C,OAAO,MAAM,GAAG;AAAA,IAC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A,kBAAU,IAAI,WAA4B,SAAS;AAAA,MACvD,QAAQ;AACJ,YAAI,OAAO;AAAA,UACP;AAAA,QACJ;AACA;AAAA,MACJ;AACA,UAAI;AACA,aAAK,IAAI,WAAoB,UAAU;AAAA,MAC3C,QAAQ;AACJ,YAAI,OAAO;AAAA,UACP;AAAA,QACJ;AACA;AAAA,MACJ;AAEA,YAAM,SAAU,GACX;AACL,UAAI,OAAO,WAAW,YAAY;AAC9B,YAAI,OAAO;AAAA,UACP;AAAA,QACJ;AACA;AAAA,MACJ;AAEA,UAAI;AACA,aAAK,SAAU,OAGE,KAAK,IAAI,QAAQ,QAAQ,QAAQ,MAAM;AACxD,YAAI,OAAO;AAAA,UACP,qFAAgF,QAAQ,MAAM;AAAA,QAClG;AAAA,MACJ,SAAS,KAAK;AACV,YAAI,OAAO;AAAA,UACP;AAAA,UACA;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ,CAAC;AAED,QAAI,KAAK,mBAAmB,YAAY;AACpC,UAAI;AACA,aAAK,SAAS;AAAA,MAClB,SAAS,KAAK;AACV,YAAI,OAAO;AAAA,UACP;AAAA,UACA;AAAA,QACJ;AAAA,MACJ;AACA,WAAK,SAAS;AAAA,IAClB,CAAC;AAAA,EACL;AACJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/cluster.ts","../src/memory/pubsub.ts","../src/memory/lock.ts","../src/memory/kv.ts","../src/memory/counter.ts","../src/split-brain-guard.ts","../src/cluster-service-plugin.ts","../src/metadata-cluster-bridge-plugin.ts"],"sourcesContent":["// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type {\n IClusterService,\n IPubSub,\n ILock,\n IKV,\n ICounter,\n} from '@objectstack/spec/contracts';\nimport type { ClusterCapabilityConfigInput } from '@objectstack/spec/kernel';\nimport { ClusterCapabilityConfigSchema } from '@objectstack/spec/kernel';\n\nimport { MemoryPubSub } from './memory/pubsub.js';\nimport { MemoryLock } from './memory/lock.js';\nimport { MemoryKV } from './memory/kv.js';\nimport { MemoryCounter } from './memory/counter.js';\n\n/**\n * Compose four cluster primitives into a single `IClusterService` facade.\n * Useful for custom driver authors who want to mix and match.\n */\nexport class ComposedClusterService implements IClusterService {\n constructor(\n public readonly nodeId: string,\n public readonly driver: string,\n public readonly pubsub: IPubSub,\n public readonly lock: ILock,\n public readonly kv: IKV,\n public readonly counter: ICounter,\n ) { }\n\n async close(): Promise<void> {\n // Reverse order, swallow errors so a slow close doesn't block siblings.\n const closers = [this.counter, this.kv, this.lock, this.pubsub];\n for (const c of closers) {\n try {\n await c.close();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[ClusterService] close error:', err);\n }\n }\n }\n}\n\n/**\n * Build an `IClusterService` from a `ClusterCapabilityConfig`. The only\n * driver shipped from this package is `memory`; other drivers (postgres,\n * redis, nats) live in dedicated packages and register themselves via\n * `registerClusterDriver()`.\n *\n * @example\n * const cluster = defineCluster({ driver: 'memory' });\n * await cluster.pubsub.publish('metadata.changed', { id: 'x' });\n */\nexport function defineCluster(\n config: ClusterCapabilityConfigInput = {},\n): IClusterService {\n const parsed = ClusterCapabilityConfigSchema.parse(config);\n const nodeId = parsed.nodeId ?? generateNodeId();\n\n if (parsed.driver === 'memory') {\n return new ComposedClusterService(\n nodeId,\n 'memory',\n new MemoryPubSub({ nodeId }),\n new MemoryLock({ defaultTtlMs: parsed.lockTtlMs }),\n new MemoryKV(),\n new MemoryCounter(),\n );\n }\n\n const factory = driverRegistry.get(parsed.driver);\n if (!factory) {\n throw new Error(\n `Cluster driver \"${parsed.driver}\" is not registered. ` +\n `Did you forget to import @objectstack/service-cluster-${parsed.driver} ` +\n `or call registerClusterDriver()? ` +\n `See content/docs/concepts/cluster-semantics.mdx §6.`,\n );\n }\n return factory({ ...parsed, nodeId });\n}\n\n// ---------------------------------------------------------------------------\n// Driver registry (for postgres/redis/nats/custom drivers)\n// ---------------------------------------------------------------------------\n\nexport interface DriverFactoryConfig {\n driver: string;\n nodeId: string;\n url?: string;\n useExistingPool?: boolean;\n heartbeatMs?: number;\n lockTtlMs?: number;\n tenantIsolation?: string;\n driverOptions?: Record<string, unknown>;\n}\n\nexport type ClusterDriverFactory = (config: DriverFactoryConfig) => IClusterService;\n\nconst driverRegistry = new Map<string, ClusterDriverFactory>();\n\n/**\n * Register a custom cluster driver. Driver packages (e.g.\n * `@objectstack/service-cluster-postgres`) should call this at module\n * load time so `defineCluster({ driver: 'postgres' })` resolves them.\n */\nexport function registerClusterDriver(\n name: string,\n factory: ClusterDriverFactory,\n): void {\n if (name === 'memory') {\n throw new Error('The \"memory\" driver is reserved.');\n }\n driverRegistry.set(name, factory);\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction generateNodeId(): string {\n // Avoid the `crypto` import dance for a single use; this is dev-only\n // randomness and the driver upgrades replace it.\n const rand = Math.random().toString(36).slice(2, 10);\n const ts = Date.now().toString(36);\n return `node-${ts}-${rand}`;\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type {\n IPubSub,\n PubSubHandler,\n PublishOptions,\n SubscribeOptions,\n Unsubscribe,\n} from '@objectstack/spec/contracts';\n\n/**\n * In-memory PubSub for single-process deployments and tests.\n *\n * Behavior:\n * - Synchronous fan-out: every subscriber's handler is invoked in the\n * same tick that `publish()` resolves. Handler errors are swallowed\n * and logged via `onError` (so one bad subscriber can't poison the bus).\n * - At-least-once semantics held vacuously (a single in-process delivery).\n * - No cross-process delivery — use the redis/postgres/nats driver for\n * real multi-node setups.\n */\nexport interface MemoryPubSubOptions {\n /** Optional error sink for handler exceptions. Defaults to console.error. */\n onError?: (err: unknown, channel: string) => void;\n /** Optional node id surfaced as `fromNode` on every message. */\n nodeId?: string;\n}\n\ninterface Subscription {\n channel: string;\n handler: PubSubHandler<unknown>;\n}\n\nexport class MemoryPubSub implements IPubSub {\n private readonly subs = new Map<string, Set<Subscription>>();\n private readonly onError: (err: unknown, channel: string) => void;\n private readonly nodeId?: string;\n private closed = false;\n\n constructor(opts: MemoryPubSubOptions = {}) {\n this.onError =\n opts.onError ??\n ((err, channel) => {\n // eslint-disable-next-line no-console\n console.error(`[MemoryPubSub] handler error on channel \"${channel}\":`, err);\n });\n this.nodeId = opts.nodeId;\n }\n\n async publish<T = unknown>(\n channel: string,\n payload: T,\n _opts?: PublishOptions,\n ): Promise<void> {\n if (this.closed) throw new Error('MemoryPubSub is closed');\n const bucket = this.subs.get(channel);\n if (!bucket || bucket.size === 0) return;\n const publishedAt = Date.now();\n // Snapshot so handler-driven unsubscribes during dispatch are safe.\n const snapshot = Array.from(bucket);\n for (const sub of snapshot) {\n try {\n const result = sub.handler({\n channel,\n payload,\n publishedAt,\n fromNode: this.nodeId,\n });\n if (result && typeof (result as Promise<void>).then === 'function') {\n (result as Promise<void>).catch((err) => this.onError(err, channel));\n }\n } catch (err) {\n this.onError(err, channel);\n }\n }\n }\n\n subscribe<T = unknown>(\n channel: string,\n handler: PubSubHandler<T>,\n _opts?: SubscribeOptions,\n ): Unsubscribe {\n if (this.closed) throw new Error('MemoryPubSub is closed');\n let bucket = this.subs.get(channel);\n if (!bucket) {\n bucket = new Set();\n this.subs.set(channel, bucket);\n }\n const sub: Subscription = { channel, handler: handler as PubSubHandler<unknown> };\n bucket.add(sub);\n let disposed = false;\n return () => {\n if (disposed) return;\n disposed = true;\n const b = this.subs.get(channel);\n if (!b) return;\n b.delete(sub);\n if (b.size === 0) this.subs.delete(channel);\n };\n }\n\n async close(): Promise<void> {\n this.closed = true;\n this.subs.clear();\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type {\n ILock,\n LockAcquireOptions,\n LockHandle,\n} from '@objectstack/spec/contracts';\n\n/**\n * In-memory lock for single-process deployments and tests.\n *\n * Behavior:\n * - Per-key FIFO wait queue (so `waitMs > 0` callers receive the lock\n * in arrival order).\n * - TTL is honored: if a holder doesn't renew before `ttlMs` elapses,\n * the lock is auto-released and the next waiter wakes.\n * - Fencing tokens are process-local monotonic bigints.\n */\n\nconst DEFAULT_TTL_MS = 15_000;\n\nexport interface MemoryLockOptions {\n /** Default TTL for `acquire` when caller doesn't supply one. */\n defaultTtlMs?: number;\n}\n\ninterface Holder {\n fencingToken: bigint;\n expiresAt: number;\n released: boolean;\n timer?: NodeJS.Timeout;\n}\n\ninterface Waiter {\n resolve: (h: LockHandle | null) => void;\n deadline: number;\n opts: LockAcquireOptions;\n timer?: NodeJS.Timeout;\n}\n\nexport class MemoryLock implements ILock {\n private readonly holders = new Map<string, Holder>();\n private readonly queues = new Map<string, Waiter[]>();\n private readonly defaultTtlMs: number;\n private fenceSeq = 0n;\n private closed = false;\n\n constructor(opts: MemoryLockOptions = {}) {\n this.defaultTtlMs = opts.defaultTtlMs ?? DEFAULT_TTL_MS;\n }\n\n async acquire(key: string, opts: LockAcquireOptions = {}): Promise<LockHandle | null> {\n if (this.closed) throw new Error('MemoryLock is closed');\n const ttlMs = opts.ttlMs ?? this.defaultTtlMs;\n const waitMs = opts.waitMs ?? 0;\n\n if (!this.holders.has(key)) {\n return this.grant(key, ttlMs);\n }\n if (waitMs <= 0) return null;\n\n return new Promise<LockHandle | null>((resolve) => {\n const deadline = Date.now() + waitMs;\n const waiter: Waiter = { resolve, deadline, opts };\n const queue = this.queues.get(key) ?? [];\n queue.push(waiter);\n this.queues.set(key, queue);\n waiter.timer = setTimeout(() => {\n const q = this.queues.get(key);\n if (q) {\n const idx = q.indexOf(waiter);\n if (idx >= 0) q.splice(idx, 1);\n }\n resolve(null);\n }, waitMs);\n });\n }\n\n async withLock<T>(\n key: string,\n fn: (h: LockHandle) => Promise<T>,\n opts?: LockAcquireOptions,\n ): Promise<T | null> {\n const handle = await this.acquire(key, opts);\n if (!handle) return null;\n try {\n return await fn(handle);\n } finally {\n await handle.release();\n }\n }\n\n async close(): Promise<void> {\n this.closed = true;\n for (const [, holder] of this.holders) {\n if (holder.timer) clearTimeout(holder.timer);\n holder.released = true;\n }\n this.holders.clear();\n for (const [, q] of this.queues) {\n for (const w of q) {\n if (w.timer) clearTimeout(w.timer);\n w.resolve(null);\n }\n }\n this.queues.clear();\n }\n\n private grant(key: string, ttlMs: number): LockHandle {\n const fencingToken = ++this.fenceSeq;\n const holder: Holder = {\n fencingToken,\n expiresAt: Date.now() + ttlMs,\n released: false,\n };\n holder.timer = setTimeout(() => this.expire(key, holder), ttlMs);\n this.holders.set(key, holder);\n\n const self = this;\n const handle: LockHandle = {\n key,\n fencingToken,\n isHeld: () => !holder.released && self.holders.get(key) === holder,\n async renew(extendMs?: number) {\n if (holder.released || self.holders.get(key) !== holder) {\n throw new Error(`Lock \"${key}\" no longer held (fence=${fencingToken})`);\n }\n const next = extendMs ?? ttlMs;\n holder.expiresAt = Date.now() + next;\n if (holder.timer) clearTimeout(holder.timer);\n holder.timer = setTimeout(() => self.expire(key, holder), next);\n },\n async release() {\n if (holder.released || self.holders.get(key) !== holder) return;\n holder.released = true;\n if (holder.timer) clearTimeout(holder.timer);\n self.holders.delete(key);\n self.handoff(key);\n },\n };\n return handle;\n }\n\n private expire(key: string, holder: Holder): void {\n if (holder.released) return;\n if (this.holders.get(key) !== holder) return;\n holder.released = true;\n this.holders.delete(key);\n this.handoff(key);\n }\n\n private handoff(key: string): void {\n const queue = this.queues.get(key);\n if (!queue || queue.length === 0) return;\n const next = queue.shift()!;\n if (next.timer) clearTimeout(next.timer);\n if (Date.now() > next.deadline) {\n next.resolve(null);\n this.handoff(key);\n return;\n }\n const ttlMs = next.opts.ttlMs ?? this.defaultTtlMs;\n next.resolve(this.grant(key, ttlMs));\n if (queue.length === 0) this.queues.delete(key);\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { IKV, KVEntry, KVSetOptions } from '@objectstack/spec/contracts';\n\ninterface Entry<T = unknown> {\n value: T;\n version: bigint;\n expiresAt?: number;\n timer?: NodeJS.Timeout;\n}\n\n/**\n * In-memory coordination KV. Supports optimistic concurrency via\n * `ifVersion` and TTL via `ttl` (seconds).\n *\n * NOT a cache, NOT a database — intended for small cluster bookkeeping.\n */\nexport class MemoryKV implements IKV {\n private readonly store = new Map<string, Entry>();\n private closed = false;\n\n async get<T = unknown>(key: string): Promise<KVEntry<T> | undefined> {\n const e = this.store.get(key);\n if (!e) return undefined;\n if (e.expiresAt && Date.now() >= e.expiresAt) {\n this.store.delete(key);\n return undefined;\n }\n return {\n key,\n value: e.value as T,\n version: e.version,\n expiresAt: e.expiresAt,\n };\n }\n\n async set<T = unknown>(\n key: string,\n value: T,\n opts: KVSetOptions = {},\n ): Promise<KVEntry<T>> {\n if (this.closed) throw new Error('MemoryKV is closed');\n const existing = this.store.get(key);\n const existingVersion = existing\n ? existing.expiresAt && Date.now() >= existing.expiresAt\n ? 0n\n : existing.version\n : 0n;\n if (opts.ifVersion !== undefined && opts.ifVersion !== existingVersion) {\n throw new VersionMismatchError(key, opts.ifVersion, existingVersion);\n }\n if (existing?.timer) clearTimeout(existing.timer);\n const version = existingVersion + 1n;\n const expiresAt = opts.ttl && opts.ttl > 0 ? Date.now() + opts.ttl * 1000 : undefined;\n const entry: Entry<T> = { value, version, expiresAt };\n if (expiresAt) {\n entry.timer = setTimeout(() => {\n const current = this.store.get(key);\n if (current === (entry as Entry<unknown>)) this.store.delete(key);\n }, expiresAt - Date.now());\n }\n this.store.set(key, entry as Entry<unknown>);\n return { key, value, version, expiresAt };\n }\n\n async delete(key: string, opts: { ifVersion?: bigint } = {}): Promise<boolean> {\n const e = this.store.get(key);\n if (!e) return false;\n if (e.expiresAt && Date.now() >= e.expiresAt) {\n this.store.delete(key);\n return false;\n }\n if (opts.ifVersion !== undefined && opts.ifVersion !== e.version) {\n throw new VersionMismatchError(key, opts.ifVersion, e.version);\n }\n if (e.timer) clearTimeout(e.timer);\n this.store.delete(key);\n return true;\n }\n\n async cas<T = unknown>(\n key: string,\n expectedVersion: bigint,\n next: T,\n opts: Omit<KVSetOptions, 'ifVersion'> = {},\n ): Promise<KVEntry<T> | undefined> {\n try {\n return await this.set(key, next, { ...opts, ifVersion: expectedVersion });\n } catch (err) {\n if (err instanceof VersionMismatchError) return undefined;\n throw err;\n }\n }\n\n async close(): Promise<void> {\n this.closed = true;\n for (const [, e] of this.store) {\n if (e.timer) clearTimeout(e.timer);\n }\n this.store.clear();\n }\n}\n\nexport class VersionMismatchError extends Error {\n constructor(\n public readonly key: string,\n public readonly expected: bigint,\n public readonly actual: bigint,\n ) {\n super(\n `KV version mismatch on \"${key}\": expected v${expected}, found v${actual}`,\n );\n this.name = 'VersionMismatchError';\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ICounter, CounterIncrOptions } from '@objectstack/spec/contracts';\n\n/**\n * In-memory monotonic counter. Single-process only — for cross-node id\n * allocation, use the postgres or redis driver.\n */\nexport class MemoryCounter implements ICounter {\n private readonly counters = new Map<string, bigint>();\n private closed = false;\n\n async incr(key: string, opts: CounterIncrOptions = {}): Promise<bigint> {\n if (this.closed) throw new Error('MemoryCounter is closed');\n const by = BigInt(opts.by ?? 1);\n const current = this.counters.get(key) ?? 0n;\n const next = current + by;\n this.counters.set(key, next);\n return next;\n }\n\n async peek(key: string): Promise<bigint> {\n return this.counters.get(key) ?? 0n;\n }\n\n async reset(key: string, value: bigint = 0n): Promise<void> {\n if (this.closed) throw new Error('MemoryCounter is closed');\n if (value === 0n) this.counters.delete(key);\n else this.counters.set(key, value);\n }\n\n async close(): Promise<void> {\n this.closed = true;\n this.counters.clear();\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Split-brain guard (ADR-0010, path A).\n *\n * The `memory` cluster driver keeps PubSub/Lock/KV/Counter state **per\n * process**. On a single node that is correct; across multiple replicas\n * each process holds its own state, so:\n * - `ILock` is acquired locally by every replica -> no mutual exclusion;\n * - `ICounter`/`IKV` versions diverge per replica;\n * - `IPubSub` does not fan out across processes.\n *\n * This fails silently -- single-node tests and dev pass, only production\n * multi-replica corrupts. The guard turns that silent corruption into a\n * loud startup error when the operator has *declared* a multi-node\n * topology yet wired an in-process driver.\n *\n * Detection is deliberately conservative (path A): it keys off an\n * explicit operator declaration, not active peer discovery (that is the\n * optional path B in ADR-0010). It cannot know at boot whether the\n * cluster primitives are actually used cross-node, so it offers an\n * escape hatch for the rare \"replicas declared but primitives unused\"\n * case.\n */\n\n/** In-process drivers whose state does not coordinate across replicas. */\nconst IN_PROCESS_DRIVERS = new Set(['memory']);\n\n/** Environment inputs the guard reads. */\nexport interface SplitBrainGuardEnv {\n /** `'true'` -> operator declares a multi-node deployment. */\n OS_EXPECT_MULTI_NODE?: string;\n /** Replica count; `> 1` -> multi-node. */\n OS_CLUSTER_REPLICAS?: string;\n /** `'true'` -> bypass the guard (replicas declared but primitives unused cross-node). */\n OS_ALLOW_MEMORY_CLUSTER_MULTINODE?: string;\n}\n\nfunction isTrue(v: string | undefined): boolean {\n return String(v).trim().toLowerCase() === 'true';\n}\n\n/**\n * True when the operator has declared a multi-node topology via\n * `OS_EXPECT_MULTI_NODE=true` or `OS_CLUSTER_REPLICAS` greater than 1.\n */\nexport function declaresMultiNode(env: SplitBrainGuardEnv = process.env): boolean {\n if (isTrue(env.OS_EXPECT_MULTI_NODE)) return true;\n const replicas = Number(env.OS_CLUSTER_REPLICAS);\n return Number.isFinite(replicas) && replicas > 1;\n}\n\n/**\n * Throw if a multi-node topology is declared while the resolved cluster\n * `driver` is in-process (`memory`), unless explicitly allowed via\n * `OS_ALLOW_MEMORY_CLUSTER_MULTINODE=true`.\n *\n * Call this at startup *before* registering the cluster service so a\n * misconfiguration fails fast.\n */\nexport function assertClusterDriverSafeForTopology(\n driver: string,\n env: SplitBrainGuardEnv = process.env,\n): void {\n if (!declaresMultiNode(env)) return;\n if (!IN_PROCESS_DRIVERS.has(driver)) return;\n if (isTrue(env.OS_ALLOW_MEMORY_CLUSTER_MULTINODE)) return;\n\n throw new Error(\n `ClusterServicePlugin: multi-node deployment declared ` +\n `(OS_EXPECT_MULTI_NODE / OS_CLUSTER_REPLICAS>1) but the cluster driver is ` +\n `in-process \"${driver}\" -- its locks/counters/pub-sub do not coordinate across ` +\n `processes, so multiple replicas silently split-brain. Configure a remote cluster ` +\n `driver (e.g. @objectstack/service-cluster-redis) or a DB-backed driver. To override ` +\n `(replicas declared but cluster primitives unused cross-node), set ` +\n `OS_ALLOW_MEMORY_CLUSTER_MULTINODE=true. See cloud ADR-0010.`,\n );\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Plugin, PluginContext } from '@objectstack/core';\nimport type { IClusterService } from '@objectstack/spec/contracts';\nimport type { ClusterCapabilityConfigInput } from '@objectstack/spec/kernel';\nimport { defineCluster } from './cluster.js';\nimport { assertClusterDriverSafeForTopology } from './split-brain-guard.js';\n\n/**\n * Options for `ClusterServicePlugin`.\n *\n * Pass either a pre-built `cluster` instance (advanced — for tests or\n * custom drivers), or a `config` object that will be passed to\n * `defineCluster()`. If both are omitted, a memory-driver cluster is\n * created with auto-generated nodeId.\n */\nexport interface ClusterServicePluginOptions {\n /** Pre-built cluster service. Wins over `config` when both provided. */\n cluster?: IClusterService;\n /** Config forwarded to `defineCluster()` when `cluster` is absent. */\n config?: ClusterCapabilityConfigInput;\n}\n\n/**\n * Registers an `IClusterService` under the well-known service name\n * `'cluster'`. Plugins consume it via:\n *\n * ```ts\n * import type { IClusterService } from '@objectstack/spec/contracts';\n * const cluster = ctx.getService<IClusterService>('cluster');\n * await cluster.pubsub.publish('metadata.changed', payload);\n * ```\n *\n * The plugin closes the cluster on kernel shutdown.\n *\n * @example default memory driver\n * kernel.use(new ClusterServicePlugin());\n *\n * @example explicit config\n * kernel.use(new ClusterServicePlugin({ config: { driver: 'memory', nodeId: 'web-1' } }));\n */\nexport class ClusterServicePlugin implements Plugin {\n name = 'com.objectstack.service.cluster';\n version = '1.0.0';\n type = 'standard';\n\n private readonly options: ClusterServicePluginOptions;\n private cluster?: IClusterService;\n private owned = false;\n\n constructor(options: ClusterServicePluginOptions = {}) {\n this.options = options;\n }\n\n async init(ctx: PluginContext): Promise<void> {\n if (this.options.cluster) {\n this.cluster = this.options.cluster;\n this.owned = false;\n } else {\n this.cluster = defineCluster(this.options.config ?? {});\n this.owned = true;\n }\n // Split-brain guard (ADR-0010): fail fast if a multi-node topology is\n // declared but the resolved driver is in-process. Runs before\n // registration so a misconfiguration never half-wires the service.\n assertClusterDriverSafeForTopology(this.cluster.driver);\n\n ctx.registerService('cluster', this.cluster);\n ctx.logger.info(\n `ClusterServicePlugin: registered \"${this.cluster.driver}\" driver (node=${this.cluster.nodeId})`,\n );\n\n ctx.hook('kernel:shutdown', async () => {\n if (this.owned && this.cluster) {\n try {\n await this.cluster.close();\n } catch (err) {\n ctx.logger.error('ClusterServicePlugin: close error', err as Error);\n }\n }\n });\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Plugin, PluginContext } from '@objectstack/core';\nimport type { IClusterService } from '@objectstack/spec/contracts';\n\n/**\n * Bridges the cluster pub/sub bus to the metadata service so that\n * metadata mutations on one node invalidate registry caches on peer\n * nodes. Implements the \"first real consumer\" of the cluster API.\n *\n * Implementation detail: this plugin lives in `@objectstack/service-cluster`\n * (not in `@objectstack/metadata`) to avoid forcing every metadata\n * consumer to pull the cluster service. The metadata package only needs\n * the `IPubSub` interface, which lives in `@objectstack/spec/contracts`.\n *\n * Activates only when both services are present and the metadata service\n * exposes `attachClusterPubSub()`. Late binding is achieved via the\n * `kernel:ready` lifecycle hook.\n *\n * Channel: `metadata.changed` — payload shape defined by\n * `ClusterMetadataChangedPayload` in `@objectstack/metadata`.\n *\n * See `content/docs/concepts/cluster-semantics.mdx` §5.\n */\nexport class MetadataClusterBridgePlugin implements Plugin {\n name = 'com.objectstack.service.metadata-cluster-bridge';\n version = '1.0.0';\n type = 'standard';\n\n private detach?: () => void;\n\n async init(ctx: PluginContext): Promise<void> {\n ctx.hook('kernel:ready', async () => {\n let cluster: IClusterService | undefined;\n let md: unknown;\n try {\n cluster = ctx.getService<IClusterService>('cluster');\n } catch {\n ctx.logger.debug(\n 'MetadataClusterBridgePlugin: no \"cluster\" service registered, skipping',\n );\n return;\n }\n try {\n md = ctx.getService<unknown>('metadata');\n } catch {\n ctx.logger.debug(\n 'MetadataClusterBridgePlugin: no \"metadata\" service registered, skipping',\n );\n return;\n }\n\n const attach = (md as { attachClusterPubSub?: unknown })\n .attachClusterPubSub;\n if (typeof attach !== 'function') {\n ctx.logger.warn(\n 'MetadataClusterBridgePlugin: metadata service does not expose attachClusterPubSub(); cross-node cache invalidation disabled',\n );\n return;\n }\n\n try {\n this.detach = (attach as (\n pubsub: IClusterService['pubsub'],\n nodeId: string,\n ) => () => void).call(md, cluster.pubsub, cluster.nodeId);\n ctx.logger.info(\n `MetadataClusterBridgePlugin: bridged metadata.changed → cluster.pubsub (node=${cluster.nodeId})`,\n );\n } catch (err) {\n ctx.logger.error(\n 'MetadataClusterBridgePlugin: attach failed',\n err as Error,\n );\n }\n });\n\n ctx.hook('kernel:shutdown', async () => {\n try {\n this.detach?.();\n } catch (err) {\n ctx.logger.error(\n 'MetadataClusterBridgePlugin: detach error',\n err as Error,\n );\n }\n this.detach = undefined;\n });\n }\n}\n"],"mappings":";AAUA,SAAS,qCAAqC;;;ACuBvC,IAAM,eAAN,MAAsC;AAAA,EAMzC,YAAY,OAA4B,CAAC,GAAG;AAL5C,SAAiB,OAAO,oBAAI,IAA+B;AAG3D,SAAQ,SAAS;AAGb,SAAK,UACD,KAAK,YACJ,CAAC,KAAK,YAAY;AAEf,cAAQ,MAAM,4CAA4C,OAAO,MAAM,GAAG;AAAA,IAC9E;AACJ,SAAK,SAAS,KAAK;AAAA,EACvB;AAAA,EAEA,MAAM,QACF,SACA,SACA,OACa;AACb,QAAI,KAAK,OAAQ,OAAM,IAAI,MAAM,wBAAwB;AACzD,UAAM,SAAS,KAAK,KAAK,IAAI,OAAO;AACpC,QAAI,CAAC,UAAU,OAAO,SA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
2
2
|
"name": "@objectstack/service-cluster",
|
|
3
|
-
"version": "9.
|
|
3
|
+
"version": "9.5.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"description": "Cluster Service for ObjectStack — pluggable PubSub/Lock/KV/Counter primitives. Memory driver included; postgres/redis drivers ship separately.",
|
|
6
6
|
"type": "module",
|
|
@@ -19,8 +19,8 @@
|
|
|
19
19
|
}
|
|
20
20
|
},
|
|
21
21
|
"dependencies": {
|
|
22
|
-
"@objectstack/core": "9.
|
|
23
|
-
"@objectstack/spec": "9.
|
|
22
|
+
"@objectstack/core": "9.5.0",
|
|
23
|
+
"@objectstack/spec": "9.5.0"
|
|
24
24
|
},
|
|
25
25
|
"devDependencies": {
|
|
26
26
|
"@types/node": "^25.9.2",
|
|
@@ -4,6 +4,7 @@ import type { Plugin, PluginContext } from '@objectstack/core';
|
|
|
4
4
|
import type { IClusterService } from '@objectstack/spec/contracts';
|
|
5
5
|
import type { ClusterCapabilityConfigInput } from '@objectstack/spec/kernel';
|
|
6
6
|
import { defineCluster } from './cluster.js';
|
|
7
|
+
import { assertClusterDriverSafeForTopology } from './split-brain-guard.js';
|
|
7
8
|
|
|
8
9
|
/**
|
|
9
10
|
* Options for `ClusterServicePlugin`.
|
|
@@ -59,6 +60,11 @@ export class ClusterServicePlugin implements Plugin {
|
|
|
59
60
|
this.cluster = defineCluster(this.options.config ?? {});
|
|
60
61
|
this.owned = true;
|
|
61
62
|
}
|
|
63
|
+
// Split-brain guard (ADR-0010): fail fast if a multi-node topology is
|
|
64
|
+
// declared but the resolved driver is in-process. Runs before
|
|
65
|
+
// registration so a misconfiguration never half-wires the service.
|
|
66
|
+
assertClusterDriverSafeForTopology(this.cluster.driver);
|
|
67
|
+
|
|
62
68
|
ctx.registerService('cluster', this.cluster);
|
|
63
69
|
ctx.logger.info(
|
|
64
70
|
`ClusterServicePlugin: registered "${this.cluster.driver}" driver (node=${this.cluster.nodeId})`,
|
package/src/index.ts
CHANGED
|
@@ -4,9 +4,19 @@
|
|
|
4
4
|
* @objectstack/service-cluster
|
|
5
5
|
*
|
|
6
6
|
* Pluggable cluster primitives (PubSub / Lock / KV / Counter) for
|
|
7
|
-
* ObjectStack. The default `memory` driver is exported here
|
|
8
|
-
*
|
|
9
|
-
*
|
|
7
|
+
* ObjectStack. The default `memory` driver is exported here and is the
|
|
8
|
+
* only driver needed for single-process runtimes.
|
|
9
|
+
*
|
|
10
|
+
* A remote driver is required only when running multiple processes that
|
|
11
|
+
* must share these primitives. Remote drivers ship as sibling packages
|
|
12
|
+
* and register via `registerClusterDriver()`; `@objectstack/service-cluster-redis`
|
|
13
|
+
* is the reference remote driver. (Postgres/NATS drivers are not built —
|
|
14
|
+
* add one on demand against the same SPI.)
|
|
15
|
+
*
|
|
16
|
+
* NOTE: the `memory` driver is per-process. Running multiple replicas on
|
|
17
|
+
* the memory driver silently splits state (each process holds its own
|
|
18
|
+
* locks/counters; pub/sub does not fan out across processes). Use a
|
|
19
|
+
* remote driver for any multi-replica deployment.
|
|
10
20
|
*
|
|
11
21
|
* See `content/docs/concepts/cluster-semantics.mdx` for the protocol.
|
|
12
22
|
*/
|
|
@@ -29,6 +39,12 @@ export {
|
|
|
29
39
|
type ClusterServicePluginOptions,
|
|
30
40
|
} from './cluster-service-plugin.js';
|
|
31
41
|
|
|
42
|
+
export {
|
|
43
|
+
assertClusterDriverSafeForTopology,
|
|
44
|
+
declaresMultiNode,
|
|
45
|
+
type SplitBrainGuardEnv,
|
|
46
|
+
} from './split-brain-guard.js';
|
|
47
|
+
|
|
32
48
|
export { MetadataClusterBridgePlugin } from './metadata-cluster-bridge-plugin.js';
|
|
33
49
|
|
|
34
50
|
// Re-export contracts for convenience.
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
import { describe, it, expect } from 'vitest';
|
|
4
|
+
import {
|
|
5
|
+
declaresMultiNode,
|
|
6
|
+
assertClusterDriverSafeForTopology,
|
|
7
|
+
} from './split-brain-guard.js';
|
|
8
|
+
|
|
9
|
+
describe('declaresMultiNode', () => {
|
|
10
|
+
it('false when nothing declared', () => {
|
|
11
|
+
expect(declaresMultiNode({})).toBe(false);
|
|
12
|
+
});
|
|
13
|
+
it('true for OS_EXPECT_MULTI_NODE=true (case-insensitive, trimmed)', () => {
|
|
14
|
+
expect(declaresMultiNode({ OS_EXPECT_MULTI_NODE: 'true' })).toBe(true);
|
|
15
|
+
expect(declaresMultiNode({ OS_EXPECT_MULTI_NODE: ' TRUE ' })).toBe(true);
|
|
16
|
+
});
|
|
17
|
+
it('false for OS_EXPECT_MULTI_NODE=false / other', () => {
|
|
18
|
+
expect(declaresMultiNode({ OS_EXPECT_MULTI_NODE: 'false' })).toBe(false);
|
|
19
|
+
expect(declaresMultiNode({ OS_EXPECT_MULTI_NODE: '1' })).toBe(false);
|
|
20
|
+
});
|
|
21
|
+
it('replicas: >1 true, <=1 false, non-numeric false', () => {
|
|
22
|
+
expect(declaresMultiNode({ OS_CLUSTER_REPLICAS: '3' })).toBe(true);
|
|
23
|
+
expect(declaresMultiNode({ OS_CLUSTER_REPLICAS: '1' })).toBe(false);
|
|
24
|
+
expect(declaresMultiNode({ OS_CLUSTER_REPLICAS: '0' })).toBe(false);
|
|
25
|
+
expect(declaresMultiNode({ OS_CLUSTER_REPLICAS: 'abc' })).toBe(false);
|
|
26
|
+
});
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
describe('assertClusterDriverSafeForTopology', () => {
|
|
30
|
+
it('no throw: single-node + memory (the common case)', () => {
|
|
31
|
+
expect(() => assertClusterDriverSafeForTopology('memory', {})).not.toThrow();
|
|
32
|
+
});
|
|
33
|
+
it('no throw: multi-node + remote driver', () => {
|
|
34
|
+
expect(() =>
|
|
35
|
+
assertClusterDriverSafeForTopology('redis', { OS_EXPECT_MULTI_NODE: 'true' }),
|
|
36
|
+
).not.toThrow();
|
|
37
|
+
});
|
|
38
|
+
it('THROWS: multi-node (OS_EXPECT_MULTI_NODE) + memory', () => {
|
|
39
|
+
expect(() =>
|
|
40
|
+
assertClusterDriverSafeForTopology('memory', { OS_EXPECT_MULTI_NODE: 'true' }),
|
|
41
|
+
).toThrow(/split-brain/);
|
|
42
|
+
});
|
|
43
|
+
it('THROWS: multi-node (replicas>1) + memory, cites ADR-0010', () => {
|
|
44
|
+
expect(() =>
|
|
45
|
+
assertClusterDriverSafeForTopology('memory', { OS_CLUSTER_REPLICAS: '2' }),
|
|
46
|
+
).toThrow(/ADR-0010/);
|
|
47
|
+
});
|
|
48
|
+
it('escape hatch: multi-node + memory + OS_ALLOW_MEMORY_CLUSTER_MULTINODE=true', () => {
|
|
49
|
+
expect(() =>
|
|
50
|
+
assertClusterDriverSafeForTopology('memory', {
|
|
51
|
+
OS_EXPECT_MULTI_NODE: 'true',
|
|
52
|
+
OS_ALLOW_MEMORY_CLUSTER_MULTINODE: 'true',
|
|
53
|
+
}),
|
|
54
|
+
).not.toThrow();
|
|
55
|
+
});
|
|
56
|
+
it('does not guard unknown custom drivers (author responsibility)', () => {
|
|
57
|
+
expect(() =>
|
|
58
|
+
assertClusterDriverSafeForTopology('mycustom', { OS_EXPECT_MULTI_NODE: 'true' }),
|
|
59
|
+
).not.toThrow();
|
|
60
|
+
});
|
|
61
|
+
});
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Split-brain guard (ADR-0010, path A).
|
|
5
|
+
*
|
|
6
|
+
* The `memory` cluster driver keeps PubSub/Lock/KV/Counter state **per
|
|
7
|
+
* process**. On a single node that is correct; across multiple replicas
|
|
8
|
+
* each process holds its own state, so:
|
|
9
|
+
* - `ILock` is acquired locally by every replica -> no mutual exclusion;
|
|
10
|
+
* - `ICounter`/`IKV` versions diverge per replica;
|
|
11
|
+
* - `IPubSub` does not fan out across processes.
|
|
12
|
+
*
|
|
13
|
+
* This fails silently -- single-node tests and dev pass, only production
|
|
14
|
+
* multi-replica corrupts. The guard turns that silent corruption into a
|
|
15
|
+
* loud startup error when the operator has *declared* a multi-node
|
|
16
|
+
* topology yet wired an in-process driver.
|
|
17
|
+
*
|
|
18
|
+
* Detection is deliberately conservative (path A): it keys off an
|
|
19
|
+
* explicit operator declaration, not active peer discovery (that is the
|
|
20
|
+
* optional path B in ADR-0010). It cannot know at boot whether the
|
|
21
|
+
* cluster primitives are actually used cross-node, so it offers an
|
|
22
|
+
* escape hatch for the rare "replicas declared but primitives unused"
|
|
23
|
+
* case.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/** In-process drivers whose state does not coordinate across replicas. */
|
|
27
|
+
const IN_PROCESS_DRIVERS = new Set(['memory']);
|
|
28
|
+
|
|
29
|
+
/** Environment inputs the guard reads. */
|
|
30
|
+
export interface SplitBrainGuardEnv {
|
|
31
|
+
/** `'true'` -> operator declares a multi-node deployment. */
|
|
32
|
+
OS_EXPECT_MULTI_NODE?: string;
|
|
33
|
+
/** Replica count; `> 1` -> multi-node. */
|
|
34
|
+
OS_CLUSTER_REPLICAS?: string;
|
|
35
|
+
/** `'true'` -> bypass the guard (replicas declared but primitives unused cross-node). */
|
|
36
|
+
OS_ALLOW_MEMORY_CLUSTER_MULTINODE?: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function isTrue(v: string | undefined): boolean {
|
|
40
|
+
return String(v).trim().toLowerCase() === 'true';
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* True when the operator has declared a multi-node topology via
|
|
45
|
+
* `OS_EXPECT_MULTI_NODE=true` or `OS_CLUSTER_REPLICAS` greater than 1.
|
|
46
|
+
*/
|
|
47
|
+
export function declaresMultiNode(env: SplitBrainGuardEnv = process.env): boolean {
|
|
48
|
+
if (isTrue(env.OS_EXPECT_MULTI_NODE)) return true;
|
|
49
|
+
const replicas = Number(env.OS_CLUSTER_REPLICAS);
|
|
50
|
+
return Number.isFinite(replicas) && replicas > 1;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Throw if a multi-node topology is declared while the resolved cluster
|
|
55
|
+
* `driver` is in-process (`memory`), unless explicitly allowed via
|
|
56
|
+
* `OS_ALLOW_MEMORY_CLUSTER_MULTINODE=true`.
|
|
57
|
+
*
|
|
58
|
+
* Call this at startup *before* registering the cluster service so a
|
|
59
|
+
* misconfiguration fails fast.
|
|
60
|
+
*/
|
|
61
|
+
export function assertClusterDriverSafeForTopology(
|
|
62
|
+
driver: string,
|
|
63
|
+
env: SplitBrainGuardEnv = process.env,
|
|
64
|
+
): void {
|
|
65
|
+
if (!declaresMultiNode(env)) return;
|
|
66
|
+
if (!IN_PROCESS_DRIVERS.has(driver)) return;
|
|
67
|
+
if (isTrue(env.OS_ALLOW_MEMORY_CLUSTER_MULTINODE)) return;
|
|
68
|
+
|
|
69
|
+
throw new Error(
|
|
70
|
+
`ClusterServicePlugin: multi-node deployment declared ` +
|
|
71
|
+
`(OS_EXPECT_MULTI_NODE / OS_CLUSTER_REPLICAS>1) but the cluster driver is ` +
|
|
72
|
+
`in-process "${driver}" -- its locks/counters/pub-sub do not coordinate across ` +
|
|
73
|
+
`processes, so multiple replicas silently split-brain. Configure a remote cluster ` +
|
|
74
|
+
`driver (e.g. @objectstack/service-cluster-redis) or a DB-backed driver. To override ` +
|
|
75
|
+
`(replicas declared but cluster primitives unused cross-node), set ` +
|
|
76
|
+
`OS_ALLOW_MEMORY_CLUSTER_MULTINODE=true. See cloud ADR-0010.`,
|
|
77
|
+
);
|
|
78
|
+
}
|