@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 320 lines 10.7 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 { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, diffTags, hasAlchemyTags, tagRecord } 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 import { retryOnConflict, waitUntilAbsent } from "./internal.ts";
13
14 export class VpcLatticeRuleUnexpectedResponse extends Data.TaggedError(
15 "VpcLatticeRuleUnexpectedResponse",
16 )<{
17 readonly message: string;
18 readonly cause?: unknown;
19 }> {}
20
21 /**
22 * The match conditions of a listener rule (HTTP method, path, and header
23 * matches).
24 */
25 export type RuleMatch = vpclattice.RuleMatch;
26
27 /**
28 * The action a rule applies to matched traffic: forward to weighted target
29 * groups or answer with a fixed HTTP status.
30 */
31 export type RuleAction = vpclattice.RuleAction;
32
33 export interface RuleProps {
34 /**
35 * ID or ARN of the lattice service the rule's listener belongs to.
36 * Immutable — changing it replaces the rule.
37 */
38 serviceIdentifier: string;
39 /**
40 * ID or ARN of the listener the rule belongs to. Immutable — changing it
41 * replaces the rule.
42 */
43 listenerIdentifier: string;
44 /**
45 * Name of the rule. If omitted, a unique name is generated. Immutable —
46 * changing it replaces the rule.
47 */
48 name?: string;
49 /**
50 * Match conditions for the rule, e.g.
51 * `{ httpMatch: { pathMatch: { match: { prefix: "/api" } } } }`.
52 */
53 match: RuleMatch;
54 /**
55 * Rule priority (1–100). Lower numbers are evaluated first; each rule on a
56 * listener must have a unique priority.
57 */
58 priority: number;
59 /**
60 * Action applied to matched requests: forward to weighted target groups or
61 * return a fixed response status.
62 */
63 action: RuleAction;
64 /**
65 * User-defined tags to apply to the rule.
66 */
67 tags?: Record<string, string>;
68 }
69
70 export interface Rule extends Resource<
71 "AWS.VpcLattice.Rule",
72 RuleProps,
73 {
74 /**
75 * Service-assigned unique ID of the rule.
76 */
77 ruleId: string;
78 /**
79 * ARN of the rule.
80 */
81 ruleArn: string;
82 /**
83 * Physical name of the rule.
84 */
85 name: string;
86 /**
87 * Current rule priority.
88 */
89 priority: number;
90 /**
91 * ID or ARN of the owning lattice service (as configured).
92 */
93 serviceIdentifier: string;
94 /**
95 * ID or ARN of the owning listener (as configured).
96 */
97 listenerIdentifier: string;
98 /**
99 * Current tags reported for the rule.
100 */
101 tags: Record<string, string>;
102 },
103 never,
104 Providers
105 > {}
106
107 /**
108 * An Amazon VPC Lattice listener rule — matches HTTP requests by method,
109 * path, or headers and forwards them to target groups (or answers with a
110 * fixed response), evaluated in priority order before the listener's default
111 * action.
112 *
113 * ### Creating Rules
114 * **Example:** Path-Prefix Rule Forwarding to a Target Group
115 * ```typescript
116 * const rule = yield* Rule("ApiRule", {
117 * serviceIdentifier: service.serviceId,
118 * listenerIdentifier: listener.listenerId,
119 * priority: 10,
120 * match: { httpMatch: { pathMatch: { match: { prefix: "/api" } } } },
121 * action: {
122 * forward: {
123 * targetGroups: [
124 * { targetGroupIdentifier: targets.targetGroupId, weight: 100 },
125 * ],
126 * },
127 * },
128 * });
129 * ```
130 *
131 * **Example:** Method Match with a Fixed Response
132 * ```typescript
133 * const rule = yield* Rule("BlockDeletes", {
134 * serviceIdentifier: service.serviceId,
135 * listenerIdentifier: listener.listenerId,
136 * priority: 1,
137 * match: { httpMatch: { method: "DELETE" } },
138 * action: { fixedResponse: { statusCode: 403 } },
139 * });
140 * ```
141 *
142 * @resource
143 */
144 export const Rule = Resource<Rule>("AWS.VpcLattice.Rule");
145
146 export const RuleProvider = () =>
147 Provider.effect(
148 Rule,
149 Effect.gen(function* () {
150 const toName = (id: string, props: { name?: string } = {}) =>
151 props.name
152 ? Effect.succeed(props.name)
153 : createPhysicalName({ id, maxLength: 63, lowercase: true });
154
155 const observe = (
156 serviceIdentifier: string,
157 listenerIdentifier: string,
158 ruleIdentifier: string,
159 ) =>
160 vpclattice
161 .getRule({ serviceIdentifier, listenerIdentifier, ruleIdentifier })
162 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
163
164 const findByName = (serviceIdentifier: string, listenerIdentifier: string, name: string) =>
165 vpclattice.listRules.pages({ serviceIdentifier, listenerIdentifier }).pipe(
166 Stream.runCollect,
167 Effect.map((chunk) =>
168 Array.from(chunk)
169 .flatMap((page) => page.items ?? [])
170 .find((r) => r.name === name),
171 ),
172 Effect.flatMap((summary) =>
173 summary?.id
174 ? observe(serviceIdentifier, listenerIdentifier, summary.id)
175 : Effect.undefined,
176 ),
177 // The owning listener/service may already be gone during
178 // teardown races.
179 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
180 );
181
182 const syncTags = Effect.fn(function* (arn: string, desiredTags: Record<string, string>) {
183 const listed = yield* vpclattice.listTagsForResource({
184 resourceArn: arn,
185 });
186 const { removed, upsert } = diffTags(tagRecord(listed.tags), desiredTags);
187 if (upsert.length > 0) {
188 yield* vpclattice.tagResource({
189 resourceArn: arn,
190 tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
191 });
192 }
193 if (removed.length > 0) {
194 yield* vpclattice.untagResource({
195 resourceArn: arn,
196 tagKeys: removed,
197 });
198 }
199 });
200
201 return {
202 stables: ["ruleId", "ruleArn", "name", "serviceIdentifier", "listenerIdentifier"],
203 diff: Effect.fn(function* ({ id, olds, news }) {
204 if (!isResolved(news)) return;
205 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
206 return { action: "replace" } as const;
207 }
208 if (
209 olds?.serviceIdentifier !== news.serviceIdentifier ||
210 olds?.listenerIdentifier !== news.listenerIdentifier
211 ) {
212 return { action: "replace" } as const;
213 }
214 }),
215 read: Effect.fn(function* ({ id, olds, output }) {
216 const serviceIdentifier = output?.serviceIdentifier ?? olds?.serviceIdentifier;
217 const listenerIdentifier = output?.listenerIdentifier ?? olds?.listenerIdentifier;
218 if (!serviceIdentifier || !listenerIdentifier) return undefined;
219 const rule = output?.ruleId
220 ? yield* observe(serviceIdentifier, listenerIdentifier, output.ruleId)
221 : yield* findByName(
222 serviceIdentifier,
223 listenerIdentifier,
224 yield* toName(id, olds ?? {}),
225 );
226 if (!rule?.arn || !rule.id) return undefined;
227 const listed = yield* vpclattice.listTagsForResource({
228 resourceArn: rule.arn,
229 });
230 const attrs = {
231 ruleId: rule.id,
232 ruleArn: rule.arn,
233 name: rule.name!,
234 priority: rule.priority ?? 0,
235 serviceIdentifier,
236 listenerIdentifier,
237 tags: tagRecord(listed.tags),
238 };
239 return (yield* hasAlchemyTags(id, listed.tags)) ? attrs : Unowned(attrs);
240 }),
241 reconcile: Effect.fn(function* ({ id, news, output, session }) {
242 const name = yield* toName(id, news);
243 const internalTags = yield* createInternalTags(id);
244 const desiredTags = { ...internalTags, ...news.tags };
245
246 // Observe — prefer the stable id cache, fall back to name lookup.
247 let rule = output?.ruleId
248 ? yield* observe(news.serviceIdentifier, news.listenerIdentifier, output.ruleId)
249 : yield* findByName(news.serviceIdentifier, news.listenerIdentifier, name);
250
251 // Ensure — create if missing.
252 if (!rule?.arn || !rule.id) {
253 rule = yield* retryOnConflict(
254 vpclattice.createRule({
255 serviceIdentifier: news.serviceIdentifier,
256 listenerIdentifier: news.listenerIdentifier,
257 name,
258 match: news.match,
259 priority: news.priority,
260 action: news.action,
261 }),
262 ).pipe(
263 Effect.catchTag("ConflictException", () =>
264 findByName(news.serviceIdentifier, news.listenerIdentifier, name),
265 ),
266 );
267 if (!rule?.arn || !rule.id) {
268 return yield* new VpcLatticeRuleUnexpectedResponse({
269 message: `Failed to create rule ${name}`,
270 });
271 }
272 } else if (
273 JSON.stringify(rule.match) !== JSON.stringify(news.match) ||
274 rule.priority !== news.priority ||
275 JSON.stringify(rule.action) !== JSON.stringify(news.action)
276 ) {
277 // Sync match/priority/action — all mutable in place.
278 yield* retryOnConflict(
279 vpclattice.updateRule({
280 serviceIdentifier: news.serviceIdentifier,
281 listenerIdentifier: news.listenerIdentifier,
282 ruleIdentifier: rule.id,
283 match: news.match,
284 priority: news.priority,
285 action: news.action,
286 }),
287 );
288 }
289
290 yield* syncTags(rule.arn, desiredTags);
291
292 yield* session.note(rule.arn);
293 return {
294 ruleId: rule.id,
295 ruleArn: rule.arn,
296 name,
297 priority: news.priority,
298 serviceIdentifier: news.serviceIdentifier,
299 listenerIdentifier: news.listenerIdentifier,
300 tags: desiredTags,
301 };
302 }),
303 // Sub-resource: rules are keyed by their owning service/listener and
304 // are removed with them, so nuke has nothing to enumerate.
305 list: () => Effect.succeed([] as Rule["Attributes"][]),
306 delete: Effect.fn(function* ({ output }) {
307 yield* retryOnConflict(
308 vpclattice.deleteRule({
309 serviceIdentifier: output.serviceIdentifier,
310 listenerIdentifier: output.listenerIdentifier,
311 ruleIdentifier: output.ruleId,
312 }),
313 ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
314 yield* waitUntilAbsent(
315 observe(output.serviceIdentifier, output.listenerIdentifier, output.ruleId),
316 );
317 }),
318 };
319 }),
320 );