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

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
@@ -190,6 +190,17 @@ an overlay key the bundler reads (`alias`, `build`, `define`, `jsx_factory`, `js
190
190
  `upload_source_maps`) and a compatibility flag it reads (Node.js, `navigator`, fetch iterable
191
191
  typing, Python) beyond the adapter's own `nodejs_compat`.
192
192
 
193
+ ## Deployment cache
194
+
195
+ A Worker keeps the admissions of callables that declare an admission age (`admission: { maxAge }`)
196
+ in its deployment cache: the Cache API cache `astrale-deployment`, behind a bounded in-isolate memory
197
+ tier read first. Cloudflare gives each Worker script, so each immutable deployment, its own Cache API
198
+ cache: no other deployment reads these entries, and a new release starts empty. An entry is kept
199
+ for its whole remaining seconds at most (`cache-control: max-age`), and in memory only when less
200
+ than one second remains. A hand-composed entrypoint keeps none with `cache: false`; every call is
201
+ then admitted by its source Kernel. `cloudflareCache()` from `@astrale-os/adapter-cloudflare/worker`
202
+ is the same cache for a Worker that calls `serve()` itself. See the SDK's `docs/admission-age.md`.
203
+
193
204
  ## Build digest
194
205
 
195
206
  `cloudflare()` and `astrale()` bundle through one bundler, `cloudflare-worker` version `1`, so
@@ -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';
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.191",
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.36",
65
65
  "@noble/hashes": "2.3.0",
66
66
  "@restatedev/restate-sdk-cloudflare-workers": "1.17.0",
67
67
  "hono": "^4.6.20",