@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 208 lines 7.25 KB
Raw
1 import * as amp from "@distilled.cloud/aws/amp";
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 Schedule from "effect/Schedule";
7 import type { Providers } from "../Providers.ts";
8 import { normalizeAmpLogGroupArn } from "./internal.ts";
9
10 export interface QueryLoggingDestination {
11 /**
12 * ARN of the CloudWatch Logs log group that receives query logs. AMP
13 * expects the ARN with a trailing `:*` — one is appended automatically
14 * when missing.
15 */
16 logGroupArn: string;
17 /**
18 * Only queries that spend at least this many Query Samples Processed
19 * (QSP) are logged. Use `0` to log every query.
20 * @default 0
21 */
22 qspThreshold?: number;
23 }
24
25 export interface QueryLoggingConfigurationProps {
26 /**
27 * Id of the AMP workspace whose queries are logged. A workspace has at
28 * most one query logging configuration. Changing the workspace replaces
29 * the configuration.
30 */
31 workspaceId: string;
32 /**
33 * Destinations that receive the query logs (currently CloudWatch Logs
34 * log groups, each with a QSP filter threshold). Updated in place.
35 */
36 destinations: QueryLoggingDestination[];
37 }
38
39 export interface QueryLoggingConfiguration extends Resource<
40 "AWS.AMP.QueryLoggingConfiguration",
41 QueryLoggingConfigurationProps,
42 {
43 workspaceId: string;
44 destinations: { logGroupArn: string; qspThreshold: number }[];
45 status: string;
46 },
47 never,
48 Providers
49 > {}
50
51 /**
52 * The query logging configuration of an Amazon Managed Service for
53 * Prometheus workspace — ships PromQL query logs (query text, QSP cost,
54 * response code) to CloudWatch Logs. A workspace has at most one.
55 *
56 * ### Creating a Query Logging Configuration
57 * **Example:** Log Expensive Queries to CloudWatch Logs
58 * ```typescript
59 * const workspace = yield* AMP.Workspace("Metrics", {});
60 * const logs = yield* Logs.LogGroup("QueryLogs", {
61 * logGroupName: "/aws/vendedlogs/prometheus/metrics-queries",
62 * });
63 * const queryLogging = yield* AMP.QueryLoggingConfiguration("QueryLogging", {
64 * workspaceId: workspace.workspaceId,
65 * destinations: [{ logGroupArn: logs.logGroupArn, qspThreshold: 1000 }],
66 * });
67 * ```
68 *
69 * @resource
70 */
71 export const QueryLoggingConfiguration = Resource<QueryLoggingConfiguration>(
72 "AWS.AMP.QueryLoggingConfiguration",
73 );
74
75 export const QueryLoggingConfigurationProvider = () =>
76 Provider.effect(
77 QueryLoggingConfiguration,
78 Effect.gen(function* () {
79 /** Describe the configuration; typed not-found → undefined. */
80 const describe = Effect.fn(function* (workspaceId: string) {
81 const response = yield* amp
82 .describeQueryLoggingConfiguration({ workspaceId })
83 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
84 return response?.queryLoggingConfiguration;
85 });
86
87 /**
88 * Bounded wait toward ACTIVE. Returns the last observed metadata —
89 * a still-transitioning configuration converges on a later reconcile.
90 */
91 const waitActive = Effect.fn(function* (workspaceId: string) {
92 return yield* amp.describeQueryLoggingConfiguration({ workspaceId }).pipe(
93 Effect.map((r) => r.queryLoggingConfiguration),
94 Effect.repeat({
95 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(20)]),
96 until: (c) => c.status.statusCode === "ACTIVE",
97 }),
98 );
99 });
100
101 /** Desired props → wire destinations (normalized + defaulted). */
102 const toWireDestinations = (destinations: QueryLoggingDestination[]) =>
103 destinations.map((destination) => ({
104 cloudWatchLogs: {
105 logGroupArn: normalizeAmpLogGroupArn(destination.logGroupArn),
106 },
107 filters: { qspThreshold: destination.qspThreshold ?? 0 },
108 }));
109
110 /** Canonical form for observed-vs-desired comparison. */
111 const canonical = (
112 destinations: {
113 cloudWatchLogs: { logGroupArn: string };
114 filters: { qspThreshold: number };
115 }[],
116 ) =>
117 JSON.stringify(
118 destinations
119 .map((d) => ({
120 logGroupArn: d.cloudWatchLogs.logGroupArn,
121 qspThreshold: d.filters.qspThreshold,
122 }))
123 .sort((a, b) => a.logGroupArn.localeCompare(b.logGroupArn)),
124 );
125
126 const toAttrs = (meta: amp.QueryLoggingConfigurationMetadata) => ({
127 workspaceId: meta.workspace,
128 destinations: meta.destinations.map((d) => ({
129 logGroupArn: d.cloudWatchLogs.logGroupArn,
130 qspThreshold: d.filters.qspThreshold,
131 })),
132 status: meta.status.statusCode,
133 });
134
135 return {
136 stables: ["workspaceId"],
137
138 diff: Effect.fn(function* ({ olds, news }) {
139 if (!isResolved(news)) return undefined;
140 if (olds?.workspaceId !== news.workspaceId) {
141 return { action: "replace" } as const;
142 }
143 }),
144
145 read: Effect.fn(function* ({ olds, output }) {
146 const workspaceId = output?.workspaceId ?? olds?.workspaceId;
147 if (!workspaceId) return undefined;
148 const meta = yield* describe(workspaceId);
149 if (meta === undefined) return undefined;
150 // Query logging configurations are not taggable — ownership is
151 // implied by the owned parent workspace.
152 return toAttrs(meta);
153 }),
154
155 reconcile: Effect.fn(function* ({ news, session }) {
156 const workspaceId = news!.workspaceId;
157 const desired = toWireDestinations(news!.destinations);
158
159 // 1. Observe — the live configuration is authoritative.
160 const existing = yield* describe(workspaceId);
161
162 // 2/3. Ensure + sync — create when absent (tolerating a create
163 // race), update when the destinations drift.
164 if (existing === undefined) {
165 yield* amp
166 .createQueryLoggingConfiguration({
167 workspaceId,
168 destinations: desired,
169 })
170 .pipe(
171 Effect.catchTag("ConflictException", () =>
172 amp.updateQueryLoggingConfiguration({
173 workspaceId,
174 destinations: desired,
175 }),
176 ),
177 );
178 } else if (canonical([...existing.destinations]) !== canonical(desired)) {
179 yield* amp.updateQueryLoggingConfiguration({
180 workspaceId,
181 destinations: desired,
182 });
183 }
184
185 const fresh = yield* waitActive(workspaceId);
186 yield* session.note(workspaceId);
187 return toAttrs(fresh);
188 }),
189
190 delete: Effect.fn(function* ({ output }) {
191 yield* amp
192 .deleteQueryLoggingConfiguration({
193 workspaceId: output.workspaceId,
194 })
195 .pipe(
196 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
197 Effect.retry({
198 while: (e) => e._tag === "ConflictException",
199 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(20)]),
200 }),
201 );
202 }),
203
204 // Singleton sub-resource keyed by its parent workspace.
205 list: () => Effect.succeed([]),
206 };
207 }),
208 );