durability 4.2.0 → 5.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.
Files changed (43) hide show
  1. package/README.md +340 -12
  2. package/dist/dev.d.ts +22 -0
  3. package/dist/dev.js +149 -0
  4. package/dist/durability-alarms.d.ts +16 -3
  5. package/dist/durability-alarms.js +21 -7
  6. package/dist/durability.d.ts +31 -6
  7. package/dist/durability.js +42 -16
  8. package/dist/errors.d.ts +31 -0
  9. package/dist/errors.js +45 -0
  10. package/dist/experimental.d.ts +5 -0
  11. package/dist/experimental.js +3 -0
  12. package/dist/fanout.d.ts +6 -0
  13. package/dist/fanout.js +20 -9
  14. package/dist/index.d.ts +4 -2
  15. package/dist/index.js +3 -2
  16. package/dist/lifecycle.d.ts +6 -1
  17. package/dist/lifecycle.js +3 -2
  18. package/dist/log.js +61 -16
  19. package/dist/memoize.d.ts +34 -0
  20. package/dist/memoize.js +136 -0
  21. package/dist/migrations.d.ts +64 -2
  22. package/dist/migrations.js +179 -34
  23. package/dist/outbox.d.ts +13 -0
  24. package/dist/outbox.js +78 -30
  25. package/dist/scheduler.d.ts +9 -0
  26. package/dist/scheduler.js +53 -11
  27. package/dist/semaphore-leases.js +15 -9
  28. package/dist/semaphore-queue-store.d.ts +12 -2
  29. package/dist/semaphore-queue-store.js +32 -5
  30. package/dist/semaphore-queue.js +109 -43
  31. package/dist/semaphore-server.js +7 -9
  32. package/dist/socket.js +19 -10
  33. package/dist/storage.d.ts +1 -0
  34. package/dist/storage.js +1 -1
  35. package/dist/topology-client.d.ts +40 -0
  36. package/dist/topology-client.js +180 -0
  37. package/dist/topology-snapshot.d.ts +70 -0
  38. package/dist/topology-snapshot.js +48 -0
  39. package/dist/topology.d.ts +94 -0
  40. package/dist/topology.js +468 -0
  41. package/dist/tracked-source.d.ts +2 -0
  42. package/dist/tracker.js +2 -0
  43. package/package.json +3 -2
package/dist/socket.js CHANGED
@@ -9,9 +9,10 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _DurabilitySocketCore_instances, _DurabilitySocketCore_context, _DurabilitySocketCore_inbound, _DurabilitySocketCore_outboundNames, _DurabilitySocketCore_metadata, _DurabilitySocketCore_retention, _DurabilitySocketCore_call, _DurabilitySocketCore_validate, _DurabilitySocketCore_subscribe, _DurabilitySocketCore_replay, _DurabilitySocketCore_headSeq, _DurabilitySocketCore_publish;
12
+ var _DurabilitySocketCore_instances, _DurabilitySocketCore_context, _DurabilitySocketCore_storage, _DurabilitySocketCore_inbound, _DurabilitySocketCore_outboundNames, _DurabilitySocketCore_metadata, _DurabilitySocketCore_retention, _DurabilitySocketCore_call, _DurabilitySocketCore_validate, _DurabilitySocketCore_subscribe, _DurabilitySocketCore_replay, _DurabilitySocketCore_headSeq, _DurabilitySocketCore_publish;
13
+ import { trace, traceFunction, traceMethods, traceStorage } from './dev.js';
13
14
  import { reportFailure, serializeError } from './errors.js';
14
- import { durabilitySocketMigrations, migrate, } from './migrations.js';
15
+ import { durabilitySocketMigrations, migrateCapability, } from './migrations.js';
15
16
  import { deserialize, serialize } from './serialization.js';
16
17
  import { parseClientFrame, socketMaxFrameLength, socketProtocolErrorCode, socketProtocolVersion, } from './socket-protocol.js';
17
18
  /** Thrown to the caller when an inbound payload fails its schema. */
@@ -24,6 +25,7 @@ export class SocketInputError extends Error {
24
25
  }
25
26
  const reservedOutboundNames = new Set(['status', 'resync']);
