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

main
ts 267 lines 9.68 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 PrivateDnsNamespaceProps {
23 /**
24 * Name of the namespace — services are discoverable in DNS as
25 * `{service}.{name}` inside the associated VPC (e.g. `internal.example.com`
26 * yields `backend.internal.example.com`). Changing the name replaces the
27 * namespace.
28 * @default a generated DNS-compatible physical name
29 */
30 name?: string;
31 /**
32 * The ID of the Amazon VPC that the private DNS namespace is associated
33 * with (a Route 53 private hosted zone is created and associated with it).
34 * Changing the VPC replaces the namespace.
35 */
36 vpc: string;
37 /**
38 * A description for the namespace.
39 */
40 description?: string;
41 /**
42 * The TTL of the SOA record for the namespace's Route 53 private hosted
43 * zone (e.g. `"60 seconds"` or `Duration.seconds(60)`; a bare number is
44 * milliseconds).
45 */
46 ttl?: Duration.Input;
47 /**
48 * Tags to apply to the namespace. Merged with internal Alchemy tags.
49 */
50 tags?: Record<string, string>;
51 }
52
53 export interface PrivateDnsNamespace extends Resource<
54 "AWS.CloudMap.PrivateDnsNamespace",
55 PrivateDnsNamespaceProps,
56 {
57 /**
58 * The unique identifier of the namespace.
59 */
60 namespaceId: string;
61 /**
62 * The ARN of the namespace.
63 */
64 namespaceArn: string;
65 /**
66 * Name of the namespace (the private DNS domain, e.g. `internal.example`).
67 */
68 namespaceName: string;
69 /**
70 * The private Route 53 hosted zone Cloud Map created for the namespace.
71 */
72 hostedZoneId: string | undefined;
73 },
74 {},
75 Providers
76 > {}
77
78 /**
79 * An AWS Cloud Map private DNS namespace — the DNS-based service registry
80 * that ECS Service Connect and `serviceRegistries` point at. Services
81 * registered in the namespace are discoverable inside the associated VPC via
82 * DNS (`{service}.{namespace}`) and from anywhere via the
83 * `DiscoverInstances` API.
84 *
85 * Namespace creation and deletion are asynchronous — the provider polls the
86 * Cloud Map operations API (bounded) until they complete, which typically
87 * takes 30-60 seconds.
88 * ### Creating Namespaces
89 * **Example:** Private DNS Namespace in a VPC
90 * ```typescript
91 * import * as AWS from "@alchemy.run/aws";
92 *
93 * const vpc = yield* AWS.EC2.Vpc("AppVpc", { cidrBlock: "10.0.0.0/16" });
94 * const namespace = yield* AWS.CloudMap.PrivateDnsNamespace("AppNamespace", {
95 * name: "internal.example.com",
96 * vpc: vpc.vpcId,
97 * });
98 * ```
99 *
100 * **Example:** Namespace with SOA TTL and Description
101 * ```typescript
102 * const namespace = yield* AWS.CloudMap.PrivateDnsNamespace("AppNamespace", {
103 * name: "internal.example.com",
104 * vpc: vpc.vpcId,
105 * description: "service discovery for the app tier",
106 * ttl: "60 seconds",
107 * });
108 * ```
109 *
110 * ### Registering Services
111 * **Example:** Service with A Records
112 * ```typescript
113 * const service = yield* AWS.CloudMap.Service("Backend", {
114 * namespaceId: namespace.namespaceId,
115 * dnsRecords: [{ type: "A", ttl: "10 seconds" }],
116 * routingPolicy: "MULTIVALUE",
117 * });
118 * ```
119 *
120 * @resource
121 */
122 export const PrivateDnsNamespace = Resource<PrivateDnsNamespace>(
123 "AWS.CloudMap.PrivateDnsNamespace",
124 );
125
126 export const PrivateDnsNamespaceProvider = () =>
127 Provider.effect(
128 PrivateDnsNamespace,
129 Effect.gen(function* () {
130 const createName = Effect.fn(function* (id: string, props: { name?: string | undefined }) {
131 return props.name ?? (yield* createPhysicalName({ id, maxLength: 253, lowercase: true }));
132 });
133
134 const toAttributes = (namespace: sd.Namespace) => ({
135 namespaceId: namespace.Id!,
136 namespaceArn: namespace.Arn!,
137 namespaceName: namespace.Name!,
138 hostedZoneId: namespace.Properties?.DnsProperties?.HostedZoneId,
139 });
140
141 return PrivateDnsNamespace.Provider.of({
142 stables: ["namespaceId", "namespaceArn", "namespaceName"],
143
144 list: () =>
145 Effect.gen(function* () {
146 const pages = yield* sd.listNamespaces
147 .pages({
148 Filters: [{ Name: "TYPE", Values: ["DNS_PRIVATE"], Condition: "EQ" }],
149 })
150 .pipe(Stream.runCollect);
151 return Array.from(pages)
152 .flatMap((page) => page.Namespaces ?? [])
153 .filter((n) => n.Id !== undefined && n.Arn !== undefined && n.Name !== undefined)
154 .map((n) => ({
155 namespaceId: n.Id!,
156 namespaceArn: n.Arn!,
157 namespaceName: n.Name!,
158 hostedZoneId: n.Properties?.DnsProperties?.HostedZoneId,
159 }));
160 }),
161
162 read: Effect.fn(function* ({ id, olds, output }) {
163 const name = output?.namespaceName ?? (yield* createName(id, olds ?? {}));
164 const namespace = yield* observeNamespace("DNS_PRIVATE", name, output?.namespaceId);
165 if (namespace?.Id === undefined) {
166 return undefined;
167 }
168 const attrs = toAttributes(namespace);
169 const tags = yield* fetchObservedTags(attrs.namespaceArn);
170 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
171 }),
172
173 diff: Effect.fn(function* ({ id, news, olds }) {
174 if (!isResolved(news)) return undefined;
175 const oldName = yield* createName(id, olds);
176 const newName = yield* createName(id, news);
177 if (oldName !== newName) {
178 return { action: "replace" } as const;
179 }
180 if (olds.vpc !== news.vpc) {
181 return { action: "replace" } as const;
182 }
183 // description/ttl/tags fall through to the default update path
184 }),
185
186 reconcile: Effect.fn(function* ({ id, news, output, session }) {
187 const name = output?.namespaceName ?? (yield* createName(id, news));
188 const internalTags = yield* createInternalTags(id);
189 const desiredTags = { ...news.tags, ...internalTags };
190 const desiredTtl = toWireSeconds(news.ttl);
191
192 // 1. OBSERVE — cloud state is authoritative; output is an id cache
193 let namespace = yield* observeNamespace("DNS_PRIVATE", name, output?.namespaceId);
194
195 // 2. ENSURE — create if missing; namespace creation is async. The
196 // created namespace is observed by the operation's target id,
197 // riding out a same-name predecessor still deleting
198 if (namespace === undefined) {
199 yield* session.note(`creating private DNS namespace ${name} (async)...`);
200 namespace = yield* ensureNamespace(
201 "DNS_PRIVATE",
202 name,
203 sd.createPrivateDnsNamespace({
204 Name: name,
205 Vpc: news.vpc,
206 Description: news.description,
207 Properties:
208 desiredTtl !== undefined
209 ? { DnsProperties: { SOA: { TTL: desiredTtl } } }
210 : undefined,
211 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
212 Key,
213 Value,
214 })),
215 }),
216 );
217 }
218 if (namespace?.Id === undefined) {
219 return yield* sd.NamespaceNotFound.make({
220 message: `namespace ${name} not visible after create`,
221 });
222 }
223
224 // 3. SYNC — description + SOA TTL, observed vs desired
225 const observedTtl = namespace.Properties?.DnsProperties?.SOA?.TTL;
226 const descriptionDelta =
227 news.description !== undefined && news.description !== namespace.Description;
228 const ttlDelta = desiredTtl !== undefined && desiredTtl !== observedTtl;
229 if (descriptionDelta || ttlDelta) {
230 const update = yield* sd.updatePrivateDnsNamespace({
231 Id: namespace.Id,
232 Namespace: {
233 Description: descriptionDelta ? news.description : undefined,
234 Properties: ttlDelta ? { DnsProperties: { SOA: { TTL: desiredTtl! } } } : undefined,
235 },
236 });
237 if (update.OperationId !== undefined) {
238 yield* awaitOperation(update.OperationId);
239 }
240 }
241
242 // 3b. SYNC TAGS — diff against OBSERVED cloud tags
243 const observedTags = yield* fetchObservedTags(namespace.Arn!);
244 yield* syncTags(namespace.Arn!, observedTags, desiredTags);
245
246 yield* session.note(namespace.Id);
247 return toAttributes(namespace);
248 }),
249
250 delete: Effect.fn(function* ({ output }) {
251 const deleted = yield* retryWhileResourceInUse(
252 sd.deleteNamespace({ Id: output.namespaceId }),
253 ).pipe(
254 Effect.catchTags({
255 NamespaceNotFound: () => Effect.succeed({ OperationId: undefined }),
256 // an identical delete is already in flight — await THAT operation
257 // instead of silently skipping the deletion
258 DuplicateRequest: (e) => Effect.succeed({ OperationId: e.DuplicateOperationId }),
259 }),
260 );
261 if (deleted.OperationId !== undefined) {
262 yield* awaitOperation(deleted.OperationId);
263 }
264 }),
265 });
266 }),
267 );