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

main
ts 334 lines 11.3 KB
Raw
1 import * as Hetzner from "@distilled.cloud/hetzner";
2 import * as Bundle from "alchemy/Bundle/Bundle";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import { Platform, type Main, type PlatformProps } from "alchemy/Platform";
6 import * as Provider from "alchemy/Provider";
7 import { Resource, type ResourceBinding } from "alchemy/Resource";
8 import type { ServerHost } from "alchemy/Runtime/Process";
9 import { Stack } from "alchemy/Stack";
10 import * as Data from "effect/Data";
11 import * as Effect from "effect/Effect";
12 import * as Redacted from "effect/Redacted";
13 import {
14 collectBindingState,
15 createHetznerHostedSupport,
16 createHetznerHostRuntimeContext,
17 type HetznerBuildOptions,
18 type HetznerHostRuntimeContext,
19 } from "./hosted.ts";
20 import type { ServiceBinding } from "./MountVolume.ts";
21 import type { Providers } from "./Providers.ts";
22 import type { Server } from "./Server.ts";
23 import { sshClientForServer } from "./Ssh.ts";
24
25 /**
26 * A resource-valued prop: the resource itself, or an Effect that produces
27 * it (so `yield* Server(...)` and `Server(...)` both type-check).
28 */
29 type Ref<T> = T | Effect.Effect<T, never, Providers>;
30
31 export interface ServiceProps extends PlatformProps {
32 /**
33 * Server this Service runs on. Accepts a `Hetzner.Server` or an Effect
34 * that produces one. Changing the Server replaces the Service.
35 */
36 server: Ref<Server>;
37 /**
38 * Module entrypoint bundled with rolldown and copied onto the Server
39 * over SSH as a systemd unit.
40 */
41 main: string;
42 /**
43 * Port the hosted HTTP server listens on. Written to `PORT` and used
44 * to build {@link Service} `url`.
45 *
46 * @default 3000
47 */
48 port?: number;
49 /**
50 * Named export to load from `main`.
51 *
52 * @default "default"
53 */
54 handler?: string;
55 /**
56 * Additional environment variables for the hosted process. Merged after
57 * binding-injected `env`.
58 */
59 env?: Record<string, any>;
60 /**
61 * Bundler configuration for `main`: rolldown `input`/`output` overrides
62 * plus pure-annotation options (`pure`) and `install` for packages that
63 * must ship as real `node_modules` (see {@link HetznerBuildOptions}).
64 */
65 build?: HetznerBuildOptions;
66 /**
67 * Extra host directories packed into the unit archive next to the
68 * bundled entry (e.g. a website `clientDirectory` at `dist/`). Hashed
69 * into `code.hash` so asset changes update the unit. Destination is
70 * relative to the unit root (`/opt/<unit>/`).
71 */
72 extraFiles?: ReadonlyArray<{
73 source: string;
74 destination: string;
75 }>;
76 }
77
78 export type Service = Resource<
79 "Hetzner.Service",
80 ServiceProps,
81 {
82 /** Numeric Hetzner Server ID the unit runs on. */
83 serverId: number;
84 /** Public IPv4 of the Server, if attached. */
85 ipv4: string | undefined;
86 /** Port the process listens on. */
87 port: number;
88 /** `http://<ipv4>:<port>` when the Server has a public IPv4. */
89 url: string | undefined;
90 /** systemd unit name (`<name>.service`). */
91 unitName: string;
92 /** Content hash of the bundled program. */
93 code: {
94 hash: string;
95 };
96 },
97 ServiceBinding,
98 Providers
99 >;
100
101 export const isService = (value: unknown): value is Service =>
102 typeof value === "object" &&
103 value !== null &&
104 (value as { Type?: string }).Type === "Hetzner.Service";
105
106 export type ServiceServices = ServerHost;
107
108 export type ServiceShape = Main<ServiceServices>;
109
110 export type ServiceRuntimeContext = HetznerHostRuntimeContext;
111
112 /**
113 * An Effect program hosted on a Hetzner Cloud Server as a systemd unit.
114 *
115 * N Services can share one Server. Each Service is bundled with rolldown,
116 * copied over SSH, and restarted as its own unit. Bind
117 * `Hetzner.MountVolume` inside the impl to attach a Volume and mount it
118 * at a path — the same `(volume, server, path)` from two Services is one
119 * attach and one mount.
120 *
121 * @see https://docs.hetzner.cloud/reference/cloud#servers
122 *
123 * ### Hosting a Service
124 * **Example:** HTTP server on a Server
125 * ```typescript
126 * const server = yield* Hetzner.Server("box", {
127 * serverType: "cpx12",
128 * image: "ubuntu-24.04",
129 * location: "nbg1",
130 * });
131 *
132 * export default class Api extends Hetzner.Service<Api>()(
133 * "Api",
134 * { server, main: import.meta.url, port: 3000 },
135 * Effect.gen(function* () {
136 * return {
137 * fetch: Effect.succeed(HttpServerResponse.json({ ok: true })),
138 * };
139 * }),
140 * ) {}
141 * ```
142 *
143 * ### Volumes
144 * **Example:** Mount a Volume
145 * ```typescript
146 * const mount = yield* Hetzner.MountVolume(volume, { path: "/data" });
147 * // write/read files under mount.path inside the hosted process
148 * ```
149 *
150 * @resource
151 * @product Service
152 */
153 export const Service: Platform<Service, ServiceServices, ServiceShape, ServiceRuntimeContext> =
154 Platform("Hetzner.Service", {
155 createRuntimeContext: createHetznerHostRuntimeContext("Hetzner.Service"),
156 // `{ server: Box }` at module scope is an Effect. Yield it here so the
157 // Server is registered and `news.server` is resolved attributes at
158 // reconcile (same DX as `yield* Server(...)` inside Effect.gen).
159 transformProps: (_id, props) =>
160 Effect.gen(function* () {
161 if (globalThis.__ALCHEMY_RUNTIME__) return props;
162 const server = Effect.isEffect(props.server)
163 ? yield* props.server as Effect.Effect<Server, never, Providers>
164 : props.server;
165 return { ...props, server };
166 }),
167 });
168
169 export class ServiceError extends Data.TaggedError("Hetzner.ServiceError")<{
170 message: string;
171 }> {}
172
173 const DEFAULT_PORT = 3000;
174
175 const serverIdOf = (value: unknown): number | undefined => {
176 if (value === null || typeof value !== "object") return undefined;
177 const rec = value as { serverId?: unknown; id?: unknown };
178 if (typeof rec.serverId === "number") return rec.serverId;
179 if (typeof rec.id === "number") return rec.id;
180 return undefined;
181 };
182
183 const ipv4Of = (value: unknown): string | undefined => {
184 if (value === null || typeof value !== "object") return undefined;
185 const rec = value as { ipv4?: unknown };
186 return typeof rec.ipv4 === "string" ? rec.ipv4 : undefined;
187 };
188
189 const unwrapKey = (value: Redacted.Redacted<string> | string | undefined): string | undefined => {
190 if (value === undefined) return undefined;
191 return typeof value === "string" ? value : Redacted.value(value);
192 };
193
194 const privateKeyOf = (value: unknown): string | undefined => {
195 if (value === null || typeof value !== "object") return undefined;
196 return unwrapKey((value as { privateKey?: Redacted.Redacted<string> | string }).privateKey);
197 };
198
199 const createUnitName = (id: string, existing?: string) =>
200 existing !== undefined
201 ? Effect.succeed(existing)
202 : createPhysicalName({
203 id,
204 maxLength: 64,
205 lowercase: true,
206 }).pipe(Effect.map((name) => name.replaceAll(/[^a-z0-9-]/g, "-")));
207
208 const serviceUrl = (ipv4: string | undefined, port: number) =>
209 ipv4 !== undefined ? `http://${ipv4}:${port}` : undefined;
210
211 export const ServiceProvider = () =>
212 Provider.effect(
213 Service,
214 Effect.gen(function* () {
215 const stack = yield* Stack;
216 const virtualEntryPlugin = yield* Bundle.virtualEntryPlugin;
217 const hosted = createHetznerHostedSupport({
218 stackName: stack.name,
219 stage: stack.stage,
220 virtualEntryPlugin,
221 });
222
223 const openSession = (news: ServiceProps) =>
224 sshClientForServer(news.server as Server, {
225 privateKey: privateKeyOf(news.server),
226 });
227
228 return Service.Provider.of({
229 stables: ["serverId", "unitName"],
230 // systemd units have no Hetzner list API. Nuke deletes the
231 // Server they live on; empty list is the documented shape for
232 // parent-keyed resources (Provider.list).
233 nuke: { dependsOn: ["Hetzner.Server"] },
234 list: () => Effect.succeed([]),
235 diff: Effect.fn(function* ({ id, news, output }) {
236 if (!isResolved(news)) return undefined;
237 const nextServer = serverIdOf(news.server);
238 if (output !== undefined && nextServer !== undefined && output.serverId !== nextServer) {
239 return { action: "replace" } as const;
240 }
241 if (output !== undefined && news.main) {
242 const { hash } = yield* hosted.bundleProgram(id, news);
243 if (hash !== output.code.hash) {
244 return { action: "update" } as const;
245 }
246 }
247 return undefined;
248 }),
249 read: Effect.fn(function* ({ olds, output }) {
250 if (output === undefined) return undefined;
251 const serverId =
252 output.serverId ?? (olds !== undefined ? serverIdOf(olds.server) : undefined);
253 if (serverId === undefined) return undefined;
254 const live = yield* Hetzner.servers.getServer({ id: serverId }).pipe(
255 Effect.map(({ server }) => server),
256 Effect.catchTag("NotFound", () => Effect.undefined),
257 );
258 if (live === undefined) return undefined;
259 return {
260 ...output,
261 serverId: live.id,
262 ipv4: live.public_net.ipv4?.ip,
263 url: serviceUrl(live.public_net.ipv4?.ip, output.port),
264 };
265 }),
266 reconcile: Effect.fn(function* ({ id, news, output, bindings }) {
267 const serverId = serverIdOf(news.server);
268 if (serverId === undefined) {
269 return yield* new ServiceError({
270 message: "Service requires a resolved Server",
271 });
272 }
273 const ipv4 = ipv4Of(news.server);
274 if (ipv4 === undefined) {
275 return yield* new ServiceError({
276 message: "Service requires the Server to have a public IPv4",
277 });
278 }
279 const port = news.port ?? DEFAULT_PORT;
280 const unitName = yield* createUnitName(id, output?.unitName);
281 const { env: bindingEnv, volumes } = collectBindingState(
282 bindings as ResourceBinding<ServiceBinding>[],
283 );
284 const env = {
285 ...bindingEnv,
286 ...hosted.alchemyEnv,
287 ...(news.port !== undefined ? { PORT: String(news.port) } : {}),
288 ...news.env,
289 };
290
291 const { archive, hash, entryRel } = yield* hosted.bundleProgram(id, news);
292
293 const ssh = yield* openSession(news);
294 yield* Effect.ensuring(
295 Effect.gen(function* () {
296 yield* hosted.waitForSsh(ssh);
297 // Attach (no automount) then mkdir+mount+fstab. The same
298 // (volume, server, path) from two Services is one attach
299 // and one mount — both steps are independently idempotent.
300 yield* hosted.attachAndMount({
301 ssh,
302 serverId,
303 volumes,
304 });
305 yield* hosted.deployUnit({
306 ssh,
307 unitName,
308 archive,
309 env,
310 entryRel,
311 });
312 }),
313 ssh.close,
314 );
315
316 return {
317 serverId,
318 ipv4,
319 port,
320 url: serviceUrl(ipv4, port),
321 unitName,
322 code: { hash },
323 };
324 }),
325 delete: Effect.fn(function* ({ olds, output }) {
326 const ssh = yield* openSession(olds).pipe(
327 Effect.catchTag("Hetzner.SshError", () => Effect.undefined),
328 );
329 if (ssh === undefined) return;
330 yield* Effect.ensuring(hosted.removeUnit({ ssh, unitName: output.unitName }), ssh.close);
331 }),
332 });
333 }),
334 );