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

main
ts 245 lines 7.77 KB
Raw
1 import * as schemas from "@distilled.cloud/aws/schemas";
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, hasAlchemyTags } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10 import { syncSchemasTags } from "./internal.ts";
11
12 export type DiscovererState = "STARTED" | "STOPPED";
13
14 export interface DiscovererProps {
15 /**
16 * The ARN of the event bus to discover schemas on. Changing it replaces
17 * the discoverer.
18 */
19 sourceArn: string;
20
21 /**
22 * A description of the discoverer.
23 */
24 description?: string;
25
26 /**
27 * Whether the discoverer also discovers schemas from events sent by other
28 * accounts.
29 * @default true
30 */
31 crossAccount?: boolean;
32
33 /**
34 * The desired state of the discoverer. A discoverer starts automatically
35 * on creation.
36 * @default "STARTED"
37 */
38 state?: DiscovererState;
39
40 /**
41 * User tags to attach to the discoverer.
42 */
43 tags?: Record<string, string>;
44 }
45
46 export interface Discoverer extends Resource<
47 "AWS.Schemas.Discoverer",
48 DiscovererProps,
49 {
50 /** The ID of the discoverer. */
51 discovererId: string;
52 /** The ARN of the discoverer. */
53 discovererArn: string;
54 /** The ARN of the event bus being discovered. */
55 sourceArn: string;
56 /** The current state of the discoverer. */
57 state: DiscovererState;
58 },
59 never,
60 Providers
61 > {}
62
63 /**
64 * An EventBridge schema discoverer — automatically infers schemas from the
65 * events flowing through an event bus and publishes them (versioned) to the
66 * AWS-managed `discovered-schemas` registry.
67 *
68 * ### Creating a Discoverer
69 * **Example:** Discover Schemas on an Event Bus
70 * ```typescript
71 * const bus = yield* AWS.EventBridge.EventBus("AppBus", {});
72 *
73 * const discoverer = yield* AWS.Schemas.Discoverer("AppDiscoverer", {
74 * sourceArn: bus.eventBusArn,
75 * description: "Discovers schemas for application events",
76 * });
77 * ```
78 *
79 * **Example:** Stopped Discoverer
80 * ```typescript
81 * const discoverer = yield* AWS.Schemas.Discoverer("PausedDiscoverer", {
82 * sourceArn: bus.eventBusArn,
83 * state: "STOPPED",
84 * });
85 * ```
86 * The discoverer is provisioned but paused; set `state: "STARTED"` (or omit
87 * it) to resume discovery.
88 *
89 * @resource
90 */
91 export const Discoverer = Resource<Discoverer>("AWS.Schemas.Discoverer");
92
93 export const DiscovererProvider = () =>
94 Provider.effect(
95 Discoverer,
96 Effect.gen(function* () {
97 const describe = (discovererId: string) =>
98 schemas
99 .describeDiscoverer({ DiscovererId: discovererId })
100 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
101
102 const toAttrs = (d: {
103 DiscovererId?: string;
104 DiscovererArn?: string;
105 SourceArn?: string;
106 State?: string;
107 }) => ({
108 discovererId: d.DiscovererId!,
109 discovererArn: d.DiscovererArn!,
110 sourceArn: d.SourceArn!,
111 state: (d.State ?? "STARTED") as DiscovererState,
112 });
113
114 return Discoverer.Provider.of({
115 stables: ["discovererId", "discovererArn", "sourceArn"],
116
117 list: () =>
118 schemas.listDiscoverers.pages({}).pipe(
119 Stream.runCollect,
120 Effect.map((chunk) =>
121 Array.from(chunk).flatMap((page) =>
122 (page.Discoverers ?? [])
123 .filter(
124 (d) => d.DiscovererId != null && d.DiscovererArn != null && d.SourceArn != null,
125 )
126 .map(toAttrs),
127 ),
128 ),
129 ),
130
131 read: Effect.fn(function* ({ id, output }) {
132 if (output?.discovererId) {
133 const found = yield* describe(output.discovererId);
134 if (!found) return undefined;
135 const attrs = toAttrs(found);
136 return (yield* hasAlchemyTags(id, found.Tags)) ? attrs : Unowned(attrs);
137 }
138 // No cached id (the discoverer id is auto-assigned) — recover by
139 // scanning for a discoverer branded with our ownership tags.
140 const all = yield* schemas.listDiscoverers.items({}).pipe(
141 Stream.runCollect,
142 Effect.map((c) => Array.from(c)),
143 );
144 for (const d of all) {
145 if (
146 d.DiscovererId != null &&
147 d.DiscovererArn != null &&
148 d.SourceArn != null &&
149 (yield* hasAlchemyTags(id, d.Tags))
150 ) {
151 return toAttrs(d);
152 }
153 }
154 return undefined;
155 }),
156
157 diff: Effect.fn(function* ({ news, olds }) {
158 if (!isResolved(news)) return undefined;
159 if (news.sourceArn !== olds.sourceArn) {
160 return { action: "replace" } as const;
161 }
162 return undefined;
163 }),
164
165 reconcile: Effect.fn(function* ({ id, news, output, session }) {
166 const internalTags = yield* createInternalTags(id);
167
168 // OBSERVE — output.discovererId is only an id cache.
169 let live:
170 | {
171 Description?: string;
172 DiscovererArn?: string;
173 DiscovererId?: string;
174 SourceArn?: string;
175 State?: string;
176 CrossAccount?: boolean;
177 }
178 | undefined;
179 if (output?.discovererId) {
180 live = yield* describe(output.discovererId);
181 }
182
183 // ENSURE — create if missing. The id is auto-assigned, so there is
184 // no name race to tolerate.
185 if (live === undefined) {
186 live = yield* schemas.createDiscoverer({
187 SourceArn: news.sourceArn,
188 Description: news.description,
189 CrossAccount: news.crossAccount,
190 Tags: { ...news.tags, ...internalTags },
191 });
192 }
193 const discovererId = live.DiscovererId!;
194 const discovererArn = live.DiscovererArn!;
195
196 // SYNC description / crossAccount — diff observed against desired.
197 const desiredCrossAccount = news.crossAccount ?? true;
198 if (
199 (news.description ?? "") !== (live.Description ?? "") ||
200 desiredCrossAccount !== (live.CrossAccount ?? true)
201 ) {
202 live = yield* schemas.updateDiscoverer({
203 DiscovererId: discovererId,
204 Description: news.description ?? "",
205 CrossAccount: desiredCrossAccount,
206 });
207 }
208
209 // SYNC state — start/stop only on delta.
210 const desiredState: DiscovererState = news.state ?? "STARTED";
211 let state = (live.State ?? "STARTED") as DiscovererState;
212 if (state !== desiredState) {
213 if (desiredState === "STARTED") {
214 const r = yield* schemas.startDiscoverer({
215 DiscovererId: discovererId,
216 });
217 state = (r.State ?? "STARTED") as DiscovererState;
218 } else {
219 const r = yield* schemas.stopDiscoverer({
220 DiscovererId: discovererId,
221 });
222 state = (r.State ?? "STOPPED") as DiscovererState;
223 }
224 }
225
226 // SYNC tags — diff against observed cloud tags.
227 yield* syncSchemasTags(discovererArn, id, news.tags);
228
229 yield* session.note(discovererId);
230 return {
231 discovererId,
232 discovererArn,
233 sourceArn: live.SourceArn ?? news.sourceArn,
234 state,
235 };
236 }),
237
238 delete: Effect.fn(function* ({ output }) {
239 yield* schemas
240 .deleteDiscoverer({ DiscovererId: output.discovererId })
241 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
242 }),
243 });
244 }),
245 );