@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 241 lines 8.52 KB
Raw
1 import * as codeartifact from "@distilled.cloud/aws/codeartifact";
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 type { Providers } from "../Providers.ts";
12
13 export interface DomainProps {
14 /**
15 * Name of the domain (2-50 chars, lowercase letters, digits and hyphens).
16 * If omitted a deterministic physical name is generated. Changing the name
17 * replaces the domain.
18 */
19 domainName?: string;
20 /**
21 * ARN of a KMS key used to encrypt assets in the domain. Defaults to an
22 * AWS-managed key. Immutable — changing it replaces the domain.
23 */
24 encryptionKey?: string;
25 /**
26 * User-defined tags.
27 */
28 tags?: Record<string, string>;
29 }
30
31 export interface Domain extends Resource<
32 "AWS.CodeArtifact.Domain",
33 DomainProps,
34 {
35 /** Physical name of the domain. */
36 domainName: string;
37 /** ARN of the domain. */
38 domainArn: string;
39 /** AWS account ID that owns the domain. */
40 owner: string;
41 /** Domain status (`Active` or `Deleted`). */
42 status: string;
43 /** ARN of the KMS key used to encrypt assets in the domain. */
44 encryptionKey: string;
45 /** ARN of the S3 bucket backing the domain's asset storage. */
46 s3BucketArn: string;
47 },
48 never,
49 Providers
50 > {}
51
52 /**
53 * An AWS CodeArtifact domain — the top-level container that groups a set of
54 * package repositories and provides a single point for encryption, ownership
55 * and cross-account access control.
56 *
57 * ### Creating a Domain
58 * **Example:** Basic Domain
59 * ```typescript
60 * const domain = yield* CodeArtifact.Domain("packages", {});
61 * ```
62 *
63 * **Example:** Domain with a customer-managed KMS key
64 * ```typescript
65 * const domain = yield* CodeArtifact.Domain("packages", {
66 * domainName: "my-org",
67 * encryptionKey: key.keyArn,
68 * tags: { team: "platform" },
69 * });
70 * ```
71 *
72 * @resource
73 */
74 export const Domain = Resource<Domain>("AWS.CodeArtifact.Domain");
75
76 /** Convert a CodeArtifact wire tag list into a plain record. */
77 const toTagRecord = (
78 tags: ReadonlyArray<{ key?: string; value?: string }> | undefined,
79 ): Record<string, string> =>
80 Object.fromEntries(
81 (tags ?? [])
82 .filter(
83 (tag): tag is { key: string; value: string } =>
84 typeof tag.key === "string" && typeof tag.value === "string",
85 )
86 .map((tag) => [tag.key, tag.value]),
87 );
88
89 export const DomainProvider = () =>
90 Provider.effect(
91 Domain,
92 Effect.gen(function* () {
93 const toName = (id: string, props: Partial<DomainProps>) =>
94 props.domainName
95 ? Effect.succeed(props.domainName)
96 : createPhysicalName({ id, maxLength: 50 });
97
98 const getDomain = Effect.fn(function* (name: string) {
99 const response = yield* codeartifact
100 .describeDomain({ domain: name })
101 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
102 return response?.domain;
103 });
104
105 const toAttrs = (domain: codeartifact.DomainDescription, name: string) => ({
106 domainName: domain.name ?? name,
107 domainArn: domain.arn!,
108 owner: domain.owner ?? "",
109 status: domain.status ?? "Active",
110 encryptionKey: domain.encryptionKey ?? "",
111 s3BucketArn: domain.s3BucketArn ?? "",
112 });
113
114 const syncTags = Effect.fn(function* (arn: string, desiredTags: Record<string, string>) {
115 const observed = yield* codeartifact
116 .listTagsForResource({ resourceArn: arn })
117 .pipe(Effect.orElseSucceed(() => undefined));
118 const { removed, upsert } = diffTags(toTagRecord(observed?.tags), desiredTags);
119 if (upsert.length > 0) {
120 yield* codeartifact.tagResource({
121 resourceArn: arn,
122 tags: upsert.map((t) => ({ key: t.Key, value: t.Value })),
123 });
124 }
125 if (removed.length > 0) {
126 yield* codeartifact.untagResource({
127 resourceArn: arn,
128 tagKeys: removed,
129 });
130 }
131 });
132
133 return {
134 stables: ["domainName", "domainArn", "owner"],
135
136 diff: Effect.fn(function* ({ id, olds, news }) {
137 if (!isResolved(news)) return undefined;
138 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
139 return { action: "replace" } as const;
140 }
141 // The encryption key is immutable — replace on change.
142 if ((news?.encryptionKey ?? undefined) !== (olds?.encryptionKey ?? undefined)) {
143 return { action: "replace" } as const;
144 }
145 }),
146
147 read: Effect.fn(function* ({ id, olds, output }) {
148 const name = output?.domainName ?? (yield* toName(id, olds ?? {}));
149 const domain = yield* getDomain(name);
150 if (domain?.arn === undefined) return undefined;
151 const attrs = toAttrs(domain, name);
152 const tags = yield* codeartifact
153 .listTagsForResource({ resourceArn: attrs.domainArn })
154 .pipe(
155 Effect.map((res) => toTagRecord(res.tags)),
156 Effect.orElseSucceed(() => ({})),
157 );
158 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
159 }),
160
161 reconcile: Effect.fn(function* ({ id, news, output, session }) {
162 const name = output?.domainName ?? (yield* toName(id, news));
163 const internalTags = yield* createInternalTags(id);
164 const desiredTags = { ...internalTags, ...news.tags };
165
166 // 1. Observe — cloud state is authoritative.
167 let observed = yield* getDomain(name);
168
169 // 2. Ensure — domains are immutable; create if missing. Tolerate a
170 // concurrent-create race as an existing domain, and retry through
171 // the deletion-propagation window where a freshly deleted domain
172 // still rejects creates (ConflictException) while describeDomain
173 // already reports it gone.
174 if (observed?.arn === undefined) {
175 observed = yield* codeartifact
176 .createDomain({
177 domain: name,
178 encryptionKey: news.encryptionKey,
179 tags: Object.entries(desiredTags).map(([key, value]) => ({
180 key,
181 value,
182 })),
183 })
184 .pipe(
185 Effect.map((res) => res.domain),
186 Effect.catchTag("ConflictException", () => getDomain(name)),
187 Effect.repeat({
188 until: (domain): boolean => domain?.arn !== undefined,
189 schedule: Schedule.spaced("2 seconds"),
190 times: 10,
191 }),
192 );
193 }
194
195 // 3. Sync tags — diff against OBSERVED cloud tags.
196 yield* syncTags(observed!.arn!, desiredTags);
197
198 // 4. Return fresh attributes.
199 yield* session.note(name);
200 return toAttrs(observed!, name);
201 }),
202
203 delete: Effect.fn(function* ({ output }) {
204 // DeleteDomain is idempotent — deleting a non-existent domain
205 // succeeds (its typed error union has no not-found variant). A
206 // domain whose repositories were deleted moments earlier can
207 // transiently Conflict while those deletions propagate.
208 yield* codeartifact.deleteDomain({ domain: output.domainName }).pipe(
209 Effect.retry({
210 while: (e): boolean => e._tag === "ConflictException",
211 schedule: Schedule.spaced("2 seconds"),
212 times: 10,
213 }),
214 );
215 }),
216
217 list: () =>
218 codeartifact.listDomains.pages({}).pipe(
219 Stream.runCollect,
220 Effect.map((chunk) =>
221 Array.from(chunk)
222 .flatMap((page) => page.domains ?? [])
223 .flatMap((d) =>
224 d.arn !== undefined && d.name !== undefined
225 ? [
226 {
227 domainName: d.name,
228 domainArn: d.arn,
229 owner: d.owner ?? "",
230 status: d.status ?? "Active",
231 encryptionKey: d.encryptionKey ?? "",
232 s3BucketArn: "",
233 },
234 ]
235 : [],
236 ),
237 ),
238 ),
239 };
240 }),
241 );