durability 4.2.0 → 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.
@@ -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
+ }