@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 229 lines 8.32 KB
Raw
1 import * as eventbridge from "@distilled.cloud/aws/eventbridge";
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 type { AccountID } from "../Environment.ts";
8 import type { Providers } from "../Providers.ts";
9 import type { RegionID } from "../Region.ts";
10
11 export type {
12 ApiDestinationHttpMethod,
13 ApiDestinationState,
14 } from "@distilled.cloud/aws/eventbridge";
15
16 export type ApiDestinationName = string;
17 export type ApiDestinationArn =
18 `arn:aws:events:${RegionID}:${AccountID}:api-destination/${ApiDestinationName}/${string}`;
19
20 export interface ApiDestinationProps {
21 /**
22 * Name of the API destination. Must match [\.\-_A-Za-z0-9]+, 1-64
23 * characters. If omitted, a unique name will be generated.
24 */
25 name?: ApiDestinationName;
26
27 /**
28 * Description of the API destination. Max 512 characters.
29 */
30 description?: string;
31
32 /**
33 * ARN of the {@link Connection} providing the endpoint's authorization.
34 */
35 connectionArn: string;
36
37 /**
38 * The HTTPS endpoint EventBridge invokes for events routed to this API
39 * destination.
40 */
41 invocationEndpoint: string;
42
43 /**
44 * The HTTP method used against the endpoint.
45 */
46 httpMethod: eventbridge.ApiDestinationHttpMethod;
47
48 /**
49 * Maximum invocations per second EventBridge sends to the endpoint. The
50 * unit (per second) is part of the AWS field's semantics — this is a rate
51 * limit, not a duration.
52 * @default 300
53 */
54 invocationRateLimitPerSecond?: number;
55 }
56
57 /**
58 * An Amazon EventBridge API destination — an HTTPS endpoint configured as an
59 * event target, invoked with the authorization held by a {@link Connection}.
60 *
61 * API destinations do not support tags, so ownership is tracked by the
62 * deterministic physical name.
63 * ### Connecting to APIs
64 * **Example:** Webhook API Destination
65 * ```typescript
66 * const destination = yield* AWS.EventBridge.ApiDestination("Webhook", {
67 * connectionArn: connection.connectionArn,
68 * invocationEndpoint: "https://hooks.example.com/events",
69 * httpMethod: "POST",
70 * });
71 * ```
72 *
73 * **Example:** Rate-Limited API Destination as a Rule Target
74 * ```typescript
75 * const destination = yield* AWS.EventBridge.ApiDestination("SlowApi", {
76 * connectionArn: connection.connectionArn,
77 * invocationEndpoint: "https://api.example.com/ingest",
78 * httpMethod: "POST",
79 * invocationRateLimitPerSecond: 10,
80 * });
81 *
82 * const rule = yield* AWS.EventBridge.Rule("ToApi", {
83 * eventPattern: { source: ["my.app"] },
84 * targets: [{
85 * Id: "Api",
86 * Arn: destination.apiDestinationArn,
87 * RoleArn: role.roleArn,
88 * }],
89 * });
90 * ```
91 *
92 * @resource
93 */
94 export interface ApiDestination extends Resource<
95 "AWS.EventBridge.ApiDestination",
96 ApiDestinationProps,
97 {
98 /** The name of the API destination. */
99 apiDestinationName: ApiDestinationName;
100 /** The ARN of the API destination. */
101 apiDestinationArn: ApiDestinationArn;
102 /** The state of the API destination (`ACTIVE` or `INACTIVE`). */
103 apiDestinationState: eventbridge.ApiDestinationState;
104 },
105 never,
106 Providers
107 > {}
108 export const ApiDestination = Resource<ApiDestination>("AWS.EventBridge.ApiDestination");
109
110 export const ApiDestinationProvider = () =>
111 Provider.effect(
112 ApiDestination,
113 Effect.gen(function* () {
114 const createDestinationName = (id: string, props: { name?: string } = {}) =>
115 props.name
116 ? Effect.succeed(props.name)
117 : createPhysicalName({
118 id,
119 maxLength: 64,
120 });
121
122 return {
123 stables: ["apiDestinationName", "apiDestinationArn"],
124 diff: Effect.fn(function* ({ id, news, olds }) {
125 if (!isResolved(news)) return;
126 const oldName = yield* createDestinationName(id, olds);
127 const newName = yield* createDestinationName(id, news);
128 if (oldName !== newName) {
129 return { action: "replace" } as const;
130 }
131 }),
132 read: Effect.fn(function* ({ id, olds, output }) {
133 // API destinations don't support tags; the deterministic physical
134 // name is the ownership signal (it embeds app/stage/logical id).
135 const name = output?.apiDestinationName ?? (yield* createDestinationName(id, olds ?? {}));
136 const described = yield* eventbridge
137 .describeApiDestination({ Name: name })
138 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
139 if (!described?.Name || !described.ApiDestinationArn) {
140 return undefined;
141 }
142 return {
143 apiDestinationName: described.Name,
144 apiDestinationArn: described.ApiDestinationArn as ApiDestinationArn,
145 apiDestinationState: described.ApiDestinationState ?? "ACTIVE",
146 };
147 }),
148 list: () =>
149 Effect.gen(function* () {
150 const attrs: {
151 apiDestinationName: ApiDestinationName;
152 apiDestinationArn: ApiDestinationArn;
153 apiDestinationState: eventbridge.ApiDestinationState;
154 }[] = [];
155 let nextToken: string | undefined;
156 do {
157 const page = yield* eventbridge.listApiDestinations({
158 NextToken: nextToken,
159 });
160 for (const destination of page.ApiDestinations ?? []) {
161 if (!destination.Name || !destination.ApiDestinationArn) {
162 continue;
163 }
164 attrs.push({
165 apiDestinationName: destination.Name,
166 apiDestinationArn: destination.ApiDestinationArn as ApiDestinationArn,
167 apiDestinationState: destination.ApiDestinationState ?? "ACTIVE",
168 });
169 }
170 nextToken = page.NextToken;
171 } while (nextToken);
172 return attrs;
173 }),
174 reconcile: Effect.fn(function* ({ id, news, output, session }) {
175 const name = output?.apiDestinationName ?? (yield* createDestinationName(id, news));
176
177 // Observe — live cloud state is authoritative; a vanished
178 // destination falls through to create.
179 const observed = yield* eventbridge
180 .describeApiDestination({ Name: name })
181 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
182
183 if (!observed?.ApiDestinationArn) {
184 // Ensure — create the destination; tolerate an AlreadyExists
185 // race with a peer reconciler and converge via the update below.
186 yield* eventbridge
187 .createApiDestination({
188 Name: name,
189 Description: news.description,
190 ConnectionArn: news.connectionArn,
191 InvocationEndpoint: news.invocationEndpoint,
192 HttpMethod: news.httpMethod,
193 InvocationRateLimitPerSecond: news.invocationRateLimitPerSecond,
194 })
195 .pipe(Effect.catchTag("ResourceAlreadyExistsException", () => Effect.void));
196 } else {
197 // Sync — updateApiDestination overwrites the mutable aspects
198 // (description, connection, endpoint, method, rate limit) in one
199 // shot (idempotent on matching values).
200 yield* eventbridge.updateApiDestination({
201 Name: name,
202 Description: news.description,
203 ConnectionArn: news.connectionArn,
204 InvocationEndpoint: news.invocationEndpoint,
205 HttpMethod: news.httpMethod,
206 InvocationRateLimitPerSecond: news.invocationRateLimitPerSecond,
207 });
208 }
209
210 const settled = yield* eventbridge.describeApiDestination({
211 Name: name,
212 });
213 const apiDestinationArn = settled.ApiDestinationArn as ApiDestinationArn;
214
215 yield* session.note(apiDestinationArn);
216 return {
217 apiDestinationName: name,
218 apiDestinationArn,
219 apiDestinationState: settled.ApiDestinationState ?? "ACTIVE",
220 };
221 }),
222 delete: Effect.fn(function* ({ output }) {
223 yield* eventbridge
224 .deleteApiDestination({ Name: output.apiDestinationName })
225 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
226 }),
227 };
228 }),
229 );