@noetic-tools/platform-cloudflare-worker 0.0.0-stage → 1.0.0-next.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.
@@ -0,0 +1,155 @@
1
+ /**
2
+ * The alarm preset (spec 25 § Cloudflare Workers): a Durable Object's alarm wakes
3
+ * the harness's parked and cut turns, and the harness sets the next alarm itself,
4
+ * through `harness.onWakeTimeChange()`.
5
+ *
6
+ * A Worker has no process between requests, so the harness's own timers
7
+ * (`park.autoWake`) cannot be relied on. Build the harness with
8
+ * `park: { autoWake: false }` and let the alarm do it.
9
+ *
10
+ * A Durable Object has one alarm. An object that needs it for its own work too
11
+ * passes `schedule` in place of `alarms`, and merges the times its parts want with
12
+ * `sharedAlarm`.
13
+ */
14
+ import type { AgentHarness } from '@noetic-tools/core';
15
+ /** @public The part of a Durable Object's storage the alarm preset uses: `ctx.storage`. */
16
+ export interface AlarmStorageLike {
17
+ setAlarm(scheduledTime: number): Promise<void> | void;
18
+ deleteAlarm(): Promise<void> | void;
19
+ }
20
+ /** @public The part of a Durable Object's storage `sharedAlarm` uses: `ctx.storage`. */
21
+ export interface SharedAlarmStorageLike extends AlarmStorageLike {
22
+ getAlarm(): Promise<number | null> | number | null;
23
+ }
24
+ /** @public The harness methods the alarm preset calls. An `AgentHarness` fits. */
25
+ export type WakeableHarness = Pick<AgentHarness, 'start' | 'wake' | 'getNextWakeTime' | 'waitForIdle' | 'onWakeTimeChange'>;
26
+ /**
27
+ * @public
28
+ * Asks for the alarm at `at`, epoch ms, or for none: one part's say in an alarm
29
+ * the host shares (`sharedAlarm(...).schedule(name)`).
30
+ */
31
+ export type AlarmSchedule = (at: number | undefined) => Promise<void> | void;
32
+ interface AlarmWakeBase {
33
+ harness: WakeableHarness;
34
+ /** The clock the harness runs on, when it is not `Date.now`. */
35
+ now?: () => number;
36
+ }
37
+ /** @public Options for `alarmWake`: the object's alarm, or a `schedule` the host merges. */
38
+ export type AlarmWakeOptions = AlarmWakeBase & ({
39
+ /** The object's storage, `ctx.storage`: the preset owns the alarm. */
40
+ alarms: AlarmStorageLike;
41
+ schedule?: never;
42
+ } | {
43
+ /** Where the preset says the time it wants; the host sets the alarm. */
44
+ schedule: AlarmSchedule;
45
+ alarms?: never;
46
+ });
47
+ /** @public What `alarmWake` returns. */
48
+ export interface AlarmWake {
49
+ /**
50
+ * Call from the object's `alarm()` handler, or from inside `sharedAlarm`'s
51
+ * `alarm()`. Starts the harness, so a `cron()` source delivers the ticks that fell
52
+ * due while nothing ran; wakes every parked or cut turn that is due; waits for
53
+ * every turn to finish or park again; then asks for the next alarm. It does not
54
+ * throw for a turn that failed: a throw would make the runtime retry the alarm,
55
+ * and the failure is already on the turn. Resolves the ids of the threads it woke.
56
+ */
57
+ alarm(): Promise<string[]>;
58
+ /** The time last asked for, epoch ms; undefined when none was, or none is wanted. */
59
+ wantedAt(): number | undefined;
60
+ /** Stop asking for alarms from the harness. */
61
+ stop(): void;
62
+ }
63
+ /** @public What `sharedAlarm` returns. */
64
+ export interface SharedAlarm {
65
+ /**
66
+ * A `schedule` for one part of the object, named `name`, which `alarmWake` takes:
67
+ * each call replaces that part's time.
68
+ */
69
+ schedule(name: string): AlarmSchedule;
70
+ /** The earliest time any part wants, epoch ms, or undefined. */
71
+ wantedAt(): number | undefined;
72
+ /**
73
+ * Call from the object's `alarm()` handler. Forgets every time that has come,
74
+ * runs `handler`, in which each part does its work and says its next time again,
75
+ * then sets the alarm to the earliest time any part wants, deleting it when none
76
+ * does. A throw from `handler` still leaves the alarm set, and reaches the runtime,
77
+ * which retries the alarm.
78
+ */
79
+ alarm(handler: () => Promise<void>): Promise<void>;
80
+ }
81
+ /** @public The part of a Durable Object's state `durableObjectHolder` reads: `ctx`. */
82
+ export interface DurableObjectStateLike {
83
+ readonly id: {
84
+ toString(): string;
85
+ };
86
+ }
87
+ /**
88
+ * @public
89
+ * Wake parked and cut turns from a Durable Object alarm. From here on the harness
90
+ * keeps the object's alarm at its next wake time (a parked turn's deadline, a cut
91
+ * turn's back-off, a `cron()` tick), and clears it when there is none: the first
92
+ * time when the harness starts, then whenever the time changes. A turn that parks
93
+ * or is cut does not answer until its alarm is set.
94
+ *
95
+ * Given `schedule` in place of `alarms`, it sets nothing itself: it says the time
96
+ * it wants, and the host merges it with its own (`sharedAlarm`).
97
+ *
98
+ * @example
99
+ * ```ts
100
+ * export class Agent extends DurableObject {
101
+ * #harness = buildHarness(createDurableObjectStorage({ sql: this.ctx.storage.sql }));
102
+ * #wake = alarmWake({ harness: this.#harness, alarms: this.ctx.storage });
103
+ *
104
+ * async alarm() {
105
+ * await this.#wake.alarm();
106
+ * }
107
+ *
108
+ * async message(text: string, messageId: string) {
109
+ * await this.#harness.execute(text, { threadId: 'main', messageId });
110
+ * return this.#harness.getAgentResponse({ threadId: 'main' });
111
+ * }
112
+ * }
113
+ * ```
114
+ */
115
+ export declare function alarmWake(options: AlarmWakeOptions): AlarmWake;
116
+ /**
117
+ * @public
118
+ * One Durable Object alarm shared by several parts of the object: the harness's
119
+ * `alarmWake` and the object's own work. Each part says the time it wants through
120
+ * its `schedule(name)`; the alarm is kept at the earliest.
121
+ *
122
+ * Outside `alarm()` a part's time only moves the stored alarm earlier: after the
123
+ * isolate restarts, the other parts' times are no longer in memory, and an alarm
124
+ * that fires early does no harm. Inside it, every part says its time again, and the
125
+ * alarm is set to the earliest of them.
126
+ *
127
+ * @example
128
+ * ```ts
129
+ * export class Session extends DurableObject {
130
+ * #alarms = sharedAlarm(this.ctx.storage);
131
+ * #wake = alarmWake({ harness: this.#harness, schedule: this.#alarms.schedule('noetic') });
132
+ * #retries = this.#alarms.schedule('retries');
133
+ *
134
+ * async alarm() {
135
+ * await this.#alarms.alarm(async () => {
136
+ * await this.#wake.alarm();
137
+ * await this.#retries(await this.retryWrites());
138
+ * });
139
+ * }
140
+ * }
141
+ * ```
142
+ */
143
+ export declare function sharedAlarm(storage: SharedAlarmStorageLike, options?: {
144
+ now?: () => number;
145
+ }): SharedAlarm;
146
+ /**
147
+ * @public
148
+ * The lease holder name for a harness in a Durable Object: the object's id. One
149
+ * instance of an object runs at a time, so the object that comes back after its
150
+ * isolate died takes its threads' leases over at once, and finds a turn the dead
151
+ * isolate was running due now, not one lease period later (spec 23 § One writer per
152
+ * turn). Pass it as `environment.storage.lease.holder`.
153
+ */
154
+ export declare function durableObjectHolder(state: DurableObjectStateLike): string;
155
+ export {};
@@ -0,0 +1,211 @@
1
+ /**
2
+ * The alarm preset (spec 25 § Cloudflare Workers): a Durable Object's alarm wakes
3
+ * the harness's parked and cut turns, and the harness sets the next alarm itself,
4
+ * through `harness.onWakeTimeChange()`.
5
+ *
6
+ * A Worker has no process between requests, so the harness's own timers
7
+ * (`park.autoWake`) cannot be relied on. Build the harness with
8
+ * `park: { autoWake: false }` and let the alarm do it.
9
+ *
10
+ * A Durable Object has one alarm. An object that needs it for its own work too
11
+ * passes `schedule` in place of `alarms`, and merges the times its parts want with
12
+ * `sharedAlarm`.
13
+ */
14
+ /**
15
+ * How long until the alarm tries again when, after a whole pass, something is still
16
+ * due that the pass could not do: a schedule's event its source did not deliver.
17
+ */
18
+ const RETRY_MS = 3e4;
19
+ //#endregion
20
+ //#region Public API
21
+ /**
22
+ * @public
23
+ * Wake parked and cut turns from a Durable Object alarm. From here on the harness
24
+ * keeps the object's alarm at its next wake time (a parked turn's deadline, a cut
25
+ * turn's back-off, a `cron()` tick), and clears it when there is none: the first
26
+ * time when the harness starts, then whenever the time changes. A turn that parks
27
+ * or is cut does not answer until its alarm is set.
28
+ *
29
+ * Given `schedule` in place of `alarms`, it sets nothing itself: it says the time
30
+ * it wants, and the host merges it with its own (`sharedAlarm`).
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * export class Agent extends DurableObject {
35
+ * #harness = buildHarness(createDurableObjectStorage({ sql: this.ctx.storage.sql }));
36
+ * #wake = alarmWake({ harness: this.#harness, alarms: this.ctx.storage });
37
+ *
38
+ * async alarm() {
39
+ * await this.#wake.alarm();
40
+ * }
41
+ *
42
+ * async message(text: string, messageId: string) {
43
+ * await this.#harness.execute(text, { threadId: 'main', messageId });
44
+ * return this.#harness.getAgentResponse({ threadId: 'main' });
45
+ * }
46
+ * }
47
+ * ```
48
+ */
49
+ export function alarmWake(options) {
50
+ const { harness } = options;
51
+ let wanted;
52
+ async function set(at) {
53
+ wanted = at;
54
+ if (options.schedule) {
55
+ await options.schedule(at);
56
+ return;
57
+ }
58
+ if (at === undefined) {
59
+ await options.alarms.deleteAlarm();
60
+ return;
61
+ }
62
+ await options.alarms.setAlarm(at);
63
+ }
64
+ const stop = harness.onWakeTimeChange(set);
65
+ return {
66
+ stop,
67
+ wantedAt: () => wanted,
68
+ async alarm() {
69
+ await harness.start();
70
+ const woken = await harness.wake();
71
+ // The handler is what keeps the object alive: stay until every turn has
72
+ // finished or parked again.
73
+ await harness.waitForIdle();
74
+ // The alarm that fired is spent. Set it again even when the time did not
75
+ // change, as when it fired early and nothing was due.
76
+ const next = await harness.getNextWakeTime();
77
+ const now = (options.now ?? Date.now)();
78
+ // Still due after a pass that did all it could: an alarm set in the past
79
+ // fires at once, and the object would spin. Try again in a while.
80
+ await set(next !== undefined && next <= now ? now + RETRY_MS : next);
81
+ return woken;
82
+ },
83
+ };
84
+ }
85
+ /**
86
+ * @public
87
+ * One Durable Object alarm shared by several parts of the object: the harness's
88
+ * `alarmWake` and the object's own work. Each part says the time it wants through
89
+ * its `schedule(name)`; the alarm is kept at the earliest.
90
+ *
91
+ * Outside `alarm()` a part's time only moves the stored alarm earlier: after the
92
+ * isolate restarts, the other parts' times are no longer in memory, and an alarm
93
+ * that fires early does no harm. Inside it, every part says its time again, and the
94
+ * alarm is set to the earliest of them.
95
+ *
96
+ * @example
97
+ * ```ts
98
+ * export class Session extends DurableObject {
99
+ * #alarms = sharedAlarm(this.ctx.storage);
100
+ * #wake = alarmWake({ harness: this.#harness, schedule: this.#alarms.schedule('noetic') });
101
+ * #retries = this.#alarms.schedule('retries');
102
+ *
103
+ * async alarm() {
104
+ * await this.#alarms.alarm(async () => {
105
+ * await this.#wake.alarm();
106
+ * await this.#retries(await this.retryWrites());
107
+ * });
108
+ * }
109
+ * }
110
+ * ```
111
+ */
112
+ export function sharedAlarm(storage, options) {
113
+ const wants = new Map();
114
+ let firing = false;
115
+ const now = options?.now ?? Date.now;
116
+ /** Storage updates, one at a time: each reads the alarm and then sets it. */
117
+ let updating = Promise.resolve();
118
+ function earliest() {
119
+ let first;
120
+ for (const at of wants.values()) {
121
+ first = first === undefined ? at : Math.min(first, at);
122
+ }
123
+ return first;
124
+ }
125
+ function inTurn(update) {
126
+ const next = updating.then(update);
127
+ updating = next.catch(() => undefined);
128
+ return next;
129
+ }
130
+ /** Outside the handler: bring the alarm forward when a part wants it sooner. */
131
+ async function bringForward() {
132
+ const current = await storage.getAlarm();
133
+ // Read after the await: a part may have asked meanwhile.
134
+ const first = earliest();
135
+ if (first === undefined) {
136
+ return;
137
+ }
138
+ if (current === null || current > first) {
139
+ await storage.setAlarm(first);
140
+ }
141
+ }
142
+ /** After the handler: every part has said its time, so the earliest is the alarm. */
143
+ async function settle() {
144
+ const first = earliest();
145
+ if (first === undefined) {
146
+ await storage.deleteAlarm();
147
+ return;
148
+ }
149
+ await storage.setAlarm(first);
150
+ }
151
+ return {
152
+ schedule: (name) => async (at) => {
153
+ if (at === undefined) {
154
+ wants.delete(name);
155
+ }
156
+ else {
157
+ wants.set(name, at);
158
+ }
159
+ // Inside the handler the alarm is set once, when it has run.
160
+ if (firing) {
161
+ return;
162
+ }
163
+ await inTurn(bringForward);
164
+ },
165
+ wantedAt: earliest,
166
+ async alarm(handler) {
167
+ const at = now();
168
+ for (const [name, wanted] of wants) {
169
+ if (wanted <= at) {
170
+ wants.delete(name);
171
+ }
172
+ }
173
+ firing = true;
174
+ let failure;
175
+ try {
176
+ await handler();
177
+ }
178
+ catch (error) {
179
+ failure = {
180
+ error,
181
+ };
182
+ }
183
+ firing = false;
184
+ try {
185
+ await inTurn(settle);
186
+ }
187
+ catch (error) {
188
+ // The handler's own failure is the one the runtime should hear.
189
+ if (!failure) {
190
+ throw error;
191
+ }
192
+ console.warn('[noetic] sharedAlarm could not set the alarm:', error);
193
+ }
194
+ if (failure) {
195
+ throw failure.error;
196
+ }
197
+ },
198
+ };
199
+ }
200
+ /**
201
+ * @public
202
+ * The lease holder name for a harness in a Durable Object: the object's id. One
203
+ * instance of an object runs at a time, so the object that comes back after its
204
+ * isolate died takes its threads' leases over at once, and finds a turn the dead
205
+ * isolate was running due now, not one lease period later (spec 23 § One writer per
206
+ * turn). Pass it as `environment.storage.lease.holder`.
207
+ */
208
+ export function durableObjectHolder(state) {
209
+ return state.id.toString();
210
+ }
211
+ //#endregion
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Cloudflare Cron Triggers as wakes for durable work (spec 25 § Cron Triggers):
3
+ * `cronWake` scans work that keeps its own cursor, and `cronTurn` gives each tick
4
+ * to a Durable Object's harness as a message.
5
+ */
6
+ import type { AgentHarness, ExecuteInput, ExecuteOptions, StorageAdapter } from '@noetic-tools/core';
7
+ import type { AlarmWake } from './alarm-wake.js';
8
+ /** @public The fields Cloudflare passes to the Worker's scheduled handler. */
9
+ export interface CronTick {
10
+ cron: string;
11
+ scheduledTime: number;
12
+ }
13
+ /** @public Options for a harness turn per cron tick. */
14
+ export interface CronTurnOptions {
15
+ cron: string;
16
+ /** Unique among the harness's cron jobs. */
17
+ name: string;
18
+ /** The harness the object's other messages go to. */
19
+ harness: Pick<AgentHarness, 'execute' | 'getAgentResponse'>;
20
+ /** The object's alarm preset, over the same harness. */
21
+ wake: Pick<AlarmWake, 'alarm'>;
22
+ /** What the turn is given. */
23
+ input: ExecuteInput | ((tick: CronTick) => ExecuteInput);
24
+ /** `execute()` options other than the identity and delivery mode the preset sets. */
25
+ options?: Omit<ExecuteOptions, 'threadId' | 'messageId' | 'deliveryMode'>;
26
+ }
27
+ /** @public Options for a periodic scan of durable work. */
28
+ export interface CronWakeOptions<Env> {
29
+ cron: string;
30
+ /** Unique among cron jobs sharing the same storage. */
31
+ name: string;
32
+ storage(env: Env): StorageAdapter;
33
+ /** Scan for all due work. It may be called again after a partial pass. */
34
+ run(env: Env, through: number): Promise<void>;
35
+ /** The wall clock, in milliseconds. */
36
+ now?: () => number;
37
+ }
38
+ /**
39
+ * @public
40
+ * Give each Cloudflare cron tick to a Durable Object's harness as one message, by
41
+ * the same `harness.execute()` the object's requests use. Route the Worker's
42
+ * `scheduled` handler to a method of the named object, and call this there.
43
+ *
44
+ * Each tick owns the thread and message id `cron:<name>:<scheduledTime>`. A later
45
+ * tick cannot replace its checkpoint or evict its completed receipt. Queued delivery
46
+ * lets a duplicate join the active turn. The alarm pass wakes due work before
47
+ * delivery. The tick's own response keeps the handler alive until it settles,
48
+ * parks or cuts. A failed response rejects the handler so its caller can report
49
+ * or retry that tick.
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * export class Agent extends DurableObject {
54
+ * #harness = buildHarness(durableObjectEnvironment(this.ctx));
55
+ * #wake = alarmWake({ harness: this.#harness, alarms: this.ctx.storage });
56
+ * #digest = cronTurn({
57
+ * cron: '0 8 * * *',
58
+ * name: 'digest',
59
+ * harness: this.#harness,
60
+ * wake: this.#wake,
61
+ * input: 'Write the morning digest.',
62
+ * });
63
+ *
64
+ * async alarm() {
65
+ * await this.#wake.alarm();
66
+ * }
67
+ *
68
+ * async tick(tick: CronTick) {
69
+ * await this.#digest(tick);
70
+ * }
71
+ * }
72
+ *
73
+ * export default {
74
+ * async scheduled(controller, env) {
75
+ * await env.AGENT.getByName('main').tick({
76
+ * cron: controller.cron,
77
+ * scheduledTime: controller.scheduledTime,
78
+ * });
79
+ * },
80
+ * };
81
+ * ```
82
+ */
83
+ export declare function cronTurn(options: CronTurnOptions): (tick: CronTick) => Promise<void>;
84
+ /**
85
+ * @public
86
+ * Turn Cloudflare cron ticks into scans of durable work. A successful scan covers
87
+ * earlier ticks too. Duplicate or concurrent delivery does not start another scan.
88
+ * The next tick can retry a failed scan, and can take over after a lost Worker’s
89
+ * lease expires. Keep the work's own cursor and use stable keys for its effects.
90
+ */
91
+ export declare function cronWake<Env>(options: CronWakeOptions<Env>): (tick: CronTick, env: Env) => Promise<void>;
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Cloudflare Cron Triggers as wakes for durable work (spec 25 § Cron Triggers):
3
+ * `cronWake` scans work that keeps its own cursor, and `cronTurn` gives each tick
4
+ * to a Durable Object's harness as a message.
5
+ */
6
+ //#endregion
7
+ //#region Public API
8
+ /**
9
+ * @public
10
+ * Give each Cloudflare cron tick to a Durable Object's harness as one message, by
11
+ * the same `harness.execute()` the object's requests use. Route the Worker's
12
+ * `scheduled` handler to a method of the named object, and call this there.
13
+ *
14
+ * Each tick owns the thread and message id `cron:<name>:<scheduledTime>`. A later
15
+ * tick cannot replace its checkpoint or evict its completed receipt. Queued delivery
16
+ * lets a duplicate join the active turn. The alarm pass wakes due work before
17
+ * delivery. The tick's own response keeps the handler alive until it settles,
18
+ * parks or cuts. A failed response rejects the handler so its caller can report
19
+ * or retry that tick.
20
+ *
21
+ * @example
22
+ * ```ts
23
+ * export class Agent extends DurableObject {
24
+ * #harness = buildHarness(durableObjectEnvironment(this.ctx));
25
+ * #wake = alarmWake({ harness: this.#harness, alarms: this.ctx.storage });
26
+ * #digest = cronTurn({
27
+ * cron: '0 8 * * *',
28
+ * name: 'digest',
29
+ * harness: this.#harness,
30
+ * wake: this.#wake,
31
+ * input: 'Write the morning digest.',
32
+ * });
33
+ *
34
+ * async alarm() {
35
+ * await this.#wake.alarm();
36
+ * }
37
+ *
38
+ * async tick(tick: CronTick) {
39
+ * await this.#digest(tick);
40
+ * }
41
+ * }
42
+ *
43
+ * export default {
44
+ * async scheduled(controller, env) {
45
+ * await env.AGENT.getByName('main').tick({
46
+ * cron: controller.cron,
47
+ * scheduledTime: controller.scheduledTime,
48
+ * });
49
+ * },
50
+ * };
51
+ * ```
52
+ */
53
+ export function cronTurn(options) {
54
+ const { harness, wake, input } = options;
55
+ return async (tick) => {
56
+ if (tick.cron !== options.cron) {
57
+ return;
58
+ }
59
+ await wake.alarm();
60
+ const id = `cron:${options.name}:${tick.scheduledTime}`;
61
+ await harness.execute(typeof input === 'function' ? input(tick) : input, {
62
+ ...options.options,
63
+ threadId: id,
64
+ messageId: id,
65
+ deliveryMode: 'next-turn',
66
+ });
67
+ await harness.getAgentResponse({
68
+ threadId: id,
69
+ });
70
+ };
71
+ }
72
+ /**
73
+ * @public
74
+ * Turn Cloudflare cron ticks into scans of durable work. A successful scan covers
75
+ * earlier ticks too. Duplicate or concurrent delivery does not start another scan.
76
+ * The next tick can retry a failed scan, and can take over after a lost Worker’s
77
+ * lease expires. Keep the work's own cursor and use stable keys for its effects.
78
+ */
79
+ export function cronWake(options) {
80
+ const key = `noetic/cron/${options.name}`;
81
+ const now = options.now ?? Date.now;
82
+ return async (tick, env) => {
83
+ if (tick.cron !== options.cron) {
84
+ return;
85
+ }
86
+ const store = options.storage(env);
87
+ if (!store.swap) {
88
+ throw new Error('cronWake needs storage with swap');
89
+ }
90
+ const state = await store.get(key);
91
+ const done = state?.done ?? -1;
92
+ const at = now();
93
+ if (done >= tick.scheduledTime || (state?.lease && state.lease.until > at)) {
94
+ return;
95
+ }
96
+ const claim = {
97
+ done,
98
+ lease: {
99
+ id: crypto.randomUUID(),
100
+ until: at + LEASE_MS,
101
+ },
102
+ };
103
+ if (!(await store.swap(key, state, claim))) {
104
+ return;
105
+ }
106
+ let through = done;
107
+ try {
108
+ await options.run(env, tick.scheduledTime);
109
+ through = tick.scheduledTime;
110
+ }
111
+ finally {
112
+ await store.swap(key, claim, {
113
+ done: through,
114
+ });
115
+ }
116
+ };
117
+ }
118
+ // A Cron Trigger invocation can live for up to 15 minutes.
119
+ const LEASE_MS = 16 * 60_000;
120
+ //#endregion
@@ -0,0 +1,56 @@
1
+ import type { StorageAdapter } from '@noetic-tools/core';
2
+ import type { SpillOptions } from './spill-storage.js';
3
+ /** @public The part of a D1 prepared statement this adapter uses. */
4
+ export interface D1StatementLike {
5
+ bind(...values: string[]): D1StatementLike;
6
+ first(): Promise<unknown>;
7
+ all(): Promise<{
8
+ results?: unknown[];
9
+ }>;
10
+ run(): Promise<{
11
+ meta: {
12
+ changes?: number;
13
+ };
14
+ }>;
15
+ }
16
+ /** @public The part of a D1 database binding this adapter uses. Pass `env.DB`. */
17
+ export interface D1DatabaseLike {
18
+ prepare(query: string): D1StatementLike;
19
+ /** Run statements in one transaction, as the D1 binding does. */
20
+ batch?(statements: D1StatementLike[]): Promise<Array<{
21
+ results?: unknown[];
22
+ }>>;
23
+ }
24
+ /** @public Options for `createD1Storage`. */
25
+ export interface CreateD1StorageOptions {
26
+ /** The D1 binding. */
27
+ database: D1DatabaseLike;
28
+ /** Table the entries live in. Created when missing. Default `noetic_storage`. */
29
+ table?: string;
30
+ /**
31
+ * Keep this storage's rows apart from others in the same table: one scope per
32
+ * tenant, user or environment. The table is then `(scope, key, value)`. Every
33
+ * adapter on one table is scoped, or none is.
34
+ */
35
+ scope?: string;
36
+ /** Write values too large for a row to a blob store, and keep a pointer in the row. */
37
+ spill?: SpillOptions;
38
+ }
39
+ /**
40
+ * @public
41
+ * A `StorageAdapter` over one D1 table, one row per key, with `swap`: the
42
+ * compare-and-set a turn lease needs (spec 23 § One writer per turn). Every Worker
43
+ * bound to the same database shares one storage, or with `scope`, one storage per
44
+ * scope. `swap` is a single conditional statement, so D1 decides the winner.
45
+ *
46
+ * Values are stored as their JSON encoding. `swap` compares encodings, so pass
47
+ * `prev` as it was read from this storage. A D1 row holds about 2 MB: give `spill`
48
+ * a blob store for values that can grow past that, such as a long thread's record.
49
+ *
50
+ * A write that fails throws; nothing is swallowed.
51
+ *
52
+ * @throws Error when `table` is not a plain identifier, or `scope` is empty; and
53
+ * from the first call, when the table's shape does not match `scope` (a scoped
54
+ * table read without one, or the reverse).
55
+ */
56
+ export declare function createD1Storage(options: CreateD1StorageOptions): StorageAdapter;