The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Neon from "@distilled.cloud/neon"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import * as ProviderLayer from "alchemy/Local/ProviderLayer"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { Stack } from "alchemy/Stack"; |
| 7 | import { Stage } from "alchemy/Stage"; |
| 8 | import { sha256Object } from "alchemy/Util/sha256"; |
| 9 | import * as Data from "effect/Data"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as Schedule from "effect/Schedule"; |
| 12 | import * as Stream from "effect/Stream"; |
| 13 | import { resolveBranchScope, type ResolvedBranchScope } from "./BranchScope.ts"; |
| 14 | import { branchScopeOf, Function, type FunctionAttributes } from "./Function.ts"; |
| 15 | import { buildFunctionArtifact } from "./FunctionArtifact.ts"; |
| 16 | import { functionEnvironment, functionSlug } from "./FunctionConfig.ts"; |
| 17 | import { LocalFunctionProvider } from "./LocalFunctionProvider.ts"; |
| 18 | |
| 19 | export class FunctionDeploymentFailed extends Data.TaggedError("FunctionDeploymentFailed")<{ |
| 20 | slug: string; |
| 21 | deploymentId: number; |
| 22 | status: string; |
| 23 | message?: string; |
| 24 | }> {} |
| 25 | export class FunctionDeploymentNotReady extends Data.TaggedError("FunctionDeploymentNotReady")<{ |
| 26 | slug: string; |
| 27 | deploymentId: number; |
| 28 | }> {} |
| 29 | |
| 30 | export const observeFunction = Effect.fn(function* (scope: ResolvedBranchScope, slug: string) { |
| 31 | let cursor: string | undefined; |
| 32 | const seen = new Set<string>(); |
| 33 | do { |
| 34 | const page = yield* Neon.listProjectBranchFunctions({ |
| 35 | project_id: scope.projectId, |
| 36 | branch_id: scope.branchId, |
| 37 | cursor, |
| 38 | }); |
| 39 | const found = page.functions.find((fn) => fn.slug === slug); |
| 40 | if (found) return found; |
| 41 | cursor = page.pagination?.next; |
| 42 | if (cursor && seen.has(cursor)) |
| 43 | return yield* new FunctionDeploymentFailed({ |
| 44 | slug, |
| 45 | deploymentId: 0, |
| 46 | status: "repeated-pagination-cursor", |
| 47 | message: "Neon Function listing returned a repeated pagination cursor", |
| 48 | }); |
| 49 | if (cursor) seen.add(cursor); |
| 50 | } while (cursor); |
| 51 | return undefined; |
| 52 | }); |
| 53 | |
| 54 | const attributes = ( |
| 55 | scope: ResolvedBranchScope, |
| 56 | fn: Neon.NeonFunction, |
| 57 | codeHash?: string, |
| 58 | environmentHash?: string, |
| 59 | ): FunctionAttributes => ({ |
| 60 | ...scope, |
| 61 | functionId: fn.id, |
| 62 | slug: fn.slug, |
| 63 | name: fn.name, |
| 64 | url: fn.invocation_url, |
| 65 | currentDeploymentId: fn.current_deployment?.id, |
| 66 | activeDeploymentId: fn.active_deployment?.id, |
| 67 | status: fn.current_deployment?.status, |
| 68 | codeHash, |
| 69 | environmentHash, |
| 70 | environment: fn.active_deployment?.environment ?? [], |
| 71 | }); |
| 72 | |
| 73 | export const waitForFunctionDeployment = ( |
| 74 | scope: ResolvedBranchScope, |
| 75 | slug: string, |
| 76 | deploymentId: number, |
| 77 | ) => |
| 78 | Effect.gen(function* () { |
| 79 | const { function: fn } = yield* Neon.getProjectBranchFunction({ |
| 80 | project_id: scope.projectId, |
| 81 | branch_id: scope.branchId, |
| 82 | slug, |
| 83 | }); |
| 84 | if (fn.current_deployment?.id === deploymentId && fn.current_deployment.status === "failed") { |
| 85 | return yield* new FunctionDeploymentFailed({ |
| 86 | slug, |
| 87 | deploymentId, |
| 88 | status: "failed", |
| 89 | message: fn.current_deployment.error ?? "Neon Function deployment failed", |
| 90 | }); |
| 91 | } |
| 92 | if ( |
| 93 | fn.active_deployment?.id !== deploymentId || |
| 94 | fn.active_deployment.status !== "completed" || |
| 95 | !fn.invocation_url.startsWith("https://") |
| 96 | ) { |
| 97 | return yield* new FunctionDeploymentNotReady({ slug, deploymentId }); |
| 98 | } |
| 99 | return fn; |
| 100 | }).pipe( |
| 101 | Effect.retry({ |
| 102 | while: (error) => error._tag === "FunctionDeploymentNotReady", |
| 103 | schedule: Schedule.spaced("5 seconds"), |
| 104 | times: 9, |
| 105 | }), |
| 106 | ); |
| 107 | |
| 108 | export class FunctionLogQueryError extends Data.TaggedError("FunctionLogQueryError")<{ |
| 109 | reason: "invalid-limit" | "invalid-cursor" | "pagination-limit"; |
| 110 | }> {} |
| 111 | |
| 112 | export const FunctionLogs = Effect.fn(function* ( |
| 113 | output: FunctionAttributes, |
| 114 | options: Provider.LogsInput, |
| 115 | ) { |
| 116 | const limit = options.limit ?? 100; |
| 117 | if (!Number.isInteger(limit) || limit < 1 || limit > 8000) |
| 118 | return yield* new FunctionLogQueryError({ reason: "invalid-limit" }); |
| 119 | // https://neon.com/docs/introduction/monitor-logs documents this service identity. |
| 120 | const service = `neon-function/${output.slug}`; |
| 121 | const query = yield* Effect.sync(() => ({ |
| 122 | project_id: output.projectId, |
| 123 | branch_id: output.branchId, |
| 124 | source: "function" as const, |
| 125 | service_name: service, |
| 126 | ...(options.since ? { start_time: options.since.toISOString() } : { since: "1h" }), |
| 127 | end_time: new Date().toISOString(), |
| 128 | limit: Math.min(limit, 1000), |
| 129 | sort_order: "desc" as const, |
| 130 | })); |
| 131 | const records: Neon.ProjectBranchLogRecord[] = []; |
| 132 | const cursors = new Set<string>(); |
| 133 | let cursor: string | undefined; |
| 134 | for (let page = 0; page < 8; page++) { |
| 135 | const response = yield* Neon.queryProjectBranchLogs({ ...query, cursor }); |
| 136 | records.push( |
| 137 | ...response.logs.filter( |
| 138 | (line) => line.source === "function" && line.service_name === service, |
| 139 | ), |
| 140 | ); |
| 141 | if (records.length >= limit || !response.is_truncated) |
| 142 | return yield* Effect.sync(() => |
| 143 | records |
| 144 | .slice(0, limit) |
| 145 | .reverse() |
| 146 | .map((line) => ({ |
| 147 | timestamp: new Date(line.timestamp), |
| 148 | message: line.message, |
| 149 | })), |
| 150 | ); |
| 151 | cursor = response.next_cursor; |
| 152 | if (!cursor || cursors.has(cursor)) |
| 153 | return yield* new FunctionLogQueryError({ reason: "invalid-cursor" }); |
| 154 | cursors.add(cursor); |
| 155 | } |
| 156 | return yield* new FunctionLogQueryError({ reason: "pagination-limit" }); |
| 157 | }, Effect.timeout("45 seconds")); |
| 158 | |
| 159 | export const FunctionProvider = () => |
| 160 | ProviderLayer.dual(Function, { |
| 161 | live: FunctionProviderLive, |
| 162 | local: LocalFunctionProvider, |
| 163 | }); |
| 164 | |
| 165 | export const FunctionProviderLive = () => |
| 166 | Provider.succeed(Function, { |
| 167 | stables: ["projectId", "branchId", "functionId", "slug", "url"], |
| 168 | list: Effect.fn(function* () { |
| 169 | const result: FunctionAttributes[] = []; |
| 170 | for (const project of yield* Neon.listProjects.items({}).pipe(Stream.runCollect)) { |
| 171 | for (const branch of yield* Neon.listProjectBranches |
| 172 | .items({ project_id: project.id }) |
| 173 | .pipe(Stream.runCollect)) { |
| 174 | const scope = { projectId: project.id, branchId: branch.id }; |
| 175 | for (const fn of yield* Neon.listProjectBranchFunctions |
| 176 | .items({ project_id: project.id, branch_id: branch.id }) |
| 177 | .pipe(Stream.runCollect)) |
| 178 | result.push(attributes(scope, fn)); |
| 179 | } |
| 180 | } |
| 181 | return result; |
| 182 | }), |
| 183 | diff: Effect.fn(function* ({ id, news, output }) { |
| 184 | if (!isResolved(news)) return; |
| 185 | const scope = yield* resolveBranchScope(branchScopeOf(news)); |
| 186 | if ( |
| 187 | output && |
| 188 | (scope.projectId !== output.projectId || |
| 189 | scope.branchId !== output.branchId || |
| 190 | (news.slug !== undefined && news.slug !== output.slug)) |
| 191 | ) |
| 192 | return { action: "replace" }; |
| 193 | yield* functionSlug(id, news.slug); |
| 194 | const artifact = yield* buildFunctionArtifact(news); |
| 195 | if (artifact.codeHash !== output?.codeHash) return { action: "update" }; |
| 196 | }), |
| 197 | read: Effect.fn(function* ({ id, olds, output }) { |
| 198 | if ( |
| 199 | !output && |
| 200 | !(olds && branchScopeOf(olds).branch?.projectId && branchScopeOf(olds).branch?.branchId) && |
| 201 | !(olds && branchScopeOf(olds).project?.projectId) |
| 202 | ) |
| 203 | return undefined; |
| 204 | const scope = output ?? (yield* resolveBranchScope(branchScopeOf(olds!))); |
| 205 | const slug = output?.slug ?? (yield* functionSlug(id, olds?.slug)); |
| 206 | const found = yield* observeFunction(scope, slug); |
| 207 | if (!found) return undefined; |
| 208 | const attrs = attributes( |
| 209 | scope, |
| 210 | found, |
| 211 | output?.activeDeploymentId === found.active_deployment?.id ? output?.codeHash : undefined, |
| 212 | output?.activeDeploymentId === found.active_deployment?.id |
| 213 | ? output?.environmentHash |
| 214 | : undefined, |
| 215 | ); |
| 216 | return output ? attrs : Unowned(attrs); |
| 217 | }), |
| 218 | reconcile: Effect.fn(function* ({ id, news, output, bindings }) { |
| 219 | const scope = yield* resolveBranchScope(branchScopeOf(news)); |
| 220 | const slug = news.slug ?? output?.slug ?? (yield* functionSlug(id)); |
| 221 | yield* functionSlug(id, slug); |
| 222 | const observed = yield* observeFunction(scope, slug); |
| 223 | const artifact = yield* buildFunctionArtifact(news); |
| 224 | const env = yield* functionEnvironment(news, bindings); |
| 225 | const stack = yield* Stack; |
| 226 | const stage = yield* Stage; |
| 227 | const managed = { |
| 228 | ...env, |
| 229 | ALCHEMY_STACK_NAME: stack.name, |
| 230 | ALCHEMY_STAGE: stage, |
| 231 | ALCHEMY_PHASE: "runtime", |
| 232 | }; |
| 233 | const environment = { |
| 234 | ...Object.fromEntries( |
| 235 | (observed?.active_deployment?.environment ?? []) |
| 236 | .filter((key) => !(key in managed)) |
| 237 | .map((key) => [key, ""]), |
| 238 | ), |
| 239 | ...managed, |
| 240 | }; |
| 241 | const unchangedCode = |
| 242 | observed !== undefined && |
| 243 | output?.activeDeploymentId === observed.active_deployment?.id && |
| 244 | output?.codeHash === artifact.codeHash; |
| 245 | const environmentHash = yield* sha256Object(managed); |
| 246 | const unchangedEnvironment = |
| 247 | output?.activeDeploymentId === observed?.active_deployment?.id && |
| 248 | output?.environmentHash === environmentHash; |
| 249 | let current = observed; |
| 250 | if (!current || !unchangedCode || !unchangedEnvironment) { |
| 251 | const zip = unchangedCode |
| 252 | ? undefined |
| 253 | : yield* Effect.sync( |
| 254 | () => |
| 255 | new File([new Uint8Array(artifact.archive)], "function.zip", { |
| 256 | type: "application/zip", |
| 257 | }), |
| 258 | ); |
| 259 | const deployment = yield* Neon.createProjectBranchFunctionDeployment({ |
| 260 | project_id: scope.projectId, |
| 261 | branch_id: scope.branchId, |
| 262 | slug, |
| 263 | runtime: "nodejs24", |
| 264 | zip, |
| 265 | environment: JSON.stringify(environment), |
| 266 | }); |
| 267 | current = yield* waitForFunctionDeployment(scope, slug, deployment.deployment.id); |
| 268 | } |
| 269 | if (current.name !== (news.name ?? slug)) { |
| 270 | const updated = yield* Neon.updateProjectBranchFunction({ |
| 271 | project_id: scope.projectId, |
| 272 | branch_id: scope.branchId, |
| 273 | slug, |
| 274 | name: news.name ?? null, |
| 275 | }); |
| 276 | current = updated.function; |
| 277 | } |
| 278 | return attributes(scope, current, artifact.codeHash, environmentHash); |
| 279 | }), |
| 280 | delete: Effect.fn(function* ({ output }) { |
| 281 | if (!(yield* observeFunction(output, output.slug))) return; |
| 282 | yield* Neon.deleteProjectBranchFunction({ |
| 283 | project_id: output.projectId, |
| 284 | branch_id: output.branchId, |
| 285 | slug: output.slug, |
| 286 | }).pipe(Effect.catchTag("NotFound", () => Effect.void)); |
| 287 | }), |
| 288 | logs: ({ output, options }) => FunctionLogs(output, options), |
| 289 | tail: ({ output }) => |
| 290 | Stream.unwrap( |
| 291 | Effect.sync(() => { |
| 292 | const seen = new Set<string>(); |
| 293 | return Stream.fromEffectSchedule( |
| 294 | FunctionLogs(output, { limit: 1000 }), |
| 295 | Schedule.spaced("3 seconds"), |
| 296 | ).pipe( |
| 297 | Stream.flatMap((lines) => Stream.fromIterable(lines)), |
| 298 | Stream.filter((line) => { |
| 299 | const key = `${line.timestamp.toISOString()}\0${line.message}`; |
| 300 | if (seen.has(key)) return false; |
| 301 | seen.add(key); |
| 302 | if (seen.size > 1000) seen.delete(seen.values().next().value!); |
| 303 | return true; |
| 304 | }), |
| 305 | ); |
| 306 | }), |
| 307 | ), |
| 308 | }); |