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

main
ts 292 lines 10.8 KB
Raw
1 import * as Credentials from "@distilled.cloud/aws/Credentials";
2 import * as Region from "@distilled.cloud/aws/Region";
3 import * as SigV4 from "@distilled.cloud/aws/SigV4";
4 /**
5 * Shared scaffolding for the OpenSearch domain data-plane bindings.
6 *
7 * An OpenSearch domain serves its search/index REST API under the domain's
8 * `endpoint`, authorized by the IAM method actions (`es:ESHttpGet`,
9 * `es:ESHttpPut`, …). There is no distilled operation for these — every
10 * request is a SigV4-signed HTTP call (service `"es"`) made with the host
11 * Function's own credentials.
12 *
13 * NOT exported from `index.ts` — only the per-capability contracts
14 * (`DomainRead` / `DomainWrite` / `DomainReadWrite`) and their `*Http`
15 * layers are public.
16 */
17 import * as Output from "alchemy/Output";
18 import type { SourceError } from "effect/ConfigProvider";
19 import * as Effect from "effect/Effect";
20 import * as Redacted from "effect/Redacted";
21 import * as AWSBindings from "../AWSBindings.ts";
22 import type {
23 BulkResponse,
24 CountResponse,
25 GetDocumentResponse,
26 RefreshOption,
27 SearchRequest,
28 SearchResponse,
29 WriteDocumentResponse,
30 } from "./DataPlaneTypes.ts";
31 import { OpenSearchApiError } from "./DataPlaneTypes.ts";
32 import type { Domain } from "./Domain.ts";
33 import type { ReadDomainClient } from "./DomainRead.ts";
34 import type { WriteDomainClient } from "./DomainWrite.ts";
35
36 /** One signed request against the domain's REST data plane. */
37 export interface OpenSearchHttpRequest {
38 method: "GET" | "HEAD" | "POST" | "PUT" | "DELETE" | "PATCH";
39 /** Path relative to the domain endpoint, e.g. `"songs/_search"`. */
40 path: string;
41 /** Query-string parameters (undefined values are skipped). */
42 query?: Record<string, string | undefined>;
43 /** JSON body (sent as `application/json`). */
44 json?: unknown;
45 /** Raw NDJSON body (used by `_bulk`; sent as `application/x-ndjson`). */
46 ndjson?: string;
47 /** Statuses (besides 2xx) whose body is returned instead of failing. */
48 allowStatuses?: readonly number[];
49 }
50
51 /**
52 * Signs and sends one {@link OpenSearchHttpRequest} and returns the parsed
53 * JSON body (`undefined` for empty bodies, e.g. `HEAD` responses — check
54 * `status` instead).
55 */
56 export type OpenSearchSend = (
57 request: OpenSearchHttpRequest,
58 ) => Effect.Effect<
59 { status: number; body: unknown },
60 OpenSearchApiError | Credentials.CredentialsError | SourceError | SigV4.SigningError
61 >;
62
63 const refreshParam = (refresh: RefreshOption | undefined): Record<string, string | undefined> =>
64 refresh === undefined ? {} : { refresh: String(refresh) };
65
66 /**
67 * Build the shared body of an OpenSearch data-plane `*Http` binding layer:
68 * resolve the ambient distilled `Credentials`/`Region` context once at layer
69 * construction, register the least-privilege IAM statement on the host
70 * Function at deploy time (`iamActions` on the domain and `domain/*`), and
71 * hand a signed-request `send` function to the capability-specific
72 * `makeClient`.
73 */
74 export const makeOpenSearchDataPlaneBinding = <Client>(options: {
75 /** Capability name used in the binding SID and trace spans, e.g. `"DomainRead"`. */
76 name: string;
77 /** IAM actions the capability requires, e.g. `["es:ESHttpGet"]`. */
78 iamActions: string[];
79 /** Build the typed runtime client from the signed-request sender. */
80 makeClient: (send: OpenSearchSend) => Client;
81 }) =>
82 Effect.gen(function* () {
83 const bind = yield* AWSBindings.Bind;
84 const services = yield* AWSBindings.withCredentials(
85 Effect.context<Credentials.Credentials | Region.Region>(),
86 );
87
88 return Effect.fn(function* (domain: Domain) {
89 const Endpoint = yield* domain.endpoint;
90 if (!globalThis.__ALCHEMY_RUNTIME__) {
91 yield* bind`AWS.OpenSearch.${options.name}(${domain})`({
92 policyStatements: [
93 {
94 Effect: "Allow",
95 Action: options.iamActions,
96 Resource: [domain.domainArn, Output.interpolate`${domain.domainArn}/*`],
97 },
98 ],
99 });
100 }
101
102 const send: OpenSearchSend = Effect.fn(`AWS.OpenSearch.${options.name}(${domain.LogicalId})`)(
103 function* (request: OpenSearchHttpRequest) {
104 const endpoint = yield* Endpoint;
105 if (endpoint === undefined) {
106 return yield* new OpenSearchApiError({
107 method: request.method,
108 path: request.path,
109 status: 0,
110 body: "domain has no endpoint (still provisioning, or VPC-only)",
111 });
112 }
113
114 const url = new URL(
115 request.path.replace(/^\//, ""),
116 `https://${endpoint.replace(/^https?:\/\//, "")}/`,
117 );
118 for (const [key, value] of Object.entries(request.query ?? {})) {
119 if (value !== undefined) url.searchParams.set(key, value);
120 }
121
122 const headers: Record<string, string> = {};
123 let body: string | undefined;
124 if (request.json !== undefined) {
125 body = JSON.stringify(request.json);
126 headers["content-type"] = "application/json";
127 } else if (request.ndjson !== undefined) {
128 body = request.ndjson;
129 headers["content-type"] = "application/x-ndjson";
130 }
131
132 // Resolve credentials fresh per request (SSO/STS sessions rotate) and
133 // sign for the domain's own region, parsed from its endpoint.
134 const { credentials, region } = yield* Effect.gen(function* () {
135 const credentials = yield* yield* Credentials.Credentials;
136 const region =
137 /\.([a-z0-9-]+)\.(?:es|aos)\.amazonaws\.com$/.exec(url.hostname)?.[1] ??
138 (yield* yield* Region.Region);
139 return { credentials, region };
140 }).pipe(Effect.provideContext(services));
141
142 const signed = yield* SigV4.sign({
143 method: request.method,
144 url: url.toString(),
145 headers,
146 body,
147 accessKeyId: Redacted.value(credentials.accessKeyId),
148 secretAccessKey: credentials.secretAccessKey,
149 sessionToken: credentials.sessionToken,
150 service: "es",
151 region,
152 allHeaders: true,
153 });
154
155 const toError = (status: number) => (cause: unknown) =>
156 new OpenSearchApiError({
157 method: request.method,
158 path: request.path,
159 status,
160 body: cause instanceof Error ? cause.message : String(cause),
161 });
162
163 const response = yield* Effect.tryPromise({
164 try: () =>
165 fetch(signed.url, {
166 method: signed.method,
167 headers: signed.headers,
168 body,
169 }),
170 catch: toError(0),
171 });
172 const text = yield* Effect.tryPromise({
173 try: () => response.text(),
174 catch: toError(response.status),
175 });
176
177 const ok =
178 (response.status >= 200 && response.status < 300) ||
179 (request.allowStatuses?.includes(response.status) ?? false);
180 if (!ok) {
181 return yield* new OpenSearchApiError({
182 method: request.method,
183 path: request.path,
184 status: response.status,
185 body: text,
186 });
187 }
188 if (text.trim() === "") {
189 return { status: response.status, body: undefined };
190 }
191
192 const parsed = yield* Effect.try({
193 try: () => JSON.parse(text) as unknown,
194 catch: toError(response.status),
195 });
196 return { status: response.status, body: parsed };
197 },
198 );
199
200 return options.makeClient(send);
201 });
202 });
203
204 const encodePath = (...segments: string[]): string =>
205 segments.map((segment) => encodeURIComponent(segment)).join("/");
206
207 /** Build the read half of the domain data-plane client. */
208 export const makeReadDomainClient = (send: OpenSearchSend): ReadDomainClient => ({
209 search: <TDoc>(request?: SearchRequest) =>
210 send({
211 method: "GET",
212 path:
213 request?.index !== undefined ? `${encodeURIComponent(request.index)}/_search` : "_search",
214 query: {
215 ...request?.query,
216 // The Query-DSL body travels in the `source` parameter so searches
217 // stay on es:ESHttpGet (POST would require the write IAM action).
218 ...(request?.body !== undefined
219 ? {
220 source: JSON.stringify(request.body),
221 source_content_type: "application/json",
222 }
223 : {}),
224 },
225 }).pipe(Effect.map(({ body }) => body as SearchResponse<TDoc>)),
226 count: (request) =>
227 send({
228 method: "GET",
229 path: request?.index !== undefined ? `${encodeURIComponent(request.index)}/_count` : "_count",
230 query:
231 request?.body !== undefined
232 ? {
233 source: JSON.stringify(request.body),
234 source_content_type: "application/json",
235 }
236 : undefined,
237 }).pipe(Effect.map(({ body }) => body as CountResponse)),
238 getDocument: <TDoc>(index: string, id: string) =>
239 send({
240 method: "GET",
241 path: encodePath(index, "_doc", id),
242 allowStatuses: [404],
243 }).pipe(Effect.map(({ body }) => body as GetDocumentResponse<TDoc>)),
244 existsDocument: (index, id) =>
245 send({
246 method: "HEAD",
247 path: encodePath(index, "_doc", id),
248 allowStatuses: [404],
249 }).pipe(Effect.map(({ status }) => status === 200)),
250 get: (path, query) => send({ method: "GET", path, query }).pipe(Effect.map(({ body }) => body)),
251 });
252
253 /** Build the write half of the domain data-plane client. */
254 export const makeWriteDomainClient = (send: OpenSearchSend): WriteDomainClient => ({
255 indexDocument: (index, document, options) =>
256 send(
257 options?.id !== undefined
258 ? {
259 method: "PUT",
260 path: encodePath(index, "_doc", options.id),
261 json: document,
262 query: refreshParam(options.refresh),
263 }
264 : {
265 method: "POST",
266 path: encodePath(index, "_doc"),
267 json: document,
268 query: refreshParam(options?.refresh),
269 },
270 ).pipe(Effect.map(({ body }) => body as WriteDocumentResponse)),
271 updateDocument: (index, id, body, options) =>
272 send({
273 method: "POST",
274 path: encodePath(index, "_update", id),
275 json: body,
276 query: refreshParam(options?.refresh),
277 }).pipe(Effect.map(({ body }) => body as WriteDocumentResponse)),
278 deleteDocument: (index, id, options) =>
279 send({
280 method: "DELETE",
281 path: encodePath(index, "_doc", id),
282 query: refreshParam(options?.refresh),
283 allowStatuses: [404],
284 }).pipe(Effect.map(({ body }) => body as WriteDocumentResponse)),
285 bulk: (operations, options) =>
286 send({
287 method: "POST",
288 path: "_bulk",
289 ndjson: `${operations.map((line) => JSON.stringify(line)).join("\n")}\n`,
290 query: refreshParam(options?.refresh),
291 }).pipe(Effect.map(({ body }) => body as BulkResponse)),
292 });