@astrale-os/adapter-cloudflare 0.5.0-beta.226 → 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.
package/README.md CHANGED
@@ -241,6 +241,13 @@ import { writeFile } from 'node:fs/promises'
241
241
  await writeFile('src/build-material.gen.ts', generateBuildMaterialModule(build))
242
242
  ```
243
243
 
244
+ Standard and custom generated Workers embed one Brotli-compressed Schema Bundle. The Release
245
+ identifies the canonical JSON by its existing size, digest and URL. Its canonical GET still returns
246
+ those exact bytes. When the compressed representation is smaller, the Release response also links
247
+ to an immutable `.br` artifact. Both routes support their own ETag and conditional GET.
248
+ The loader accepts historical v1 material. The synchronous `build.schema.bundle.bytes()` accessor
249
+ and the explicit `material(build)` export both produce canonical bytes.
250
+
244
251
  The generated TypeScript module exports `loadBuildMaterial()`. Call it from the
245
252
  `load` callback of `generatedCloudflareWorkerEntry` alongside the Domain's Runtime.
246
253
  That callback loads deterministic local modules once per entrypoint. Concurrent execution and
@@ -1,11 +1,13 @@
1
1
  import type { Bundle, BundleContext, Bundler } from '@astrale-os/sdk/deployment/adapter';
2
2
  import type { frontend as frontendBuild } from '@astrale-os/sdk/deployment/build';
3
+ import type { ArtifactRef } from '@astrale-os/sdk/release';
3
4
  import type { ReleaseModule } from './worker/execution.prepare.js';
4
5
  /**
5
6
  * Environment-free bytes of one generated Worker: its entry, the modules it loads (the execution
6
7
  * Service, the deferred workflow engine and their WASM) and its frontend.
7
8
  */
8
9
  export interface WorkerBytes {
10
+ readonly compactBundle?: ArtifactRef;
9
11
  readonly entry: Uint8Array;
10
12
  readonly modules: readonly ReleaseModule[];
11
13
  readonly frontend: readonly frontendBuild.FrontendFile[];
@@ -17,6 +17,7 @@ export const cloudflareWorkerBundler = Object.freeze({
17
17
  const worker = await bundleWorker(context);
18
18
  return Object.freeze({
19
19
  entrypoint: RELEASE_ENTRY,
20
+ ...(worker.compactBundle === undefined ? {} : { compactBundle: worker.compactBundle }),
20
21
  files: Object.freeze([
21
22
  { path: RELEASE_ENTRY, content: worker.entry },
22
23
  ...worker.modules.map(({ path, content }) => ({ path, content })),
@@ -49,7 +50,12 @@ export async function bundleWorker(context) {
49
50
  ...(frontend.length === 0 ? {} : { frontendRevision: frontendRevision(frontend) }),
50
51
  ...(addressed.length === 0 ? {} : { frontendAddressed: addressed }),
51
52
  });
52
- return Object.freeze({ entry: modules.entry, modules: modules.modules, frontend });
53
+ return Object.freeze({
54
+ entry: modules.entry,
55
+ modules: modules.modules,
56
+ frontend,
57
+ compactBundle: modules.compactBundle,
58
+ });
53
59
  }
54
60
  finally {
55
61
  await rm(directory, { recursive: true, force: true });
@@ -90,6 +96,7 @@ export function bundledWorker(bundle, build) {
90
96
  }
91
97
  return Object.freeze({
92
98
  entry,
99
+ ...(bundle.compactBundle === undefined ? {} : { compactBundle: bundle.compactBundle }),
93
100
  modules: Object.freeze(modules),
94
101
  frontend: Object.freeze(frontend),
95
102
  });
@@ -1,4 +1,4 @@
1
- import { generatedMaterial } from '@astrale-os/sdk/deployment/build';
1
+ import { generatedCompactMaterial } from '@astrale-os/sdk/deployment/build/compact';
2
2
  import { sharedLiteral, verifySharedLiteral } from './worker/codegen/literal.js';
3
3
  /**
4
4
  * Generate a TypeScript module exporting `loadBuildMaterial()` for a custom Worker entrypoint.
@@ -9,17 +9,17 @@ import { sharedLiteral, verifySharedLiteral } from './worker/codegen/literal.js'
9
9
  * compression dependency is needed by the generated module at runtime.
10
10
  */
11
11
  export function generateBuildMaterialModule(build) {
12
- const generated = generatedMaterial(build);
12
+ const generated = generatedCompactMaterial(build);
13
13
  const literal = sharedLiteral(generated);
14
14
  verifySharedLiteral(literal, generated);
15
15
  // An empty shared array otherwise has an implicit any[] type in strict TypeScript consumers.
16
16
  const declarations = literal.declarations.map((line) => ` ${line.replace(/ = \[\]$/, ': readonly [] = []')}`);
17
17
  return `// AUTO-GENERATED by @astrale-os/adapter-cloudflare — do not edit.
