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

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.
@@ -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,8 @@ 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. A write may show up only after a while, so the read back is retried within
16
+ * `KV_READ_BACK_MS`.
16
17
  */
17
18
  export declare const RECORD_PREFIX = "record:";
18
19
  export declare const RETIREMENT_PREFIX = "retirement:";
@@ -49,9 +50,16 @@ export type RoutingKvLocator = {
49
50
  } | {
50
51
  readonly title: string;
51
52
  };
53
+ /**
54
+ * How long a write or delete may take to read back through the account API before it fails
55
+ * `unavailable`. Workers KV is eventually consistent: a read just after a write may still answer
56
+ * the previous value.
57
+ */
58
+ export declare const KV_READ_BACK_MS = 30000;
52
59
  /**
53
60
  * 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.
61
+ * every write and delete is read back before it counts, and fails `unavailable` when it does not
62
+ * read back within `KV_READ_BACK_MS` (or the client's deadline).
55
63
  */
56
64
  export declare class RoutingKv {
57
65
  private readonly client;
@@ -83,6 +91,12 @@ export declare class RoutingKv {
83
91
  * the listing's cursor to its end.
84
92
  */
85
93
  keys(prefix: string): Promise<readonly string[]>;
94
+ /**
95
+ * Read back what a write or delete at `key` left, until `kept` admits it, within
96
+ * `KV_READ_BACK_MS`; a read that fails `unavailable` is tried again too. `kept` reads through this
97
+ * KV on a client bounded by that budget, so no single read outlasts it.
98
+ */
99
+ private readBack;
86
100
  private value;
87
101
  private path;
88
102
  }
@@ -15,7 +15,8 @@ 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. A write may show up only after a while, so the read back is retried within
19
+ * `KV_READ_BACK_MS`.
19
20
  */
20
21
  export const RECORD_PREFIX = 'record:';
21
22
  export const RETIREMENT_PREFIX = 'retirement:';
@@ -87,11 +88,18 @@ export function decodeSchedules(text, name) {
87
88
  }
88
89
  return crons;
89
90
  }
91
+ /**
92
+ * How long a write or delete may take to read back through the account API before it fails
93
+ * `unavailable`. Workers KV is eventually consistent: a read just after a write may still answer
94
+ * the previous value.
95
+ */
96
+ export const KV_READ_BACK_MS = 30_000;
90
97
  /** The most keys one page of a KV key listing returns, as Cloudflare caps it. */
91
98
  const KEYS_PAGE = 1_000;
92
99
  /**
93
100
  * 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.
101
+ * every write and delete is read back before it counts, and fails `unavailable` when it does not
102
+ * read back within `KV_READ_BACK_MS` (or the client's deadline).
95
103
  */
96
104
  export class RoutingKv {
97
105
  client;
@@ -124,8 +132,7 @@ export class RoutingKv {
124
132
  /** Write `text` at `key`, then read it back. */
125
133
  async put(key, text, contentType) {
126
134
  await this.client.text('PUT', this.value(key), { text, contentType });
127
- if ((await this.get(key)) !== text)
128
- notKept(key);
135
+ await this.readBack(key, 'write', async (kv) => (await kv.get(key)) === text);
129
136
  }
130
137
  /**
131
138
  * The bytes stored at `key` and their metadata (`null` when they were written without), or
@@ -153,19 +160,18 @@ export class RoutingKv {
153
160
  form.append('value', new Blob([bytes]));
154
161
  form.append('metadata', text);
155
162
  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
- }
163
+ await this.readBack(key, 'write', async (kv) => {
164
+ const stored = await kv.getWithMetadata(key);
165
+ return (stored !== undefined &&
166
+ stored.bytes.byteLength === bytes.byteLength &&
167
+ stored.bytes.every((byte, index) => byte === bytes[index]) &&
168
+ JSON.stringify(stored.metadata) === text);
169
+ });
163
170
  }
164
171
  /** Delete `key`, then read back its absence. */
165
172
  async delete(key) {
166
173
  await this.client.text('DELETE', this.value(key));
167
- if ((await this.get(key)) !== undefined)
168
- notKept(key);
174
+ await this.readBack(key, 'delete', async (kv) => (await kv.get(key)) === undefined);
169
175
  }
170
176
  /**
171
177
  * Every key name that starts with `prefix`, in Cloudflare's (lexicographic) order, following
@@ -182,6 +188,17 @@ export class RoutingKv {
182
188
  return name;
183
189
  }));
184
190
  }
191
+ /**
192
+ * Read back what a write or delete at `key` left, until `kept` admits it, within
193
+ * `KV_READ_BACK_MS`; a read that fails `unavailable` is tried again too. `kept` reads through this
194
+ * KV on a client bounded by that budget, so no single read outlasts it.
195
+ */
196
+ async readBack(key, effect, kept) {
197
+ await this.client.retryWithin(KV_READ_BACK_MS, async (client) => {
198
+ if (!(await kept(new RoutingKv(client, this.id))))
199
+ notKept(key, effect);
200
+ });
201
+ }
185
202
  value(key) {
186
203
  return this.path('values', key);
187
204
  }
@@ -201,7 +218,16 @@ export async function findKvNamespace(client, title) {
201
218
  }
202
219
  return found.id;
203
220
  }
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}.`);
221
+ /** What a routing key holds, in words: an error names the kind of key, never the key or value. */
222
+ const KEY_KINDS = Object.freeze({
223
+ [RECORD_PREFIX]: 'deployment record',
224
+ [RETIREMENT_PREFIX]: 'retirement tombstone',
225
+ [CURRENT_PREFIX]: 'current deployment',
226
+ [CRON_PREFIX]: 'schedules',
227
+ });
228
+ function notKept(key, effect) {
229
+ const kind = KEY_KINDS[key.slice(0, key.indexOf(':') + 1)] ?? 'value';
230
+ throw new CloudflareApiError('unavailable', effect === 'write'
231
+ ? `Workers KV did not read back the ${kind} just written.`
232
+ : `Workers KV still reads the ${kind} just deleted.`);
207
233
  }
@@ -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
@@ -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.228",
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.73",
65
65
  "@noble/hashes": "2.3.0",
66
66
  "@restatedev/restate-sdk-cloudflare-workers": "1.17.0",
67
67
  "hono": "^4.13.11",