@astrale-os/adapter-cloudflare 0.5.0-beta.227 → 0.5.0-beta.229

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 CHANGED
@@ -127,7 +127,8 @@ Node and inside a Worker (`fetch` and WebCrypto only).
127
127
  the name's labels), `cron:<name>` (canonical UTC crons). The record's metadata is mandatory: a
128
128
  `record:<label>` without it activates nothing at the dispatcher (every path of the label answers
129
129
  as not active yet, and no cron fires on it) and the kit refuses it (`record-invalid`) instead of
130
- reading it as any record. Every write is read back before it counts.
130
+ reading it as any record. Every write is read back before it counts, for up to 65 s: a Workers
131
+ KV location keeps each read it answered, a key's absence included, for 60 s after it.
131
132
  - **Scripts.** `deploymentBindings`, `deploymentTags` (with a host's extra tags),
132
133
  `uploadDeploymentScript` (create-only, every module kind, assets in parallel),
133
134
  `observeScript`, `scriptSettings`, `scriptSecretNames`, `putScriptSecret`, `deleteScript`, and
@@ -88,7 +88,16 @@ export declare class CloudflareClient {
88
88
  private readonly rateLimit;
89
89
  private readonly pause;
90
90
  private readonly now;
91
+ private readonly options;
91
92
  constructor(options: CloudflareClientOptions);
93
+ /**
94
+ * Run `attempt` until it succeeds, trying it again after an `unavailable` failure (from 250 ms,
95
+ * doubling up to 2 s) for `withinMs`, never past the client's deadline, on the client's clock and
96
+ * cancellation. Each attempt runs on a client bounded by that deadline: its requests time out and
97
+ * its rate-limit waits stop there. Any other failure, or the last `unavailable` one, rejects. Only
98
+ * for attempts a retry cannot harm, such as reads.
99
+ */
100
+ retryWithin<Result>(withinMs: number, attempt: (client: CloudflareClient) => Promise<Result>): Promise<Result>;
92
101
  /** `/accounts/<account><path>`. */
93
102
  account(path: string): string;
94
103
  /** `/zones/<zone><path>`. */
@@ -1,5 +1,5 @@
1
1
  import { retryAfterMs } from './retry-after.js';
2
- import { wait } from './time.js';
2
+ import { retryUntil, wait } from './time.js';
3
3
  /** Cloudflare's REST API. The kit calls it directly: Wrangler has no create-only upload. */
4
4
  export const CLOUDFLARE_API_BASE = 'https://api.cloudflare.com/client/v4';
5
5
  const DEFAULT_TIMEOUT_MS = 30_000;
@@ -9,6 +9,9 @@ const MAXIMUM_JSON_RESPONSE_BYTES = 8 * 1024 * 1024;
9
9
  const MAXIMUM_TEXT_RESPONSE_BYTES = 1024 * 1024;
10
10
  /** Without `Retry-After`, a rate-limited resend backs off from one second, doubling. */
11
11
  const RATE_LIMIT_BACKOFF_MS = 1_000;
12
+ /** `retryWithin` waits from 250 ms between attempts, doubling up to 2 s. */
13
+ const RETRY_INTERVAL_MS = 250;
14
+ const MAXIMUM_RETRY_INTERVAL_MS = 2_000;
12
15
  /** The most entries one page of a numbered listing asks for, as Cloudflare caps KV namespaces. */
13
16
  const PAGE_SIZE = 1_000;
14
17
  /** A deploy's policy: three resends, none waiting more than 10 s. */
@@ -58,7 +61,9 @@ export class CloudflareClient {
58
61
  rateLimit;
59
62
  pause;
60
63
  now;
64
+ options;
61
65
  constructor(options) {
66
+ this.options = options;
62
67
  if (!stable(options.accountId))
63
68
  invalid('Cloudflare accountId is required.');
64
69
  if (!stable(options.token)) {
@@ -87,6 +92,26 @@ export class CloudflareClient {
87
92
  this.pause = options.pause ?? wait;
88
93
  this.now = options.now ?? Date.now;
89
94
  }
95
+ /**
96
+ * Run `attempt` until it succeeds, trying it again after an `unavailable` failure (from 250 ms,
97
+ * doubling up to 2 s) for `withinMs`, never past the client's deadline, on the client's clock and
98
+ * cancellation. Each attempt runs on a client bounded by that deadline: its requests time out and
99
+ * its rate-limit waits stop there. Any other failure, or the last `unavailable` one, rejects. Only
100
+ * for attempts a retry cannot harm, such as reads.
101
+ */
102
+ async retryWithin(withinMs, attempt) {
103
+ const deadline = Math.min(this.now() + withinMs, this.deadline ?? Number.POSITIVE_INFINITY);
104
+ const bounded = new CloudflareClient({ ...this.options, deadline });
105
+ return retryUntil(() => attempt(bounded), {
106
+ deadline,
107
+ intervalMs: RETRY_INTERVAL_MS,
108
+ maximumIntervalMs: MAXIMUM_RETRY_INTERVAL_MS,
109
+ retryable: (cause) => cause instanceof CloudflareApiError && cause.kind === 'unavailable',
110
+ ...(this.signal === undefined ? {} : { signal: this.signal }),
111
+ now: this.now,
112
+ pause: this.pause,
113
+ });
114
+ }
90
115
  /** `/accounts/<account><path>`. */
91
116
  account(path) {
92
117
  return `/accounts/${encodeURIComponent(this.accountId)}${path}`;
@@ -12,7 +12,7 @@ import type { CloudflareClient } from './client.js';
12
12
  * `record:<label>` activates the label and outlives its retirement. Its metadata is mandatory: a
13
13
  * value without it is no record the kit writes: it activates nothing at the dispatcher, and the
14
14
  * kit refuses it (`record-invalid`). Workers KV has no compare-and-set: every write is read
15
- * back before it counts.
15
+ * back before it counts, within `KV_VISIBILITY_MS`.
16
16
  */
17
17
  export declare const RECORD_PREFIX = "record:";
18
18
  export declare const RETIREMENT_PREFIX = "retirement:";
@@ -49,9 +49,19 @@ export type RoutingKvLocator = {
49
49
  } | {
50
50
  readonly title: string;
51
51
  };
52
+ /**
53
+ * The longest a Workers KV write or delete may stay invisible to a reader, the kit's own reads
54
+ * through the account API included. A location keeps each read it answers, a key's absence
55
+ * included, for the read's `cacheTtl`, and a change does not evict it: a reader that read the key
56
+ * just before the change sees the change only once that entry expires. An account API read sets
57
+ * no `cacheTtl` and keeps the default, 60 s, as every dispatcher read does; 5 s cover the expiry.
58
+ * A read back that misses a change sooner is no evidence that the change was lost.
59
+ */
60
+ export declare const KV_VISIBILITY_MS = 65000;
52
61
  /**
53
62
  * One routing KV, through the account API. Reads answer the stored text (undefined when absent);
54
- * every write and delete is read back before it counts, and fails `unavailable` otherwise.
63
+ * every write and delete is read back before it counts, and fails `unavailable` when it does not
64
+ * read back within `KV_VISIBILITY_MS` (or the client's deadline).
55
65
  */
56
66
  export declare class RoutingKv {
57
67
  private readonly client;
@@ -83,6 +93,12 @@ export declare class RoutingKv {
83
93
  * the listing's cursor to its end.
84
94
  */
85
95
  keys(prefix: string): Promise<readonly string[]>;
96
+ /**
97
+ * Read back what a write or delete at `key` left, until `kept` admits it, within
98
+ * `KV_VISIBILITY_MS`; a read that fails `unavailable` is tried again too. `kept` reads through this
99
+ * KV on a client bounded by that budget, so no single read outlasts it.
100
+ */
101
+ private readBack;
86
102
  private value;
87
103
  private path;
88
104
  }
@@ -15,7 +15,7 @@ import { HostingRefusal } from './refusal.js';
15
15
  * `record:<label>` activates the label and outlives its retirement. Its metadata is mandatory: a
16
16
  * value without it is no record the kit writes: it activates nothing at the dispatcher, and the
17
17
  * kit refuses it (`record-invalid`). Workers KV has no compare-and-set: every write is read
18
- * back before it counts.
18
+ * back before it counts, within `KV_VISIBILITY_MS`.
19
19
  */
20
20
  export const RECORD_PREFIX = 'record:';
21
21
  export const RETIREMENT_PREFIX = 'retirement:';
@@ -87,11 +87,21 @@ export function decodeSchedules(text, name) {
87
87
  }
88
88
  return crons;
89
89
  }
90
+ /**
91
+ * The longest a Workers KV write or delete may stay invisible to a reader, the kit's own reads
92
+ * through the account API included. A location keeps each read it answers, a key's absence
93
+ * included, for the read's `cacheTtl`, and a change does not evict it: a reader that read the key
94
+ * just before the change sees the change only once that entry expires. An account API read sets
95
+ * no `cacheTtl` and keeps the default, 60 s, as every dispatcher read does; 5 s cover the expiry.
96
+ * A read back that misses a change sooner is no evidence that the change was lost.
97
+ */
98
+ export const KV_VISIBILITY_MS = 65_000;
90
99
  /** The most keys one page of a KV key listing returns, as Cloudflare caps it. */
91
100
  const KEYS_PAGE = 1_000;
92
101
  /**
93
102
  * One routing KV, through the account API. Reads answer the stored text (undefined when absent);
94
- * every write and delete is read back before it counts, and fails `unavailable` otherwise.
103
+ * every write and delete is read back before it counts, and fails `unavailable` when it does not
104
+ * read back within `KV_VISIBILITY_MS` (or the client's deadline).
95
105
  */
96
106
  export class RoutingKv {
97
107
  client;
@@ -124,8 +134,7 @@ export class RoutingKv {
124
134
  /** Write `text` at `key`, then read it back. */
125
135
  async put(key, text, contentType) {
126
136
  await this.client.text('PUT', this.value(key), { text, contentType });
127
- if ((await this.get(key)) !== text)
128
- notKept(key);
137
+ await this.readBack(key, 'write', async (kv) => (await kv.get(key)) === text);
129
138
  }
130
139
  /**
131
140
  * The bytes stored at `key` and their metadata (`null` when they were written without), or
@@ -153,19 +162,18 @@ export class RoutingKv {
153
162
  form.append('value', new Blob([bytes]));
154
163
  form.append('metadata', text);
155
164
  await this.client.form('PUT', this.value(key), form);
156
- const stored = await this.getWithMetadata(key);
157
- if (stored === undefined ||
158
- stored.bytes.byteLength !== bytes.byteLength ||
159
- stored.bytes.some((byte, index) => byte !== bytes[index]) ||
160
- JSON.stringify(stored.metadata) !== text) {
161
- notKept(key);
162
- }
165
+ await this.readBack(key, 'write', async (kv) => {
166
+ const stored = await kv.getWithMetadata(key);
167
+ return (stored !== undefined &&
168
+ stored.bytes.byteLength === bytes.byteLength &&
169
+ stored.bytes.every((byte, index) => byte === bytes[index]) &&
170
+ JSON.stringify(stored.metadata) === text);
171
+ });
163
172
  }
164
173
  /** Delete `key`, then read back its absence. */
165
174
  async delete(key) {
166
175
  await this.client.text('DELETE', this.value(key));
167
- if ((await this.get(key)) !== undefined)
168
- notKept(key);
176
+ await this.readBack(key, 'delete', async (kv) => (await kv.get(key)) === undefined);
169
177
  }
170
178
  /**
171
179
  * Every key name that starts with `prefix`, in Cloudflare's (lexicographic) order, following
@@ -182,6 +190,17 @@ export class RoutingKv {
182
190
  return name;
183
191
  }));
184
192
  }
193
+ /**
194
+ * Read back what a write or delete at `key` left, until `kept` admits it, within
195
+ * `KV_VISIBILITY_MS`; a read that fails `unavailable` is tried again too. `kept` reads through this
196
+ * KV on a client bounded by that budget, so no single read outlasts it.
197
+ */
198
+ async readBack(key, effect, kept) {
199
+ await this.client.retryWithin(KV_VISIBILITY_MS, async (client) => {
200
+ if (!(await kept(new RoutingKv(client, this.id))))
201
+ notKept(key, effect);
202
+ });
203
+ }
185
204
  value(key) {
186
205
  return this.path('values', key);
187
206
  }
@@ -201,7 +220,16 @@ export async function findKvNamespace(client, title) {
201
220
  }
202
221
  return found.id;
203
222
  }
204
- function notKept(key) {
205
- const kind = key.slice(0, key.indexOf(':') + 1) || 'a key';
206
- throw new CloudflareApiError('unavailable', `Cloudflare did not keep the write at ${kind}.`);
223
+ /** What a routing key holds, in words: an error names the kind of key, never the key or value. */
224
+ const KEY_KINDS = Object.freeze({
225
+ [RECORD_PREFIX]: 'deployment record',
226
+ [RETIREMENT_PREFIX]: 'retirement tombstone',
227
+ [CURRENT_PREFIX]: 'current deployment',
228
+ [CRON_PREFIX]: 'schedules',
229
+ });
230
+ function notKept(key, effect) {
231
+ const kind = KEY_KINDS[key.slice(0, key.indexOf(':') + 1)] ?? 'value';
232
+ throw new CloudflareApiError('unavailable', effect === 'write'
233
+ ? `Workers KV did not read back the ${kind} just written.`
234
+ : `Workers KV still reads the ${kind} just deleted.`);
207
235
  }
@@ -1,4 +1,4 @@
1
- import { wait } from './time.js';
1
+ import { retryUntil, wait } from './time.js';
2
2
  /** The response header the generated Worker answers its provider version in. */
3
3
  export const VERSION_HEADER = 'x-astrale-worker-version';
4
4
  /** Reach a deployment through its public URL, with `fetch`. */
@@ -26,28 +26,25 @@ export async function waitForReadiness(input) {
26
26
  throw new TypeError('Deployment readiness requires one exact HTTPS origin.');
27
27
  }
28
28
  const now = input.now ?? Date.now;
29
- const pause = input.pause ?? wait;
30
- const deadline = now() + input.timeoutMs;
31
29
  const versioned = versionFetch(origin.origin, input.version, input.fetcher);
32
30
  const check = input.check ?? pathsAnswer(input.paths ?? ['/']);
33
- let last;
34
- for (;;) {
31
+ try {
32
+ await retryUntil(() => {
33
+ const attempt = AbortSignal.timeout(input.attemptTimeoutMs ?? 5_000);
34
+ return check(versioned, input.signal === undefined ? attempt : AbortSignal.any([input.signal, attempt]));
35
+ }, {
36
+ deadline: now() + input.timeoutMs,
37
+ intervalMs: input.retryMs ?? 1_000,
38
+ ...(input.signal === undefined ? {} : { signal: input.signal }),
39
+ now,
40
+ pause: input.pause ?? wait,
41
+ });
42
+ }
43
+ catch (cause) {
35
44
  input.signal?.throwIfAborted();
36
- const attempt = AbortSignal.timeout(input.attemptTimeoutMs ?? 5_000);
37
- try {
38
- await check(versioned, input.signal === undefined ? attempt : AbortSignal.any([input.signal, attempt]));
39
- return;
40
- }
41
- catch (cause) {
42
- input.signal?.throwIfAborted();
43
- last = cause;
44
- }
45
- if (now() >= deadline)
46
- break;
47
- await pause(input.retryMs ?? 1_000, input.signal);
45
+ throw new Error(`The deployment did not serve from version ${input.version} within ` +
46
+ `${input.timeoutMs / 1_000} s.`, { cause });
48
47
  }
49
- throw new Error(`The deployment did not serve from version ${input.version} within ` +
50
- `${input.timeoutMs / 1_000} s.`, { cause: last });
51
48
  }
52
49
  /**
53
50
  * A fetch that stays on the deployment origin and admits only responses of the expected provider
@@ -5,7 +5,7 @@ import type { NamespaceScript } from './script.js';
5
5
  import { WITHDRAWN } from './kv.js';
6
6
  /** The dispatcher's retirement probe path; it is never a call of the deployment. */
7
7
  export declare const RETIREMENT_PROBE_PATH = "/__services_retirement_probe__";
8
- /** How long Workers KV takes to carry a tombstone to every dispatcher. */
8
+ /** How long Workers KV takes to carry a tombstone to every dispatcher (`KV_VISIBILITY_MS`). */
9
9
  export declare const RETIREMENT_PROPAGATION_MS = 65000;
10
10
  /** How long a caller waits before probing again when the dispatcher does not answer yet. */
11
11
  export declare const RETIREMENT_PROBE_RETRY_MS = 15000;
@@ -1,10 +1,10 @@
1
1
  import { readRecord, readRetirement, sameRecord } from './activation.js';
2
- import { retirementKey, WITHDRAWN } from './kv.js';
2
+ import { KV_VISIBILITY_MS, retirementKey, WITHDRAWN } from './kv.js';
3
3
  import { deleteScript, observeScript } from './script.js';
4
4
  /** The dispatcher's retirement probe path; it is never a call of the deployment. */
5
5
  export const RETIREMENT_PROBE_PATH = '/__services_retirement_probe__';
6
- /** How long Workers KV takes to carry a tombstone to every dispatcher. */
7
- export const RETIREMENT_PROPAGATION_MS = 65_000;
6
+ /** How long Workers KV takes to carry a tombstone to every dispatcher (`KV_VISIBILITY_MS`). */
7
+ export const RETIREMENT_PROPAGATION_MS = KV_VISIBILITY_MS;
8
8
  /** How long a caller waits before probing again when the dispatcher does not answer yet. */
9
9
  export const RETIREMENT_PROBE_RETRY_MS = 15_000;
10
10
  const DEFAULT_PROBE_TIMEOUT_MS = 10_000;
@@ -2,3 +2,24 @@
2
2
  * Wait `ms` without outliving the caller: a cancellation rejects the wait with the signal's reason.
3
3
  */
4
4
  export declare function wait(ms: number, signal?: AbortSignal): Promise<void>;
5
+ /** When and how `retryUntil` tries again. */
6
+ export interface RetryPolicy {
7
+ /** The instant (epoch ms, on `now`) no wait reaches and no attempt starts at or after. */
8
+ readonly deadline: number;
9
+ /** The first wait between attempts. */
10
+ readonly intervalMs: number;
11
+ /** The longest wait between attempts; each wait doubles up to it. Default `intervalMs`. */
12
+ readonly maximumIntervalMs?: number;
13
+ /** Whether a failure is retried; the others reject at once. Default: every failure. */
14
+ readonly retryable?: (cause: unknown) => boolean;
15
+ /** Cancels the attempts and the waits; a cancellation rejects with the signal's reason. */
16
+ readonly signal?: AbortSignal;
17
+ readonly now: () => number;
18
+ readonly pause: (ms: number, signal?: AbortSignal) => Promise<void>;
19
+ }
20
+ /**
21
+ * Run `attempt` until it succeeds. A retryable failure is tried again after a wait when that wait
22
+ * ends before the deadline, and otherwise rejects at once as the last failure: no wait reaches the
23
+ * deadline and no attempt starts at or after it. Any other failure rejects at once.
24
+ */
25
+ export declare function retryUntil<Result>(attempt: () => Promise<Result>, policy: RetryPolicy): Promise<Result>;
@@ -18,3 +18,31 @@ export function wait(ms, signal) {
18
18
  signal?.addEventListener('abort', abort, { once: true });
19
19
  });
20
20
  }
21
+ /**
22
+ * Run `attempt` until it succeeds. A retryable failure is tried again after a wait when that wait
23
+ * ends before the deadline, and otherwise rejects at once as the last failure: no wait reaches the
24
+ * deadline and no attempt starts at or after it. Any other failure rejects at once.
25
+ */
26
+ export async function retryUntil(attempt, policy) {
27
+ let intervalMs = policy.intervalMs;
28
+ for (;;) {
29
+ policy.signal?.throwIfAborted();
30
+ let failure;
31
+ try {
32
+ return await attempt();
33
+ }
34
+ catch (cause) {
35
+ policy.signal?.throwIfAborted();
36
+ if (policy.retryable?.(cause) === false)
37
+ throw cause;
38
+ failure = cause;
39
+ }
40
+ if (policy.now() + intervalMs >= policy.deadline)
41
+ throw failure;
42
+ await policy.pause(intervalMs, policy.signal);
43
+ // A timer may fire late: the deadline is read again before the next attempt.
44
+ if (policy.now() >= policy.deadline)
45
+ throw failure;
46
+ intervalMs = Math.min(intervalMs * 2, policy.maximumIntervalMs ?? policy.intervalMs);
47
+ }
48
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrale-os/adapter-cloudflare",
3
- "version": "0.5.0-beta.227",
3
+ "version": "0.5.0-beta.229",
4
4
  "description": "Deploy an Astrale Domain through Cloudflare Workers",
5
5
  "keywords": [
6
6
  "adapter",
@@ -61,7 +61,7 @@
61
61
  "registry": "https://registry.npmjs.org/"
62
62
  },
63
63
  "dependencies": {
64
- "@astrale-os/sdk": "0.6.0-beta.72",
64
+ "@astrale-os/sdk": "0.6.0-beta.74",
65
65
  "@noble/hashes": "2.3.0",
66
66
  "@restatedev/restate-sdk-cloudflare-workers": "1.17.0",
67
67
  "hono": "^4.13.11",