@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 392 lines 14.1 KB
Raw
1 import * as appsignals from "@distilled.cloud/aws/application-signals";
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 class ServiceLevelObjectiveOperationFailed extends Data.TaggedError(
14 "ServiceLevelObjectiveOperationFailed",
15 )<{
16 readonly message: string;
17 readonly cause?: unknown;
18 }> {}
19
20 export interface ServiceLevelObjectiveProps {
21 /**
22 * Name of the SLO (up to 127 characters, pattern
23 * `[0-9A-Za-z][-._A-Za-z0-9 ]*`). Changing the name replaces the SLO —
24 * the API has no rename operation.
25 * @default ${app}-${stage}-${id}
26 */
27 sloName?: string;
28 /**
29 * A human-readable description of the SLO. Shown in the CloudWatch
30 * console next to the SLO.
31 */
32 description?: string;
33 /**
34 * Period-based service level indicator: a CloudWatch metric (via
35 * `SliMetricConfig.MetricDataQueries` for any metric or math expression,
36 * or the `KeyAttributes`/`OperationName` shorthand for services discovered
37 * by Application Signals), a `MetricThreshold`, and a `ComparisonOperator`.
38 *
39 * Exactly one of `sliConfig` or `requestBasedSliConfig` must be provided.
40 * Switching between them replaces the SLO — the evaluation type of an
41 * existing SLO cannot be changed.
42 */
43 sliConfig?: appsignals.ServiceLevelIndicatorConfig;
44 /**
45 * Request-based service level indicator: `TotalRequestCountMetric` plus a
46 * `GoodCountMetric` or `BadCountMetric` under
47 * `RequestBasedSliMetricConfig.MonitoredRequestCountMetric`.
48 *
49 * Exactly one of `sliConfig` or `requestBasedSliConfig` must be provided.
50 * Switching between them replaces the SLO.
51 */
52 requestBasedSliConfig?: appsignals.RequestBasedServiceLevelIndicatorConfig;
53 /**
54 * The attainment goal for the SLO: the `Interval` (rolling or calendar),
55 * the `AttainmentGoal` percentage, and the `WarningThreshold`.
56 * @default rolling 7-day interval, 99% attainment, 30% warning threshold
57 */
58 goal?: appsignals.Goal;
59 /**
60 * Burn-rate windows to compute for the SLO. Each entry creates a burn-rate
61 * metric over the given look-back window.
62 */
63 burnRateConfigurations?: appsignals.BurnRateConfiguration[];
64 /**
65 * Tags to apply to the SLO. Merged with internal Alchemy tags.
66 */
67 tags?: Record<string, string>;
68 }
69
70 export interface ServiceLevelObjective extends Resource<
71 "AWS.ApplicationSignals.ServiceLevelObjective",
72 ServiceLevelObjectiveProps,
73 {
74 /**
75 * Name of the service level objective.
76 */
77 sloName: string;
78 /**
79 * ARN of the service level objective.
80 */
81 sloArn: string;
82 /**
83 * How the SLO is evaluated (`PeriodBased` or `RequestBased`).
84 */
85 evaluationType: appsignals.EvaluationType | undefined;
86 },
87 never,
88 Providers
89 > {}
90
91 /**
92 * A CloudWatch Application Signals service level objective (SLO) that tracks
93 * an attainment goal against a service level indicator — any CloudWatch
94 * metric or metric-math expression, or a service operation discovered by
95 * Application Signals.
96 * ### Creating Service Level Objectives
97 * **Example:** Period-based SLO on a CloudWatch metric
98 * ```typescript
99 * import * as ApplicationSignals from "@alchemy.run/aws/ApplicationSignals";
100 *
101 * const slo = yield* ApplicationSignals.ServiceLevelObjective("ApiLatency", {
102 * description: "p99 latency under 2 seconds",
103 * sliConfig: {
104 * SliMetricConfig: {
105 * MetricDataQueries: [
106 * {
107 * Id: "m1",
108 * MetricStat: {
109 * Metric: {
110 * Namespace: "AWS/Lambda",
111 * MetricName: "Duration",
112 * Dimensions: [{ Name: "FunctionName", Value: "my-api" }],
113 * },
114 * Period: 60,
115 * Stat: "p99",
116 * },
117 * ReturnData: true,
118 * },
119 * ],
120 * },
121 * MetricThreshold: 2000,
122 * ComparisonOperator: "LessThanOrEqualTo",
123 * },
124 * goal: {
125 * Interval: { RollingInterval: { DurationUnit: "DAY", Duration: 7 } },
126 * AttainmentGoal: 99,
127 * WarningThreshold: 50,
128 * },
129 * });
130 * ```
131 *
132 * **Example:** Request-based SLO
133 * ```typescript
134 * const slo = yield* ApplicationSignals.ServiceLevelObjective("Availability", {
135 * requestBasedSliConfig: {
136 * RequestBasedSliMetricConfig: {
137 * TotalRequestCountMetric: [
138 * {
139 * Id: "total",
140 * MetricStat: {
141 * Metric: { Namespace: "AWS/ApplicationELB", MetricName: "RequestCount" },
142 * Period: 60,
143 * Stat: "Sum",
144 * },
145 * ReturnData: true,
146 * },
147 * ],
148 * MonitoredRequestCountMetric: {
149 * BadCountMetric: [
150 * {
151 * Id: "bad",
152 * MetricStat: {
153 * Metric: { Namespace: "AWS/ApplicationELB", MetricName: "HTTPCode_Target_5XX_Count" },
154 * Period: 60,
155 * Stat: "Sum",
156 * },
157 * ReturnData: true,
158 * },
159 * ],
160 * },
161 * },
162 * },
163 * goal: { AttainmentGoal: 99.9 },
164 * });
165 * ```
166 *
167 * @resource
168 */
169 export const ServiceLevelObjective = Resource<ServiceLevelObjective>(
170 "AWS.ApplicationSignals.ServiceLevelObjective",
171 );
172
173 /**
174 * Rebuild `Date` instances that the engine's state serialization flattened
175 * to ISO strings (calendar intervals carry a `StartTime` timestamp).
176 */
177 const normalizeGoal = (goal: appsignals.Goal | undefined): appsignals.Goal | undefined => {
178 const interval = goal?.Interval;
179 if (interval && "CalendarInterval" in interval && interval.CalendarInterval) {
180 return {
181 ...goal,
182 Interval: {
183 CalendarInterval: {
184 ...interval.CalendarInterval,
185 StartTime: new Date(interval.CalendarInterval.StartTime),
186 },
187 },
188 };
189 }
190 return goal;
191 };
192
193 const isPlainObject = (value: unknown): value is Record<string, unknown> =>
194 typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date);
195
196 const toTime = (value: unknown): number =>
197 value instanceof Date ? value.getTime() : new Date(value as string | number).getTime();
198
199 /**
200 * Structural subset comparison: every DEFINED field of `desired` must
201 * deep-equal the corresponding field of `observed`. Extra observed fields
202 * (server-side defaults the API echoes back, e.g. `ReturnData`, resolved
203 * account ids) are ignored, so a reconcile whose desired state matches the
204 * cloud skips the update call entirely.
205 */
206 const subsetMatches = (desired: unknown, observed: unknown): boolean => {
207 if (desired === undefined) return true;
208 if (desired instanceof Date || observed instanceof Date) {
209 return toTime(desired) === toTime(observed);
210 }
211 if (Array.isArray(desired)) {
212 return (
213 Array.isArray(observed) &&
214 observed.length === desired.length &&
215 desired.every((item, index) => subsetMatches(item, observed[index]))
216 );
217 }
218 if (isPlainObject(desired)) {
219 return (
220 isPlainObject(observed) &&
221 Object.entries(desired).every(([key, value]) => subsetMatches(value, observed[key]))
222 );
223 }
224 return desired === observed;
225 };
226
227 /** The mutable aspects of the SLO, in `UpdateServiceLevelObjective` shape. */
228 const desiredState = (news: ServiceLevelObjectiveProps) => ({
229 Description: news.description,
230 SliConfig: news.sliConfig,
231 RequestBasedSliConfig: news.requestBasedSliConfig,
232 Goal: normalizeGoal(news.goal),
233 BurnRateConfigurations: news.burnRateConfigurations,
234 });
235
236 /** Project the observed SLO into the same shape as {@link desiredState}. */
237 const observedState = (slo: appsignals.ServiceLevelObjective) => ({
238 Description: slo.Description,
239 SliConfig: slo.Sli && {
240 SliMetricConfig: slo.Sli.SliMetric,
241 MetricThreshold: slo.Sli.MetricThreshold,
242 ComparisonOperator: slo.Sli.ComparisonOperator,
243 },
244 RequestBasedSliConfig: slo.RequestBasedSli && {
245 RequestBasedSliMetricConfig: slo.RequestBasedSli.RequestBasedSliMetric,
246 MetricThreshold: slo.RequestBasedSli.MetricThreshold,
247 ComparisonOperator: slo.RequestBasedSli.ComparisonOperator,
248 },
249 Goal: slo.Goal,
250 BurnRateConfigurations: slo.BurnRateConfigurations,
251 });
252
253 export const ServiceLevelObjectiveProvider = () =>
254 Provider.effect(
255 ServiceLevelObjective,
256 Effect.gen(function* () {
257 const createSloName = Effect.fn(function* (
258 id: string,
259 props: Pick<ServiceLevelObjectiveProps, "sloName">,
260 ) {
261 // SLO names are limited to 127 characters.
262 return props.sloName ?? (yield* createPhysicalName({ id, maxLength: 127 }));
263 });
264
265 // `Id` accepts the SLO name or ARN interchangeably.
266 const observeSlo = (id: string) =>
267 appsignals.getServiceLevelObjective({ Id: id }).pipe(
268 Effect.map((r) => r.Slo),
269 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
270 );
271
272 const observedTags = (sloArn: string) =>
273 appsignals.listTagsForResource({ ResourceArn: sloArn }).pipe(
274 Effect.map((r) => Object.fromEntries((r.Tags ?? []).map((t) => [t.Key, t.Value]))),
275 Effect.catchTag("ResourceNotFoundException", () =>
276 Effect.succeed({} as Record<string, string>),
277 ),
278 );
279
280 return ServiceLevelObjective.Provider.of({
281 stables: ["sloName", "sloArn"],
282 list: () =>
283 Effect.gen(function* () {
284 const summaries = yield* appsignals.listServiceLevelObjectives
285 .items({})
286 .pipe(Stream.runCollect);
287 return Array.from(summaries).map((slo) => ({
288 sloName: slo.Name,
289 sloArn: slo.Arn,
290 evaluationType: slo.EvaluationType,
291 }));
292 }),
293 read: Effect.fn(function* ({ id, olds, output }) {
294 const sloName = output?.sloName ?? (yield* createSloName(id, olds ?? {}));
295 const found = yield* observeSlo(sloName);
296 if (!found) return undefined;
297 const attrs = {
298 sloName: found.Name,
299 sloArn: found.Arn,
300 evaluationType: found.EvaluationType,
301 };
302 const tags = yield* observedTags(found.Arn);
303 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
304 }),
305 diff: Effect.fn(function* ({ id, news, olds }) {
306 if (!isResolved(news)) return undefined;
307 const oldName = yield* createSloName(id, olds ?? {});
308 const newName = yield* createSloName(id, news ?? {});
309 if (oldName !== newName) {
310 return { action: "replace" } as const;
311 }
312 // An SLO cannot switch between period-based and request-based
313 // evaluation — swapping the SLI config kind replaces the SLO.
314 const oldKind = olds?.requestBasedSliConfig ? "RequestBased" : "PeriodBased";
315 const newKind = news?.requestBasedSliConfig ? "RequestBased" : "PeriodBased";
316 if (oldKind !== newKind) {
317 return { action: "replace" } as const;
318 }
319 // fall through: engine default update logic for mutable fields
320 }),
321 reconcile: Effect.fn(function* ({ id, news, output, session }) {
322 const sloName = output?.sloName ?? (yield* createSloName(id, news));
323 const internalTags = yield* createInternalTags(id);
324 const desiredTags = { ...news.tags, ...internalTags };
325 const desired = desiredState(news);
326
327 // 1. OBSERVE — cloud state is authoritative; `output` is only a
328 // cache for the physical name.
329 let live = yield* observeSlo(sloName);
330
331 if (live === undefined) {
332 // 2. ENSURE — create when missing; a concurrent create surfaces
333 // as the typed ConflictException, which we treat as a race
334 // and re-observe.
335 live = yield* appsignals
336 .createServiceLevelObjective({
337 Name: sloName,
338 ...desired,
339 Tags: createTagsList(desiredTags),
340 })
341 .pipe(
342 Effect.map((r) => r.Slo),
343 Effect.catchTag("ConflictException", () => observeSlo(sloName)),
344 );
345 } else if (!subsetMatches(desired, observedState(live))) {
346 // 3. SYNC — converge every mutable aspect with a single PATCH;
347 // skipped entirely when the observed state already satisfies
348 // the desired state (update retains omitted parameters).
349 live = yield* appsignals
350 .updateServiceLevelObjective({ Id: sloName, ...desired })
351 .pipe(Effect.map((r) => r.Slo));
352 }
353
354 if (live === undefined) {
355 return yield* new ServiceLevelObjectiveOperationFailed({
356 message: `failed to reconcile SLO '${sloName}'`,
357 });
358 }
359
360 // 3b. SYNC TAGS — diff against OBSERVED cloud tags so adoption
361 // converges (create-time Tags only apply on first create).
362 const currentTags = yield* observedTags(live.Arn);
363 const { upsert, removed } = diffTags(currentTags, desiredTags);
364 if (upsert.length > 0) {
365 yield* appsignals.tagResource({
366 ResourceArn: live.Arn,
367 Tags: upsert,
368 });
369 }
370 if (removed.length > 0) {
371 yield* appsignals.untagResource({
372 ResourceArn: live.Arn,
373 TagKeys: removed,
374 });
375 }
376
377 yield* session.note(sloName);
378 return {
379 sloName: live.Name,
380 sloArn: live.Arn,
381 evaluationType: live.EvaluationType,
382 };
383 }),
384 delete: Effect.fn(function* ({ output }) {
385 yield* appsignals.deleteServiceLevelObjective({ Id: output.sloName }).pipe(
386 // Idempotent delete — already-gone is success.
387 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
388 );
389 }),
390 });
391 }),
392 );