18
- import type { GeneratedBuildMaterial } from '@astrale-os/sdk/deployment/build'
18
+ import type { GeneratedCompactBuildMaterial } from '@astrale-os/sdk/deployment/build'
19
19
 
20
- export function loadBuildMaterial(): GeneratedBuildMaterial {
20
+ export function loadBuildMaterial(): GeneratedCompactBuildMaterial {
21
21
  ${declarations.join('\n')}
22
- return ${literal.expression} as unknown as GeneratedBuildMaterial
22
+ return ${literal.expression} as unknown as GeneratedCompactBuildMaterial
23
23
  }
24
24
  `;
25
25
  }
@@ -11,4 +11,4 @@ export interface ExecutionCodegenOptions {
11
11
  readonly durable?: boolean;
12
12
  readonly restateSpecifier?: string;
13
13
  }
14
- export declare function generateExecutionService(options: ExecutionCodegenOptions): string;
14
+ export declare function generateExecutionService(options: ExecutionCodegenOptions, generated?: import("@astrale-os/sdk/deployment/build").GeneratedCompactBuildMaterial): string;
@@ -1,8 +1,7 @@
1
- import { generatedMaterial } from '@astrale-os/sdk/deployment/build';
1
+ import { generatedCompactMaterial } from '@astrale-os/sdk/deployment/build/compact';
2
2
  import { sharedLiteral, verifySharedLiteral } from './literal.js';
3
- export function generateExecutionService(options) {
3
+ export function generateExecutionService(options, generated = generatedCompactMaterial(options.build)) {
4
4
  const workerSpecifier = options.workerSpecifier ?? '@astrale-os/adapter-cloudflare/worker';
5
- const generated = generatedMaterial(options.build);
6
5
  // JSON has no references, so a flat literal repeats every repeated subtree. A compiled Domain
7
6
  // is dominated by pattern automata, of which a few expressions account for dozens of identical
8
7
  // copies, so sharing them cuts what the isolate allocates and seals by an order of magnitude.
@@ -23,7 +22,7 @@ const RESTATE_SPECIFIER = ${JSON.stringify(options.restateSpecifier ?? './restat
23
22
  // checkout characters into esbuild's minifier histogram, making identical Services differ.
24
23
  return `// AUTO-GENERATED by @astrale-os/adapter-cloudflare — do not edit.
25
24
  // Domain origin: ${options.origin}
26
- import type { BuildMaterial, GeneratedBuildMaterial } from '@astrale-os/sdk/deployment/build'
25
+ import type { BuildMaterial, GeneratedCompactBuildMaterial } from '@astrale-os/sdk/deployment/build'
27
26
 
28
27
  import { generatedCloudflareWorkerEntry, type CloudflareAdapterBindings } from ${JSON.stringify(workerSpecifier)}
29
28
  import { decodeSigningIdentity, deploymentSettings, runtimeBindings } from ${JSON.stringify(workerSpecifier)}
@@ -38,7 +37,7 @@ export default generatedCloudflareWorkerEntry<WorkerEnv, RuntimeEnv>()({
38
37
  ${frontend}${options.frontendRevision === undefined ? '' : ` frontendRevision: ${JSON.stringify(options.frontendRevision)},\n`}${options.frontendAddressed === undefined ? '' : ` frontendAddressed: ${JSON.stringify(options.frontendAddressed)},\n`} load: async () => {
39
38
  ${materialDeclarations} return {
40
39
  runtime: (await import(${JSON.stringify(options.runtimeSpecifier)})).default,
41
- material: ${material.expression} as unknown as GeneratedBuildMaterial,
40
+ material: ${material.expression} as unknown as GeneratedCompactBuildMaterial,
42
41
  }
43
42
  },
44
43
  privateKey: (env) => decodeSigningIdentity(env.ASTRALE_SIGNING_IDENTITY),
@@ -1,4 +1,5 @@
1
1
  import type { BundleContext } from '@astrale-os/sdk/deployment/adapter';
2
+ import type { ArtifactRef } from '@astrale-os/sdk/release';
2
3
  export declare const RELEASE_ENTRY = "bundle/index.mjs";
3
4
  export declare const RELEASE_SERVICE = "bundle/service.mjs";
4
5
  export declare const RELEASE_RESTATE = "bundle/restate.mjs";
@@ -16,5 +17,6 @@ export declare function prepareExecution(input: {
16
17
  }): Promise<{
17
18
  readonly entry: Uint8Array;
18
19
  readonly modules: readonly ReleaseModule[];
20
+ readonly compactBundle: ArtifactRef;
19
21
  }>;
20
22
  export declare function declaresDurable(build: BundleContext['build']): boolean;
@@ -1,4 +1,4 @@
1
- import { generatedMaterial } from '@astrale-os/sdk/deployment/build';
1
+ import { generatedCompactMaterial } from '@astrale-os/sdk/deployment/build/compact';
2
2
  import { DURABLE_ENGINE_EXPORTS } from '@astrale-os/sdk/execution';
3
3
  import { mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises';
4
4
  import { dirname, join, relative, resolve } from 'node:path';
@@ -22,6 +22,7 @@ export async function prepareExecution(input) {
22
22
  const runtimePath = resolve(input.context.projectDir, input.context.runtime.reference.path);
23
23
  const runtimeSpecifier = moduleSpecifier(relative(input.directory, runtimePath));
24
24
  const workerSpecifier = workerModuleSpecifier();
25
+ const generated = generatedCompactMaterial(input.context.build);
25
26
  const serviceSource = generateExecutionService({
26
27
  origin: input.context.build.schema.compiled.root.origin,
27
28
  runtimeSpecifier,
@@ -34,7 +35,7 @@ export async function prepareExecution(input) {
34
35
  ...(input.frontendAddressed === undefined
35
36
  ? {}
36
37
  : { frontendAddressed: input.frontendAddressed }),
37
- });
38
+ }, generated);
38
39
  const modules = [];
39
40
  const bundle = async (name, path, source, admit) => {
40
41
  const sourcePath = join(input.directory, `${name}.gen.ts`);
@@ -80,7 +81,7 @@ export async function prepareExecution(input) {
80
81
  `export { ${DURABLE_ENGINE_EXPORTS.join(', ')} } from ${JSON.stringify(restateModuleSpecifier())}\nexport default {}\n`, admitDurableEngineBundle);
81
82
  }
82
83
  const sourcePath = join(input.directory, 'worker.gen.ts');
83
- const frontend = generatedMaterial(input.context.build).material.frontend;
84
+ const frontend = input.context.build.frontend;
84
85
  await writeFile(sourcePath, generateExecutionEntry('./service.mjs', {
85
86
  frontSpecifier: frontModuleSpecifier(),
86
87
  ...(frontend === undefined ? {} : { frontend }),
@@ -112,6 +113,7 @@ export async function prepareExecution(input) {
112
113
  return Object.freeze({
113
114
  entry: new Uint8Array(await readFile(emitted.bundlePath)),
114
115
  modules: Object.freeze(modules),
116
+ compactBundle: generated.material.schema.bundle.stored.ref,
115
117
  });
116
118
  }
117
119
  function moduleSpecifier(input) {
@@ -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
+ }
@@ -143,6 +143,7 @@ class NamespaceDeployment {
143
143
  try {
144
144
  await waitForNamespaceReadiness({
145
145
  release: this.context.release,
146
+ bundle: this.context.bundle,
146
147
  version: deployed.version,
147
148
  timeoutMs: deployed.activated ? ACTIVATION_READINESS_MS : ROTATION_READINESS_MS,
148
149
  signal: this.context.signal,
@@ -1,3 +1,4 @@
1
+ import type { Bundle } from '@astrale-os/sdk/deployment/adapter';
1
2
  import type { Release } from '@astrale-os/sdk/deployment/release';
2
3
  /**
3
4
  * How long a deployment this deploy activated may take to serve: the dispatcher reads the label's
@@ -19,6 +20,7 @@ export declare const ROTATION_READINESS_MS = 30000;
19
20
  export declare function waitForNamespaceReadiness(input: {
20
21
  /** The sealed release the deployment must serve at its URL. */
21
22
  readonly release: Release;
23
+ readonly bundle?: Bundle;
22
24
  /** The provider version that must answer, in the UUID form the Worker reports. */
23
25
  readonly version: string;
24
26
  readonly timeoutMs: number;
@@ -24,7 +24,11 @@ export async function waitForNamespaceReadiness(input) {
24
24
  fetcher: publicFetcher(input.fetch),
25
25
  timeoutMs: input.timeoutMs,
26
26
  signal: input.signal,
27
- check: (fetch, signal) => verifyReadiness(input.release, { fetch, signal }).then(() => { }),
27
+ check: (fetch, signal) => verifyReadiness(input.release, {
28
+ fetch,
29
+ signal,
30
+ ...(input.bundle === undefined ? {} : { bundle: input.bundle }),
31
+ }).then(() => { }),
28
32
  ...(input.pause === undefined ? {} : { pause: input.pause }),
29
33
  ...(input.now === undefined ? {} : { now: input.now }),
30
34
  });
@@ -1,12 +1,12 @@
1
1
  import type { JsonWebKey } from '@astrale-os/sdk/auth';
2
- import type { BuildMaterial, GeneratedBuildMaterial } from '@astrale-os/sdk/deployment/build/material';
2
+ import type { BuildMaterial, CompactBuildMaterial, GeneratedBuildMaterial, GeneratedCompactBuildMaterial } from '@astrale-os/sdk/deployment/build/material';
3
3
  import type { DurableServingProvider, ExecutionContext } from '@astrale-os/sdk/execution';
4
4
  import type { Runtime } from '@astrale-os/sdk/runtime';
5
5
  import type { DurableWorkerOptions } from '../params.js';
6
6
  import type { CloudflareAdapterBindings, CloudflareFrontDoorConfig, Fetcher } from './front.js';
7
7
  import type { CloudflareWorkerSettings } from './settings.js';
8
8
  export type { CloudflareAdapterBindings, Fetcher } from './front.js';
9
- export interface CloudflareWorkerConfig<RuntimeValue extends Runtime, Bindings extends CloudflareAdapterBindings, Environment, Material = BuildMaterial> extends CloudflareFrontDoorConfig, CloudflareWorkerSettings<Bindings> {
9
+ export interface CloudflareWorkerConfig<RuntimeValue extends Runtime, Bindings extends CloudflareAdapterBindings, Environment, Material = BuildMaterial | CompactBuildMaterial> extends CloudflareFrontDoorConfig, CloudflareWorkerSettings<Bindings> {
10
10
  /**
11
11
  * Load the exact local Runtime and Build once per entrypoint, after the isolate has accepted a
12
12
  * request or execution is prepared. Concurrent callers share the result, including a rejection;
@@ -32,7 +32,7 @@ export interface CloudflareWorkerConfig<RuntimeValue extends Runtime, Bindings e
32
32
  /** Resolve the engine for this durable request with the deployment's captured options. */
33
33
  readonly durable?: (bindings: Bindings, request: Request, options?: DurableWorkerOptions) => ReturnType<DurableServingProvider>;
34
34
  }
35
- export interface CloudflareWorkerSource<RuntimeValue extends Runtime, Material = BuildMaterial> {
35
+ export interface CloudflareWorkerSource<RuntimeValue extends Runtime, Material = BuildMaterial | CompactBuildMaterial> {
36
36
  readonly runtime: RuntimeValue;
37
37
  readonly material: Material;
38
38
  }
@@ -42,6 +42,6 @@ export interface CloudflareWorker<Bindings> {
42
42
  prepare?(): Promise<void>;
43
43
  }
44
44
  /** Compose one installed Domain implementation at its immutable deployment URL. */
45
- export declare function cloudflareWorkerEntry<Bindings extends CloudflareAdapterBindings, Environment = Bindings>(): <RuntimeValue extends Runtime>(config: CloudflareWorkerConfig<RuntimeValue, Bindings, Environment, BuildMaterial>) => CloudflareWorker<Bindings>;
45
+ export declare function cloudflareWorkerEntry<Bindings extends CloudflareAdapterBindings, Environment = Bindings>(): <RuntimeValue extends Runtime>(config: CloudflareWorkerConfig<RuntimeValue, Bindings, Environment, BuildMaterial | CompactBuildMaterial>) => CloudflareWorker<Bindings>;
46
46
  /** Compose generated execution code whose exact Build material carries build-owner evidence. */
47
- export declare function generatedCloudflareWorkerEntry<Bindings extends CloudflareAdapterBindings, Environment = Bindings>(): <RuntimeValue extends Runtime>(config: CloudflareWorkerConfig<RuntimeValue, Bindings, Environment, GeneratedBuildMaterial>) => CloudflareWorker<Bindings>;
47
+ export declare function generatedCloudflareWorkerEntry<Bindings extends CloudflareAdapterBindings, Environment = Bindings>(): <RuntimeValue extends Runtime>(config: CloudflareWorkerConfig<RuntimeValue, Bindings, Environment, GeneratedBuildMaterial | GeneratedCompactBuildMaterial>) => CloudflareWorker<Bindings>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrale-os/adapter-cloudflare",
3
- "version": "0.5.0-beta.226",
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.71",
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",