@astrale-os/adapter-cloudflare 0.5.0-beta.23 → 0.5.0-beta.231

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.
Files changed (201) hide show
  1. package/README.md +258 -0
  2. package/dist/adapter.d.ts +9 -15
  3. package/dist/adapter.js +43 -129
  4. package/dist/build/bundle/admit.d.ts +3 -0
  5. package/dist/build/bundle/admit.js +47 -0
  6. package/dist/build/bundle/compiled-wasm-loader.d.ts +8 -0
  7. package/dist/build/bundle/compiled-wasm-loader.js +21 -0
  8. package/dist/build/bundler.d.ts +23 -0
  9. package/dist/build/bundler.js +103 -0
  10. package/dist/build/closure.d.ts +4 -1
  11. package/dist/build/closure.js +7 -1
  12. package/dist/build/codegen/execution.d.ts +3 -13
  13. package/dist/build/codegen/execution.js +2 -44
  14. package/dist/build/codegen/wrangler.d.ts +28 -10
  15. package/dist/build/codegen/wrangler.js +71 -21
  16. package/dist/build/configuration/invocation-timeout.d.ts +2 -0
  17. package/dist/build/configuration/invocation-timeout.js +9 -0
  18. package/dist/build/configuration/request-limit.d.ts +2 -0
  19. package/dist/build/configuration/request-limit.js +9 -0
  20. package/dist/build/configuration/router.d.ts +7 -0
  21. package/dist/build/configuration/router.js +17 -0
  22. package/dist/build/configuration/settings.d.ts +6 -0
  23. package/dist/build/configuration/settings.js +40 -0
  24. package/dist/build/configuration.d.ts +4 -9
  25. package/dist/build/configuration.js +4 -40
  26. package/dist/build/frontend/files.d.ts +19 -0
  27. package/dist/build/frontend/files.js +99 -0
  28. package/dist/build/frontend/readiness.d.ts +16 -0
  29. package/dist/build/frontend/readiness.js +21 -0
  30. package/dist/build/frontend/revision.d.ts +5 -0
  31. package/dist/build/frontend/revision.js +14 -0
  32. package/dist/build/frontend/vite.d.ts +14 -0
  33. package/dist/build/frontend/vite.js +42 -0
  34. package/dist/build/frontend/vite.process.d.ts +7 -0
  35. package/dist/build/frontend/vite.process.js +65 -0
  36. package/dist/build/frontend/vite.runner.d.ts +1 -0
  37. package/dist/build/frontend/vite.runner.js +155 -0
  38. package/dist/build/index.d.ts +10 -6
  39. package/dist/build/index.js +10 -6
  40. package/dist/build/material.d.ts +10 -0
  41. package/dist/build/material.js +25 -0
  42. package/dist/build/worker/codegen/entry.d.ts +9 -0
  43. package/dist/build/worker/codegen/entry.js +65 -0
  44. package/dist/build/worker/codegen/literal.d.ts +28 -0
  45. package/dist/build/worker/codegen/literal.js +136 -0
  46. package/dist/build/worker/codegen/service.d.ts +14 -0
  47. package/dist/build/worker/codegen/service.js +56 -0
  48. package/dist/build/worker/execution.prepare.d.ts +22 -0
  49. package/dist/build/worker/execution.prepare.js +131 -0
  50. package/dist/build/worker/media-type.d.ts +1 -0
  51. package/dist/build/worker/media-type.js +20 -0
  52. package/dist/build/worker/modules.d.ts +20 -0
  53. package/dist/build/worker/modules.js +32 -0
  54. package/dist/build/worker/specifier.d.ts +5 -0
  55. package/dist/build/worker/specifier.js +15 -0
  56. package/dist/build/worker/upload.d.ts +23 -0
  57. package/dist/build/worker/upload.js +42 -0
  58. package/dist/hosting/activation.d.ts +46 -0
  59. package/dist/hosting/activation.js +127 -0
  60. package/dist/hosting/assets.d.ts +14 -0
  61. package/dist/hosting/assets.js +53 -0
  62. package/dist/hosting/bounded.d.ts +10 -0
  63. package/dist/hosting/bounded.js +32 -0
  64. package/dist/hosting/bytes.d.ts +6 -0
  65. package/dist/hosting/bytes.js +25 -0
  66. package/dist/hosting/client.d.ts +153 -0
  67. package/dist/hosting/client.js +516 -0
  68. package/dist/hosting/dispatcher/cron.d.mts +10 -0
  69. package/dist/hosting/dispatcher/cron.mjs +135 -0
  70. package/dist/hosting/dispatcher/deployments.d.mts +26 -0
  71. package/dist/hosting/dispatcher/deployments.mjs +158 -0
  72. package/dist/hosting/dispatcher/dispatcher.d.mts +17 -0
  73. package/dist/hosting/dispatcher/dispatcher.mjs +76 -0
  74. package/dist/hosting/dispatcher/env.d.mts +51 -0
  75. package/dist/hosting/dispatcher/failure.d.mts +4 -0
  76. package/dist/hosting/dispatcher/failure.mjs +15 -0
  77. package/dist/hosting/dispatcher/index.d.mts +4 -0
  78. package/dist/hosting/dispatcher/index.mjs +8 -0
  79. package/dist/hosting/dispatcher/modules.d.ts +24 -0
  80. package/dist/hosting/dispatcher/modules.js +55 -0
  81. package/dist/hosting/dispatcher/services.d.mts +23 -0
  82. package/dist/hosting/dispatcher/services.mjs +202 -0
  83. package/dist/hosting/identity.d.ts +15 -0
  84. package/dist/hosting/identity.js +36 -0
  85. package/dist/hosting/index.d.ts +34 -0
  86. package/dist/hosting/index.js +32 -0
  87. package/dist/hosting/kv.d.ts +106 -0
  88. package/dist/hosting/kv.js +235 -0
  89. package/dist/hosting/listing.d.ts +34 -0
  90. package/dist/hosting/listing.js +49 -0
  91. package/dist/hosting/names.d.ts +16 -0
  92. package/dist/hosting/names.js +28 -0
  93. package/dist/hosting/provision/account.d.ts +11 -0
  94. package/dist/hosting/provision/account.js +86 -0
  95. package/dist/hosting/provision/dispatcher.d.ts +42 -0
  96. package/dist/hosting/provision/dispatcher.js +99 -0
  97. package/dist/hosting/provision/ingress.d.ts +12 -0
  98. package/dist/hosting/provision/ingress.js +31 -0
  99. package/dist/hosting/provision/plan.d.ts +143 -0
  100. package/dist/hosting/provision/plan.js +246 -0
  101. package/dist/hosting/provision/routing.d.ts +82 -0
  102. package/dist/hosting/provision/routing.js +226 -0
  103. package/dist/hosting/readiness.d.ts +53 -0
  104. package/dist/hosting/readiness.js +79 -0
  105. package/dist/hosting/refusal.d.ts +28 -0
  106. package/dist/hosting/refusal.js +13 -0
  107. package/dist/hosting/retirement.d.ts +68 -0
  108. package/dist/hosting/retirement.js +99 -0
  109. package/dist/hosting/retry-after.d.ts +6 -0
  110. package/dist/hosting/retry-after.js +55 -0
  111. package/dist/hosting/script.d.ts +186 -0
  112. package/dist/hosting/script.js +324 -0
  113. package/dist/hosting/testing/fake-cloudflare.d.ts +212 -0
  114. package/dist/hosting/testing/fake-cloudflare.js +757 -0
  115. package/dist/hosting/testing/index.d.ts +6 -0
  116. package/dist/hosting/testing/index.js +6 -0
  117. package/dist/hosting/time.d.ts +25 -0
  118. package/dist/hosting/time.js +48 -0
  119. package/dist/identity/binding.d.ts +1 -1
  120. package/dist/identity/binding.js +1 -1
  121. package/dist/identity/material.d.ts +1 -2
  122. package/dist/identity/material.js +5 -18
  123. package/dist/index.d.ts +14 -12
  124. package/dist/index.js +13 -11
  125. package/dist/namespace/configure.d.ts +22 -0
  126. package/dist/namespace/configure.js +199 -0
  127. package/dist/namespace/coordinates.d.ts +15 -0
  128. package/dist/namespace/coordinates.js +49 -0
  129. package/dist/namespace/deploy-release.d.ts +53 -0
  130. package/dist/namespace/deploy-release.js +387 -0
  131. package/dist/namespace/hosting.d.ts +29 -0
  132. package/dist/namespace/hosting.js +120 -0
  133. package/dist/namespace/index.d.ts +12 -0
  134. package/dist/namespace/index.js +12 -0
  135. package/dist/namespace/list.d.ts +18 -0
  136. package/dist/namespace/list.js +63 -0
  137. package/dist/namespace/readiness.d.ts +32 -0
  138. package/dist/namespace/readiness.js +35 -0
  139. package/dist/namespace/record.d.ts +21 -0
  140. package/dist/namespace/record.js +53 -0
  141. package/dist/params.d.ts +60 -76
  142. package/dist/release/build.d.ts +35 -0
  143. package/dist/release/build.js +44 -0
  144. package/dist/release/deployment.d.ts +44 -0
  145. package/dist/release/deployment.js +141 -0
  146. package/dist/release/index.d.ts +2 -2
  147. package/dist/release/index.js +2 -2
  148. package/dist/worker/binary.d.ts +21 -0
  149. package/dist/worker/binary.js +31 -0
  150. package/dist/worker/build-digest.d.ts +10 -0
  151. package/dist/worker/build-digest.js +22 -0
  152. package/dist/worker/cache.d.ts +28 -0
  153. package/dist/worker/cache.js +70 -0
  154. package/dist/worker/durable.d.ts +3 -0
  155. package/dist/worker/durable.js +5 -0
  156. package/dist/worker/entry.d.ts +38 -25
  157. package/dist/worker/entry.js +87 -109
  158. package/dist/worker/front.d.ts +56 -0
  159. package/dist/worker/front.js +59 -0
  160. package/dist/worker/frontend.d.ts +4 -0
  161. package/dist/worker/frontend.js +83 -0
  162. package/dist/worker/index.d.ts +4 -1
  163. package/dist/worker/index.js +4 -1
  164. package/dist/worker/restate.d.ts +6 -0
  165. package/dist/worker/restate.js +6 -0
  166. package/dist/worker/settings.d.ts +47 -0
  167. package/dist/worker/settings.js +163 -0
  168. package/dist/wrangler/bundle.d.ts +18 -0
  169. package/dist/wrangler/bundle.js +36 -0
  170. package/dist/wrangler/index.d.ts +3 -0
  171. package/dist/wrangler/index.js +3 -0
  172. package/dist/wrangler/process.d.ts +15 -0
  173. package/dist/wrangler/process.js +113 -0
  174. package/dist/wrangler/type-generation.d.ts +6 -0
  175. package/dist/wrangler/type-generation.js +19 -0
  176. package/package.json +36 -14
  177. package/template/astrale.config.ts +42 -36
  178. package/dist/build/artifact.d.ts +0 -8
  179. package/dist/build/artifact.js +0 -179
  180. package/dist/build/codegen/gateway.d.ts +0 -1
  181. package/dist/build/codegen/gateway.js +0 -7
  182. package/dist/build/frontend-v1.d.ts +0 -16
  183. package/dist/build/frontend-v1.js +0 -133
  184. package/dist/build/parse-output.d.ts +0 -26
  185. package/dist/build/parse-output.js +0 -57
  186. package/dist/build/wrangler-cli.d.ts +0 -105
  187. package/dist/build/wrangler-cli.js +0 -448
  188. package/dist/deploy/deploy.d.ts +0 -17
  189. package/dist/deploy/deploy.js +0 -207
  190. package/dist/deploy/index.d.ts +0 -1
  191. package/dist/deploy/index.js +0 -1
  192. package/dist/identity/secret.d.ts +0 -3
  193. package/dist/identity/secret.js +0 -7
  194. package/dist/identity/source.d.ts +0 -26
  195. package/dist/identity/source.js +0 -98
  196. package/dist/release/namespace.d.ts +0 -2
  197. package/dist/release/namespace.js +0 -6
  198. package/dist/release/target.d.ts +0 -2
  199. package/dist/release/target.js +0 -9
  200. package/dist/worker/gateway.d.ts +0 -15
  201. package/dist/worker/gateway.js +0 -26
