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

main
ts 335 lines 11.9 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 Option from "effect/Option";
11 import * as Stream from "effect/Stream";
12 import { AWSEnvironment } from "../Environment.ts";
13 import type { Providers } from "../Providers.ts";
14
15 export interface SamplingRuleProps {
16 /**
17 * Name of the sampling rule (1-32 characters). `Default` is reserved by
18 * X-Ray for the built-in fallback rule.
19 *
20 * Changing the name replaces the rule.
21 * @default ${app}-${stage}-${id}
22 */
23 ruleName?: string;
24 /**
25 * The priority of the sampling rule. X-Ray evaluates rules in ascending
26 * order of priority (`1` - `9999`) and applies the first rule that matches.
27 */
28 priority: number;
29 /**
30 * The percentage of matching requests to instrument, after the reservoir is
31 * exhausted (`0.0` - `1.0`, e.g. `0.05` for 5%).
32 */
33 fixedRate: number;
34 /**
35 * A fixed number of matching requests to instrument per second, before
36 * applying the fixed rate. The reservoir is not used directly by services,
37 * but applies to all services using the rule collectively.
38 * @default 0
39 */
40 reservoirSize?: number;
41 /**
42 * Matches the `name` that the service uses to identify itself in segments.
43 * @default "*"
44 */
45 serviceName?: string;
46 /**
47 * Matches the `origin` that the service uses to identify its type in
48 * segments (e.g. `AWS::Lambda::Function`).
49 * @default "*"
50 */
51 serviceType?: string;
52 /**
53 * Matches the hostname from a request URL.
54 * @default "*"
55 */
56 host?: string;
57 /**
58 * Matches the HTTP method of a request.
59 * @default "*"
60 */
61 httpMethod?: string;
62 /**
63 * Matches the path from a request URL.
64 * @default "*"
65 */
66 urlPath?: string;
67 /**
68 * Matches the ARN of the Amazon Web Services resource on which the service
69 * runs.
70 * @default "*"
71 */
72 resourceArn?: string;
73 /**
74 * Matches attributes derived from the request (segment annotations).
75 */
76 attributes?: Record<string, string>;
77 /**
78 * Tags to apply to the sampling rule. Merged with internal Alchemy tags.
79 */
80 tags?: Record<string, string>;
81 }
82
83 export interface SamplingRule extends Resource<
84 "AWS.XRay.SamplingRule",
85 SamplingRuleProps,
86 {
87 /**
88 * Name of the sampling rule.
89 */
90 ruleName: string;
91 /**
92 * ARN of the sampling rule
93 * (`arn:aws:xray:{region}:{account}:sampling-rule/{name}`).
94 */
95 ruleArn: string;
96 },
97 never,
98 Providers
99 > {}
100
101 /**
102 * An AWS X-Ray sampling rule that controls which requests are recorded as
103 * traces by instrumented applications.
104 *
105 * X-Ray evaluates sampling rules in ascending priority order for each
106 * request. The first matching rule borrows from its reservoir, then applies
107 * the fixed rate.
108 * ### Creating Sampling Rules
109 * **Example:** Sample all requests to a service
110 * ```typescript
111 * import * as XRay from "@alchemy.run/aws/XRay";
112 *
113 * const rule = yield* XRay.SamplingRule("SampleEverything", {
114 * priority: 100,
115 * fixedRate: 1.0,
116 * reservoirSize: 5,
117 * serviceName: "my-api-*",
118 * });
119 * ```
120 *
121 * **Example:** Low-rate sampling for a noisy endpoint
122 * ```typescript
123 * const rule = yield* XRay.SamplingRule("HealthChecks", {
124 * priority: 10,
125 * fixedRate: 0.01,
126 * urlPath: "/health",
127 * httpMethod: "GET",
128 * });
129 * ```
130 *
131 * **Example:** Match on segment attributes
132 * ```typescript
133 * const rule = yield* XRay.SamplingRule("PremiumTenants", {
134 * priority: 50,
135 * fixedRate: 0.5,
136 * reservoirSize: 1,
137 * attributes: { tier: "premium" },
138 * });
139 * ```
140 *
141 * @resource
142 */
143 export const SamplingRule = Resource<SamplingRule>("AWS.XRay.SamplingRule");
144
145 /**
146 * Raised when a `SamplingRule` is configured with the reserved rule name
147 * `Default`, which X-Ray uses for the built-in fallback rule.
148 */
149 export class XRayReservedRuleName extends Data.TaggedError("XRayReservedRuleName")<{
150 message: string;
151 }> {}
152
153 const validateRuleName = (props: Pick<SamplingRuleProps, "ruleName">) =>
154 props.ruleName === "Default"
155 ? Effect.fail(
156 new XRayReservedRuleName({
157 message:
158 '"Default" is reserved for the built-in X-Ray fallback sampling rule — choose another ruleName.',
159 }),
160 )
161 : Effect.void;
162
163 const shallowRecordEqual = (
164 a: Record<string, string | undefined>,
165 b: Record<string, string | undefined>,
166 ) => {
167 const aKeys = Object.keys(a).filter((k) => a[k] !== undefined);
168 const bKeys = Object.keys(b).filter((k) => b[k] !== undefined);
169 return aKeys.length === bKeys.length && aKeys.every((key) => a[key] === b[key]);
170 };
171
172 export const SamplingRuleProvider = () =>
173 Provider.effect(
174 SamplingRule,
175 Effect.gen(function* () {
176 const createRuleName = Effect.fn(function* (
177 id: string,
178 props: Pick<SamplingRuleProps, "ruleName">,
179 ) {
180 // X-Ray rule names are limited to 32 characters.
181 return props.ruleName ?? (yield* createPhysicalName({ id, maxLength: 32 }));
182 });
183
184 // The desired wire shape for both create and update, derived purely
185 // from the new props.
186 const desiredRule = (name: string, props: SamplingRuleProps) => ({
187 RuleName: name,
188 ResourceARN: props.resourceArn ?? "*",
189 Priority: props.priority,
190 FixedRate: props.fixedRate,
191 ReservoirSize: props.reservoirSize ?? 0,
192 ServiceName: props.serviceName ?? "*",
193 ServiceType: props.serviceType ?? "*",
194 Host: props.host ?? "*",
195 HTTPMethod: props.httpMethod ?? "*",
196 URLPath: props.urlPath ?? "*",
197 Attributes: props.attributes ?? {},
198 });
199
200 // X-Ray has no GetSamplingRule — observe by enumerating the (small)
201 // rule list and matching on the deterministic rule name.
202 const observeRule = (name: string) =>
203 xray.getSamplingRules.items({}).pipe(
204 Stream.filter((record) => record.SamplingRule?.RuleName === name),
205 Stream.runHead,
206 Effect.map((record) => Option.getOrUndefined(record)?.SamplingRule),
207 );
208
209 const observedTags = (ruleArn: string) =>
210 xray.listTagsForResource.items({ ResourceARN: ruleArn }).pipe(
211 Stream.runCollect,
212 Effect.map((chunk) => Object.fromEntries(Array.from(chunk).map((t) => [t.Key, t.Value]))),
213 Effect.catchTag("ResourceNotFoundException", () =>
214 Effect.succeed({} as Record<string, string>),
215 ),
216 );
217
218 return SamplingRule.Provider.of({
219 stables: ["ruleName", "ruleArn"],
220 list: () =>
221 Effect.gen(function* () {
222 const records = yield* xray.getSamplingRules.items({}).pipe(Stream.runCollect);
223 return Array.from(records).flatMap((record) =>
224 record.SamplingRule?.RuleName &&
225 record.SamplingRule.RuleARN &&
226 // The built-in `Default` sampling rule always exists and can
227 // never be deleted — keep it out of enumeration for
228 // account-wide teardown (nuke).
229 record.SamplingRule.RuleName !== "Default"
230 ? [
231 {
232 ruleName: record.SamplingRule.RuleName,
233 ruleArn: record.SamplingRule.RuleARN,
234 },
235 ]
236 : [],
237 );
238 }),
239 read: Effect.fn(function* ({ id, olds, output }) {
240 const ruleName = output?.ruleName ?? (yield* createRuleName(id, olds ?? {}));
241 const found = yield* observeRule(ruleName);
242 if (!found?.RuleARN) return undefined;
243 const attrs = { ruleName, ruleArn: found.RuleARN };
244 const tags = yield* observedTags(found.RuleARN);
245 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
246 }),
247 diff: Effect.fn(function* ({ id, news, olds }) {
248 if (!isResolved(news)) return undefined;
249 yield* validateRuleName(news ?? {});
250 const oldName = yield* createRuleName(id, olds ?? {});
251 const newName = yield* createRuleName(id, news ?? {});
252 if (oldName !== newName) {
253 return { action: "replace" } as const;
254 }
255 // fall through: engine default update logic for mutable fields
256 }),
257 reconcile: Effect.fn(function* ({ id, news, output, session }) {
258 yield* validateRuleName(news);
259 const ruleName = output?.ruleName ?? (yield* createRuleName(id, news));
260 const desired = desiredRule(ruleName, news);
261 const internalTags = yield* createInternalTags(id);
262 const desiredTags = { ...news.tags, ...internalTags };
263
264 // 1. OBSERVE — the rule list is authoritative; output is only a
265 // cached identifier.
266 let live = yield* observeRule(ruleName);
267
268 // 2. ENSURE — create when missing; a concurrent create surfaces as
269 // the typed SamplingRuleAlreadyExists tag, which we treat as a
270 // race and re-observe.
271 if (live === undefined) {
272 live = yield* xray
273 .createSamplingRule({
274 SamplingRule: { ...desired, Version: 1 },
275 Tags: createTagsList(desiredTags),
276 })
277 .pipe(
278 Effect.map((r) => r.SamplingRuleRecord?.SamplingRule),
279 Effect.catchTag("SamplingRuleAlreadyExists", () => observeRule(ruleName)),
280 );
281 }
282
283 // 3. SYNC — diff every mutable field of the OBSERVED rule against
284 // the desired shape; a single UpdateSamplingRule applies the
285 // full desired state only when something actually drifted.
286 const inSync =
287 live !== undefined &&
288 live.ResourceARN === desired.ResourceARN &&
289 live.Priority === desired.Priority &&
290 live.FixedRate === desired.FixedRate &&
291 live.ReservoirSize === desired.ReservoirSize &&
292 live.ServiceName === desired.ServiceName &&
293 live.ServiceType === desired.ServiceType &&
294 live.Host === desired.Host &&
295 live.HTTPMethod === desired.HTTPMethod &&
296 live.URLPath === desired.URLPath &&
297 shallowRecordEqual(live.Attributes ?? {}, desired.Attributes);
298 if (!inSync) {
299 live = yield* xray
300 .updateSamplingRule({ SamplingRuleUpdate: desired })
301 .pipe(Effect.map((r) => r.SamplingRuleRecord?.SamplingRule));
302 }
303
304 // The ARN shape is deterministic:
305 // arn:aws:xray:{region}:{account}:sampling-rule/{name}
306 const { accountId, region } = yield* AWSEnvironment.current;
307 const ruleArn =
308 live?.RuleARN ?? `arn:aws:xray:${region}:${accountId}:sampling-rule/${ruleName}`;
309
310 // 3b. SYNC TAGS — diff against OBSERVED cloud tags so adoption
311 // converges (create-time Tags only apply on first create).
312 const currentTags = yield* observedTags(ruleArn);
313 const { upsert, removed } = diffTags(currentTags, desiredTags);
314 if (upsert.length > 0) {
315 yield* xray.tagResource({ ResourceARN: ruleArn, Tags: upsert });
316 }
317 if (removed.length > 0) {
318 yield* xray.untagResource({
319 ResourceARN: ruleArn,
320 TagKeys: removed,
321 });
322 }
323
324 yield* session.note(ruleName);
325 return { ruleName, ruleArn };
326 }),
327 delete: Effect.fn(function* ({ output }) {
328 yield* xray.deleteSamplingRule({ RuleName: output.ruleName }).pipe(
329 // Typed synthetic tag for a missing rule — idempotent delete.
330 Effect.catchTag("SamplingRuleNotFound", () => Effect.void),
331 );
332 }),
333 });
334 }),
335 );