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

main
ts 310 lines 11.2 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 Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12 import { fetchObservedTags, syncResourceTags, toTagList } from "./internal.ts";
13
14 /**
15 * VPC configuration provisioned for a {@link Host} whose self-managed
16 * provider is only reachable from inside a VPC.
17 */
18 export interface HostVpcConfiguration {
19 /**
20 * ID of the VPC connected to the provider's infrastructure.
21 */
22 vpcId: string;
23 /**
24 * IDs of the subnets associated with the VPC.
25 */
26 subnetIds: string[];
27 /**
28 * IDs of the security groups associated with the VPC.
29 */
30 securityGroupIds: string[];
31 /**
32 * PEM value of the TLS certificate used by the provider's infrastructure,
33 * for endpoints served with a self-signed or private CA certificate.
34 * This is public certificate material (not a private key).
35 */
36 tlsCertificate?: string;
37 }
38
39 export interface HostProps {
40 /**
41 * Name of the host (1-64 chars). If omitted a deterministic physical name
42 * is generated. Changing the name replaces the host.
43 */
44 name?: string;
45 /**
46 * The self-managed source provider the host is installed on. Changing the
47 * provider replaces the host.
48 */
49 providerType: "GitHubEnterpriseServer" | "GitLabSelfManaged";
50 /**
51 * Endpoint of the infrastructure the provider is installed on, e.g.
52 * `https://ghe.example.com`.
53 */
54 providerEndpoint: string;
55 /**
56 * VPC configuration to provision for the host when the provider endpoint
57 * is only reachable from inside a VPC.
58 */
59 vpcConfiguration?: HostVpcConfiguration;
60 /**
61 * User-defined tags.
62 */
63 tags?: Record<string, string>;
64 }
65
66 export interface Host extends Resource<
67 "AWS.CodeConnections.Host",
68 HostProps,
69 {
70 /** Physical name of the host. */
71 hostName: string;
72 /** ARN of the host (passed as `hostArn` to a `Connection`). */
73 hostArn: string;
74 /**
75 * Host state. A freshly created host is `PENDING` until its setup is
76 * completed **manually** in the AWS console; it then becomes
77 * `AVAILABLE`.
78 */
79 hostStatus: string;
80 /** The self-managed source provider. */
81 providerType: string;
82 /** Endpoint of the provider's infrastructure. */
83 providerEndpoint: string;
84 },
85 never,
86 Providers
87 > {}
88
89 /**
90 * An AWS CodeConnections host — the infrastructure representation of a
91 * self-managed source provider (GitHub Enterprise Server or GitLab
92 * self-managed). One host serves all connections to that provider.
93 *
94 * A host is created in the `PENDING` state. Completing it requires a
95 * one-time setup performed **manually** in the AWS console — there is no
96 * API to finish the setup. Once completed the host becomes `AVAILABLE` and
97 * `Connection`s can reference it via `hostArn`.
98 * ### Creating a Host
99 * **Example:** GitHub Enterprise Server Host (created PENDING)
100 * ```typescript
101 * const host = yield* CodeConnections.Host("GHE", {
102 * providerType: "GitHubEnterpriseServer",
103 * providerEndpoint: "https://ghe.example.com",
104 * });
105 * // host.hostStatus === "PENDING"
106 * // Complete the setup in the console before creating connections on it.
107 * ```
108 *
109 * **Example:** Connection on a Host
110 * ```typescript
111 * const connection = yield* CodeConnections.Connection("GHEConn", {
112 * providerType: "GitHubEnterpriseServer",
113 * hostArn: host.hostArn,
114 * });
115 * ```
116 *
117 * ### Reaching a Private Endpoint
118 * **Example:** Host with VPC Configuration
119 * ```typescript
120 * const host = yield* CodeConnections.Host("PrivateGHE", {
121 * providerType: "GitHubEnterpriseServer",
122 * providerEndpoint: "https://ghe.internal.example.com",
123 * vpcConfiguration: {
124 * vpcId: vpc.vpcId,
125 * subnetIds: [subnetA.subnetId, subnetB.subnetId],
126 * securityGroupIds: [securityGroup.securityGroupId],
127 * },
128 * });
129 * ```
130 *
131 * @resource
132 */
133 export const Host = Resource<Host>("AWS.CodeConnections.Host");
134
135 const toWireVpcConfiguration = (
136 vpc: HostVpcConfiguration | undefined,
137 ): codeconnections.VpcConfiguration | undefined =>
138 vpc === undefined
139 ? undefined
140 : {
141 VpcId: vpc.vpcId,
142 SubnetIds: vpc.subnetIds,
143 SecurityGroupIds: vpc.securityGroupIds,
144 TlsCertificate: vpc.tlsCertificate,
145 };
146
147 const sameVpcConfiguration = (
148 observed: codeconnections.VpcConfiguration | undefined,
149 desired: codeconnections.VpcConfiguration | undefined,
150 ): boolean =>
151 observed?.VpcId === desired?.VpcId &&
152 JSON.stringify([...(observed?.SubnetIds ?? [])].sort()) ===
153 JSON.stringify([...(desired?.SubnetIds ?? [])].sort()) &&
154 JSON.stringify([...(observed?.SecurityGroupIds ?? [])].sort()) ===
155 JSON.stringify([...(desired?.SecurityGroupIds ?? [])].sort()) &&
156 (observed?.TlsCertificate ?? undefined) === (desired?.TlsCertificate ?? undefined);
157
158 export const HostProvider = () =>
159 Provider.effect(
160 Host,
161 Effect.gen(function* () {
162 const toName = (id: string, props: Partial<HostProps>) =>
163 props.name ? Effect.succeed(props.name) : createPhysicalName({ id, maxLength: 64 });
164
165 /**
166 * Read a host by ARN; a missing host reads as absent. `GetHost` does
167 * not echo the ARN back, so it is re-attached from the input.
168 */
169 const getByArn = Effect.fn(function* (arn: string) {
170 const response = yield* codeconnections
171 .getHost({ HostArn: arn })
172 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
173 return response === undefined
174 ? undefined
175 : ({ ...response, HostArn: arn } satisfies codeconnections.Host);
176 });
177
178 /** Find a host by name (getHost only accepts an ARN). */
179 const findByName = Effect.fn(function* (name: string) {
180 const hosts = yield* codeconnections.listHosts.pages({}).pipe(
181 Stream.runCollect,
182 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Hosts ?? [])),
183 );
184 return hosts.find((h) => h.Name === name);
185 });
186
187 const toAttrs = (host: codeconnections.Host, name: string) => ({
188 hostName: host.Name ?? name,
189 hostArn: host.HostArn!,
190 hostStatus: host.Status ?? "PENDING",
191 providerType: host.ProviderType ?? "",
192 providerEndpoint: host.ProviderEndpoint ?? "",
193 });
194
195 return {
196 stables: ["hostName", "hostArn", "providerType"],
197
198 diff: Effect.fn(function* ({ id, olds, news }) {
199 if (!isResolved(news)) return undefined;
200 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
201 return { action: "replace" } as const;
202 }
203 // Provider type is immutable — replace on change. Endpoint and VPC
204 // configuration are mutable via UpdateHost.
205 if ((news?.providerType ?? undefined) !== (olds?.providerType ?? undefined)) {
206 return { action: "replace" } as const;
207 }
208 }),
209
210 read: Effect.fn(function* ({ id, olds, output }) {
211 const name = output?.hostName ?? (yield* toName(id, olds ?? {}));
212 const host = output?.hostArn ? yield* getByArn(output.hostArn) : yield* findByName(name);
213 if (host?.HostArn === undefined) return undefined;
214 const attrs = toAttrs(host, name);
215 const tags = yield* fetchObservedTags(attrs.hostArn);
216 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
217 }),
218
219 reconcile: Effect.fn(function* ({ id, news, output, session }) {
220 const name = output?.hostName ?? (yield* toName(id, news));
221 const internalTags = yield* createInternalTags(id);
222 const desiredTags = { ...internalTags, ...news.tags };
223 const desiredVpc = toWireVpcConfiguration(news.vpcConfiguration);
224
225 // 1. Observe — cloud state is authoritative.
226 let observed = output?.hostArn
227 ? yield* getByArn(output.hostArn)
228 : yield* findByName(name);
229
230 // 2. Ensure — create if missing. The host is created PENDING and
231 // its setup is completed manually in the console.
232 if (observed?.HostArn === undefined) {
233 const created = yield* codeconnections.createHost({
234 Name: name,
235 ProviderType: news.providerType,
236 ProviderEndpoint: news.providerEndpoint,
237 VpcConfiguration: desiredVpc,
238 Tags: toTagList(desiredTags),
239 });
240 observed = created.HostArn ? yield* getByArn(created.HostArn) : yield* findByName(name);
241 if (observed?.HostArn === undefined) {
242 observed = {
243 Name: name,
244 HostArn: created.HostArn,
245 ProviderType: news.providerType,
246 ProviderEndpoint: news.providerEndpoint,
247 VpcConfiguration: desiredVpc,
248 Status: "PENDING",
249 };
250 }
251 }
252
253 // 3. Sync — endpoint + VPC configuration, diffed against OBSERVED
254 // cloud state; skip the API entirely on no-op.
255 if (
256 observed.ProviderEndpoint !== news.providerEndpoint ||
257 !sameVpcConfiguration(observed.VpcConfiguration, desiredVpc)
258 ) {
259 yield* codeconnections.updateHost({
260 HostArn: observed.HostArn!,
261 ProviderEndpoint: news.providerEndpoint,
262 VpcConfiguration: desiredVpc,
263 });
264 observed = (yield* getByArn(observed.HostArn!)) ?? observed;
265 }
266
267 // 4. Sync tags — diff against OBSERVED cloud tags.
268 yield* syncResourceTags(observed.HostArn!, desiredTags);
269
270 yield* session.note(name);
271 return toAttrs(observed, name);
272 }),
273
274 delete: Effect.fn(function* ({ output }) {
275 // A host cannot be deleted while its VPC configuration is
276 // initializing/deleting — retry the transient state, bounded.
277 yield* codeconnections.deleteHost({ HostArn: output.hostArn }).pipe(
278 Effect.retry({
279 while: (e): boolean => e._tag === "ResourceUnavailableException",
280 schedule: Schedule.exponential("2 seconds"),
281 times: 8,
282 }),
283 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
284 );
285 }),
286
287 list: () =>
288 codeconnections.listHosts.pages({}).pipe(
289 Stream.runCollect,
290 Effect.map((chunk) =>
291 Array.from(chunk)
292 .flatMap((page) => page.Hosts ?? [])
293 .flatMap((h) =>
294 h.HostArn !== undefined
295 ? [
296 {
297 hostName: h.Name ?? "",
298 hostArn: h.HostArn,
299 hostStatus: h.Status ?? "PENDING",
300 providerType: h.ProviderType ?? "",
301 providerEndpoint: h.ProviderEndpoint ?? "",
302 },
303 ]
304 : [],
305 ),
306 ),
307 ),
308 };
309 }),
310 );