@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 259 lines 9.13 KB
Raw
1 import * as scheduler from "@distilled.cloud/aws/scheduler";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, createTagsList, diffTags, hasTags, tagRecord } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11
12 export class ScheduleGroupConflict extends Data.TaggedError("ScheduleGroupConflict")<{
13 readonly message: string;
14 readonly cause?: unknown;
15 }> {}
16
17 export class ScheduleGroupUnexpectedResponse extends Data.TaggedError(
18 "ScheduleGroupUnexpectedResponse",
19 )<{
20 readonly message: string;
21 readonly cause?: unknown;
22 }> {}
23
24 export interface ScheduleGroupProps {
25 /**
26 * Schedule group name. If omitted, Alchemy generates a deterministic name.
27 */
28 name?: string;
29 /**
30 * User-defined tags for the schedule group.
31 */
32 tags?: Record<string, string>;
33 }
34
35 /**
36 * An EventBridge Scheduler schedule group.
37 *
38 * Schedule groups provide a namespace for schedules so higher-level helpers can
39 * organize recurring jobs separately from one-shot or operational schedules.
40 * ### Creating Schedule Groups
41 * **Example:** Basic Group
42 * ```typescript
43 * const group = yield* ScheduleGroup("Operations", {
44 * tags: {
45 * domain: "ops",
46 * },
47 * });
48 * ```
49 *
50 * @resource
51 */
52 export interface ScheduleGroup extends Resource<
53 "AWS.Scheduler.ScheduleGroup",
54 ScheduleGroupProps,
55 {
56 /**
57 * ARN of the schedule group.
58 */
59 scheduleGroupArn: string;
60 /**
61 * Name of the schedule group.
62 */
63 scheduleGroupName: string;
64 /**
65 * Current state of the schedule group (`ACTIVE` or `DELETING`).
66 */
67 state: string | undefined;
68 /**
69 * Tags on the schedule group, as observed. Lets `alchemy drift` detect
70 * out-of-band changes.
71 */
72 tags?: Record<string, string>;
73 },
74 never,
75 Providers
76 > {}
77
78 export const ScheduleGroup = Resource<ScheduleGroup>("AWS.Scheduler.ScheduleGroup");
79
80 export const ScheduleGroupProvider = () =>
81 Provider.effect(
82 ScheduleGroup,
83 Effect.gen(function* () {
84 const toName = (id: string, props: ScheduleGroupProps) =>
85 props.name ? Effect.succeed(props.name) : createPhysicalName({ id, maxLength: 64 });
86
87 return {
88 stables: ["scheduleGroupArn", "scheduleGroupName"],
89 diff: Effect.fn(function* ({ id, olds, news }) {
90 if (!isResolved(news)) return undefined;
91 if ((yield* toName(id, olds)) !== (yield* toName(id, news as ScheduleGroupProps))) {
92 return { action: "replace" } as const;
93 }
94 }),
95 read: Effect.fn(function* ({ id, olds, output }) {
96 const scheduleGroupName = output?.scheduleGroupName ?? (yield* toName(id, olds));
97 const described = yield* scheduler
98 .getScheduleGroup({
99 Name: scheduleGroupName,
100 })
101 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
102
103 if (!described?.Arn || !described.Name) {
104 return undefined;
105 }
106
107 const { Tags } = yield* scheduler
108 .listTagsForResource({ ResourceArn: described.Arn })
109 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.succeed({ Tags: [] })));
110 return {
111 scheduleGroupArn: described.Arn,
112 scheduleGroupName: described.Name,
113 state: described.State,
114 tags: tagRecord(Tags),
115 };
116 }),
117 reconcile: Effect.fn(function* ({ id, news, output, session }) {
118 const scheduleGroupName = output?.scheduleGroupName ?? (yield* toName(id, news));
119 const internalTags = yield* createInternalTags(id);
120 const desiredTags = { ...internalTags, ...news.tags };
121
122 // Observe — fetch live group; gracefully handle missing.
123 let observed = yield* scheduler
124 .getScheduleGroup({ Name: scheduleGroupName })
125 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
126
127 // Ensure — create if missing. Tolerate `ConflictException` as a
128 // race or adoption case: verify ownership via tags before
129 // continuing.
130 if (!observed?.Arn) {
131 yield* scheduler
132 .createScheduleGroup({
133 Name: scheduleGroupName,
134 Tags: createTagsList(desiredTags),
135 })
136 .pipe(
137 Effect.catchTag("ConflictException", () =>
138 scheduler.getScheduleGroup({ Name: scheduleGroupName }).pipe(
139 Effect.flatMap((existing) =>
140 existing.Arn
141 ? scheduler.listTagsForResource({ ResourceArn: existing.Arn }).pipe(
142 Effect.filterOrFail(
143 ({ Tags }) => hasTags(internalTags, Tags),
144 () =>
145 new ScheduleGroupConflict({
146 message: `ScheduleGroup '${scheduleGroupName}' already exists and is not managed by alchemy`,
147 }),
148 ),
149 Effect.asVoid,
150 )
151 : Effect.fail(
152 new ScheduleGroupConflict({
153 message: `ScheduleGroup '${scheduleGroupName}' already exists but could not be described`,
154 }),
155 ),
156 ),
157 ),
158 ),
159 );
160 observed = yield* scheduler
161 .getScheduleGroup({ Name: scheduleGroupName })
162 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
163 }
164
165 if (!observed?.Arn) {
166 return yield* new ScheduleGroupUnexpectedResponse({
167 message: `Failed to read created ScheduleGroup '${scheduleGroupName}'`,
168 });
169 }
170
171 const groupArn = observed.Arn;
172
173 // Sync tags — diff observed cloud tags against desired so
174 // adoption rewrites ownership tags.
175 const observedTagsResp = yield* scheduler
176 .listTagsForResource({ ResourceArn: groupArn })
177 .pipe(
178 Effect.catchTag("ResourceNotFoundException", () =>
179 Effect.succeed({ Tags: [] as scheduler.Tag[] }),
180 ),
181 );
182 const observedTags = Object.fromEntries(
183 (observedTagsResp.Tags ?? []).map((t) => [t.Key, t.Value]),
184 );
185 const { removed, upsert } = diffTags(observedTags, desiredTags);
186
187 if (removed.length > 0) {
188 yield* scheduler.untagResource({
189 ResourceArn: groupArn,
190 TagKeys: removed,
191 });
192 }
193 if (upsert.length > 0) {
194 yield* scheduler.tagResource({
195 ResourceArn: groupArn,
196 Tags: upsert,
197 });
198 }
199
200 yield* session.note(groupArn);
201
202 return {
203 scheduleGroupArn: groupArn,
204 scheduleGroupName,
205 state: observed?.State,
206 tags: desiredTags,
207 };
208 }),
209 list: () =>
210 Effect.gen(function* () {
211 // Enumerate every schedule group in the account/region,
212 // paginated.
213 const summaries = yield* scheduler.listScheduleGroups.pages({}).pipe(
214 Stream.runCollect,
215 Effect.map((chunk) =>
216 Array.from(chunk).flatMap((page) =>
217 (page.ScheduleGroups ?? []).filter(
218 (
219 g,
220 ): g is scheduler.ScheduleGroupSummary & {
221 Name: string;
222 } => g.Name != null,
223 ),
224 ),
225 ),
226 );
227
228 // Hydrate each summary via GetScheduleGroup into the exact
229 // `read` shape. Skip groups deleted between list and get.
230 const rows = yield* Effect.forEach(
231 summaries,
232 (summary) =>
233 scheduler.getScheduleGroup({ Name: summary.Name }).pipe(
234 Effect.map((described) =>
235 described.Arn && described.Name
236 ? {
237 scheduleGroupArn: described.Arn,
238 scheduleGroupName: described.Name,
239 state: described.State,
240 }
241 : undefined,
242 ),
243 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
244 ),
245 { concurrency: 10 },
246 );
247
248 return rows.filter((row): row is ScheduleGroup["Attributes"] => row !== undefined);
249 }),
250 delete: Effect.fn(function* ({ output }) {
251 yield* scheduler
252 .deleteScheduleGroup({
253 Name: output.scheduleGroupName,
254 })
255 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
256 }),
257 };
258 }),
259 );