@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 232 lines 8.55 KB
Raw
1 import * as sd from "@distilled.cloud/aws/servicediscovery";
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, hasAlchemyTags } from "alchemy/Tags";
8 import { toWireSeconds } from "alchemy/Util/Duration";
9 import type * as Duration from "effect/Duration";
10 import * as Effect from "effect/Effect";
11 import * as Stream from "effect/Stream";
12 import type { Providers } from "../Providers.ts";
13 import {
14 awaitOperation,
15 ensureNamespace,
16 fetchObservedTags,
17 observeNamespace,
18 retryWhileResourceInUse,
19 syncTags,
20 } from "./internal.ts";
21
22 export interface PublicDnsNamespaceProps {
23 /**
24 * Name of the namespace — must be a domain name you intend to serve
25 * publicly (a Route 53 public hosted zone is created for it). Changing the
26 * name replaces the namespace.
27 * @default a generated DNS-compatible physical name
28 */
29 name?: string;
30 /**
31 * A description for the namespace.
32 */
33 description?: string;
34 /**
35 * The TTL of the SOA record for the namespace's Route 53 public hosted
36 * zone (e.g. `"60 seconds"` or `Duration.seconds(60)`; a bare number is
37 * milliseconds).
38 */
39 ttl?: Duration.Input;
40 /**
41 * Tags to apply to the namespace. Merged with internal Alchemy tags.
42 */
43 tags?: Record<string, string>;
44 }
45
46 export interface PublicDnsNamespace extends Resource<
47 "AWS.CloudMap.PublicDnsNamespace",
48 PublicDnsNamespaceProps,
49 {
50 /**
51 * The unique identifier of the namespace.
52 */
53 namespaceId: string;
54 /**
55 * The ARN of the namespace.
56 */
57 namespaceArn: string;
58 /**
59 * Name of the namespace (the public DNS domain).
60 */
61 namespaceName: string;
62 /**
63 * The public Route 53 hosted zone Cloud Map created for the namespace.
64 */
65 hostedZoneId: string | undefined;
66 },
67 {},
68 Providers
69 > {}
70
71 /**
72 * An AWS Cloud Map public DNS namespace — a service registry backed by a
73 * Route 53 **public** hosted zone, so registered instances are discoverable
74 * on the public internet via DNS as well as via the `DiscoverInstances` API.
75 *
76 * The hosted zone incurs standard Route 53 charges while the namespace
77 * exists, and the namespace name is only useful if you control the domain.
78 *
79 * Namespace creation and deletion are asynchronous — the provider polls the
80 * Cloud Map operations API (bounded) until they complete.
81 * ### Creating Namespaces
82 * **Example:** Public DNS Namespace
83 * ```typescript
84 * import * as AWS from "@alchemy.run/aws";
85 *
86 * const namespace = yield* AWS.CloudMap.PublicDnsNamespace("PublicNamespace", {
87 * name: "discovery.example.com",
88 * });
89 * ```
90 *
91 * @resource
92 */
93 export const PublicDnsNamespace = Resource<PublicDnsNamespace>("AWS.CloudMap.PublicDnsNamespace");
94
95 export const PublicDnsNamespaceProvider = () =>
96 Provider.effect(
97 PublicDnsNamespace,
98 Effect.gen(function* () {
99 const createName = Effect.fn(function* (id: string, props: { name?: string | undefined }) {
100 return props.name ?? (yield* createPhysicalName({ id, maxLength: 253, lowercase: true }));
101 });
102
103 const toAttributes = (namespace: sd.Namespace) => ({
104 namespaceId: namespace.Id!,
105 namespaceArn: namespace.Arn!,
106 namespaceName: namespace.Name!,
107 hostedZoneId: namespace.Properties?.DnsProperties?.HostedZoneId,
108 });
109
110 return PublicDnsNamespace.Provider.of({
111 stables: ["namespaceId", "namespaceArn", "namespaceName"],
112
113 list: () =>
114 Effect.gen(function* () {
115 const pages = yield* sd.listNamespaces
116 .pages({
117 Filters: [{ Name: "TYPE", Values: ["DNS_PUBLIC"], Condition: "EQ" }],
118 })
119 .pipe(Stream.runCollect);
120 return Array.from(pages)
121 .flatMap((page) => page.Namespaces ?? [])
122 .filter((n) => n.Id !== undefined && n.Arn !== undefined && n.Name !== undefined)
123 .map((n) => ({
124 namespaceId: n.Id!,
125 namespaceArn: n.Arn!,
126 namespaceName: n.Name!,
127 hostedZoneId: n.Properties?.DnsProperties?.HostedZoneId,
128 }));
129 }),
130
131 read: Effect.fn(function* ({ id, olds, output }) {
132 const name = output?.namespaceName ?? (yield* createName(id, olds ?? {}));
133 const namespace = yield* observeNamespace("DNS_PUBLIC", name, output?.namespaceId);
134 if (namespace?.Id === undefined) {
135 return undefined;
136 }
137 const attrs = toAttributes(namespace);
138 const tags = yield* fetchObservedTags(attrs.namespaceArn);
139 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
140 }),
141
142 diff: Effect.fn(function* ({ id, news = {}, olds = {} }) {
143 if (!isResolved(news)) return undefined;
144 const oldName = yield* createName(id, olds);
145 const newName = yield* createName(id, news);
146 if (oldName !== newName) {
147 return { action: "replace" } as const;
148 }
149 // description/ttl/tags fall through to the default update path
150 }),
151
152 reconcile: Effect.fn(function* ({ id, news = {}, output, session }) {
153 const name = output?.namespaceName ?? (yield* createName(id, news));
154 const internalTags = yield* createInternalTags(id);
155 const desiredTags = { ...news.tags, ...internalTags };
156 const desiredTtl = toWireSeconds(news.ttl);
157
158 // 1. OBSERVE
159 let namespace = yield* observeNamespace("DNS_PUBLIC", name, output?.namespaceId);
160
161 // 2. ENSURE — create if missing (async operation); the created
162 // namespace is observed by the operation's target id, riding out
163 // a same-name predecessor still deleting (see ensureNamespace)
164 if (namespace === undefined) {
165 yield* session.note(`creating public DNS namespace ${name} (async)...`);
166 namespace = yield* ensureNamespace(
167 "DNS_PUBLIC",
168 name,
169 sd.createPublicDnsNamespace({
170 Name: name,
171 Description: news.description,
172 Properties:
173 desiredTtl !== undefined
174 ? { DnsProperties: { SOA: { TTL: desiredTtl } } }
175 : undefined,
176 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
177 Key,
178 Value,
179 })),
180 }),
181 );
182 }
183 if (namespace?.Id === undefined) {
184 return yield* sd.NamespaceNotFound.make({
185 message: `namespace ${name} not visible after create`,
186 });
187 }
188
189 // 3. SYNC — description + SOA TTL, observed vs desired
190 const observedTtl = namespace.Properties?.DnsProperties?.SOA?.TTL;
191 const descriptionDelta =
192 news.description !== undefined && news.description !== namespace.Description;
193 const ttlDelta = desiredTtl !== undefined && desiredTtl !== observedTtl;
194 if (descriptionDelta || ttlDelta) {
195 const update = yield* sd.updatePublicDnsNamespace({
196 Id: namespace.Id,
197 Namespace: {
198 Description: descriptionDelta ? news.description : undefined,
199 Properties: ttlDelta ? { DnsProperties: { SOA: { TTL: desiredTtl! } } } : undefined,
200 },
201 });
202 if (update.OperationId !== undefined) {
203 yield* awaitOperation(update.OperationId);
204 }
205 }
206
207 // 3b. SYNC TAGS — diff against OBSERVED cloud tags
208 const observedTags = yield* fetchObservedTags(namespace.Arn!);
209 yield* syncTags(namespace.Arn!, observedTags, desiredTags);
210
211 yield* session.note(namespace.Id);
212 return toAttributes(namespace);
213 }),
214
215 delete: Effect.fn(function* ({ output }) {
216 const deleted = yield* retryWhileResourceInUse(
217 sd.deleteNamespace({ Id: output.namespaceId }),
218 ).pipe(
219 Effect.catchTags({
220 NamespaceNotFound: () => Effect.succeed({ OperationId: undefined }),
221 // an identical delete is already in flight — await THAT operation
222 // instead of silently skipping the deletion
223 DuplicateRequest: (e) => Effect.succeed({ OperationId: e.DuplicateOperationId }),
224 }),
225 );
226 if (deleted.OperationId !== undefined) {
227 yield* awaitOperation(deleted.OperationId);
228 }
229 }),
230 });
231 }),
232 );