@astrale-os/adapter-astrale 0.5.0-beta.21 → 0.5.0-beta.210

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 (54) hide show
  1. package/README.md +161 -2
  2. package/dist/adapter.d.ts +7 -16
  3. package/dist/adapter.js +27 -266
  4. package/dist/admit.d.ts +7 -0
  5. package/dist/admit.js +44 -0
  6. package/dist/cli/commands/call.d.ts +15 -0
  7. package/dist/cli/commands/call.js +36 -0
  8. package/dist/cli/commands/version.d.ts +12 -0
  9. package/dist/cli/commands/version.js +56 -0
  10. package/dist/cli/diagnostic.d.ts +6 -0
  11. package/dist/cli/diagnostic.js +28 -0
  12. package/dist/cli/error.d.ts +7 -0
  13. package/dist/cli/error.js +29 -0
  14. package/dist/cli/executable.d.ts +2 -0
  15. package/dist/cli/executable.js +54 -0
  16. package/dist/cli/identity.d.ts +5 -0
  17. package/dist/cli/identity.js +11 -0
  18. package/dist/cli/json.d.ts +2 -0
  19. package/dist/cli/json.js +39 -0
  20. package/dist/cli/process.d.ts +18 -0
  21. package/dist/cli/process.js +109 -0
  22. package/dist/configure.d.ts +17 -0
  23. package/dist/configure.js +40 -0
  24. package/dist/deploy/deploy-release.d.ts +30 -0
  25. package/dist/deploy/deploy-release.js +168 -0
  26. package/dist/deploy/list.d.ts +22 -0
  27. package/dist/deploy/list.js +63 -0
  28. package/dist/deploy/readiness.d.ts +17 -0
  29. package/dist/deploy/readiness.js +56 -0
  30. package/dist/index.d.ts +21 -10
  31. package/dist/index.js +21 -10
  32. package/dist/params.d.ts +25 -36
  33. package/dist/services/api.d.ts +35 -0
  34. package/dist/services/api.js +39 -0
  35. package/dist/services/client.d.ts +93 -0
  36. package/dist/services/client.js +116 -0
  37. package/dist/services/directory.d.ts +16 -0
  38. package/dist/services/directory.js +78 -0
  39. package/dist/services/index.d.ts +44 -0
  40. package/dist/services/index.js +27 -0
  41. package/dist/services/request.d.ts +25 -0
  42. package/dist/services/request.js +71 -0
  43. package/package.json +18 -11
  44. package/template/astrale.config.ts +27 -38
  45. package/dist/cli.d.ts +0 -15
  46. package/dist/cli.js +0 -48
  47. package/dist/prerequisite.d.ts +0 -19
  48. package/dist/prerequisite.js +0 -59
  49. package/dist/service/addressing.d.ts +0 -3
  50. package/dist/service/addressing.js +0 -16
  51. package/dist/service/artifact.d.ts +0 -34
  52. package/dist/service/artifact.js +0 -122
  53. package/dist/service/readiness.d.ts +0 -3
  54. package/dist/service/readiness.js +0 -16
