@astrale-os/adapter-cloudflare 0.5.0-beta.190 → 0.5.0-beta.192

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
@@ -95,8 +95,9 @@ Every line is readable. Namespace mode is a thin layer over the hosting kit belo
95
95
  key while the script exists, and the call target `{ kind: 'namespace', namespace, script }`. Its
96
96
  state is `active`, `retiring` (tombstoned, script not deleted yet), `retired` (script deleted) or
97
97
  `failed` (activated, script gone).
98
- - **Refused.** A direct-mode parameter beside `namespace` (`route`, `workerName`, `identityIssuer`,
99
- `addressing`, `signingIdentity`), a `router.binding` other than `ROUTER`, and any `wrangler` key
98
+ - **Refused.** A removed direct-mode parameter (`route`, `workerName`, `identityIssuer`,
99
+ `addressing`, `signingIdentity`), any `router` key but `service`, `hostSuffix` and `minLabels`
100
+ (the binding is always `ROUTER`), and any `wrangler` key
100
101
  but `services`, `dispatch_namespaces` and `compatibility_flags`, `triggers` first: an immutable
101
102
  deployment runs no cron of its own. A `dispatch_namespaces` entry is exactly
102
103
  `{ binding, namespace }`; it is frozen into the configuration (`bindings.dispatchNamespaces`), so
