@objectstack/service-cluster 10.2.0 → 11.0.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.2.0 build /home/runner/work/framework/framework/packages/services/service-cluster
2
+ > @objectstack/service-cluster@11.0.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 165ms
18
- CJS dist/index.cjs 15.26 KB
17
+ ESM ⚡️ Build success in 987ms
18
+ CJS dist/index.cjs 15.68 KB
19
19
  CJS dist/testing.cjs 11.60 KB
20
- CJS dist/index.cjs.map 41.16 KB
20
+ CJS dist/index.cjs.map 43.08 KB
21
21
  CJS dist/testing.cjs.map 14.18 KB
22
- CJS ⚡️ Build success in 762ms
22
+ CJS ⚡️ Build success in 1000ms
23
23
  DTS Build start
24
- DTS ⚡️ Build success in 18788ms
25
- DTS dist/index.d.ts 9.12 KB
24
+ DTS ⚡️ Build success in 18458ms
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,60 @@
1
1
  # @objectstack/service-cluster
2
2
 
3
+ ## 11.0.0
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [ab5718a]
8
+ - Updated dependencies [4845c12]
9
+ - Updated dependencies [c1a754a]
10
+ - Updated dependencies [6fbe91f]
11
+ - Updated dependencies [715d667]
12
+ - Updated dependencies [5eef4cf]
13
+ - Updated dependencies [72759e1]
14
+ - Updated dependencies [6c4fbd9]
15
+ - Updated dependencies [ef3ed67]
16
+ - Updated dependencies [cd51229]
17
+ - Updated dependencies [7697a0e]
18
+ - Updated dependencies [e7e04f1]
19
+ - Updated dependencies [cfd5ac4]
20
+ - Updated dependencies [2be5c1f]
21
+ - Updated dependencies [ad143ce]
22
+ - Updated dependencies [5c4a8c8]
23
+ - Updated dependencies [3afaeed]
24
+ - Updated dependencies [8801c02]
25
+ - Updated dependencies [3d04e06]
26
+ - Updated dependencies [4a84c98]
27
+ - Updated dependencies [c715d25]
28
+ - Updated dependencies [aa33b02]
29
+ - Updated dependencies [d980f0d]
30
+ - Updated dependencies [a658523]
31
+ - Updated dependencies [82ff91c]
32
+ - Updated dependencies [638f472]
33
+ - @objectstack/spec@11.0.0
34
+ - @objectstack/core@11.0.0
35
+
36
+ ## 10.3.0
37
+
38
+ ### Minor Changes
39
+
40
+ - 2b355d5: feat(cluster): multi-node authorization gate (open mechanism)
41
+
42
+ `@objectstack/service-cluster` now exports `registerMultiNodeGate` /
43
+ `checkMultiNodeAllowed`: a distribution (e.g. the Enterprise Edition) can
44
+ register a gate that authorizes whether the runtime may enable a multi-node
45
+ (remote-driver) topology. The open framework ships no gate — multi-node is
46
+ always allowed.
47
+
48
+ `os serve` consults the gate before activating a remote cluster driver; on
49
+ denial it **downgrades to single-node (in-memory) rather than failing** —
50
+ multi-node is an add-on, never bricks the runtime. The framework holds zero
51
+ license logic; this is the open seam an EE license plugs into (cloud ADR-0022).
52
+
53
+ ### Patch Changes
54
+
55
+ - @objectstack/spec@10.3.0
56
+ - @objectstack/core@10.3.0
57
+
3
58
  ## 10.2.0
4
59
 
5
60
  ### Patch Changes
