@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 224 lines 8.16 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 AMP data-plane HTTP bindings.
6 *
7 * Amazon Managed Service for Prometheus exposes its data plane as a
8 * Prometheus-compatible HTTP API under the workspace's `prometheusEndpoint`
9 * (`aps:RemoteWrite`, `aps:QueryMetrics`, `aps:GetLabels`, `aps:GetSeries`,
10 * `aps:GetMetricMetadata`). There is no distilled operation for these — every
11 * request is a SigV4-signed HTTP call (service `"aps"`) made with the host
12 * Function's own credentials.
13 *
14 * NOT exported from `index.ts` — only the per-capability contracts and
15 * `*Http` layers are public.
16 */
17 import { toWireSeconds } from "alchemy/Util/Duration";
18 import type { SourceError } from "effect/ConfigProvider";
19 import type * as Duration from "effect/Duration";
20 import * as Effect from "effect/Effect";
21 import * as Redacted from "effect/Redacted";
22 import * as AWSBindings from "../AWSBindings.ts";
23 import { PrometheusApiError, type PrometheusTime } from "./PrometheusTypes.ts";
24 import type { Workspace } from "./Workspace.ts";
25
26 /** A request against the workspace's Prometheus-compatible endpoint. */
27 export interface AmpHttpRequest {
28 method: "GET" | "POST";
29 /** Path relative to `prometheusEndpoint`, e.g. `"api/v1/query"`. */
30 path: string;
31 /** Query-string parameters; array values are appended repeatedly. */
32 query?: Record<string, string | string[] | undefined>;
33 /** URL-encoded form body (`application/x-www-form-urlencoded`). */
34 form?: Record<string, string | string[] | undefined>;
35 /** Raw binary body (used by remote-write). */
36 bytes?: {
37 data: Uint8Array;
38 contentType: string;
39 headers?: Record<string, string>;
40 };
41 }
42
43 /**
44 * Signs and sends one {@link AmpHttpRequest}, unwraps the Prometheus
45 * `{ status, data }` envelope, and returns `data` (or `undefined` for
46 * empty-body responses like remote-write's `200`).
47 */
48 export type AmpSend = (
49 request: AmpHttpRequest,
50 ) => Effect.Effect<
51 unknown,
52 PrometheusApiError | Credentials.CredentialsError | SourceError | SigV4.SigningError
53 >;
54
55 const appendParams = (
56 target: URLSearchParams,
57 params: Record<string, string | string[] | undefined>,
58 ) => {
59 for (const [key, value] of Object.entries(params)) {
60 if (value === undefined) continue;
61 if (Array.isArray(value)) {
62 for (const item of value) target.append(key, item);
63 } else {
64 target.set(key, value);
65 }
66 }
67 };
68
69 /** Serialize a {@link PrometheusTime} for the query API. */
70 export const toPromTime = (time: PrometheusTime): string =>
71 time instanceof Date ? time.toISOString() : String(time);
72
73 /** Serialize a `Duration.Input` as a Prometheus duration string (`"30s"`). */
74 export const toPromDuration = (input: Duration.Input): string => `${toWireSeconds(input)}s`;
75
76 /**
77 * Build the shared body of an AMP data-plane `*Http` binding layer:
78 * resolve the ambient distilled `Credentials`/`Region` context once at layer
79 * construction, register the least-privilege IAM statement on the host
80 * Function at deploy time, and hand a signed-request `send` function to the
81 * capability-specific `makeClient`.
82 */
83 export const makeAmpWorkspaceHttpBinding = <Client>(options: {
84 /** Capability name used in the binding SID and trace spans, e.g. `"QueryMetrics"`. */
85 name: string;
86 /** IAM actions the capability requires on the workspace, e.g. `["aps:QueryMetrics"]`. */
87 iamActions: string[];
88 /** Build the typed runtime client from the signed-request sender. */
89 makeClient: (send: AmpSend) => Client;
90 }) =>
91 Effect.gen(function* () {
92 const bind = yield* AWSBindings.Bind;
93 const services = yield* AWSBindings.withCredentials(
94 Effect.context<Credentials.Credentials | Region.Region>(),
95 );
96
97 return Effect.fn(function* (workspace: Workspace) {
98 const PrometheusEndpoint = yield* workspace.prometheusEndpoint;
99 if (!globalThis.__ALCHEMY_RUNTIME__) {
100 yield* bind`AWS.AMP.${options.name}(${workspace})`({
101 policyStatements: [
102 {
103 Effect: "Allow",
104 Action: options.iamActions,
105 Resource: [workspace.workspaceArn],
106 },
107 ],
108 });
109 }
110
111 const send: AmpSend = Effect.fn(`AWS.AMP.${options.name}(${workspace.LogicalId})`)(function* (
112 request: AmpHttpRequest,
113 ) {
114 const endpoint = yield* PrometheusEndpoint;
115 if (endpoint === undefined) {
116 return yield* new PrometheusApiError({
117 method: request.method,
118 path: request.path,
119 status: 0,
120 body: "workspace has no prometheusEndpoint",
121 });
122 }
123
124 const base = endpoint.endsWith("/") ? endpoint : `${endpoint}/`;
125 const url = new URL(request.path, base);
126 appendParams(url.searchParams, request.query ?? {});
127
128 const headers: Record<string, string> = {};
129 let body: string | Uint8Array<ArrayBuffer> | undefined;
130 if (request.form !== undefined) {
131 const form = new URLSearchParams();
132 appendParams(form, request.form);
133 body = form.toString();
134 headers["content-type"] = "application/x-www-form-urlencoded";
135 } else if (request.bytes !== undefined) {
136 // Copy into a fresh ArrayBuffer-backed view — `fetch`'s `BodyInit`
137 // rejects `Uint8Array<ArrayBufferLike>` (SharedArrayBuffer-backed).
138 body = new Uint8Array(request.bytes.data);
139 headers["content-type"] = request.bytes.contentType;
140 Object.assign(headers, request.bytes.headers);
141 }
142
143 // Resolve credentials fresh per request (SSO/STS sessions rotate) and
144 // sign for the workspace's own region, parsed from its endpoint.
145 const { credentials, region } = yield* Effect.gen(function* () {
146 const credentials = yield* yield* Credentials.Credentials;
147 const region =
148 /^aps-workspaces\.([a-z0-9-]+)\.amazonaws\.com$/.exec(url.hostname)?.[1] ??
149 (yield* yield* Region.Region);
150 return { credentials, region };
151 }).pipe(Effect.provideContext(services));
152
153 const signed = yield* SigV4.sign({
154 method: request.method,
155 url: url.toString(),
156 headers,
157 body,
158 accessKeyId: Redacted.value(credentials.accessKeyId),
159 secretAccessKey: credentials.secretAccessKey,
160 sessionToken: credentials.sessionToken,
161 service: "aps",
162 region,
163 allHeaders: true,
164 });
165
166 const toError = (status: number) => (cause: unknown) =>
167 new PrometheusApiError({
168 method: request.method,
169 path: request.path,
170 status,
171 body: cause instanceof Error ? cause.message : String(cause),
172 });
173
174 const response = yield* Effect.tryPromise({
175 try: () =>
176 fetch(signed.url, {
177 method: signed.method,
178 headers: signed.headers,
179 body,
180 }),
181 catch: toError(0),
182 });
183 const text = yield* Effect.tryPromise({
184 try: () => response.text(),
185 catch: toError(response.status),
186 });
187
188 if (response.status < 200 || response.status >= 300) {
189 return yield* new PrometheusApiError({
190 method: request.method,
191 path: request.path,
192 status: response.status,
193 body: text,
194 });
195 }
196 if (text.trim() === "") {
197 // remote-write success has no body.
198 return undefined;
199 }
200
201 const envelope = yield* Effect.try({
202 try: () =>
203 JSON.parse(text) as {
204 status?: string;
205 data?: unknown;
206 error?: string;
207 errorType?: string;
208 },
209 catch: toError(response.status),
210 });
211 if (envelope.status !== undefined && envelope.status !== "success") {
212 return yield* new PrometheusApiError({
213 method: request.method,
214 path: request.path,
215 status: response.status,
216 body: text,
217 });
218 }
219 return envelope.data;
220 });
221
222 return options.makeClient(send);
223 });
224 });