@objectstack/service-cluster 10.0.0 → 10.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
 
2
- > @objectstack/service-cluster@10.0.0 build /home/runner/work/framework/framework/packages/services/service-cluster
2
+ > @objectstack/service-cluster@10.3.0 build /home/runner/work/framework/framework/packages/services/service-cluster
3
3
  > tsup
4
4
 
5
5
  CLI Building entry: src/index.ts, src/testing.ts
@@ -10,19 +10,19 @@
10
10
  CLI Cleaning output folder
11
11
  ESM Build start
12
12
  CJS Build start
13
- ESM dist/index.js 13.87 KB
13
+ ESM dist/index.js 14.21 KB
14
14
  ESM dist/testing.js 8.60 KB
15
- ESM dist/index.js.map 38.10 KB
15
+ ESM dist/index.js.map 40.08 KB
16
16
  ESM dist/testing.js.map 18.62 KB
17
- ESM ⚡️ Build success in 835ms
17
+ ESM ⚡️ Build success in 1085ms
18
+ CJS dist/index.cjs 15.68 KB
18
19
  CJS dist/testing.cjs 11.60 KB
19
- CJS dist/index.cjs 15.26 KB
20
+ CJS dist/index.cjs.map 43.08 KB
20
21
  CJS dist/testing.cjs.map 14.18 KB
21
- CJS dist/index.cjs.map 41.16 KB
22
- CJS ⚡️ Build success in 845ms
22
+ CJS ⚡️ Build success in 1098ms
23
23
  DTS Build start
24
- DTS ⚡️ Build success in 18597ms
25
- DTS dist/index.d.ts 9.12 KB
24
+ DTS ⚡️ Build success in 19770ms
25
+ DTS dist/index.d.ts 10.74 KB
26
26
  DTS dist/testing.d.ts 794.00 B
27
- DTS dist/index.d.cts 9.12 KB
27
+ DTS dist/index.d.cts 10.74 KB
28
28
  DTS dist/testing.d.cts 794.00 B
package/CHANGELOG.md CHANGED
@@ -1,5 +1,44 @@
1
1
  # @objectstack/service-cluster
2
2
 
3
+ ## 10.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 2b355d5: feat(cluster): multi-node authorization gate (open mechanism)
8
+
9
+ `@objectstack/service-cluster` now exports `registerMultiNodeGate` /
10
+ `checkMultiNodeAllowed`: a distribution (e.g. the Enterprise Edition) can
11
+ register a gate that authorizes whether the runtime may enable a multi-node
12
+ (remote-driver) topology. The open framework ships no gate — multi-node is
13
+ always allowed.
14
+
15
+ `os serve` consults the gate before activating a remote cluster driver; on
16
+ denial it **downgrades to single-node (in-memory) rather than failing** —
17
+ multi-node is an add-on, never bricks the runtime. The framework holds zero
18
+ license logic; this is the open seam an EE license plugs into (cloud ADR-0022).
19
+
20
+ ### Patch Changes
21
+
22
+ - @objectstack/spec@10.3.0
23
+ - @objectstack/core@10.3.0
24
+
25
+ ## 10.2.0
26
+
27
+ ### Patch Changes
28
+
29
+ - Updated dependencies [b496498]
30
+ - @objectstack/spec@10.2.0
31
+ - @objectstack/core@10.2.0
32
+
33
+ ## 10.1.0
34
+
35
+ ### Patch Changes
36
+
37
+ - Updated dependencies [49da36e]
38
+ - Updated dependencies [ac79f16]
39
+ - @objectstack/spec@10.1.0
40
+ - @objectstack/core@10.1.0
41
+
3
42
  ## 10.0.0
4
43
 
5
44
  ### Patch Changes
package/dist/index.cjs CHANGED
@@ -450,6 +450,21 @@ var MetadataClusterBridgePlugin = class {
450
450
  }
451
451
  };
452
452
 
453
+ // src/multi-node-gate.ts
454
+ var registered;
455
+ function registerMultiNodeGate(gate) {
456
+ registered = gate;
457
+ }
458
+ function checkMultiNodeAllowed() {
459
+ return registered ? registered.allowMultiNode() : { allowed: true };
460
+ }
461
+ function __resetMultiNodeGate() {
462
+ registered = void 0;
463
+ }
464
+
465
+
466
+
467
+
453
468
 