package/LICENSE CHANGED
@@ -1,93 +1,202 @@
1
- License text copyright (c) 2020 MariaDB Corporation Ab, All Rights Reserved.
2
- "Business Source License" is a trademark of MariaDB Corporation Ab.
3
-
4
- Parameters
5
-
6
- Licensor: ObjectStack AI LLC
7
- Licensed Work: ObjectStack Runtime: the BSL-licensed packages
8
- of the ObjectStack monorepo as listed in LICENSING.md.
9
- Copyright (c) 2026 ObjectStack AI LLC.
10
- Additional Use Grant: You may make production use of the Licensed Work, provided
11
- Your use does not include offering the Licensed Work to third
12
- parties on a hosted or embedded basis in order to compete with
13
- ObjectStack AI LLC's paid version(s) of the Licensed Work. For purposes
14
- of this license:
15
-
16
- A "competitive offering" is a Product that is offered to third
17
- parties on a paid basis, including through paid support
18
- arrangements, that significantly overlaps with the capabilities
19
- of ObjectStack AI LLC's paid version(s) of the Licensed Work. If Your
20
- Product is not a competitive offering when You first make it
21
- generally available, it will not become a competitive offering
22
- later due to ObjectStack AI LLC releasing a new version of the Licensed
23
- Work with additional capabilities. In addition, Products that
24
- are not provided on a paid basis are not competitive.
25
-
26
- "Product" means software that is offered to end users to manage
27
- in their own environments or offered as a service on a hosted
28
- basis.
29
-
30
- "Embedded" means including the source code or executable code
31
- from the Licensed Work in a competitive offering. "Embedded"
32
- also means packaging the competitive offering in such a way
33
- that the Licensed Work must be accessed or downloaded for the
34
- competitive offering to operate.
35
-
36
- Hosting or using the Licensed Work(s) for internal purposes
37
- within an organization is not considered a competitive
38
- offering. ObjectStack AI LLC considers your organization to include all
39
- of your affiliates under common control.
40
-
41
- For binding interpretive guidance on using ObjectStack AI LLC products
42
- under the Business Source License, please visit our FAQ.
43
- (see LICENSING.md in this repository)
44
- Change Date: Four years from the date the Licensed Work is published.
45
- Change License: Apache License, Version 2.0
46
-
47
- For information about alternative licensing arrangements for the Licensed Work,
48
- please contact licensing@objectstack.dev.
49
-
50
- Notice
51
-
52
- Business Source License 1.1
53
-
54
- Terms
55
-
56
- The Licensor hereby grants you the right to copy, modify, create derivative
57
- works, redistribute, and make non-production use of the Licensed Work. The
58
- Licensor may make an Additional Use Grant, above, permitting limited production use.
59
-
60
- Effective on the Change Date, or the fourth anniversary of the first publicly
61
- available distribution of a specific version of the Licensed Work under this
62
- License, whichever comes first, the Licensor hereby grants you rights under
63
- the terms of the Change License, and the rights granted in the paragraph
64
- above terminate.
65
-
66
- If your use of the Licensed Work does not comply with the requirements
67
- currently in effect as described in this License, you must purchase a
68
- commercial license from the Licensor, its affiliated entities, or authorized
69
- resellers, or you must refrain from using the Licensed Work.
70
-
71
- All copies of the original and modified Licensed Work, and derivative works
72
- of the Licensed Work, are subject to this License. This License applies
73
- separately for each version of the Licensed Work and the Change Date may vary
74
- for each version of the Licensed Work released by Licensor.
75
-
76
- You must conspicuously display this License on each original or modified copy
77
- of the Licensed Work. If you receive the Licensed Work in original or
78
- modified form from a third party, the terms and conditions set forth in this
79
- License apply to your use of that work.
80
-
81
- Any use of the Licensed Work in violation of this License will automatically
82
- terminate your rights under this License for the current and all other
83
- versions of the Licensed Work.
84
-
85
- This License does not grant you any right in any trademark or logo of
86
- Licensor or its affiliates (provided that you may use a trademark or logo of
87
- Licensor as expressly required by this License).
88
-
89
- TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
90
- AN "AS IS" BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
91
- EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
92
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
93
- TITLE.
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute
108
+ must include a readable copy of the attribution notices
109
+ contained within such NOTICE file, excluding those notices
110
+ that do not pertain to any part of the Derivative Works,
111
+ in at least one of the following places: within a NOTICE
112
+ text file distributed as part of the Derivative Works; within
113
+ the Source form or documentation, if provided along with
114
+ the Derivative Works; or, within a display generated by the
115
+ Derivative Works, if and wherever such third-party notices
116
+ normally appear. The contents of the NOTICE file are for
117
+ informational purposes only and do not modify the License.
118
+ You may add Your own attribution notices within Derivative
119
+ Works that You distribute, alongside or as an addendum to
120
+ the NOTICE text from the Work, provided that such additional
121
+ attribution notices cannot be construed as modifying the
122
+ License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 ObjectStack
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
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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AAc,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,WAAA,CAAY,KAAA,EAA4B,CAAC,CAAA,EAAG;AAL5C,IAAA,IAAA,CAAiB,KAAA,kBAAO,IAAI,GAAA,CAA+B,CAAA;AAG3D,IAAA,IAAA,CAAQ,OAAA,EAAS,KAAA;AAGb,IAAA,IAAA,CAAK,QAAA,mBACD,IAAA,CAAK,OAAA,UAAA,CACJ,CAAC,GAAA,EAAK,OAAA,EAAA,GAAY;AAEf,MAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,yCAAA,EAA4C,OAAO,CAAA,EAAA,CAAA,EAAM,GAAG,CAAA;AAAA,IAC9E,CAAA,GAAA;AACJ,IAAA,IAAA,CAAK,OAAA,EAAS,IAAA,CAAK,MAAA;AAAA,EACvB;AAAA,EAEA,MAAM,OAAA,CACF,OAAA,EACA,OAAA,EACA,KAAA,EACa;AACb,IAAA,GAAA,CAAI,IAAA,CAAK,MAAA,EAAQ,MAAM,IAAI,KAAA,CAAM,wBAAwB,CAAA;AACzD,IAAA,MAAM,OAAA,EAAS,IAAA,CAAK,IAAA,CAAK,GAAA,CAAI,OAAO,CAAA;AACpC,IAAA,GAAA,CAAI,CAAC,OAAA,GAAU,MAAA,CAAO,KAAA,IAAS,CAAA,EAAG,MAAA;AAClC,IAAA,MAAM,YAAA,EAAc,IAAA,CAAK,GAAA,CAAI,CAAA;AAE7B,IAAA,MAAM,SAAA,EAAW,KAAA,CAAM,IAAA,CAAK,MAAM,CAAA;AAClC,IAAA,IAAA,CAAA,MAAW,IAAA,GAAO,QAAA,EAAU;AACxB,MAAA,I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;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;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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D,YAAI,OAAO;AAAA,UACP,qFAAgF,QAAQ,MAAM;AAAA,QAClG;AAAA,MACJ,SAAS,KAAK;AACV,YAAI,OAAO;AAAA,UACP;AAAA,UACA;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ,CAAC;AAED,QAAI,KAAK,mBAAmB,YAAY;AACpC,UAAI;AACA,aAAK,SAAS;AAAA,MAClB,SAAS,KAAK;AACV,YAAI,OAAO;AAAA,UACP;AAAA,UACA;AAAA,QACJ;AAAA,MACJ;AACA,WAAK,SAAS;AAAA,IAClB,CAAC;AAAA,EACL;AACJ;","names":[]}
1
+ {"version":3,"sources":["../src/cluster.ts","../src/memory/pubsub.ts","../src/memory/lock.ts","../src/memory/kv.ts","../src/memory/counter.ts","../src/split-brain-guard.ts","../src/cluster-service-plugin.ts","../src/metadata-cluster-bridge-plugin.ts","../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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AQ,QAAQ,MAAM;AACxD,YAAI,OAAO;AAAA,UACP,qFAAgF,QAAQ,MAAM;AAAA,QAClG;AAAA,MACJ,SAAS,KAAK;AACV,YAAI,OAAO;AAAA,UACP;AAAA,UACA;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ,CAAC;AAED,QAAI,KAAK,mBAAmB,YAAY;AACpC,UAAI;AACA,aAAK,SAAS;AAAA,MAClB,SAAS,KAAK;AACV,YAAI,OAAO;AAAA,UACP;AAAA,UACA;AAAA,QACJ;AAAA,MACJ;AACA,WAAK,SAAS;AAAA,IAClB,CAAC;AAAA,EACL;AACJ;;;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.2.0",
3
+ "version": "11.0.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/spec": "10.2.0",
23
- "@objectstack/core": "10.2.0"
22
+ "@objectstack/core": "11.0.0",
23
+ "@objectstack/spec": "11.0.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
+ }