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

main
ts 241 lines 8.57 KB
Raw
1 import * as xray from "@distilled.cloud/aws/xray";
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, createTagsList, diffTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12
13 export interface GroupProps {
14 /**
15 * Name of the group (1-32 characters). `Default` is reserved by X-Ray for
16 * the built-in group that matches all traces.
17 *
18 * Changing the name replaces the group.
19 * @default ${app}-${stage}-${id}
20 */
21 groupName?: string;
22 /**
23 * The filter expression defining the criteria by which traces belong to
24 * the group, e.g. `service("my-api") AND responsetime > 2`.
25 */
26 filterExpression: string;
27 /**
28 * Whether to enable insights for the group. Insights detect anomalies in
29 * the group's traces.
30 * @default false
31 */
32 insightsEnabled?: boolean;
33 /**
34 * Whether insights should generate EventBridge notifications. Requires
35 * `insightsEnabled: true`.
36 * @default false
37 */
38 notificationsEnabled?: boolean;
39 /**
40 * Tags to apply to the group. Merged with internal Alchemy tags.
41 */
42 tags?: Record<string, string>;
43 }
44
45 export interface Group extends Resource<
46 "AWS.XRay.Group",
47 GroupProps,
48 {
49 /**
50 * Name of the group.
51 */
52 groupName: string;
53 /**
54 * ARN of the group.
55 */
56 groupArn: string;
57 },
58 never,
59 Providers
60 > {}
61
62 /**
63 * An AWS X-Ray group that collects traces matching a filter expression, for
64 * focused service maps, analytics, and insights.
65 * ### Creating Groups
66 * **Example:** Group traces for one service
67 * ```typescript
68 * import * as XRay from "@alchemy.run/aws/XRay";
69 *
70 * const group = yield* XRay.Group("ApiGroup", {
71 * filterExpression: 'service("my-api")',
72 * });
73 * ```
74 *
75 * **Example:** Group slow requests with insights enabled
76 * ```typescript
77 * const group = yield* XRay.Group("SlowRequests", {
78 * filterExpression: "responsetime > 2",
79 * insightsEnabled: true,
80 * notificationsEnabled: true,
81 * });
82 * ```
83 *
84 * @resource
85 */
86 export const Group = Resource<Group>("AWS.XRay.Group");
87
88 /**
89 * Raised when a `Group` is configured with the reserved group name
90 * `Default`, which X-Ray uses for the built-in group matching all traces.
91 */
92 export class XRayReservedGroupName extends Data.TaggedError("XRayReservedGroupName")<{
93 message: string;
94 }> {}
95
96 const validateGroupName = (props: Pick<GroupProps, "groupName">) =>
97 props.groupName === "Default"
98 ? Effect.fail(
99 new XRayReservedGroupName({
100 message: '"Default" is reserved for the built-in X-Ray group — choose another groupName.',
101 }),
102 )
103 : Effect.void;
104
105 export const GroupProvider = () =>
106 Provider.effect(
107 Group,
108 Effect.gen(function* () {
109 const createGroupName = Effect.fn(function* (
110 id: string,
111 props: Pick<GroupProps, "groupName">,
112 ) {
113 // X-Ray group names are limited to 32 characters.
114 return props.groupName ?? (yield* createPhysicalName({ id, maxLength: 32 }));
115 });
116
117 const desiredInsights = (props: GroupProps) => ({
118 InsightsEnabled: props.insightsEnabled ?? false,
119 NotificationsEnabled: props.notificationsEnabled ?? false,
120 });
121
122 const observeGroup = (groupName: string) =>
123 xray.getGroup({ GroupName: groupName }).pipe(
124 Effect.map((r) => r.Group),
125 // Typed synthetic tag for a missing group.
126 Effect.catchTag("GroupNotFound", () => Effect.undefined),
127 );
128
129 const observedTags = (groupArn: string) =>
130 xray.listTagsForResource.items({ ResourceARN: groupArn }).pipe(
131 Stream.runCollect,
132 Effect.map((chunk) => Object.fromEntries(Array.from(chunk).map((t) => [t.Key, t.Value]))),
133 Effect.catchTag("ResourceNotFoundException", () =>
134 Effect.succeed({} as Record<string, string>),
135 ),
136 );
137
138 return Group.Provider.of({
139 stables: ["groupName", "groupArn"],
140 list: () =>
141 Effect.gen(function* () {
142 const groups = yield* xray.getGroups.items({}).pipe(Stream.runCollect);
143 return Array.from(groups).flatMap((group) =>
144 group.GroupName && group.GroupARN && group.GroupName !== "Default"
145 ? [{ groupName: group.GroupName, groupArn: group.GroupARN }]
146 : [],
147 );
148 }),
149 read: Effect.fn(function* ({ id, olds, output }) {
150 const groupName = output?.groupName ?? (yield* createGroupName(id, olds ?? {}));
151 const found = yield* observeGroup(groupName);
152 if (!found?.GroupARN) return undefined;
153 const attrs = { groupName, groupArn: found.GroupARN };
154 const tags = yield* observedTags(found.GroupARN);
155 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
156 }),
157 diff: Effect.fn(function* ({ id, news, olds }) {
158 if (!isResolved(news)) return undefined;
159 yield* validateGroupName(news ?? {});
160 const oldName = yield* createGroupName(id, olds ?? {});
161 const newName = yield* createGroupName(id, news ?? {});
162 if (oldName !== newName) {
163 return { action: "replace" } as const;
164 }
165 // fall through: engine default update logic for mutable fields
166 }),
167 reconcile: Effect.fn(function* ({ id, news, output, session }) {
168 yield* validateGroupName(news);
169 const groupName = output?.groupName ?? (yield* createGroupName(id, news));
170 const insights = desiredInsights(news);
171 const internalTags = yield* createInternalTags(id);
172 const desiredTags = { ...news.tags, ...internalTags };
173
174 // 1. OBSERVE — cloud state is authoritative.
175 let live = yield* observeGroup(groupName);
176
177 // 2. ENSURE — create when missing; a concurrent create surfaces as
178 // the typed GroupAlreadyExists tag, which we treat as a race
179 // and re-observe.
180 if (live === undefined) {
181 live = yield* xray
182 .createGroup({
183 GroupName: groupName,
184 FilterExpression: news.filterExpression,
185 InsightsConfiguration: insights,
186 Tags: createTagsList(desiredTags),
187 })
188 .pipe(
189 Effect.map((r) => r.Group),
190 Effect.catchTag("GroupAlreadyExists", () => observeGroup(groupName)),
191 );
192 }
193
194 // 3. SYNC — diff the OBSERVED filter expression and insights
195 // configuration against the desired state; update only on drift.
196 const observedInsights = live?.InsightsConfiguration ?? {};
197 const inSync =
198 live !== undefined &&
199 live.FilterExpression === news.filterExpression &&
200 (observedInsights.InsightsEnabled ?? false) === insights.InsightsEnabled &&
201 (observedInsights.NotificationsEnabled ?? false) === insights.NotificationsEnabled;
202 if (!inSync) {
203 live = yield* xray
204 .updateGroup({
205 GroupName: groupName,
206 FilterExpression: news.filterExpression,
207 InsightsConfiguration: insights,
208 })
209 .pipe(Effect.map((r) => r.Group));
210 }
211
212 const groupArn = live?.GroupARN ?? output?.groupArn;
213
214 // 3b. SYNC TAGS — diff against OBSERVED cloud tags so adoption
215 // converges (create-time Tags only apply on first create).
216 if (groupArn !== undefined) {
217 const currentTags = yield* observedTags(groupArn);
218 const { upsert, removed } = diffTags(currentTags, desiredTags);
219 if (upsert.length > 0) {
220 yield* xray.tagResource({ ResourceARN: groupArn, Tags: upsert });
221 }
222 if (removed.length > 0) {
223 yield* xray.untagResource({
224 ResourceARN: groupArn,
225 TagKeys: removed,
226 });
227 }
228 }
229
230 yield* session.note(groupName);
231 return { groupName, groupArn: groupArn! };
232 }),
233 delete: Effect.fn(function* ({ output }) {
234 yield* xray.deleteGroup({ GroupName: output.groupName }).pipe(
235 // Typed synthetic tag for a missing group — idempotent delete.
236 Effect.catchTag("GroupNotFound", () => Effect.void),
237 );
238 }),
239 });
240 }),
241 );