454
469
 
455
470
 
@@ -462,5 +477,5 @@ var MetadataClusterBridgePlugin = class {
462
477
 
463
478
 
464
479
 
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;
480
+ 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.__resetMultiNodeGate = __resetMultiNodeGate; exports.assertClusterDriverSafeForTopology = assertClusterDriverSafeForTopology; exports.checkMultiNodeAllowed = checkMultiNodeAllowed; exports.declaresMultiNode = declaresMultiNode; exports.defineCluster = defineCluster; exports.registerClusterDriver = registerClusterDriver; exports.registerMultiNodeGate = registerMultiNodeGate;
466
481
  //# sourceMappingURL=index.cjs.map
@@ -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/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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e,EAAA;AACnB,EAAA;AAGI,IAAA;AACI,MAAA;AACA,MAAA;AAAa,IAAA;AAEb,MAAA;AACA,MAAA;AAAa,IAAA;AAKjB,IAAA;AAEA,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;APqTA;AACA;AQhXO;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;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"]}
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","../src/multi-node-gate.ts"],"names":[],"mappings":"AAAA;ACUA,kDAA8C;ADR9C;AACA;AE8BO,IAAM,aAAA,EAAN,MAAsC;AAAA,EAMzC,W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AA;AACA,QAAA;AACJ,MAAA;AAEJ,MAAA;AAAc,IAAA;AACjB,EAAA;AAET;AR0WA;AACA;AS5aA;AAMO;AACH,EAAA;AACJ;AAMO;AACH,EAAA;AACJ;AAGO;AACH,EAAA;AACJ;ATkaA;AACA;AACA;AACA;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","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Multi-node authorization gate (open mechanism).\n *\n * The open framework ships **no gate** — multi-node is always allowed. A\n * distribution (e.g. the Enterprise Edition) registers a gate to authorize\n * whether the runtime may enable a multi-node (remote-driver) topology — for\n * example, an EE license check. The framework deliberately knows nothing about\n * *why* a gate allows or denies; it only consults the registered decision.\n *\n * When a gate denies, the caller (e.g. `os serve`) **downgrades to single-node**\n * rather than failing — multi-node is an add-on, not a precondition for the\n * runtime to serve. This is distinct from the split-brain guard, which throws\n * on an outright misconfiguration (memory driver declared multi-node).\n */\nexport interface MultiNodeGate {\n /**\n * Called before the runtime enables a remote-driver (multi-node) topology.\n * Return `allowed: false` to force single-node; `reason` is surfaced in logs.\n */\n allowMultiNode(): { allowed: boolean; reason?: string };\n}\n\nlet registered: MultiNodeGate | undefined;\n\n/**\n * Register the multi-node authorization gate. Last registration wins. A\n * distribution calls this at boot (before the cluster topology is resolved).\n */\nexport function registerMultiNodeGate(gate: MultiNodeGate): void {\n registered = gate;\n}\n\n/**\n * Resolve the multi-node decision. With no gate registered (open framework),\n * multi-node is allowed.\n */\nexport function checkMultiNodeAllowed(): { allowed: boolean; reason?: string } {\n return registered ? registered.allowMultiNode() : { allowed: true };\n}\n\n/** Clear the registered gate. For tests. */\nexport function __resetMultiNodeGate(): void {\n registered = undefined;\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -224,4 +224,44 @@ declare class MetadataClusterBridgePlugin implements Plugin {
224
224
  init(ctx: PluginContext): Promise<void>;
225
225
  }
226
226
 
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 };
227
+ /**
228
+ * Multi-node authorization gate (open mechanism).
229
+ *
230
+ * The open framework ships **no gate** — multi-node is always allowed. A
231
+ * distribution (e.g. the Enterprise Edition) registers a gate to authorize
232
+ * whether the runtime may enable a multi-node (remote-driver) topology — for
233
+ * example, an EE license check. The framework deliberately knows nothing about
234
+ * *why* a gate allows or denies; it only consults the registered decision.
235
+ *
236
+ * When a gate denies, the caller (e.g. `os serve`) **downgrades to single-node**
237
+ * rather than failing — multi-node is an add-on, not a precondition for the
238
+ * runtime to serve. This is distinct from the split-brain guard, which throws
239
+ * on an outright misconfiguration (memory driver declared multi-node).
240
+ */
241
+ interface MultiNodeGate {
242
+ /**
243
+ * Called before the runtime enables a remote-driver (multi-node) topology.
244
+ * Return `allowed: false` to force single-node; `reason` is surfaced in logs.
245
+ */
246
+ allowMultiNode(): {
247
+ allowed: boolean;
248
+ reason?: string;
249
+ };
250
+ }
251
+ /**
252
+ * Register the multi-node authorization gate. Last registration wins. A
253
+ * distribution calls this at boot (before the cluster topology is resolved).
254
+ */
255
+ declare function registerMultiNodeGate(gate: MultiNodeGate): void;
256
+ /**
257
+ * Resolve the multi-node decision. With no gate registered (open framework),
258
+ * multi-node is allowed.
259
+ */
260
+ declare function checkMultiNodeAllowed(): {
261
+ allowed: boolean;
262
+ reason?: string;
263
+ };
264
+ /** Clear the registered gate. For tests. */
265
+ declare function __resetMultiNodeGate(): void;
266
+
267
+ export { type ClusterDriverFactory, ClusterServicePlugin, type ClusterServicePluginOptions, ComposedClusterService, type DriverFactoryConfig, MemoryCounter, MemoryKV, MemoryLock, type MemoryLockOptions, MemoryPubSub, type MemoryPubSubOptions, MetadataClusterBridgePlugin, type MultiNodeGate, type SplitBrainGuardEnv, VersionMismatchError, __resetMultiNodeGate, assertClusterDriverSafeForTopology, checkMultiNodeAllowed, declaresMultiNode, defineCluster, registerClusterDriver, registerMultiNodeGate };
package/dist/index.d.ts CHANGED
@@ -224,4 +224,44 @@ declare class MetadataClusterBridgePlugin implements Plugin {
224
224
  init(ctx: PluginContext): Promise<void>;
225
225
  }
226
226
 
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 };
227
+ /**
228
+ * Multi-node authorization gate (open mechanism).
229
+ *
230
+ * The open framework ships **no gate** — multi-node is always allowed. A
231
+ * distribution (e.g. the Enterprise Edition) registers a gate to authorize
232
+ * whether the runtime may enable a multi-node (remote-driver) topology — for
233
+ * example, an EE license check. The framework deliberately knows nothing about
234
+ * *why* a gate allows or denies; it only consults the registered decision.
235
+ *
236
+ * When a gate denies, the caller (e.g. `os serve`) **downgrades to single-node**
237
+ * rather than failing — multi-node is an add-on, not a precondition for the
238
+ * runtime to serve. This is distinct from the split-brain guard, which throws
239
+ * on an outright misconfiguration (memory driver declared multi-node).
240
+ */
241
+ interface MultiNodeGate {
242
+ /**
243
+ * Called before the runtime enables a remote-driver (multi-node) topology.
244
+ * Return `allowed: false` to force single-node; `reason` is surfaced in logs.
245
+ */
246
+ allowMultiNode(): {
247
+ allowed: boolean;
248
+ reason?: string;
249
+ };
250
+ }
251
+ /**
252
+ * Register the multi-node authorization gate. Last registration wins. A
253
+ * distribution calls this at boot (before the cluster topology is resolved).
254
+ */
255
+ declare function registerMultiNodeGate(gate: MultiNodeGate): void;
256
+ /**
257
+ * Resolve the multi-node decision. With no gate registered (open framework),
258
+ * multi-node is allowed.
259
+ */
260
+ declare function checkMultiNodeAllowed(): {
261
+ allowed: boolean;
262
+ reason?: string;
263
+ };
264
+ /** Clear the registered gate. For tests. */
265
+ declare function __resetMultiNodeGate(): void;
266
+
267
+ export { type ClusterDriverFactory, ClusterServicePlugin, type ClusterServicePluginOptions, ComposedClusterService, type DriverFactoryConfig, MemoryCounter, MemoryKV, MemoryLock, type MemoryLockOptions, MemoryPubSub, type MemoryPubSubOptions, MetadataClusterBridgePlugin, type MultiNodeGate, type SplitBrainGuardEnv, VersionMismatchError, __resetMultiNodeGate, assertClusterDriverSafeForTopology, checkMultiNodeAllowed, declaresMultiNode, defineCluster, registerClusterDriver, registerMultiNodeGate };
package/dist/index.js CHANGED
@@ -449,6 +449,18 @@ var MetadataClusterBridgePlugin = class {
449
449
  });
