@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, 06:00 UTC

main
ts 1,120 lines 39 KB
Raw
1 import * as cloudbuild from "@distilled.cloud/gcp/cloudbuild_v2";
2 import type { GcpOpContext } from "@distilled.cloud/gcp/Protocol";
3 import { Unowned } from "alchemy/AdoptPolicy";
4 import { isResolved } from "alchemy/Diff";
5 import { createPhysicalName } from "alchemy/PhysicalName";
6 import * as Provider from "alchemy/Provider";
7 import { Resource } from "alchemy/Resource";
8 import { tagRecord } from "alchemy/Tags";
9 import * as Data from "effect/Data";
10 import * as Effect from "effect/Effect";
11 import * as Schedule from "effect/Schedule";
12 import * as Stream from "effect/Stream";
13 import { GcpEnvironment } from "../Environment.ts";
14 import {
15 createInternalLabels,
16 diffLabels,
17 hasAlchemyLabels,
18 stripInternalLabels,
19 toLabels,
20 } from "../Labels.ts";
21 import { waitForOperation as waitForLongRunningOperation } from "../Operation.ts";
22 import type { Providers } from "../Providers.ts";
23
24 const MAX_NAME_LENGTH = 63;
25
26 export type OAuthCredential = {
27 /**
28 * Secret Manager resource containing the OAuth token that authorizes the
29 * Cloud Build GitHub App, as
30 * `projects/{project}/secrets/{secret}/versions/{version}`.
31 */
32 oauthTokenSecretVersion?: string;
33 };
34
35 export type GitHubConfig = {
36 /**
37 * OAuth credential of the account that authorized the Cloud Build GitHub
38 * App. Prefer a robot account. The token must be tied to the Cloud Build
39 * GitHub App.
40 */
41 authorizerCredential?: OAuthCredential;
42 /**
43 * GitHub App installation id.
44 */
45 appInstallationId?: string;
46 };
47
48 export type ServiceDirectoryConfig = {
49 /**
50 * Service Directory service used to reach a private host, as
51 * `projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}`.
52 */
53 service?: string;
54 };
55
56 export type UserCredential = {
57 /**
58 * Secret Manager resource containing the user token, as
59 * `projects/{project}/secrets/{secret}/versions/{version}`.
60 */
61 userTokenSecretVersion?: string;
62 };
63
64 export type GitHubEnterpriseConfig = {
65 /**
66 * URI of the GitHub Enterprise host. Immutable — changing it replaces
67 * the connection.
68 */
69 hostUri?: string;
70 /**
71 * API key used to authenticate webhook events.
72 */
73 apiKey?: string;
74 /**
75 * Id of the GitHub App created from the manifest.
76 */
77 appId?: string;
78 /**
79 * URL-friendly name of the GitHub App.
80 */
81 appSlug?: string;
82 /**
83 * Secret Manager resource containing the GitHub App private key, as
84 * `projects/{project}/secrets/{secret}/versions/{version}`.
85 */
86 privateKeySecretVersion?: string;
87 /**
88 * Secret Manager resource containing the GitHub App webhook secret, as
89 * `projects/{project}/secrets/{secret}/versions/{version}`.
90 */
91 webhookSecretSecretVersion?: string;
92 /**
93 * Installation id of the GitHub App.
94 */
95 appInstallationId?: string;
96 /**
97 * Service Directory config for a private GitHub Enterprise host.
98 */
99 serviceDirectoryConfig?: ServiceDirectoryConfig;
100 /**
101 * SSL certificate used for requests to GitHub Enterprise.
102 */
103 sslCa?: string;
104 };
105
106 export type GitLabConfig = {
107 /**
108 * GitLab host URI. Defaults to `https://gitlab.com`. Immutable —
109 * changing it replaces the connection.
110 */
111 hostUri?: string;
112 /**
113 * Secret Manager resource containing the webhook secret, as
114 * `projects/{project}/secrets/{secret}/versions/{version}`. Immutable —
115 * changing it replaces the connection.
116 */
117 webhookSecretSecretVersion?: string;
118 /**
119 * GitLab personal access token with at least `read_api` scope.
120 */
121 readAuthorizerCredential?: UserCredential;
122 /**
123 * GitLab personal access token with `api` scope.
124 */
125 authorizerCredential?: UserCredential;
126 /**
127 * Service Directory config for a private GitLab Enterprise host.
128 */
129 serviceDirectoryConfig?: ServiceDirectoryConfig;
130 /**
131 * SSL certificate used for requests to GitLab Enterprise.
132 */
133 sslCa?: string;
134 };
135
136 export type BitbucketDataCenterConfig = {
137 /**
138 * URI of the Bitbucket Data Center instance. Immutable — changing it
139 * replaces the connection.
140 */
141 hostUri?: string;
142 /**
143 * Secret Manager resource containing the webhook secret, as
144 * `projects/{project}/secrets/{secret}/versions/{version}`. Immutable —
145 * changing it replaces the connection.
146 */
147 webhookSecretSecretVersion?: string;
148 /**
149 * HTTP access token with `REPO_READ` access.
150 */
151 readAuthorizerCredential?: UserCredential;
152 /**
153 * HTTP access token with `REPO_ADMIN` access.
154 */
155 authorizerCredential?: UserCredential;
156 /**
157 * Service Directory config for a private Bitbucket Data Center host.
158 */
159 serviceDirectoryConfig?: ServiceDirectoryConfig;
160 /**
161 * SSL certificate used for requests to Bitbucket Data Center.
162 */
163 sslCa?: string;
164 };
165
166 export type BitbucketCloudConfig = {
167 /**
168 * Bitbucket Cloud workspace id. Immutable — changing it replaces the
169 * connection.
170 */
171 workspace?: string;
172 /**
173 * Secret Manager resource containing the webhook secret, as
174 * `projects/{project}/secrets/{secret}/versions/{version}`. Immutable —
175 * changing it replaces the connection.
176 */
177 webhookSecretSecretVersion?: string;
178 /**
179 * Access token with `repository` access.
180 */
181 readAuthorizerCredential?: UserCredential;
182 /**
183 * Access token with `webhook`, `repository`, `repository:admin`, and
184 * `pullrequest` scope.
185 */
186 authorizerCredential?: UserCredential;
187 };
188
189 export type InstallationState = {
190 /** Current step of the installation process. */
191 stage?: string;
192 /** Message describing the next user action, if any. */
193 message?: string;
194 /** Link for the next user action, if any. */
195 actionUri?: string;
196 };
197
198 export type ConnectionProps = {
199 /**
200 * Connection id (the `{connection}` segment of
201 * `projects/{project}/locations/{location}/connections/{connection}`).
202 * If omitted, a unique name is generated from the stack, stage, and
203 * logical id. Must be unique per project and location. Immutable —
204 * changing it replaces the connection.
205 */
206 connectionId?: string;
207 /**
208 * Cloud Build location (`us-central1`, `us-east1`, …). Immutable —
209 * changing it replaces the connection. `US-CENTRAL1` is accepted and
210 * normalized to `us-central1`.
211 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
212 */
213 location?: string;
214 /**
215 * When true, repository APIs and webhook processing for this connection
216 * are disabled.
217 * @default false
218 */
219 disabled?: boolean;
220 /**
221 * User annotations. Cloud Build connections have no labels, so Alchemy
222 * ownership (`alchemy-stack` / `alchemy-stage` / `alchemy-id`) is stored
223 * here for `list` / nuke.
224 */
225 annotations?: Record<string, string>;
226 /**
227 * Configuration for github.com. If no SCM config is set, Alchemy
228 * defaults to an empty GitHub config on create (installation stays
229 * pending until the Cloud Build GitHub App is authorized).
230 */
231 githubConfig?: GitHubConfig;
232 /**
233 * Configuration for a GitHub Enterprise host. Mutually exclusive with
234 * the other SCM configs. Changing `hostUri` replaces the connection.
235 */
236 githubEnterpriseConfig?: GitHubEnterpriseConfig;
237 /**
238 * Configuration for gitlab.com or GitLab Enterprise. Mutually exclusive
239 * with the other SCM configs. Changing `hostUri` or
240 * `webhookSecretSecretVersion` replaces the connection.
241 */
242 gitlabConfig?: GitLabConfig;
243 /**
244 * Configuration for Bitbucket Data Center. Mutually exclusive with the
245 * other SCM configs. Changing `hostUri` or
246 * `webhookSecretSecretVersion` replaces the connection.
247 */
248 bitbucketDataCenterConfig?: BitbucketDataCenterConfig;
249 /**
250 * Configuration for Bitbucket Cloud. Mutually exclusive with the other
251 * SCM configs. Changing `workspace` or `webhookSecretSecretVersion`
252 * replaces the connection.
253 */
254 bitbucketCloudConfig?: BitbucketCloudConfig;
255 };
256
257 export type Connection = Resource<
258 "GCP.CloudBuild.Connection",
259 ConnectionProps,
260 {
261 /** Full resource name `projects/{project}/locations/{location}/connections/{connection}`. */
262 name: string;
263 /** Connection id (last path segment). */
264 connectionId: string;
265 /** Project id. */
266 project: string;
267 /** Location id (`us-central1`, …). */
268 location: string;
269 /** Whether repository APIs and webhooks are disabled. */
270 disabled: boolean;
271 /** User annotations (Alchemy ownership keys stripped). */
272 annotations: Record<string, string>;
273 /** github.com configuration, if this is a GitHub connection. */
274 githubConfig: GitHubConfig | undefined;
275 /** GitHub Enterprise configuration, if any. */
276 githubEnterpriseConfig: GitHubEnterpriseConfig | undefined;
277 /** GitLab configuration, if any. */
278 gitlabConfig: GitLabConfig | undefined;
279 /** Bitbucket Data Center configuration, if any. */
280 bitbucketDataCenterConfig: BitbucketDataCenterConfig | undefined;
281 /** Bitbucket Cloud configuration, if any. */
282 bitbucketCloudConfig: BitbucketCloudConfig | undefined;
283 /** Installation progress for GitHub-based connections. */
284 installationState: InstallationState | undefined;
285 /** True while Cloud Build is applying the connection in the background. */
286 reconciling: boolean;
287 /** Server checksum of the resource. */
288 etag: string | undefined;
289 /** RFC3339 creation timestamp. */
290 createTime: string | undefined;
291 /** RFC3339 last-update timestamp. */
292 updateTime: string | undefined;
293 },
294 never,
295 Providers
296 >;
297
298 /**
299 * A Cloud Build v2 connection to a source-control host (GitHub, GitHub
300 * Enterprise, GitLab, Bitbucket Data Center, or Bitbucket Cloud).
301 *
302 * Changing `connectionId` or `location` replaces the connection. Switching
303 * SCM kinds, or changing immutable host fields (`hostUri`, `workspace`,
304 * `webhookSecretSecretVersion`), also replaces. `disabled` and
305 * `annotations` update in place.
306 *
307 * Cloud Build connections have no labels. Alchemy stores ownership in
308 * annotations (`alchemy-stack` / `alchemy-stage` / `alchemy-id`) so
309 * `list` / `pnpm nuke:gcp` can find them.
310 *
311 * ### Creating a Connection
312 * **Example:** Generated GitHub connection
313 * ```typescript
314 * const github = yield* GCP.CloudBuild.Connection("Github", {
315 * githubConfig: {},
316 * });
317 * ```
318 *
319 * **Example:** Named GitHub connection with installation
320 * ```typescript
321 * const github = yield* GCP.CloudBuild.Connection("Github", {
322 * connectionId: "app-github",
323 * location: "us-central1",
324 * annotations: { env: "prod" },
325 * githubConfig: {
326 * appInstallationId: "123456",
327 * authorizerCredential: {
328 * oauthTokenSecretVersion:
329 * "projects/{project}/secrets/github-pat/versions/latest",
330 * },
331 * },
332 * });
333 * ```
334 *
335 * ### Disabling a Connection
336 * **Example:** Disable webhook processing
337 * ```typescript
338 * const github = yield* GCP.CloudBuild.Connection("Github", {
339 * connectionId: "app-github",
340 * githubConfig: {},
341 * disabled: true,
342 * });
343 * ```
344 *
345 * ### GitLab
346 * **Example:** GitLab.com connection
347 * ```typescript
348 * const gitlab = yield* GCP.CloudBuild.Connection("Gitlab", {
349 * gitlabConfig: {
350 * webhookSecretSecretVersion:
351 * "projects/{project}/secrets/gitlab-webhook/versions/latest",
352 * readAuthorizerCredential: {
353 * userTokenSecretVersion:
354 * "projects/{project}/secrets/gitlab-read/versions/latest",
355 * },
356 * authorizerCredential: {
357 * userTokenSecretVersion:
358 * "projects/{project}/secrets/gitlab-api/versions/latest",
359 * },
360 * },
361 * });
362 * ```
363 *
364 * @resource
365 * @category CloudBuild
366 */
367 export const Connection = Resource<Connection>("GCP.CloudBuild.Connection");
368
369 export class ConnectionNotResolved extends Data.TaggedError(
370 "GCP.CloudBuild.ConnectionNotResolved",
371 )<{
372 resourceName: string;
373 }> {}
374
375 export class ConnectionStillExists extends Data.TaggedError(
376 "GCP.CloudBuild.ConnectionStillExists",
377 )<{
378 resourceName: string;
379 }> {}
380
381 type ScmKind = "github" | "githubEnterprise" | "gitlab" | "bitbucketDataCenter" | "bitbucketCloud";
382
383 const lastSegment = (value: string) => {
384 const trimmed = value.replace(/\/+$/, "");
385 const parts = trimmed.split("/");
386 return parts[parts.length - 1] || trimmed;
387 };
388
389 const normalizeLocation = (location: string | undefined, fallback: string) =>
390 lastSegment(location ?? fallback).toLowerCase();
391
392 const resourceName = (project: string, location: string, connectionId: string) =>
393 `projects/${project}/locations/${location}/connections/${connectionId}`;
394
395 const parentOf = (project: string, location: string) => `projects/${project}/locations/${location}`;
396
397 const parseName = (name: string) => {
398 const parts = name.split("/").filter((part) => part.length > 0);
399 const connectionsAt = parts.lastIndexOf("connections");
400 const locationsAt = parts.lastIndexOf("locations");
401 const projectsAt = parts.lastIndexOf("projects");
402 return {
403 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
404 location: locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : "",
405 connectionId:
406 connectionsAt >= 0 && parts[connectionsAt + 1]
407 ? parts[connectionsAt + 1]!
408 : lastSegment(name),
409 };
410 };
411
412 const userAnnotations = (
413 annotations: Record<string, string | undefined> | null | undefined,
414 ): Record<string, string> => stripInternalLabels(tagRecord(annotations));
415
416 const toId = (id: string, connectionId: string | undefined, existing?: string) =>
417 Effect.gen(function* () {
418 return (
419 connectionId ??
420 existing ??
421 (yield* createPhysicalName({
422 id,
423 maxLength: MAX_NAME_LENGTH,
424 lowercase: true,
425 }))
426 );
427 });
428
429 const compact = <T extends Record<string, unknown>>(value: T): T =>
430 Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined)) as T;
431
432 const toOAuthCredential = (
433 credential: OAuthCredential | undefined,
434 ): cloudbuild.OAuthCredential | undefined => {
435 if (credential === undefined) return undefined;
436 return compact({
437 oauthTokenSecretVersion: credential.oauthTokenSecretVersion,
438 });
439 };
440
441 const toUserCredential = (
442 credential: UserCredential | undefined,
443 ): cloudbuild.UserCredential | undefined => {
444 if (credential === undefined) return undefined;
445 return compact({
446 userTokenSecretVersion: credential.userTokenSecretVersion,
447 });
448 };
449
450 const toServiceDirectory = (
451 config: ServiceDirectoryConfig | undefined,
452 ): cloudbuild.GoogleDevtoolsCloudbuildV2ServiceDirectoryConfig | undefined => {
453 if (config === undefined) return undefined;
454 return compact({ service: config.service });
455 };
456
457 const toGithub = (config: GitHubConfig | undefined): cloudbuild.GitHubConfig | undefined => {
458 if (config === undefined) return undefined;
459 return compact({
460 authorizerCredential: toOAuthCredential(config.authorizerCredential),
461 appInstallationId: config.appInstallationId,
462 });
463 };
464
465 const toGithubEnterprise = (
466 config: GitHubEnterpriseConfig | undefined,
467 ): cloudbuild.GoogleDevtoolsCloudbuildV2GitHubEnterpriseConfig | undefined => {
468 if (config === undefined) return undefined;
469 return compact({
470 hostUri: config.hostUri,
471 apiKey: config.apiKey,
472 appId: config.appId,
473 appSlug: config.appSlug,
474 privateKeySecretVersion: config.privateKeySecretVersion,
475 webhookSecretSecretVersion: config.webhookSecretSecretVersion,
476 appInstallationId: config.appInstallationId,
477 serviceDirectoryConfig: toServiceDirectory(config.serviceDirectoryConfig),
478 sslCa: config.sslCa,
479 });
480 };
481
482 const toGitlab = (
483 config: GitLabConfig | undefined,
484 ): cloudbuild.GoogleDevtoolsCloudbuildV2GitLabConfig | undefined => {
485 if (config === undefined) return undefined;
486 return compact({
487 hostUri: config.hostUri,
488 webhookSecretSecretVersion: config.webhookSecretSecretVersion,
489 readAuthorizerCredential: toUserCredential(config.readAuthorizerCredential),
490 authorizerCredential: toUserCredential(config.authorizerCredential),
491 serviceDirectoryConfig: toServiceDirectory(config.serviceDirectoryConfig),
492 sslCa: config.sslCa,
493 });
494 };
495
496 const toBitbucketDataCenter = (
497 config: BitbucketDataCenterConfig | undefined,
498 ): cloudbuild.BitbucketDataCenterConfig | undefined => {
499 if (config === undefined) return undefined;
500 return compact({
501 hostUri: config.hostUri,
502 webhookSecretSecretVersion: config.webhookSecretSecretVersion,
503 readAuthorizerCredential: toUserCredential(config.readAuthorizerCredential),
504 authorizerCredential: toUserCredential(config.authorizerCredential),
505 serviceDirectoryConfig: toServiceDirectory(config.serviceDirectoryConfig),
506 sslCa: config.sslCa,
507 });
508 };
509
510 const toBitbucketCloud = (
511 config: BitbucketCloudConfig | undefined,
512 ): cloudbuild.BitbucketCloudConfig | undefined => {
513 if (config === undefined) return undefined;
514 return compact({
515 workspace: config.workspace,
516 webhookSecretSecretVersion: config.webhookSecretSecretVersion,
517 readAuthorizerCredential: toUserCredential(config.readAuthorizerCredential),
518 authorizerCredential: toUserCredential(config.authorizerCredential),
519 });
520 };
521
522 const fromGithub = (config: cloudbuild.GitHubConfig | undefined): GitHubConfig | undefined => {
523 if (config === undefined) return undefined;
524 return compact({
525 authorizerCredential: config.authorizerCredential
526 ? compact({
527 oauthTokenSecretVersion: config.authorizerCredential.oauthTokenSecretVersion,
528 })
529 : undefined,
530 appInstallationId: config.appInstallationId,
531 });
532 };
533
534 const fromGithubEnterprise = (
535 config: cloudbuild.GoogleDevtoolsCloudbuildV2GitHubEnterpriseConfig | undefined,
536 ): GitHubEnterpriseConfig | undefined => {
537 if (config === undefined) return undefined;
538 return compact({
539 hostUri: config.hostUri,
540 apiKey: config.apiKey,
541 appId: config.appId,
542 appSlug: config.appSlug,
543 privateKeySecretVersion: config.privateKeySecretVersion,
544 webhookSecretSecretVersion: config.webhookSecretSecretVersion,
545 appInstallationId: config.appInstallationId,
546 serviceDirectoryConfig: config.serviceDirectoryConfig
547 ? compact({ service: config.serviceDirectoryConfig.service })
548 : undefined,
549 sslCa: config.sslCa,
550 });
551 };
552
553 const fromGitlab = (
554 config: cloudbuild.GoogleDevtoolsCloudbuildV2GitLabConfig | undefined,
555 ): GitLabConfig | undefined => {
556 if (config === undefined) return undefined;
557 return compact({
558 hostUri: config.hostUri,
559 webhookSecretSecretVersion: config.webhookSecretSecretVersion,
560 readAuthorizerCredential: config.readAuthorizerCredential
561 ? compact({
562 userTokenSecretVersion: config.readAuthorizerCredential.userTokenSecretVersion,
563 })
564 : undefined,
565 authorizerCredential: config.authorizerCredential
566 ? compact({
567 userTokenSecretVersion: config.authorizerCredential.userTokenSecretVersion,
568 })
569 : undefined,
570 serviceDirectoryConfig: config.serviceDirectoryConfig
571 ? compact({ service: config.serviceDirectoryConfig.service })
572 : undefined,
573 sslCa: config.sslCa,
574 });
575 };
576
577 const fromBitbucketDataCenter = (
578 config: cloudbuild.BitbucketDataCenterConfig | undefined,
579 ): BitbucketDataCenterConfig | undefined => {
580 if (config === undefined) return undefined;
581 return compact({
582 hostUri: config.hostUri,
583 webhookSecretSecretVersion: config.webhookSecretSecretVersion,
584 readAuthorizerCredential: config.readAuthorizerCredential
585 ? compact({
586 userTokenSecretVersion: config.readAuthorizerCredential.userTokenSecretVersion,
587 })
588 : undefined,
589 authorizerCredential: config.authorizerCredential
590 ? compact({
591 userTokenSecretVersion: config.authorizerCredential.userTokenSecretVersion,
592 })
593 : undefined,
594 serviceDirectoryConfig: config.serviceDirectoryConfig
595 ? compact({ service: config.serviceDirectoryConfig.service })
596 : undefined,
597 sslCa: config.sslCa,
598 });
599 };
600
601 const fromBitbucketCloud = (
602 config: cloudbuild.BitbucketCloudConfig | undefined,
603 ): BitbucketCloudConfig | undefined => {
604 if (config === undefined) return undefined;
605 return compact({
606 workspace: config.workspace,
607 webhookSecretSecretVersion: config.webhookSecretSecretVersion,
608 readAuthorizerCredential: config.readAuthorizerCredential
609 ? compact({
610 userTokenSecretVersion: config.readAuthorizerCredential.userTokenSecretVersion,
611 })
612 : undefined,
613 authorizerCredential: config.authorizerCredential
614 ? compact({
615 userTokenSecretVersion: config.authorizerCredential.userTokenSecretVersion,
616 })
617 : undefined,
618 });
619 };
620
621 const fromInstallationState = (
622 state: cloudbuild.InstallationState | undefined,
623 ): InstallationState | undefined => {
624 if (state === undefined) return undefined;
625 return compact({
626 stage: state.stage,
627 message: state.message,
628 actionUri: state.actionUri,
629 });
630 };
631
632 const scmKindOf = (value: {
633 githubConfig?: unknown;
634 githubEnterpriseConfig?: unknown;
635 gitlabConfig?: unknown;
636 bitbucketDataCenterConfig?: unknown;
637 bitbucketCloudConfig?: unknown;
638 }): ScmKind | undefined => {
639 if (value.githubEnterpriseConfig !== undefined) return "githubEnterprise";
640 if (value.gitlabConfig !== undefined) return "gitlab";
641 if (value.bitbucketDataCenterConfig !== undefined) return "bitbucketDataCenter";
642 if (value.bitbucketCloudConfig !== undefined) return "bitbucketCloud";
643 if (value.githubConfig !== undefined) return "github";
644 return undefined;
645 };
646
647 const observedScmKind = (connection: cloudbuild.Connection): ScmKind | undefined => {
648 if (connection.githubEnterpriseConfig !== undefined) return "githubEnterprise";
649 if (connection.gitlabConfig !== undefined) return "gitlab";
650 if (connection.bitbucketDataCenterConfig !== undefined) return "bitbucketDataCenter";
651 if (connection.bitbucketCloudConfig !== undefined) return "bitbucketCloud";
652 if (connection.githubConfig !== undefined) return "github";
653 return undefined;
654 };
655
656 const desiredScmKind = (news: ConnectionProps): ScmKind | undefined => scmKindOf(news);
657
658 const toScmBody = (news: ConnectionProps): Partial<cloudbuild.Connection> => {
659 const kind = desiredScmKind(news) ?? "github";
660 switch (kind) {
661 case "githubEnterprise":
662 return {
663 githubEnterpriseConfig: toGithubEnterprise(news.githubEnterpriseConfig),
664 };
665 case "gitlab":
666 return { gitlabConfig: toGitlab(news.gitlabConfig) };
667 case "bitbucketDataCenter":
668 return {
669 bitbucketDataCenterConfig: toBitbucketDataCenter(news.bitbucketDataCenterConfig),
670 };
671 case "bitbucketCloud":
672 return {
673 bitbucketCloudConfig: toBitbucketCloud(news.bitbucketCloudConfig),
674 };
675 default:
676 return { githubConfig: toGithub(news.githubConfig ?? {}) };
677 }
678 };
679
680 const fieldChanged = (desired: string | undefined, observed: string | undefined) =>
681 desired !== undefined && (desired ?? "") !== (observed ?? "");
682
683 const githubChanged = (desired: GitHubConfig | undefined, observed: GitHubConfig | undefined) => {
684 if (desired === undefined) return false;
685 return (
686 fieldChanged(desired.appInstallationId, observed?.appInstallationId) ||
687 fieldChanged(
688 desired.authorizerCredential?.oauthTokenSecretVersion,
689 observed?.authorizerCredential?.oauthTokenSecretVersion,
690 )
691 );
692 };
693
694 const githubEnterpriseChanged = (
695 desired: GitHubEnterpriseConfig | undefined,
696 observed: GitHubEnterpriseConfig | undefined,
697 ) => {
698 if (desired === undefined) return false;
699 return (
700 fieldChanged(desired.hostUri, observed?.hostUri) ||
701 fieldChanged(desired.apiKey, observed?.apiKey) ||
702 fieldChanged(desired.appId, observed?.appId) ||
703 fieldChanged(desired.appSlug, observed?.appSlug) ||
704 fieldChanged(desired.privateKeySecretVersion, observed?.privateKeySecretVersion) ||
705 fieldChanged(desired.webhookSecretSecretVersion, observed?.webhookSecretSecretVersion) ||
706 fieldChanged(desired.appInstallationId, observed?.appInstallationId) ||
707 fieldChanged(
708 desired.serviceDirectoryConfig?.service,
709 observed?.serviceDirectoryConfig?.service,
710 ) ||
711 fieldChanged(desired.sslCa, observed?.sslCa)
712 );
713 };
714
715 const gitlabChanged = (desired: GitLabConfig | undefined, observed: GitLabConfig | undefined) => {
716 if (desired === undefined) return false;
717 return (
718 fieldChanged(desired.hostUri, observed?.hostUri) ||
719 fieldChanged(desired.webhookSecretSecretVersion, observed?.webhookSecretSecretVersion) ||
720 fieldChanged(
721 desired.readAuthorizerCredential?.userTokenSecretVersion,
722 observed?.readAuthorizerCredential?.userTokenSecretVersion,
723 ) ||
724 fieldChanged(
725 desired.authorizerCredential?.userTokenSecretVersion,
726 observed?.authorizerCredential?.userTokenSecretVersion,
727 ) ||
728 fieldChanged(
729 desired.serviceDirectoryConfig?.service,
730 observed?.serviceDirectoryConfig?.service,
731 ) ||
732 fieldChanged(desired.sslCa, observed?.sslCa)
733 );
734 };
735
736 const bitbucketDataCenterChanged = (
737 desired: BitbucketDataCenterConfig | undefined,
738 observed: BitbucketDataCenterConfig | undefined,
739 ) => {
740 if (desired === undefined) return false;
741 return (
742 fieldChanged(desired.hostUri, observed?.hostUri) ||
743 fieldChanged(desired.webhookSecretSecretVersion, observed?.webhookSecretSecretVersion) ||
744 fieldChanged(
745 desired.readAuthorizerCredential?.userTokenSecretVersion,
746 observed?.readAuthorizerCredential?.userTokenSecretVersion,
747 ) ||
748 fieldChanged(
749 desired.authorizerCredential?.userTokenSecretVersion,
750 observed?.authorizerCredential?.userTokenSecretVersion,
751 ) ||
752 fieldChanged(
753 desired.serviceDirectoryConfig?.service,
754 observed?.serviceDirectoryConfig?.service,
755 ) ||
756 fieldChanged(desired.sslCa, observed?.sslCa)
757 );
758 };
759
760 const bitbucketCloudChanged = (
761 desired: BitbucketCloudConfig | undefined,
762 observed: BitbucketCloudConfig | undefined,
763 ) => {
764 if (desired === undefined) return false;
765 return (
766 fieldChanged(desired.workspace, observed?.workspace) ||
767 fieldChanged(desired.webhookSecretSecretVersion, observed?.webhookSecretSecretVersion) ||
768 fieldChanged(
769 desired.readAuthorizerCredential?.userTokenSecretVersion,
770 observed?.readAuthorizerCredential?.userTokenSecretVersion,
771 ) ||
772 fieldChanged(
773 desired.authorizerCredential?.userTokenSecretVersion,
774 observed?.authorizerCredential?.userTokenSecretVersion,
775 )
776 );
777 };
778
779 const immutableHostOf = (value: {
780 githubEnterpriseConfig?: { hostUri?: string };
781 gitlabConfig?: { hostUri?: string };
782 bitbucketDataCenterConfig?: { hostUri?: string };
783 bitbucketCloudConfig?: { workspace?: string };
784 }) =>
785 value.githubEnterpriseConfig?.hostUri ??
786 value.gitlabConfig?.hostUri ??
787 value.bitbucketDataCenterConfig?.hostUri ??
788 value.bitbucketCloudConfig?.workspace;
789
790 const immutableWebhookOf = (value: {
791 githubEnterpriseConfig?: { webhookSecretSecretVersion?: string };
792 gitlabConfig?: { webhookSecretSecretVersion?: string };
793 bitbucketDataCenterConfig?: { webhookSecretSecretVersion?: string };
794 bitbucketCloudConfig?: { webhookSecretSecretVersion?: string };
795 }) =>
796 value.githubEnterpriseConfig?.webhookSecretSecretVersion ??
797 value.gitlabConfig?.webhookSecretSecretVersion ??
798 value.bitbucketDataCenterConfig?.webhookSecretSecretVersion ??
799 value.bitbucketCloudConfig?.webhookSecretSecretVersion;
800
801 const toAttrs = (connection: cloudbuild.Connection, project: string) => {
802 const name = connection.name ?? "";
803 const parsed = parseName(name);
804 return {
805 name,
806 connectionId: parsed.connectionId,
807 project: parsed.project || project,
808 location: parsed.location,
809 disabled: connection.disabled === true,
810 annotations: userAnnotations(connection.annotations),
811 githubConfig: fromGithub(connection.githubConfig),
812 githubEnterpriseConfig: fromGithubEnterprise(connection.githubEnterpriseConfig),
813 gitlabConfig: fromGitlab(connection.gitlabConfig),
814 bitbucketDataCenterConfig: fromBitbucketDataCenter(connection.bitbucketDataCenterConfig),
815 bitbucketCloudConfig: fromBitbucketCloud(connection.bitbucketCloudConfig),
816 installationState: fromInstallationState(connection.installationState),
817 reconciling: connection.reconciling === true,
818 etag: connection.etag,
819 createTime: connection.createTime,
820 updateTime: connection.updateTime,
821 };
822 };
823
824 const getByName = (name: string) =>
825 cloudbuild
826 .getProjectsLocationsConnections({ name })
827 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
828
829 /**
830 * Wait on a Cloud Build connections long-running operation (seconds to a minute).
831 * `ALREADY_EXISTS` (a create race) counts as success; so does `NOT_FOUND`
832 * when `notFoundOk` (deletes). Returns the final operation.
833 */
834 const waitForOperation = (operation: cloudbuild.Operation, options?: { notFoundOk?: boolean }) =>
835 Effect.suspend(() => {
836 let latest = operation;
837 return waitForLongRunningOperation(
838 operation,
839 (name) => {
840 const get = cloudbuild.getProjectsLocationsOperations({ name }).pipe(
841 Effect.tap((current) =>
842 Effect.sync(() => {
843 latest = current;
844 }),
845 ),
846 );
847 const observe: Effect.Effect<
848 cloudbuild.Operation,
849 cloudbuild.GetProjectsLocationsOperationsError,
850 GcpOpContext
851 > =
852 options?.notFoundOk === true
853 ? get.pipe(
854 Effect.catchTag("NotFound", () =>
855 Effect.succeed<cloudbuild.Operation>({ name, done: true }),
856 ),
857 )
858 : get.pipe(
859 // A just-returned operation can briefly 404 on read.
860 Effect.retry({
861 while: (error) => error._tag === "NotFound",
862 times: 5,
863 schedule: Schedule.exponential("250 millis"),
864 }),
865 );
866 return observe;
867 },
868 { budget: "5 minutes" },
869 ).pipe(
870 Effect.map(() => latest),
871 // google.rpc.Code ALREADY_EXISTS = 6, NOT_FOUND = 5.
872 Effect.catchTag("GCP.OperationFailed", (error) =>
873 error.code === 6 || (options?.notFoundOk === true && error.code === 5)
874 ? Effect.succeed(latest)
875 : Effect.fail(error),
876 ),
877 );
878 });
879
880 const waitUntilExists = (name: string) =>
881 getByName(name).pipe(
882 Effect.flatMap((connection) =>
883 connection
884 ? Effect.succeed(connection)
885 : Effect.fail(new ConnectionNotResolved({ resourceName: name })),
886 ),
887 Effect.retry({
888 while: (error) => error._tag === "GCP.CloudBuild.ConnectionNotResolved",
889 times: 8,
890 schedule: Schedule.spaced("1 second"),
891 }),
892 );
893
894 const waitUntilGone = (name: string) =>
895 getByName(name).pipe(
896 Effect.flatMap((connection) =>
897 connection === undefined
898 ? Effect.void
899 : Effect.fail(new ConnectionStillExists({ resourceName: name })),
900 ),
901 Effect.retry({
902 while: (error) => error._tag === "GCP.CloudBuild.ConnectionStillExists",
903 times: 10,
904 schedule: Schedule.spaced("1 second"),
905 }),
906 );
907
908 export const ConnectionProvider = () =>
909 Provider.succeed(Connection, {
910 stables: ["name", "connectionId", "location", "project", "createTime"],
911
912 diff: Effect.fn(function* ({ news, olds, output }) {
913 const env = yield* GcpEnvironment.current;
914 if (!isResolved(news)) return undefined;
915 const previousId = olds?.connectionId ?? output?.connectionId;
916 const nextId = news.connectionId ?? previousId;
917 const idChanged = previousId !== undefined && nextId !== undefined && nextId !== previousId;
918
919 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
920 const nextLocation = normalizeLocation(news.location ?? output?.location, env.region);
921 const locationChanged = previousLocation !== nextLocation;
922
923 const previousKind =
924 desiredScmKind(olds ?? {}) ?? (output === undefined ? undefined : scmKindOf(output));
925 const nextKind = desiredScmKind(news);
926 const kindChanged =
927 previousKind !== undefined && nextKind !== undefined && nextKind !== previousKind;
928
929 const previousHost = immutableHostOf(olds ?? {}) ?? immutableHostOf(output ?? {});
930 const nextHost = immutableHostOf(news);
931 const hostChanged =
932 previousHost !== undefined && nextHost !== undefined && nextHost !== previousHost;
933
934 const previousWebhook = immutableWebhookOf(olds ?? {}) ?? immutableWebhookOf(output ?? {});
935 const nextWebhook = immutableWebhookOf(news);
936 const webhookChanged =
937 previousWebhook !== undefined &&
938 nextWebhook !== undefined &&
939 nextWebhook !== previousWebhook;
940
941 if (idChanged || locationChanged || kindChanged || hostChanged || webhookChanged) {
942 return { action: "replace" as const, deleteFirst: false };
943 }
944 return undefined;
945 }),
946
947 read: Effect.fn(function* ({ id, olds, output }) {
948 const env = yield* GcpEnvironment.current;
949 const connectionId = yield* toId(id, olds?.connectionId, output?.connectionId);
950 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
951 const name = output?.name ?? resourceName(env.project, location, connectionId);
952 const existing = yield* getByName(name);
953 if (existing === undefined) return undefined;
954 const attrs = toAttrs(existing, env.project);
955 return (yield* hasAlchemyLabels(id, tagRecord(existing.annotations)))
956 ? attrs
957 : Unowned(attrs);
958 }),
959
960 list: () =>
961 Effect.gen(function* () {
962 const env = yield* GcpEnvironment.current;
963 return yield* cloudbuild.listProjectsLocationsConnections
964 .pages({
965 parent: `projects/${env.project}/locations/-`,
966 pageSize: 1000,
967 returnPartialSuccess: true,
968 })
969 .pipe(
970 Stream.flatMap((page) => Stream.fromIterable(page.connections ?? [])),
971 Stream.filter((connection) =>
972 Object.keys(connection.annotations ?? {}).some((key) => key.startsWith("alchemy-")),
973 ),
974 Stream.map((connection) => toAttrs(connection, env.project)),
975 Stream.runCollect,
976 Effect.map((chunk) => Array.from(chunk)),
977 Effect.catchTag("NotFound", () => Effect.succeed([])),
978 );
979 }),
980
981 reconcile: Effect.fn(function* ({ id, news, output }) {
982 const env = yield* GcpEnvironment.current;
983 const connectionId = yield* toId(id, news.connectionId, output?.connectionId);
984 const location = normalizeLocation(news.location ?? output?.location, env.region);
985 const name = resourceName(env.project, location, connectionId);
986 const parent = parentOf(env.project, location);
987 const desiredAnnotations = {
988 ...toLabels(news.annotations),
989 ...(yield* createInternalLabels(id)),
990 };
991 const desiredDisabled = news.disabled === true;
992 const scmBody = toScmBody(news);
993
994 let current = yield* getByName(name);
995
996 if (current === undefined) {
997 const created = yield* cloudbuild
998 .createProjectsLocationsConnections({
999 parent,
1000 connectionId,
1001 body: compact({
1002 ...scmBody,
1003 disabled: desiredDisabled ? true : undefined,
1004 annotations: desiredAnnotations,
1005 }),
1006 })
1007 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
1008 if (created !== undefined) {
1009 yield* waitForOperation(created);
1010 }
1011 current = yield* waitUntilExists(name);
1012 }
1013
1014 if (current === undefined) {
1015 return yield* new ConnectionNotResolved({ resourceName: name });
1016 }
1017
1018 const observedAnnotations = tagRecord(current.annotations);
1019 const { upsert, removed } = diffLabels(observedAnnotations, desiredAnnotations);
1020 const annotationsChanged = upsert.length > 0 || removed.length > 0;
1021 const disabledChanged = (current.disabled === true) !== desiredDisabled;
1022 const observedKind = observedScmKind(current);
1023 const nextKind = desiredScmKind(news);
1024 const githubConfigChanged =
1025 nextKind === "github" && githubChanged(news.githubConfig, fromGithub(current.githubConfig));
1026 const githubEnterpriseConfigChanged =
1027 nextKind === "githubEnterprise" &&
1028 githubEnterpriseChanged(
1029 news.githubEnterpriseConfig,
1030 fromGithubEnterprise(current.githubEnterpriseConfig),
1031 );
1032 const gitlabConfigChanged =
1033 nextKind === "gitlab" && gitlabChanged(news.gitlabConfig, fromGitlab(current.gitlabConfig));
1034 const bitbucketDataCenterConfigChanged =
1035 nextKind === "bitbucketDataCenter" &&
1036 bitbucketDataCenterChanged(
1037 news.bitbucketDataCenterConfig,
1038 fromBitbucketDataCenter(current.bitbucketDataCenterConfig),
1039 );
1040 const bitbucketCloudConfigChanged =
1041 nextKind === "bitbucketCloud" &&
1042 bitbucketCloudChanged(
1043 news.bitbucketCloudConfig,
1044 fromBitbucketCloud(current.bitbucketCloudConfig),
1045 );
1046 const scmChanged =
1047 (nextKind !== undefined && observedKind !== undefined && nextKind !== observedKind) ||
1048 githubConfigChanged ||
1049 githubEnterpriseConfigChanged ||
1050 gitlabConfigChanged ||
1051 bitbucketDataCenterConfigChanged ||
1052 bitbucketCloudConfigChanged;
1053
1054 const updateMask = [
1055 annotationsChanged ? "annotations" : undefined,
1056 disabledChanged ? "disabled" : undefined,
1057 scmChanged && (nextKind ?? observedKind) === "github" ? "githubConfig" : undefined,
1058 scmChanged && (nextKind ?? observedKind) === "githubEnterprise"
1059 ? "githubEnterpriseConfig"
1060 : undefined,
1061 scmChanged && (nextKind ?? observedKind) === "gitlab" ? "gitlabConfig" : undefined,
1062 scmChanged && (nextKind ?? observedKind) === "bitbucketDataCenter"
1063 ? "bitbucketDataCenterConfig"
1064 : undefined,
1065 scmChanged && (nextKind ?? observedKind) === "bitbucketCloud"
1066 ? "bitbucketCloudConfig"
1067 : undefined,
1068 ].filter((field): field is string => field !== undefined);
1069
1070 if (updateMask.length > 0) {
1071 const body = compact({
1072 ...(scmChanged ? scmBody : {}),
1073 disabled: desiredDisabled,
1074 annotations: desiredAnnotations,
1075 });
1076 const operation = yield* cloudbuild
1077 .patchProjectsLocationsConnections({
1078 name,
1079 updateMask: updateMask.join(","),
1080 body,
1081 })
1082 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
1083 if (operation === undefined) {
1084 const created = yield* cloudbuild
1085 .createProjectsLocationsConnections({
1086 parent,
1087 connectionId,
1088 body: compact({
1089 ...scmBody,
1090 disabled: desiredDisabled ? true : undefined,
1091 annotations: desiredAnnotations,
1092 }),
1093 })
1094 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
1095 if (created !== undefined) {
1096 yield* waitForOperation(created);
1097 }
1098 } else {
1099 yield* waitForOperation(operation);
1100 }
1101 current = yield* waitUntilExists(name);
1102 }
1103
1104 if (current === undefined) {
1105 return yield* new ConnectionNotResolved({ resourceName: name });
1106 }
1107
1108 return toAttrs(current, env.project);
1109 }),
1110
1111 delete: Effect.fn(function* ({ output }) {
1112 const operation = yield* cloudbuild
1113 .deleteProjectsLocationsConnections({ name: output.name })
1114 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
1115 if (operation !== undefined) {
1116 yield* waitForOperation(operation, { notFoundOk: true });
1117 }
1118 yield* waitUntilGone(output.name);
1119 }),
1120 });