26
27
  const sendFrame = (ws, frame) => {
28
+ trace('socket.send', { frame });
27
29
  let text = JSON.stringify(frame);
28
30
  if (text.length > socketMaxFrameLength) {
29
31
  if (frame.type === 'event') {
@@ -64,6 +66,7 @@ class DurabilitySocketCore {
64
66
  constructor(config) {
65
67
  _DurabilitySocketCore_instances.add(this);
66
68
  _DurabilitySocketCore_context.set(this, void 0);
69
+ _DurabilitySocketCore_storage.set(this, void 0);
67
70
  _DurabilitySocketCore_inbound.set(this, void 0);
68
71
  _DurabilitySocketCore_outboundNames.set(this, void 0);
69
72
  _DurabilitySocketCore_metadata.set(this, void 0);
@@ -73,6 +76,7 @@ class DurabilitySocketCore {
73
76
  throw new RangeError('retention must be a positive safe integer');
74
77
  }
75
78
  __classPrivateFieldSet(this, _DurabilitySocketCore_context, config.context, "f");
79
+ __classPrivateFieldSet(this, _DurabilitySocketCore_storage, traceStorage(config.context.storage), "f");
76
80
  // Only own keys are callable; nothing on the prototype chain is reachable.
77
81
  __classPrivateFieldSet(this, _DurabilitySocketCore_inbound, new Map(Object.entries(config.inbound)), "f");
78
82
  __classPrivateFieldSet(this, _DurabilitySocketCore_metadata, config.metadata, "f");
@@ -87,17 +91,17 @@ class DurabilitySocketCore {
87
91
  throw new Error(`"${name}" is reserved by DurabilitySocket`);
88
92
  }
89
93
  Object.defineProperty(this, name, {
90
- value: (payload) => __classPrivateFieldGet(this, _DurabilitySocketCore_instances, "m", _DurabilitySocketCore_publish).call(this, name, payload),
94
+ value: traceFunction(`DurabilitySocket.${name}`, (payload) => __classPrivateFieldGet(this, _DurabilitySocketCore_instances, "m", _DurabilitySocketCore_publish).call(this, name, payload)),
91
95
  enumerable: true,
92
96
  });
93
97
  }
94
- migrate(__classPrivateFieldGet(this, _DurabilitySocketCore_context, "f").storage, 'socket', durabilitySocketMigrations, undefined);
98
+ migrateCapability(__classPrivateFieldGet(this, _DurabilitySocketCore_storage, "f"), 'socket', durabilitySocketMigrations, undefined);
95
99
  // Keep-alive pings are answered by the runtime without waking a hibernated object.
96
100
  __classPrivateFieldGet(this, _DurabilitySocketCore_context, "f").setWebSocketAutoResponse(new WebSocketRequestResponsePair(JSON.stringify({ v: socketProtocolVersion, type: 'ping' }), JSON.stringify({ v: socketProtocolVersion, type: 'pong' })));
97
101
  }
98
102
  /** Applies or reverts the `durability_socket_events` schema. */
99
103
  static migrate(context, target) {
100
- return migrate(context.storage, 'socket', durabilitySocketMigrations, target);
104
+ return migrateCapability(context.storage, 'socket', durabilitySocketMigrations, target);
101
105
  }
102
106
  /** Accepts a WebSocket upgrade; call from the Durable Object's `fetch`. */
103
107
  async fetch(request) {
@@ -120,6 +124,10 @@ class DurabilitySocketCore {
120
124
  const text = typeof message === 'string' ? message : new TextDecoder().decode(message);
121
125
  const frame = parseClientFrame(text);
122
126
  if (!frame) {
127
+ trace('socket.close', {
128
+ code: socketProtocolErrorCode,
129
+ reason: 'Invalid frame',
130
+ });
123
131
  ws.close(socketProtocolErrorCode, 'Invalid frame');
124
132
  return;
125
133
  }
@@ -136,7 +144,7 @@ class DurabilitySocketCore {
136
144
  */
137
145
  webSocketClose(_ws) { }
138
146
  }
139
- _DurabilitySocketCore_context = new WeakMap(), _DurabilitySocketCore_inbound = new WeakMap(), _DurabilitySocketCore_outboundNames = new WeakMap(), _DurabilitySocketCore_metadata = new WeakMap(), _DurabilitySocketCore_retention = new WeakMap(), _DurabilitySocketCore_instances = new WeakSet(), _DurabilitySocketCore_call = async function _DurabilitySocketCore_call(ws, frame) {
147
+ _DurabilitySocketCore_context = new WeakMap(), _DurabilitySocketCore_storage = new WeakMap(), _DurabilitySocketCore_inbound = new WeakMap(), _DurabilitySocketCore_outboundNames = new WeakMap(), _DurabilitySocketCore_metadata = new WeakMap(), _DurabilitySocketCore_retention = new WeakMap(), _DurabilitySocketCore_instances = new WeakSet(), _DurabilitySocketCore_call = async function _DurabilitySocketCore_call(ws, frame) {
140
148
  const handler = __classPrivateFieldGet(this, _DurabilitySocketCore_inbound, "f").get(frame.method);
141
149
  if (!handler) {
142
150
  sendFrame(ws, {
@@ -213,13 +221,13 @@ _DurabilitySocketCore_context = new WeakMap(), _DurabilitySocketCore_inbound = n
213
221
  if (since === head) {
214
222
  return true;
215
223
  }
216
- const oldest = __classPrivateFieldGet(this, _DurabilitySocketCore_context, "f").storage.sql
224
+ const oldest = __classPrivateFieldGet(this, _DurabilitySocketCore_storage, "f").sql
217
225
  .exec('SELECT MIN(seq) AS seq FROM durability_socket_events')
218
226
  .one().seq;
219
227
  if (since + 1 < oldest) {
220
228
  return false;
221
229
  }
222
- const rows = __classPrivateFieldGet(this, _DurabilitySocketCore_context, "f").storage.sql
230
+ const rows = __classPrivateFieldGet(this, _DurabilitySocketCore_storage, "f").sql
223
231
  .exec('SELECT seq, name, payload FROM durability_socket_events WHERE seq > ? ORDER BY seq', since)
224
232
  .toArray();
225
233
  const wanted = new Set(names);
@@ -237,13 +245,13 @@ _DurabilitySocketCore_context = new WeakMap(), _DurabilitySocketCore_inbound = n
237
245
  }
238
246
  return true;
239
247
  }, _DurabilitySocketCore_headSeq = function _DurabilitySocketCore_headSeq() {
240
- const row = __classPrivateFieldGet(this, _DurabilitySocketCore_context, "f").storage.sql
248
+ const row = __classPrivateFieldGet(this, _DurabilitySocketCore_storage, "f").sql
241
249
  .exec('SELECT MAX(seq) AS seq FROM durability_socket_events')
242
250
  .one();
243
251
  return row.seq ?? 0;
244
252
  }, _DurabilitySocketCore_publish = function _DurabilitySocketCore_publish(name, payload) {
245
253
  const serialized = serialize(payload);
246
- const sql = __classPrivateFieldGet(this, _DurabilitySocketCore_context, "f").storage.sql;
254
+ const sql = __classPrivateFieldGet(this, _DurabilitySocketCore_storage, "f").sql;
247
255
  const { seq } = sql
248
256
  .exec('INSERT INTO durability_socket_events (name, payload, created_at) VALUES (?, ?, ?) RETURNING seq', name, serialized, Date.now())
249
257
  .one();
@@ -265,6 +273,7 @@ _DurabilitySocketCore_context = new WeakMap(), _DurabilitySocketCore_inbound = n
265
273
  sendFrame(ws, frame);
266
274
  }
267
275
  };
276
+ traceMethods(DurabilitySocketCore.prototype, 'DurabilitySocket');
268
277
  // TypeScript cannot declare class members derived from a generic event map,
269
278
  // so the constructor is typed separately; the constructor installs and
270
279
  // reserves every outbound method at runtime.
package/dist/storage.d.ts CHANGED
@@ -12,6 +12,7 @@ export type AttemptRef = {
12
12
  generation: string;
13
13
  attempt: number;
14
14
  };
15
+ export declare const pendingGeneration: (table: DurableTable) => string;
15
16
  /** Starts the next attempt and returns its number, unless the generation is gone or out of attempts. */
16
17
  export declare const claimAttempt: (sql: SqlStorage, table: DurableTable, key: string, generation: string, maxAttempts: number) => number | undefined;
17
18
  /**
package/dist/storage.js CHANGED
@@ -4,7 +4,7 @@ const attemptRowSchema = z.object({
4
4
  });
5
5
  // Every write is conditional on the record's generation and pending status, so a
6
6
  // stale execution can never overwrite a replacement or a later attempt.
7
- const pendingGeneration = (table) => `${table.key} = ? AND generation_id = ? AND status = 'pending'`;
7
+ export const pendingGeneration = (table) => `${table.key} = ? AND generation_id = ? AND status = 'pending'`;
8
8
  /** Starts the next attempt and returns its number, unless the generation is gone or out of attempts. */
9
9
  export const claimAttempt = (sql, table, key, generation, maxAttempts) => attemptRowSchema.optional().parse(sql
10
10
  .exec(`UPDATE ${table.name}
@@ -0,0 +1,40 @@
1
+ import { type TopologyFallbackReason } from './errors.js';
2
+ import { type TopologyMemberInput, type TopologySnapshot } from './topology-snapshot.js';
3
+ export type TopologySource = 'published' | 'stale' | 'seed' | 'fallback';
4
+ export type TopologyView<Meta = undefined> = TopologySnapshot<Meta> & {
5
+ source: TopologySource;
6
+ fetchedAt: number;
7
+ };
8
+ export type TopologyClientConfig<Meta = undefined> = {
9
+ /** Returns the `encoded` value the coordinator's publisher stored, or null. */
10
+ read(group: string): Promise<string | null | undefined>;
11
+ /** Defaults to 1 second. */
12
+ readTimeoutMs?: number;
13
+ /** Defaults to 30 seconds, jittered by ±20% so isolates do not refresh together. */
14
+ ttlMs?: number;
15
+ /** How long a missing or failed read is remembered before reading again. Defaults to 5 seconds. */
16
+ negativeTtlMs?: number;
17
+ /** Opt-in: serve this isolate's last good snapshot for this long after it expires when a read fails. */
18
+ staleIfErrorMs?: number;
19
+ /** Opt-in: members derived locally, without I/O. */
20
+ seed?(group: string): readonly TopologyMemberInput<Meta>[] | undefined;
21
+ /** Opt-in and application-owned. Not cached: whatever it calls runs on every fallback. */
22
+ fallback?(group: string, reason: TopologyFallbackReason): Promise<TopologySnapshot<Meta> | undefined>;
23
+ onFallback?(event: {
24
+ group: string;
25
+ reason: TopologyFallbackReason;
26
+ source: TopologySource | 'none';
27
+ }): void;
28
+ };
29
+ /** Read-only. Created by `DurabilityTopology.client`. */
30
+ export declare class TopologyClient<Meta = undefined> {
31
+ #private;
32
+ constructor(config: TopologyClientConfig<Meta>);
33
+ /**
34
+ * Returns the group's snapshot from this isolate's cache or the read store.
35
+ * Concurrent calls share one read, and a newer snapshot is never replaced by
36
+ * an older one. Throws {@link TopologyUnavailableError} when the published
37
+ * snapshot is unusable and no opt-in fallback produced one.
38
+ */
39
+ get(group: string): Promise<TopologyView<Meta>>;
40
+ }
@@ -0,0 +1,180 @@
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
+ };
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
12
+ var _TopologyClient_instances, _TopologyClient_config, _TopologyClient_readTimeoutMs, _TopologyClient_ttlMs, _TopologyClient_negativeTtlMs, _TopologyClient_cache, _TopologyClient_inflight, _TopologyClient_load, _TopologyClient_read, _TopologyClient_fallback, _TopologyClient_remember;
13
+ import { TopologyUnavailableError, } from './errors.js';
14
+ import { assertPositiveInteger } from './policy.js';
15
+ import { decodeSnapshot, } from './topology-snapshot.js';
16
+ // High-cardinality groups (one per tenant) must not grow an isolate without bound; the least recently used go first.
17
+ const maxCachedGroups = 1024;
18
+ class ReadTimeoutError extends Error {
19
+ }
20
+ const jittered = (ms) => Math.round(ms * (0.8 + Math.random() * 0.4));
21
+ /** Read-only. Created by `DurabilityTopology.client`. */
22
+ export class TopologyClient {
23
+ constructor(config) {
24
+ _TopologyClient_instances.add(this);
25
+ _TopologyClient_config.set(this, void 0);
26
+ _TopologyClient_readTimeoutMs.set(this, void 0);
27
+ _TopologyClient_ttlMs.set(this, void 0);
28
+ _TopologyClient_negativeTtlMs.set(this, void 0);
29
+ _TopologyClient_cache.set(this, new Map());
30
+ _TopologyClient_inflight.set(this, new Map());
31
+ if (typeof config.read !== 'function') {
32
+ throw new TypeError('A topology client needs a read function');
33
+ }
34
+ __classPrivateFieldSet(this, _TopologyClient_readTimeoutMs, config.readTimeoutMs ?? 1000, "f");
35
+ __classPrivateFieldSet(this, _TopologyClient_ttlMs, config.ttlMs ?? 30000, "f");
36
+ __classPrivateFieldSet(this, _TopologyClient_negativeTtlMs, config.negativeTtlMs ?? 5000, "f");
37
+ assertPositiveInteger('readTimeoutMs', __classPrivateFieldGet(this, _TopologyClient_readTimeoutMs, "f"));
38
+ assertPositiveInteger('ttlMs', __classPrivateFieldGet(this, _TopologyClient_ttlMs, "f"));
39
+ assertPositiveInteger('negativeTtlMs', __classPrivateFieldGet(this, _TopologyClient_negativeTtlMs, "f"));
40
+ if (config.staleIfErrorMs !== undefined &&
41
+ (!Number.isSafeInteger(config.staleIfErrorMs) ||
42
+ config.staleIfErrorMs < 0)) {
43
+ throw new RangeError('staleIfErrorMs must be a non-negative integer');
44
+ }
45
+ __classPrivateFieldSet(this, _TopologyClient_config, config, "f");
46
+ }
47
+ /**
48
+ * Returns the group's snapshot from this isolate's cache or the read store.
49
+ * Concurrent calls share one read, and a newer snapshot is never replaced by
50
+ * an older one. Throws {@link TopologyUnavailableError} when the published
51
+ * snapshot is unusable and no opt-in fallback produced one.
52
+ */
53
+ get(group) {
54
+ const entry = __classPrivateFieldGet(this, _TopologyClient_cache, "f").get(group);
55
+ if (entry && Date.now() < entry.expiresAt) {
56
+ if (entry.failure) {
57
+ return __classPrivateFieldGet(this, _TopologyClient_instances, "m", _TopologyClient_fallback).call(this, group, entry);
58
+ }
59
+ if (entry.view) {
60
+ __classPrivateFieldGet(this, _TopologyClient_instances, "m", _TopologyClient_remember).call(this, group, entry);
61
+ return Promise.resolve(entry.view);
62
+ }
63
+ }
64
+ const inflight = __classPrivateFieldGet(this, _TopologyClient_inflight, "f").get(group);
65
+ if (inflight) {
66
+ return inflight;
67
+ }
68
+ const run = __classPrivateFieldGet(this, _TopologyClient_instances, "m", _TopologyClient_load).call(this, group).finally(() => __classPrivateFieldGet(this, _TopologyClient_inflight, "f").delete(group));
69
+ __classPrivateFieldGet(this, _TopologyClient_inflight, "f").set(group, run);
70
+ return run;
71
+ }
72
+ }
73
+ _TopologyClient_config = new WeakMap(), _TopologyClient_readTimeoutMs = new WeakMap(), _TopologyClient_ttlMs = new WeakMap(), _TopologyClient_negativeTtlMs = new WeakMap(), _TopologyClient_cache = new WeakMap(), _TopologyClient_inflight = new WeakMap(), _TopologyClient_instances = new WeakSet(), _TopologyClient_load = async function _TopologyClient_load(group) {
74
+ const previous = __classPrivateFieldGet(this, _TopologyClient_cache, "f").get(group);
75
+ const result = await __classPrivateFieldGet(this, _TopologyClient_instances, "m", _TopologyClient_read).call(this, group);
76
+ const now = Date.now();
77
+ if ('snapshot' in result) {
78
+ const { snapshot } = result;
79
+ // The store is eventually consistent; a lagging replica must not move readers backwards.
80
+ // Versions only compare within one coordinator: a group moved to another starts over.
81
+ const keep = previous?.view !== undefined &&
82
+ previous.view.coordinator === snapshot.coordinator &&
83
+ previous.view.version > snapshot.version;
84
+ const view = keep
85
+ ? previous.view
86
+ : { ...snapshot, source: 'published', fetchedAt: now };
87
+ const expiresAt = now + jittered(__classPrivateFieldGet(this, _TopologyClient_ttlMs, "f"));
88
+ __classPrivateFieldGet(this, _TopologyClient_instances, "m", _TopologyClient_remember).call(this, group, {
89
+ view,
90
+ expiresAt,
91
+ staleUntil: expiresAt + (__classPrivateFieldGet(this, _TopologyClient_config, "f").staleIfErrorMs ?? 0),
92
+ });
93
+ return view;
94
+ }
95
+ const entry = {
96
+ // A missing group is not an error, so nothing stale may be served for it.
97
+ ...(result.failure.reason === 'missing' || !previous?.view
98
+ ? {}
99
+ : { view: previous.view }),
100
+ staleUntil: previous?.staleUntil ?? 0,
101
+ expiresAt: now + jittered(__classPrivateFieldGet(this, _TopologyClient_negativeTtlMs, "f")),
102
+ failure: result.failure,
103
+ };
104
+ __classPrivateFieldGet(this, _TopologyClient_instances, "m", _TopologyClient_remember).call(this, group, entry);
105
+ return __classPrivateFieldGet(this, _TopologyClient_instances, "m", _TopologyClient_fallback).call(this, group, entry);
106
+ }, _TopologyClient_read = async function _TopologyClient_read(group) {
107
+ let encoded;
108
+ let timer;
109
+ try {
110
+ encoded = await Promise.race([
111
+ Promise.resolve().then(() => __classPrivateFieldGet(this, _TopologyClient_config, "f").read(group)),
112
+ new Promise((_resolve, reject) => {
113
+ timer = setTimeout(() => reject(new ReadTimeoutError()), __classPrivateFieldGet(this, _TopologyClient_readTimeoutMs, "f"));
114
+ }),
115
+ ]);
116
+ }
117
+ catch (cause) {
118
+ return {
119
+ failure: {
120
+ reason: cause instanceof ReadTimeoutError ? 'timeout' : 'error',
121
+ cause,
122
+ },
123
+ };
124
+ }
125
+ finally {
126
+ clearTimeout(timer);
127
+ }
128
+ if (encoded === null || encoded === undefined) {
129
+ return { failure: { reason: 'missing' } };
130
+ }
131
+ try {
132
+ const snapshot = decodeSnapshot(encoded);
133
+ if (snapshot.group !== group) {
134
+ throw new Error(`Snapshot belongs to group "${snapshot.group}"`);
135
+ }
136
+ return { snapshot };
137
+ }
138
+ catch (cause) {
139
+ return { failure: { reason: 'invalid', cause } };
140
+ }
141
+ }, _TopologyClient_fallback = async function _TopologyClient_fallback(group, entry) {
142
+ const { reason, cause } = entry.failure;
143
+ const notify = (source) => __classPrivateFieldGet(this, _TopologyClient_config, "f").onFallback?.({ group, reason, source });
144
+ if (__classPrivateFieldGet(this, _TopologyClient_config, "f").staleIfErrorMs !== undefined &&
145
+ entry.view !== undefined &&
146
+ Date.now() < entry.staleUntil) {
147
+ notify('stale');
148
+ return { ...entry.view, source: 'stale' };
149
+ }
150
+ const seeded = __classPrivateFieldGet(this, _TopologyClient_config, "f").seed?.(group);
151
+ if (seeded !== undefined && seeded.length > 0) {
152
+ notify('seed');
153
+ return {
154
+ group,
155
+ version: 0,
156
+ coordinator: '',
157
+ members: seeded
158
+ .map((member) => ({ ...member, joinedAt: 0 }))
159
+ .sort((a, b) => (a.id < b.id ? -1 : 1)),
160
+ source: 'seed',
161
+ fetchedAt: Date.now(),
162
+ };
163
+ }
164
+ const fallback = await __classPrivateFieldGet(this, _TopologyClient_config, "f").fallback?.(group, reason);
165
+ if (fallback !== undefined) {
166
+ notify('fallback');
167
+ return { ...fallback, source: 'fallback', fetchedAt: Date.now() };
168
+ }
169
+ notify('none');
170
+ throw new TopologyUnavailableError(group, reason, { cause });
171
+ }, _TopologyClient_remember = function _TopologyClient_remember(group, entry) {
172
+ __classPrivateFieldGet(this, _TopologyClient_cache, "f").delete(group);
173
+ __classPrivateFieldGet(this, _TopologyClient_cache, "f").set(group, entry);
174
+ if (__classPrivateFieldGet(this, _TopologyClient_cache, "f").size > maxCachedGroups) {
175
+ const oldest = __classPrivateFieldGet(this, _TopologyClient_cache, "f").keys().next().value;
176
+ if (oldest !== undefined) {
177
+ __classPrivateFieldGet(this, _TopologyClient_cache, "f").delete(oldest);
178
+ }
179
+ }
180
+ };
@@ -0,0 +1,70 @@
1
+ import { z } from 'zod';
2
+ /** `active` members are in the write and read sets; `draining` members only in the read set. */
3
+ export type TopologyMemberState = 'active' | 'draining';
4
+ type MetaField<Meta> = undefined extends Meta ? {
5
+ meta?: Meta;
6
+ } : {
7
+ meta: Meta;
8
+ };
9
+ /** A member as the application declares it. */
10
+ export type TopologyMemberInput<Meta = undefined> = {
11
+ /** The member's Durable Object name. */
12
+ id: string;
13
+ state: TopologyMemberState;
14
+ locationHint?: DurableObjectLocationHint;
15
+ } & MetaField<Meta>;
16
+ export type TopologyMember<Meta = undefined> = TopologyMemberInput<Meta> & {
17
+ joinedAt: number;
18
+ };
19
+ export type TopologySnapshot<Meta = undefined> = {
20
+ group: string;
21
+ /** Increases on every membership change, and keeps increasing across deletes. */
22
+ version: number;
23
+ /** ID of the coordinator Durable Object that published this snapshot. */
24
+ coordinator: string;
25
+ /** Sorted by ID. */
26
+ members: readonly TopologyMember<Meta>[];
27
+ };
28
+ export declare const memberInputSchema: z.ZodObject<{
29
+ id: z.ZodString;
30
+ state: z.ZodEnum<{
31
+ active: "active";
32
+ draining: "draining";
33
+ }>;
34
+ locationHint: z.ZodOptional<z.ZodEnum<{
35
+ wnam: "wnam";
36
+ enam: "enam";
37
+ sam: "sam";
38
+ weur: "weur";
39
+ eeur: "eeur";
40
+ apac: "apac";
41
+ oc: "oc";
42
+ afr: "afr";
43
+ me: "me";
44
+ }>>;
45
+ meta: z.ZodOptional<z.ZodJSONSchema>;
46
+ }, z.core.$strip>;
47
+ export declare const membersSchema: z.ZodArray<z.ZodObject<{
48
+ id: z.ZodString;
49
+ state: z.ZodEnum<{
50
+ active: "active";
51
+ draining: "draining";
52
+ }>;
53
+ locationHint: z.ZodOptional<z.ZodEnum<{
54
+ wnam: "wnam";
55
+ enam: "enam";
56
+ sam: "sam";
57
+ weur: "weur";
58
+ eeur: "eeur";
59
+ apac: "apac";
60
+ oc: "oc";
61
+ afr: "afr";
62
+ me: "me";
63
+ }>>;
64
+ meta: z.ZodOptional<z.ZodJSONSchema>;
65
+ joinedAt: z.ZodNumber;
66
+ }, z.core.$strip>>;
67
+ export declare const encodeSnapshot: <Meta>(snapshot: TopologySnapshot<Meta>) => string;
68
+ /** The stored value crossed a trust boundary, so every field is re-validated. */
69
+ export declare const decodeSnapshot: <Meta>(encoded: string) => TopologySnapshot<Meta>;
70
+ export {};
@@ -0,0 +1,48 @@
1
+ import { z } from 'zod';
2
+ const locationHints = [
3
+ 'wnam',
4
+ 'enam',
5
+ 'sam',
6
+ 'weur',
7
+ 'eeur',
8
+ 'apac',
9
+ 'oc',
10
+ 'afr',
11
+ 'me',
12
+ ];
13
+ // Unknown keys are stripped, so current members (which carry `joinedAt`) can be returned as input.
14
+ export const memberInputSchema = z.object({
15
+ id: z.string().min(1),
16
+ state: z.enum(['active', 'draining']),
17
+ locationHint: z.enum(locationHints).optional(),
18
+ meta: z.json().optional(),
19
+ });
20
+ const memberSchema = memberInputSchema.extend({
21
+ joinedAt: z.number().int().nonnegative(),
22
+ });
23
+ export const membersSchema = memberSchema
24
+ .array()
25
+ .superRefine((members, ctx) => {
26
+ for (let index = 1; index < members.length; index++) {
27
+ if (members[index - 1].id >= members[index].id) {
28
+ ctx.addIssue({
29
+ code: 'custom',
30
+ message: 'Members must be sorted by ID and unique',
31
+ path: [index, 'id'],
32
+ });
33
+ }
34
+ }
35
+ });
36
+ const encodedSchema = z.object({
37
+ format: z.literal(1),
38
+ group: z.string().min(1),
39
+ version: z.number().int().positive(),
40
+ coordinator: z.string().min(1),
41
+ members: membersSchema.min(1),
42
+ });
43
+ export const encodeSnapshot = (snapshot) => JSON.stringify({ format: 1, ...snapshot });
44
+ /** The stored value crossed a trust boundary, so every field is re-validated. */
45
+ export const decodeSnapshot = (encoded) => {
46
+ const { format: _format, ...snapshot } = encodedSchema.parse(JSON.parse(encoded));
47
+ return snapshot;
48
+ };
@@ -0,0 +1,94 @@
1
+ import { type DurabilityOutboxEvent } from './outbox.js';
2
+ import { type SchedulerAttachment } from './scheduler.js';
3
+ import { TopologyClient, type TopologyClientConfig } from './topology-client.js';
4
+ import { type TopologyMember, type TopologyMemberInput, type TopologySnapshot } from './topology-snapshot.js';
5
+ /** `write` channels reach active members; `read` channels reach draining members too. */
6
+ export type TopologyRole = 'write' | 'read';
7
+ /** Publication and sync never give up: a stale topology must still converge. */
8
+ export type TopologyRetryOptions = {
9
+ /** Maximum duration of one write or delivery. Defaults to 30 seconds. */
10
+ attemptTimeoutMs?: number;
11
+ retries?: {
12
+ /** Delay in milliseconds after a failed attempt. Defaults to jittered exponential backoff capped at 5 minutes. */
13
+ delay?: (attempt: number) => number;
14
+ };
15
+ };
16
+ export type TopologyStateUpdate<Value> = {
17
+ group: string;
18
+ channel: string;
19
+ /** Increases on every update sent to this member. Apply only versions newer than the last one applied. */
20
+ version: number;
21
+ topologyVersion: number;
22
+ value: Value;
23
+ };
24
+ export type TopologyPublisher<Meta> = TopologyRetryOptions & {
25
+ /** Must be idempotent. Store `encoded` as is: it is what the client reads. */
26
+ write(snapshot: TopologySnapshot<Meta>, encoded: string): Promise<unknown>;
27
+ delete(group: string, version: number): Promise<unknown>;
28
+ };
29
+ export type TopologyChannel<Value, Meta> = TopologyRetryOptions & {
30
+ /** Defaults to `write`. */
31
+ members?: TopologyRole;
32
+ deliver(member: TopologyMember<Meta>, update: TopologyStateUpdate<Value>): unknown;
33
+ };
34
+ /**
35
+ * Publication and sync run on outbox channels: `durability.topology` keyed by
36
+ * group, and `durability.topology.<channel>` keyed by `[group, member]`.
37
+ */
38
+ export type DurabilityTopologyEvent = DurabilityOutboxEvent;
39
+ export type DurabilityTopologyConfig<Meta, States extends Record<string, unknown>> = SchedulerAttachment & TopologyRetryOptions & {
40
+ /** Without a publisher, membership is only visible inside this object. */
41
+ publish?: TopologyPublisher<Meta>;
42
+ states?: {
43
+ [Name in keyof States]: TopologyChannel<States[Name], Meta>;
44
+ };
45
+ onLifecycleEvent?: (event: DurabilityTopologyEvent) => void | Promise<void>;
46
+ };
47
+ export type TopologyCurrent<Meta, States> = {
48
+ members: readonly TopologyMember<Meta>[];
49
+ states: Partial<States>;
50
+ };
51
+ export type TopologyDraft<Meta, States> = {
52
+ /** Omit to keep the current members. */
53
+ members?: readonly TopologyMemberInput<Meta>[];
54
+ /** Only the channels being set. */
55
+ states?: Partial<States>;
56
+ };
57
+ /**
58
+ * Experimental. Holds the membership of shard groups inside one coordinator
59
+ * Durable Object, publishes each group's snapshot to a read store, and drives
60
+ * every member to the latest value of each state channel. Only this instance
61
+ * can change or publish its groups; readers use {@link DurabilityTopology.client}.
62
+ */
63
+ export declare class DurabilityTopology<Meta = undefined, States extends Record<string, unknown> = Record<string, never>> {
64
+ #private;
65
+ constructor(config: DurabilityTopologyConfig<Meta, States>);
66
+ /** A read-only client for stateless Workers. It never contacts the coordinator. */
67
+ static client<Meta = undefined>(config: TopologyClientConfig<Meta>): TopologyClient<Meta>;
68
+ /** Reverts only the topology tables; outbox channels migrateCapability with `DurabilityOutbox.migrate`. */
69
+ static migrate(context: Pick<DurableObjectState, 'storage'>, target?: string | null): import("./migrations.js").DurabilityMigrationResult;
70
+ alarm(info?: AlarmInvocationInfo): Promise<void>;
71
+ /**
72
+ * Applies one change in a single transaction. `next` runs inside it and must
73
+ * return synchronously, so nothing can interleave between reading `current`
74
+ * and writing the draft. After the commit, one publish is attempted:
75
+ * `published: false` means the snapshot is not yet final in the store:
76
+ * the write failed, or an older write may still land over it. The outbox
77
+ * keeps going until it is.
78
+ */
79
+ update(group: string, next: (current: TopologyCurrent<Meta, States>) => TopologyDraft<Meta, States>): Promise<{
80
+ snapshot: TopologySnapshot<Meta>;
81
+ published: boolean;
82
+ }>;
83
+ /**
84
+ * Deletes the group in one transaction: members and state values are dropped
85
+ * and pending deliveries discarded. Versions keep counting, so a recreated
86
+ * group is newer than anything readers cached. One publisher delete is
87
+ * attempted after the commit.
88
+ */
89
+ delete(group: string): Promise<{
90
+ published: boolean;
91
+ }>;
92
+ /** Coordinator-local read. Readers elsewhere use the published copy. */
93
+ snapshot(group: string): TopologySnapshot<Meta> | undefined;
94
+ }