@objectstack/service-cluster 5.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +28 -0
- package/CHANGELOG.md +11 -0
- package/LICENSE +202 -0
- package/dist/index.cjs +444 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +203 -0
- package/dist/index.d.ts +203 -0
- package/dist/index.js +444 -0
- package/dist/index.js.map +1 -0
- package/dist/testing.cjs +264 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +15 -0
- package/dist/testing.d.ts +15 -0
- package/dist/testing.js +264 -0
- package/dist/testing.js.map +1 -0
- package/package.json +48 -0
- package/src/cluster-service-plugin.ts +77 -0
- package/src/cluster.ts +129 -0
- package/src/index.ts +52 -0
- package/src/memory/counter.ts +36 -0
- package/src/memory/kv.ts +115 -0
- package/src/memory/lock.ts +166 -0
- package/src/memory/memory.contract.test.ts +65 -0
- package/src/memory/pubsub.ts +106 -0
- package/src/metadata-cluster-bridge-plugin.ts +90 -0
- package/src/testing.ts +310 -0
- package/tsconfig.json +10 -0
- package/tsup.config.ts +14 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
// src/cluster.ts
|
|
2
|
+
import { ClusterCapabilityConfigSchema } from "@objectstack/spec/kernel";
|
|
3
|
+
|
|
4
|
+
// src/memory/pubsub.ts
|
|
5
|
+
var MemoryPubSub = class {
|
|
6
|
+
constructor(opts = {}) {
|
|
7
|
+
this.subs = /* @__PURE__ */ new Map();
|
|
8
|
+
this.closed = false;
|
|
9
|
+
this.onError = opts.onError ?? ((err, channel) => {
|
|
10
|
+
console.error(`[MemoryPubSub] handler error on channel "${channel}":`, err);
|
|
11
|
+
});
|
|
12
|
+
this.nodeId = opts.nodeId;
|
|
13
|
+
}
|
|
14
|
+
async publish(channel, payload, _opts) {
|
|
15
|
+
if (this.closed) throw new Error("MemoryPubSub is closed");
|
|
16
|
+
const bucket = this.subs.get(channel);
|
|
17
|
+
if (!bucket || bucket.size === 0) return;
|
|
18
|
+
const publishedAt = Date.now();
|
|
19
|
+
const snapshot = Array.from(bucket);
|
|
20
|
+
for (const sub of snapshot) {
|
|
21
|
+
try {
|
|
22
|
+
const result = sub.handler({
|
|
23
|
+
channel,
|
|
24
|
+
payload,
|
|
25
|
+
publishedAt,
|
|
26
|
+
fromNode: this.nodeId
|
|
27
|
+
});
|
|
28
|
+
if (result && typeof result.then === "function") {
|
|
29
|
+
result.catch((err) => this.onError(err, channel));
|
|
30
|
+
}
|
|
31
|
+
} catch (err) {
|
|
32
|
+
this.onError(err, channel);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
subscribe(channel, handler, _opts) {
|
|
37
|
+
if (this.closed) throw new Error("MemoryPubSub is closed");
|
|
38
|
+
let bucket = this.subs.get(channel);
|
|
39
|
+
if (!bucket) {
|
|
40
|
+
bucket = /* @__PURE__ */ new Set();
|
|
41
|
+
this.subs.set(channel, bucket);
|
|
42
|
+
}
|
|
43
|
+
const sub = { channel, handler };
|
|
44
|
+
bucket.add(sub);
|
|
45
|
+
let disposed = false;
|
|
46
|
+
return () => {
|
|
47
|
+
if (disposed) return;
|
|
48
|
+
disposed = true;
|
|
49
|
+
const b = this.subs.get(channel);
|
|
50
|
+
if (!b) return;
|
|
51
|
+
b.delete(sub);
|
|
52
|
+
if (b.size === 0) this.subs.delete(channel);
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
async close() {
|
|
56
|
+
this.closed = true;
|
|
57
|
+
this.subs.clear();
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
// src/memory/lock.ts
|
|
62
|
+
var DEFAULT_TTL_MS = 15e3;
|
|
63
|
+
var MemoryLock = class {
|
|
64
|
+
constructor(opts = {}) {
|
|
65
|
+
this.holders = /* @__PURE__ */ new Map();
|
|
66
|
+
this.queues = /* @__PURE__ */ new Map();
|
|
67
|
+
this.fenceSeq = 0n;
|
|
68
|
+
this.closed = false;
|
|
69
|
+
this.defaultTtlMs = opts.defaultTtlMs ?? DEFAULT_TTL_MS;
|
|
70
|
+
}
|
|
71
|
+
async acquire(key, opts = {}) {
|
|
72
|
+
if (this.closed) throw new Error("MemoryLock is closed");
|
|
73
|
+
const ttlMs = opts.ttlMs ?? this.defaultTtlMs;
|
|
74
|
+
const waitMs = opts.waitMs ?? 0;
|
|
75
|
+
if (!this.holders.has(key)) {
|
|
76
|
+
return this.grant(key, ttlMs);
|
|
77
|
+
}
|
|
78
|
+
if (waitMs <= 0) return null;
|
|
79
|
+
return new Promise((resolve) => {
|
|
80
|
+
const deadline = Date.now() + waitMs;
|
|
81
|
+
const waiter = { resolve, deadline, opts };
|
|
82
|
+
const queue = this.queues.get(key) ?? [];
|
|
83
|
+
queue.push(waiter);
|
|
84
|
+
this.queues.set(key, queue);
|
|
85
|
+
waiter.timer = setTimeout(() => {
|
|
86
|
+
const q = this.queues.get(key);
|
|
87
|
+
if (q) {
|
|
88
|
+
const idx = q.indexOf(waiter);
|
|
89
|
+
if (idx >= 0) q.splice(idx, 1);
|
|
90
|
+
}
|
|
91
|
+
resolve(null);
|
|
92
|
+
}, waitMs);
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
async withLock(key, fn, opts) {
|
|
96
|
+
const handle = await this.acquire(key, opts);
|
|
97
|
+
if (!handle) return null;
|
|
98
|
+
try {
|
|
99
|
+
return await fn(handle);
|
|
100
|
+
} finally {
|
|
101
|
+
await handle.release();
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
async close() {
|
|
105
|
+
this.closed = true;
|
|
106
|
+
for (const [, holder] of this.holders) {
|
|
107
|
+
if (holder.timer) clearTimeout(holder.timer);
|
|
108
|
+
holder.released = true;
|
|
109
|
+
}
|
|
110
|
+
this.holders.clear();
|
|
111
|
+
for (const [, q] of this.queues) {
|
|
112
|
+
for (const w of q) {
|
|
113
|
+
if (w.timer) clearTimeout(w.timer);
|
|
114
|
+
w.resolve(null);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
this.queues.clear();
|
|
118
|
+
}
|
|
119
|
+
grant(key, ttlMs) {
|
|
120
|
+
const fencingToken = ++this.fenceSeq;
|
|
121
|
+
const holder = {
|
|
122
|
+
fencingToken,
|
|
123
|
+
expiresAt: Date.now() + ttlMs,
|
|
124
|
+
released: false
|
|
125
|
+
};
|
|
126
|
+
holder.timer = setTimeout(() => this.expire(key, holder), ttlMs);
|
|
127
|
+
this.holders.set(key, holder);
|
|
128
|
+
const self = this;
|
|
129
|
+
const handle = {
|
|
130
|
+
key,
|
|
131
|
+
fencingToken,
|
|
132
|
+
isHeld: () => !holder.released && self.holders.get(key) === holder,
|
|
133
|
+
async renew(extendMs) {
|
|
134
|
+
if (holder.released || self.holders.get(key) !== holder) {
|
|
135
|
+
throw new Error(`Lock "${key}" no longer held (fence=${fencingToken})`);
|
|
136
|
+
}
|
|
137
|
+
const next = extendMs ?? ttlMs;
|
|
138
|
+
holder.expiresAt = Date.now() + next;
|
|
139
|
+
if (holder.timer) clearTimeout(holder.timer);
|
|
140
|
+
holder.timer = setTimeout(() => self.expire(key, holder), next);
|
|
141
|
+
},
|
|
142
|
+
async release() {
|
|
143
|
+
if (holder.released || self.holders.get(key) !== holder) return;
|
|
144
|
+
holder.released = true;
|
|
145
|
+
if (holder.timer) clearTimeout(holder.timer);
|
|
146
|
+
self.holders.delete(key);
|
|
147
|
+
self.handoff(key);
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
return handle;
|
|
151
|
+
}
|
|
152
|
+
expire(key, holder) {
|
|
153
|
+
if (holder.released) return;
|
|
154
|
+
if (this.holders.get(key) !== holder) return;
|
|
155
|
+
holder.released = true;
|
|
156
|
+
this.holders.delete(key);
|
|
157
|
+
this.handoff(key);
|
|
158
|
+
}
|
|
159
|
+
handoff(key) {
|
|
160
|
+
const queue = this.queues.get(key);
|
|
161
|
+
if (!queue || queue.length === 0) return;
|
|
162
|
+
const next = queue.shift();
|
|
163
|
+
if (next.timer) clearTimeout(next.timer);
|
|
164
|
+
if (Date.now() > next.deadline) {
|
|
165
|
+
next.resolve(null);
|
|
166
|
+
this.handoff(key);
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
const ttlMs = next.opts.ttlMs ?? this.defaultTtlMs;
|
|
170
|
+
next.resolve(this.grant(key, ttlMs));
|
|
171
|
+
if (queue.length === 0) this.queues.delete(key);
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
// src/memory/kv.ts
|
|
176
|
+
var MemoryKV = class {
|
|
177
|
+
constructor() {
|
|
178
|
+
this.store = /* @__PURE__ */ new Map();
|
|
179
|
+
this.closed = false;
|
|
180
|
+
}
|
|
181
|
+
async get(key) {
|
|
182
|
+
const e = this.store.get(key);
|
|
183
|
+
if (!e) return void 0;
|
|
184
|
+
if (e.expiresAt && Date.now() >= e.expiresAt) {
|
|
185
|
+
this.store.delete(key);
|
|
186
|
+
return void 0;
|
|
187
|
+
}
|
|
188
|
+
return {
|
|
189
|
+
key,
|
|
190
|
+
value: e.value,
|
|
191
|
+
version: e.version,
|
|
192
|
+
expiresAt: e.expiresAt
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
async set(key, value, opts = {}) {
|
|
196
|
+
if (this.closed) throw new Error("MemoryKV is closed");
|
|
197
|
+
const existing = this.store.get(key);
|
|
198
|
+
const existingVersion = existing ? existing.expiresAt && Date.now() >= existing.expiresAt ? 0n : existing.version : 0n;
|
|
199
|
+
if (opts.ifVersion !== void 0 && opts.ifVersion !== existingVersion) {
|
|
200
|
+
throw new VersionMismatchError(key, opts.ifVersion, existingVersion);
|
|
201
|
+
}
|
|
202
|
+
if (existing?.timer) clearTimeout(existing.timer);
|
|
203
|
+
const version = existingVersion + 1n;
|
|
204
|
+
const expiresAt = opts.ttl && opts.ttl > 0 ? Date.now() + opts.ttl * 1e3 : void 0;
|
|
205
|
+
const entry = { value, version, expiresAt };
|
|
206
|
+
if (expiresAt) {
|
|
207
|
+
entry.timer = setTimeout(() => {
|
|
208
|
+
const current = this.store.get(key);
|
|
209
|
+
if (current === entry) this.store.delete(key);
|
|
210
|
+
}, expiresAt - Date.now());
|
|
211
|
+
}
|
|
212
|
+
this.store.set(key, entry);
|
|
213
|
+
return { key, value, version, expiresAt };
|
|
214
|
+
}
|
|
215
|
+
async delete(key, opts = {}) {
|
|
216
|
+
const e = this.store.get(key);
|
|
217
|
+
if (!e) return false;
|
|
218
|
+
if (e.expiresAt && Date.now() >= e.expiresAt) {
|
|
219
|
+
this.store.delete(key);
|
|
220
|
+
return false;
|
|
221
|
+
}
|
|
222
|
+
if (opts.ifVersion !== void 0 && opts.ifVersion !== e.version) {
|
|
223
|
+
throw new VersionMismatchError(key, opts.ifVersion, e.version);
|
|
224
|
+
}
|
|
225
|
+
if (e.timer) clearTimeout(e.timer);
|
|
226
|
+
this.store.delete(key);
|
|
227
|
+
return true;
|
|
228
|
+
}
|
|
229
|
+
async cas(key, expectedVersion, next, opts = {}) {
|
|
230
|
+
try {
|
|
231
|
+
return await this.set(key, next, { ...opts, ifVersion: expectedVersion });
|
|
232
|
+
} catch (err) {
|
|
233
|
+
if (err instanceof VersionMismatchError) return void 0;
|
|
234
|
+
throw err;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
async close() {
|
|
238
|
+
this.closed = true;
|
|
239
|
+
for (const [, e] of this.store) {
|
|
240
|
+
if (e.timer) clearTimeout(e.timer);
|
|
241
|
+
}
|
|
242
|
+
this.store.clear();
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
var VersionMismatchError = class extends Error {
|
|
246
|
+
constructor(key, expected, actual) {
|
|
247
|
+
super(
|
|
248
|
+
`KV version mismatch on "${key}": expected v${expected}, found v${actual}`
|
|
249
|
+
);
|
|
250
|
+
this.key = key;
|
|
251
|
+
this.expected = expected;
|
|
252
|
+
this.actual = actual;
|
|
253
|
+
this.name = "VersionMismatchError";
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
// src/memory/counter.ts
|
|
258
|
+
var MemoryCounter = class {
|
|
259
|
+
constructor() {
|
|
260
|
+
this.counters = /* @__PURE__ */ new Map();
|
|
261
|
+
this.closed = false;
|
|
262
|
+
}
|
|
263
|
+
async incr(key, opts = {}) {
|
|
264
|
+
if (this.closed) throw new Error("MemoryCounter is closed");
|
|
265
|
+
const by = BigInt(opts.by ?? 1);
|
|
266
|
+
const current = this.counters.get(key) ?? 0n;
|
|
267
|
+
const next = current + by;
|
|
268
|
+
this.counters.set(key, next);
|
|
269
|
+
return next;
|
|
270
|
+
}
|
|
271
|
+
async peek(key) {
|
|
272
|
+
return this.counters.get(key) ?? 0n;
|
|
273
|
+
}
|
|
274
|
+
async reset(key, value = 0n) {
|
|
275
|
+
if (this.closed) throw new Error("MemoryCounter is closed");
|
|
276
|
+
if (value === 0n) this.counters.delete(key);
|
|
277
|
+
else this.counters.set(key, value);
|
|
278
|
+
}
|
|
279
|
+
async close() {
|
|
280
|
+
this.closed = true;
|
|
281
|
+
this.counters.clear();
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
// src/cluster.ts
|
|
286
|
+
var ComposedClusterService = class {
|
|
287
|
+
constructor(nodeId, driver, pubsub, lock, kv, counter) {
|
|
288
|
+
this.nodeId = nodeId;
|
|
289
|
+
this.driver = driver;
|
|
290
|
+
this.pubsub = pubsub;
|
|
291
|
+
this.lock = lock;
|
|
292
|
+
this.kv = kv;
|
|
293
|
+
this.counter = counter;
|
|
294
|
+
}
|
|
295
|
+
async close() {
|
|
296
|
+
const closers = [this.counter, this.kv, this.lock, this.pubsub];
|
|
297
|
+
for (const c of closers) {
|
|
298
|
+
try {
|
|
299
|
+
await c.close();
|
|
300
|
+
} catch (err) {
|
|
301
|
+
console.error("[ClusterService] close error:", err);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
function defineCluster(config = {}) {
|
|
307
|
+
const parsed = ClusterCapabilityConfigSchema.parse(config);
|
|
308
|
+
const nodeId = parsed.nodeId ?? generateNodeId();
|
|
309
|
+
if (parsed.driver === "memory") {
|
|
310
|
+
return new ComposedClusterService(
|
|
311
|
+
nodeId,
|
|
312
|
+
"memory",
|
|
313
|
+
new MemoryPubSub({ nodeId }),
|
|
314
|
+
new MemoryLock({ defaultTtlMs: parsed.lockTtlMs }),
|
|
315
|
+
new MemoryKV(),
|
|
316
|
+
new MemoryCounter()
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
const factory = driverRegistry.get(parsed.driver);
|
|
320
|
+
if (!factory) {
|
|
321
|
+
throw new Error(
|
|
322
|
+
`Cluster driver "${parsed.driver}" is not registered. Did you forget to import @objectstack/service-cluster-${parsed.driver} or call registerClusterDriver()? See content/docs/concepts/cluster-semantics.mdx \xA76.`
|
|
323
|
+
);
|
|
324
|
+
}
|
|
325
|
+
return factory({ ...parsed, nodeId });
|
|
326
|
+
}
|
|
327
|
+
var driverRegistry = /* @__PURE__ */ new Map();
|
|
328
|
+
function registerClusterDriver(name, factory) {
|
|
329
|
+
if (name === "memory") {
|
|
330
|
+
throw new Error('The "memory" driver is reserved.');
|
|
331
|
+
}
|
|
332
|
+
driverRegistry.set(name, factory);
|
|
333
|
+
}
|
|
334
|
+
function generateNodeId() {
|
|
335
|
+
const rand = Math.random().toString(36).slice(2, 10);
|
|
336
|
+
const ts = Date.now().toString(36);
|
|
337
|
+
return `node-${ts}-${rand}`;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// src/cluster-service-plugin.ts
|
|
341
|
+
var ClusterServicePlugin = class {
|
|
342
|
+
constructor(options = {}) {
|
|
343
|
+
this.name = "com.objectstack.service.cluster";
|
|
344
|
+
this.version = "1.0.0";
|
|
345
|
+
this.type = "standard";
|
|
346
|
+
this.owned = false;
|
|
347
|
+
this.options = options;
|
|
348
|
+
}
|
|
349
|
+
async init(ctx) {
|
|
350
|
+
if (this.options.cluster) {
|
|
351
|
+
this.cluster = this.options.cluster;
|
|
352
|
+
this.owned = false;
|
|
353
|
+
} else {
|
|
354
|
+
this.cluster = defineCluster(this.options.config ?? {});
|
|
355
|
+
this.owned = true;
|
|
356
|
+
}
|
|
357
|
+
ctx.registerService("cluster", this.cluster);
|
|
358
|
+
ctx.logger.info(
|
|
359
|
+
`ClusterServicePlugin: registered "${this.cluster.driver}" driver (node=${this.cluster.nodeId})`
|
|
360
|
+
);
|
|
361
|
+
ctx.hook("kernel:shutdown", async () => {
|
|
362
|
+
if (this.owned && this.cluster) {
|
|
363
|
+
try {
|
|
364
|
+
await this.cluster.close();
|
|
365
|
+
} catch (err) {
|
|
366
|
+
ctx.logger.error("ClusterServicePlugin: close error", err);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
|
|
373
|
+
// src/metadata-cluster-bridge-plugin.ts
|
|
374
|
+
var MetadataClusterBridgePlugin = class {
|
|
375
|
+
constructor() {
|
|
376
|
+
this.name = "com.objectstack.service.metadata-cluster-bridge";
|
|
377
|
+
this.version = "1.0.0";
|
|
378
|
+
this.type = "standard";
|
|
379
|
+
}
|
|
380
|
+
async init(ctx) {
|
|
381
|
+
ctx.hook("kernel:ready", async () => {
|
|
382
|
+
let cluster;
|
|
383
|
+
let md;
|
|
384
|
+
try {
|
|
385
|
+
cluster = ctx.getService("cluster");
|
|
386
|
+
} catch {
|
|
387
|
+
ctx.logger.debug(
|
|
388
|
+
'MetadataClusterBridgePlugin: no "cluster" service registered, skipping'
|
|
389
|
+
);
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
try {
|
|
393
|
+
md = ctx.getService("metadata");
|
|
394
|
+
} catch {
|
|
395
|
+
ctx.logger.debug(
|
|
396
|
+
'MetadataClusterBridgePlugin: no "metadata" service registered, skipping'
|
|
397
|
+
);
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
const attach = md.attachClusterPubSub;
|
|
401
|
+
if (typeof attach !== "function") {
|
|
402
|
+
ctx.logger.warn(
|
|
403
|
+
"MetadataClusterBridgePlugin: metadata service does not expose attachClusterPubSub(); cross-node cache invalidation disabled"
|
|
404
|
+
);
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
try {
|
|
408
|
+
this.detach = attach.call(md, cluster.pubsub, cluster.nodeId);
|
|
409
|
+
ctx.logger.info(
|
|
410
|
+
`MetadataClusterBridgePlugin: bridged metadata.changed \u2192 cluster.pubsub (node=${cluster.nodeId})`
|
|
411
|
+
);
|
|
412
|
+
} catch (err) {
|
|
413
|
+
ctx.logger.error(
|
|
414
|
+
"MetadataClusterBridgePlugin: attach failed",
|
|
415
|
+
err
|
|
416
|
+
);
|
|
417
|
+
}
|
|
418
|
+
});
|
|
419
|
+
ctx.hook("kernel:shutdown", async () => {
|
|
420
|
+
try {
|
|
421
|
+
this.detach?.();
|
|
422
|
+
} catch (err) {
|
|
423
|
+
ctx.logger.error(
|
|
424
|
+
"MetadataClusterBridgePlugin: detach error",
|
|
425
|
+
err
|
|
426
|
+
);
|
|
427
|
+
}
|
|
428
|
+
this.detach = void 0;
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
export {
|
|
433
|
+
ClusterServicePlugin,
|
|
434
|
+
ComposedClusterService,
|
|
435
|
+
MemoryCounter,
|
|
436
|
+
MemoryKV,
|
|
437
|
+
MemoryLock,
|
|
438
|
+
MemoryPubSub,
|
|
439
|
+
MetadataClusterBridgePlugin,
|
|
440
|
+
VersionMismatchError,
|
|
441
|
+
defineCluster,
|
|
442
|
+
registerClusterDriver
|
|
443
|
+
};
|
|
444
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cluster.ts","../src/memory/pubsub.ts","../src/memory/lock.ts","../src/memory/kv.ts","../src/memory/counter.ts","../src/cluster-service-plugin.ts","../src/metadata-cluster-bridge-plugin.ts"],"sourcesContent":["// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type {\n IClusterService,\n IPubSub,\n ILock,\n IKV,\n ICounter,\n} from '@objectstack/spec/contracts';\nimport type { ClusterCapabilityConfigInput } from '@objectstack/spec/kernel';\nimport { ClusterCapabilityConfigSchema } from '@objectstack/spec/kernel';\n\nimport { MemoryPubSub } from './memory/pubsub.js';\nimport { MemoryLock } from './memory/lock.js';\nimport { MemoryKV } from './memory/kv.js';\nimport { MemoryCounter } from './memory/counter.js';\n\n/**\n * Compose four cluster primitives into a single `IClusterService` facade.\n * Useful for custom driver authors who want to mix and match.\n */\nexport class ComposedClusterService implements IClusterService {\n constructor(\n public readonly nodeId: string,\n public readonly driver: string,\n public readonly pubsub: IPubSub,\n public readonly lock: ILock,\n public readonly kv: IKV,\n public readonly counter: ICounter,\n ) { }\n\n async close(): Promise<void> {\n // Reverse order, swallow errors so a slow close doesn't block siblings.\n const closers = [this.counter, this.kv, this.lock, this.pubsub];\n for (const c of closers) {\n try {\n await c.close();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[ClusterService] close error:', err);\n }\n }\n }\n}\n\n/**\n * Build an `IClusterService` from a `ClusterCapabilityConfig`. The only\n * driver shipped from this package is `memory`; other drivers (postgres,\n * redis, nats) live in dedicated packages and register themselves via\n * `registerClusterDriver()`.\n *\n * @example\n * const cluster = defineCluster({ driver: 'memory' });\n * await cluster.pubsub.publish('metadata.changed', { id: 'x' });\n */\nexport function defineCluster(\n config: ClusterCapabilityConfigInput = {},\n): IClusterService {\n const parsed = ClusterCapabilityConfigSchema.parse(config);\n const nodeId = parsed.nodeId ?? generateNodeId();\n\n if (parsed.driver === 'memory') {\n return new ComposedClusterService(\n nodeId,\n 'memory',\n new MemoryPubSub({ nodeId }),\n new MemoryLock({ defaultTtlMs: parsed.lockTtlMs }),\n new MemoryKV(),\n new MemoryCounter(),\n );\n }\n\n const factory = driverRegistry.get(parsed.driver);\n if (!factory) {\n throw new Error(\n `Cluster driver \"${parsed.driver}\" is not registered. ` +\n `Did you forget to import @objectstack/service-cluster-${parsed.driver} ` +\n `or call registerClusterDriver()? ` +\n `See content/docs/concepts/cluster-semantics.mdx §6.`,\n );\n }\n return factory({ ...parsed, nodeId });\n}\n\n// ---------------------------------------------------------------------------\n// Driver registry (for postgres/redis/nats/custom drivers)\n// ---------------------------------------------------------------------------\n\nexport interface DriverFactoryConfig {\n driver: string;\n nodeId: string;\n url?: string;\n useExistingPool?: boolean;\n heartbeatMs?: number;\n lockTtlMs?: number;\n tenantIsolation?: string;\n driverOptions?: Record<string, unknown>;\n}\n\nexport type ClusterDriverFactory = (config: DriverFactoryConfig) => IClusterService;\n\nconst driverRegistry = new Map<string, ClusterDriverFactory>();\n\n/**\n * Register a custom cluster driver. Driver packages (e.g.\n * `@objectstack/service-cluster-postgres`) should call this at module\n * load time so `defineCluster({ driver: 'postgres' })` resolves them.\n */\nexport function registerClusterDriver(\n name: string,\n factory: ClusterDriverFactory,\n): void {\n if (name === 'memory') {\n throw new Error('The \"memory\" driver is reserved.');\n }\n driverRegistry.set(name, factory);\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction generateNodeId(): string {\n // Avoid the `crypto` import dance for a single use; this is dev-only\n // randomness and the driver upgrades replace it.\n const rand = Math.random().toString(36).slice(2, 10);\n const ts = Date.now().toString(36);\n return `node-${ts}-${rand}`;\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type {\n IPubSub,\n PubSubHandler,\n PublishOptions,\n SubscribeOptions,\n Unsubscribe,\n} from '@objectstack/spec/contracts';\n\n/**\n * In-memory PubSub for single-process deployments and tests.\n *\n * Behavior:\n * - Synchronous fan-out: every subscriber's handler is invoked in the\n * same tick that `publish()` resolves. Handler errors are swallowed\n * and logged via `onError` (so one bad subscriber can't poison the bus).\n * - At-least-once semantics held vacuously (a single in-process delivery).\n * - No cross-process delivery — use the redis/postgres/nats driver for\n * real multi-node setups.\n */\nexport interface MemoryPubSubOptions {\n /** Optional error sink for handler exceptions. Defaults to console.error. */\n onError?: (err: unknown, channel: string) => void;\n /** Optional node id surfaced as `fromNode` on every message. */\n nodeId?: string;\n}\n\ninterface Subscription {\n channel: string;\n handler: PubSubHandler<unknown>;\n}\n\nexport class MemoryPubSub implements IPubSub {\n private readonly subs = new Map<string, Set<Subscription>>();\n private readonly onError: (err: unknown, channel: string) => void;\n private readonly nodeId?: string;\n private closed = false;\n\n constructor(opts: MemoryPubSubOptions = {}) {\n this.onError =\n opts.onError ??\n ((err, channel) => {\n // eslint-disable-next-line no-console\n console.error(`[MemoryPubSub] handler error on channel \"${channel}\":`, err);\n });\n this.nodeId = opts.nodeId;\n }\n\n async publish<T = unknown>(\n channel: string,\n payload: T,\n _opts?: PublishOptions,\n ): Promise<void> {\n if (this.closed) throw new Error('MemoryPubSub is closed');\n const bucket = this.subs.get(channel);\n if (!bucket || bucket.size === 0) return;\n const publishedAt = Date.now();\n // Snapshot so handler-driven unsubscribes during dispatch are safe.\n const snapshot = Array.from(bucket);\n for (const sub of snapshot) {\n try {\n const result = sub.handler({\n channel,\n payload,\n publishedAt,\n fromNode: this.nodeId,\n });\n if (result && typeof (result as Promise<void>).then === 'function') {\n (result as Promise<void>).catch((err) => this.onError(err, channel));\n }\n } catch (err) {\n this.onError(err, channel);\n }\n }\n }\n\n subscribe<T = unknown>(\n channel: string,\n handler: PubSubHandler<T>,\n _opts?: SubscribeOptions,\n ): Unsubscribe {\n if (this.closed) throw new Error('MemoryPubSub is closed');\n let bucket = this.subs.get(channel);\n if (!bucket) {\n bucket = new Set();\n this.subs.set(channel, bucket);\n }\n const sub: Subscription = { channel, handler: handler as PubSubHandler<unknown> };\n bucket.add(sub);\n let disposed = false;\n return () => {\n if (disposed) return;\n disposed = true;\n const b = this.subs.get(channel);\n if (!b) return;\n b.delete(sub);\n if (b.size === 0) this.subs.delete(channel);\n };\n }\n\n async close(): Promise<void> {\n this.closed = true;\n this.subs.clear();\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type {\n ILock,\n LockAcquireOptions,\n LockHandle,\n} from '@objectstack/spec/contracts';\n\n/**\n * In-memory lock for single-process deployments and tests.\n *\n * Behavior:\n * - Per-key FIFO wait queue (so `waitMs > 0` callers receive the lock\n * in arrival order).\n * - TTL is honored: if a holder doesn't renew before `ttlMs` elapses,\n * the lock is auto-released and the next waiter wakes.\n * - Fencing tokens are process-local monotonic bigints.\n */\n\nconst DEFAULT_TTL_MS = 15_000;\n\nexport interface MemoryLockOptions {\n /** Default TTL for `acquire` when caller doesn't supply one. */\n defaultTtlMs?: number;\n}\n\ninterface Holder {\n fencingToken: bigint;\n expiresAt: number;\n released: boolean;\n timer?: NodeJS.Timeout;\n}\n\ninterface Waiter {\n resolve: (h: LockHandle | null) => void;\n deadline: number;\n opts: LockAcquireOptions;\n timer?: NodeJS.Timeout;\n}\n\nexport class MemoryLock implements ILock {\n private readonly holders = new Map<string, Holder>();\n private readonly queues = new Map<string, Waiter[]>();\n private readonly defaultTtlMs: number;\n private fenceSeq = 0n;\n private closed = false;\n\n constructor(opts: MemoryLockOptions = {}) {\n this.defaultTtlMs = opts.defaultTtlMs ?? DEFAULT_TTL_MS;\n }\n\n async acquire(key: string, opts: LockAcquireOptions = {}): Promise<LockHandle | null> {\n if (this.closed) throw new Error('MemoryLock is closed');\n const ttlMs = opts.ttlMs ?? this.defaultTtlMs;\n const waitMs = opts.waitMs ?? 0;\n\n if (!this.holders.has(key)) {\n return this.grant(key, ttlMs);\n }\n if (waitMs <= 0) return null;\n\n return new Promise<LockHandle | null>((resolve) => {\n const deadline = Date.now() + waitMs;\n const waiter: Waiter = { resolve, deadline, opts };\n const queue = this.queues.get(key) ?? [];\n queue.push(waiter);\n this.queues.set(key, queue);\n waiter.timer = setTimeout(() => {\n const q = this.queues.get(key);\n if (q) {\n const idx = q.indexOf(waiter);\n if (idx >= 0) q.splice(idx, 1);\n }\n resolve(null);\n }, waitMs);\n });\n }\n\n async withLock<T>(\n key: string,\n fn: (h: LockHandle) => Promise<T>,\n opts?: LockAcquireOptions,\n ): Promise<T | null> {\n const handle = await this.acquire(key, opts);\n if (!handle) return null;\n try {\n return await fn(handle);\n } finally {\n await handle.release();\n }\n }\n\n async close(): Promise<void> {\n this.closed = true;\n for (const [, holder] of this.holders) {\n if (holder.timer) clearTimeout(holder.timer);\n holder.released = true;\n }\n this.holders.clear();\n for (const [, q] of this.queues) {\n for (const w of q) {\n if (w.timer) clearTimeout(w.timer);\n w.resolve(null);\n }\n }\n this.queues.clear();\n }\n\n private grant(key: string, ttlMs: number): LockHandle {\n const fencingToken = ++this.fenceSeq;\n const holder: Holder = {\n fencingToken,\n expiresAt: Date.now() + ttlMs,\n released: false,\n };\n holder.timer = setTimeout(() => this.expire(key, holder), ttlMs);\n this.holders.set(key, holder);\n\n const self = this;\n const handle: LockHandle = {\n key,\n fencingToken,\n isHeld: () => !holder.released && self.holders.get(key) === holder,\n async renew(extendMs?: number) {\n if (holder.released || self.holders.get(key) !== holder) {\n throw new Error(`Lock \"${key}\" no longer held (fence=${fencingToken})`);\n }\n const next = extendMs ?? ttlMs;\n holder.expiresAt = Date.now() + next;\n if (holder.timer) clearTimeout(holder.timer);\n holder.timer = setTimeout(() => self.expire(key, holder), next);\n },\n async release() {\n if (holder.released || self.holders.get(key) !== holder) return;\n holder.released = true;\n if (holder.timer) clearTimeout(holder.timer);\n self.holders.delete(key);\n self.handoff(key);\n },\n };\n return handle;\n }\n\n private expire(key: string, holder: Holder): void {\n if (holder.released) return;\n if (this.holders.get(key) !== holder) return;\n holder.released = true;\n this.holders.delete(key);\n this.handoff(key);\n }\n\n private handoff(key: string): void {\n const queue = this.queues.get(key);\n if (!queue || queue.length === 0) return;\n const next = queue.shift()!;\n if (next.timer) clearTimeout(next.timer);\n if (Date.now() > next.deadline) {\n next.resolve(null);\n this.handoff(key);\n return;\n }\n const ttlMs = next.opts.ttlMs ?? this.defaultTtlMs;\n next.resolve(this.grant(key, ttlMs));\n if (queue.length === 0) this.queues.delete(key);\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { IKV, KVEntry, KVSetOptions } from '@objectstack/spec/contracts';\n\ninterface Entry<T = unknown> {\n value: T;\n version: bigint;\n expiresAt?: number;\n timer?: NodeJS.Timeout;\n}\n\n/**\n * In-memory coordination KV. Supports optimistic concurrency via\n * `ifVersion` and TTL via `ttl` (seconds).\n *\n * NOT a cache, NOT a database — intended for small cluster bookkeeping.\n */\nexport class MemoryKV implements IKV {\n private readonly store = new Map<string, Entry>();\n private closed = false;\n\n async get<T = unknown>(key: string): Promise<KVEntry<T> | undefined> {\n const e = this.store.get(key);\n if (!e) return undefined;\n if (e.expiresAt && Date.now() >= e.expiresAt) {\n this.store.delete(key);\n return undefined;\n }\n return {\n key,\n value: e.value as T,\n version: e.version,\n expiresAt: e.expiresAt,\n };\n }\n\n async set<T = unknown>(\n key: string,\n value: T,\n opts: KVSetOptions = {},\n ): Promise<KVEntry<T>> {\n if (this.closed) throw new Error('MemoryKV is closed');\n const existing = this.store.get(key);\n const existingVersion = existing\n ? existing.expiresAt && Date.now() >= existing.expiresAt\n ? 0n\n : existing.version\n : 0n;\n if (opts.ifVersion !== undefined && opts.ifVersion !== existingVersion) {\n throw new VersionMismatchError(key, opts.ifVersion, existingVersion);\n }\n if (existing?.timer) clearTimeout(existing.timer);\n const version = existingVersion + 1n;\n const expiresAt = opts.ttl && opts.ttl > 0 ? Date.now() + opts.ttl * 1000 : undefined;\n const entry: Entry<T> = { value, version, expiresAt };\n if (expiresAt) {\n entry.timer = setTimeout(() => {\n const current = this.store.get(key);\n if (current === (entry as Entry<unknown>)) this.store.delete(key);\n }, expiresAt - Date.now());\n }\n this.store.set(key, entry as Entry<unknown>);\n return { key, value, version, expiresAt };\n }\n\n async delete(key: string, opts: { ifVersion?: bigint } = {}): Promise<boolean> {\n const e = this.store.get(key);\n if (!e) return false;\n if (e.expiresAt && Date.now() >= e.expiresAt) {\n this.store.delete(key);\n return false;\n }\n if (opts.ifVersion !== undefined && opts.ifVersion !== e.version) {\n throw new VersionMismatchError(key, opts.ifVersion, e.version);\n }\n if (e.timer) clearTimeout(e.timer);\n this.store.delete(key);\n return true;\n }\n\n async cas<T = unknown>(\n key: string,\n expectedVersion: bigint,\n next: T,\n opts: Omit<KVSetOptions, 'ifVersion'> = {},\n ): Promise<KVEntry<T> | undefined> {\n try {\n return await this.set(key, next, { ...opts, ifVersion: expectedVersion });\n } catch (err) {\n if (err instanceof VersionMismatchError) return undefined;\n throw err;\n }\n }\n\n async close(): Promise<void> {\n this.closed = true;\n for (const [, e] of this.store) {\n if (e.timer) clearTimeout(e.timer);\n }\n this.store.clear();\n }\n}\n\nexport class VersionMismatchError extends Error {\n constructor(\n public readonly key: string,\n public readonly expected: bigint,\n public readonly actual: bigint,\n ) {\n super(\n `KV version mismatch on \"${key}\": expected v${expected}, found v${actual}`,\n );\n this.name = 'VersionMismatchError';\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ICounter, CounterIncrOptions } from '@objectstack/spec/contracts';\n\n/**\n * In-memory monotonic counter. Single-process only — for cross-node id\n * allocation, use the postgres or redis driver.\n */\nexport class MemoryCounter implements ICounter {\n private readonly counters = new Map<string, bigint>();\n private closed = false;\n\n async incr(key: string, opts: CounterIncrOptions = {}): Promise<bigint> {\n if (this.closed) throw new Error('MemoryCounter is closed');\n const by = BigInt(opts.by ?? 1);\n const current = this.counters.get(key) ?? 0n;\n const next = current + by;\n this.counters.set(key, next);\n return next;\n }\n\n async peek(key: string): Promise<bigint> {\n return this.counters.get(key) ?? 0n;\n }\n\n async reset(key: string, value: bigint = 0n): Promise<void> {\n if (this.closed) throw new Error('MemoryCounter is closed');\n if (value === 0n) this.counters.delete(key);\n else this.counters.set(key, value);\n }\n\n async close(): Promise<void> {\n this.closed = true;\n this.counters.clear();\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Plugin, PluginContext } from '@objectstack/core';\nimport type { IClusterService } from '@objectstack/spec/contracts';\nimport type { ClusterCapabilityConfigInput } from '@objectstack/spec/kernel';\nimport { defineCluster } from './cluster.js';\n\n/**\n * Options for `ClusterServicePlugin`.\n *\n * Pass either a pre-built `cluster` instance (advanced — for tests or\n * custom drivers), or a `config` object that will be passed to\n * `defineCluster()`. If both are omitted, a memory-driver cluster is\n * created with auto-generated nodeId.\n */\nexport interface ClusterServicePluginOptions {\n /** Pre-built cluster service. Wins over `config` when both provided. */\n cluster?: IClusterService;\n /** Config forwarded to `defineCluster()` when `cluster` is absent. */\n config?: ClusterCapabilityConfigInput;\n}\n\n/**\n * Registers an `IClusterService` under the well-known service name\n * `'cluster'`. Plugins consume it via:\n *\n * ```ts\n * import type { IClusterService } from '@objectstack/spec/contracts';\n * const cluster = ctx.getService<IClusterService>('cluster');\n * await cluster.pubsub.publish('metadata.changed', payload);\n * ```\n *\n * The plugin closes the cluster on kernel shutdown.\n *\n * @example default memory driver\n * kernel.use(new ClusterServicePlugin());\n *\n * @example explicit config\n * kernel.use(new ClusterServicePlugin({ config: { driver: 'memory', nodeId: 'web-1' } }));\n */\nexport class ClusterServicePlugin implements Plugin {\n name = 'com.objectstack.service.cluster';\n version = '1.0.0';\n type = 'standard';\n\n private readonly options: ClusterServicePluginOptions;\n private cluster?: IClusterService;\n private owned = false;\n\n constructor(options: ClusterServicePluginOptions = {}) {\n this.options = options;\n }\n\n async init(ctx: PluginContext): Promise<void> {\n if (this.options.cluster) {\n this.cluster = this.options.cluster;\n this.owned = false;\n } else {\n this.cluster = defineCluster(this.options.config ?? {});\n this.owned = true;\n }\n ctx.registerService('cluster', this.cluster);\n ctx.logger.info(\n `ClusterServicePlugin: registered \"${this.cluster.driver}\" driver (node=${this.cluster.nodeId})`,\n );\n\n ctx.hook('kernel:shutdown', async () => {\n if (this.owned && this.cluster) {\n try {\n await this.cluster.close();\n } catch (err) {\n ctx.logger.error('ClusterServicePlugin: close error', err as Error);\n }\n }\n });\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Plugin, PluginContext } from '@objectstack/core';\nimport type { IClusterService } from '@objectstack/spec/contracts';\n\n/**\n * Bridges the cluster pub/sub bus to the metadata service so that\n * metadata mutations on one node invalidate registry caches on peer\n * nodes. Implements the \"first real consumer\" of the cluster API.\n *\n * Implementation detail: this plugin lives in `@objectstack/service-cluster`\n * (not in `@objectstack/metadata`) to avoid forcing every metadata\n * consumer to pull the cluster service. The metadata package only needs\n * the `IPubSub` interface, which lives in `@objectstack/spec/contracts`.\n *\n * Activates only when both services are present and the metadata service\n * exposes `attachClusterPubSub()`. Late binding is achieved via the\n * `kernel:ready` lifecycle hook.\n *\n * Channel: `metadata.changed` — payload shape defined by\n * `ClusterMetadataChangedPayload` in `@objectstack/metadata`.\n *\n * See `content/docs/concepts/cluster-semantics.mdx` §5.\n */\nexport class MetadataClusterBridgePlugin implements Plugin {\n name = 'com.objectstack.service.metadata-cluster-bridge';\n version = '1.0.0';\n type = 'standard';\n\n private detach?: () => void;\n\n async init(ctx: PluginContext): Promise<void> {\n ctx.hook('kernel:ready', async () => {\n let cluster: IClusterService | undefined;\n let md: unknown;\n try {\n cluster = ctx.getService<IClusterService>('cluster');\n } catch {\n ctx.logger.debug(\n 'MetadataClusterBridgePlugin: no \"cluster\" service registered, skipping',\n );\n return;\n }\n try {\n md = ctx.getService<unknown>('metadata');\n } catch {\n ctx.logger.debug(\n 'MetadataClusterBridgePlugin: no \"metadata\" service registered, skipping',\n );\n return;\n }\n\n const attach = (md as { attachClusterPubSub?: unknown })\n .attachClusterPubSub;\n if (typeof attach !== 'function') {\n ctx.logger.warn(\n 'MetadataClusterBridgePlugin: metadata service does not expose attachClusterPubSub(); cross-node cache invalidation disabled',\n );\n return;\n }\n\n try {\n this.detach = (attach as (\n pubsub: IClusterService['pubsub'],\n nodeId: string,\n ) => () => void).call(md, cluster.pubsub, cluster.nodeId);\n ctx.logger.info(\n `MetadataClusterBridgePlugin: bridged metadata.changed → cluster.pubsub (node=${cluster.nodeId})`,\n );\n } catch (err) {\n ctx.logger.error(\n 'MetadataClusterBridgePlugin: attach failed',\n err as Error,\n );\n }\n });\n\n ctx.hook('kernel:shutdown', async () => {\n try {\n this.detach?.();\n } catch (err) {\n ctx.logger.error(\n 'MetadataClusterBridgePlugin: detach error',\n err as Error,\n );\n }\n this.detach = undefined;\n });\n }\n}\n"],"mappings":";AAUA,SAAS,qCAAqC;;;ACuBvC,IAAM,eAAN,MAAsC;AAAA,EAMzC,YAAY,OAA4B,CAAC,GAAG;AAL5C,SAAiB,OAAO,oBAAI,IAA+B;AAG3D,SAAQ,SAAS;AAGb,SAAK,UACD,KAAK,YACJ,CAAC,KAAK,YAAY;AAEf,cAAQ,MAAM,4CAA4C,OAAO,MAAM,GAAG;AAAA,IAC9E;AACJ,SAAK,SAAS,KAAK;AAAA,EACvB;AAAA,EAEA,MAAM,QACF,SACA,SACA,OACa;AACb,QAAI,KAAK,OAAQ,OAAM,IAAI,MAAM,wBAAwB;AACzD,UAAM,SAAS,KAAK,KAAK,IAAI,OAAO;AACpC,QAAI,CAAC,UAAU,OAAO,SAAS,EAAG;AAClC,UAAM,cAAc,KAAK,IAAI;AAE7B,UAAM,WAAW,MAAM,KAAK,MAAM;AAClC,eAAW,OAAO,UAAU;AACxB,UAAI;AACA,cAAM,SAAS,IAAI,QAAQ;AAAA,UACvB;AAAA,UACA;AAAA,UACA;AAAA,UACA,UAAU,KAAK;AAAA,QACnB,CAAC;AACD,YAAI,UAAU,OAAQ,OAAyB,SAAS,YAAY;AAChE,UAAC,OAAyB,MAAM,CAAC,QAAQ,KAAK,QAAQ,KAAK,OAAO,CAAC;AAAA,QACvE;AAAA,MACJ,SAAS,KAAK;AACV,aAAK,QAAQ,KAAK,OAAO;AAAA,MAC7B;AAAA,IACJ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