@objectstack/service-cluster 5.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@objectstack/service-cluster",
3
+ "version": "5.1.1",
4
+ "license": "Apache-2.0",
5
+ "description": "Cluster Service for ObjectStack — pluggable PubSub/Lock/KV/Counter primitives. Memory driver included; postgres/redis drivers ship separately.",
6
+ "type": "module",
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs"
14
+ },
15
+ "./testing": {
16
+ "types": "./dist/testing.d.ts",
17
+ "import": "./dist/testing.js",
18
+ "require": "./dist/testing.cjs"
19
+ }
20
+ },
21
+ "dependencies": {
22
+ "@objectstack/core": "5.2.0",
23
+ "@objectstack/spec": "5.2.0"
24
+ },
25
+ "devDependencies": {
26
+ "@types/node": "^25.9.1",
27
+ "typescript": "^6.0.3",
28
+ "vitest": "^4.1.7"
29
+ },
30
+ "keywords": [
31
+ "objectstack",
32
+ "service",
33
+ "cluster",
34
+ "pubsub",
35
+ "lock",
36
+ "kv"
37
+ ],
38
+ "author": "ObjectStack",
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "https://github.com/objectstack-ai/framework.git",
42
+ "directory": "packages/services/service-cluster"
43
+ },
44
+ "scripts": {
45
+ "build": "tsup",
46
+ "test": "vitest run"
47
+ }
48
+ }
@@ -0,0 +1,77 @@
1
+ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2
+
3
+ import type { Plugin, PluginContext } from '@objectstack/core';
4
+ import type { IClusterService } from '@objectstack/spec/contracts';
5
+ import type { ClusterCapabilityConfigInput } from '@objectstack/spec/kernel';
6
+ import { defineCluster } from './cluster.js';
7
+
8
+ /**
9
+ * Options for `ClusterServicePlugin`.
10
+ *
11
+ * Pass either a pre-built `cluster` instance (advanced — for tests or
12
+ * custom drivers), or a `config` object that will be passed to
13
+ * `defineCluster()`. If both are omitted, a memory-driver cluster is
14
+ * created with auto-generated nodeId.
15
+ */
16
+ export interface ClusterServicePluginOptions {
17
+ /** Pre-built cluster service. Wins over `config` when both provided. */
18
+ cluster?: IClusterService;
19
+ /** Config forwarded to `defineCluster()` when `cluster` is absent. */
20
+ config?: ClusterCapabilityConfigInput;
21
+ }
22
+
23
+ /**
24
+ * Registers an `IClusterService` under the well-known service name
25
+ * `'cluster'`. Plugins consume it via:
26
+ *
27
+ * ```ts
28
+ * import type { IClusterService } from '@objectstack/spec/contracts';
29
+ * const cluster = ctx.getService<IClusterService>('cluster');
30
+ * await cluster.pubsub.publish('metadata.changed', payload);
31
+ * ```
32
+ *
33
+ * The plugin closes the cluster on kernel shutdown.
34
+ *
35
+ * @example default memory driver
36
+ * kernel.use(new ClusterServicePlugin());
37
+ *
38
+ * @example explicit config
39
+ * kernel.use(new ClusterServicePlugin({ config: { driver: 'memory', nodeId: 'web-1' } }));
40
+ */
41
+ export class ClusterServicePlugin implements Plugin {
42
+ name = 'com.objectstack.service.cluster';
43
+ version = '1.0.0';
44
+ type = 'standard';
45
+
46
+ private readonly options: ClusterServicePluginOptions;
47
+ private cluster?: IClusterService;
48
+ private owned = false;
49
+
50
+ constructor(options: ClusterServicePluginOptions = {}) {
51
+ this.options = options;
52
+ }
53
+
54
+ async init(ctx: PluginContext): Promise<void> {
55
+ if (this.options.cluster) {
56
+ this.cluster = this.options.cluster;
57
+ this.owned = false;
58
+ } else {
59
+ this.cluster = defineCluster(this.options.config ?? {});
60
+ this.owned = true;
61
+ }
62
+ ctx.registerService('cluster', this.cluster);
63
+ ctx.logger.info(
64
+ `ClusterServicePlugin: registered "${this.cluster.driver}" driver (node=${this.cluster.nodeId})`,
65
+ );
66
+
67
+ ctx.hook('kernel:shutdown', async () => {
68
+ if (this.owned && this.cluster) {
69
+ try {
70
+ await this.cluster.close();
71
+ } catch (err) {
72
+ ctx.logger.error('ClusterServicePlugin: close error', err as Error);
73
+ }
74
+ }
75
+ });
76
+ }
77
+ }
package/src/cluster.ts ADDED
@@ -0,0 +1,129 @@
1
+ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2
+
3
+ import type {
4
+ IClusterService,
5
+ IPubSub,
6
+ ILock,
7
+ IKV,
8
+ ICounter,
9
+ } from '@objectstack/spec/contracts';
10
+ import type { ClusterCapabilityConfigInput } from '@objectstack/spec/kernel';
11
+ import { ClusterCapabilityConfigSchema } from '@objectstack/spec/kernel';
12
+
13
+ import { MemoryPubSub } from './memory/pubsub.js';
14
+ import { MemoryLock } from './memory/lock.js';
15
+ import { MemoryKV } from './memory/kv.js';
16
+ import { MemoryCounter } from './memory/counter.js';
17
+
18
+ /**
19
+ * Compose four cluster primitives into a single `IClusterService` facade.
20
+ * Useful for custom driver authors who want to mix and match.
21
+ */
22
+ export class ComposedClusterService implements IClusterService {
23
+ constructor(
24
+ public readonly nodeId: string,
25
+ public readonly driver: string,
26
+ public readonly pubsub: IPubSub,
27
+ public readonly lock: ILock,
28
+ public readonly kv: IKV,
29
+ public readonly counter: ICounter,
30
+ ) { }
31
+
32
+ async close(): Promise<void> {
33
+ // Reverse order, swallow errors so a slow close doesn't block siblings.
34
+ const closers = [this.counter, this.kv, this.lock, this.pubsub];
35
+ for (const c of closers) {
36
+ try {
37
+ await c.close();
38
+ } catch (err) {
39
+ // eslint-disable-next-line no-console
40
+ console.error('[ClusterService] close error:', err);
41
+ }
42
+ }
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Build an `IClusterService` from a `ClusterCapabilityConfig`. The only
48
+ * driver shipped from this package is `memory`; other drivers (postgres,
49
+ * redis, nats) live in dedicated packages and register themselves via
50
+ * `registerClusterDriver()`.
51
+ *
52
+ * @example
53
+ * const cluster = defineCluster({ driver: 'memory' });
54
+ * await cluster.pubsub.publish('metadata.changed', { id: 'x' });
55
+ */
56
+ export function defineCluster(
57
+ config: ClusterCapabilityConfigInput = {},
58
+ ): IClusterService {
59
+ const parsed = ClusterCapabilityConfigSchema.parse(config);
60
+ const nodeId = parsed.nodeId ?? generateNodeId();
61
+
62
+ if (parsed.driver === 'memory') {
63
+ return new ComposedClusterService(
64
+ nodeId,
65
+ 'memory',
66
+ new MemoryPubSub({ nodeId }),
67
+ new MemoryLock({ defaultTtlMs: parsed.lockTtlMs }),
68
+ new MemoryKV(),
69
+ new MemoryCounter(),
70
+ );
71
+ }
72
+
73
+ const factory = driverRegistry.get(parsed.driver);
74
+ if (!factory) {
75
+ throw new Error(
76
+ `Cluster driver "${parsed.driver}" is not registered. ` +
77
+ `Did you forget to import @objectstack/service-cluster-${parsed.driver} ` +
78
+ `or call registerClusterDriver()? ` +
79
+ `See content/docs/concepts/cluster-semantics.mdx §6.`,
80
+ );
81
+ }
82
+ return factory({ ...parsed, nodeId });
83
+ }
84
+
85
+ // ---------------------------------------------------------------------------
86
+ // Driver registry (for postgres/redis/nats/custom drivers)
87
+ // ---------------------------------------------------------------------------
88
+
89
+ export interface DriverFactoryConfig {
90
+ driver: string;
91
+ nodeId: string;
92
+ url?: string;
93
+ useExistingPool?: boolean;
94
+ heartbeatMs?: number;
95
+ lockTtlMs?: number;
96
+ tenantIsolation?: string;
97
+ driverOptions?: Record<string, unknown>;
98
+ }
99
+
100
+ export type ClusterDriverFactory = (config: DriverFactoryConfig) => IClusterService;
101
+
102
+ const driverRegistry = new Map<string, ClusterDriverFactory>();
103
+
104
+ /**
105
+ * Register a custom cluster driver. Driver packages (e.g.
106
+ * `@objectstack/service-cluster-postgres`) should call this at module
107
+ * load time so `defineCluster({ driver: 'postgres' })` resolves them.
108
+ */
109
+ export function registerClusterDriver(
110
+ name: string,
111
+ factory: ClusterDriverFactory,
112
+ ): void {
113
+ if (name === 'memory') {
114
+ throw new Error('The "memory" driver is reserved.');
115
+ }
116
+ driverRegistry.set(name, factory);
117
+ }
118
+
119
+ // ---------------------------------------------------------------------------
120
+ // Helpers
121
+ // ---------------------------------------------------------------------------
122
+
123
+ function generateNodeId(): string {
124
+ // Avoid the `crypto` import dance for a single use; this is dev-only
125
+ // randomness and the driver upgrades replace it.
126
+ const rand = Math.random().toString(36).slice(2, 10);
127
+ const ts = Date.now().toString(36);
128
+ return `node-${ts}-${rand}`;
129
+ }
package/src/index.ts ADDED
@@ -0,0 +1,52 @@
1
+ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2
+
3
+ /**
4
+ * @objectstack/service-cluster
5
+ *
6
+ * Pluggable cluster primitives (PubSub / Lock / KV / Counter) for
7
+ * ObjectStack. The default `memory` driver is exported here; remote
8
+ * drivers (postgres/redis/nats) ship as sibling packages and register
9
+ * themselves via `registerClusterDriver()`.
10
+ *
11
+ * See `content/docs/concepts/cluster-semantics.mdx` for the protocol.
12
+ */
13
+
14
+ export {
15
+ defineCluster,
16
+ registerClusterDriver,
17
+ ComposedClusterService,
18
+ type ClusterDriverFactory,
19
+ type DriverFactoryConfig,
20
+ } from './cluster.js';
21
+
22
+ export { MemoryPubSub, type MemoryPubSubOptions } from './memory/pubsub.js';
23
+ export { MemoryLock, type MemoryLockOptions } from './memory/lock.js';
24
+ export { MemoryKV, VersionMismatchError } from './memory/kv.js';
25
+ export { MemoryCounter } from './memory/counter.js';
26
+
27
+ export {
28
+ ClusterServicePlugin,
29
+ type ClusterServicePluginOptions,
30
+ } from './cluster-service-plugin.js';
31
+
32
+ export { MetadataClusterBridgePlugin } from './metadata-cluster-bridge-plugin.js';
33
+
34
+ // Re-export contracts for convenience.
35
+ export type {
36
+ IClusterService,
37
+ IPubSub,
38
+ PubSubMessage,
39
+ PubSubHandler,
40
+ PublishOptions,
41
+ SubscribeOptions,
42
+ Unsubscribe,
43
+ ILock,
44
+ LockHandle,
45
+ LockAcquireOptions,
46
+ IKV,
47
+ KVEntry,
48
+ KVSetOptions,
49
+ ICounter,
50
+ CounterIncrOptions,
51
+ ClusterCallContext,
52
+ } from '@objectstack/spec/contracts';
@@ -0,0 +1,36 @@
1
+ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2
+
3
+ import type { ICounter, CounterIncrOptions } from '@objectstack/spec/contracts';
4
+
5
+ /**
6
+ * In-memory monotonic counter. Single-process only — for cross-node id
7
+ * allocation, use the postgres or redis driver.
8
+ */
9
+ export class MemoryCounter implements ICounter {
10
+ private readonly counters = new Map<string, bigint>();
11
+ private closed = false;
12
+
13
+ async incr(key: string, opts: CounterIncrOptions = {}): Promise<bigint> {
14
+ if (this.closed) throw new Error('MemoryCounter is closed');
15
+ const by = BigInt(opts.by ?? 1);
16
+ const current = this.counters.get(key) ?? 0n;
17
+ const next = current + by;
18
+ this.counters.set(key, next);
19
+ return next;
20
+ }
21
+
22
+ async peek(key: string): Promise<bigint> {
23
+ return this.counters.get(key) ?? 0n;
24
+ }
25
+
26
+ async reset(key: string, value: bigint = 0n): Promise<void> {
27
+ if (this.closed) throw new Error('MemoryCounter is closed');
28
+ if (value === 0n) this.counters.delete(key);
29
+ else this.counters.set(key, value);
30
+ }
31
+
32
+ async close(): Promise<void> {
33
+ this.closed = true;
34
+ this.counters.clear();
35
+ }
36
+ }
@@ -0,0 +1,115 @@
1
+ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2
+
3
+ import type { IKV, KVEntry, KVSetOptions } from '@objectstack/spec/contracts';
4
+
5
+ interface Entry<T = unknown> {
6
+ value: T;
7
+ version: bigint;
8
+ expiresAt?: number;
9
+ timer?: NodeJS.Timeout;
10
+ }
11
+
12
+ /**
13
+ * In-memory coordination KV. Supports optimistic concurrency via
14
+ * `ifVersion` and TTL via `ttl` (seconds).
15
+ *
16
+ * NOT a cache, NOT a database — intended for small cluster bookkeeping.
17
+ */
18
+ export class MemoryKV implements IKV {
19
+ private readonly store = new Map<string, Entry>();
20
+ private closed = false;
21
+
22
+ async get<T = unknown>(key: string): Promise<KVEntry<T> | undefined> {
23
+ const e = this.store.get(key);
24
+ if (!e) return undefined;
25
+ if (e.expiresAt && Date.now() >= e.expiresAt) {
26
+ this.store.delete(key);
27
+ return undefined;
28
+ }
29
+ return {
30
+ key,
31
+ value: e.value as T,
32
+ version: e.version,
33
+ expiresAt: e.expiresAt,
34
+ };
35
+ }
36
+
37
+ async set<T = unknown>(
38
+ key: string,
39
+ value: T,
40
+ opts: KVSetOptions = {},
41
+ ): Promise<KVEntry<T>> {
42
+ if (this.closed) throw new Error('MemoryKV is closed');
43
+ const existing = this.store.get(key);
44
+ const existingVersion = existing
45
+ ? existing.expiresAt && Date.now() >= existing.expiresAt
46
+ ? 0n
47
+ : existing.version
48
+ : 0n;
49
+ if (opts.ifVersion !== undefined && opts.ifVersion !== existingVersion) {
50
+ throw new VersionMismatchError(key, opts.ifVersion, existingVersion);
51
+ }
52
+ if (existing?.timer) clearTimeout(existing.timer);
53
+ const version = existingVersion + 1n;
54
+ const expiresAt = opts.ttl && opts.ttl > 0 ? Date.now() + opts.ttl * 1000 : undefined;
55
+ const entry: Entry<T> = { value, version, expiresAt };
56
+ if (expiresAt) {
57
+ entry.timer = setTimeout(() => {
58
+ const current = this.store.get(key);
59
+ if (current === (entry as Entry<unknown>)) this.store.delete(key);
60
+ }, expiresAt - Date.now());
61
+ }
62
+ this.store.set(key, entry as Entry<unknown>);
63
+ return { key, value, version, expiresAt };
64
+ }
65
+
66
+ async delete(key: string, opts: { ifVersion?: bigint } = {}): Promise<boolean> {
67
+ const e = this.store.get(key);
68
+ if (!e) return false;
69
+ if (e.expiresAt && Date.now() >= e.expiresAt) {
70
+ this.store.delete(key);
71
+ return false;
72
+ }
73
+ if (opts.ifVersion !== undefined && opts.ifVersion !== e.version) {
74
+ throw new VersionMismatchError(key, opts.ifVersion, e.version);
75
+ }
76
+ if (e.timer) clearTimeout(e.timer);
77
+ this.store.delete(key);
78
+ return true;
79
+ }
80
+
81
+ async cas<T = unknown>(
82
+ key: string,
83
+ expectedVersion: bigint,
84
+ next: T,
85
+ opts: Omit<KVSetOptions, 'ifVersion'> = {},
86
+ ): Promise<KVEntry<T> | undefined> {
87
+ try {
88
+ return await this.set(key, next, { ...opts, ifVersion: expectedVersion });
89
+ } catch (err) {
90
+ if (err instanceof VersionMismatchError) return undefined;
91
+ throw err;
92
+ }
93
+ }
94
+
95
+ async close(): Promise<void> {
96
+ this.closed = true;
97
+ for (const [, e] of this.store) {
98
+ if (e.timer) clearTimeout(e.timer);
99
+ }
100
+ this.store.clear();
101
+ }
102
+ }
103
+
104
+ export class VersionMismatchError extends Error {
105
+ constructor(
106
+ public readonly key: string,
107
+ public readonly expected: bigint,
108
+ public readonly actual: bigint,
109
+ ) {
110
+ super(
111
+ `KV version mismatch on "${key}": expected v${expected}, found v${actual}`,
112
+ );
113
+ this.name = 'VersionMismatchError';
114
+ }
115
+ }
@@ -0,0 +1,166 @@
1
+ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2
+
3
+ import type {
4
+ ILock,
5
+ LockAcquireOptions,
6
+ LockHandle,
7
+ } from '@objectstack/spec/contracts';
8
+
9
+ /**
10
+ * In-memory lock for single-process deployments and tests.
11
+ *
12
+ * Behavior:
13
+ * - Per-key FIFO wait queue (so `waitMs > 0` callers receive the lock
14
+ * in arrival order).
15
+ * - TTL is honored: if a holder doesn't renew before `ttlMs` elapses,
16
+ * the lock is auto-released and the next waiter wakes.
17
+ * - Fencing tokens are process-local monotonic bigints.
18
+ */
19
+
20
+ const DEFAULT_TTL_MS = 15_000;
21
+
22
+ export interface MemoryLockOptions {
23
+ /** Default TTL for `acquire` when caller doesn't supply one. */
24
+ defaultTtlMs?: number;
25
+ }
26
+
27
+ interface Holder {
28
+ fencingToken: bigint;
29
+ expiresAt: number;
30
+ released: boolean;
31
+ timer?: NodeJS.Timeout;
32
+ }
33
+
34
+ interface Waiter {
35
+ resolve: (h: LockHandle | null) => void;
36
+ deadline: number;
37
+ opts: LockAcquireOptions;
38
+ timer?: NodeJS.Timeout;
39
+ }
40
+
41
+ export class MemoryLock implements ILock {
42
+ private readonly holders = new Map<string, Holder>();
43
+ private readonly queues = new Map<string, Waiter[]>();
44
+ private readonly defaultTtlMs: number;
45
+ private fenceSeq = 0n;
46
+ private closed = false;
47
+
48
+ constructor(opts: MemoryLockOptions = {}) {
49
+ this.defaultTtlMs = opts.defaultTtlMs ?? DEFAULT_TTL_MS;
50
+ }
51
+
52
+ async acquire(key: string, opts: LockAcquireOptions = {}): Promise<LockHandle | null> {
53
+ if (this.closed) throw new Error('MemoryLock is closed');
54
+ const ttlMs = opts.ttlMs ?? this.defaultTtlMs;
55
+ const waitMs = opts.waitMs ?? 0;
56
+
57
+ if (!this.holders.has(key)) {
58
+ return this.grant(key, ttlMs);
59
+ }
60
+ if (waitMs <= 0) return null;
61
+
62
+ return new Promise<LockHandle | null>((resolve) => {
63
+ const deadline = Date.now() + waitMs;
64
+ const waiter: Waiter = { resolve, deadline, opts };
65
+ const queue = this.queues.get(key) ?? [];
66
+ queue.push(waiter);
67
+ this.queues.set(key, queue);
68
+ waiter.timer = setTimeout(() => {
69
+ const q = this.queues.get(key);
70
+ if (q) {
71
+ const idx = q.indexOf(waiter);
72
+ if (idx >= 0) q.splice(idx, 1);
73
+ }
74
+ resolve(null);
75
+ }, waitMs);
76
+ });
77
+ }
78
+
79
+ async withLock<T>(
80
+ key: string,
81
+ fn: (h: LockHandle) => Promise<T>,
82
+ opts?: LockAcquireOptions,
83
+ ): Promise<T | null> {
84
+ const handle = await this.acquire(key, opts);
85
+ if (!handle) return null;
86
+ try {
87
+ return await fn(handle);
88
+ } finally {
89
+ await handle.release();
90
+ }
91
+ }
92
+
93
+ async close(): Promise<void> {
94
+ this.closed = true;
95
+ for (const [, holder] of this.holders) {
96
+ if (holder.timer) clearTimeout(holder.timer);
97
+ holder.released = true;
98
+ }
99
+ this.holders.clear();
100
+ for (const [, q] of this.queues) {
101
+ for (const w of q) {
102
+ if (w.timer) clearTimeout(w.timer);
103
+ w.resolve(null);
104
+ }
105
+ }
106
+ this.queues.clear();
107
+ }
108
+
109
+ private grant(key: string, ttlMs: number): LockHandle {
110
+ const fencingToken = ++this.fenceSeq;
111
+ const holder: Holder = {
112
+ fencingToken,
113
+ expiresAt: Date.now() + ttlMs,
114
+ released: false,
115
+ };
116
+ holder.timer = setTimeout(() => this.expire(key, holder), ttlMs);
117
+ this.holders.set(key, holder);
118
+
119
+ const self = this;
120
+ const handle: LockHandle = {
121
+ key,
122
+ fencingToken,
123
+ isHeld: () => !holder.released && self.holders.get(key) === holder,
124
+ async renew(extendMs?: number) {
125
+ if (holder.released || self.holders.get(key) !== holder) {
126
+ throw new Error(`Lock "${key}" no longer held (fence=${fencingToken})`);
127
+ }
128
+ const next = extendMs ?? ttlMs;
129
+ holder.expiresAt = Date.now() + next;
130
+ if (holder.timer) clearTimeout(holder.timer);
131
+ holder.timer = setTimeout(() => self.expire(key, holder), next);
132
+ },
133
+ async release() {
134
+ if (holder.released || self.holders.get(key) !== holder) return;
135
+ holder.released = true;
136
+ if (holder.timer) clearTimeout(holder.timer);
137
+ self.holders.delete(key);
138
+ self.handoff(key);
139
+ },
140
+ };
141
+ return handle;
142
+ }
143
+
144
+ private expire(key: string, holder: Holder): void {
145
+ if (holder.released) return;
146
+ if (this.holders.get(key) !== holder) return;
147
+ holder.released = true;
148
+ this.holders.delete(key);
149
+ this.handoff(key);
150
+ }
151
+
152
+ private handoff(key: string): void {
153
+ const queue = this.queues.get(key);
154
+ if (!queue || queue.length === 0) return;
155
+ const next = queue.shift()!;
156
+ if (next.timer) clearTimeout(next.timer);
157
+ if (Date.now() > next.deadline) {
158
+ next.resolve(null);
159
+ this.handoff(key);
160
+ return;
161
+ }
162
+ const ttlMs = next.opts.ttlMs ?? this.defaultTtlMs;
163
+ next.resolve(this.grant(key, ttlMs));
164
+ if (queue.length === 0) this.queues.delete(key);
165
+ }
166
+ }
@@ -0,0 +1,65 @@
1
+ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2
+
3
+ import { describe, expect, it } from 'vitest';
4
+ import { runFullContract } from '../testing.js';
5
+ import { MemoryPubSub } from './pubsub.js';
6
+ import { MemoryLock } from './lock.js';
7
+ import { MemoryKV } from './kv.js';
8
+ import { MemoryCounter } from './counter.js';
9
+ import { defineCluster } from '../cluster.js';
10
+
11
+ runFullContract('memory', {
12
+ makePubSub: async () => new MemoryPubSub(),
13
+ makeLock: async () => new MemoryLock(),
14
+ makeKV: async () => new MemoryKV(),
15
+ makeCounter: async () => new MemoryCounter(),
16
+ });
17
+
18
+ describe('defineCluster(memory) smoke', () => {
19
+ it('builds a working facade with all four primitives', async () => {
20
+ const cluster = defineCluster({ driver: 'memory', nodeId: 'test-1' });
21
+ expect(cluster.nodeId).toBe('test-1');
22
+ expect(cluster.driver).toBe('memory');
23
+
24
+ // Round-trip through all four.
25
+ const received: unknown[] = [];
26
+ cluster.pubsub.subscribe('e', (m) => received.push(m.payload));
27
+ await cluster.pubsub.publish('e', 'hi');
28
+ expect(received).toEqual(['hi']);
29
+
30
+ const h = await cluster.lock.acquire('k');
31
+ expect(h).not.toBeNull();
32
+ await h!.release();
33
+
34
+ await cluster.kv.set('s', { ok: true });
35
+ expect((await cluster.kv.get('s'))?.value).toEqual({ ok: true });
36
+
37
+ expect(await cluster.counter.incr('seq')).toBe(1n);
38
+ expect(await cluster.counter.incr('seq')).toBe(2n);
39
+
40
+ await cluster.close();
41
+ });
42
+
43
+ it('auto-generates a nodeId when absent', () => {
44
+ const cluster = defineCluster();
45
+ expect(cluster.nodeId).toMatch(/^node-/);
46
+ void cluster.close();
47
+ });
48
+
49
+ it('rejects unknown drivers with a helpful message', () => {
50
+ expect(() => defineCluster({ driver: 'redis' })).toThrow(
51
+ /not registered/i,
52
+ );
53
+ });
54
+
55
+ it('PubSub messages carry the nodeId as fromNode', async () => {
56
+ const cluster = defineCluster({ driver: 'memory', nodeId: 'node-X' });
57
+ let from: string | undefined;
58
+ cluster.pubsub.subscribe('c', (m) => {
59
+ from = m.fromNode;
60
+ });
61
+ await cluster.pubsub.publish('c', 'p');
62
+ expect(from).toBe('node-X');
63
+ await cluster.close();
64
+ });
65
+ });