@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 343 lines 12.4 KB
Raw
1 import * as amplify from "@distilled.cloud/aws/amplify";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, diffTags, hasAlchemyTags, tagRecord } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import type * as Redacted from "effect/Redacted";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12
13 /**
14 * Hosting platform for the Amplify app. `WEB` = static site, `WEB_DYNAMIC` =
15 * server-side rendered, `WEB_COMPUTE` = SSR with compute (Next.js 12+).
16 */
17 export type Platform = "WEB" | "WEB_DYNAMIC" | "WEB_COMPUTE";
18
19 /**
20 * A URL redirect/rewrite rule for the Amplify app.
21 */
22 export interface CustomRule {
23 /** Source URL pattern. */
24 source: string;
25 /** Target URL. */
26 target: string;
27 /** HTTP status / rule type (e.g. `"200"`, `"301"`, `"404"`). */
28 status?: string;
29 /** Condition (e.g. country code) for the rule to apply. */
30 condition?: string;
31 }
32
33 export interface AppProps {
34 /**
35 * Name of the app. If omitted, a unique name is generated.
36 */
37 name?: string;
38 /**
39 * Description of the app.
40 */
41 description?: string;
42 /**
43 * Hosting platform.
44 * @default "WEB"
45 */
46 platform?: Platform;
47 /**
48 * Environment variables available to the build.
49 */
50 environmentVariables?: Record<string, string>;
51 /**
52 * Build specification (amplify.yml contents) for the app.
53 */
54 buildSpec?: string;
55 /**
56 * URL redirect and rewrite rules.
57 */
58 customRules?: CustomRule[];
59 /**
60 * Whether to require basic auth to view the app's branches by default.
61 */
62 enableBasicAuth?: boolean;
63 /**
64 * Default basic auth credentials for the app's branches, as base64 of
65 * `user:password`.
66 */
67 basicAuthCredentials?: Redacted.Redacted<string>;
68 /**
69 * User-defined tags to apply to the app.
70 */
71 tags?: Record<string, string>;
72 }
73
74 export interface App extends Resource<
75 "AWS.Amplify.App",
76 AppProps,
77 {
78 appId: string;
79 appArn: string;
80 name: string;
81 platform: Platform;
82 defaultDomain: string;
83 tags: Record<string, string>;
84 },
85 never,
86 Providers
87 > {}
88
89 /**
90 * An AWS Amplify Hosting app. This resource provisions the app container; it
91 * does **not** connect a Git repository.
92 *
93 * Connecting a repository requires an OAuth handshake (via CodeConnections or a
94 * personal access token) that is inherently human-in-the-loop and cannot be
95 * automated from infrastructure code. To wire a repo, create the app with this
96 * resource, then connect the repository from the Amplify console or CLI.
97 * Manual-deploy branches (no repo required) are code-driven via the
98 * {@link Branch} resource plus the `CreateDeployment`/`StartDeployment`
99 * bindings. For a fully code-driven static/SSR site on AWS, prefer Alchemy's
100 * own `Website` composites (S3 + CloudFront).
101 *
102 * ### Creating Amplify Apps
103 * **Example:** Basic App
104 * ```typescript
105 * const app = yield* App("MyApp", {
106 * description: "Marketing site",
107 * platform: "WEB",
108 * });
109 * ```
110 *
111 * **Example:** App with Build Config and Redirects
112 * ```typescript
113 * const app = yield* App("MyApp", {
114 * platform: "WEB_COMPUTE",
115 * environmentVariables: { NODE_ENV: "production" },
116 * customRules: [
117 * { source: "/<*>", target: "/index.html", status: "404-200" },
118 * ],
119 * buildSpec: "version: 1\nfrontend:\n phases:\n build:\n commands: []\n",
120 * });
121 * ```
122 *
123 * ### Deploying and Observing From a Function
124 * **Example:** Manual Deploy Pipeline (CreateDeployment + StartDeployment)
125 * ```typescript
126 * // init — bind the deployment operations to the app
127 * const createDeployment = yield* AWS.Amplify.CreateDeployment(app);
128 * const startDeployment = yield* AWS.Amplify.StartDeployment(app);
129 *
130 * // runtime — stage, upload, release
131 * const { jobId, zipUploadUrl } = yield* createDeployment({
132 * branchName: "main",
133 * });
134 * // PUT the site zip to zipUploadUrl, then:
135 * yield* startDeployment({ branchName: "main", jobId });
136 * ```
137 *
138 * **Example:** React to Deployment Status Changes
139 * ```typescript
140 * yield* AWS.Amplify.consumeDeploymentStatusChanges(
141 * { jobStatus: ["FAILED"] },
142 * (events) =>
143 * Stream.runForEach(events, (event) =>
144 * Effect.log(`build failed on ${event.detail.branchName}`),
145 * ),
146 * );
147 * ```
148 *
149 * @resource
150 */
151 export const App = Resource<App>("AWS.Amplify.App");
152
153 // Amplify throttles control-plane writes account-wide in roughly per-minute
154 // buckets and surfaces it as a BadRequestException with a "Rate exceeded"
155 // message (not a throttling error class). A burst elsewhere in the account
156 // (e.g. a mass delete) can keep the bucket exhausted for most of a minute, so
157 // spread bounded retries evenly across ~80s instead of front-loading an
158 // exponential that spends its whole budget in the first few seconds.
159 const amplifyWriteRetrySchedule = Schedule.max([Schedule.spaced("8 seconds"), Schedule.recurs(10)]);
160
161 export const AppProvider = () =>
162 Provider.effect(
163 App,
164 Effect.gen(function* () {
165 const toName = (id: string, props: { name?: string } = {}) =>
166 props.name ? Effect.succeed(props.name) : createPhysicalName({ id, maxLength: 100 });
167
168 const observe = (appId: string) =>
169 amplify.getApp({ appId }).pipe(
170 Effect.map((r) => r.app),
171 // Amplify's API Gateway front door can time out a slow
172 // control-plane call ("Endpoint request timed out"); reads are
173 // side-effect free, so retry the typed tag with bounded backoff.
174 Effect.retry({
175 while: (e): boolean => e._tag === "TimeoutException",
176 schedule: Schedule.exponential("2 seconds"),
177 times: 3,
178 }),
179 Effect.catchTag("NotFoundException", () => Effect.undefined),
180 );
181
182 // Find an app we own (matching physical name + internal Alchemy tags).
183 // Used to recover from a timed-out CreateApp whose outcome is unknown —
184 // the backend may have created the app even though the front door gave
185 // up on the response.
186 const findOwnApp = Effect.fn(function* (id: string, name: string) {
187 const apps = yield* amplify.listApps.pages({}).pipe(
188 Stream.runCollect,
189 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.apps ?? [])),
190 );
191 for (const app of apps) {
192 if (app.name !== name) continue;
193 if (yield* hasAlchemyTags(id, app.tags)) return app;
194 }
195 return undefined;
196 });
197
198 const syncTags = Effect.fn(function* (
199 appArn: string,
200 desiredTags: Record<string, string>,
201 observedTags: Record<string, string>,
202 ) {
203 const { removed, upsert } = diffTags(observedTags, desiredTags);
204 if (upsert.length > 0) {
205 yield* amplify.tagResource({
206 resourceArn: appArn,
207 tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
208 });
209 }
210 if (removed.length > 0) {
211 yield* amplify.untagResource({
212 resourceArn: appArn,
213 tagKeys: removed,
214 });
215 }
216 });
217
218 return {
219 stables: ["appId", "appArn"],
220 read: Effect.fn(function* ({ id, output }) {
221 if (!output?.appId) return undefined;
222 const app = yield* observe(output.appId);
223 if (!app) return undefined;
224 const attrs = {
225 appId: app.appId,
226 appArn: app.appArn,
227 name: app.name,
228 platform: (app.platform as Platform) ?? "WEB",
229 defaultDomain: app.defaultDomain ?? "",
230 tags: tagRecord(app.tags),
231 };
232 return (yield* hasAlchemyTags(id, app.tags)) ? attrs : Unowned(attrs);
233 }),
234 reconcile: Effect.fn(function* ({ id, news, output, session }) {
235 const name = yield* toName(id, news);
236 const internalTags = yield* createInternalTags(id);
237 const desiredTags = { ...internalTags, ...news.tags };
238
239 let app = output?.appId ? yield* observe(output.appId) : undefined;
240
241 if (!app) {
242 // CreateApp is subject to the account-wide "Rate exceeded"
243 // throttle (see amplifyWriteRetrySchedule). Its API Gateway
244 // front door can also time out a slow CreateApp (typed
245 // TimeoutException, "Endpoint request timed out") with the
246 // outcome unknown — the backend may still have created the
247 // app. Observe by name + internal tags before every (re)try so
248 // a retry never creates a duplicate app.
249 app = yield* findOwnApp(id, name).pipe(
250 Effect.flatMap((existing) =>
251 existing
252 ? Effect.succeed(existing)
253 : amplify
254 .createApp({
255 name,
256 description: news.description,
257 platform: news.platform ?? "WEB",
258 environmentVariables: news.environmentVariables,
259 buildSpec: news.buildSpec,
260 customRules: news.customRules,
261 enableBasicAuth: news.enableBasicAuth,
262 basicAuthCredentials: news.basicAuthCredentials,
263 tags: desiredTags,
264 })
265 .pipe(Effect.map((r) => r.app)),
266 ),
267 Effect.retry({
268 while: (e): boolean =>
269 e._tag === "TimeoutException" ||
270 (e._tag === "BadRequestException" && (e.message ?? "").includes("Rate exceeded")),
271 schedule: amplifyWriteRetrySchedule,
272 }),
273 );
274 } else {
275 // UpdateApp is idempotent — retry front-door timeouts and the
276 // "Rate exceeded" throttle with bounded backoff.
277 yield* amplify
278 .updateApp({
279 appId: app.appId,
280 name,
281 description: news.description,
282 platform: news.platform ?? "WEB",
283 environmentVariables: news.environmentVariables,
284 buildSpec: news.buildSpec,
285 customRules: news.customRules,
286 enableBasicAuth: news.enableBasicAuth,
287 basicAuthCredentials: news.basicAuthCredentials,
288 })
289 .pipe(
290 Effect.retry({
291 while: (e): boolean =>
292 e._tag === "TimeoutException" ||
293 (e._tag === "BadRequestException" &&
294 (e.message ?? "").includes("Rate exceeded")),
295 schedule: amplifyWriteRetrySchedule,
296 }),
297 );
298 yield* syncTags(app.appArn, desiredTags, tagRecord(app.tags));
299 }
300
301 yield* session.note(app.appArn);
302 return {
303 appId: app.appId,
304 appArn: app.appArn,
305 name,
306 platform: (news.platform as Platform) ?? "WEB",
307 defaultDomain: app.defaultDomain ?? "",
308 tags: desiredTags,
309 };
310 }),
311 list: () =>
312 Effect.gen(function* () {
313 const apps = yield* amplify.listApps.pages({}).pipe(
314 Stream.runCollect,
315 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.apps ?? [])),
316 );
317 return apps.map((app) => ({
318 appId: app.appId,
319 appArn: app.appArn,
320 name: app.name,
321 platform: (app.platform as Platform) ?? "WEB",
322 defaultDomain: app.defaultDomain ?? "",
323 tags: tagRecord(app.tags),
324 }));
325 }),
326 delete: Effect.fn(function* ({ output }) {
327 // DeleteApp is idempotent — retry front-door timeouts and the
328 // account-wide "Rate exceeded" throttle; a timed-out delete that
329 // actually landed resolves to NotFoundException on the retry,
330 // which is swallowed below.
331 yield* amplify.deleteApp({ appId: output.appId }).pipe(
332 Effect.retry({
333 while: (e): boolean =>
334 e._tag === "TimeoutException" ||
335 (e._tag === "BadRequestException" && (e.message ?? "").includes("Rate exceeded")),
336 schedule: amplifyWriteRetrySchedule,
337 }),
338 Effect.catchTag("NotFoundException", () => Effect.void),
339 );
340 }),
341 };
342 }),
343 );