@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 299 lines 11.2 KB
Raw
1 import * as codeconnections from "@distilled.cloud/aws/codeconnections";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Stream from "effect/Stream";
7 import type { Providers } from "../Providers.ts";
8
9 export interface SyncConfigurationProps {
10 /**
11 * Branch of the repository that Git sync monitors, e.g. `main`.
12 */
13 branch: string;
14 /**
15 * Path to the configuration file (deployment file) in the repository,
16 * e.g. `deployments/stack-deployment.yaml`.
17 */
18 configFile: string;
19 /**
20 * ID of the repository link Git sync monitors (from a `RepositoryLink`).
21 */
22 repositoryLinkId: string;
23 /**
24 * Name of the Amazon Web Services resource kept in sync — for
25 * `CFN_STACK_SYNC` this is the CloudFormation stack name. Together with
26 * `syncType` it identifies the sync configuration; changing it replaces
27 * the configuration.
28 */
29 resourceName: string;
30 /**
31 * ARN of the IAM role that Git sync assumes to sync content to the
32 * resource.
33 */
34 roleArn: string;
35 /**
36 * The sync type. Changing it replaces the configuration.
37 * @default "CFN_STACK_SYNC"
38 */
39 syncType?: "CFN_STACK_SYNC";
40 /**
41 * Whether to publish deployment status (start/end) back to the provider
42 * as commit statuses.
43 * @default "ENABLED"
44 */
45 publishDeploymentStatus?: "ENABLED" | "DISABLED";
46 /**
47 * When to trigger a sync of the resource: on any change to the branch or
48 * only when the tracked config file changes.
49 * @default "ANY_CHANGE"
50 */
51 triggerResourceUpdateOn?: "ANY_CHANGE" | "FILE_CHANGE";
52 /**
53 * Whether Git sync comments sync status on pull requests against the
54 * tracked branch.
55 * @default "ENABLED"
56 */
57 pullRequestComment?: "ENABLED" | "DISABLED";
58 }
59
60 export interface SyncConfiguration extends Resource<
61 "AWS.CodeConnections.SyncConfiguration",
62 SyncConfigurationProps,
63 {
64 /** Name of the synced Amazon Web Services resource (e.g. stack name). */
65 resourceName: string;
66 /** The sync type. */
67 syncType: string;
68 /** Monitored branch. */
69 branch: string;
70 /** Path to the deployment file in the repository. */
71 configFile: string;
72 /** ID of the monitored repository link. */
73 repositoryLinkId: string;
74 /** Name of the linked repository. */
75 repositoryName: string;
76 /** Owner ID of the linked repository. */
77 ownerId: string;
78 /** The source provider (`GitHub`, `GitLab`, ...). */
79 providerType: string;
80 /** ARN of the IAM role Git sync assumes. */
81 roleArn: string;
82 },
83 never,
84 Providers
85 > {}
86
87 /**
88 * An AWS CodeConnections sync configuration — connects a repository link's
89 * branch + deployment file to an Amazon Web Services resource so Git sync
90 * keeps the resource updated from the repository (CloudFormation stack
91 * sync).
92 * ### Syncing a CloudFormation Stack
93 * **Example:** Stack Sync from a Repository Link
94 * ```typescript
95 * const sync = yield* CodeConnections.SyncConfiguration("StackSync", {
96 * branch: "main",
97 * configFile: "deployments/stack-deployment.yaml",
98 * repositoryLinkId: link.repositoryLinkId,
99 * resourceName: "my-stack",
100 * roleArn: gitSyncRole.roleArn,
101 * });
102 * ```
103 *
104 * **Example:** Sync Only on Deployment-File Changes
105 * ```typescript
106 * const sync = yield* CodeConnections.SyncConfiguration("StackSync", {
107 * branch: "main",
108 * configFile: "deployments/stack-deployment.yaml",
109 * repositoryLinkId: link.repositoryLinkId,
110 * resourceName: "my-stack",
111 * roleArn: gitSyncRole.roleArn,
112 * triggerResourceUpdateOn: "FILE_CHANGE",
113 * pullRequestComment: "DISABLED",
114 * });
115 * ```
116 *
117 * @resource
118 */
119 export const SyncConfiguration = Resource<SyncConfiguration>(
120 "AWS.CodeConnections.SyncConfiguration",
121 );
122
123 const DEFAULT_SYNC_TYPE = "CFN_STACK_SYNC";
124
125 export const SyncConfigurationProvider = () =>
126 Provider.effect(
127 SyncConfiguration,
128 Effect.gen(function* () {
129 /**
130 * Read a sync configuration by its identity (sync type + resource
131 * name); a missing configuration reads as absent.
132 */
133 const getByIdentity = Effect.fn(function* (syncType: string, resourceName: string) {
134 const response = yield* codeconnections
135 .getSyncConfiguration({
136 SyncType: syncType,
137 ResourceName: resourceName,
138 })
139 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
140 return response?.SyncConfiguration;
141 });
142
143 const toAttrs = (config: codeconnections.SyncConfiguration) => ({
144 resourceName: config.ResourceName,
145 syncType: config.SyncType,
146 branch: config.Branch,
147 configFile: config.ConfigFile ?? "",
148 repositoryLinkId: config.RepositoryLinkId,
149 repositoryName: config.RepositoryName,
150 ownerId: config.OwnerId,
151 providerType: config.ProviderType ?? "",
152 roleArn: config.RoleArn,
153 });
154
155 return {
156 stables: ["resourceName", "syncType", "repositoryName", "ownerId", "providerType"],
157
158 diff: Effect.fn(function* ({ olds, news }) {
159 if (!isResolved(news)) return undefined;
160 // (syncType, resourceName) is the configuration's identity —
161 // replace on change. Everything else is mutable via
162 // UpdateSyncConfiguration.
163 if (
164 (news?.resourceName ?? undefined) !== (olds?.resourceName ?? undefined) ||
165 (news?.syncType ?? DEFAULT_SYNC_TYPE) !== (olds?.syncType ?? DEFAULT_SYNC_TYPE)
166 ) {
167 return { action: "replace" } as const;
168 }
169 }),
170
171 // Sync configurations carry no tags — ownership is keyed by the
172 // (syncType, resourceName) identity the caller declares, so `read`
173 // returns the observed state as owned.
174 read: Effect.fn(function* ({ olds, output }) {
175 const syncType = output?.syncType ?? olds?.syncType ?? DEFAULT_SYNC_TYPE;
176 const resourceName = output?.resourceName ?? olds?.resourceName;
177 if (resourceName === undefined) return undefined;
178 const config = yield* getByIdentity(syncType, resourceName);
179 return config === undefined ? undefined : toAttrs(config);
180 }),
181
182 reconcile: Effect.fn(function* ({ news, session }) {
183 const syncType = news.syncType ?? DEFAULT_SYNC_TYPE;
184
185 // 1. Observe — cloud state is authoritative.
186 let observed = yield* getByIdentity(syncType, news.resourceName);
187
188 // 2. Ensure — create if missing; tolerate the AlreadyExists race.
189 if (observed === undefined) {
190 observed = yield* codeconnections
191 .createSyncConfiguration({
192 Branch: news.branch,
193 ConfigFile: news.configFile,
194 RepositoryLinkId: news.repositoryLinkId,
195 ResourceName: news.resourceName,
196 RoleArn: news.roleArn,
197 SyncType: syncType,
198 PublishDeploymentStatus: news.publishDeploymentStatus,
199 TriggerResourceUpdateOn: news.triggerResourceUpdateOn,
200 PullRequestComment: news.pullRequestComment,
201 })
202 .pipe(
203 Effect.map((res) => res.SyncConfiguration),
204 Effect.catchTag("ResourceAlreadyExistsException", (error) =>
205 getByIdentity(syncType, news.resourceName).pipe(
206 Effect.flatMap((config) =>
207 config === undefined ? Effect.fail(error) : Effect.succeed(config),
208 ),
209 ),
210 ),
211 );
212 }
213
214 // 3. Sync — diff every mutable field against OBSERVED cloud state;
215 // skip the API entirely on no-op. Optional prop left undefined
216 // keeps the observed value (service-side default).
217 const drifted =
218 observed.Branch !== news.branch ||
219 (observed.ConfigFile ?? "") !== news.configFile ||
220 observed.RepositoryLinkId !== news.repositoryLinkId ||
221 observed.RoleArn !== news.roleArn ||
222 (news.publishDeploymentStatus !== undefined &&
223 observed.PublishDeploymentStatus !== news.publishDeploymentStatus) ||
224 (news.triggerResourceUpdateOn !== undefined &&
225 observed.TriggerResourceUpdateOn !== news.triggerResourceUpdateOn) ||
226 (news.pullRequestComment !== undefined &&
227 observed.PullRequestComment !== news.pullRequestComment);
228 if (drifted) {
229 const updated = yield* codeconnections.updateSyncConfiguration({
230 ResourceName: news.resourceName,
231 SyncType: syncType,
232 Branch: news.branch,
233 ConfigFile: news.configFile,
234 RepositoryLinkId: news.repositoryLinkId,
235 RoleArn: news.roleArn,
236 PublishDeploymentStatus: news.publishDeploymentStatus,
237 TriggerResourceUpdateOn: news.triggerResourceUpdateOn,
238 PullRequestComment: news.pullRequestComment,
239 });
240 observed = updated.SyncConfiguration;
241 }
242
243 yield* session.note(`${syncType}/${news.resourceName}`);
244 return toAttrs(observed);
245 }),
246
247 // DeleteSyncConfiguration documents no NotFound error — observe
248 // first so a repeat delete (after a state-persistence failure) is a
249 // no-op instead of an InvalidInput failure.
250 delete: Effect.fn(function* ({ output }) {
251 const observed = yield* getByIdentity(output.syncType, output.resourceName);
252 if (observed !== undefined) {
253 yield* codeconnections.deleteSyncConfiguration({
254 SyncType: output.syncType,
255 ResourceName: output.resourceName,
256 });
257 }
258 }),
259
260 // Enumerate every repository link's sync configurations.
261 list: () =>
262 codeconnections.listRepositoryLinks.pages({}).pipe(
263 Stream.runCollect,
264 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.RepositoryLinks ?? [])),
265 Effect.flatMap((links) =>
266 Effect.forEach(
267 links,
268 (link) =>
269 codeconnections.listSyncConfigurations
270 .pages({
271 RepositoryLinkId: link.RepositoryLinkId,
272 SyncType: DEFAULT_SYNC_TYPE,
273 })
274 .pipe(
275 Stream.runCollect,
276 Effect.map((chunk) =>
277 Array.from(chunk).flatMap((page) => page.SyncConfigurations ?? []),
278 ),
279 ),
280 { concurrency: 4 },
281 ),
282 ),
283 Effect.map((configs) =>
284 configs.flat().map((config) => ({
285 resourceName: config.ResourceName,
286 syncType: config.SyncType,
287 branch: config.Branch,
288 configFile: config.ConfigFile ?? "",
289 repositoryLinkId: config.RepositoryLinkId,
290 repositoryName: config.RepositoryName,
291 ownerId: config.OwnerId,
292 providerType: config.ProviderType ?? "",
293 roleArn: config.RoleArn,
294 })),
295 ),
296 ),
297 };
298 }),
299 );