@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 207 lines 7.94 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 { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
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 ConnectionProps {
14 /**
15 * Name of the connection (1-32 chars). If omitted a deterministic
16 * physical name is generated. Changing the name replaces the connection.
17 */
18 connectionName?: string;
19 /**
20 * Source-provider the connection authenticates against. Changing the
21 * provider replaces the connection.
22 */
23 providerType: "GitHub" | "GitHubEnterpriseServer" | "Bitbucket" | "GitLab" | "GitLabSelfManaged";
24 /**
25 * ARN of a CodeConnections `Host` (required for self-managed providers
26 * such as `GitHubEnterpriseServer` / `GitLabSelfManaged`).
27 */
28 hostArn?: string;
29 /**
30 * User-defined tags.
31 */
32 tags?: Record<string, string>;
33 }
34
35 export interface Connection extends Resource<
36 "AWS.CodeConnections.Connection",
37 ConnectionProps,
38 {
39 /** Physical name of the connection. */
40 connectionName: string;
41 /** ARN of the connection (referenced by CodePipeline source actions). */
42 connectionArn: string;
43 /**
44 * Connection state. A freshly created connection is `PENDING` until the
45 * OAuth handshake is completed manually in the AWS console; it then
46 * becomes `AVAILABLE`.
47 */
48 connectionStatus: string;
49 /** The source provider (`GitHub`, `GitLab`, `Bitbucket`, ...). */
50 providerType: string;
51 },
52 never,
53 Providers
54 > {}
55
56 /**
57 * An AWS CodeConnections connection to a source-code provider (GitHub,
58 * GitLab, Bitbucket).
59 *
60 * A connection is created in the `PENDING` state. Completing it requires a
61 * one-time OAuth handshake performed **manually** in the AWS console (the
62 * "Update pending connection" flow) — there is no API to finish the
63 * handshake. Once completed the connection becomes `AVAILABLE` and can be
64 * referenced by a CodePipeline `CodeStarSourceConnection` action.
65 * ### Creating a Connection
66 * **Example:** GitHub Connection (created PENDING)
67 * ```typescript
68 * const connection = yield* CodeConnections.Connection("GitHub", {
69 * providerType: "GitHub",
70 * });
71 * // connection.connectionStatus === "PENDING"
72 * // Complete the handshake in the console before using it in a pipeline.
73 * ```
74 *
75 * @resource
76 */
77 export const Connection = Resource<Connection>("AWS.CodeConnections.Connection");
78
79 export const ConnectionProvider = () =>
80 Provider.effect(
81 Connection,
82 Effect.gen(function* () {
83 const toName = (id: string, props: Partial<ConnectionProps>) =>
84 props.connectionName
85 ? Effect.succeed(props.connectionName)
86 : createPhysicalName({ id, maxLength: 32 });
87
88 /** Read a connection by ARN; a missing connection reads as absent. */
89 const getByArn = Effect.fn(function* (arn: string) {
90 const response = yield* codeconnections
91 .getConnection({ ConnectionArn: arn })
92 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
93 return response?.Connection;
94 });
95
96 /** Find a connection by name (getConnection only accepts an ARN). */
97 const findByName = Effect.fn(function* (name: string) {
98 const connections = yield* codeconnections.listConnections.pages({}).pipe(
99 Stream.runCollect,
100 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Connections ?? [])),
101 );
102 return connections.find((c) => c.ConnectionName === name);
103 });
104
105 const toAttrs = (connection: codeconnections.Connection, name: string) => ({
106 connectionName: connection.ConnectionName ?? name,
107 connectionArn: connection.ConnectionArn!,
108 connectionStatus: connection.ConnectionStatus ?? "PENDING",
109 providerType: connection.ProviderType ?? "",
110 });
111
112 return {
113 stables: ["connectionName", "connectionArn", "providerType"],
114
115 diff: Effect.fn(function* ({ id, olds, news }) {
116 if (!isResolved(news)) return undefined;
117 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
118 return { action: "replace" } as const;
119 }
120 // Provider type and host are immutable — replace on change.
121 if (
122 (news?.providerType ?? undefined) !== (olds?.providerType ?? undefined) ||
123 (news?.hostArn ?? undefined) !== (olds?.hostArn ?? undefined)
124 ) {
125 return { action: "replace" } as const;
126 }
127 }),
128
129 read: Effect.fn(function* ({ id, olds, output }) {
130 const name = output?.connectionName ?? (yield* toName(id, olds ?? {}));
131 const connection = output?.connectionArn
132 ? yield* getByArn(output.connectionArn)
133 : yield* findByName(name);
134 if (connection?.ConnectionArn === undefined) return undefined;
135 const attrs = toAttrs(connection, name);
136 const tags = yield* fetchObservedTags(attrs.connectionArn);
137 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
138 }),
139
140 reconcile: Effect.fn(function* ({ id, news, output, session }) {
141 const name = output?.connectionName ?? (yield* toName(id, news));
142 const internalTags = yield* createInternalTags(id);
143 const desiredTags = { ...internalTags, ...news.tags };
144
145 // 1. Observe — cloud state is authoritative.
146 let observed = output?.connectionArn
147 ? yield* getByArn(output.connectionArn)
148 : yield* findByName(name);
149
150 // 2. Ensure — connections are immutable; create if missing. The
151 // connection is created in PENDING and its OAuth handshake is
152 // completed manually.
153 if (observed?.ConnectionArn === undefined) {
154 const created = yield* codeconnections.createConnection({
155 ConnectionName: name,
156 ProviderType: news.providerType,
157 HostArn: news.hostArn,
158 Tags: toTagList(desiredTags),
159 });
160 observed = yield* getByArn(created.ConnectionArn);
161 if (observed?.ConnectionArn === undefined) {
162 observed = {
163 ConnectionName: name,
164 ConnectionArn: created.ConnectionArn,
165 ProviderType: news.providerType,
166 ConnectionStatus: "PENDING",
167 };
168 }
169 }
170
171 // 3. Sync tags — diff against OBSERVED cloud tags.
172 yield* syncResourceTags(observed.ConnectionArn!, desiredTags);
173
174 // 4. Return fresh attributes.
175 yield* session.note(name);
176 return toAttrs(observed, name);
177 }),
178
179 delete: Effect.fn(function* ({ output }) {
180 yield* codeconnections
181 .deleteConnection({ ConnectionArn: output.connectionArn })
182 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
183 }),
184
185 list: () =>
186 codeconnections.listConnections.pages({}).pipe(
187 Stream.runCollect,
188 Effect.map((chunk) =>
189 Array.from(chunk)
190 .flatMap((page) => page.Connections ?? [])
191 .flatMap((c) =>
192 c.ConnectionArn !== undefined
193 ? [
194 {
195 connectionName: c.ConnectionName ?? "",
196 connectionArn: c.ConnectionArn,
197 connectionStatus: c.ConnectionStatus ?? "PENDING",
198 providerType: c.ProviderType ?? "",
199 },
200 ]
201 : [],
202 ),
203 ),
204 ),
205 };
206 }),
207 );