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

main
ts 108 lines 4.5 KB
Raw
1 import type { Function as LambdaFunction } from "@alchemy.run/aws/Lambda/Function";
2 import { InvokeFunction } from "@alchemy.run/aws/Lambda/InvokeFunction";
3 /**
4 * `Hasher` over an AWS Lambda (DESIGN §22.11). Each chunk is one
5 * `InvokeFunction` call — a JSON payload with the chunk in base64 — signed
6 * from the Worker with the cross-cloud identity `AWS.Lambda.InvokeFunctionHttp`
7 * provisions for a Worker host (an IAM user, key and assume-role Role,
8 * once per Worker). Chunks are 4 MiB (the 6 MB invoke limit) and the pump
9 * writes the spill parts itself (`writesSpill: false`). Any failure on the
10 * Lambda side — throttling, a cold-start timeout, an oversize response —
11 * falls back to hashing that chunk inline, so a push never fails because
12 * the hasher did.
13 */
14 import * as Effect from "effect/Effect";
15 import * as Layer from "effect/Layer";
16 import * as Stream from "effect/Stream";
17 import { hashBounds, resolveDeltas, scanPart } from "../Protocol/PartialScan.ts";
18 import { Hasher, HashError, type HasherShape } from "./Hasher.ts";
19 import {
20 decodeHashResponse,
21 encodeHashEvent,
22 LAMBDA_CHUNK_BYTES,
23 type HashResponse,
24 } from "./LambdaEvent.ts";
25
26 export const HasherLambda = (
27 fn: LambdaFunction | Effect.Effect<LambdaFunction, any, any>,
28 ): Layer.Layer<Hasher, never, InvokeFunction> =>
29 Layer.effect(
30 Hasher,
31 Effect.gen(function* () {
32 // A class-style declaration (`HasherFunction`) is yielded here — at
33 // deploy that registers the function, at runtime it resolves it.
34 const func = Effect.isEffect(fn) ? yield* fn as Effect.Effect<LambdaFunction> : fn;
35 const invoke = yield* InvokeFunction(func);
36 const remote = (payload: Uint8Array, options: Parameters<HasherShape["hashPart"]>[1]) =>
37 Effect.gen(function* () {
38 const response = yield* invoke({
39 Payload: JSON.stringify(encodeHashEvent(payload, options)),
40 }).pipe(
41 Effect.mapError((error) =>
42 HashError.make({
43 reason: `lambda invoke: ${error._tag}${"message" in error ? `: ${String(error.message)}` : ""}`,
44 }),
45 ),
46 );
47 if (response.FunctionError !== undefined) {
48 return yield* HashError.make({
49 reason: `lambda hasher: ${response.FunctionError}`,
50 });
51 }
52 const chunks = response.Payload
53 ? Array.from(
54 yield* Stream.runCollect(response.Payload).pipe(
55 Effect.mapError((error) =>
56 HashError.make({
57 reason: `lambda response: ${String(error)}`,
58 }),
59 ),
60 ),
61 )
62 : [];
63 const text = new TextDecoder().decode(chunks.length === 1 ? chunks[0] : concat(chunks));
64 const parsed = yield* Effect.try({
65 try: () => JSON.parse(text) as HashResponse,
66 catch: () => HashError.make({ reason: `lambda response: not JSON` }),
67 });
68 return yield* decodeHashResponse(parsed);
69 });
70 return {
71 writesSpill: false,
72 chunkBytes: LAMBDA_CHUNK_BYTES,
73 hashPart: (payload, options) =>
74 // A region larger than a chunk (a big object straddling parts)
75 // cannot fit the invoke payload: hash it here without the trip.
76 (payload.length > LAMBDA_CHUNK_BYTES
77 ? Effect.fail(
78 HashError.make({
79 reason: `payload of ${payload.length} bytes exceeds the invoke limit`,
80 }),
81 )
82 : remote(payload, options)
83 ).pipe(
84 Effect.catchTag("HashError", (error) => {
85 if (payload.length <= LAMBDA_CHUNK_BYTES) {
86 console.warn(`[hasher] ${error.reason}; hashing inline`);
87 }
88 const skip = options.skip ?? 0;
89 return scanPart(skip > 0 ? payload.subarray(skip) : payload, options);
90 }),
91 ),
92 // Delta batches stay on the receiver for now: a batch would need the
93 // same base64 event budget as a chunk.
94 resolveDeltas: (bases, jobs, options) => resolveDeltas(bases, jobs, options),
95 hashBoundsPart: (payload, bounds, options) => hashBounds(payload, bounds, options),
96 } satisfies HasherShape;
97 }),
98 );
99
100 const concat = (chunks: ReadonlyArray<Uint8Array>): Uint8Array => {
101 const out = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
102 let at = 0;
103 for (const c of chunks) {
104 out.set(c, at);
105 at += c.length;
106 }
107 return out;
108 };