@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 400 lines 13.1 KB
Raw
1 import * as codepipeline from "@distilled.cloud/aws/codepipeline";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } 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 } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { AWSEnvironment } from "../Environment.ts";
12 import type { Providers } from "../Providers.ts";
13
14 /**
15 * Where a pipeline stores the artifacts it passes between stages.
16 */
17 export interface PipelineArtifactStore {
18 /**
19 * Store type. Only `S3` is supported by CodePipeline.
20 * @default "S3"
21 */
22 type?: "S3";
23 /**
24 * Name of the S3 bucket that holds pipeline artifacts.
25 */
26 location: string;
27 /**
28 * Optional customer-managed KMS key for artifact encryption.
29 */
30 encryptionKey?: {
31 /** Key id or ARN. */
32 id: string;
33 /** Key type. */
34 type: "KMS";
35 };
36 }
37
38 /**
39 * A single action within a stage — a source pull, a build, a deploy, etc.
40 */
41 export interface PipelineActionConfig {
42 /** Unique name of the action within its stage. */
43 name: string;
44 /** Action category. */
45 category: "Source" | "Build" | "Deploy" | "Test" | "Invoke" | "Approval" | "Compute";
46 /** Who owns the action provider. */
47 owner: "AWS" | "ThirdParty" | "Custom";
48 /**
49 * Action provider, e.g. `S3`, `CodeBuild`, `CodeDeploy`,
50 * `CodeStarSourceConnection`.
51 */
52 provider: string;
53 /**
54 * Provider version.
55 * @default "1"
56 */
57 version?: string;
58 /**
59 * Provider-specific configuration key/value map (e.g. `{ ProjectName }`
60 * for CodeBuild, `{ S3Bucket, S3ObjectKey }` for an S3 source).
61 */
62 configuration?: Record<string, string>;
63 /** Names of artifacts this action consumes. */
64 inputArtifacts?: string[];
65 /** Names of artifacts this action produces. */
66 outputArtifacts?: string[];
67 /** Order of execution within the stage (actions with the same order run in parallel). */
68 runOrder?: number;
69 /** Region the action runs in (for cross-region actions). */
70 region?: string;
71 /** IAM role the action assumes. */
72 roleArn?: string;
73 /** Variable namespace for referencing this action's output variables. */
74 namespace?: string;
75 }
76
77 /**
78 * A pipeline stage: a named group of actions.
79 */
80 export interface PipelineStageConfig {
81 /** Unique name of the stage. */
82 name: string;
83 /** Actions that make up the stage. */
84 actions: PipelineActionConfig[];
85 }
86
87 export interface PipelineProps {
88 /**
89 * Name of the pipeline. If omitted a deterministic physical name is
90 * generated. Changing the name replaces the pipeline.
91 */
92 pipelineName?: string;
93 /**
94 * ARN of the IAM role CodePipeline assumes. Must trust
95 * `codepipeline.amazonaws.com`.
96 */
97 roleArn: string;
98 /**
99 * Artifact store for passing outputs between stages.
100 */
101 artifactStore: PipelineArtifactStore;
102 /**
103 * Ordered list of stages. A pipeline needs at least two stages, the first
104 * of which contains a single source action.
105 */
106 stages: PipelineStageConfig[];
107 /**
108 * Pipeline type.
109 * @default "V2"
110 */
111 pipelineType?: "V1" | "V2";
112 /**
113 * Execution mode (V2 pipelines).
114 * @default "SUPERSEDED"
115 */
116 executionMode?: "QUEUED" | "SUPERSEDED" | "PARALLEL";
117 /**
118 * User-defined tags.
119 */
120 tags?: Record<string, string>;
121 }
122
123 export interface Pipeline extends Resource<
124 "AWS.CodePipeline.Pipeline",
125 PipelineProps,
126 {
127 /** Physical name of the pipeline. */
128 pipelineName: string;
129 /** ARN of the pipeline. */
130 pipelineArn: string;
131 /** Version number, incremented by CodePipeline on every structure update. */
132 pipelineVersion: number;
133 },
134 never,
135 Providers
136 > {}
137
138 /**
139 * An AWS CodePipeline continuous-delivery pipeline: an ordered set of
140 * stages, each running one or more actions (source → build → deploy), with
141 * an S3 artifact store carrying outputs between them.
142 *
143 * Defining and updating the pipeline is instant. Pipelines that use a git
144 * source require a CodeConnections connection whose OAuth handshake is
145 * completed manually — use an S3 source to avoid the handshake.
146 * ### Creating a Pipeline
147 * **Example:** S3-Source → CodeBuild Pipeline
148 * ```typescript
149 * const pipeline = yield* CodePipeline.Pipeline("Release", {
150 * roleArn: role.roleArn,
151 * artifactStore: { type: "S3", location: artifactBucket.bucketName },
152 * stages: [
153 * {
154 * name: "Source",
155 * actions: [{
156 * name: "S3Source",
157 * category: "Source",
158 * owner: "AWS",
159 * provider: "S3",
160 * outputArtifacts: ["SourceOutput"],
161 * configuration: {
162 * S3Bucket: sourceBucket.bucketName,
163 * S3ObjectKey: "source.zip",
164 * PollForSourceChanges: "false",
165 * },
166 * }],
167 * },
168 * {
169 * name: "Build",
170 * actions: [{
171 * name: "Build",
172 * category: "Build",
173 * owner: "AWS",
174 * provider: "CodeBuild",
175 * inputArtifacts: ["SourceOutput"],
176 * configuration: { ProjectName: project.projectName },
177 * }],
178 * },
179 * ],
180 * });
181 * ```
182 *
183 * @resource
184 */
185 export const Pipeline = Resource<Pipeline>("AWS.CodePipeline.Pipeline");
186
187 /** Convert a CodePipeline wire tag list into a plain record. */
188 const toTagRecord = (
189 tags: ReadonlyArray<{ key?: string; value?: string }> | undefined,
190 ): Record<string, string> =>
191 Object.fromEntries(
192 (tags ?? [])
193 .filter(
194 (tag): tag is { key: string; value: string } =>
195 typeof tag.key === "string" && typeof tag.value === "string",
196 )
197 .map((tag) => [tag.key, tag.value]),
198 );
199
200 const toWireArtifactStore = (store: PipelineArtifactStore): codepipeline.ArtifactStore => ({
201 type: store.type ?? "S3",
202 location: store.location,
203 encryptionKey: store.encryptionKey,
204 });
205
206 const toWireStages = (stages: PipelineStageConfig[]): codepipeline.StageDeclaration[] =>
207 stages.map((stage) => ({
208 name: stage.name,
209 actions: stage.actions.map((action) => ({
210 name: action.name,
211 actionTypeId: {
212 category: action.category,
213 owner: action.owner,
214 provider: action.provider,
215 version: action.version ?? "1",
216 },
217 runOrder: action.runOrder,
218 configuration: action.configuration,
219 inputArtifacts: action.inputArtifacts?.map((n) => ({ name: n })),
220 outputArtifacts: action.outputArtifacts?.map((n) => ({ name: n })),
221 region: action.region,
222 roleArn: action.roleArn,
223 namespace: action.namespace,
224 })),
225 }));
226
227 const toWireDeclaration = (
228 name: string,
229 props: PipelineProps,
230 ): codepipeline.PipelineDeclaration => ({
231 name,
232 roleArn: props.roleArn,
233 artifactStore: toWireArtifactStore(props.artifactStore),
234 stages: toWireStages(props.stages),
235 pipelineType: props.pipelineType ?? "V2",
236 executionMode: props.executionMode,
237 });
238
239 /**
240 * CodePipeline validates the pipeline role at create time; a freshly created
241 * IAM role is not yet assumable, surfacing as an `InvalidStructureException`
242 * whose message mentions the role cannot be assumed / is not authorized.
243 * Retry (bounded) through IAM propagation. The explicit return annotation
244 * keeps the retry's conditional type out of declaration emit (PATTERNS §7).
245 */
246 const retryIamPropagation = <A, E extends { readonly _tag: string; readonly message?: string }, R>(
247 effect: Effect.Effect<A, E, R>,
248 ): Effect.Effect<A, E, R> =>
249 effect.pipe(
250 Effect.retry({
251 while: (e) => {
252 const message = (e.message ?? "").toLowerCase();
253 return (
254 e._tag === "InvalidStructureException" &&
255 (message.includes("not authorized") ||
256 message.includes("cannot be assumed") ||
257 message.includes("unable to assume"))
258 );
259 },
260 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(10)]),
261 }),
262 );
263
264 export const PipelineProvider = () =>
265 Provider.effect(
266 Pipeline,
267 Effect.gen(function* () {
268 const toName = (id: string, props: Partial<PipelineProps>) =>
269 props.pipelineName
270 ? Effect.succeed(props.pipelineName)
271 : createPhysicalName({ id, maxLength: 100 });
272
273 /** Read a pipeline; a missing pipeline reads as absent. */
274 const getPipeline = Effect.fn(function* (name: string) {
275 return yield* codepipeline
276 .getPipeline({ name })
277 .pipe(Effect.catchTag("PipelineNotFoundException", () => Effect.undefined));
278 });
279
280 const syncTags = Effect.fn(function* (arn: string, desiredTags: Record<string, string>) {
281 const observed = yield* codepipeline
282 .listTagsForResource({ resourceArn: arn })
283 .pipe(Effect.orElseSucceed(() => undefined));
284 const { removed, upsert } = diffTags(toTagRecord(observed?.tags), desiredTags);
285 if (upsert.length > 0) {
286 yield* codepipeline.tagResource({
287 resourceArn: arn,
288 tags: upsert.map(({ Key, Value }) => ({ key: Key, value: Value })),
289 });
290 }
291 if (removed.length > 0) {
292 yield* codepipeline.untagResource({
293 resourceArn: arn,
294 tagKeys: removed,
295 });
296 }
297 });
298
299 return {
300 stables: ["pipelineName", "pipelineArn"],
301
302 diff: Effect.fn(function* ({ id, olds, news }) {
303 if (!isResolved(news)) return undefined;
304 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
305 return { action: "replace" } as const;
306 }
307 }),
308
309 read: Effect.fn(function* ({ id, olds, output }) {
310 const name = output?.pipelineName ?? (yield* toName(id, olds ?? {}));
311 const found = yield* getPipeline(name);
312 if (found?.metadata?.pipelineArn === undefined) return undefined;
313 const attrs = {
314 pipelineName: found.pipeline?.name ?? name,
315 pipelineArn: found.metadata.pipelineArn,
316 pipelineVersion: found.pipeline?.version ?? 1,
317 };
318 const tags = yield* codepipeline
319 .listTagsForResource({ resourceArn: attrs.pipelineArn })
320 .pipe(
321 Effect.map((res) => toTagRecord(res.tags)),
322 Effect.orElseSucceed(() => ({})),
323 );
324 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
325 }),
326
327 reconcile: Effect.fn(function* ({ id, news, output, session }) {
328 const { accountId, region } = yield* AWSEnvironment.current;
329 const name = output?.pipelineName ?? (yield* toName(id, news));
330 const internalTags = yield* createInternalTags(id);
331 const desiredTags = { ...internalTags, ...news.tags };
332 const declaration = toWireDeclaration(name, news);
333
334 // 1. Observe — cloud state is authoritative.
335 let observed = yield* getPipeline(name);
336
337 // 2. Ensure — create if missing; tolerate the name-in-use race.
338 if (observed === undefined) {
339 yield* retryIamPropagation(
340 codepipeline.createPipeline({
341 pipeline: declaration,
342 tags: Object.entries(desiredTags).map(([key, value]) => ({
343 key,
344 value,
345 })),
346 }),
347 ).pipe(Effect.catchTag("PipelineNameInUseException", () => Effect.void));
348 observed = yield* getPipeline(name);
349 } else {
350 // 3. Sync — updatePipeline is a full upsert of the declaration.
351 yield* retryIamPropagation(codepipeline.updatePipeline({ pipeline: declaration }));
352 observed = yield* getPipeline(name);
353 }
354
355 const arn =
356 observed?.metadata?.pipelineArn ??
357 `arn:aws:codepipeline:${region}:${accountId}:${name}`;
358
359 // 3b. Sync tags — diff against OBSERVED cloud tags.
360 yield* syncTags(arn, desiredTags);
361
362 // 4. Return fresh attributes.
363 yield* session.note(name);
364 return {
365 pipelineName: observed?.pipeline?.name ?? name,
366 pipelineArn: arn,
367 pipelineVersion: observed?.pipeline?.version ?? 1,
368 };
369 }),
370
371 delete: Effect.fn(function* ({ output }) {
372 // deletePipeline is idempotent — a missing pipeline returns success.
373 yield* codepipeline.deletePipeline({ name: output.pipelineName });
374 }),
375
376 list: () =>
377 codepipeline.listPipelines.pages({}).pipe(
378 Stream.runCollect,
379 Effect.flatMap((chunk) =>
380 Effect.gen(function* () {
381 const { accountId, region } = yield* AWSEnvironment.current;
382 return Array.from(chunk)
383 .flatMap((page) => page.pipelines ?? [])
384 .flatMap((p) =>
385 p.name !== undefined
386 ? [
387 {
388 pipelineName: p.name,
389 pipelineArn: `arn:aws:codepipeline:${region}:${accountId}:${p.name}`,
390 pipelineVersion: p.version ?? 1,
391 },
392 ]
393 : [],
394 );
395 }),
396 ),
397 ),
398 };
399 }),
400 );