@@ -0,0 +1,56 @@
1
+ import { CliProcessError } from '../error.js';
2
+ import { runCliProcess } from '../process.js';
3
+ /**
4
+ * The first astrale CLI release whose `call` runs on the Admin kernel (`--admin`) and reads its
5
+ * input from stdin with `-d -` (CT21, cli#579), built on an SDK that reads an R1 Kernel's Schema
6
+ * introspection (cli#581): every deploy reaches Admin's Services that way. cli 1.0.0-beta.125
7
+ * carries neither.
8
+ */
9
+ export const MINIMUM_ASTRALE_CLI_VERSION = '1.0.0-beta.126';
10
+ export async function requireCliVersion(input) {
11
+ const result = await runCliProcess({
12
+ executable: input.executable,
13
+ projectDir: input.projectDir,
14
+ args: ['--version'],
15
+ signal: input.signal,
16
+ timeoutMs: 10_000,
17
+ stdoutLimit: 256,
18
+ stderrLimit: 4_096,
19
+ });
20
+ if (!result.ok)
21
+ throw new CliProcessError('command', 'version', result.failure);
22
+ const version = result.stdout.trim().replace(/^v/u, '');
23
+ if (!isCompatible(version)) {
24
+ throw new TypeError(`Astrale CLI ${version || '<invalid>'} is incompatible; ${MINIMUM_ASTRALE_CLI_VERSION} or newer is required.`);
25
+ }
26
+ return version;
27
+ }
28
+ function isCompatible(input) {
29
+ const value = semver(input);
30
+ const minimum = semver(MINIMUM_ASTRALE_CLI_VERSION);
31
+ if (value === undefined)
32
+ return false;
33
+ for (let index = 0; index < 3; index += 1) {
34
+ if (value.core[index] > minimum.core[index])
35
+ return true;
36
+ if (value.core[index] < minimum.core[index])
37
+ return false;
38
+ }
39
+ if (value.prerelease === undefined)
40
+ return true;
41
+ if (minimum.prerelease === undefined)
42
+ return false;
43
+ if (value.prerelease.name !== minimum.prerelease.name) {
44
+ return value.prerelease.name.localeCompare(minimum.prerelease.name) > 0;
45
+ }
46
+ return value.prerelease.number >= minimum.prerelease.number;
47
+ }
48
+ function semver(input) {
49
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:-([a-z]+)\.(\d+))?$/u.exec(input);
50
+ if (match === null)
51
+ return undefined;
52
+ return {
53
+ core: [Number(match[1]), Number(match[2]), Number(match[3])],
54
+ ...(match[4] === undefined ? {} : { prerelease: { name: match[4], number: Number(match[5]) } }),
55
+ };
56
+ }
@@ -0,0 +1,6 @@
1
+ export type PublicResponseDiagnostic = Readonly<{
2
+ code: number;
3
+ message?: string;
4
+ }>;
5
+ /** Admit only the CLI's bounded, caller-safe public response projection. */
6
+ export declare function publicResponseDiagnostic(input: Readonly<Record<string, unknown>> | undefined): PublicResponseDiagnostic | undefined;
@@ -0,0 +1,28 @@
1
+ const MAXIMUM_RESPONSE_MESSAGE_LENGTH = 1_024;
2
+ /** Admit only the CLI's bounded, caller-safe public response projection. */
3
+ export function publicResponseDiagnostic(input) {
4
+ if (input?.error !== 'RESPONSE_ERROR' || !publicResponseCode(input.code))
5
+ return undefined;
6
+ return Object.freeze({
7
+ code: input.code,
8
+ ...(publicResponseMessage(input.message) ? { message: input.message } : {}),
9
+ });
10
+ }
11
+ function publicResponseCode(input) {
12
+ return Number.isSafeInteger(input) && input >= 1_000 && input <= 9_999;
13
+ }
14
+ function publicResponseMessage(input) {
15
+ if (typeof input !== 'string' ||
16
+ input.length === 0 ||
17
+ input.length > MAXIMUM_RESPONSE_MESSAGE_LENGTH ||
18
+ input.trim() !== input ||
19
+ input.normalize('NFC') !== input) {
20
+ return false;
21
+ }
22
+ for (const character of input) {
23
+ const point = character.codePointAt(0);
24
+ if (point <= 0x1f || point === 0x7f)
25
+ return false;
26
+ }
27
+ return true;
28
+ }
@@ -0,0 +1,7 @@
1
+ export type CliProcessFailureKind = 'cancelled' | 'timeout' | 'output-limit' | 'spawn' | 'protocol' | 'command';
2
+ export declare class CliProcessError extends Error {
3
+ readonly kind: CliProcessFailureKind;
4
+ readonly command: string;
5
+ readonly diagnostic?: Readonly<Record<string, unknown>> | undefined;
6
+ constructor(kind: CliProcessFailureKind, command: string, diagnostic?: Readonly<Record<string, unknown>> | undefined, options?: ErrorOptions);
7
+ }
@@ -0,0 +1,29 @@
1
+ import { publicResponseDiagnostic } from './diagnostic.js';
2
+ export class CliProcessError extends Error {
3
+ kind;
4
+ command;
5
+ diagnostic;
6
+ constructor(kind, command, diagnostic, options) {
7
+ const code = diagnosticCode(diagnostic);
8
+ const message = publicResponseDiagnostic(diagnostic)?.message;
9
+ super(`Astrale CLI ${command} failed: ${kind}${code}.` +
10
+ (message === undefined ? '' : ` ${message}`), options);
11
+ this.kind = kind;
12
+ this.command = command;
13
+ this.diagnostic = diagnostic;
14
+ this.name = 'CliProcessError';
15
+ }
16
+ }
17
+ function diagnosticCode(diagnostic) {
18
+ const error = safeCode(diagnostic?.error);
19
+ const responseCode = publicResponseDiagnostic(diagnostic)?.code;
20
+ const reason = diagnostic?.reason;
21
+ const reasonCode = reason !== null && typeof reason === 'object' && !Array.isArray(reason)
22
+ ? safeCode(reason.code)
23
+ : undefined;
24
+ const value = [error, responseCode, reasonCode].filter((part) => part !== undefined).join('/');
25
+ return value.length === 0 ? '' : ` (${value})`;
26
+ }
27
+ function safeCode(value) {
28
+ return typeof value === 'string' && /^[A-Z][A-Z0-9_]{0,127}$/u.test(value) ? value : undefined;
29
+ }
@@ -0,0 +1,2 @@
1
+ /** Resolve the exact CLI executable once so a session cannot drift with PATH. */
2
+ export declare function resolveCliExecutable(input?: string): Promise<string>;
@@ -0,0 +1,54 @@
1
+ import { constants } from 'node:fs';
2
+ import { access, readFile, realpath } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { delimiter, isAbsolute, join } from 'node:path';
5
+ /** Resolve the exact CLI executable once so a session cannot drift with PATH. */
6
+ export async function resolveCliExecutable(input) {
7
+ const override = input === undefined ? process.env.ASTRALE_BIN : undefined;
8
+ if (override !== undefined && !isAbsolute(override)) {
9
+ throw new TypeError('ASTRALE_BIN must name an absolute executable path.');
10
+ }
11
+ input ??= override ?? 'astrale';
12
+ const candidates = isAbsolute(input) ? [input] : await executableCandidates(input);
13
+ for (const candidate of candidates) {
14
+ try {
15
+ await access(candidate, constants.X_OK);
16
+ return await realpath(candidate);
17
+ }
18
+ catch {
19
+ // Continue through the bounded PATH candidate set.
20
+ }
21
+ }
22
+ throw new TypeError(override === undefined
23
+ ? 'Astrale CLI is unavailable. Install it with the official Astrale installer.'
24
+ : 'The Astrale CLI configured by ASTRALE_BIN is unavailable or not executable.');
25
+ }
26
+ async function executableCandidates(input) {
27
+ const path = (process.env.PATH ?? '')
28
+ .split(delimiter)
29
+ .filter(Boolean)
30
+ .map((directory) => join(directory, input));
31
+ if (input !== 'astrale')
32
+ return path;
33
+ const installed = await recordedInstallation();
34
+ return installed === undefined ? path : [installed, ...path];
35
+ }
36
+ async function recordedInstallation() {
37
+ const home = process.env.ASTRALE_HOME ?? join(homedir(), '.astrale');
38
+ try {
39
+ const decoded = JSON.parse(await readFile(join(home, 'install.json'), 'utf8'));
40
+ if (typeof decoded !== 'object' ||
41
+ decoded === null ||
42
+ !('method' in decoded) ||
43
+ decoded.method !== 'script' ||
44
+ !('bin' in decoded) ||
45
+ typeof decoded.bin !== 'string' ||
46
+ !isAbsolute(decoded.bin)) {
47
+ return undefined;
48
+ }
49
+ return decoded.bin;
50
+ }
51
+ catch {
52
+ return undefined;
53
+ }
54
+ }
@@ -0,0 +1,5 @@
1
+ export declare function identityArguments(identity: string | undefined): readonly string[];
2
+ export declare function authorityArguments(input: {
3
+ readonly identity?: string;
4
+ readonly credential?: string;
5
+ }): readonly string[];
@@ -0,0 +1,11 @@
1
+ export function identityArguments(identity) {
2
+ return identity === undefined ? [] : ['--as', identity];
3
+ }
4
+ export function authorityArguments(input) {
5
+ if (input.identity !== undefined && input.credential !== undefined) {
6
+ throw new TypeError('Astrale authority cannot combine an identity and a credential.');
7
+ }
8
+ return input.credential === undefined
9
+ ? identityArguments(input.identity)
10
+ : Object.freeze(['--creds', input.credential]);
11
+ }
@@ -0,0 +1,2 @@
1
+ export declare function decodeJson(input: string, label: string): unknown;
2
+ export declare function decodeFailure(input: string): Readonly<Record<string, unknown>>;
@@ -0,0 +1,39 @@
1
+ import { publicResponseDiagnostic } from './diagnostic.js';
2
+ export function decodeJson(input, label) {
3
+ if (input.trim().length === 0)
4
+ throw new TypeError(`${label} is empty.`);
5
+ try {
6
+ return JSON.parse(input);
7
+ }
8
+ catch (cause) {
9
+ throw new TypeError(`${label} is not one complete JSON value.`, { cause });
10
+ }
11
+ }
12
+ export function decodeFailure(input) {
13
+ const value = decodeJson(input, 'Astrale CLI failure');
14
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
15
+ invalid();
16
+ const record = value;
17
+ if (typeof record.error !== 'string' || record.error.length === 0)
18
+ invalid();
19
+ const response = publicResponseDiagnostic(record);
20
+ const reason = failureReason(record.reason);
21
+ return Object.freeze({
22
+ error: record.error,
23
+ ...response,
24
+ ...(reason === undefined ? {} : { reason }),
25
+ });
26
+ }
27
+ function failureReason(input) {
28
+ if (input === undefined)
29
+ return undefined;
30
+ if (input === null || typeof input !== 'object' || Array.isArray(input))
31
+ return undefined;
32
+ const code = input.code;
33
+ if (typeof code !== 'string' || code.length === 0)
34
+ return undefined;
35
+ return Object.freeze({ code });
36
+ }
37
+ function invalid() {
38
+ throw new TypeError('Astrale CLI failure envelope is invalid.');
39
+ }
@@ -0,0 +1,18 @@
1
+ export interface CliProcessInput {
2
+ readonly executable: string;
3
+ readonly projectDir: string;
4
+ readonly args: readonly string[];
5
+ readonly signal: AbortSignal;
6
+ readonly timeoutMs: number;
7
+ readonly stdin?: string;
8
+ readonly stdoutLimit?: number;
9
+ readonly stderrLimit?: number;
10
+ }
11
+ export type CliProcessResult = {
12
+ readonly ok: true;
13
+ readonly stdout: string;
14
+ } | {
15
+ readonly ok: false;
16
+ readonly failure: Readonly<Record<string, unknown>>;
17
+ };
18
+ export declare function runCliProcess(input: CliProcessInput): Promise<CliProcessResult>;
@@ -0,0 +1,109 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { CliProcessError } from './error.js';
3
+ import { decodeFailure } from './json.js';
4
+ const DEFAULT_LIMIT = 256 * 1024;
5
+ const TERMINATION_GRACE_MS = 1_000;
6
+ export function runCliProcess(input) {
7
+ const command = commandName(input.args);
8
+ if (input.signal.aborted) {
9
+ return Promise.reject(new CliProcessError('cancelled', command));
10
+ }
11
+ if (!Number.isSafeInteger(input.timeoutMs) || input.timeoutMs <= 0) {
12
+ return Promise.reject(new TypeError('Astrale CLI timeout must be a positive integer.'));
13
+ }
14
+ return new Promise((resolve, reject) => {
15
+ let child;
16
+ try {
17
+ child = spawn(input.executable, [...input.args], {
18
+ cwd: input.projectDir,
19
+ stdio: ['pipe', 'pipe', 'pipe'],
20
+ shell: false,
21
+ });
22
+ }
23
+ catch (cause) {
24
+ reject(new CliProcessError('spawn', command, undefined, { cause }));
25
+ return;
26
+ }
27
+ // Chunks are decoded once complete: a chunk can end inside a multi-byte UTF-8 character.
28
+ const stdout = [];
29
+ const stderr = [];
30
+ let stdoutBytes = 0;
31
+ let stderrBytes = 0;
32
+ let settled = false;
33
+ let terminationKind;
34
+ let escalation;
35
+ const timeout = setTimeout(() => terminate('timeout'), input.timeoutMs);
36
+ const abort = () => terminate('cancelled');
37
+ input.signal.addEventListener('abort', abort, { once: true });
38
+ const finish = (handler) => {
39
+ if (settled)
40
+ return;
41
+ settled = true;
42
+ clearTimeout(timeout);
43
+ if (escalation !== undefined)
44
+ clearTimeout(escalation);
45
+ input.signal.removeEventListener('abort', abort);
46
+ handler();
47
+ };
48
+ const fail = (error) => finish(() => reject(error));
49
+ const terminate = (kind) => {
50
+ if (settled || terminationKind !== undefined)
51
+ return;
52
+ terminationKind = kind;
53
+ child.stdin.destroy();
54
+ child.kill('SIGTERM');
55
+ escalation = setTimeout(() => {
56
+ if (child.exitCode === null && child.signalCode === null)
57
+ child.kill('SIGKILL');
58
+ }, TERMINATION_GRACE_MS);
59
+ };
60
+ child.stdout.on('data', (chunk) => {
61
+ stdoutBytes += chunk.byteLength;
62
+ if (stdoutBytes > (input.stdoutLimit ?? DEFAULT_LIMIT))
63
+ terminate('output-limit');
64
+ else
65
+ stdout.push(chunk);
66
+ });
67
+ child.stderr.on('data', (chunk) => {
68
+ stderrBytes += chunk.byteLength;
69
+ if (stderrBytes > (input.stderrLimit ?? DEFAULT_LIMIT))
70
+ terminate('output-limit');
71
+ else
72
+ stderr.push(chunk);
73
+ });
74
+ child.once('error', (cause) => fail(terminationKind === undefined
75
+ ? new CliProcessError('spawn', command, undefined, { cause })
76
+ : new CliProcessError(terminationKind, command, undefined, { cause })));
77
+ child.once('close', (code) => {
78
+ if (settled)
79
+ return;
80
+ if (terminationKind !== undefined) {
81
+ fail(new CliProcessError(terminationKind, command));
82
+ return;
83
+ }
84
+ const out = Buffer.concat(stdout).toString('utf8');
85
+ const error = Buffer.concat(stderr).toString('utf8');
86
+ if (code === 0) {
87
+ finish(() => resolve(Object.freeze({ ok: true, stdout: out })));
88
+ return;
89
+ }
90
+ let failure;
91
+ try {
92
+ failure = decodeFailure(error);
93
+ }
94
+ catch (cause) {
95
+ fail(new CliProcessError('protocol', command, undefined, { cause }));
96
+ return;
97
+ }
98
+ finish(() => resolve(Object.freeze({ ok: false, failure })));
99
+ });
100
+ if (input.stdin === undefined)
101
+ child.stdin.end();
102
+ else
103
+ child.stdin.end(input.stdin);
104
+ });
105
+ }
106
+ function commandName(args) {
107
+ const visible = args.filter((arg) => !arg.startsWith('-')).slice(0, 2);
108
+ return visible.join(' ') || 'version';
109
+ }
@@ -0,0 +1,17 @@
1
+ import type { ConfigureContext } from '@astrale-os/sdk/deployment/adapter';
2
+ import type { WorkerConfigurationV1 } from '@astrale-os/sdk/deployment/worker';
3
+ import type { AstraleParams } from './params.js';
4
+ /**
5
+ * What one deployment of this Environment freezes beside its build, as the Worker configuration
6
+ * Admin's Services hosts: the Workers runtime every generated Worker runs on, the author's
7
+ * variables and the execution settings the generated Worker runs under (defaults resolved, its
8
+ * durable options when the Environment declares them, AM-175) bound as `ASTRALE_SETTINGS`, the
9
+ * names of the Environment's secrets, and what a Domain asks of its host: the record it publishes
10
+ * at `/.well-known/astrale/deployment.json` and a signing key of its own. A deployment on Admin's
11
+ * Services binds no service, no dispatch namespace and no router (AM-174): it reaches its Kernel
12
+ * through its public issuer, so its settings name no router either.
13
+ *
14
+ * Pure: the same parameters and secret names give the same configuration, so the same release
15
+ * gives the same deployment address on every run.
16
+ */
17
+ export declare function configureAstrale(parameters: AstraleParams, context: ConfigureContext): WorkerConfigurationV1;
@@ -0,0 +1,40 @@
1
+ import { encodeWorkerSettings, GENERATED_WORKER_RUNTIME, isAdapterVar, SETTINGS_BINDING, workerSettings, } from '@astrale-os/adapter-cloudflare/build';
2
+ import { WORKER_HOST_BINDINGS, workerConfiguration } from '@astrale-os/sdk/deployment/worker';
3
+ /**
4
+ * What one deployment of this Environment freezes beside its build, as the Worker configuration
5
+ * Admin's Services hosts: the Workers runtime every generated Worker runs on, the author's
6
+ * variables and the execution settings the generated Worker runs under (defaults resolved, its
7
+ * durable options when the Environment declares them, AM-175) bound as `ASTRALE_SETTINGS`, the
8
+ * names of the Environment's secrets, and what a Domain asks of its host: the record it publishes
9
+ * at `/.well-known/astrale/deployment.json` and a signing key of its own. A deployment on Admin's
10
+ * Services binds no service, no dispatch namespace and no router (AM-174): it reaches its Kernel
11
+ * through its public issuer, so its settings name no router either.
12
+ *
13
+ * Pure: the same parameters and secret names give the same configuration, so the same release
14
+ * gives the same deployment address on every run.
15
+ */
16
+ export function configureAstrale(parameters, context) {
17
+ const vars = parameters.vars ?? {};
18
+ const owned = [...Object.keys(vars), ...context.secrets].filter((name) => isAdapterVar(name) || WORKER_HOST_BINDINGS.includes(name));
19
+ if (owned.length > 0) {
20
+ throw new TypeError(`Astrale Environment ${context.environment} binds ${owned.join(', ')}, which the deployment ` +
21
+ 'binds itself; rename the variable or secret.');
22
+ }
23
+ const settings = workerSettings({
24
+ ...(parameters.maximumRequestBytes === undefined
25
+ ? {}
26
+ : { maximumRequestBytes: parameters.maximumRequestBytes }),
27
+ ...(parameters.tokenExchange === undefined ? {} : { tokenExchange: parameters.tokenExchange }),
28
+ ...(parameters.durable === undefined ? {} : { durable: parameters.durable }),
29
+ });
30
+ return workerConfiguration({
31
+ compatibilityDate: GENERATED_WORKER_RUNTIME.compatibilityDate,
32
+ compatibilityFlags: GENERATED_WORKER_RUNTIME.compatibilityFlags,
33
+ vars: { ...vars, [SETTINGS_BINDING]: encodeWorkerSettings({ ...settings, router: false }) },
34
+ secrets: context.secrets,
35
+ record: true,
36
+ signingIdentity: true,
37
+ // An Admin-hosted Domain reaches its Kernel through its public issuer, never a router.
38
+ router: false,
39
+ });
40
+ }
@@ -0,0 +1,30 @@
1
+ import type { Placement, PlacementContext, ReleaseDeployContext, ReleaseDeployResult } from '@astrale-os/sdk/deployment/adapter';
2
+ import type { Release } from '@astrale-os/sdk/deployment/release';
3
+ import type { AstraleParams } from '../params.js';
4
+ import type { ServicesDependencies } from '../services/client.js';
5
+ /** The effects this adapter has, replaceable in tests. */
6
+ export interface AstraleDependencies extends ServicesDependencies {
7
+ /** Wait until the deployment serves its sealed release at its URL. */
8
+ readonly waitForReadiness: (release: Release, signal: AbortSignal) => Promise<void>;
9
+ }
10
+ /**
11
+ * Where Admin's Services places this Environment's deployments: under the routing domain its
12
+ * `hosting` answers, on the opaque line that names the Service of the Domain's origin and the
13
+ * Environment. The readable form is the platform organisation's, whose Domains deploy into the
14
+ * platform namespace instead (D12). Reading `hosting` changes nothing at the host.
15
+ */
16
+ export declare function placeAstrale(parameters: AstraleParams, context: PlacementContext, dependencies: AstraleDependencies): Promise<Placement>;
17
+ /**
18
+ * Create, or reuse, the immutable deployment of one sealed release on Admin's Services.
19
+ *
20
+ * One non-durable `CloudflareService.deploy` call carries the release as the Worker deployment
21
+ * Services hosts for any Worker (`WorkerDeploymentRequestV1`): its address, its Worker upload, its
22
+ * configuration, its `DeploymentRecordV1` document, the paths of its release to probe before
23
+ * activation and the Environment's current secrets, which are never journaled. Services creates
24
+ * the Service of the origin and Environment on its first deploy, owned by the caller. A new
25
+ * deployment binds those secrets and a key Services generates for it; a deployment of the same
26
+ * release (same label) is reused and has its own declared secrets rewritten in place when they
27
+ * changed. No other deployment is ever written (AM-4'), and the Service's stable URL then serves
28
+ * this one. The deployment is ready once its own URL serves exactly the sealed release.
29
+ */
30
+ export declare function deployAstraleRelease(parameters: AstraleParams, context: ReleaseDeployContext, dependencies: AstraleDependencies): Promise<ReleaseDeployResult>;
@@ -0,0 +1,168 @@
1
+ import { decodeDeploymentRecord } from '@astrale-os/sdk/deployment/address';
2
+ import { addressing } from '@astrale-os/sdk/deployment/release';
3
+ import { decodeWorkerDeploymentResponse, decodeWorkerHosting, encodeWorkerDeploymentRequest, workerConfigurationDigest, } from '@astrale-os/sdk/deployment/worker';
4
+ import { authorityArguments } from '../cli/identity.js';
5
+ import { SERVICES_METHODS } from '../services/api.js';
6
+ import { requireAstraleCli, servicesSummary } from '../services/client.js';
7
+ import { domainWorkerDeployment } from '../services/request.js';
8
+ /**
9
+ * Where Admin's Services places this Environment's deployments: under the routing domain its
10
+ * `hosting` answers, on the opaque line that names the Service of the Domain's origin and the
11
+ * Environment. The readable form is the platform organisation's, whose Domains deploy into the
12
+ * platform namespace instead (D12). Reading `hosting` changes nothing at the host.
13
+ */
14
+ export async function placeAstrale(parameters, context, dependencies) {
15
+ // `astrale-domain` runs in its Project directory.
16
+ const projectDir = process.cwd();
17
+ const executable = await requireAstraleCli(projectDir, context.signal, dependencies);
18
+ const answer = await dependencies.callAdmin({
19
+ executable,
20
+ projectDir,
21
+ ...(parameters.admin === undefined ? {} : { admin: parameters.admin }),
22
+ path: SERVICES_METHODS.hosting,
23
+ authority: authorityArguments(context.identity === undefined ? {} : { identity: context.identity }),
24
+ data: {},
25
+ signal: context.signal,
26
+ });
27
+ const hosting = decodeWorkerHosting(answer);
28
+ return Object.freeze({ addressing: 'opaque', routingDomain: hosting.routingDomain });
29
+ }
30
+ /**
31
+ * Create, or reuse, the immutable deployment of one sealed release on Admin's Services.
32
+ *
33
+ * One non-durable `CloudflareService.deploy` call carries the release as the Worker deployment
34
+ * Services hosts for any Worker (`WorkerDeploymentRequestV1`): its address, its Worker upload, its
35
+ * configuration, its `DeploymentRecordV1` document, the paths of its release to probe before
36
+ * activation and the Environment's current secrets, which are never journaled. Services creates
37
+ * the Service of the origin and Environment on its first deploy, owned by the caller. A new
38
+ * deployment binds those secrets and a key Services generates for it; a deployment of the same
39
+ * release (same label) is reused and has its own declared secrets rewritten in place when they
40
+ * changed. No other deployment is ever written (AM-4'), and the Service's stable URL then serves
41
+ * this one. The deployment is ready once its own URL serves exactly the sealed release.
42
+ */
43
+ export async function deployAstraleRelease(parameters, context, dependencies) {
44
+ let executable;
45
+ let authority;
46
+ let request;
47
+ try {
48
+ authority = authorityArguments({
49
+ ...(context.credential === undefined ? {} : { credential: context.credential }),
50
+ ...(context.credential !== undefined || context.identity === undefined
51
+ ? {}
52
+ : { identity: context.identity }),
53
+ });
54
+ request = await encodeWorkerDeploymentRequest(domainWorkerDeployment(context));
55
+ // The build Services binds is the release's, at the label the SDK sealed it under.
56
+ if (request.buildDigest !== context.bundle.digest || request.label !== context.label) {
57
+ throw new TypeError('The Worker deployment of the release names another build or label.');
58
+ }
59
+ executable = await requireAstraleCli(context.projectDir, context.signal, dependencies);
60
+ }
61
+ catch (cause) {
62
+ return failed('prerequisite', NONE, cause);
63
+ }
64
+ let answer;
65
+ try {
66
+ answer = await dependencies.callAdmin({
67
+ executable,
68
+ projectDir: context.projectDir,
69
+ ...(parameters.admin === undefined ? {} : { admin: parameters.admin }),
70
+ path: SERVICES_METHODS.deploy,
71
+ authority,
72
+ data: request,
73
+ signal: context.signal,
74
+ });
75
+ }
76
+ catch (cause) {
77
+ // The call may have reached Services before it failed.
78
+ return failed('provider', UNKNOWN, cause);
79
+ }
80
+ let response;
81
+ let record;
82
+ try {
83
+ response = decodeWorkerDeploymentResponse(answer);
84
+ if (response.kind === 'rejected') {
85
+ return failed('provider',
86
+ // A validation or ownership refusal changed nothing. `service-unavailable` waited on, or
87
+ // lost to, another operation on the deployment, possibly after effects: a creation that
88
+ // lost its lease after uploading, or a rewrite in place that wrote part of the values.
89
+ // Rerunning the same deploy converges.
90
+ response.reason === 'service-unavailable' ? UNKNOWN : NONE, new Error(`Admin Services refused the deployment (${response.reason}): ${response.message}` +
91
+ (response.retryAfter === undefined ? '' : ` Retry after ${response.retryAfter}.`)));
92
+ }
93
+ record = expectDeployment(response, context, request);
94
+ }
95
+ catch (cause) {
96
+ return failed('provider', UNKNOWN, cause);
97
+ }
98
+ const applied = Object.freeze({
99
+ kind: 'applied',
100
+ evidence: Object.freeze({ id: response.deployment.id, label: response.deployment.label }),
101
+ });
102
+ try {
103
+ await dependencies.waitForReadiness(context.release, context.signal);
104
+ }
105
+ catch (cause) {
106
+ return failed('readiness', applied, cause);
107
+ }
108
+ return Object.freeze({
109
+ status: 'ready',
110
+ state: response.state,
111
+ record,
112
+ url: response.deployment.url,
113
+ secrets: Object.freeze({ state: response.secrets.state }),
114
+ });
115
+ }
116
+ /**
117
+ * The deployment Services answered with is the one this deploy addressed: its label and URL, active,
118
+ * of this build and configuration, publishing a record that declares exactly the sealed release.
119
+ *
120
+ * The record's commit is not compared. A label is the release (line, build, configuration), never
121
+ * the commit it was built from, and a deployment keeps the record it was created with: Services
122
+ * reuses the deployment of the same release from any commit (an unrelated commit, dirty to clean,
123
+ * a sibling Domain's commit in a monorepo), and resumes a failed creation with its first record.
124
+ * The commit a deployment declares is that of the deploy that created it.
125
+ */
126
+ function expectDeployment(response, context, request) {
127
+ const deployment = servicesSummary(response.deployment);
128
+ const { document } = context.release;
129
+ expect('label', deployment.label, context.label);
130
+ expect('URL', addressing(deployment.url).issuer, context.release.url);
131
+ expect('state', deployment.state, 'active');
132
+ expect('project', deployment.project, document.origin);
133
+ expect('build digest', deployment.buildDigest, context.bundle.digest);
134
+ expect('configuration', deployment.configuration, workerConfigurationDigest(request.configuration));
135
+ let record;
136
+ try {
137
+ if (deployment.record === undefined)
138
+ throw new TypeError('The deployment publishes no record.');
139
+ record = decodeDeploymentRecord(deployment.record);
140
+ }
141
+ catch (cause) {
142
+ throw new TypeError('Admin Services returned a deployment record that does not admit.', {
143
+ cause,
144
+ });
145
+ }
146
+ expect('origin', record.origin, document.origin);
147
+ expect('environment', record.environment, context.environment);
148
+ expect('release digest', record.releaseDigest, document.digest);
149
+ expect('build digest', record.buildDigest, context.bundle.digest);
150
+ expect('Schema revision', record.schemaRevision, document.schema.revision);
151
+ expect('provider script', record.providerScript, context.label);
152
+ return record;
153
+ }
154
+ const NONE = Object.freeze({ kind: 'none' });
155
+ const UNKNOWN = Object.freeze({ kind: 'unknown' });
156
+ function failed(phase, provider, cause) {
157
+ return Object.freeze({
158
+ status: 'failed',
159
+ phase,
160
+ provider,
161
+ error: cause instanceof Error ? cause : new Error(String(cause)),
162
+ });
163
+ }
164
+ function expect(member, actual, expected) {
165
+ if (actual !== expected) {
166
+ throw new TypeError(`Admin Services answered with ${member} ${actual}, not ${expected}.`);
167
+ }
168
+ }