450
450
  }
451
451
  };
452
+
453
+ // src/multi-node-gate.ts
454
+ var registered;
455
+ function registerMultiNodeGate(gate) {
456
+ registered = gate;
457
+ }
458
+ function checkMultiNodeAllowed() {
459
+ return registered ? registered.allowMultiNode() : { allowed: true };
460
+ }
461
+ function __resetMultiNodeGate() {
462
+ registered = void 0;
463
+ }
452
464
  export {
453
465
  ClusterServicePlugin,
454
466
  ComposedClusterService,
@@ -458,9 +470,12 @@ export {
458
470
  MemoryPubSub,
459
471
  MetadataClusterBridgePlugin,
460
472
  VersionMismatchError,
473
+ __resetMultiNodeGate,
461
474
  assertClusterDriverSafeForTopology,
475
+ checkMultiNodeAllowed,
462
476
  declaresMultiNode,
463
477
  defineCluster,
464
- registerClusterDriver
478
+ registerClusterDriver,
479
+ registerMultiNodeGate
465
480
  };
466
481
  //# sourceMappingURL=index.js.map
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/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,MA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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","../src/multi-node-gate.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","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Multi-node authorization gate (open mechanism).\n *\n * The open framework ships **no gate** — multi-node is always allowed. A\n * distribution (e.g. the Enterprise Edition) registers a gate to authorize\n * whether the runtime may enable a multi-node (remote-driver) topology — for\n * example, an EE license check. The framework deliberately knows nothing about\n * *why* a gate allows or denies; it only consults the registered decision.\n *\n * When a gate denies, the caller (e.g. `os serve`) **downgrades to single-node**\n * rather than failing — multi-node is an add-on, not a precondition for the\n * runtime to serve. This is distinct from the split-brain guard, which throws\n * on an outright misconfiguration (memory driver declared multi-node).\n */\nexport interface MultiNodeGate {\n /**\n * Called before the runtime enables a remote-driver (multi-node) topology.\n * Return `allowed: false` to force single-node; `reason` is surfaced in logs.\n */\n allowMultiNode(): { allowed: boolean; reason?: string };\n}\n\nlet registered: MultiNodeGate | undefined;\n\n/**\n * Register the multi-node authorization gate. Last registration wins. A\n * distribution calls this at boot (before the cluster topology is resolved).\n */\nexport function registerMultiNodeGate(gate: MultiNodeGate): void {\n registered = gate;\n}\n\n/**\n * Resolve the multi-node decision. With no gate registered (open framework),\n * multi-node is allowed.\n */\nexport function checkMultiNodeAllowed(): { allowed: boolean; reason?: string } {\n return registered ? registered.allowMultiNode() : { allowed: true };\n}\n\n/** Clear the registered gate. For tests. */\nexport function __resetMultiNodeGate(): void {\n registered = undefined;\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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AAO;AAAA,UACP;AAAA,UACA;AAAA,QACJ;AAAA,MACJ;AACA,WAAK,SAAS;AAAA,IAClB,CAAC;AAAA,EACL;AACJ;;;ACjEA,IAAI;AAMG,SAAS,sBAAsB,MAA2B;AAC7D,eAAa;AACjB;AAMO,SAAS,wBAA+D;AAC3E,SAAO,aAAa,WAAW,eAAe,IAAI,EAAE,SAAS,KAAK;AACtE;AAGO,SAAS,uBAA6B;AACzC,eAAa;AACjB;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@objectstack/service-cluster",
3
- "version": "10.0.0",
3
+ "version": "10.3.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": "10.0.0",
23
- "@objectstack/spec": "10.0.0"
22
+ "@objectstack/core": "10.3.0",
23
+ "@objectstack/spec": "10.3.0"
24
24
  },
25
25
  "devDependencies": {
26
26
  "@types/node": "^26.0.0",
package/src/index.ts CHANGED
@@ -66,3 +66,10 @@ export type {
66
66
  CounterIncrOptions,
67
67
  ClusterCallContext,
68
68
  } from '@objectstack/spec/contracts';
69
+
70
+ export {
71
+ registerMultiNodeGate,
72
+ checkMultiNodeAllowed,
73
+ __resetMultiNodeGate,
74
+ type MultiNodeGate,
75
+ } from './multi-node-gate.js';
@@ -0,0 +1,37 @@
1
+ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2
+ import { describe, it, expect, afterEach } from 'vitest';
3
+ import {
4
+ registerMultiNodeGate,
5
+ checkMultiNodeAllowed,
6
+ __resetMultiNodeGate,
7
+ } from './multi-node-gate.js';
8
+
9
+ afterEach(() => __resetMultiNodeGate());
10
+
11
+ describe('multi-node gate', () => {
12
+ it('allows when no gate is registered (open framework)', () => {
13
+ expect(checkMultiNodeAllowed()).toEqual({ allowed: true });
14
+ });
15
+
16
+ it('honors a denying gate with reason', () => {
17
+ registerMultiNodeGate({ allowMultiNode: () => ({ allowed: false, reason: 'unlicensed' }) });
18
+ expect(checkMultiNodeAllowed()).toEqual({ allowed: false, reason: 'unlicensed' });
19
+ });
20
+
21
+ it('honors an allowing gate', () => {
22
+ registerMultiNodeGate({ allowMultiNode: () => ({ allowed: true }) });
23
+ expect(checkMultiNodeAllowed().allowed).toBe(true);
24
+ });
25
+
26
+ it('last registration wins', () => {
27
+ registerMultiNodeGate({ allowMultiNode: () => ({ allowed: false }) });
28
+ registerMultiNodeGate({ allowMultiNode: () => ({ allowed: true }) });
29
+ expect(checkMultiNodeAllowed().allowed).toBe(true);
30
+ });
31
+
32
+ it('reset restores open default', () => {
33
+ registerMultiNodeGate({ allowMultiNode: () => ({ allowed: false }) });
34
+ __resetMultiNodeGate();
35
+ expect(checkMultiNodeAllowed()).toEqual({ allowed: true });
36
+ });
37
+ });
@@ -0,0 +1,46 @@
1
+ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2
+
3
+ /**
4
+ * Multi-node authorization gate (open mechanism).
5
+ *
6
+ * The open framework ships **no gate** — multi-node is always allowed. A
7
+ * distribution (e.g. the Enterprise Edition) registers a gate to authorize
8
+ * whether the runtime may enable a multi-node (remote-driver) topology — for
9
+ * example, an EE license check. The framework deliberately knows nothing about
10
+ * *why* a gate allows or denies; it only consults the registered decision.
11
+ *
12
+ * When a gate denies, the caller (e.g. `os serve`) **downgrades to single-node**
13
+ * rather than failing — multi-node is an add-on, not a precondition for the
14
+ * runtime to serve. This is distinct from the split-brain guard, which throws
15
+ * on an outright misconfiguration (memory driver declared multi-node).
16
+ */
17
+ export interface MultiNodeGate {
18
+ /**
19
+ * Called before the runtime enables a remote-driver (multi-node) topology.
20
+ * Return `allowed: false` to force single-node; `reason` is surfaced in logs.
21
+ */
22
+ allowMultiNode(): { allowed: boolean; reason?: string };
23
+ }
24
+
25
+ let registered: MultiNodeGate | undefined;
26
+
27
+ /**
28
+ * Register the multi-node authorization gate. Last registration wins. A
29
+ * distribution calls this at boot (before the cluster topology is resolved).
30
+ */
31
+ export function registerMultiNodeGate(gate: MultiNodeGate): void {
32
+ registered = gate;
33
+ }
34
+
35
+ /**
36
+ * Resolve the multi-node decision. With no gate registered (open framework),
37
+ * multi-node is allowed.
38
+ */
39
+ export function checkMultiNodeAllowed(): { allowed: boolean; reason?: string } {
40
+ return registered ? registered.allowMultiNode() : { allowed: true };
41
+ }
42
+
43
+ /** Clear the registered gate. For tests. */
44
+ export function __resetMultiNodeGate(): void {
45
+ registered = undefined;
46
+ }