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

main
ts 220 lines 7.88 KB
Raw
1 import * as logs from "@distilled.cloud/aws/cloudwatch-logs";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Option from "effect/Option";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import type { PolicyDocument } from "../IAM/Policy.ts";
11 import type { Providers } from "../Providers.ts";
12
13 export interface DestinationProps {
14 /**
15 * Name of the destination. The destination name is its identity within the
16 * account and region (put semantics upsert by name). If omitted, a unique
17 * name is generated. Changing this value replaces the destination.
18 */
19 destinationName?: string;
20 /**
21 * ARN of the physical target that receives the log events — a Kinesis
22 * stream in this account.
23 */
24 targetArn: string;
25 /**
26 * ARN of an IAM role that CloudWatch Logs assumes to write to the target.
27 * The role must trust `logs.amazonaws.com`.
28 */
29 roleArn: string;
30 /**
31 * Access policy governing which accounts may create subscription filters
32 * against this destination, either as a JSON string or a structured
33 * document. Required before another account can subscribe.
34 */
35 accessPolicy?: PolicyDocument | string;
36 }
37
38 export interface Destination extends Resource<
39 "AWS.Logs.Destination",
40 DestinationProps,
41 {
42 destinationName: string;
43 destinationArn: string;
44 targetArn: string;
45 roleArn: string;
46 accessPolicy?: string;
47 },
48 never,
49 Providers
50 > {}
51
52 /**
53 * A CloudWatch Logs destination — a cross-account subscription target that
54 * forwards log events to a Kinesis stream. Producers in other accounts create
55 * subscription filters whose `destinationArn` points at this destination;
56 * the `accessPolicy` controls which accounts may subscribe.
57 * ### Cross-Account Log Fan-Out
58 * **Example:** Kinesis-Backed Destination
59 * ```typescript
60 * const destination = yield* Destination("CentralLogs", {
61 * targetArn: stream.streamArn,
62 * roleArn: role.roleArn,
63 * accessPolicy: {
64 * Version: "2012-10-17",
65 * Statement: [
66 * {
67 * Effect: "Allow",
68 * Principal: { AWS: "123456789012" },
69 * Action: ["logs:PutSubscriptionFilter"],
70 * Resource: "*",
71 * },
72 * ],
73 * },
74 * });
75 * ```
76 *
77 * @resource
78 */
79 export const Destination = Resource<Destination>("AWS.Logs.Destination");
80
81 /**
82 * `putDestination` validates that CloudWatch Logs can assume the delivery role
83 * at call time; when the role was created in the same deploy this fails with
84 * `InvalidParameterException` until IAM propagates. Bounded retry.
85 *
86 * NOTE: explicit return annotation is load-bearing — an inlined `Effect.retry`
87 * in provider lifecycle code widens the provider layer during declaration emit
88 * (see PATTERNS.md §7).
89 */
90 const retryThroughRolePropagation = <A, E extends { _tag: string }, R>(
91 self: Effect.Effect<A, E, R>,
92 ): Effect.Effect<A, E, R> =>
93 Effect.retry(self, {
94 while: (e) => e._tag === "InvalidParameterException" || e._tag === "OperationAbortedException",
95 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(9)]),
96 });
97
98 export const DestinationProvider = () =>
99 Provider.effect(
100 Destination,
101 Effect.gen(function* () {
102 const toDestinationName = (id: string, props: { destinationName?: string } = {}) =>
103 props.destinationName
104 ? Effect.succeed(props.destinationName)
105 : createPhysicalName({ id, maxLength: 512 });
106
107 const toPolicyString = (policy: PolicyDocument | string | undefined) =>
108 policy === undefined
109 ? undefined
110 : typeof policy === "string"
111 ? policy
112 : JSON.stringify(policy);
113
114 const observe = Effect.fn(function* (destinationName: string) {
115 return yield* logs.describeDestinations
116 .items({ DestinationNamePrefix: destinationName })
117 .pipe(
118 Stream.filter((destination) => destination.destinationName === destinationName),
119 Stream.runHead,
120 Effect.map(Option.getOrUndefined),
121 );
122 });
123
124 return {
125 stables: ["destinationName", "destinationArn"],
126 list: () =>
127 logs.describeDestinations.pages({}).pipe(
128 Stream.runCollect,
129 Effect.map((chunk) =>
130 Array.from(chunk)
131 .flatMap((page) => page.destinations ?? [])
132 .filter(
133 (
134 destination,
135 ): destination is logs.Destination & {
136 destinationName: string;
137 arn: string;
138 } => destination.destinationName != null && destination.arn != null,
139 )
140 .map((destination) => ({
141 destinationName: destination.destinationName,
142 destinationArn: destination.arn,
143 targetArn: destination.targetArn ?? "",
144 roleArn: destination.roleArn ?? "",
145 accessPolicy: destination.accessPolicy,
146 })),
147 ),
148 ),
149 diff: Effect.fn(function* ({ id, olds, news }) {
150 if (!isResolved(news)) return;
151 if ((yield* toDestinationName(id, olds)) !== (yield* toDestinationName(id, news))) {
152 return { action: "replace" } as const;
153 }
154 }),
155 read: Effect.fn(function* ({ id, olds, output }) {
156 const destinationName =
157 output?.destinationName ?? (yield* toDestinationName(id, olds ?? {}));
158 const observed = yield* observe(destinationName);
159 if (!observed?.arn) return undefined;
160 return {
161 destinationName,
162 destinationArn: observed.arn,
163 targetArn: observed.targetArn ?? "",
164 roleArn: observed.roleArn ?? "",
165 accessPolicy: observed.accessPolicy,
166 };
167 }),
168 reconcile: Effect.fn(function* ({ id, news, output, session }) {
169 const destinationName = output?.destinationName ?? (yield* toDestinationName(id, news));
170 const desiredPolicy = toPolicyString(news.accessPolicy);
171
172 // Observe — putDestination upserts by name; skip when target/role
173 // already match.
174 let observed = yield* observe(destinationName);
175 if (observed?.targetArn !== news.targetArn || observed?.roleArn !== news.roleArn) {
176 const put = yield* retryThroughRolePropagation(
177 logs.putDestination({
178 destinationName,
179 targetArn: news.targetArn,
180 roleArn: news.roleArn,
181 }),
182 );
183 observed = put.destination ?? (yield* observe(destinationName));
184 }
185
186 // Sync access policy against the observed policy.
187 if (desiredPolicy !== undefined && observed?.accessPolicy !== desiredPolicy) {
188 yield* retryThroughRolePropagation(
189 logs.putDestinationPolicy({
190 destinationName,
191 accessPolicy: desiredPolicy,
192 }),
193 );
194 }
195
196 yield* session.note(destinationName);
197
198 return {
199 destinationName,
200 destinationArn: observed?.arn ?? "",
201 targetArn: news.targetArn,
202 roleArn: news.roleArn,
203 accessPolicy: desiredPolicy,
204 };
205 }),
206 delete: Effect.fn(function* ({ output }) {
207 yield* logs.deleteDestination({ destinationName: output.destinationName }).pipe(
208 Effect.retry({
209 while: (error) =>
210 error._tag === "OperationAbortedException" ||
211 error._tag === "ServiceUnavailableException",
212 schedule: Schedule.exponential(100),
213 times: 8,
214 }),
215 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
216 );
217 }),
218 };
219 }),
220 );