@@ -190,6 +191,17 @@ an overlay key the bundler reads (`alias`, `build`, `define`, `jsx_factory`, `js
190
191
  `upload_source_maps`) and a compatibility flag it reads (Node.js, `navigator`, fetch iterable
191
192
  typing, Python) beyond the adapter's own `nodejs_compat`.
192
193
 
194
+ ## Deployment cache
195
+
196
+ A Worker keeps the admissions of callables that declare an admission age (`admission: { maxAge }`)
197
+ in its deployment cache: the Cache API cache `astrale-deployment`, behind a bounded in-isolate memory
198
+ tier read first. Cloudflare gives each Worker script, so each immutable deployment, its own Cache API
199
+ cache: no other deployment reads these entries, and a new release starts empty. An entry is kept
200
+ for its whole remaining seconds at most (`cache-control: max-age`), and in memory only when less
201
+ than one second remains. A hand-composed entrypoint keeps none with `cache: false`; every call is
202
+ then admitted by its source Kernel. `cloudflareCache()` from `@astrale-os/adapter-cloudflare/worker`
203
+ is the same cache for a Worker that calls `serve()` itself. See the SDK's `docs/admission-age.md`.
204
+
193
205
  ## Build digest
194
206
 
195
207
  `cloudflare()` and `astrale()` bundle through one bundler, `cloudflare-worker` version `1`, so
@@ -40,7 +40,7 @@ export async function admitWorkerBundle(path) {
40
40
  export async function admitDurableEngineBundle(path) {
41
41
  admitCompiledWasm();
42
42
  const engine = (await import(`${pathToFileURL(path).href}?admit=${Date.now()}`));
43
- if (['createEndpointHandler', 'workflow', 'TerminalError', 'CancelledError'].some((key) => typeof engine[key] !== 'function')) {
43
+ if (['createEndpointHandler', 'workflow', 'TerminalError', 'CancelledError', 'TimeoutError'].some((key) => typeof engine[key] !== 'function')) {
44
44
  throw new TypeError('Generated durable engine bundle does not export the platform Fetch entrypoint.');
45
45
  }
46
46
  }
@@ -76,7 +76,7 @@ export async function prepareExecution(input) {
76
76
  if (declaresDurable(input.context.build)) {
77
77
  await bundle('restate', RELEASE_RESTATE,
78
78
  // Wrangler requires a default export to classify an independently bundled ESM entry.
79
- `export { createEndpointHandler, workflow, TerminalError, CancelledError } from ${JSON.stringify(restateModuleSpecifier())}\nexport default {}\n`, admitDurableEngineBundle);
79
+ `export { createEndpointHandler, workflow, TerminalError, CancelledError, TimeoutError } from ${JSON.stringify(restateModuleSpecifier())}\nexport default {}\n`, admitDurableEngineBundle);
80
80
  }
81
81
  const sourcePath = join(input.directory, 'worker.gen.ts');
82
82
  const frontend = generatedMaterial(input.context.build).material.frontend;
@@ -0,0 +1,28 @@
1
+ import type { DeploymentCache } from '@astrale-os/sdk/execution';
2
+ /**
3
+ * The Cache API cache a deployment keeps its entries in. Cloudflare isolates the Cache API of each
4
+ * Worker script, and so of each immutable deployment: no other deployment reads these entries.
5
+ */
6
+ export declare const DEPLOYMENT_CACHE_NAME = "astrale-deployment";
7
+ /** The part of the Cache API a deployment cache uses. */
8
+ export interface CacheApiStorage {
9
+ open(cacheName: string): Promise<CacheApiCache>;
10
+ }
11
+ export interface CacheApiCache {
12
+ match(request: string): Promise<Response | undefined>;
13
+ put(request: string, response: Response): Promise<void>;
14
+ }
15
+ export interface CloudflareCacheOptions {
16
+ /** The Cache API; defaults to the isolate's `caches`, and to none where the isolate has none. */
17
+ readonly caches?: CacheApiStorage;
18
+ /** The in-isolate tier read first; defaults to a bounded memory cache. */
19
+ readonly memory?: DeploymentCache;
20
+ }
21
+ /**
22
+ * A deployment cache shared by every isolate of one deployment in a data center: the Cache API,
23
+ * behind a bounded in-isolate memory tier read first. The Cache API keeps an entry for its whole
24
+ * remaining seconds at most, so an entry with less than one second left is kept in memory only.
25
+ * The cache is opened per operation and nothing pending is shared, because a Worker binds I/O to
26
+ * the request that started it.
27
+ */
28
+ export declare function cloudflareCache(options?: CloudflareCacheOptions): DeploymentCache;
@@ -0,0 +1,70 @@
1
+ import { memoryCache } from '@astrale-os/sdk/execution';
2
+ /**
3
+ * The Cache API cache a deployment keeps its entries in. Cloudflare isolates the Cache API of each
4
+ * Worker script, and so of each immutable deployment: no other deployment reads these entries.
5
+ */
6
+ export const DEPLOYMENT_CACHE_NAME = 'astrale-deployment';
7
+ /** Origin of the synthetic URLs that name entries; they are never fetched. */
8
+ const ENTRY_ORIGIN = 'https://deployment-cache.astrale.invalid/';
9
+ /** Absolute expiry of an entry, in Unix milliseconds, carried beside its value. */
10
+ const EXPIRES_AT = 'x-astrale-expires-at';
11
+ /**
12
+ * A deployment cache shared by every isolate of one deployment in a data center: the Cache API,
13
+ * behind a bounded in-isolate memory tier read first. The Cache API keeps an entry for its whole
14
+ * remaining seconds at most, so an entry with less than one second left is kept in memory only.
15
+ * The cache is opened per operation and nothing pending is shared, because a Worker binds I/O to
16
+ * the request that started it.
17
+ */
18
+ export function cloudflareCache(options = {}) {
19
+ if (options === null || typeof options !== 'object' || Array.isArray(options))
20
+ invalid();
21
+ const memory = options.memory ?? memoryCache();
22
+ const storage = options.caches ?? isolateCaches();
23
+ return Object.freeze({
24
+ async get(key) {
25
+ const near = await memory.get(key);
26
+ if (near !== undefined || storage === undefined)
27
+ return near;
28
+ const response = await (await storage.open(DEPLOYMENT_CACHE_NAME)).match(entryUrl(key));
29
+ if (response === undefined)
30
+ return undefined;
31
+ const value = await response.text();
32
+ const expiresAt = Number(response.headers.get(EXPIRES_AT));
33
+ if (!Number.isSafeInteger(expiresAt) || expiresAt <= Date.now())
34
+ return undefined;
35
+ await memory.put(key, value, expiresAt);
36
+ return value;
37
+ },
38
+ async put(key, value, expiresAt) {
39
+ await memory.put(key, value, expiresAt);
40
+ if (storage === undefined || !Number.isSafeInteger(expiresAt))
41
+ return;
42
+ const seconds = Math.floor((expiresAt - Date.now()) / 1000);
43
+ if (seconds < 1)
44
+ return;
45
+ await (await storage.open(DEPLOYMENT_CACHE_NAME)).put(entryUrl(key), new Response(value, {
46
+ headers: {
47
+ 'cache-control': `max-age=${seconds}`,
48
+ 'content-type': 'text/plain; charset=utf-8',
49
+ [EXPIRES_AT]: String(expiresAt),
50
+ },
51
+ }));
52
+ },
53
+ });
54
+ }
55
+ function entryUrl(key) {
56
+ if (typeof key !== 'string')
57
+ invalid();
58
+ return `${ENTRY_ORIGIN}${encodeURIComponent(key)}`;
59
+ }
60
+ function isolateCaches() {
61
+ const caches = Reflect.get(globalThis, 'caches');
62
+ return caches !== null &&
63
+ typeof caches === 'object' &&
64
+ typeof Reflect.get(caches, 'open') === 'function'
65
+ ? caches
66
+ : undefined;
67
+ }
68
+ function invalid() {
69
+ throw new TypeError('Cloudflare cache input is invalid.');
70
+ }
@@ -23,6 +23,12 @@ export interface CloudflareWorkerConfig<RuntimeValue extends Runtime, Bindings e
23
23
  * them in this configuration instead; one Worker never takes both.
24
24
  */
25
25
  readonly settings?: (bindings: Bindings) => CloudflareWorkerSettings<Bindings>;
26
+ /**
27
+ * The deployment cache, which keeps the admissions of callables that declare an admission age:
28
+ * by default the Cache API behind an in-isolate memory tier. `false` keeps nothing, and every
29
+ * call is admitted by its source Kernel.
30
+ */
31
+ readonly cache?: false;
26
32
  /** Resolve the engine for this durable request with the deployment's captured options. */
27
33
  readonly durable?: (bindings: Bindings, request: Request, options?: DurableWorkerOptions) => ReturnType<DurableServingProvider>;
28
34
  }
@@ -3,6 +3,7 @@ import { restoreBuild, restoreGeneratedBuild } from '@astrale-os/sdk/deployment/
3
3
  import { assemble } from '@astrale-os/sdk/deployment/release/runtime';
4
4
  import { createIdentity, serve } from '@astrale-os/sdk/execution';
5
5
  import { deploymentBuildDigest } from './build-digest.js';
6
+ import { cloudflareCache } from './cache.js';
6
7
  import { dispatchCloudflareRequest, prepareCloudflareRequest } from './fetch.js';
7
8
  import { cloudflareFrontDoor, withProviderVersion } from './front.js';
8
9
  import { frontendAsset } from './frontend.js';
@@ -72,6 +73,7 @@ function createCloudflareWorkerEntry(restore) {
72
73
  : { tokenExchange: settings.tokenExchange }),
73
74
  });
74
75
  },
76
+ cache: config.cache === false ? false : () => cloudflareCache(),
75
77
  ...(config.durable === undefined
76
78
  ? {}
77
79
  : {
@@ -1,4 +1,5 @@
1
1
  export * from './entry.js';
2
+ export { cloudflareCache, DEPLOYMENT_CACHE_NAME, type CacheApiCache, type CacheApiStorage, type CloudflareCacheOptions, } from './cache.js';
2
3
  export { BUILD_DIGEST_BINDING } from './build-digest.js';
3
4
  export { decodeSigningIdentity, runtimeBindings } from './identity.js';
4
5
  export { decodeWorkerSettings, deploymentSettings, encodeWorkerSettings, SETTINGS_BINDING, type CloudflareWorkerSettings, type WorkerSettings, } from './settings.js';
@@ -1,4 +1,5 @@
1
1
  export * from './entry.js';
2
+ export { cloudflareCache, DEPLOYMENT_CACHE_NAME, } from './cache.js';
2
3
  export { BUILD_DIGEST_BINDING } from './build-digest.js';
3
4
  export { decodeSigningIdentity, runtimeBindings } from './identity.js';
4
5
  export { decodeWorkerSettings, deploymentSettings, encodeWorkerSettings, SETTINGS_BINDING, } from './settings.js';
@@ -2,6 +2,7 @@ import { spawn } from 'node:child_process';
2
2
  import { existsSync, readFileSync } from 'node:fs';
3
3
  import { createRequire } from 'node:module';
4
4
  import { dirname, join, resolve } from 'node:path';
5
+ import { StringDecoder } from 'node:string_decoder';
5
6
  export function wranglerCommand(projectDir, runtime = {
6
7
  executable: process.execPath,
7
8
  bun: process.versions.bun !== undefined,
@@ -41,6 +42,8 @@ export function runCapture(cmd, args, cwd, onLog, signal, redact = (input) => in
41
42
  let stdout = '';
42
43
  let stderr = '';
43
44
  let outputBytes = 0;
45
+ // One decoder per stream: a chunk can end inside a multi-byte UTF-8 character.
46
+ const decoders = { stdout: new StringDecoder('utf8'), stderr: new StringDecoder('utf8') };
44
47
  let terminating;
45
48
  const timeout = setTimeout(() => terminate(new Error('Wrangler process timed out.')), 300_000);
46
49
  const abort = () => terminate(new Error('Wrangler process cancelled.'));
@@ -68,7 +71,7 @@ export function runCapture(cmd, args, cwd, onLog, signal, redact = (input) => in
68
71
  terminate(new Error('Wrangler process exceeded its output limit.'));
69
72
  return;
70
73
  }
71
- const chunk = buffer.toString();
74
+ const chunk = decoders[stream].write(buffer);
72
75
  out += chunk;
73
76
  if (stream === 'stdout')
74
77
  stdout += chunk;
@@ -82,6 +85,14 @@ export function runCapture(cmd, args, cwd, onLog, signal, redact = (input) => in
82
85
  if (terminating !== undefined)
83
86
  reject(terminating);
84
87
  else {
88
+ for (const stream of ['stdout', 'stderr']) {
89
+ const rest = decoders[stream].end();
90
+ out += rest;
91
+ if (stream === 'stdout')
92
+ stdout += rest;
93
+ else
94
+ stderr += rest;
95
+ }
85
96
  const safe = redact(out);
86
97
  for (const line of safe.split('\n'))
87
98
  if (line.trim())
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrale-os/adapter-cloudflare",
3
- "version": "0.5.0-beta.190",
3
+ "version": "0.5.0-beta.192",
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.35",
64
+ "@astrale-os/sdk": "0.6.0-beta.37",
65
65
  "@noble/hashes": "2.3.0",
66
66
  "@restatedev/restate-sdk-cloudflare-workers": "1.17.0",
67
67
  "hono": "^4.6.20",