@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 225 lines 8.24 KB
Raw
1 import * as route53 from "@distilled.cloud/aws/route-53";
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 * as Stream from "effect/Stream";
8 import type { Providers } from "../Providers.ts";
9
10 export interface QueryLoggingConfigProps {
11 /**
12 * ID of the public hosted zone to log DNS queries for. Changing this forces
13 * replacement.
14 */
15 hostedZoneId: string;
16 /**
17 * ARN of the CloudWatch Logs log group Route 53 publishes query logs to.
18 * The log group **must live in `us-east-1`** (Route 53 is a global service
19 * and only delivers query logs to that region), and a CloudWatch Logs
20 * resource policy in `us-east-1` must grant `route53.amazonaws.com`
21 * permission to `logs:CreateLogStream` and `logs:PutLogEvents` on it (see
22 * `AWS.Logs.ResourcePolicy`). Changing this forces replacement.
23 */
24 cloudWatchLogsLogGroupArn: string;
25 }
26
27 export interface QueryLoggingConfig extends Resource<
28 "AWS.Route53.QueryLoggingConfig",
29 QueryLoggingConfigProps,
30 {
31 /**
32 * ID of the query logging configuration.
33 */
34 id: string;
35 /**
36 * Hosted zone the configuration logs queries for.
37 */
38 hostedZoneId: string;
39 /**
40 * ARN of the destination CloudWatch Logs log group.
41 */
42 cloudWatchLogsLogGroupArn: string;
43 },
44 never,
45 Providers
46 > {}
47
48 /**
49 * DNS query logging for a Route 53 public hosted zone.
50 *
51 * Route 53 publishes query logs to a CloudWatch Logs log group in
52 * `us-east-1`. The log group needs a CloudWatch Logs resource policy (also in
53 * `us-east-1`) that allows the `route53.amazonaws.com` service principal to
54 * create log streams and put log events — model it with
55 * `AWS.Logs.ResourcePolicy`.
56 *
57 * A hosted zone can have at most one query logging configuration, and the
58 * configuration is immutable — changing either property replaces it.
59 * ### Enabling Query Logging
60 * **Example:** Log Queries for a Hosted Zone
61 * ```typescript
62 * // Both the log group and the resource policy must live in us-east-1.
63 * const policy = yield* Logs.ResourcePolicy("Route53QueryLogging", {
64 * policyName: "route53-query-logging",
65 * policyDocument: {
66 * Version: "2012-10-17",
67 * Statement: [
68 * {
69 * Effect: "Allow",
70 * Principal: { Service: "route53.amazonaws.com" },
71 * Action: ["logs:CreateLogStream", "logs:PutLogEvents"],
72 * Resource: `arn:aws:logs:us-east-1:${accountId}:log-group:/aws/route53/*`,
73 * },
74 * ],
75 * },
76 * });
77 *
78 * const logging = yield* QueryLoggingConfig("ZoneQueryLogging", {
79 * hostedZoneId: zone.id,
80 * cloudWatchLogsLogGroupArn: logGroup.logGroupArn,
81 * });
82 * ```
83 *
84 * @resource
85 */
86 export const QueryLoggingConfig = Resource<QueryLoggingConfig>("AWS.Route53.QueryLoggingConfig");
87
88 const toAttrs = (config: route53.QueryLoggingConfig): QueryLoggingConfig["Attributes"] => ({
89 id: config.Id,
90 hostedZoneId: config.HostedZoneId,
91 cloudWatchLogsLogGroupArn: config.CloudWatchLogsLogGroupArn,
92 });
93
94 /**
95 * `createQueryLoggingConfig` validates the CloudWatch Logs resource policy
96 * at call time. A policy that was just put (same deploy) can take a few
97 * seconds to become visible to Route 53, surfacing as
98 * `InsufficientCloudWatchLogsResourcePolicy` — retry it (and
99 * `ConcurrentModification`) on a bounded schedule (~40s).
100 *
101 * Explicitly typed: inlining `Effect.retry` with options in provider
102 * lifecycle code can widen the provider layer to `unknown` in declaration
103 * emit.
104 *
105 * @internal
106 */
107 const retryQueryLoggingCreate = <A, E extends { _tag: string }, R>(
108 self: Effect.Effect<A, E, R>,
109 ): Effect.Effect<A, E, R> =>
110 Effect.retry(self, {
111 while: (e) =>
112 e._tag === "InsufficientCloudWatchLogsResourcePolicy" || e._tag === "ConcurrentModification",
113 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(20)]),
114 });
115
116 export const QueryLoggingConfigProvider = () =>
117 Provider.effect(
118 QueryLoggingConfig,
119 Effect.gen(function* () {
120 // A hosted zone has at most one query logging configuration, so
121 // observing by zone id is exact.
122 const observeByZone = Effect.fn(function* (hostedZoneId: string) {
123 const response = yield* route53
124 .listQueryLoggingConfigs({
125 HostedZoneId: hostedZoneId,
126 MaxResults: 1,
127 })
128 .pipe(
129 Effect.catchTag("NoSuchHostedZone", () => Effect.succeed({ QueryLoggingConfigs: [] })),
130 );
131 return (response.QueryLoggingConfigs ?? []).at(0);
132 });
133
134 const observeById = Effect.fn(function* (id: string) {
135 const response = yield* route53
136 .getQueryLoggingConfig({ Id: id })
137 .pipe(Effect.catchTag("NoSuchQueryLoggingConfig", () => Effect.undefined));
138 return response?.QueryLoggingConfig;
139 });
140
141 const deleteById = Effect.fn(function* (id: string) {
142 yield* route53
143 .deleteQueryLoggingConfig({ Id: id })
144 .pipe(Effect.catchTag("NoSuchQueryLoggingConfig", () => Effect.void));
145 });
146
147 return {
148 stables: ["id", "hostedZoneId", "cloudWatchLogsLogGroupArn"],
149 list: () =>
150 route53.listQueryLoggingConfigs.pages({}).pipe(
151 Stream.runCollect,
152 Effect.map((chunk) =>
153 Array.from(chunk).flatMap((page) => (page.QueryLoggingConfigs ?? []).map(toAttrs)),
154 ),
155 ),
156 // The configuration is immutable (no update API) — any property
157 // change replaces it.
158 diff: Effect.fn(function* ({ olds, news }) {
159 if (!isResolved(news)) return undefined;
160 if (
161 olds.hostedZoneId !== news.hostedZoneId ||
162 olds.cloudWatchLogsLogGroupArn !== news.cloudWatchLogsLogGroupArn
163 ) {
164 return { action: "replace" } as const;
165 }
166 }),
167 read: Effect.fn(function* ({ olds, output }) {
168 // Prefer the stored config id; fall back to the zone lookup
169 // (state-loss recovery). A half-created state row can't round-trip
170 // an Output-valued `hostedZoneId` — report "not found".
171 const config = output?.id
172 ? yield* observeById(output.id)
173 : olds?.hostedZoneId !== undefined
174 ? yield* observeByZone(olds.hostedZoneId)
175 : undefined;
176 if (!config) {
177 return undefined;
178 }
179 return toAttrs(config);
180 }),
181 reconcile: Effect.fn(function* ({ news, session }) {
182 // Observe — the zone's (at most one) live configuration.
183 let observed = yield* observeByZone(news.hostedZoneId);
184
185 // Sync — the configuration is immutable; an adopted/drifted config
186 // pointing at a different log group is converged by delete +
187 // recreate (routine prop changes replace via `diff` instead).
188 if (observed && observed.CloudWatchLogsLogGroupArn !== news.cloudWatchLogsLogGroupArn) {
189 yield* deleteById(observed.Id);
190 observed = undefined;
191 }
192
193 // Ensure — create when missing. `QueryLoggingConfigAlreadyExists`
194 // is a race with a peer reconciler; re-observe.
195 if (!observed) {
196 observed = yield* retryQueryLoggingCreate(
197 route53.createQueryLoggingConfig({
198 HostedZoneId: news.hostedZoneId,
199 CloudWatchLogsLogGroupArn: news.cloudWatchLogsLogGroupArn,
200 }),
201 ).pipe(
202 Effect.map((response) => response.QueryLoggingConfig),
203 Effect.catchTag("QueryLoggingConfigAlreadyExists", () =>
204 observeByZone(news.hostedZoneId).pipe(
205 Effect.flatMap((existing) =>
206 existing
207 ? Effect.succeed(existing)
208 : Effect.die(
209 `Route53 query logging config for zone '${news.hostedZoneId}' already exists but could not be observed`,
210 ),
211 ),
212 ),
213 ),
214 );
215 }
216
217 yield* session.note(observed.Id);
218 return toAttrs(observed);
219 }),
220 delete: Effect.fn(function* ({ output }) {
221 yield* deleteById(output.id);
222 }),
223 };
224 }),
225 );