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

main
ts 188 lines 6.84 KB
Raw
1 import * as sd from "@distilled.cloud/aws/servicediscovery";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import type { Providers } from "../Providers.ts";
7 import { awaitOperation, retryWhileResourceInUse } from "./internal.ts";
8
9 export interface InstanceRegistrationProps {
10 /**
11 * The ID of the Cloud Map service to register the instance with.
12 * Changing the service replaces the registration.
13 */
14 serviceId: string;
15 /**
16 * The instance ID — unique within the service. Changing it replaces the
17 * registration.
18 */
19 instanceId: string;
20 /**
21 * Instance attributes. For DNS services these drive record creation:
22 * `AWS_INSTANCE_IPV4` (A records), `AWS_INSTANCE_IPV6` (AAAA),
23 * `AWS_INSTANCE_PORT` (SRV), `AWS_INSTANCE_CNAME` (CNAME). Custom keys are
24 * returned by `DiscoverInstances`. Mutable — re-registering with the same
25 * instance ID updates the attributes.
26 */
27 attributes: Record<string, string>;
28 }
29
30 export interface InstanceRegistration extends Resource<
31 "AWS.CloudMap.InstanceRegistration",
32 InstanceRegistrationProps,
33 {
34 /**
35 * The Cloud Map service the instance is registered with.
36 */
37 serviceId: string;
38 /**
39 * The identifier of the registered instance.
40 */
41 instanceId: string;
42 },
43 {},
44 Providers
45 > {}
46
47 /**
48 * A manual AWS Cloud Map instance registration — registers a static
49 * endpoint (an IP, port, CNAME, or an arbitrary attribute bag) with a Cloud
50 * Map service so it is returned by `DiscoverInstances` and, for DNS
51 * services, resolvable via Route 53.
52 *
53 * Use this for non-ECS targets: static IPs, on-prem hosts, external
54 * dependencies. ECS registers its own tasks automatically via
55 * `serviceRegistries`.
56 *
57 * `RegisterInstance` is an upsert — reconcile re-registers with the desired
58 * attributes and Cloud Map converges the records. Registration and
59 * deregistration are asynchronous; the provider polls the operations API
60 * (bounded) until they complete.
61 * ### Registering Instances
62 * **Example:** Register a Static IP
63 * ```typescript
64 * import * as AWS from "@alchemy.run/aws";
65 *
66 * const instance = yield* AWS.CloudMap.InstanceRegistration("Primary", {
67 * serviceId: service.serviceId,
68 * instanceId: "primary",
69 * attributes: { AWS_INSTANCE_IPV4: "10.0.1.10" },
70 * });
71 * ```
72 *
73 * **Example:** Register an API-only Instance with Custom Attributes
74 * ```typescript
75 * const instance = yield* AWS.CloudMap.InstanceRegistration("Worker", {
76 * serviceId: service.serviceId,
77 * instanceId: "worker-1",
78 * attributes: { endpoint: "https://worker-1.internal:8443", zone: "us-west-2a" },
79 * });
80 * ```
81 *
82 * @resource
83 */
84 export const InstanceRegistration = Resource<InstanceRegistration>(
85 "AWS.CloudMap.InstanceRegistration",
86 );
87
88 export const InstanceRegistrationProvider = () =>
89 Provider.effect(
90 InstanceRegistration,
91 Effect.gen(function* () {
92 return InstanceRegistration.Provider.of({
93 stables: ["serviceId", "instanceId"],
94
95 // Sub-resource keyed by its parent service — there is no
96 // account-level enumeration without a service id, so listing is
97 // handled by the parent's lifecycle.
98 list: () => Effect.succeed([]),
99
100 read: Effect.fn(function* ({ olds, output }) {
101 const serviceId = output?.serviceId ?? olds?.serviceId;
102 const instanceId = output?.instanceId ?? olds?.instanceId;
103 if (serviceId === undefined || instanceId === undefined) {
104 return undefined;
105 }
106 const instance = yield* sd
107 .getInstance({ ServiceId: serviceId, InstanceId: instanceId })
108 .pipe(
109 Effect.map((r) => r.Instance),
110 Effect.catchTag(["InstanceNotFound", "ServiceNotFound"], () => Effect.undefined),
111 );
112 if (instance === undefined) {
113 return undefined;
114 }
115 // instances carry no tags, so ownership can't be branded — treat
116 // presence as ours (identity is fully determined by the props)
117 return { serviceId, instanceId };
118 }),
119
120 diff: Effect.fn(function* ({ news, olds }) {
121 if (!isResolved(news)) return undefined;
122 if (olds.serviceId !== news.serviceId || olds.instanceId !== news.instanceId) {
123 return { action: "replace" } as const;
124 }
125 // attributes fall through to the default update path (upsert)
126 }),
127
128 reconcile: Effect.fn(function* ({ news, session }) {
129 // OBSERVE — compare live attributes so an unchanged registration
130 // is a no-op instead of a Route 53 record churn
131 const observed = yield* sd
132 .getInstance({
133 ServiceId: news.serviceId,
134 InstanceId: news.instanceId,
135 })
136 .pipe(
137 Effect.map((r) => r.Instance),
138 Effect.catchTag(["InstanceNotFound", "ServiceNotFound"], () => Effect.undefined),
139 );
140
141 const observedAttributes = observed?.Attributes ?? undefined;
142 const desiredEntries = Object.entries(news.attributes);
143 const matches =
144 observedAttributes !== undefined &&
145 desiredEntries.length === Object.keys(observedAttributes).length &&
146 desiredEntries.every(([key, value]) => observedAttributes[key] === value);
147
148 // ENSURE/SYNC — registerInstance is a create-or-update upsert
149 if (!matches) {
150 const registered = yield* retryWhileResourceInUse(
151 sd.registerInstance({
152 ServiceId: news.serviceId,
153 InstanceId: news.instanceId,
154 Attributes: news.attributes,
155 }),
156 );
157 if (registered.OperationId !== undefined) {
158 yield* awaitOperation(registered.OperationId);
159 }
160 }
161
162 yield* session.note(news.instanceId);
163 return { serviceId: news.serviceId, instanceId: news.instanceId };
164 }),
165
166 delete: Effect.fn(function* ({ output }) {
167 const deregistered = yield* retryWhileResourceInUse(
168 sd.deregisterInstance({
169 ServiceId: output.serviceId,
170 InstanceId: output.instanceId,
171 }),
172 ).pipe(
173 Effect.catchTag(["InstanceNotFound", "ServiceNotFound"], () =>
174 Effect.succeed({ OperationId: undefined }),
175 ),
176 // an identical deregistration is already in flight — await THAT
177 // operation instead of silently skipping it
178 Effect.catchTag("DuplicateRequest", (e) =>
179 Effect.succeed({ OperationId: e.DuplicateOperationId }),
180 ),
181 );
182 if (deregistered.OperationId !== undefined) {
183 yield* awaitOperation(deregistered.OperationId);
184 }
185 }),
186 });
187 }),
188 );