The best way to control Claude Code, Codex and more from any computer or phone

main
ts 138 lines 5.4 KB
Raw
1 /**
2 * Shared core of the generated process bootstraps (ECS, App Runner, Batch,
3 * EC2, Cloudflare Containers, MicroVM, Docker, Fly, Hetzner, Prisma).
4 *
5 * Each bundler used to emit its bootstrap as an inline TypeScript string —
6 * a virtual module with no location on disk, whose imports mixed alchemy's
7 * own dependencies (`@distilled.cloud/*`, `@effect/platform-*`) with the
8 * consumer's (`alchemy`, `effect`). No directory can resolve both under an
9 * isolated install (bun `--linker=isolated`, pnpm), so the imports were
10 * left external and the process died at boot with `Cannot find module`.
11 *
12 * Now the generated entry is a three-line shim that imports ONLY
13 * the provider's `Bootstrap` module (e.g. `@alchemy.run/aws/Bootstrap/Ecs`,
14 * resolvable from any consumer — the provider is its direct dependency) plus
15 * the user's `main`. Everything
16 * alchemy needs lives in these real modules, whose imports resolve by the
17 * ordinary rule: from the file that wrote them.
18 *
19 * The helpers here are the pieces every platform module composes; the
20 * layer ORDER (which service is provided to which) is platform-specific and
21 * stays in each module.
22 */
23 import * as Config from "effect/Config";
24 import * as Context from "effect/Context";
25 import * as Effect from "effect/Effect";
26 import * as Layer from "effect/Layer";
27 import { makeEntrypointLayer } from "../Runtime.ts";
28 import { Self } from "../Self.ts";
29 import { Stack } from "../Stack.ts";
30 import { Stage } from "../Stage.ts";
31 import { provideProcessTelemetry } from "../Telemetry.ts";
32 import { withManagedHttpShutdown } from "./ManagedHttpShutdown.ts";
33
34 /**
35 * The tag every bundled platform program registers itself under
36 * (`Self`'s key). Typed loosely on purpose: the shape is the platform
37 * instance, which differs per platform and is only ever read dynamically.
38 */
39 // oxlint-disable-next-line effecttsgo/service-not-as-class
40 export const entrypointTag = Context.Service<any, any>(Self.key);
41
42 /**
43 * Normalize the entrypoint export into the layer providing
44 * {@link entrypointTag}: an inline-effect class default export is an Effect
45 * resolving the platform instance, while the tagged form
46 * (`X.make(props, impl)`) exports a Layer providing the `Self` tag.
47 */
48 export const entrypointLayer = (entrypoint: unknown): Layer.Layer<any> =>
49 makeEntrypointLayer(entrypointTag, entrypoint);
50
51 const stackLayer = (name: string, stage: string): Layer.Layer<Stack | Stage> =>
52 Layer.mergeAll(
53 Layer.succeed(Stack, {
54 name,
55 stage,
56 bindings: {},
57 resources: {},
58 actions: {},
59 }),
60 Layer.succeed(Stage, stage),
61 );
62
63 /** `Stack` and `Stage` from the `ALCHEMY_STACK_NAME` / `ALCHEMY_STAGE` the host injects. */
64 export const stackFromEnv: Layer.Layer<Stack | Stage, Config.ConfigError> = Layer.unwrap(
65 Effect.all([Config.String("ALCHEMY_STACK_NAME"), Config.String("ALCHEMY_STAGE")]).pipe(
66 Effect.map(([name, stage]) => stackLayer(name, stage)),
67 ),
68 );
69
70 /** `Stack` and `Stage` from constants baked in at deploy time. */
71 export const stackConstant = (name: string, stage: string): Layer.Layer<Stack | Stage> =>
72 stackLayer(name, stage);
73
74 /**
75 * Resolve the program the bundled platform registered under `exportKey`
76 * (`program` for the server/one-shot hosts, `default` for containers,
77 * `handler` for Lambda), optionally under process-lifetime telemetry: built
78 * once into the root scope; exporters batch on their intervals and flush
79 * when the scope closes on graceful shutdown.
80 */
81 export const resolveProgram = (
82 exportKey: string,
83 options?: { readonly telemetry?: boolean },
84 ): Effect.Effect<any, any, any> =>
85 entrypointTag.pipe(
86 Effect.flatMap((self) => {
87 const program: Effect.Effect<any, any, any> = self.RuntimeContext.exports.pipe(
88 Effect.flatMap((exports: any) => exports[exportKey]),
89 );
90 return options?.telemetry
91 ? program.pipe(provideProcessTelemetry(self.RuntimeContext))
92 : program;
93 }),
94 );
95
96 /**
97 * Run `program` as the process entry: log the start, exit 1 on failure.
98 * With `exitOnComplete`, exit 0 explicitly once it completes (one-shot jobs
99 * whose host waits on the process, e.g. Batch).
100 */
101 export const runProcess = (
102 label: string,
103 program: Effect.Effect<unknown, unknown>,
104 options?: {
105 readonly exitOnComplete?: boolean;
106 /**
107 * Enable process-wide SIGTERM/SIGINT handling and bounded cleanup for the
108 * managed Fly bootstrap. May force process exit; see {@link withManagedHttpShutdown}.
109 */
110 readonly managedHttpShutdownTimeoutMs?: number;
111 },
112 ): Promise<void> => {
113 console.log(`${label} bootstrap starting...`);
114 // Node 26 exits 13 (unsettled TLA) when the event loop is empty while
115 // `await bootstrap(...)` is still pending. `host.run(Effect.never)` has
116 // no native handle; an HTTP `listen` does. Hold a timer so run-only
117 // Services stay up the same way Bun does.
118 const keepAlive = setInterval(() => undefined, 1 << 30);
119 const managed = options?.managedHttpShutdownTimeoutMs;
120 const execution =
121 managed === undefined
122 ? program.pipe(Effect.as(false))
123 : withManagedHttpShutdown(program, managed);
124 return Effect.runPromise(execution).then(
125 (shutdown) => {
126 clearInterval(keepAlive);
127 if (shutdown || options?.exitOnComplete) {
128 console.log(`${label} completed.`);
129 process.exit(0);
130 }
131 },
132 (err) => {
133 clearInterval(keepAlive);
134 console.error(`${label} bootstrap failed:`, err);
135 process.exit(1);
136 },
137 );
138 };