The best way to control Claude Code, Codex and more from any computer or phone

main
ts 255 lines 9.48 KB
Raw
1 import * as codeconnections from "@distilled.cloud/aws/codeconnections";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11 import { fetchObservedTags, syncResourceTags, toTagList } from "./internal.ts";
12
13 export interface RepositoryLinkProps {
14 /**
15 * ARN of the connection to the external provider. The connection must be
16 * in the `AVAILABLE` state (its OAuth handshake completed in the console).
17 */
18 connectionArn: string;
19 /**
20 * Owner ID of the repository — the GitHub organization/user or GitLab
21 * group/user that owns the repository. Changing the owner replaces the
22 * link.
23 */
24 ownerId: string;
25 /**
26 * Name of the repository to link. Changing the repository replaces the
27 * link.
28 */
29 repositoryName: string;
30 /**
31 * ARN of the KMS key used to encrypt the repository link's sync content.
32 */
33 encryptionKeyArn?: string;
34 /**
35 * User-defined tags.
36 */
37 tags?: Record<string, string>;
38 }
39
40 export interface RepositoryLink extends Resource<
41 "AWS.CodeConnections.RepositoryLink",
42 RepositoryLinkProps,
43 {
44 /** Unique ID of the repository link (used by sync operations). */
45 repositoryLinkId: string;
46 /** ARN of the repository link. */
47 repositoryLinkArn: string;
48 /** ARN of the connection the link authenticates through. */
49 connectionArn: string;
50 /** Owner ID of the linked repository. */
51 ownerId: string;
52 /** Name of the linked repository. */
53 repositoryName: string;
54 /** The source provider (`GitHub`, `GitLab`, ...). */
55 providerType: string;
56 /** ARN of the KMS key encrypting the link's sync content, if any. */
57 encryptionKeyArn: string | undefined;
58 },
59 never,
60 Providers
61 > {}
62
63 /**
64 * An AWS CodeConnections repository link — associates a connection with a
65 * specific external Git repository so Git sync can monitor and sync changes
66 * (e.g. CloudFormation git sync).
67 *
68 * Requires a connection in the `AVAILABLE` state; the connection's OAuth
69 * handshake is a one-time **manual** console step.
70 * ### Linking a Repository
71 * **Example:** Link a GitHub Repository
72 * ```typescript
73 * const link = yield* CodeConnections.RepositoryLink("Repo", {
74 * connectionArn: connection.connectionArn,
75 * ownerId: "my-github-org",
76 * repositoryName: "my-repo",
77 * });
78 * ```
79 *
80 * **Example:** Encrypted Repository Link
81 * ```typescript
82 * const link = yield* CodeConnections.RepositoryLink("Repo", {
83 * connectionArn: connection.connectionArn,
84 * ownerId: "my-github-org",
85 * repositoryName: "my-repo",
86 * encryptionKeyArn: key.keyArn,
87 * });
88 * ```
89 *
90 * @resource
91 */
92 export const RepositoryLink = Resource<RepositoryLink>("AWS.CodeConnections.RepositoryLink");
93
94 export const RepositoryLinkProvider = () =>
95 Provider.effect(
96 RepositoryLink,
97 Effect.gen(function* () {
98 /** Read a repository link by ID; a missing link reads as absent. */
99 const getById = Effect.fn(function* (id: string) {
100 const response = yield* codeconnections
101 .getRepositoryLink({ RepositoryLinkId: id })
102 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
103 return response?.RepositoryLinkInfo;
104 });
105
106 /**
107 * Find a repository link by its identity — owner + repository name
108 * (getRepositoryLink only accepts an ID).
109 */
110 const findByIdentity = Effect.fn(function* (ownerId: string, repositoryName: string) {
111 const links = yield* codeconnections.listRepositoryLinks.pages({}).pipe(
112 Stream.runCollect,
113 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.RepositoryLinks ?? [])),
114 );
115 return links.find(
116 (link) => link.OwnerId === ownerId && link.RepositoryName === repositoryName,
117 );
118 });
119
120 const toAttrs = (link: codeconnections.RepositoryLinkInfo) => ({
121 repositoryLinkId: link.RepositoryLinkId,
122 repositoryLinkArn: link.RepositoryLinkArn,
123 connectionArn: link.ConnectionArn,
124 ownerId: link.OwnerId,
125 repositoryName: link.RepositoryName,
126 providerType: link.ProviderType ?? "",
127 encryptionKeyArn: link.EncryptionKeyArn,
128 });
129
130 return {
131 stables: [
132 "repositoryLinkId",
133 "repositoryLinkArn",
134 "ownerId",
135 "repositoryName",
136 "providerType",
137 ],
138
139 diff: Effect.fn(function* ({ olds, news }) {
140 if (!isResolved(news)) return undefined;
141 // The linked repository is the link's identity — replace on change.
142 // Connection and encryption key are mutable via UpdateRepositoryLink.
143 if (
144 (news?.ownerId ?? undefined) !== (olds?.ownerId ?? undefined) ||
145 (news?.repositoryName ?? undefined) !== (olds?.repositoryName ?? undefined)
146 ) {
147 return { action: "replace" } as const;
148 }
149 }),
150
151 read: Effect.fn(function* ({ id, olds, output }) {
152 const link = output?.repositoryLinkId
153 ? yield* getById(output.repositoryLinkId)
154 : olds?.ownerId && olds?.repositoryName
155 ? yield* findByIdentity(olds.ownerId, olds.repositoryName)
156 : undefined;
157 if (link === undefined) return undefined;
158 const attrs = toAttrs(link);
159 const tags = yield* fetchObservedTags(attrs.repositoryLinkArn);
160 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
161 }),
162
163 reconcile: Effect.fn(function* ({ id, news, output, session }) {
164 const internalTags = yield* createInternalTags(id);
165 const desiredTags = { ...internalTags, ...news.tags };
166
167 // 1. Observe — cloud state is authoritative.
168 let observed = output?.repositoryLinkId
169 ? yield* getById(output.repositoryLinkId)
170 : yield* findByIdentity(news.ownerId, news.repositoryName);
171
172 // 2. Ensure — create if missing; tolerate the AlreadyExists race.
173 if (observed === undefined) {
174 observed = yield* codeconnections
175 .createRepositoryLink({
176 ConnectionArn: news.connectionArn,
177 OwnerId: news.ownerId,
178 RepositoryName: news.repositoryName,
179 EncryptionKeyArn: news.encryptionKeyArn,
180 Tags: toTagList(desiredTags),
181 })
182 .pipe(
183 Effect.map((res) => res.RepositoryLinkInfo),
184 Effect.catchTag("ResourceAlreadyExistsException", (error) =>
185 findByIdentity(news.ownerId, news.repositoryName).pipe(
186 Effect.flatMap((link) =>
187 link === undefined
188 ? // The race lost and the winner is not visible yet —
189 // surface the typed conflict; the engine retries.
190 Effect.fail(error)
191 : Effect.succeed(link),
192 ),
193 ),
194 ),
195 );
196 }
197
198 // 3. Sync — connection + encryption key, diffed against OBSERVED
199 // cloud state; skip the API entirely on no-op.
200 if (
201 observed.ConnectionArn !== news.connectionArn ||
202 (observed.EncryptionKeyArn ?? undefined) !== (news.encryptionKeyArn ?? undefined)
203 ) {
204 const updated = yield* codeconnections.updateRepositoryLink({
205 RepositoryLinkId: observed.RepositoryLinkId,
206 ConnectionArn: news.connectionArn,
207 EncryptionKeyArn: news.encryptionKeyArn,
208 });
209 observed = updated.RepositoryLinkInfo;
210 }
211
212 // 4. Sync tags — diff against OBSERVED cloud tags.
213 yield* syncResourceTags(observed.RepositoryLinkArn, desiredTags);
214
215 yield* session.note(`${news.ownerId}/${news.repositoryName}`);
216 return toAttrs(observed);
217 }),
218
219 delete: Effect.fn(function* ({ output }) {
220 // Sync configurations on the link must be deleted first — retry
221 // the dependency violation while downstream deletions land.
222 yield* codeconnections
223 .deleteRepositoryLink({
224 RepositoryLinkId: output.repositoryLinkId,
225 })
226 .pipe(
227 Effect.retry({
228 while: (e): boolean => e._tag === "SyncConfigurationStillExistsException",
229 schedule: Schedule.exponential("2 seconds"),
230 times: 8,
231 }),
232 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
233 );
234 }),
235
236 list: () =>
237 codeconnections.listRepositoryLinks.pages({}).pipe(
238 Stream.runCollect,
239 Effect.map((chunk) =>
240 Array.from(chunk)
241 .flatMap((page) => page.RepositoryLinks ?? [])
242 .map((link) => ({
243 repositoryLinkId: link.RepositoryLinkId,
244 repositoryLinkArn: link.RepositoryLinkArn,
245 connectionArn: link.ConnectionArn,
246 ownerId: link.OwnerId,
247 repositoryName: link.RepositoryName,
248 providerType: link.ProviderType ?? "",
249 encryptionKeyArn: link.EncryptionKeyArn,
250 })),
251 ),
252 ),
253 };
254 }),
255 );