@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, 04:45 UTC

main
ts 257 lines 9.43 KB
Raw
1 import * as Effect from "effect/Effect";
2 import { identity } from "effect/Function";
3 import * as HttpApiClient from "effect/http-api/HttpApiClient";
4 import * as HttpApiError from "effect/http-api/HttpApiError";
5 import * as HttpClient from "effect/http/HttpClient";
6 import * as HttpClientError from "effect/http/HttpClientError";
7 import * as HttpClientRequest from "effect/http/HttpClientRequest";
8 import * as Schedule from "effect/Schedule";
9 import * as Schema from "effect/Schema";
10 import { profileCommandHint } from "../Util/interactive.ts";
11 import { StateApi, StateStoreFailure } from "./HttpStateApi.ts";
12 import type { ReplacedResourceState, ResourceState } from "./ResourceState.ts";
13 import { StateStoreError, type PersistedState, type StateService } from "./State.ts";
14 import { encodeState, reviveStateRecursive } from "./StateEncoding.ts";
15
16 /**
17 * Persisted shape of an HTTP state store endpoint — `{ url, authToken }`.
18 * Stored in the credentials file alongside other per-profile secrets.
19 * Deliberately separate from {@link HttpStateStoreProps}: `id` and
20 * `transformClient` are deployment-time choices, not credentials.
21 */
22 export interface HttpStateStoreCredentials {
23 url: string;
24 /** Bearer token used to authenticate every request. */
25 authToken: string;
26 }
27
28 export interface HttpStateStoreProps extends HttpStateStoreCredentials {
29 /**
30 * `StateService.id` slug for telemetry — e.g. `"http"` for a bare
31 * HTTP store, `"cloudflare-http"` for the Cloudflare-deployed
32 * variant. Required so every concrete deployment of this state-store
33 * shape shows up distinctly on the adoption dashboard.
34 */
35 id: string;
36 transformClient?: (
37 client: HttpClientRequest.HttpClientRequest,
38 ) => HttpClientRequest.HttpClientRequest;
39 }
40
41 export const checkHttpStateStoreAuth = ({ url, authToken }: { url: string; authToken: string }) =>
42 Effect.gen(function* () {
43 const apiClient = yield* HttpApiClient.make(StateApi, {
44 baseUrl: url,
45 transformClient: HttpClient.mapRequest((req) =>
46 req.pipe(HttpClientRequest.bearerToken(authToken)),
47 ),
48 });
49 return yield* apiClient.state.listStacks().pipe(
50 Effect.map(() => true),
51 Effect.catchTag("Unauthorized", () => Effect.succeed(false)),
52 Effect.retry({
53 while: (error) =>
54 // the store failing behind the API is as transient as a 5xx
55 error._tag === "StateStoreFailure" ||
56 (error._tag === "HttpClientError" &&
57 // transport-level failures (no response — DNS, TCP reset, TLS,
58 // "fetch failed") are as transient as the post-deploy 404s
59 (!error.response ||
60 // worker can 404 for a bit on first deploy
61 error.response.status === 404 ||
62 error.response.status >= 500)),
63 // Bounded: a store that 404s/500s forever is a hard failure, not
64 // something to spin on until the process is killed.
65 schedule: Schedule.max([Schedule.fixed(200), Schedule.recurs(75)]),
66 }),
67 );
68 });
69
70 export const makeHttpStateStore = ({ url, authToken, transformClient, id }: HttpStateStoreProps) =>
71 Effect.gen(function* () {
72 const apiClient = yield* HttpApiClient.make(StateApi, {
73 baseUrl: url,
74 transformClient: HttpClient.mapRequest((req) =>
75 req.pipe(HttpClientRequest.bearerToken(authToken), transformClient ?? identity),
76 ),
77 });
78 const state = apiClient.state;
79
80 const service: StateService = {
81 id,
82 getVersion: () =>
83 apiClient.version.getVersion().pipe(
84 Effect.map((v) => v.version),
85 mapStateStoreError,
86 ),
87 listStacks: () =>
88 state.listStacks().pipe(
89 Effect.map((stacks) => [...stacks]),
90 mapStateStoreError,
91 ),
92 listStages: (stack) => state.listStages({ params: { stack } }).pipe(mapStateStoreError),
93 list: (request) => state.listResources({ params: request }).pipe(mapStateStoreError),
94 get: (request) =>
95 state
96 .getState({
97 params: {
98 stack: request.stack,
99 stage: request.stage,
100 fqn: encodeURIComponent(request.fqn),
101 },
102 })
103 .pipe(
104 Effect.map((s) => (s == null ? undefined : (reviveStateRecursive(s) as ResourceState))),
105 mapStateStoreError,
106 ),
107 getReplacedResources: (request) =>
108 state.getReplacedResources({ params: request }).pipe(
109 Effect.map((resources) =>
110 resources.map((s) => reviveStateRecursive(s) as ReplacedResourceState),
111 ),
112 mapStateStoreError,
113 ),
114 set: <V extends PersistedState>(request: {
115 stack: string;
116 stage: string;
117 fqn: string;
118 value: V;
119 }) =>
120 state
121 .setState({
122 params: {
123 stack: request.stack,
124 stage: request.stage,
125 fqn: encodeURIComponent(request.fqn),
126 },
127 payload: encodeState(request.value),
128 })
129 .pipe(
130 // Server echoes the stored value, but the client already
131 // has the canonical object (including any Redacted<T>
132 // instances); returning the input avoids a lossy round-trip.
133 Effect.map(() => request.value),
134 mapStateStoreError,
135 ),
136 delete: (request) =>
137 state
138 .deleteState({
139 params: {
140 stack: request.stack,
141 stage: request.stage,
142 fqn: encodeURIComponent(request.fqn),
143 },
144 })
145 .pipe(Effect.asVoid, mapStateStoreError),
146 deleteStack: (request) =>
147 state
148 .deleteStack({
149 params: { stack: request.stack },
150 query: request.stage === undefined ? {} : { stage: request.stage },
151 })
152 .pipe(Effect.asVoid, mapStateStoreError),
153 getOutput: (request) =>
154 state
155 .getStackOutput({
156 params: { stack: request.stack, stage: request.stage },
157 })
158 .pipe(
159 Effect.map((s) => (s == null ? undefined : reviveStateRecursive(s))),
160 mapStateStoreError,
161 ),
162 setOutput: (request) =>
163 state
164 .setStackOutput({
165 params: { stack: request.stack, stage: request.stage },
166 payload: encodeState(request.value as any),
167 })
168 .pipe(
169 Effect.map(() => request.value),
170 mapStateStoreError,
171 ),
172 };
173 return service;
174 });
175
176 /**
177 * Predicate over an `HttpClientError`-shaped failure that returns `true`
178 * for failures we expect to clear up on their own.
179 *
180 * We retry:
181 * - all transport-level errors (no `response` — DNS, TCP reset, TLS,
182 * abort, etc.)
183 * - 408 (request timeout) and 429 (rate limit)
184 * - 404, which is normal in the seconds after a worker is first
185 * deployed and the route hasn't propagated yet
186 * - every 5xx
187 *
188 * Anything else (400/401/403/etc.) is a real client-side problem and
189 * shouldn't be hidden behind retries.
190 */
191 const isTransient = (e: any): boolean => {
192 // The store failed behind the API (e.g. a Durable Object or secret read).
193 if (e?._tag === "StateStoreFailure") return true;
194 if (e?._tag !== "HttpClientError") return false;
195 const status: number | undefined = e.response?.status;
196 if (status == null) return true;
197 if (status === 404 || status === 408 || status === 429) return true;
198 return status >= 500 && status < 600;
199 };
200
201 const retryTransient = <A, Err, Req>(eff: Effect.Effect<A, Err, Req>) =>
202 Effect.retry(eff, {
203 while: isTransient,
204 // Exponential backoff capped at 2s, max 5 attempts. Beyond that
205 // the issue isn't transient and we'd rather surface a hard
206 // failure than block the deploy indefinitely.
207 schedule: Schedule.max([
208 Schedule.min([Schedule.exponential(100), Schedule.spaced("2 seconds")]),
209 Schedule.recurs(5),
210 ]),
211 });
212
213 /**
214 * Describe a state-store failure using only its known kind and HTTP status.
215 * Client/decoder messages and causes can contain serialized state, including
216 * secrets unwrapped by encodeState, so they must not become diagnostics.
217 */
218 export const describeStateStoreFailure = (
219 e: unknown,
220 profileCommand = "alchemy profile edit",
221 ): string => {
222 if (Schema.is(HttpApiError.Unauthorized)(e)) {
223 return (
224 "State store rejected the request as unauthorized. " +
225 `The stored state-store credentials may be stale. Run \`${profileCommand}\` to reconfigure them.`
226 );
227 }
228 if (Schema.is(StateStoreFailure)(e)) {
229 return `${e.message}.`;
230 }
231 if (HttpClientError.isHttpClientError(e)) {
232 const status = e.response?.status;
233 return `State store request failed (${e.reason._tag}${status === undefined ? "" : `, HTTP ${status}`}).`;
234 }
235 return "State store request failed.";
236 };
237
238 /** Collapse any client failure into a {@link StateStoreError}. */
239 const mapStateStoreError = <A, E, R>(eff: Effect.Effect<A, E, R>) =>
240 eff.pipe(
241 retryTransient,
242 Effect.catch((e: E) =>
243 Effect.gen(function* () {
244 const command = yield* profileCommandHint("alchemy profile edit");
245 return yield* new StateStoreError({
246 message: describeStateStoreFailure(e, command),
247 http: HttpClientError.isHttpClientError(e)
248 ? { status: e.response?.status }
249 : Schema.is(HttpApiError.Unauthorized)(e)
250 ? { status: 401 }
251 : Schema.is(StateStoreFailure)(e)
252 ? { status: 500 }
253 : undefined,
254 });
255 }),
256 ),
257 ) as Effect.Effect<A, StateStoreError, R>;