@@ -0,0 +1,158 @@
1
+ import { scriptMissing } from './failure.mjs'
2
+
3
+ // @ts-check
4
+
5
+ /** @typedef {import('./env.mjs').DispatcherEnvironment} DispatcherEnvironment */
6
+ /** @typedef {{ body: ArrayBuffer, contentType?: string }} PublishedRecord */
7
+
8
+ /**
9
+ * Every deployment label, as `@astrale-os/sdk/deployment/address` declares `DEPLOYMENT_LABEL`: an
10
+ * optional readable part, the 16-character line fingerprint and the 16-character content, in
11
+ * lower-case base32. The dispatcher is uploaded as plain modules, so it holds its own copy.
12
+ */
13
+ const DEPLOYMENT_LABEL = /^(?:[a-z0-9]+(?:-[a-z0-9]+)*-)?[a-z2-7]{16}-[a-z2-7]{16}$/u
14
+ /** The longest label a deploy gives: a line of 40 characters, a dash and the content. */
15
+ const MAXIMUM_LABEL_LENGTH = 57
16
+
17
+ /**
18
+ * Where the dispatcher serves a deployment's record, which the deployment then never sees. A
19
+ * deployment that publishes no record answers the path itself.
20
+ */
21
+ const DEPLOYMENT_RECORD_PATH = '/.well-known/astrale/deployment.json'
22
+ const ENVELOPE_TYPE = 'application/vnd.astrale+json'
23
+ /** The retirement probe (`retirementVisible`); it is never a call of the deployment. */
24
+ export const RETIREMENT_PROBE_PATH = '/__services_retirement_probe__'
25
+ const ACTIVATION_RETRY_AFTER_SECONDS = '30'
26
+
27
+ /** @param {string} label */
28
+ export function isDeploymentLabel(label) {
29
+ return label.length <= MAXIMUM_LABEL_LENGTH && DEPLOYMENT_LABEL.test(label)
30
+ }
31
+
32
+ /**
33
+ * Route one request to one deployment: the one its host names, or the one a name points at
34
+ * (`./services.mjs`). A deployer writes `record:<label>` to activate the label, and its owner
35
+ * `retirement:<label>` to retire it; the record outlives the retirement. Every call of a retired
36
+ * deployment answers `DEPLOYMENT_RETIRED`, whatever its path. The record endpoint is not a call:
37
+ * the dispatcher answers it itself with the record the deployer published, its bytes and its media
38
+ * type as written, and the record it serves immutable stays readable after retirement. A
39
+ * deployment without its record is not active yet (KV is eventually consistent, so a caller
40
+ * retries), and only an active deployment runs, as one call point when `CALLS` is bound. A
41
+ * `record:<label>` without its media type metadata activates nothing (`activationRecord`).
42
+ *
43
+ * @param {Request} request
44
+ * @param {DispatcherEnvironment} environment
45
+ * @param {string} label
46
+ */
47
+ export async function dispatchDeployment(request, environment, label) {
48
+ const url = new URL(request.url)
49
+ try {
50
+ const [retirement, record] = await Promise.all([
51
+ environment.SCHEDULES.get(`retirement:${label}`),
52
+ activationRecord(environment, label),
53
+ ])
54
+ if (url.pathname === DEPLOYMENT_RECORD_PATH && record?.contentType !== undefined) {
55
+ return deploymentRecordResponse(request, record)
56
+ }
57
+ if (retirement !== null) return deploymentRetiredResponse(url.origin)
58
+ if (record === null) return inactiveDeploymentResponse(url.origin)
59
+ if (url.pathname !== RETIREMENT_PROBE_PATH) {
60
+ environment.CALLS?.writeDataPoint({ indexes: [label] })
61
+ }
62
+ return await environment.DEPLOYMENTS.get(label).fetch(request)
63
+ } catch (cause) {
64
+ if (scriptMissing(cause)) return inactiveDeploymentResponse(url.origin)
65
+ return new Response('dispatch error', { status: 502 })
66
+ }
67
+ }
68
+
69
+ /**
70
+ * The record that activates a label, as the kit writes `record:<label>`: its bytes with the media
71
+ * type of its metadata (`{"contentType":<type>}`), or without `contentType` when the deployment
72
+ * publishes no record (`-`, `{"contentType":null}`). `null` when the label is not activated, and
73
+ * when its value carries no such metadata: that is no record the kit writes, and activates
74
+ * nothing.
75
+ *
76
+ * @param {Pick<DispatcherEnvironment, 'SCHEDULES'>} environment
77
+ * @param {string} label
78
+ * @returns {Promise<PublishedRecord | null>}
79
+ */
80
+ export async function activationRecord(environment, label) {
81
+ const stored = await environment.SCHEDULES.getWithMetadata(`record:${label}`, 'arrayBuffer')
82
+ if (stored.value === null) return null
83
+ const metadata = /** @type {{ contentType?: unknown } | null | undefined} */ (stored.metadata)
84
+ const contentType = typeof metadata === 'object' ? metadata?.contentType : undefined
85
+ if (typeof contentType === 'string') return { body: stored.value, contentType }
86
+ return contentType === null ? { body: stored.value } : null
87
+ }
88
+
89
+ /**
90
+ * The record a deployer published for this label. It never changes: the label is derived from the
91
+ * build and the configuration of the deployment it describes.
92
+ *
93
+ * @param {Request} request
94
+ * @param {PublishedRecord} record
95
+ */
96
+ function deploymentRecordResponse(request, record) {
97
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
98
+ return new Response('method not allowed', {
99
+ status: 405,
100
+ headers: { allow: 'GET, HEAD', 'cache-control': 'no-store' },
101
+ })
102
+ }
103
+ return new Response(record.body, {
104
+ status: 200,
105
+ headers: {
106
+ 'content-type': /** @type {string} */ (record.contentType),
107
+ 'cache-control': 'public, max-age=31536000, immutable',
108
+ },
109
+ })
110
+ }
111
+
112
+ /**
113
+ * `DEPLOYMENT_RETIRED` in the one HTTP form every emitter answers, attributed to the deployment,
114
+ * whose issuer is its origin: the bytes of kernel-protocol `routes.deploymentRetiredBody`, in its
115
+ * key order, and `routes.deploymentRetiredHeaders`.
116
+ *
117
+ * @param {string} deployment
118
+ */
119
+ function deploymentRetiredResponse(deployment) {
120
+ return new Response(
121
+ JSON.stringify({
122
+ error: {
123
+ code: 3002,
124
+ message: 'This deployment is retired.',
125
+ data: { code: 'DEPLOYMENT_RETIRED', details: { deployment } },
126
+ },
127
+ requestId: null,
128
+ invocation: { source: deployment, id: 'unavailable' },
129
+ }),
130
+ {
131
+ status: 410,
132
+ headers: {
133
+ 'x-astrale-deployment-retired': '1',
134
+ 'cache-control': 'no-store',
135
+ 'content-type': ENVELOPE_TYPE,
136
+ },
137
+ },
138
+ )
139
+ }
140
+
141
+ /** @param {string} deployment */
142
+ function inactiveDeploymentResponse(deployment) {
143
+ return new Response(
144
+ JSON.stringify({
145
+ requestId: null,
146
+ invocation: { source: deployment, id: 'unavailable' },
147
+ error: { code: 5001, message: 'This deployment is not active yet.' },
148
+ }),
149
+ {
150
+ status: 503,
151
+ headers: {
152
+ 'cache-control': 'no-store',
153
+ 'content-type': ENVELOPE_TYPE,
154
+ 'retry-after': ACTIVATION_RETRY_AFTER_SECONDS,
155
+ },
156
+ },
157
+ )
158
+ }
@@ -0,0 +1,17 @@
1
+ import type { DispatcherEnvironment, ScheduleController } from './env.mjs'
2
+
3
+ export interface Dispatcher<Environment extends DispatcherEnvironment = DispatcherEnvironment> {
4
+ fetch(request: Request, environment: Environment): Promise<Response>
5
+ scheduled(controller: ScheduleController, environment: Environment): Promise<void>
6
+ }
7
+
8
+ /**
9
+ * Whether a public path names the schedule endpoint in any spelling a router behind the dispatcher
10
+ * could normalize to it: percent-encoded, with repeated or trailing slashes, in any case.
11
+ */
12
+ export function isSchedulePath(pathname: string): boolean
13
+
14
+ /** Create one public dispatcher over canonical deployment routing and schedules. */
15
+ export function createDispatcher<
16
+ Environment extends DispatcherEnvironment = DispatcherEnvironment,
17
+ >(): Dispatcher<Environment>
@@ -0,0 +1,76 @@
1
+ import { dispatchDeployment, isDeploymentLabel } from './deployments.mjs'
2
+ import {
3
+ dispatchService,
4
+ fanOutSchedules,
5
+ isServiceName,
6
+ missingServiceResponse,
7
+ } from './services.mjs'
8
+
9
+ // @ts-check
10
+
11
+ /** @typedef {import('./env.mjs').DispatcherEnvironment} DispatcherEnvironment */
12
+
13
+ /**
14
+ * Whether a public path names the schedule endpoint in any spelling a router behind the dispatcher
15
+ * could normalize to it: percent-encoded, with repeated or trailing slashes, in any case.
16
+ *
17
+ * @param {string} pathname
18
+ * @returns {boolean}
19
+ */
20
+ export function isSchedulePath(pathname) {
21
+ let decoded = pathname
22
+ try {
23
+ decoded = decodeURIComponent(pathname)
24
+ } catch {
25
+ // A malformed escape is compared as written.
26
+ }
27
+ return (
28
+ decoded
29
+ .replace(/\/{2,}/gu, '/')
30
+ .replace(/\/+$/u, '')
31
+ .toLowerCase() === '/__scheduled'
32
+ )
33
+ }
34
+
35
+ /**
36
+ * Create one public dispatcher of a dispatch namespace. A deployment label
37
+ * (`https://<label>.<routing domain>`) reaches its own script; a name
38
+ * (`https://<name>.<routing domain>`) reaches the deployment `current:<name>` names, through the
39
+ * same deployment routing; anything else answers `no such service: <name>`. The public never
40
+ * reaches a deployment's schedule endpoint, `/__scheduled`: only the cron fan-out calls it.
41
+ *
42
+ * The dispatcher is given no custom limits: a dispatcher's `limits.subRequests` would also count
43
+ * the deployments' own binding calls.
44
+ *
45
+ * @template {DispatcherEnvironment} Environment
46
+ */
47
+ export function createDispatcher() {
48
+ if (arguments.length !== 0) {
49
+ throw new TypeError('Dispatcher creation accepts no options.')
50
+ }
51
+ return Object.freeze({
52
+ /**
53
+ * @param {Request} request
54
+ * @param {Environment} environment
55
+ * @returns {Promise<Response>}
56
+ */
57
+ async fetch(request, environment) {
58
+ const url = new URL(request.url)
59
+ // Only the cron fan-out reaches a deployment's schedule endpoint, never the public.
60
+ if (isSchedulePath(url.pathname)) return new Response('not found', { status: 404 })
61
+ const name = url.hostname.split('.')[0] ?? ''
62
+ if (isDeploymentLabel(name)) return dispatchDeployment(request, environment, name)
63
+ if (isServiceName(name)) return dispatchService(request, environment, name)
64
+ return missingServiceResponse(request, name)
65
+ },
66
+
67
+ /**
68
+ * @param {{ scheduledTime?: number }} controller
69
+ * @param {Environment} environment
70
+ * @returns {Promise<void>}
71
+ */
72
+ async scheduled(controller, environment) {
73
+ await fanOutSchedules(controller, environment)
74
+ },
75
+ })
76
+ }
@@ -0,0 +1,51 @@
1
+ /** What a dispatch namespace binding's `get(name)` answers: the script's fetcher. */
2
+ export interface DispatchFetcher {
3
+ fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>
4
+ }
5
+
6
+ /** A dispatch namespace binding (`DEPLOYMENTS`, or one a consumer binds beside it). */
7
+ export interface DispatchNamespaceBinding {
8
+ get(name: string): DispatchFetcher
9
+ }
10
+
11
+ export interface ScheduleKey {
12
+ readonly name: string
13
+ }
14
+
15
+ export type SchedulePage =
16
+ | { readonly keys: readonly ScheduleKey[]; readonly list_complete: true }
17
+ | {
18
+ readonly keys: readonly ScheduleKey[]
19
+ readonly list_complete: false
20
+ readonly cursor: string
21
+ }
22
+
23
+ /** The routing KV binding (`SCHEDULES`): the dispatcher only reads it. */
24
+ export interface RoutingKvBinding {
25
+ get(key: string): Promise<string | null>
26
+ /** Read for `record:<label>` only: a record's bytes and the metadata it was written with. */
27
+ getWithMetadata(
28
+ key: string,
29
+ type: 'arrayBuffer',
30
+ ): Promise<{ readonly value: ArrayBuffer | null; readonly metadata: unknown }>
31
+ list(options: { readonly prefix: string; readonly cursor?: string }): Promise<SchedulePage>
32
+ }
33
+
34
+ /** The calls dataset binding (`CALLS`), optional: one data point `{ indexes: [label] }` per call. */
35
+ export interface CallsBinding {
36
+ writeDataPoint(point: { readonly indexes: readonly string[] }): void
37
+ }
38
+
39
+ /** The bindings the kit's dispatcher reads. */
40
+ export interface DispatcherEnvironment {
41
+ readonly DEPLOYMENTS: DispatchNamespaceBinding
42
+ readonly SCHEDULES: RoutingKvBinding
43
+ readonly CALLS?: CallsBinding
44
+ }
45
+
46
+ /** The bindings the cron fan-out reads. */
47
+ export type ScheduleEnvironment = Pick<DispatcherEnvironment, 'DEPLOYMENTS' | 'SCHEDULES'>
48
+
49
+ export interface ScheduleController {
50
+ readonly scheduledTime?: number
51
+ }
@@ -0,0 +1,4 @@
1
+ /** The message of a failure, as the dispatcher logs it. */
2
+ export function errorText(cause: unknown): string
3
+ /** Whether a dispatch namespace refused a script it does not hold (`Worker not found.`). */
4
+ export function scriptMissing(cause: unknown): boolean
@@ -0,0 +1,15 @@
1
+ // @ts-check
2
+
3
+ /** @param {unknown} cause */
4
+ export function errorText(cause) {
5
+ return cause instanceof Error ? cause.message : String(cause)
6
+ }
7
+
8
+ /**
9
+ * Whether a dispatch namespace refused a script it does not hold. Cloudflare rejects
10
+ * `get(<absent>).fetch()` with `Error: Worker not found.`
11
+ * @param {unknown} cause
12
+ */
13
+ export function scriptMissing(cause) {
14
+ return /not found|could not find|no such/iu.test(errorText(cause))
15
+ }
@@ -0,0 +1,4 @@
1
+ import type { Dispatcher } from './dispatcher.mjs'
2
+
3
+ declare const dispatcher: Dispatcher
4
+ export default dispatcher
@@ -0,0 +1,8 @@
1
+ import { createDispatcher } from './dispatcher.mjs'
2
+
3
+ // @ts-check
4
+
5
+ /**
6
+ * The kit's canonical dispatcher: the main module (`index.mjs`) `dispatcherModules()` uploads.
7
+ */
8
+ export default createDispatcher()
@@ -0,0 +1,24 @@
1
+ /** One module of the dispatcher Worker upload. */
2
+ export interface DispatcherModule {
3
+ /** The module name the Worker imports it by (`index.mjs` is the main module). */
4
+ readonly name: string;
5
+ readonly bytes: Uint8Array;
6
+ /** The multipart type Cloudflare reads the module as. */
7
+ readonly type: 'application/javascript+module';
8
+ }
9
+ /** The main module every dispatcher upload names. */
10
+ export declare const DISPATCHER_MAIN_MODULE = "index.mjs";
11
+ /**
12
+ * The kit's dispatcher modules, under the names they import each other by. They are plain ES
13
+ * modules shipped with the package (`dist/hosting/dispatcher/*.mjs`) and uploaded as they are.
14
+ */
15
+ export declare const DISPATCHER_MODULE_NAMES: readonly ["index.mjs", "dispatcher.mjs", "deployments.mjs", "services.mjs", "failure.mjs", "cron.mjs"];
16
+ /**
17
+ * The modules of one dispatcher upload: the kit's, read from the package, with `extra` added or
18
+ * replacing a kit module of the same name. A consumer with routing of its own supplies its own
19
+ * `index.mjs` and any module that it imports.
20
+ */
21
+ export declare function dispatcherModules(extra?: readonly {
22
+ readonly name: string;
23
+ readonly bytes: Uint8Array;
24
+ }[]): Promise<readonly DispatcherModule[]>;
@@ -0,0 +1,55 @@
1
+ /** The main module every dispatcher upload names. */
2
+ export const DISPATCHER_MAIN_MODULE = 'index.mjs';
3
+ /**
4
+ * The kit's dispatcher modules, under the names they import each other by. They are plain ES
5
+ * modules shipped with the package (`dist/hosting/dispatcher/*.mjs`) and uploaded as they are.
6
+ */
7
+ export const DISPATCHER_MODULE_NAMES = Object.freeze([
8
+ 'index.mjs',
9
+ 'dispatcher.mjs',
10
+ 'deployments.mjs',
11
+ 'services.mjs',
12
+ 'failure.mjs',
13
+ 'cron.mjs',
14
+ ]);
15
+ /**
16
+ * The modules of one dispatcher upload: the kit's, read from the package, with `extra` added or
17
+ * replacing a kit module of the same name. A consumer with routing of its own supplies its own
18
+ * `index.mjs` and any module that it imports.
19
+ */
20
+ export async function dispatcherModules(extra = []) {
21
+ const names = new Set();
22
+ for (const module of extra) {
23
+ if (!/^[A-Za-z0-9_][A-Za-z0-9_./-]*\.mjs$/u.test(module.name) || module.name.includes('..')) {
24
+ throw new TypeError(`Dispatcher module name ${module.name} is invalid.`);
25
+ }
26
+ if (names.has(module.name))
27
+ throw new TypeError(`Dispatcher module ${module.name} repeats.`);
28
+ names.add(module.name);
29
+ }
30
+ const kit = await Promise.all(DISPATCHER_MODULE_NAMES.filter((name) => !names.has(name)).map(async (name) => ({
31
+ name,
32
+ bytes: await readModule(name),
33
+ })));
34
+ const all = [...kit, ...extra];
35
+ // The main module first, as Cloudflare's own uploads list it.
36
+ all.sort((left, right) => Number(right.name === DISPATCHER_MAIN_MODULE) - Number(left.name === DISPATCHER_MAIN_MODULE));
37
+ return Object.freeze(all.map((module) => Object.freeze({
38
+ name: module.name,
39
+ bytes: module.bytes,
40
+ type: 'application/javascript+module',
41
+ })));
42
+ }
43
+ /**
44
+ * Read one kit module beside this one. Node's file system is reached through
45
+ * `process.getBuiltinModule`, never an import: the rest of the kit runs in a Worker, and a bundler
46
+ * must not see a `node:` module through it.
47
+ */
48
+ async function readModule(name) {
49
+ const host = globalThis.process;
50
+ const fs = host?.getBuiltinModule?.('node:fs/promises');
51
+ if (fs === undefined) {
52
+ throw new TypeError('Reading the dispatcher modules needs Node.js (provisioning runs in Node).');
53
+ }
54
+ return new Uint8Array(await fs.readFile(new URL(`./${name}`, import.meta.url)));
55
+ }
@@ -0,0 +1,23 @@
1
+ import type { DispatcherEnvironment, ScheduleController, ScheduleEnvironment } from './env.mjs'
2
+
3
+ /** Whether a host label is a line name (≤ 40 characters, never a deployment label). */
4
+ export function isServiceName(name: string): boolean
5
+ /** Route one request to the deployment `current:<name>` names. */
6
+ export function dispatchService(
7
+ request: Request,
8
+ environment: DispatcherEnvironment,
9
+ service: string,
10
+ ): Promise<Response>
11
+ /** 404 `no such service: <name>` (no-store), or the 503 5001 envelope on `/invoke`. */
12
+ export function missingServiceResponse(request: Request, service: string): Response
13
+ /** Fire every due `cron:<name>` on its current active deployment. */
14
+ export function fanOutSchedules<Environment extends ScheduleEnvironment>(
15
+ controller: ScheduleController,
16
+ environment: Environment,
17
+ ): Promise<void>
18
+ /** Run one bounded sliding-window fan-out. */
19
+ export function pool<Value>(
20
+ items: readonly Value[],
21
+ limit: number,
22
+ operation: (value: Value) => void | Promise<void>,
23
+ ): Promise<void>
@@ -0,0 +1,202 @@
1
+ import { canonicalUtcCrons, matches } from './cron.mjs'
2
+ import { activationRecord, dispatchDeployment, isDeploymentLabel } from './deployments.mjs'
3
+ import { errorText } from './failure.mjs'
4
+
5
+ // @ts-check
6
+ /* eslint-disable no-console -- the cron fan-out reports each schedule event to Workers logs. */
7
+
8
+ /** @typedef {import('./env.mjs').DispatcherEnvironment} DispatcherEnvironment */
9
+ /** @typedef {import('./env.mjs').ScheduleEnvironment} ScheduleEnvironment */
10
+ /**
11
+ * Every name a deployment line gives, as a deployer admits one: the 16-character fingerprint
12
+ * alone when opaque, `<readable>-<fingerprint>` when readable, and never a deployment label.
13
+ */
14
+ const SERVICE_NAME = /^(?:[a-z0-9]+(?:-[a-z0-9]+)*-)?[a-z2-7]{16}$/u
15
+ /** The longest line a deploy gives. */
16
+ const MAXIMUM_SERVICE_NAME_LENGTH = 40
17
+ const SCHEDULED_TIMEOUT_MS = 10_000
18
+ const FAN_OUT_CONCURRENCY = 16
19
+
20
+ /** @param {string} name */
21
+ export function isServiceName(name) {
22
+ return (
23
+ name.length <= MAXIMUM_SERVICE_NAME_LENGTH &&
24
+ SERVICE_NAME.test(name) &&
25
+ !isDeploymentLabel(name)
26
+ )
27
+ }
28
+
29
+ /**
30
+ * The deployment one name serves now: `current:<name>`, admitted as one of its own labels.
31
+ *
32
+ * @param {Pick<DispatcherEnvironment, 'SCHEDULES'>} environment
33
+ * @param {string} service
34
+ * @returns {Promise<string | null>}
35
+ */
36
+ async function currentDeployment(environment, service) {
37
+ const label = await environment.SCHEDULES.get(`current:${service}`)
38
+ if (label === null) return null
39
+ if (!isDeploymentLabel(label) || !label.startsWith(`${service}-`)) {
40
+ throw new TypeError('The current deployment of the name is not one of its labels.')
41
+ }
42
+ return label
43
+ }
44
+
45
+ /**
46
+ * Route one request to the deployment a name points at (`current:<name>`), exactly as that
47
+ * deployment's own URL routes it: its record, its tombstone and its call point apply. A name with
48
+ * no current deployment serves nothing.
49
+ *
50
+ * @param {Request} request
51
+ * @param {DispatcherEnvironment} environment
52
+ * @param {string} service
53
+ */
54
+ export async function dispatchService(request, environment, service) {
55
+ /** @type {string | null} */
56
+ let label
57
+ try {
58
+ label = await currentDeployment(environment, service)
59
+ } catch {
60
+ return new Response('dispatch error', { status: 502 })
61
+ }
62
+ if (label === null) return missingServiceResponse(request, service)
63
+ return dispatchDeployment(request, environment, label)
64
+ }
65
+
66
+ /**
67
+ * The answer for a name nothing serves: `/invoke` answers the invocation envelope of an
68
+ * unavailable callee, every other path a plain 404 the ingress probe recognizes.
69
+ *
70
+ * @param {Request} request
71
+ * @param {string} service
72
+ */
73
+ export function missingServiceResponse(request, service) {
74
+ const headers = { 'cache-control': 'no-store' }
75
+ const url = new URL(request.url)
76
+ if (url.pathname !== '/invoke') {
77
+ return new Response(`no such service: ${service}`, { status: 404, headers })
78
+ }
79
+ return new Response(
80
+ JSON.stringify({
81
+ requestId: null,
82
+ invocation: { source: url.origin, id: 'unavailable' },
83
+ error: { code: 5001, message: 'Service is unavailable.' },
84
+ }),
85
+ {
86
+ status: 503,
87
+ headers: { ...headers, 'content-type': 'application/vnd.astrale+json' },
88
+ },
89
+ )
90
+ }
91
+
92
+ /**
93
+ * Fire every cron of `cron:<name>` that matches this minute on the deployment the name serves now
94
+ * (`current:<name>`), while it is active (`record:<label>`) and not retired (`retirement:<label>`).
95
+ * One name's failure never stops the others.
96
+ *
97
+ * @template {ScheduleEnvironment} Environment
98
+ * @param {{ scheduledTime?: number }} controller
99
+ * @param {Environment} environment
100
+ */
101
+ export async function fanOutSchedules(controller, environment) {
102
+ const scheduledAt = controller.scheduledTime ?? Date.now()
103
+ const date = new Date(scheduledAt)
104
+ const cursors = new Set()
105
+ /** @type {string | undefined} */
106
+ let cursor
107
+ do {
108
+ const page = await environment.SCHEDULES.list({ prefix: 'cron:', cursor })
109
+ await pool(page.keys, FAN_OUT_CONCURRENCY, ({ name }) =>
110
+ fire(environment, name.slice('cron:'.length), name, date, scheduledAt),
111
+ )
112
+ if (page.list_complete) cursor = undefined
113
+ else {
114
+ const next = page.cursor
115
+ if (typeof next !== 'string' || next.length === 0 || cursors.has(next)) {
116
+ throw new TypeError('Schedule cursor did not advance.')
117
+ }
118
+ cursors.add(next)
119
+ cursor = next
120
+ }
121
+ } while (cursor !== undefined)
122
+ }
123
+
124
+ /**
125
+ * Run one bounded sliding-window fan-out.
126
+ *
127
+ * @template Value
128
+ * @param {readonly Value[]} items
129
+ * @param {number} limit
130
+ * @param {(value: Value) => void | Promise<void>} operation
131
+ */
132
+ export async function pool(items, limit, operation) {
133
+ const iterator = items[Symbol.iterator]()
134
+ const worker = async () => {
135
+ for (let item = iterator.next(); !item.done; item = iterator.next()) {
136
+ await operation(item.value)
137
+ }
138
+ }
139
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker))
140
+ }
141
+
142
+ /**
143
+ * @template {ScheduleEnvironment} Environment
144
+ * @param {Environment} environment
145
+ * @param {string} service
146
+ * @param {string} key
147
+ * @param {Date} date
148
+ * @param {number} scheduledAt
149
+ */
150
+ async function fire(environment, service, key, date, scheduledAt) {
151
+ if (!isServiceName(service)) {
152
+ console.warn(JSON.stringify({ event: 'service.schedule.invalid-service', service }))
153
+ return
154
+ }
155
+ /** @type {unknown} */
156
+ let crons
157
+ try {
158
+ crons = JSON.parse((await environment.SCHEDULES.get(key)) ?? '[]')
159
+ } catch {
160
+ console.warn(JSON.stringify({ event: 'service.schedule.invalid', service }))
161
+ return
162
+ }
163
+ const schedules = canonicalUtcCrons(crons)
164
+ if (schedules === undefined) {
165
+ console.warn(JSON.stringify({ event: 'service.schedule.invalid', service }))
166
+ return
167
+ }
168
+ const cron = schedules.find((value) => matches(value, date))
169
+ if (cron === undefined) return
170
+ try {
171
+ const deployment = await currentDeployment(environment, service)
172
+ if (deployment === null) return
173
+ const [retirement, record] = await Promise.all([
174
+ environment.SCHEDULES.get(`retirement:${deployment}`),
175
+ activationRecord(environment, deployment),
176
+ ])
177
+ if (retirement !== null || record === null) return
178
+ const fetcher = environment.DEPLOYMENTS.get(deployment)
179
+ const response = await fetcher.fetch('https://cron.internal/__scheduled', {
180
+ method: 'POST',
181
+ headers: {
182
+ 'x-astrale-cron': cron,
183
+ 'x-astrale-scheduled-time': String(scheduledAt),
184
+ },
185
+ signal: AbortSignal.timeout(SCHEDULED_TIMEOUT_MS),
186
+ })
187
+ if (!response.ok) {
188
+ console.warn(
189
+ JSON.stringify({
190
+ event: 'service.schedule.rejected',
191
+ service,
192
+ deployment,
193
+ status: response.status,
194
+ }),
195
+ )
196
+ }
197
+ } catch (cause) {
198
+ console.error(
199
+ JSON.stringify({ event: 'service.schedule.failed', service, error: errorText(cause) }),
200
+ )
201
+ }
202
+ }
@@ -0,0 +1,15 @@
1
+ /** The private key of one deployment, as its Worker reads `ASTRALE_SIGNING_IDENTITY`. */
2
+ export interface DeploymentSigningIdentity {
3
+ /** RFC 7638 thumbprint of the public key: the `astrale-key:` tag and the JWK's `kid`. */
4
+ readonly keyId: string;
5
+ /**
6
+ * The private Ed25519 JWK as JSON text, `{ kty, crv, x, d, alg: 'EdDSA', kid }`: bound once as a
7
+ * `secret_text` and never logged, returned or stored anywhere else.
8
+ */
9
+ readonly secret: string;
10
+ }
11
+ /**
12
+ * Generate the Ed25519 key of one new deployment with WebCrypto, so it runs in Node and in a
13
+ * Worker. Every deployment is its own issuer with a key of its own.
14
+ */
15
+ export declare function createSigningIdentity(): Promise<DeploymentSigningIdentity>;