@astrale-os/adapter-cloudflare 0.5.0-beta.22 → 0.5.0-beta.221

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 +246 -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 +21 -0
  9. package/dist/build/bundler.js +96 -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 +57 -0
  48. package/dist/build/worker/execution.prepare.d.ts +20 -0
  49. package/dist/build/worker/execution.prepare.js +129 -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 +144 -0
  67. package/dist/hosting/client.js +491 -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 +90 -0
  88. package/dist/hosting/kv.js +207 -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 +82 -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 +4 -0
  118. package/dist/hosting/time.js +20 -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 +386 -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 +30 -0
  138. package/dist/namespace/readiness.js +31 -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 +10 -0
  169. package/dist/wrangler/bundle.js +27 -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,226 @@
1
+ import { CloudflareApiError } from '../client.js';
2
+ /** The content of the wildcard record: a proxied AAAA to the discard prefix, so only Workers answer. */
3
+ const WILDCARD_CONTENT = '100::';
4
+ /** DNS record types that route no traffic to a host: certificate validation and policy. */
5
+ const TRAFFICLESS_DNS_TYPES = new Set(['TXT', 'CAA']);
6
+ /** Read the wildcard DNS record and Worker route of one routing domain, changing nothing. */
7
+ export async function observeWildcardRouting(input) {
8
+ const { client, zone } = input;
9
+ const wildcard = `*.${input.routingDomain}`;
10
+ const query = `?type=AAAA&name=${encodeURIComponent(wildcard)}`;
11
+ const records = (await dnsRecords(client, zone, query)).filter((entry) => entry.type === 'AAAA' && entry.name === wildcard);
12
+ return observation(input, records, await workerRoutes(client, zone));
13
+ }
14
+ /**
15
+ * Read everything the zone and the account hold at, under or above one routing domain, changing
16
+ * nothing: every DNS record of the zone, every Worker route of the zone and every Workers custom
17
+ * domain of the account.
18
+ */
19
+ export async function observeDedicatedRouting(input) {
20
+ const { client, zone, routingDomain } = input;
21
+ const records = await dnsRecords(client, zone, '');
22
+ const routes = await workerRoutes(client, zone);
23
+ const customDomains = await accountCustomDomains(client);
24
+ const observed = observation(input, records.filter((entry) => entry.type === 'AAAA' && entry.name === `*.${routingDomain}`), routes);
25
+ const occupants = [];
26
+ for (const entry of records) {
27
+ if (observed.dns.state === 'exact' && entry.id === observed.dns.id)
28
+ continue;
29
+ if (TRAFFICLESS_DNS_TYPES.has(entry.type))
30
+ continue;
31
+ const described = `DNS ${entry.type} ${entry.name}${entry.proxied ? ' (proxied)' : ''}`;
32
+ if (atOrUnder(entry.name, routingDomain))
33
+ occupants.push(described);
34
+ else if (entry.name.startsWith('*.') && routingDomain.endsWith(`.${entry.name.slice(2)}`)) {
35
+ occupants.push(`${described}, which answers every name under ${routingDomain}`);
36
+ }
37
+ }
38
+ for (const candidate of routes) {
39
+ if (observed.route.state === 'exact' && candidate.id === observed.route.id)
40
+ continue;
41
+ if (routeReaches(candidate.pattern, routingDomain)) {
42
+ occupants.push(`route ${candidate.pattern} to ${candidate.script ?? 'no Worker'}`);
43
+ }
44
+ }
45
+ for (const domain of customDomains) {
46
+ if (atOrUnder(domain.hostname, routingDomain)) {
47
+ occupants.push(`Workers custom domain ${domain.hostname} (${domain.service ?? 'no Worker'})`);
48
+ }
49
+ }
50
+ return Object.freeze({ ...observed, occupants: Object.freeze(occupants) });
51
+ }
52
+ /**
53
+ * Converge one routing domain's wildcard ingress on its dispatcher, from an observation: a proxied
54
+ * AAAA `100::` record `*.<domain>` and a `*.<domain>/*` route to the dispatcher. A record or route
55
+ * that says otherwise (`other`) is rewritten: callers that must not take over anything refuse
56
+ * before calling this, from `observeDedicatedRouting`'s occupants.
57
+ */
58
+ export async function applyWildcardRouting(input) {
59
+ const { client, zone, observed } = input;
60
+ const dnsBody = {
61
+ type: 'AAAA',
62
+ name: observed.wildcard,
63
+ content: WILDCARD_CONTENT,
64
+ proxied: true,
65
+ comment: input.comment,
66
+ };
67
+ if (observed.dns.state === 'absent') {
68
+ await client.json('POST', client.zone(zone, '/dns_records'), dnsBody);
69
+ }
70
+ else if (observed.dns.state === 'other') {
71
+ await client.json('PUT', client.zone(zone, `/dns_records/${encodeURIComponent(observed.dns.id)}`), dnsBody);
72
+ }
73
+ const routeBody = { pattern: observed.pattern, script: input.dispatchWorker };
74
+ if (observed.route.state === 'absent') {
75
+ await client.json('POST', client.zone(zone, '/workers/routes'), routeBody);
76
+ }
77
+ else if (observed.route.state === 'other') {
78
+ await client.json('PUT', client.zone(zone, `/workers/routes/${encodeURIComponent(observed.route.id)}`), routeBody);
79
+ }
80
+ }
81
+ /**
82
+ * The id of the account's zone that holds `domain`: the zone named the domain itself or its
83
+ * closest parent, or undefined when the account has none.
84
+ */
85
+ export async function findZone(client, domain) {
86
+ const labels = domain.split('.');
87
+ for (let start = 0; start < labels.length - 1; start += 1) {
88
+ const name = labels.slice(start).join('.');
89
+ const query = new URLSearchParams({ name, 'account.id': client.accountId });
90
+ const zones = await client.json('GET', `/zones?${query}`);
91
+ if (!Array.isArray(zones))
92
+ invalid('zone listing');
93
+ const zone = zones.find((entry) => entry?.name === name);
94
+ if (zone !== undefined) {
95
+ if (typeof zone.id !== 'string' || zone.id.length === 0)
96
+ invalid('zone');
97
+ return zone.id;
98
+ }
99
+ }
100
+ return undefined;
101
+ }
102
+ /**
103
+ * Whether a Worker route pattern matches the routing domain or a host under it, at any depth. A
104
+ * pattern's host is exact, `*.<suffix>` (every name under the suffix) or `*<suffix>` (every name
105
+ * ending with the suffix, the suffix itself included).
106
+ */
107
+ export function routeReaches(pattern, domain) {
108
+ const unschemed = pattern.replace(/^https?:\/\//iu, '');
109
+ const slash = unschemed.indexOf('/');
110
+ const host = (slash === -1 ? unschemed : unschemed.slice(0, slash)).toLowerCase();
111
+ if (host.startsWith('*.')) {
112
+ const suffix = host.slice(2);
113
+ return atOrUnder(suffix, domain) || domain.endsWith(`.${suffix}`);
114
+ }
115
+ if (host.startsWith('*')) {
116
+ const suffix = host.slice(1);
117
+ return `.${domain}`.endsWith(suffix) || suffix.endsWith(`.${domain}`);
118
+ }
119
+ return atOrUnder(host, domain);
120
+ }
121
+ function observation(input, wildcardRecords, routes) {
122
+ const wildcard = `*.${input.routingDomain}`;
123
+ const pattern = `${wildcard}/*`;
124
+ if (wildcardRecords.length > 1)
125
+ invalid('ambiguous wildcard DNS records');
126
+ const exactRoutes = routes.filter((route) => route.pattern === pattern);
127
+ if (exactRoutes.length > 1)
128
+ invalid('ambiguous wildcard Worker routes');
129
+ const record = wildcardRecords[0];
130
+ const route = exactRoutes[0];
131
+ return Object.freeze({
132
+ wildcard,
133
+ pattern,
134
+ dns: record === undefined
135
+ ? { state: 'absent' }
136
+ : {
137
+ state: record.content === WILDCARD_CONTENT && record.proxied
138
+ ? 'exact'
139
+ : 'other',
140
+ id: record.id,
141
+ },
142
+ route: route === undefined
143
+ ? { state: 'absent' }
144
+ : {
145
+ state: route.script === input.dispatchWorker ? 'exact' : 'other',
146
+ id: route.id,
147
+ ...(route.script === undefined ? {} : { script: route.script }),
148
+ },
149
+ });
150
+ }
151
+ /** DNS records of one zone, across all of their pages; `query` narrows them (`?type=&name=`). */
152
+ async function dnsRecords(client, zone, query) {
153
+ const rows = await client.pagedList(client.zone(zone, `/dns_records${query}`), undefined, 100);
154
+ return rows.map((row) => {
155
+ const value = row;
156
+ if (value === null ||
157
+ typeof value !== 'object' ||
158
+ typeof value.id !== 'string' ||
159
+ value.id.length === 0 ||
160
+ typeof value.type !== 'string' ||
161
+ typeof value.name !== 'string' ||
162
+ value.name.length === 0 ||
163
+ (value.content !== undefined && typeof value.content !== 'string') ||
164
+ (value.proxied !== undefined && typeof value.proxied !== 'boolean')) {
165
+ invalid('DNS record');
166
+ }
167
+ return Object.freeze({
168
+ id: value.id,
169
+ type: value.type.toUpperCase(),
170
+ name: value.name.toLowerCase(),
171
+ ...(typeof value.content === 'string' ? { content: value.content } : {}),
172
+ proxied: value.proxied === true,
173
+ });
174
+ });
175
+ }
176
+ async function workerRoutes(client, zone) {
177
+ const rows = await client.json('GET', client.zone(zone, '/workers/routes'));
178
+ if (!Array.isArray(rows))
179
+ invalid('Worker routes');
180
+ return rows.map((row) => {
181
+ const value = row;
182
+ if (value === null ||
183
+ typeof value !== 'object' ||
184
+ typeof value.id !== 'string' ||
185
+ value.id.length === 0 ||
186
+ typeof value.pattern !== 'string' ||
187
+ (value.script !== undefined && value.script !== null && typeof value.script !== 'string')) {
188
+ invalid('Worker route');
189
+ }
190
+ return Object.freeze({
191
+ id: value.id,
192
+ pattern: value.pattern,
193
+ ...(typeof value.script === 'string' ? { script: value.script } : {}),
194
+ });
195
+ });
196
+ }
197
+ /** Every Workers custom domain of the account: Cloudflare returns them in one page. */
198
+ async function accountCustomDomains(client) {
199
+ const page = await client.page(client.account('/workers/domains'));
200
+ if (page.cursor !== undefined || (page.totalPages !== undefined && page.totalPages > 1)) {
201
+ invalid('Workers custom domain inventory');
202
+ }
203
+ if (!Array.isArray(page.result))
204
+ invalid('Workers custom domains');
205
+ return page.result.map((row) => {
206
+ const value = row;
207
+ if (value === null ||
208
+ typeof value !== 'object' ||
209
+ typeof value.hostname !== 'string' ||
210
+ value.hostname.length === 0 ||
211
+ (value.service !== undefined && value.service !== null && typeof value.service !== 'string')) {
212
+ invalid('Workers custom domain');
213
+ }
214
+ return Object.freeze({
215
+ hostname: value.hostname.toLowerCase(),
216
+ ...(typeof value.service === 'string' ? { service: value.service } : {}),
217
+ });
218
+ });
219
+ }
220
+ /** Whether a host name is the routing domain or a name under it. */
221
+ function atOrUnder(name, domain) {
222
+ return name === domain || name.endsWith(`.${domain}`);
223
+ }
224
+ function invalid(context) {
225
+ throw new CloudflareApiError('upstream', `Cloudflare returned invalid ${context} evidence.`);
226
+ }
@@ -0,0 +1,53 @@
1
+ /** The response header the generated Worker answers its provider version in. */
2
+ export declare const VERSION_HEADER = "x-astrale-worker-version";
3
+ /**
4
+ * One way to reach a deployment for readiness:
5
+ *
6
+ * - through its public URL, after activation (the dispatcher serves a label only once its record
7
+ * is published): `publicFetcher(fetch)`;
8
+ * - through a native dispatch namespace binding of the caller's Worker, before activation:
9
+ * `dispatchFetcher(binding, label)`.
10
+ */
11
+ export type ReadinessFetcher = (request: Request) => Promise<Response>;
12
+ /** Reach a deployment through its public URL, with `fetch`. */
13
+ export declare function publicFetcher(fetcher: typeof fetch): ReadinessFetcher;
14
+ /** Reach one deployment through a dispatch namespace binding (`env.<BINDING>.get(label)`). */
15
+ export declare function dispatchFetcher(namespace: {
16
+ get(name: string): {
17
+ fetch(request: Request): Promise<Response>;
18
+ };
19
+ }, label: string): ReadinessFetcher;
20
+ /**
21
+ * Wait until a deployment answers from exactly the provider version this deploy made: every
22
+ * `check` passes on responses carrying `x-astrale-worker-version` equal to `version` (the UUID
23
+ * form of the script's `deployment_id`). A response from another version is propagation still in
24
+ * progress; any failure of `check` is retried every `retryMs` until `timeoutMs`. Requests never
25
+ * leave `url`'s origin, never follow redirects and send no version override: a dispatcher always
26
+ * serves a script's current version.
27
+ *
28
+ * `check` defaults to: every path of `paths` (default `/`) answers 200. A deployer that verifies
29
+ * the release it sealed passes its own check over the versioned fetch it receives.
30
+ */
31
+ export declare function waitForReadiness(input: {
32
+ /** The deployment's origin, `https://<label>.<routing domain>`. */
33
+ readonly url: string;
34
+ readonly version: string;
35
+ readonly fetcher: ReadinessFetcher;
36
+ readonly timeoutMs: number;
37
+ readonly signal?: AbortSignal;
38
+ readonly paths?: readonly string[];
39
+ /** Throws until the deployment is ready; every request it makes goes through `fetch`. */
40
+ readonly check?: (fetch: typeof globalThis.fetch, signal: AbortSignal) => Promise<void>;
41
+ /** Each attempt's own bound. Default 5 s. */
42
+ readonly attemptTimeoutMs?: number;
43
+ /** Between attempts. Default 1 s. */
44
+ readonly retryMs?: number;
45
+ /** Wait between attempts, and the clock the deadline is read on; replaceable in tests. */
46
+ readonly pause?: (ms: number, signal?: AbortSignal) => Promise<void>;
47
+ readonly now?: () => number;
48
+ }): Promise<void>;
49
+ /**
50
+ * A fetch that stays on the deployment origin and admits only responses of the expected provider
51
+ * version: a response of another version is refused, as propagation still in progress.
52
+ */
53
+ export declare function versionFetch(origin: string, version: string, fetcher: ReadinessFetcher): typeof globalThis.fetch;
@@ -0,0 +1,82 @@
1
+ import { wait } from './time.js';
2
+ /** The response header the generated Worker answers its provider version in. */
3
+ export const VERSION_HEADER = 'x-astrale-worker-version';
4
+ /** Reach a deployment through its public URL, with `fetch`. */
5
+ export function publicFetcher(fetcher) {
6
+ return (request) => fetcher(request);
7
+ }
8
+ /** Reach one deployment through a dispatch namespace binding (`env.<BINDING>.get(label)`). */
9
+ export function dispatchFetcher(namespace, label) {
10
+ return (request) => namespace.get(label).fetch(request);
11
+ }
12
+ /**
13
+ * Wait until a deployment answers from exactly the provider version this deploy made: every
14
+ * `check` passes on responses carrying `x-astrale-worker-version` equal to `version` (the UUID
15
+ * form of the script's `deployment_id`). A response from another version is propagation still in
16
+ * progress; any failure of `check` is retried every `retryMs` until `timeoutMs`. Requests never
17
+ * leave `url`'s origin, never follow redirects and send no version override: a dispatcher always
18
+ * serves a script's current version.
19
+ *
20
+ * `check` defaults to: every path of `paths` (default `/`) answers 200. A deployer that verifies
21
+ * the release it sealed passes its own check over the versioned fetch it receives.
22
+ */
23
+ export async function waitForReadiness(input) {
24
+ const origin = new URL(input.url);
25
+ if (origin.protocol !== 'https:' || origin.origin !== input.url.replace(/\/$/u, '')) {
26
+ throw new TypeError('Deployment readiness requires one exact HTTPS origin.');
27
+ }
28
+ const now = input.now ?? Date.now;
29
+ const pause = input.pause ?? wait;
30
+ const deadline = now() + input.timeoutMs;
31
+ const versioned = versionFetch(origin.origin, input.version, input.fetcher);
32
+ const check = input.check ?? pathsAnswer(input.paths ?? ['/']);
33
+ let last;
34
+ for (;;) {
35
+ 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);
48
+ }
49
+ throw new Error(`The deployment did not serve from version ${input.version} within ` +
50
+ `${input.timeoutMs / 1_000} s.`, { cause: last });
51
+ }
52
+ /**
53
+ * A fetch that stays on the deployment origin and admits only responses of the expected provider
54
+ * version: a response of another version is refused, as propagation still in progress.
55
+ */
56
+ export function versionFetch(origin, version, fetcher) {
57
+ const expected = new URL(origin).origin;
58
+ return async (input, init) => {
59
+ const request = input instanceof Request
60
+ ? new Request(input, { ...init, redirect: 'manual' })
61
+ : new Request(new URL(String(input), expected), { ...init, redirect: 'manual' });
62
+ if (new URL(request.url).origin !== expected) {
63
+ throw new TypeError('Deployment readiness cannot leave the deployment origin.');
64
+ }
65
+ const response = await fetcher(request);
66
+ if (response.headers.get(VERSION_HEADER) !== version) {
67
+ await response.body?.cancel();
68
+ throw new Error('The deployment answered from another provider version.');
69
+ }
70
+ return response;
71
+ };
72
+ }
73
+ function pathsAnswer(paths) {
74
+ return async (fetcher, signal) => {
75
+ for (const path of paths) {
76
+ const response = await fetcher(path, { method: 'GET', signal });
77
+ await response.body?.cancel();
78
+ if (response.status !== 200)
79
+ throw new Error(`${path} answered HTTP ${response.status}.`);
80
+ }
81
+ };
82
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Why the hosting kit refused before, or instead of, a write. A refusal is a decision about what
3
+ * the account holds, never a transport failure (`CloudflareApiError`): rerunning without changing
4
+ * the account or the request is refused again.
5
+ */
6
+ export declare class HostingRefusal extends Error {
7
+ readonly name = "HostingRefusal";
8
+ readonly reason:
9
+ /** The namespace's routing KV does not exist: provision the namespace first. */
10
+ 'not-provisioned'
11
+ /** The label names another deployment's script or record; nothing was written. */
12
+ | 'deployment-conflict'
13
+ /** The label is withdrawn and is never served again. */
14
+ | 'deployment-retired'
15
+ /** A stored `record:` is not a record the kit publishes (media type, bytes, metadata). */
16
+ | 'record-invalid'
17
+ /** A stored `retirement:` holds another value than `withdrawn`. */
18
+ | 'retirement-invalid'
19
+ /** A `current:` value (stored or asked) is not a deployment of its name. */
20
+ | 'route-invalid'
21
+ /** A `cron:` value (stored or asked) is not distinct canonical UTC crons. */
22
+ | 'schedules-invalid'
23
+ /** Provisioning would take over what serves something else. */
24
+ | 'resource-conflict'
25
+ /** The API token cannot read what provisioning must observe first. */
26
+ | 'token-scope';
27
+ constructor(reason: HostingRefusal['reason'], message: string);
28
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Why the hosting kit refused before, or instead of, a write. A refusal is a decision about what
3
+ * the account holds, never a transport failure (`CloudflareApiError`): rerunning without changing
4
+ * the account or the request is refused again.
5
+ */
6
+ export class HostingRefusal extends Error {
7
+ name = 'HostingRefusal';
8
+ reason;
9
+ constructor(reason, message) {
10
+ super(message);
11
+ this.reason = reason;
12
+ }
13
+ }
@@ -0,0 +1,68 @@
1
+ import type { WorkerRecord } from '@astrale-os/sdk/deployment/worker';
2
+ import type { CloudflareClient } from './client.js';
3
+ import type { RoutingKv } from './kv.js';
4
+ import type { NamespaceScript } from './script.js';
5
+ import { WITHDRAWN } from './kv.js';
6
+ /** The dispatcher's retirement probe path; it is never a call of the deployment. */
7
+ export declare const RETIREMENT_PROBE_PATH = "/__services_retirement_probe__";
8
+ /** How long Workers KV takes to carry a tombstone to every dispatcher. */
9
+ export declare const RETIREMENT_PROPAGATION_MS = 65000;
10
+ /** How long a caller waits before probing again when the dispatcher does not answer yet. */
11
+ export declare const RETIREMENT_PROBE_RETRY_MS = 15000;
12
+ /**
13
+ * Phase one of a retirement: write the tombstone `retirement:<label>` = `withdrawn`, unless it is
14
+ * already there, read back before it counts. From then on the dispatcher answers
15
+ * `DEPLOYMENT_RETIRED` to every call of the label, while its record endpoint keeps serving
16
+ * `record:<label>`. A withdrawal is permanent: nothing deletes the tombstone.
17
+ */
18
+ export declare function markRetired(kv: RoutingKv, label: string): Promise<{
19
+ readonly previous: 'absent' | typeof WITHDRAWN;
20
+ }>;
21
+ /**
22
+ * Whether the dispatcher answers `DEPLOYMENT_RETIRED` for the deployment at `url`, exactly as
23
+ * kernel-protocol defines it: 410, `x-astrale-deployment-retired: 1`, and the envelope naming the
24
+ * deployment origin. The probe path is never counted as a call. A failed probe answers false;
25
+ * only the caller's cancellation rejects.
26
+ */
27
+ export declare function retirementVisible(input: {
28
+ readonly fetch: typeof fetch;
29
+ readonly url: string;
30
+ readonly timeoutMs?: number;
31
+ readonly signal?: AbortSignal;
32
+ }): Promise<boolean>;
33
+ /** Where phase two of a retirement stands. */
34
+ export type RetirementCompletion = {
35
+ readonly kind: 'removed';
36
+ } | {
37
+ readonly kind: 'propagating';
38
+ readonly retryAfterMs: number;
39
+ } | {
40
+ readonly kind: 'conflict';
41
+ readonly message: string;
42
+ };
43
+ /**
44
+ * Phase two of a retirement: once the tombstone has propagated (`RETIREMENT_PROPAGATION_MS` after
45
+ * `retiredAt`, when the caller kept it) and the dispatcher answers `DEPLOYMENT_RETIRED` for the
46
+ * label (`probe`, usually `retirementVisible` through the public URL), delete its script, and with
47
+ * it the key bound to it; until then delete nothing and answer `propagating`. The record stays at
48
+ * `record:<label>`.
49
+ *
50
+ * The script is deleted only when it is the caller's deployment: a stored record must be the one
51
+ * the caller published (`record`: the same media type and bytes, or `null` for none) when the
52
+ * caller passes it, and the script must satisfy `owns` (its tags, its etag) when the caller passes
53
+ * it; otherwise nothing is deleted (`conflict`). A stored record the kit refuses (`record-invalid`:
54
+ * no metadata, or invalid metadata) rejects before the script is observed or deleted. An absent script
55
+ * is already removed. Rerunning converges.
56
+ */
57
+ export declare function completeRetirement(input: {
58
+ readonly client: CloudflareClient;
59
+ readonly kv: RoutingKv;
60
+ readonly namespace: string;
61
+ readonly label: string;
62
+ readonly probe: () => Promise<boolean>;
63
+ readonly record?: WorkerRecord | null;
64
+ readonly owns?: (script: NamespaceScript) => boolean;
65
+ /** When the tombstone was written (epoch ms), if the caller keeps it. */
66
+ readonly retiredAt?: number;
67
+ readonly now?: () => number;
68
+ }): Promise<RetirementCompletion>;
@@ -0,0 +1,99 @@
1
+ import { readRecord, readRetirement, sameRecord } from './activation.js';
2
+ import { retirementKey, WITHDRAWN } from './kv.js';
3
+ import { deleteScript, observeScript } from './script.js';
4
+ /** The dispatcher's retirement probe path; it is never a call of the deployment. */
5
+ export const RETIREMENT_PROBE_PATH = '/__services_retirement_probe__';
6
+ /** How long Workers KV takes to carry a tombstone to every dispatcher. */
7
+ export const RETIREMENT_PROPAGATION_MS = 65_000;
8
+ /** How long a caller waits before probing again when the dispatcher does not answer yet. */
9
+ export const RETIREMENT_PROBE_RETRY_MS = 15_000;
10
+ const DEFAULT_PROBE_TIMEOUT_MS = 10_000;
11
+ /**
12
+ * Phase one of a retirement: write the tombstone `retirement:<label>` = `withdrawn`, unless it is
13
+ * already there, read back before it counts. From then on the dispatcher answers
14
+ * `DEPLOYMENT_RETIRED` to every call of the label, while its record endpoint keeps serving
15
+ * `record:<label>`. A withdrawal is permanent: nothing deletes the tombstone.
16
+ */
17
+ export async function markRetired(kv, label) {
18
+ if ((await readRetirement(kv, label)) === WITHDRAWN)
19
+ return Object.freeze({ previous: WITHDRAWN });
20
+ await kv.put(retirementKey(label), WITHDRAWN, 'text/plain');
21
+ return Object.freeze({ previous: 'absent' });
22
+ }
23
+ /**
24
+ * Whether the dispatcher answers `DEPLOYMENT_RETIRED` for the deployment at `url`, exactly as
25
+ * kernel-protocol defines it: 410, `x-astrale-deployment-retired: 1`, and the envelope naming the
26
+ * deployment origin. The probe path is never counted as a call. A failed probe answers false;
27
+ * only the caller's cancellation rejects.
28
+ */
29
+ export async function retirementVisible(input) {
30
+ const deployment = new URL(input.url).origin;
31
+ const probe = new URL(RETIREMENT_PROBE_PATH, deployment);
32
+ probe.searchParams.set('retirement', Date.now().toString(36));
33
+ const timeout = AbortSignal.timeout(input.timeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS);
34
+ try {
35
+ const response = await input.fetch(probe, {
36
+ method: 'GET',
37
+ headers: { accept: 'application/json', 'cache-control': 'no-cache' },
38
+ redirect: 'manual',
39
+ signal: input.signal === undefined ? timeout : AbortSignal.any([input.signal, timeout]),
40
+ });
41
+ const text = await response.text();
42
+ if (response.status !== 410 || response.headers.get('x-astrale-deployment-retired') !== '1') {
43
+ return false;
44
+ }
45
+ const body = JSON.parse(text);
46
+ return (body.error?.code === 3002 &&
47
+ body.error.data?.code === 'DEPLOYMENT_RETIRED' &&
48
+ body.error.data.details?.deployment === deployment);
49
+ }
50
+ catch (cause) {
51
+ if (input.signal?.aborted === true)
52
+ throw input.signal.reason ?? cause;
53
+ return false;
54
+ }
55
+ }
56
+ /**
57
+ * Phase two of a retirement: once the tombstone has propagated (`RETIREMENT_PROPAGATION_MS` after
58
+ * `retiredAt`, when the caller kept it) and the dispatcher answers `DEPLOYMENT_RETIRED` for the
59
+ * label (`probe`, usually `retirementVisible` through the public URL), delete its script, and with
60
+ * it the key bound to it; until then delete nothing and answer `propagating`. The record stays at
61
+ * `record:<label>`.
62
+ *
63
+ * The script is deleted only when it is the caller's deployment: a stored record must be the one
64
+ * the caller published (`record`: the same media type and bytes, or `null` for none) when the
65
+ * caller passes it, and the script must satisfy `owns` (its tags, its etag) when the caller passes
66
+ * it; otherwise nothing is deleted (`conflict`). A stored record the kit refuses (`record-invalid`:
67
+ * no metadata, or invalid metadata) rejects before the script is observed or deleted. An absent script
68
+ * is already removed. Rerunning converges.
69
+ */
70
+ export async function completeRetirement(input) {
71
+ const { client, label } = input;
72
+ if (input.record !== undefined) {
73
+ const published = await readRecord(input.kv, label);
74
+ if (published !== undefined && !sameRecord(published, input.record)) {
75
+ return conflict(`The record published for ${label} is not this deployment's.`);
76
+ }
77
+ }
78
+ const script = await observeScript(client, input.namespace, label);
79
+ if (script !== undefined && input.owns !== undefined && !input.owns(script)) {
80
+ return conflict(`The script ${label} is not this deployment's; nothing was deleted.`);
81
+ }
82
+ if (input.retiredAt !== undefined) {
83
+ const remaining = input.retiredAt + RETIREMENT_PROPAGATION_MS - (input.now ?? Date.now)();
84
+ if (remaining > 0)
85
+ return Object.freeze({ kind: 'propagating', retryAfterMs: remaining });
86
+ }
87
+ if (!(await input.probe())) {
88
+ return Object.freeze({ kind: 'propagating', retryAfterMs: RETIREMENT_PROBE_RETRY_MS });
89
+ }
90
+ if (script !== undefined)
91
+ await deleteScript(client, input.namespace, label);
92
+ return Object.freeze({ kind: 'removed' });
93
+ }
94
+ function conflict(message) {
95
+ return Object.freeze({
96
+ kind: 'conflict',
97
+ message: message.length <= 500 ? message : `${message.slice(0, 497)}...`,
98
+ });
99
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The wait an RFC 9110 `Retry-After` states, in milliseconds: delay seconds or an HTTP-date in any
3
+ * of its three forms, as of `now`. Anything else states no wait (undefined). Delay seconds too
4
+ * large to count in milliseconds state an unbounded wait, which no policy admits.
5
+ */
6
+ export declare function retryAfterMs(value: string | null, now: number): number | undefined;
@@ -0,0 +1,55 @@
1
+ // RFC 9110 §5.6.7: a recipient accepts all three HTTP-date forms, each case-sensitive and in GMT.
2
+ const HTTP_DATES = [
3
+ // IMF-fixdate: Sun, 06 Nov 1994 08:49:37 GMT
4
+ /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (?<day>\d{2}) (?<month>[A-Z][a-z]{2}) (?<year>\d{4}) (?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2}) GMT$/u,
5
+ // Obsolete RFC 850 form: Sunday, 06-Nov-94 08:49:37 GMT
6
+ /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (?<day>\d{2})-(?<month>[A-Z][a-z]{2})-(?<year>\d{2}) (?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2}) GMT$/u,
7
+ // Obsolete asctime form: Sun Nov 6 08:49:37 1994
8
+ /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?<month>[A-Z][a-z]{2}) (?<day>\d{2}| \d) (?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2}) (?<year>\d{4})$/u,
9
+ ];
10
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
11
+ /**
12
+ * The wait an RFC 9110 `Retry-After` states, in milliseconds: delay seconds or an HTTP-date in any
13
+ * of its three forms, as of `now`. Anything else states no wait (undefined). Delay seconds too
14
+ * large to count in milliseconds state an unbounded wait, which no policy admits.
15
+ */
16
+ export function retryAfterMs(value, now) {
17
+ if (value === null)
18
+ return undefined;
19
+ const text = value.trim();
20
+ if (/^\d+$/u.test(text)) {
21
+ const waitMs = Number(text) * 1_000;
22
+ return Number.isSafeInteger(waitMs) ? waitMs : Number.POSITIVE_INFINITY;
23
+ }
24
+ const at = httpDate(text, now);
25
+ return at === undefined ? undefined : Math.max(0, at - now);
26
+ }
27
+ /** The instant an RFC 9110 HTTP-date names, or undefined when the text is not a real one. */
28
+ function httpDate(text, now) {
29
+ const fields = HTTP_DATES.map((form) => form.exec(text)?.groups).find(Boolean);
30
+ if (fields === undefined)
31
+ return undefined;
32
+ const month = MONTHS.indexOf(fields.month);
33
+ const day = Number(fields.day);
34
+ const [hour, minute, second] = [fields.hour, fields.minute, fields.second].map(Number);
35
+ if (month < 0 || hour > 23 || minute > 59 || second > 60)
36
+ return undefined;
37
+ const year = fields.year.length === 2 ? rfc850Year(Number(fields.year), now) : Number(fields.year);
38
+ // setUTCFullYear keeps years below 100 literal, which Date.UTC would move to the 1900s.
39
+ const date = new Date(0);
40
+ date.setUTCFullYear(year, month, day);
41
+ if (date.getUTCDate() !== day)
42
+ return undefined;
43
+ return date.getTime() + ((hour * 60 + minute) * 60 + second) * 1_000;
44
+ }
45
+ /**
46
+ * RFC 9110 §5.6.7: a two-digit year that would be more than 50 years ahead names the most recent
47
+ * past year with those last two digits.
48
+ */
49
+ function rfc850Year(lastTwoDigits, now) {
50
+ const current = new Date(now).getUTCFullYear();
51
+ const year = current - (current % 100) + lastTwoDigits;
52
+ if (year > current + 50)
53
+ return year - 100;
54
+ return year <= current - 50 ? year + 100 : year;
55
+ }