sdk.ts
This file
Path
apps/sandbox/src/checker/sdk.ts
262 lines · 7.9 KiB · TypeScript
Last changed by
Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263// The catch-all intercept takes every host registered after it, so the job's// `@proxy` hosts are reserved when the layer is built. Registering a target// again replaces its handler in place. Intercepts last one container, so a// restore registers them again.import { Context, Effect, Layer, Option, Predicate, Redacted, Ref,} from "effect";
import { BoxFailed } from "../box.ts";import type { EnvGatewayProps } from "../env-gateway.ts";import type { CloneProps, EgressProps } from "../outbound.ts";import { Network } from "./network.ts";import type { CloneRoute, EnvRoute } from "./network.ts";import { Snapshots } from "./snapshots.ts";
export interface Gateways { readonly CloneGateway: (options: { readonly props: CloneProps }) => Fetcher; readonly EgressGateway: (options: { readonly props: EgressProps }) => Fetcher; readonly EnvGateway: (options: { readonly props: EnvGatewayProps; }) => Fetcher;}
export const hasGateways = ( exports: Cloudflare.Exports): exports is Cloudflare.Exports & Gateways => Predicate.hasProperty(exports, "CloneGateway") && Predicate.isFunction(exports.CloneGateway) && Predicate.hasProperty(exports, "EgressGateway") && Predicate.isFunction(exports.EgressGateway) && Predicate.hasProperty(exports, "EnvGateway") && Predicate.isFunction(exports.EnvGateway);
export interface SnapshotIndex { readonly find: (key: string) => Promise<string | null>; readonly keep: (key: string, id: string) => Promise<void>; readonly forget: (key: string) => Promise<void>;}
interface Routes { readonly clone: Option.Option<CloneRoute>; readonly allow: readonly string[]; readonly cloned: boolean; readonly proxied: readonly string[]; readonly env: Option.Option<EnvRoute>;}
const SNAPSHOT_NAME = "check-setup";
const IDLE = ["sleep", "infinity"];
const failed = (reason: string) => (cause: unknown) => new BoxFailed({ operation: "exec", reason: `${reason}: ${String(cause)}` });
/** A failed registration is a defect: the network would not be what the job needs. */const intercept = (register: () => Promise<void>) => Effect.promise(register);
/** The values leave their redaction only here, on the Worker's side. */const envProps = ({ rules, values }: EnvRoute): EnvGatewayProps => ({ rules, values: values.map(({ key, placeholder, value }) => ({ key, placeholder, value: Redacted.value(value), })),});
interface Opened { readonly hosts: readonly string[]; readonly to: Fetcher;}
/** Registration order matters: named hosts before the catch-all. */const install = ( container: Container, gateways: Gateways, { allow, clone, cloned, env, proxied }: Routes) => Effect.gen(function* () { const egress = gateways.EgressGateway({ props: { allow } });
if (Option.isSome(clone)) { const route = clone.value;
yield* intercept(() => container.interceptOutboundHttps( route.host, cloned ? egress : gateways.CloneGateway({ props: { remote: route.remote, token: Redacted.value(route.token), }, }) ) ); }
const opened = Option.match(env, { onNone: (): Opened => ({ hosts: [], to: egress }), onSome: (route): Opened => ({ hosts: route.hosts, to: gateways.EnvGateway({ props: envProps(route) }), }), });
yield* Effect.forEach( [...new Set([...proxied, ...opened.hosts])], (host) => intercept(() => container.interceptOutboundHttps( host, opened.hosts.includes(host) ? opened.to : egress ) ), { discard: true } );
yield* intercept(() => container.interceptOutboundHttps("*", egress)); yield* intercept(() => container.interceptAllOutboundHttp(egress)); });
const probe = (container: Container) => Effect.tryPromise({ catch: failed("the restored container did not answer"), try: () => container.exec(["true"]), }).pipe( Effect.flatMap((process) => Effect.tryPromise({ catch: failed("the restored container did not answer"), try: () => process.output(), }) ), Effect.filterOrFail( ({ exitCode }) => exitCode === 0, ({ exitCode }) => new BoxFailed({ operation: "exec", reason: `the restored container's probe exited ${exitCode}`, }) ) );
export interface CheckerStart { /** A host first registered after the catch-all would never be reached. */ readonly proxied: readonly string[]; readonly instance: NonNullable<ContainerStartupOptions["instance"]>;}
export const SdkChecker = { layer: ( container: Container, gateways: Gateways, index: SnapshotIndex, { instance, proxied }: CheckerStart ): Layer.Layer<Network | Snapshots> => Layer.effectContext( Effect.gen(function* () { const routes = yield* Ref.make<Routes>({ allow: [], clone: Option.none(), cloned: false, env: Option.none(), proxied, });
const reinstall = (change: (now: Routes) => Routes) => Effect.flatMap(Ref.updateAndGet(routes, change), (now) => install(container, gateways, now) );
const network = Network.of({ allow: (hosts) => reinstall((now) => ({ ...now, allow: [...hosts], cloned: true })), routeClone: (route) => reinstall((now) => ({ ...now, clone: Option.some(route) })), routeEnv: (route) => Effect.andThen( Effect.forEach( route.hosts.filter((host) => !proxied.includes(host)), (host) => Effect.logWarning( "a proxy host was not reserved: the catch-all takes its requests" ).pipe(Effect.annotateLogs({ host })), { discard: true } ), reinstall((now) => ({ ...now, env: Option.some(route) })) ), });
const restoreFrom = (key: string, id: string) => Effect.gen(function* () { yield* Effect.tryPromise({ catch: failed("the container did not stop for a restore"), try: () => container.destroy(), });
yield* Effect.try({ catch: failed("the snapshot did not start"), try: () => { container.start({ containerSnapshot: { id }, enableInternet: false, entrypoint: IDLE, instance, }); }, });
yield* reinstall((now) => now); yield* probe(container); }).pipe( // A snapshot that will not come back is dropped, so the next // check runs setup instead. Effect.tapError(() => Effect.ignore(Effect.tryPromise(() => index.forget(key))) ) );
const snapshots = Snapshots.of({ restore: (key) => Effect.gen(function* () { const id = yield* Effect.tryPromise({ catch: failed("the snapshot index did not answer"), try: () => index.find(key), });
if (id === null) { return false; }
yield* restoreFrom(key, id);
return true; }), save: (key) => Effect.tryPromise({ catch: failed("the snapshot was not taken"), try: () => container.snapshotContainer({ name: SNAPSHOT_NAME }), }).pipe( Effect.flatMap(({ id }) => Effect.tryPromise({ catch: failed("the snapshot index did not keep it"), try: () => index.keep(key, id), }) ) ), });
return Context.make(Network, network).pipe( Context.add(Snapshots, snapshots) ); }) ),};