The best way to control Claude Code, Codex and more from any computer or phone
| 1 | /** @effect-diagnostics anyUnknownInErrorContext:off */ |
| 2 | |
| 3 | /** |
| 4 | * The `alchemy dev` provider for `AWS.Lambda.Function`: deploys the function |
| 5 | * into the floci emulator and hot-swaps its code on file change. |
| 6 | * |
| 7 | * Built on the shared dev-watch skeleton |
| 8 | * ([DevWatchProvider](../Local/DevWatchProvider.ts)), which owns the |
| 9 | * RPC-sidecar hosting, the live-provider delegation into the floci override |
| 10 | * context, the instanceId-guarded watch registry, and the never-bundling dev |
| 11 | * diff policy. This file supplies only the Lambda-specific parts: |
| 12 | * |
| 13 | * - **Watch loop** — a forked `Bundle.watch` (same rolldown config the |
| 14 | * deploy used, via [FunctionBundle](./FunctionBundle.ts)) rebuilds on file |
| 15 | * change and uploads the fresh archive to a stable per-function S3 key in |
| 16 | * the emulator's assets bucket. The first swap repoints the function's |
| 17 | * code at that key with `UpdateFunctionCode`, which enrolls floci's |
| 18 | * reactive S3 sync; every later swap is a bare `PutObject` (measured |
| 19 | * 111–138 ms re-extract, warm containers drained, no stale invoke) — |
| 20 | * until an engine reconcile re-points the function at a content-addressed |
| 21 | * key, after which the next swap re-enrolls it (see `enrolledAttrs`). |
| 22 | * `bundle: false` props fs-watch the prebuilt directory instead. |
| 23 | * - **Replacement rules** — functionName and durableConfig-presence changes |
| 24 | * replace, mirroring the live diff. |
| 25 | * - **Precreate pinning** — floci validates the Handler FILE against the |
| 26 | * package at CreateFunction (AWS defers that to first invoke); the 503 |
| 27 | * stub ships a single `index.*` module, so handler-affecting props are |
| 28 | * pinned to the stub's own shape. |
| 29 | */ |
| 30 | |
| 31 | import * as Lambda from "@distilled.cloud/aws/lambda"; |
| 32 | import * as s3 from "@distilled.cloud/aws/s3"; |
| 33 | import * as Bundle from "alchemy/Bundle/Bundle"; |
| 34 | import * as TempRoot from "alchemy/Bundle/TempRoot"; |
| 35 | import * as Effect from "effect/Effect"; |
| 36 | import * as FileSystem from "effect/FileSystem"; |
| 37 | import * as Schedule from "effect/Schedule"; |
| 38 | import * as Stream from "effect/Stream"; |
| 39 | import { Assets, AssetsLive } from "../Assets.ts"; |
| 40 | import { flociProvidersUrl, makeDevWatchProvider } from "../Local/DevWatchProvider.ts"; |
| 41 | import { |
| 42 | Function, |
| 43 | FunctionProvider, |
| 44 | layerVersionArnOf, |
| 45 | type FunctionImageProps, |
| 46 | type FunctionProps, |
| 47 | } from "./Function.ts"; |
| 48 | import { makeFunctionBundler, type FunctionBundleResult } from "./FunctionBundle.ts"; |
| 49 | |
| 50 | const isFunctionImageProps = (props: FunctionProps): props is FunctionImageProps => |
| 51 | props.image !== undefined; |
| 52 | |
| 53 | export const FlociFunctionProvider = () => |
| 54 | makeDevWatchProvider<Function, FunctionProps, Function["Attributes"]>( |
| 55 | Function, |
| 56 | flociProvidersUrl(), |
| 57 | { |
| 58 | liveProvider: () => FunctionProvider(), |
| 59 | // A FRESH `Assets` instance: its cached bucket lookup must resolve |
| 60 | // against the emulator (auto-bootstrapped there) and can never share a |
| 61 | // cache with the live arm's instance. |
| 62 | services: AssetsLive, |
| 63 | // The restart surface of the watch loop: everything that changes WHAT |
| 64 | // the watcher builds or WHERE it uploads. `build` may carry plugin |
| 65 | // closures, which degrade to stable placeholders under canonical |
| 66 | // hashing. |
| 67 | watchConfigOf: (news, attrs) => |
| 68 | isFunctionImageProps(news) |
| 69 | ? { |
| 70 | functionName: attrs.functionName, |
| 71 | image: news.image, |
| 72 | architecture: news.architecture, |
| 73 | } |
| 74 | : { |
| 75 | functionName: attrs.functionName, |
| 76 | main: news.main, |
| 77 | handler: news.handler, |
| 78 | bundle: news.bundle, |
| 79 | isExternal: news.isExternal, |
| 80 | runtime: news.runtime, |
| 81 | architecture: news.architecture, |
| 82 | uploadSourceMap: news.uploadSourceMap, |
| 83 | build: news.build, |
| 84 | }, |
| 85 | // Mirrors the live diff's replacement rules. |
| 86 | replaceOn: ({ olds, news, output }) => |
| 87 | Effect.sync(() => { |
| 88 | const newFunctionName = news.functionName ?? output.functionName; |
| 89 | if (output.functionName !== newFunctionName) { |
| 90 | return { action: "replace" as const }; |
| 91 | } |
| 92 | if (isFunctionImageProps(olds) !== isFunctionImageProps(news)) { |
| 93 | return { |
| 94 | action: "replace" as const, |
| 95 | deleteFirst: news.functionName !== undefined, |
| 96 | }; |
| 97 | } |
| 98 | if ( |
| 99 | !isFunctionImageProps(olds) && |
| 100 | !isFunctionImageProps(news) && |
| 101 | !!olds.durableConfig !== !!news.durableConfig |
| 102 | ) { |
| 103 | return { |
| 104 | action: "replace" as const, |
| 105 | deleteFirst: news.functionName !== undefined, |
| 106 | }; |
| 107 | } |
| 108 | return undefined; |
| 109 | }), |
| 110 | normalizeProps: (props) => |
| 111 | isFunctionImageProps(props) |
| 112 | ? props |
| 113 | : { |
| 114 | ...props, |
| 115 | layers: (props.layers ?? []).map(layerVersionArnOf), |
| 116 | }, |
| 117 | // Floci validates the Handler FILE against the package at |
| 118 | // CreateFunction (AWS defers that to first invoke). The precreate 503 |
| 119 | // stub ships a single `index.*` module, so a `bundle: false` / |
| 120 | // custom-handler props set (`handler.handler`) would be rejected — pin |
| 121 | // the stub's handler-affecting props to the stub's own shape; |
| 122 | // `reconcile` applies the real Handler together with the real package. |
| 123 | transformPrecreateNews: (news) => |
| 124 | isFunctionImageProps(news) |
| 125 | ? news |
| 126 | : { |
| 127 | ...news, |
| 128 | bundle: undefined, |
| 129 | isExternal: undefined, |
| 130 | handler: undefined, |
| 131 | }, |
| 132 | startWatch: (ctx) => |
| 133 | Effect.gen(function* () { |
| 134 | const props = ctx.news; |
| 135 | if (isFunctionImageProps(props)) { |
| 136 | // Image functions are converged by the delegated live provider. |
| 137 | // There is no ZIP module graph to watch or hot-swap. |
| 138 | return; |
| 139 | } |
| 140 | const functionName = ctx.attrs.functionName; |
| 141 | const bundler = yield* makeFunctionBundler; |
| 142 | const assets = yield* Assets; |
| 143 | let lastHash = ctx.attrs.code?.hash ?? ""; |
| 144 | // The attributes object that was current when the watch loop |
| 145 | // last pointed the function at the stable dev key. Every |
| 146 | // engine-driven reconcile (a binding added, an env var changed, |
| 147 | // …) re-uploads the bundle to a content-addressed key and |
| 148 | // re-points the function THERE, silently detaching it from the |
| 149 | // dev key: floci's reactive S3 sync only follows the key the |
| 150 | // function is enrolled at, so every later PutObject would be |
| 151 | // ignored and hot swap would be dead until the next engine |
| 152 | // update. The skeleton hands the watcher a fresh attrs object per |
| 153 | // reconcile, so identity (not the code hash — a source edited |
| 154 | // back to its original content hashes the same) is the signal |
| 155 | // that a re-point happened and the function must be re-enrolled. |
| 156 | let enrolledAttrs: Function["Attributes"] | undefined; |
| 157 | let startedAt = Date.now(); |
| 158 | |
| 159 | const swap = Effect.fn(function* (result: FunctionBundleResult) { |
| 160 | if (result.identityHash === lastHash) return; |
| 161 | const { archive } = yield* result.buildArchive; |
| 162 | const bucket = yield* assets.bucketName; |
| 163 | const key = `lambda/dev/${functionName}.zip`; |
| 164 | yield* s3.putObject({ |
| 165 | Bucket: bucket, |
| 166 | Key: key, |
| 167 | Body: archive, |
| 168 | ContentType: "application/zip", |
| 169 | }); |
| 170 | const current = yield* ctx.currentAttrs; |
| 171 | if (enrolledAttrs !== current) { |
| 172 | // First swap, or the engine re-pointed the function since the |
| 173 | // last one: (re)point its code at the stable dev key — floci's |
| 174 | // reactive S3 sync then re-extracts on every subsequent |
| 175 | // PutObject with no further Lambda API calls. |
| 176 | yield* Lambda.updateFunctionCode({ |
| 177 | FunctionName: functionName, |
| 178 | S3Bucket: bucket, |
| 179 | S3Key: key, |
| 180 | }).pipe( |
| 181 | Effect.retry({ |
| 182 | while: (e): boolean => e._tag === "ResourceConflictException", |
| 183 | schedule: Schedule.exponential(50), |
| 184 | times: 8, |
| 185 | }), |
| 186 | ); |
| 187 | enrolledAttrs = current; |
| 188 | } |
| 189 | lastHash = result.identityHash; |
| 190 | yield* Effect.logInfo(`code swapped in ${Date.now() - startedAt}ms`); |
| 191 | }); |
| 192 | |
| 193 | if (props.bundle === false) { |
| 194 | // Prebuilt directory: no module graph to watch — fs-watch the |
| 195 | // directory and re-zip it as-is (exactly like `prebuiltCode`). |
| 196 | const fs = yield* FileSystem.FileSystem; |
| 197 | const realMain = yield* TempRoot.resolveMainPath(props.main); |
| 198 | const dir = realMain.slice(0, realMain.lastIndexOf("/")); |
| 199 | yield* fs.watch(dir, { recursive: true }).pipe( |
| 200 | Stream.debounce("200 millis"), |
| 201 | Stream.runForEach(() => |
| 202 | Effect.gen(function* () { |
| 203 | startedAt = Date.now(); |
| 204 | const result = yield* bundler.prebuiltCode(realMain); |
| 205 | yield* swap(result); |
| 206 | }).pipe(Effect.catchCause((cause) => Effect.logWarning(`code swap failed`, cause))), |
| 207 | ), |
| 208 | ); |
| 209 | } else { |
| 210 | // The exact rolldown config the deploy used — incremental |
| 211 | // rebuilds produce the identical artifact shape. |
| 212 | const plan = yield* bundler.resolveBundlePlan(props); |
| 213 | yield* Bundle.watch(plan.inputOptions, plan.outputOptions, plan.extra).pipe( |
| 214 | Stream.runForEach((event) => |
| 215 | Effect.gen(function* () { |
| 216 | switch (event._tag) { |
| 217 | case "Start": { |
| 218 | startedAt = Date.now(); |
| 219 | return; |
| 220 | } |
| 221 | case "Error": { |
| 222 | yield* Effect.logWarning(`rebuild failed: ${event.error.message}`); |
| 223 | return; |
| 224 | } |
| 225 | case "Success": { |
| 226 | const result = yield* bundler.finishBundle(plan, event.output); |
| 227 | yield* swap(result); |
| 228 | } |
| 229 | } |
| 230 | }).pipe(Effect.catchCause((cause) => Effect.logWarning(`code swap failed`, cause))), |
| 231 | ), |
| 232 | ); |
| 233 | } |
| 234 | }), |
| 235 | }, |
| 236 | ); |