@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, 06:00 UTC

main
ts 286 lines 10.4 KB
Raw
1 import * as vpclattice from "@distilled.cloud/aws/vpc-lattice";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, diffTags, hasAlchemyTags, tagRecord } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11 import { retryOnConflict } from "./internal.ts";
12
13 export class AccessLogSubscriptionUnexpectedResponse extends Data.TaggedError(
14 "AccessLogSubscriptionUnexpectedResponse",
15 )<{
16 readonly message: string;
17 readonly cause?: unknown;
18 }> {}
19
20 /**
21 * Which traffic a service-network access log subscription captures.
22 */
23 export type ServiceNetworkLogType = "SERVICE" | "RESOURCE";
24
25 /** The delivery service encoded in a destination ARN (`arn:aws:<service>:…`). */
26 const destinationType = (arn: string) => arn.split(":")[2] ?? "";
27
28 /**
29 * Normalize a destination ARN for comparison — CloudWatch log-group ARNs
30 * round-trip through the API with a trailing `:*`.
31 */
32 const normalizeDestinationArn = (arn: string) => arn.replace(/:\*$/, "");
33
34 export interface AccessLogSubscriptionProps {
35 /**
36 * ID or ARN of the service network or lattice service whose traffic is
37 * logged. Immutable — changing it replaces the subscription.
38 */
39 resourceIdentifier: string;
40 /**
41 * ARN of the delivery destination: a CloudWatch log group, Firehose
42 * delivery stream, or S3 bucket. The destination can be updated in place,
43 * but changing the destination *type* (e.g. CloudWatch → S3) replaces the
44 * subscription.
45 */
46 destinationArn: string;
47 /**
48 * For service networks, whether to log traffic to lattice services or to
49 * shared VPC resources. Immutable — changing it replaces the subscription.
50 * @default "SERVICE"
51 */
52 serviceNetworkLogType?: ServiceNetworkLogType;
53 /**
54 * User-defined tags to apply to the subscription.
55 */
56 tags?: Record<string, string>;
57 }
58
59 export interface AccessLogSubscription extends Resource<
60 "AWS.VpcLattice.AccessLogSubscription",
61 AccessLogSubscriptionProps,
62 {
63 /**
64 * Service-assigned unique ID of the subscription.
65 */
66 accessLogSubscriptionId: string;
67 /**
68 * ARN of the subscription.
69 */
70 accessLogSubscriptionArn: string;
71 /**
72 * ID of the service network or service whose traffic is logged.
73 */
74 resourceId: string;
75 /**
76 * ARN of the service network or service whose traffic is logged.
77 */
78 resourceArn: string;
79 /**
80 * ARN of the delivery destination.
81 */
82 destinationArn: string;
83 /**
84 * Current tags reported for the subscription.
85 */
86 tags: Record<string, string>;
87 },
88 never,
89 Providers
90 > {}
91
92 /**
93 * An Amazon VPC Lattice access log subscription — delivers per-request
94 * access logs for a service network or lattice service to CloudWatch Logs,
95 * Kinesis Data Firehose, or S3.
96 *
97 * ### Creating Access Log Subscriptions
98 * **Example:** Log a Service Network to CloudWatch
99 * ```typescript
100 * const logs = yield* AccessLogSubscription("NetworkLogs", {
101 * resourceIdentifier: network.serviceNetworkId,
102 * destinationArn: logGroup.logGroupArn,
103 * });
104 * ```
105 *
106 * **Example:** Log a Service to S3
107 * ```typescript
108 * const logs = yield* AccessLogSubscription("ServiceLogs", {
109 * resourceIdentifier: service.serviceId,
110 * destinationArn: bucket.bucketArn,
111 * });
112 * ```
113 *
114 * @resource
115 */
116 export const AccessLogSubscription = Resource<AccessLogSubscription>(
117 "AWS.VpcLattice.AccessLogSubscription",
118 );
119
120 export const AccessLogSubscriptionProvider = () =>
121 Provider.effect(
122 AccessLogSubscription,
123 Effect.gen(function* () {
124 const observe = (id: string) =>
125 vpclattice
126 .getAccessLogSubscription({ accessLogSubscriptionIdentifier: id })
127 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
128
129 // A resource can hold at most one subscription per destination type;
130 // recover the existing one for our destination's type.
131 const findByDestinationType = (resourceIdentifier: string, desiredDestinationArn: string) =>
132 vpclattice.listAccessLogSubscriptions.pages({ resourceIdentifier }).pipe(
133 Stream.runCollect,
134 Effect.map((chunk) =>
135 Array.from(chunk)
136 .flatMap((page) => page.items ?? [])
137 .find(
138 (s) => destinationType(s.destinationArn) === destinationType(desiredDestinationArn),
139 ),
140 ),
141 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
142 );
143
144 const syncTags = Effect.fn(function* (arn: string, desiredTags: Record<string, string>) {
145 const listed = yield* vpclattice.listTagsForResource({
146 resourceArn: arn,
147 });
148 const { removed, upsert } = diffTags(tagRecord(listed.tags), desiredTags);
149 if (upsert.length > 0) {
150 yield* vpclattice.tagResource({
151 resourceArn: arn,
152 tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
153 });
154 }
155 if (removed.length > 0) {
156 yield* vpclattice.untagResource({
157 resourceArn: arn,
158 tagKeys: removed,
159 });
160 }
161 });
162
163 return {
164 stables: [
165 "accessLogSubscriptionId",
166 "accessLogSubscriptionArn",
167 "resourceId",
168 "resourceArn",
169 ],
170 diff: Effect.fn(function* ({ olds, news }) {
171 if (!isResolved(news)) return;
172 if (
173 olds?.resourceIdentifier !== news.resourceIdentifier ||
174 (olds?.serviceNetworkLogType ?? undefined) !== news.serviceNetworkLogType
175 ) {
176 return { action: "replace" } as const;
177 }
178 // The destination is mutable in place, but only within the same
179 // destination service (CloudWatch/Firehose/S3).
180 if (
181 olds !== undefined &&
182 destinationType(olds.destinationArn) !== destinationType(news.destinationArn)
183 ) {
184 return { action: "replace" } as const;
185 }
186 }),
187 read: Effect.fn(function* ({ id, olds, output }) {
188 const subscription = output?.accessLogSubscriptionId
189 ? yield* observe(output.accessLogSubscriptionId)
190 : olds
191 ? yield* findByDestinationType(olds.resourceIdentifier, olds.destinationArn)
192 : undefined;
193 if (!subscription) return undefined;
194 const listed = yield* vpclattice.listTagsForResource({
195 resourceArn: subscription.arn,
196 });
197 const attrs = {
198 accessLogSubscriptionId: subscription.id,
199 accessLogSubscriptionArn: subscription.arn,
200 resourceId: subscription.resourceId,
201 resourceArn: subscription.resourceArn,
202 destinationArn: subscription.destinationArn,
203 tags: tagRecord(listed.tags),
204 };
205 return (yield* hasAlchemyTags(id, listed.tags)) ? attrs : Unowned(attrs);
206 }),
207 reconcile: Effect.fn(function* ({ id, news, output, session }) {
208 const internalTags = yield* createInternalTags(id);
209 const desiredTags = { ...internalTags, ...news.tags };
210
211 // Observe — prefer the stable id cache, fall back to discovering
212 // the resource's subscription for our destination type. The create
213 // response carries the same identifying fields but no timestamps,
214 // so keep the local shape to the fields we actually use.
215 let subscription:
216 | {
217 id: string;
218 arn: string;
219 resourceId: string;
220 resourceArn: string;
221 destinationArn: string;
222 }
223 | undefined = output?.accessLogSubscriptionId
224 ? yield* observe(output.accessLogSubscriptionId)
225 : yield* findByDestinationType(news.resourceIdentifier, news.destinationArn);
226
227 // Ensure — create if missing. A ConflictException means a
228 // subscription for this destination type already exists (a race);
229 // recover it and converge below.
230 if (!subscription) {
231 const created = yield* retryOnConflict(
232 vpclattice.createAccessLogSubscription({
233 resourceIdentifier: news.resourceIdentifier,
234 destinationArn: news.destinationArn,
235 serviceNetworkLogType: news.serviceNetworkLogType,
236 tags: desiredTags,
237 }),
238 ).pipe(
239 Effect.catchTag("ConflictException", () =>
240 findByDestinationType(news.resourceIdentifier, news.destinationArn),
241 ),
242 );
243 if (!created) {
244 return yield* new AccessLogSubscriptionUnexpectedResponse({
245 message: "Failed to create access log subscription",
246 });
247 }
248 subscription = created;
249 }
250
251 // Sync destination — mutable within the same destination type.
252 if (
253 normalizeDestinationArn(subscription.destinationArn) !==
254 normalizeDestinationArn(news.destinationArn)
255 ) {
256 yield* vpclattice.updateAccessLogSubscription({
257 accessLogSubscriptionIdentifier: subscription.id,
258 destinationArn: news.destinationArn,
259 });
260 }
261
262 yield* syncTags(subscription.arn, desiredTags);
263
264 yield* session.note(subscription.arn);
265 return {
266 accessLogSubscriptionId: subscription.id,
267 accessLogSubscriptionArn: subscription.arn,
268 resourceId: subscription.resourceId,
269 resourceArn: subscription.resourceArn,
270 destinationArn: news.destinationArn,
271 tags: desiredTags,
272 };
273 }),
274 // Sub-resource: subscriptions are keyed by their service network /
275 // service and are removed with it, so nuke has nothing to enumerate.
276 list: () => Effect.succeed([] as AccessLogSubscription["Attributes"][]),
277 delete: Effect.fn(function* ({ output }) {
278 yield* retryOnConflict(
279 vpclattice.deleteAccessLogSubscription({
280 accessLogSubscriptionIdentifier: output.accessLogSubscriptionId,
281 }),
282 ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
283 }),
284 };
285 }),
286 );