durability 4.1.2 → 4.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +406 -1
- package/dist/dev.d.ts +22 -0
- package/dist/dev.js +149 -0
- package/dist/durability-alarms.d.ts +1 -1
- package/dist/durability-alarms.js +6 -4
- package/dist/durability.d.ts +1 -1
- package/dist/durability.js +8 -5
- package/dist/durable-object-target.d.ts +12 -0
- package/dist/durable-object-target.js +17 -0
- package/dist/errors.d.ts +25 -0
- package/dist/errors.js +36 -0
- package/dist/experimental.d.ts +8 -0
- package/dist/experimental.js +6 -0
- package/dist/fanout.js +14 -9
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -1
- package/dist/lifecycle.d.ts +14 -3
- package/dist/lifecycle.js +3 -2
- package/dist/log.js +26 -4
- package/dist/migrations.d.ts +74 -2
- package/dist/migrations.js +307 -36
- package/dist/outbox.d.ts +85 -0
- package/dist/outbox.js +433 -0
- package/dist/routing.d.ts +2 -9
- package/dist/routing.js +2 -14
- package/dist/scheduler.d.ts +14 -2
- package/dist/scheduler.js +38 -13
- package/dist/semaphore-client.d.ts +22 -0
- package/dist/semaphore-client.js +61 -0
- package/dist/semaphore-leases.d.ts +109 -0
- package/dist/semaphore-leases.js +272 -0
- package/dist/semaphore-protocol.d.ts +231 -0
- package/dist/semaphore-protocol.js +106 -0
- package/dist/semaphore-queue-store.d.ts +95 -0
- package/dist/semaphore-queue-store.js +248 -0
- package/dist/semaphore-queue.d.ts +119 -0
- package/dist/semaphore-queue.js +863 -0
- package/dist/semaphore-server.d.ts +89 -0
- package/dist/semaphore-server.js +518 -0
- package/dist/semaphore-store.d.ts +43 -0
- package/dist/semaphore-store.js +108 -0
- package/dist/semaphore.d.ts +42 -0
- package/dist/semaphore.js +57 -0
- package/dist/socket.js +19 -10
- package/dist/topology-client.d.ts +40 -0
- package/dist/topology-client.js +180 -0
- package/dist/topology-snapshot.d.ts +70 -0
- package/dist/topology-snapshot.js +48 -0
- package/dist/topology.d.ts +94 -0
- package/dist/topology.js +468 -0
- package/dist/tracker.js +2 -0
- package/package.json +6 -2
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export const grantRowSchema = z.object({
|
|
3
|
+
grant_id: z.string(),
|
|
4
|
+
client_id: z.string(),
|
|
5
|
+
grp: z.string(),
|
|
6
|
+
permits: z.number().int().nonnegative(),
|
|
7
|
+
claimed: z.number().int().nonnegative(),
|
|
8
|
+
released: z.number().int().nonnegative(),
|
|
9
|
+
created_at: z.number().int().nonnegative(),
|
|
10
|
+
/** Unclaimed permits are reclaimed once this passes. */
|
|
11
|
+
expires_at: z.number().int().nonnegative(),
|
|
12
|
+
});
|
|
13
|
+
/** Permits a client may draw locally without a round trip; held by the holder. */
|
|
14
|
+
export const leaseRowSchema = z.object({
|
|
15
|
+
lease_id: z.string(),
|
|
16
|
+
client_id: z.string(),
|
|
17
|
+
grp: z.string(),
|
|
18
|
+
permits: z.number().int().nonnegative(),
|
|
19
|
+
/** Drawn permits the client has returned, as a high-water mark. */
|
|
20
|
+
released: z.number().int().nonnegative(),
|
|
21
|
+
created_at: z.number().int().nonnegative(),
|
|
22
|
+
/** Refreshed by every report; the lease is swept once this passes. */
|
|
23
|
+
expires_at: z.number().int().nonnegative(),
|
|
24
|
+
/** 1 once no more permits may be drawn; footprint stays until released. */
|
|
25
|
+
retired: z.number().int().min(0).max(1),
|
|
26
|
+
});
|
|
27
|
+
const grantColumns = grantRowSchema.keyof().options;
|
|
28
|
+
const leaseColumns = leaseRowSchema.keyof().options;
|
|
29
|
+
/**
|
|
30
|
+
* Permits a semaphore has handed out. Grants and leases are small and bounded
|
|
31
|
+
* by live clients, so aggregates are computed from `list()`.
|
|
32
|
+
*/
|
|
33
|
+
export class HolderStore {
|
|
34
|
+
constructor(sql) {
|
|
35
|
+
this.sql = sql;
|
|
36
|
+
}
|
|
37
|
+
list() {
|
|
38
|
+
return grantRowSchema
|
|
39
|
+
.array()
|
|
40
|
+
.parse(this.sql
|
|
41
|
+
.exec('SELECT * FROM durability_semaphore_grants ORDER BY created_at')
|
|
42
|
+
.toArray());
|
|
43
|
+
}
|
|
44
|
+
get(grantId) {
|
|
45
|
+
return grantRowSchema
|
|
46
|
+
.optional()
|
|
47
|
+
.parse(this.sql
|
|
48
|
+
.exec('SELECT * FROM durability_semaphore_grants WHERE grant_id = ? LIMIT 1', grantId)
|
|
49
|
+
.toArray()[0]);
|
|
50
|
+
}
|
|
51
|
+
nextPendingAt() {
|
|
52
|
+
return grantRowSchema
|
|
53
|
+
.pick({ expires_at: true })
|
|
54
|
+
.optional()
|
|
55
|
+
.parse(this.sql
|
|
56
|
+
.exec(`SELECT expires_at FROM durability_semaphore_grants
|
|
57
|
+
WHERE claimed < permits
|
|
58
|
+
ORDER BY expires_at ASC
|
|
59
|
+
LIMIT 1`)
|
|
60
|
+
.toArray()[0])?.expires_at;
|
|
61
|
+
}
|
|
62
|
+
insert(row) {
|
|
63
|
+
return (this.sql
|
|
64
|
+
.exec(`INSERT INTO durability_semaphore_grants (${grantColumns.join(', ')})
|
|
65
|
+
VALUES (${grantColumns.map(() => '?').join(', ')})
|
|
66
|
+
ON CONFLICT(grant_id) DO NOTHING
|
|
67
|
+
RETURNING grant_id`, ...grantColumns.map((column) => row[column]))
|
|
68
|
+
.toArray().length > 0);
|
|
69
|
+
}
|
|
70
|
+
update(row) {
|
|
71
|
+
this.sql.exec(`UPDATE durability_semaphore_grants
|
|
72
|
+
SET permits = ?, claimed = ?, released = ?, expires_at = ?
|
|
73
|
+
WHERE grant_id = ?`, row.permits, row.claimed, row.released, row.expires_at, row.grant_id);
|
|
74
|
+
}
|
|
75
|
+
remove(grantId) {
|
|
76
|
+
this.sql.exec('DELETE FROM durability_semaphore_grants WHERE grant_id = ?', grantId);
|
|
77
|
+
}
|
|
78
|
+
listLeases() {
|
|
79
|
+
return leaseRowSchema
|
|
80
|
+
.array()
|
|
81
|
+
.parse(this.sql
|
|
82
|
+
.exec('SELECT * FROM durability_semaphore_leases ORDER BY created_at')
|
|
83
|
+
.toArray());
|
|
84
|
+
}
|
|
85
|
+
getLease(leaseId) {
|
|
86
|
+
return leaseRowSchema
|
|
87
|
+
.optional()
|
|
88
|
+
.parse(this.sql
|
|
89
|
+
.exec('SELECT * FROM durability_semaphore_leases WHERE lease_id = ? LIMIT 1', leaseId)
|
|
90
|
+
.toArray()[0]);
|
|
91
|
+
}
|
|
92
|
+
insertLease(row) {
|
|
93
|
+
return (this.sql
|
|
94
|
+
.exec(`INSERT INTO durability_semaphore_leases (${leaseColumns.join(', ')})
|
|
95
|
+
VALUES (${leaseColumns.map(() => '?').join(', ')})
|
|
96
|
+
ON CONFLICT(lease_id) DO NOTHING
|
|
97
|
+
RETURNING lease_id`, ...leaseColumns.map((column) => row[column]))
|
|
98
|
+
.toArray().length > 0);
|
|
99
|
+
}
|
|
100
|
+
updateLease(row) {
|
|
101
|
+
this.sql.exec(`UPDATE durability_semaphore_leases
|
|
102
|
+
SET permits = ?, released = ?, expires_at = ?, retired = ?
|
|
103
|
+
WHERE lease_id = ?`, row.permits, row.released, row.expires_at, row.retired, row.lease_id);
|
|
104
|
+
}
|
|
105
|
+
removeLease(leaseId) {
|
|
106
|
+
this.sql.exec('DELETE FROM durability_semaphore_leases WHERE lease_id = ?', leaseId);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Experimental: this entry point may change or be removed in a minor
|
|
3
|
+
* release. Pin an exact version of `durability` when depending on it.
|
|
4
|
+
*
|
|
5
|
+
* @packageDocumentation
|
|
6
|
+
*/
|
|
7
|
+
import { type TransformContext, type TransformStub } from '@durability/transforms';
|
|
8
|
+
import { type DurableObjectTarget } from './durable-object-target.js';
|
|
9
|
+
import { type PermitGrant, type PermitRequest, type PermitSync, type PermitSyncResult, type SemaphoreRequest, type SemaphoreResponse } from './semaphore-protocol.js';
|
|
10
|
+
import { DurabilitySemaphoreServer } from './semaphore-server.js';
|
|
11
|
+
export { SemaphoreProtocolError } from './errors.js';
|
|
12
|
+
export { durabilitySemaphoreMigrations, durabilitySemaphoreQueueMigrations, } from './migrations.js';
|
|
13
|
+
export type { GrantReport, GrantResult, PermitGrant, PermitRequest, PermitSync, PermitSyncResult, SemaphoreBlockedReason, SemaphoreRequest, SemaphoreResponse, } from './semaphore-protocol.js';
|
|
14
|
+
export type { SemaphoreAddress, SemaphoreClientConfig, } from './semaphore-client.js';
|
|
15
|
+
export { SemaphoreClient } from './semaphore-client.js';
|
|
16
|
+
export type { DurabilitySemaphoreConfig, DurabilitySemaphoreEvent, SemaphoreUsage, } from './semaphore-server.js';
|
|
17
|
+
export type { SemaphoreLeaseOptions, SemaphoreProvisioning, } from './semaphore-leases.js';
|
|
18
|
+
export { DurabilitySemaphoreQueue, type AdmittedItem, type DurabilitySemaphoreQueueConfig, type DurabilitySemaphoreQueueEvent, type SemaphoreHolder, type SemaphoreInput, type SemaphoreItemStatus, } from './semaphore-queue.js';
|
|
19
|
+
export type SemaphoreSession = {
|
|
20
|
+
request(key: string, message: PermitRequest): Promise<PermitGrant>;
|
|
21
|
+
sync(key: string, message: PermitSync): Promise<PermitSyncResult>;
|
|
22
|
+
setContext(context: TransformContext): {
|
|
23
|
+
invoke(method: string, args: unknown[]): Promise<unknown>;
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
export type DurabilitySemaphoreClientConfig<Target extends Rpc.DurableObjectBranded> = DurableObjectTarget<Target> & {
|
|
27
|
+
/** Chooses the application RPC method that forwards to `handle`; never hardcoded. */
|
|
28
|
+
invoke(stub: DurableObjectStub<Target>, message: SemaphoreRequest): Promise<SemaphoreResponse>;
|
|
29
|
+
locationHint?: (key: string) => DurableObjectLocationHint | undefined;
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Inside a DO, holds one concurrency limit for many client Durable Objects.
|
|
33
|
+
* Outside the DO, `client()` routes semaphore messages to the application-owned
|
|
34
|
+
* holder class by key using ordinary @durability/transforms caller transforms.
|
|
35
|
+
*/
|
|
36
|
+
export declare class DurabilitySemaphore extends DurabilitySemaphoreServer {
|
|
37
|
+
/**
|
|
38
|
+
* Routes semaphore messages to the application-owned holder class by key.
|
|
39
|
+
* Caller transforms such as `timeout` apply; transform context is not used.
|
|
40
|
+
*/
|
|
41
|
+
static client<Target extends Rpc.DurableObjectBranded>(config: DurabilitySemaphoreClientConfig<Target>): TransformStub<SemaphoreSession>;
|
|
42
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Experimental: this entry point may change or be removed in a minor
|
|
3
|
+
* release. Pin an exact version of `durability` when depending on it.
|
|
4
|
+
*
|
|
5
|
+
* @packageDocumentation
|
|
6
|
+
*/
|
|
7
|
+
import { createTransformStub, } from '@durability/transforms';
|
|
8
|
+
import { resolveNamespace, } from './durable-object-target.js';
|
|
9
|
+
import { SemaphoreProtocolError } from './errors.js';
|
|
10
|
+
import { SemaphoreClient } from './semaphore-client.js';
|
|
11
|
+
import { DurabilitySemaphoreServer } from './semaphore-server.js';
|
|
12
|
+
export { SemaphoreProtocolError } from './errors.js';
|
|
13
|
+
export { durabilitySemaphoreMigrations, durabilitySemaphoreQueueMigrations, } from './migrations.js';
|
|
14
|
+
export { SemaphoreClient } from './semaphore-client.js';
|
|
15
|
+
export { DurabilitySemaphoreQueue, } from './semaphore-queue.js';
|
|
16
|
+
/**
|
|
17
|
+
* Inside a DO, holds one concurrency limit for many client Durable Objects.
|
|
18
|
+
* Outside the DO, `client()` routes semaphore messages to the application-owned
|
|
19
|
+
* holder class by key using ordinary @durability/transforms caller transforms.
|
|
20
|
+
*/
|
|
21
|
+
export class DurabilitySemaphore extends DurabilitySemaphoreServer {
|
|
22
|
+
/**
|
|
23
|
+
* Routes semaphore messages to the application-owned holder class by key.
|
|
24
|
+
* Caller transforms such as `timeout` apply; transform context is not used.
|
|
25
|
+
*/
|
|
26
|
+
static client(config) {
|
|
27
|
+
const client = new SemaphoreClient({
|
|
28
|
+
invoke: (address, message) => {
|
|
29
|
+
const namespace = resolveNamespace(config, (text) => new SemaphoreProtocolError(text));
|
|
30
|
+
const stub = namespace.getByName(address.key, address.locationHint === undefined
|
|
31
|
+
? undefined
|
|
32
|
+
: { locationHint: address.locationHint });
|
|
33
|
+
return config.invoke(stub, message);
|
|
34
|
+
},
|
|
35
|
+
...(config.locationHint === undefined
|
|
36
|
+
? {}
|
|
37
|
+
: { locationHint: config.locationHint }),
|
|
38
|
+
});
|
|
39
|
+
const session = {
|
|
40
|
+
request: (key, message) => client.request(key, message),
|
|
41
|
+
sync: (key, message) => client.sync(key, message),
|
|
42
|
+
setContext: () => ({
|
|
43
|
+
invoke: (method, args) => {
|
|
44
|
+
const key = args[0];
|
|
45
|
+
if (method === 'request') {
|
|
46
|
+
return client.request(key, args[1]);
|
|
47
|
+
}
|
|
48
|
+
if (method === 'sync') {
|
|
49
|
+
return client.sync(key, args[1]);
|
|
50
|
+
}
|
|
51
|
+
throw new SemaphoreProtocolError(`Unknown semaphore method "${method}"`);
|
|
52
|
+
},
|
|
53
|
+
}),
|
|
54
|
+
};
|
|
55
|
+
return createTransformStub(session);
|
|
56
|
+
}
|
|
57
|
+
}
|
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,
|
|
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
|
-
|
|
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
|
|
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,
|
|
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,
|
|
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,
|
|
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,
|
|
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.
|
|
@@ -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
|
+
};
|