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
| 1 | import * as amplify from "@distilled.cloud/aws/amplify"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved, somePropsAreDifferent } from "alchemy/Diff"; |
| 4 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { Resource } from "alchemy/Resource"; |
| 7 | import { createInternalTags, diffTags, hasAlchemyTags, tagRecord } from "alchemy/Tags"; |
| 8 | import { toWireSeconds } from "alchemy/Util/Duration"; |
| 9 | import type * as Duration from "effect/Duration"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import type * as Redacted from "effect/Redacted"; |
| 12 | import * as Schedule from "effect/Schedule"; |
| 13 | import * as Stream from "effect/Stream"; |
| 14 | import type { Providers } from "../Providers.ts"; |
| 15 | |
| 16 | /** |
| 17 | * Deployment stage of an Amplify branch. |
| 18 | */ |
| 19 | export type BranchStage = "PRODUCTION" | "BETA" | "DEVELOPMENT" | "EXPERIMENTAL" | "PULL_REQUEST"; |
| 20 | |
| 21 | export interface BranchProps { |
| 22 | /** |
| 23 | * ID of the Amplify {@link App} the branch belongs to. Changing it replaces |
| 24 | * the branch. |
| 25 | */ |
| 26 | appId: string; |
| 27 | /** |
| 28 | * Name of the branch (e.g. `main`). For an app without a connected |
| 29 | * repository this is just a label for manual deployments. If omitted, a |
| 30 | * unique name is generated. Changing it replaces the branch. |
| 31 | */ |
| 32 | branchName?: string; |
| 33 | /** |
| 34 | * Description of the branch. |
| 35 | */ |
| 36 | description?: string; |
| 37 | /** |
| 38 | * Display name shown in the Amplify console. |
| 39 | */ |
| 40 | displayName?: string; |
| 41 | /** |
| 42 | * Deployment stage of the branch. |
| 43 | */ |
| 44 | stage?: BranchStage; |
| 45 | /** |
| 46 | * Framework label for the branch (e.g. `React`, `Next.js`). |
| 47 | */ |
| 48 | framework?: string; |
| 49 | /** |
| 50 | * Whether pushing to the (repo-connected) branch automatically triggers a |
| 51 | * build. Branches of repo-less apps should set this to `false`. |
| 52 | */ |
| 53 | enableAutoBuild?: boolean; |
| 54 | /** |
| 55 | * Whether to enable deployment skew protection for the branch. |
| 56 | */ |
| 57 | enableSkewProtection?: boolean; |
| 58 | /** |
| 59 | * Whether to enable performance mode (longer edge cache intervals). |
| 60 | */ |
| 61 | enablePerformanceMode?: boolean; |
| 62 | /** |
| 63 | * Environment variables available to builds of this branch. |
| 64 | */ |
| 65 | environmentVariables?: Record<string, string>; |
| 66 | /** |
| 67 | * Whether to require basic auth to view the branch's site. |
| 68 | */ |
| 69 | enableBasicAuth?: boolean; |
| 70 | /** |
| 71 | * Basic auth credentials for the branch, as base64 of `user:password`. |
| 72 | */ |
| 73 | basicAuthCredentials?: Redacted.Redacted<string>; |
| 74 | /** |
| 75 | * Build specification (amplify.yml contents) overriding the app's. |
| 76 | */ |
| 77 | buildSpec?: string; |
| 78 | /** |
| 79 | * Content Time-To-Live for the branch's website (wire unit: seconds). |
| 80 | */ |
| 81 | ttl?: Duration.Input; |
| 82 | /** |
| 83 | * Whether pull requests to the (repo-connected) branch create previews. |
| 84 | */ |
| 85 | enablePullRequestPreview?: boolean; |
| 86 | /** |
| 87 | * Amplify environment name used for pull request previews. |
| 88 | */ |
| 89 | pullRequestEnvironmentName?: string; |
| 90 | /** |
| 91 | * User-defined tags to apply to the branch. |
| 92 | */ |
| 93 | tags?: Record<string, string>; |
| 94 | } |
| 95 | |
| 96 | export interface Branch extends Resource< |
| 97 | "AWS.Amplify.Branch", |
| 98 | BranchProps, |
| 99 | { |
| 100 | appId: string; |
| 101 | branchName: string; |
| 102 | branchArn: string; |
| 103 | tags: Record<string, string>; |
| 104 | }, |
| 105 | never, |
| 106 | Providers |
| 107 | > {} |
| 108 | |
| 109 | /** |
| 110 | * A branch of an AWS Amplify Hosting app. |
| 111 | * |
| 112 | * For apps without a connected Git repository, a branch is the target of the |
| 113 | * manual-deploy pipeline: stage a zip with `CreateDeployment`, upload it to |
| 114 | * the pre-signed URL, and release it with `StartDeployment`. |
| 115 | * |
| 116 | * ### Creating Branches |
| 117 | * **Example:** Manual-Deploy Branch |
| 118 | * ```typescript |
| 119 | * const app = yield* App("MySite", { platform: "WEB" }); |
| 120 | * const branch = yield* Branch("Main", { |
| 121 | * appId: app.appId, |
| 122 | * branchName: "main", |
| 123 | * stage: "PRODUCTION", |
| 124 | * enableAutoBuild: false, |
| 125 | * }); |
| 126 | * ``` |
| 127 | * |
| 128 | * **Example:** Password-Protected Branch with Content TTL |
| 129 | * ```typescript |
| 130 | * const branch = yield* Branch("Preview", { |
| 131 | * appId: app.appId, |
| 132 | * branchName: "preview", |
| 133 | * stage: "DEVELOPMENT", |
| 134 | * ttl: "10 minutes", |
| 135 | * enableBasicAuth: true, |
| 136 | * // base64 of "user:password" |
| 137 | * basicAuthCredentials: Redacted.make(credentials), |
| 138 | * }); |
| 139 | * ``` |
| 140 | * |
| 141 | * @resource |
| 142 | */ |
| 143 | export const Branch = Resource<Branch>("AWS.Amplify.Branch"); |
| 144 | |
| 145 | // Amplify throttles control-plane writes account-wide in roughly per-minute |
| 146 | // buckets and surfaces it as a BadRequestException with a "Rate exceeded" |
| 147 | // message (not a throttling error class). A burst elsewhere in the account |
| 148 | // (e.g. a mass delete) can keep the bucket exhausted for most of a minute, so |
| 149 | // spread bounded retries evenly across ~80s instead of front-loading an |
| 150 | // exponential that spends its whole budget in the first few seconds. |
| 151 | const amplifyWriteRetrySchedule = Schedule.max([Schedule.spaced("8 seconds"), Schedule.recurs(10)]); |
| 152 | |
| 153 | export const BranchProvider = () => |
| 154 | Provider.effect( |
| 155 | Branch, |
| 156 | Effect.gen(function* () { |
| 157 | const toName = (id: string, props: { branchName?: string } = {}) => |
| 158 | props.branchName |
| 159 | ? Effect.succeed(props.branchName) |
| 160 | : createPhysicalName({ id, maxLength: 100 }); |
| 161 | |
| 162 | const observe = (appId: string, branchName: string) => |
| 163 | amplify.getBranch({ appId, branchName }).pipe( |
| 164 | Effect.map((r) => r.branch), |
| 165 | // Amplify's API Gateway front door can time out a slow |
| 166 | // control-plane call ("Endpoint request timed out"); reads are |
| 167 | // side-effect free, so retry the typed tag with bounded backoff. |
| 168 | Effect.retry({ |
| 169 | while: (e): boolean => e._tag === "TimeoutException", |
| 170 | schedule: Schedule.exponential("2 seconds"), |
| 171 | times: 3, |
| 172 | }), |
| 173 | Effect.catchTag("NotFoundException", () => Effect.undefined), |
| 174 | ); |
| 175 | |
| 176 | const syncTags = Effect.fn(function* ( |
| 177 | branchArn: string, |
| 178 | desiredTags: Record<string, string>, |
| 179 | observedTags: Record<string, string>, |
| 180 | ) { |
| 181 | const { removed, upsert } = diffTags(observedTags, desiredTags); |
| 182 | if (upsert.length > 0) { |
| 183 | yield* amplify.tagResource({ |
| 184 | resourceArn: branchArn, |
| 185 | tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])), |
| 186 | }); |
| 187 | } |
| 188 | if (removed.length > 0) { |
| 189 | yield* amplify.untagResource({ |
| 190 | resourceArn: branchArn, |
| 191 | tagKeys: removed, |
| 192 | }); |
| 193 | } |
| 194 | }); |
| 195 | |
| 196 | return { |
| 197 | stables: ["appId", "branchName", "branchArn"], |
| 198 | diff: Effect.fn(function* ({ news, olds }) { |
| 199 | if (!isResolved(news)) return; |
| 200 | if (somePropsAreDifferent(olds, news, ["appId", "branchName"])) { |
| 201 | return { action: "replace" }; |
| 202 | } |
| 203 | }), |
| 204 | read: Effect.fn(function* ({ id, output }) { |
| 205 | if (!output?.appId || !output.branchName) return undefined; |
| 206 | const branch = yield* observe(output.appId, output.branchName); |
| 207 | if (!branch) return undefined; |
| 208 | const attrs = { |
| 209 | appId: output.appId, |
| 210 | branchName: branch.branchName, |
| 211 | branchArn: branch.branchArn, |
| 212 | tags: tagRecord(branch.tags), |
| 213 | }; |
| 214 | return (yield* hasAlchemyTags(id, branch.tags)) ? attrs : Unowned(attrs); |
| 215 | }), |
| 216 | reconcile: Effect.fn(function* ({ id, news, session }) { |
| 217 | const branchName = yield* toName(id, news); |
| 218 | const internalTags = yield* createInternalTags(id); |
| 219 | const desiredTags = { ...internalTags, ...news.tags }; |
| 220 | const ttl = news.ttl === undefined ? undefined : String(toWireSeconds(news.ttl)); |
| 221 | |
| 222 | const settings = { |
| 223 | description: news.description, |
| 224 | displayName: news.displayName, |
| 225 | stage: news.stage, |
| 226 | framework: news.framework, |
| 227 | enableAutoBuild: news.enableAutoBuild, |
| 228 | enableSkewProtection: news.enableSkewProtection, |
| 229 | enablePerformanceMode: news.enablePerformanceMode, |
| 230 | environmentVariables: news.environmentVariables, |
| 231 | enableBasicAuth: news.enableBasicAuth, |
| 232 | basicAuthCredentials: news.basicAuthCredentials, |
| 233 | buildSpec: news.buildSpec, |
| 234 | ttl, |
| 235 | enablePullRequestPreview: news.enablePullRequestPreview, |
| 236 | pullRequestEnvironmentName: news.pullRequestEnvironmentName, |
| 237 | }; |
| 238 | |
| 239 | let branch = yield* observe(news.appId, branchName); |
| 240 | |
| 241 | if (!branch) { |
| 242 | // CreateBranch is subject to the account-wide "Rate exceeded" |
| 243 | // throttle (see amplifyWriteRetrySchedule). Its API Gateway |
| 244 | // front door can also time out a slow CreateBranch (typed |
| 245 | // TimeoutException, "Endpoint request timed out") with the |
| 246 | // outcome unknown — re-observe before every (re)try so a |
| 247 | // retry converges on the branch the timed-out call created. |
| 248 | branch = yield* observe(news.appId, branchName).pipe( |
| 249 | Effect.flatMap((existing) => |
| 250 | existing |
| 251 | ? Effect.succeed(existing) |
| 252 | : amplify |
| 253 | .createBranch({ |
| 254 | appId: news.appId, |
| 255 | branchName, |
| 256 | ...settings, |
| 257 | tags: desiredTags, |
| 258 | }) |
| 259 | .pipe(Effect.map((r) => r.branch)), |
| 260 | ), |
| 261 | Effect.retry({ |
| 262 | while: (e): boolean => |
| 263 | e._tag === "TimeoutException" || |
| 264 | (e._tag === "BadRequestException" && (e.message ?? "").includes("Rate exceeded")), |
| 265 | schedule: amplifyWriteRetrySchedule, |
| 266 | }), |
| 267 | ); |
| 268 | } else { |
| 269 | // UpdateBranch is idempotent — retry front-door timeouts and |
| 270 | // the "Rate exceeded" throttle with bounded backoff. |
| 271 | const updated = yield* amplify |
| 272 | .updateBranch({ |
| 273 | appId: news.appId, |
| 274 | branchName, |
| 275 | ...settings, |
| 276 | }) |
| 277 | .pipe( |
| 278 | Effect.retry({ |
| 279 | while: (e): boolean => |
| 280 | e._tag === "TimeoutException" || |
| 281 | (e._tag === "BadRequestException" && |
| 282 | (e.message ?? "").includes("Rate exceeded")), |
| 283 | schedule: amplifyWriteRetrySchedule, |
| 284 | }), |
| 285 | ); |
| 286 | yield* syncTags(updated.branch.branchArn, desiredTags, tagRecord(branch.tags)); |
| 287 | branch = updated.branch; |
| 288 | } |
| 289 | |
| 290 | yield* session.note(branch.branchArn); |
| 291 | return { |
| 292 | appId: news.appId, |
| 293 | branchName: branch.branchName, |
| 294 | branchArn: branch.branchArn, |
| 295 | tags: desiredTags, |
| 296 | }; |
| 297 | }), |
| 298 | list: () => |
| 299 | Effect.gen(function* () { |
| 300 | const apps = yield* amplify.listApps.pages({}).pipe( |
| 301 | Stream.runCollect, |
| 302 | Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.apps ?? [])), |
| 303 | ); |
| 304 | const branches: Array<{ |
| 305 | appId: string; |
| 306 | branchName: string; |
| 307 | branchArn: string; |
| 308 | tags: Record<string, string>; |
| 309 | }> = []; |
| 310 | for (const app of apps) { |
| 311 | const appBranches = yield* amplify.listBranches.pages({ appId: app.appId }).pipe( |
| 312 | Stream.runCollect, |
| 313 | Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.branches ?? [])), |
| 314 | ); |
| 315 | for (const branch of appBranches) { |
| 316 | branches.push({ |
| 317 | appId: app.appId, |
| 318 | branchName: branch.branchName, |
| 319 | branchArn: branch.branchArn, |
| 320 | tags: tagRecord(branch.tags), |
| 321 | }); |
| 322 | } |
| 323 | } |
| 324 | return branches; |
| 325 | }), |
| 326 | delete: Effect.fn(function* ({ output }) { |
| 327 | // DeleteBranch 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 |
| 332 | .deleteBranch({ |
| 333 | appId: output.appId, |
| 334 | branchName: output.branchName, |
| 335 | }) |
| 336 | .pipe( |
| 337 | Effect.retry({ |
| 338 | while: (e): boolean => |
| 339 | e._tag === "TimeoutException" || |
| 340 | (e._tag === "BadRequestException" && (e.message ?? "").includes("Rate exceeded")), |
| 341 | schedule: amplifyWriteRetrySchedule, |
| 342 | }), |
| 343 | Effect.catchTag("NotFoundException", () => Effect.void), |
| 344 | ); |
| 345 | }), |
| 346 | }; |
| 347 | }), |
| 348 | ); |