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

main
ts 512 lines 19.1 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 Option from "effect/Option";
12 import * as Stream from "effect/Stream";
13 import type { Providers } from "../Providers.ts";
14 import {
15 awaitOperation,
16 deregisterAllInstances,
17 fetchObservedTags,
18 retryWhileResourceInUse,
19 syncTags,
20 } from "./internal.ts";
21
22 export interface ServiceDnsRecord {
23 /**
24 * The DNS record type Cloud Map creates in the namespace's hosted zone
25 * when an instance is registered. Changing the set of record types
26 * replaces the service.
27 */
28 type: "A" | "AAAA" | "SRV" | "CNAME";
29 /**
30 * The TTL of the DNS record (e.g. `"10 seconds"` or
31 * `Duration.seconds(10)`; a bare number is milliseconds). Mutable.
32 */
33 ttl: Duration.Input;
34 }
35
36 export interface ServiceProps {
37 /**
38 * Name of the service — for DNS namespaces this becomes the DNS label
39 * (`{name}.{namespace}`). Changing the name replaces the service.
40 * @default a generated DNS-compatible physical name
41 */
42 name?: string;
43 /**
44 * The ID of the namespace to register the service in. Changing the
45 * namespace replaces the service.
46 */
47 namespaceId: string;
48 /**
49 * A description for the service.
50 */
51 description?: string;
52 /**
53 * DNS records Cloud Map creates when instances are registered. Omit for
54 * API-only (HTTP namespace) services. TTLs are mutable; changing the set
55 * of record types replaces the service.
56 */
57 dnsRecords?: ServiceDnsRecord[];
58 /**
59 * How Route 53 responds to DNS queries: `MULTIVALUE` returns up to eight
60 * healthy records, `WEIGHTED` returns one. Create-only — changing it
61 * replaces the service.
62 * @default "MULTIVALUE"
63 */
64 routingPolicy?: "MULTIVALUE" | "WEIGHTED";
65 /**
66 * A Route 53 health check for instances (public DNS namespaces only).
67 * Mutually exclusive with `healthCheckCustomConfig`.
68 */
69 healthCheckConfig?: {
70 /** The endpoint protocol Route 53 health-checks: HTTP, HTTPS, or TCP. */
71 type: "HTTP" | "HTTPS" | "TCP";
72 /** The path Route 53 requests, e.g. `/health` (HTTP/HTTPS only). */
73 resourcePath?: string;
74 /** Consecutive failures before the instance is considered unhealthy. */
75 failureThreshold?: number;
76 };
77 /**
78 * Custom health checking — instance health is pushed via
79 * `UpdateInstanceCustomHealthStatus` instead of probed by Route 53.
80 * Create-only: it cannot be added, changed, or removed after creation, so
81 * any change replaces the service.
82 */
83 healthCheckCustomConfig?: {
84 /** Deprecated by AWS (always behaves as 1); retained for parity. */
85 failureThreshold?: number;
86 };
87 /**
88 * Set to `"HTTP"` to force API-only discovery even inside a DNS namespace.
89 * Create-only — changing it replaces the service.
90 */
91 type?: "HTTP";
92 /**
93 * Custom service-level attributes (up to 30 key/value pairs) stored on the
94 * service and readable at runtime via `GetServiceAttributes`. Mutable —
95 * reconcile diffs the observed attributes against this map, upserting
96 * changed keys and deleting keys no longer declared.
97 */
98 attributes?: Record<string, string>;
99 /**
100 * Tags to apply to the service. Merged with internal Alchemy tags.
101 */
102 tags?: Record<string, string>;
103 }
104
105 export interface Service extends Resource<
106 "AWS.CloudMap.Service",
107 ServiceProps,
108 {
109 /**
110 * The unique identifier of the service.
111 */
112 serviceId: string;
113 /**
114 * The ARN of the service.
115 */
116 serviceArn: string;
117 /**
118 * Name of the service.
119 */
120 serviceName: string;
121 /**
122 * The namespace the service belongs to.
123 */
124 namespaceId: string;
125 /**
126 * Name of the namespace the service belongs to.
127 */
128 namespaceName: string;
129 },
130 {},
131 Providers
132 > {}
133
134 /**
135 * An AWS Cloud Map service — a named entry in a namespace that instances
136 * register against. For DNS namespaces, Cloud Map creates the configured DNS
137 * records per registered instance; every service is also queryable via the
138 * `DiscoverInstances` API. This is what ECS `serviceRegistries[].registryArn`
139 * consumes.
140 * ### Creating Services
141 * **Example:** DNS Service with A Records
142 * ```typescript
143 * import * as AWS from "@alchemy.run/aws";
144 *
145 * const namespace = yield* AWS.CloudMap.PrivateDnsNamespace("AppNamespace", {
146 * name: "internal.example.com",
147 * vpc: vpc.vpcId,
148 * });
149 *
150 * const service = yield* AWS.CloudMap.Service("Backend", {
151 * namespaceId: namespace.namespaceId,
152 * dnsRecords: [{ type: "A", ttl: "10 seconds" }],
153 * routingPolicy: "MULTIVALUE",
154 * });
155 * ```
156 *
157 * **Example:** API-only Service in an HTTP Namespace
158 * ```typescript
159 * const namespace = yield* AWS.CloudMap.HttpNamespace("AppNamespace");
160 * const service = yield* AWS.CloudMap.Service("Backend", {
161 * namespaceId: namespace.namespaceId,
162 * });
163 * ```
164 *
165 * **Example:** Service with Custom Health Checks
166 * ```typescript
167 * const service = yield* AWS.CloudMap.Service("Backend", {
168 * namespaceId: namespace.namespaceId,
169 * dnsRecords: [{ type: "SRV", ttl: "10 seconds" }],
170 * healthCheckCustomConfig: {},
171 * });
172 * ```
173 *
174 * **Example:** Service with Custom Attributes
175 * ```typescript
176 * const service = yield* AWS.CloudMap.Service("Backend", {
177 * namespaceId: namespace.namespaceId,
178 * attributes: { tier: "backend", version: "2" },
179 * });
180 * ```
181 *
182 * ### Discovering Instances
183 * **Example:** Discover Healthy Instances from a Lambda
184 * ```typescript
185 * // init
186 * const discover = yield* AWS.CloudMap.DiscoverInstances(service);
187 *
188 * // runtime
189 * const { Instances } = yield* discover({ HealthStatus: "HEALTHY" });
190 * ```
191 *
192 * @resource
193 */
194 export const Service = Resource<Service>("AWS.CloudMap.Service");
195
196 export const ServiceProvider = () =>
197 Provider.effect(
198 Service,
199 Effect.gen(function* () {
200 const createName = Effect.fn(function* (id: string, props: { name?: string | undefined }) {
201 // 63 = the Route 53 per-label limit; the service name becomes the
202 // DNS label `{name}.{namespace}` for DNS namespaces
203 return props.name ?? (yield* createPhysicalName({ id, maxLength: 63, lowercase: true }));
204 });
205
206 /** Observe by cached id, falling back to name lookup in the namespace. */
207 const observeService = Effect.fn(function* (
208 namespaceId: string,
209 name: string,
210 serviceId: string | undefined,
211 ) {
212 if (serviceId !== undefined) {
213 const byId = yield* sd.getService({ Id: serviceId }).pipe(
214 Effect.map((r) => r.Service),
215 Effect.catchTag("ServiceNotFound", () => Effect.undefined),
216 );
217 if (byId !== undefined) {
218 return byId;
219 }
220 }
221 const summary = yield* sd.listServices
222 .pages({
223 Filters: [{ Name: "NAMESPACE_ID", Values: [namespaceId], Condition: "EQ" }],
224 })
225 .pipe(
226 Stream.map((page) => page.Services ?? []),
227 Stream.flattenIterable,
228 Stream.filter((s) => s.Name === name),
229 Stream.runHead,
230 Effect.map(Option.getOrUndefined),
231 );
232 if (summary?.Id === undefined) {
233 return undefined;
234 }
235 return yield* sd.getService({ Id: summary.Id }).pipe(
236 Effect.map((r) => r.Service),
237 Effect.catchTag("ServiceNotFound", () => Effect.undefined),
238 );
239 });
240
241 const resolveNamespaceName = Effect.fn(function* (namespaceId: string) {
242 const namespace = yield* sd.getNamespace({ Id: namespaceId });
243 return namespace.Namespace?.Name ?? "";
244 });
245
246 const toDesiredDnsConfig = (props: ServiceProps) =>
247 props.dnsRecords !== undefined
248 ? {
249 DnsRecords: props.dnsRecords.map((record) => ({
250 Type: record.type,
251 TTL: toWireSeconds(record.ttl)!,
252 })),
253 RoutingPolicy: props.routingPolicy,
254 }
255 : undefined;
256
257 const toDesiredHealthCheckConfig = (props: ServiceProps) =>
258 props.healthCheckConfig !== undefined
259 ? {
260 Type: props.healthCheckConfig.type,
261 ResourcePath: props.healthCheckConfig.resourcePath,
262 FailureThreshold: props.healthCheckConfig.failureThreshold,
263 }
264 : undefined;
265
266 const recordKey = (records: { Type: string; TTL: number }[]) =>
267 records
268 .map((r) => `${r.Type}:${r.TTL}`)
269 .sort()
270 .join(",");
271
272 const recordTypeKey = (records: { type: string }[] | undefined) =>
273 (records ?? [])
274 .map((r) => r.type)
275 .sort()
276 .join(",");
277
278 return Service.Provider.of({
279 stables: ["serviceId", "serviceArn", "serviceName", "namespaceId", "namespaceName"],
280
281 list: () =>
282 Effect.gen(function* () {
283 const pages = yield* sd.listServices.pages({}).pipe(Stream.runCollect);
284 const summaries = Array.from(pages).flatMap((page) => page.Services ?? []);
285 const items = yield* Effect.forEach(
286 summaries,
287 (summary) =>
288 Effect.gen(function* () {
289 if (summary.Id === undefined) return undefined;
290 const service = yield* sd.getService({ Id: summary.Id }).pipe(
291 Effect.map((r) => r.Service),
292 Effect.catchTag("ServiceNotFound", () => Effect.undefined),
293 );
294 if (
295 service?.Id === undefined ||
296 service.Arn === undefined ||
297 service.Name === undefined ||
298 service.NamespaceId === undefined
299 ) {
300 return undefined;
301 }
302 const namespaceName = yield* resolveNamespaceName(service.NamespaceId).pipe(
303 Effect.catchTag("NamespaceNotFound", () => Effect.succeed("")),
304 );
305 return {
306 serviceId: service.Id,
307 serviceArn: service.Arn,
308 serviceName: service.Name,
309 namespaceId: service.NamespaceId,
310 namespaceName,
311 };
312 }),
313 { concurrency: 10 },
314 );
315 return items.filter((item): item is Service["Attributes"] => item !== undefined);
316 }),
317
318 read: Effect.fn(function* ({ id, olds, output }) {
319 const namespaceId = output?.namespaceId ?? olds?.namespaceId;
320 if (namespaceId === undefined) return undefined;
321 const name = output?.serviceName ?? (yield* createName(id, olds ?? {}));
322 const service = yield* observeService(namespaceId, name, output?.serviceId);
323 if (
324 service?.Id === undefined ||
325 service.Arn === undefined ||
326 service.NamespaceId === undefined
327 ) {
328 return undefined;
329 }
330 const namespaceName = yield* resolveNamespaceName(service.NamespaceId).pipe(
331 Effect.catchTag("NamespaceNotFound", () => Effect.succeed("")),
332 );
333 const attrs = {
334 serviceId: service.Id,
335 serviceArn: service.Arn,
336 serviceName: service.Name ?? name,
337 namespaceId: service.NamespaceId,
338 namespaceName,
339 };
340 const tags = yield* fetchObservedTags(attrs.serviceArn);
341 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
342 }),
343
344 diff: Effect.fn(function* ({ id, news, olds }) {
345 if (!isResolved(news)) return undefined;
346 const oldName = yield* createName(id, olds);
347 const newName = yield* createName(id, news);
348 if (oldName !== newName) {
349 return { action: "replace" } as const;
350 }
351 if (olds.namespaceId !== news.namespaceId) {
352 return { action: "replace" } as const;
353 }
354 if (olds.routingPolicy !== news.routingPolicy) {
355 return { action: "replace" } as const;
356 }
357 if (recordTypeKey(olds.dnsRecords) !== recordTypeKey(news.dnsRecords)) {
358 return { action: "replace" } as const;
359 }
360 // healthCheckCustomConfig cannot be added, changed, or removed
361 if (
362 (olds.healthCheckCustomConfig === undefined) !==
363 (news.healthCheckCustomConfig === undefined)
364 ) {
365 return { action: "replace" } as const;
366 }
367 if (olds.type !== news.type) {
368 return { action: "replace" } as const;
369 }
370 // description / record TTLs / healthCheckConfig / tags → update
371 }),
372
373 reconcile: Effect.fn(function* ({ id, news, output, session }) {
374 const name = output?.serviceName ?? (yield* createName(id, news));
375 const internalTags = yield* createInternalTags(id);
376 const desiredTags = { ...news.tags, ...internalTags };
377
378 // 1. OBSERVE — cloud state is authoritative
379 let service = yield* observeService(news.namespaceId, name, output?.serviceId);
380
381 // 2. ENSURE — createService is synchronous
382 if (service === undefined) {
383 service = yield* sd
384 .createService({
385 Name: name,
386 NamespaceId: news.namespaceId,
387 Description: news.description,
388 DnsConfig: toDesiredDnsConfig(news),
389 HealthCheckConfig: toDesiredHealthCheckConfig(news),
390 HealthCheckCustomConfig: news.healthCheckCustomConfig
391 ? {
392 FailureThreshold: news.healthCheckCustomConfig.failureThreshold,
393 }
394 : undefined,
395 Type: news.type,
396 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
397 Key,
398 Value,
399 })),
400 })
401 .pipe(
402 Effect.map((r) => r.Service),
403 // a concurrent reconciler created it — observe instead
404 Effect.catchTag("ServiceAlreadyExists", (e) =>
405 e.ServiceId !== undefined
406 ? sd.getService({ Id: e.ServiceId }).pipe(Effect.map((r) => r.Service))
407 : observeService(news.namespaceId, name, undefined),
408 ),
409 );
410 }
411 if (service?.Id === undefined || service.Arn === undefined) {
412 return yield* sd.ServiceNotFound.make({
413 message: `service ${name} not visible after create`,
414 });
415 }
416
417 // 3. SYNC — description / DNS record TTLs / health check config.
418 // UpdateService deletes DnsRecords/HealthCheckConfig omitted from
419 // the change, so we always send the FULL desired configuration and
420 // only skip the call when observed already matches desired.
421 const desiredDns = toDesiredDnsConfig(news);
422 const desiredHealth = toDesiredHealthCheckConfig(news);
423 const observedRecords = service.DnsConfig?.DnsRecords ?? [];
424 const desiredRecords = desiredDns?.DnsRecords ?? [];
425 const dnsDelta = recordKey([...observedRecords]) !== recordKey(desiredRecords);
426 const descriptionDelta =
427 (news.description ?? undefined) !== (service.Description ?? undefined);
428 const observedHealth = service.HealthCheckConfig;
429 const healthDelta =
430 (desiredHealth === undefined) !== (observedHealth === undefined) ||
431 (desiredHealth !== undefined &&
432 (desiredHealth.Type !== observedHealth?.Type ||
433 (desiredHealth.ResourcePath ?? undefined) !==
434 (observedHealth?.ResourcePath ?? undefined) ||
435 (desiredHealth.FailureThreshold ?? undefined) !==
436 (observedHealth?.FailureThreshold ?? undefined)));
437 if (dnsDelta || descriptionDelta || healthDelta) {
438 const update = yield* sd.updateService({
439 Id: service.Id,
440 Service: {
441 Description: news.description,
442 DnsConfig:
443 desiredDns !== undefined ? { DnsRecords: desiredDns.DnsRecords } : undefined,
444 HealthCheckConfig: desiredHealth,
445 },
446 });
447 if (update.OperationId !== undefined) {
448 yield* awaitOperation(update.OperationId);
449 }
450 }
451
452 // 3b. SYNC SERVICE ATTRIBUTES — diff OBSERVED custom attributes
453 // against the desired map; upsert changed keys, delete undeclared
454 const observedAttributes: { [key: string]: string | undefined } = yield* sd
455 .getServiceAttributes({ ServiceId: service.Id })
456 .pipe(
457 Effect.map((r) => r.ServiceAttributes?.Attributes ?? {}),
458 Effect.catchTag("ServiceNotFound", () => Effect.succeed({})),
459 );
460 const desiredAttributes = news.attributes ?? {};
461 const attributeUpserts = Object.entries(desiredAttributes).filter(
462 ([key, value]) => observedAttributes[key] !== value,
463 );
464 const attributeRemovals = Object.keys(observedAttributes).filter(
465 (key) => !(key in desiredAttributes),
466 );
467 if (attributeUpserts.length > 0) {
468 yield* sd.updateServiceAttributes({
469 ServiceId: service.Id,
470 Attributes: Object.fromEntries(attributeUpserts),
471 });
472 }
473 if (attributeRemovals.length > 0) {
474 yield* sd.deleteServiceAttributes({
475 ServiceId: service.Id,
476 Attributes: attributeRemovals,
477 });
478 }
479
480 // 3c. SYNC TAGS — diff against OBSERVED cloud tags
481 const observedTags = yield* fetchObservedTags(service.Arn);
482 yield* syncTags(service.Arn, observedTags, desiredTags);
483
484 const namespaceId = service.NamespaceId ?? news.namespaceId;
485 const namespaceName = yield* resolveNamespaceName(namespaceId);
486
487 yield* session.note(service.Id);
488 return {
489 serviceId: service.Id,
490 serviceArn: service.Arn,
491 serviceName: service.Name ?? name,
492 namespaceId,
493 namespaceName,
494 };
495 }),
496
497 delete: Effect.fn(function* ({ output }) {
498 // OBSERVE — instances registered at runtime (RegisterInstance
499 // binding) block DeleteService; deregister any that remain and
500 // await the async operations before deleting.
501 yield* deregisterAllInstances(output.serviceId).pipe(
502 Effect.catchTag("ServiceNotFound", () => Effect.void),
503 );
504 // deregistrations still propagating surface as ResourceInUse —
505 // retry through the visibility window (bounded)
506 yield* retryWhileResourceInUse(sd.deleteService({ Id: output.serviceId })).pipe(
507 Effect.catchTag("ServiceNotFound", () => Effect.void),
508 );
509 }),
510 });
511 }),
512 );