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

main
ts 267 lines 9.91 KB
Raw
1 import * as sd from "@distilled.cloud/aws/servicediscovery";
2 import { diffTags } from "alchemy/Tags";
3 import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5 import * as Schedule from "effect/Schedule";
6
7 /**
8 * Raised when an asynchronous Cloud Map operation (namespace create/delete,
9 * instance register/deregister, service update) terminates with `FAIL` or
10 * fails to reach a terminal status within the polling budget.
11 */
12 export class CloudMapOperationFailed extends Data.TaggedError("CloudMapOperationFailed")<{
13 readonly operationId: string;
14 readonly status: string | undefined;
15 readonly errorCode: string | undefined;
16 readonly errorMessage: string | undefined;
17 }> {}
18
19 /**
20 * Repeat a `getOperation` poll until the operation reaches a terminal status
21 * (`SUCCESS` | `FAIL`), spaced 2s and bounded at 60 repetitions (~2 minutes —
22 * namespace operations typically take 30-60s).
23 *
24 * Expressed as an explicitly-typed helper: inlining `Effect.repeat` in
25 * lifecycle code leaves its conditional return type unresolved in the
26 * provider's declaration emit, which widens the `AWS.providers()` layer type
27 * for every downstream consumer.
28 */
29 const untilTerminalStatus = <E, R>(
30 self: Effect.Effect<sd.GetOperationResponse, E, R>,
31 ): Effect.Effect<sd.Operation | undefined, E, R> =>
32 Effect.repeat(
33 Effect.map(self, (response) => response.Operation),
34 {
35 schedule: Schedule.spaced("2 seconds"),
36 until: (operation) => operation?.Status === "SUCCESS" || operation?.Status === "FAIL",
37 times: 60,
38 },
39 );
40
41 /**
42 * Await a Cloud Map async operation: poll `getOperation` (bounded) until it
43 * reaches a terminal status and fail with `CloudMapOperationFailed` unless
44 * that status is `SUCCESS`. Returns the terminal `Operation` (whose
45 * `Targets` map carries the created NAMESPACE/SERVICE/INSTANCE ids).
46 */
47 export const awaitOperation = Effect.fn("AWS.CloudMap.awaitOperation")(function* (
48 operationId: string,
49 ) {
50 const operation = yield* untilTerminalStatus(sd.getOperation({ OperationId: operationId }));
51 if (operation?.Status !== "SUCCESS") {
52 return yield* new CloudMapOperationFailed({
53 operationId,
54 status: operation?.Status,
55 errorCode: operation?.ErrorCode,
56 errorMessage: operation?.ErrorMessage,
57 });
58 }
59 return operation;
60 });
61
62 /**
63 * Bounded retry through transient `ResourceInUse` dependency violations —
64 * e.g. deleting a namespace while its last service deletion is still
65 * propagating, or deleting a service while an instance deregistration is in
66 * flight. Explicitly typed for the same declaration-emit reason as above.
67 */
68 export const retryWhileResourceInUse = <A, E extends { _tag: string }, R>(
69 self: Effect.Effect<A, E, R>,
70 ): Effect.Effect<A, E, R> =>
71 Effect.retry(self, {
72 while: (e) => e._tag === "ResourceInUse",
73 schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(20)]),
74 });
75
76 /**
77 * Deregister every instance still registered on a service and await the
78 * async deregistration operations. Instances registered at runtime (via the
79 * `RegisterInstance` binding) are data-plane ephemera owned by the service —
80 * they would otherwise block `DeleteService` with `ResourceInUse` forever.
81 * Deregistrations already in flight surface as `DuplicateRequest` and are
82 * tolerated; `DeleteService`'s own `ResourceInUse` retry rides out the
83 * remaining visibility window.
84 */
85 export const deregisterAllInstances = Effect.fn("AWS.CloudMap.deregisterAllInstances")(function* (
86 serviceId: string,
87 ) {
88 const operationIds: string[] = [];
89 let nextToken: string | undefined;
90 do {
91 const page = yield* sd.listInstances({
92 ServiceId: serviceId,
93 NextToken: nextToken,
94 });
95 for (const instance of page.Instances ?? []) {
96 if (instance.Id === undefined) {
97 continue;
98 }
99 const response = yield* sd
100 .deregisterInstance({ ServiceId: serviceId, InstanceId: instance.Id })
101 .pipe(
102 // already gone / a deregistration already in flight — both mean
103 // the instance is on its way out
104 Effect.catchTag(["InstanceNotFound", "DuplicateRequest"], () => Effect.undefined),
105 );
106 if (response?.OperationId !== undefined) {
107 operationIds.push(response.OperationId);
108 }
109 }
110 nextToken = page.NextToken;
111 } while (nextToken !== undefined);
112 for (const operationId of operationIds) {
113 yield* awaitOperation(operationId);
114 }
115 });
116
117 export type NamespaceKind = "DNS_PRIVATE" | "DNS_PUBLIC" | "HTTP";
118
119 /** Find a namespace of the given type by exact name via the list API. */
120 export const findNamespaceByName = Effect.fn("AWS.CloudMap.findNamespaceByName")(function* (
121 type: NamespaceKind,
122 name: string,
123 ) {
124 const response = yield* sd.listNamespaces({
125 Filters: [
126 { Name: "TYPE", Values: [type], Condition: "EQ" },
127 { Name: "NAME", Values: [name], Condition: "EQ" },
128 ],
129 });
130 return response.Namespaces?.[0];
131 });
132
133 /**
134 * Observe a namespace: by cached id when we have one (tolerating out-of-band
135 * deletion), falling back to an exact-name list lookup.
136 */
137 export const observeNamespace = Effect.fn("AWS.CloudMap.observeNamespace")(function* (
138 type: NamespaceKind,
139 name: string,
140 namespaceId: string | undefined,
141 ) {
142 if (namespaceId !== undefined) {
143 const byId = yield* sd.getNamespace({ Id: namespaceId }).pipe(
144 Effect.map((r) => r.Namespace),
145 Effect.catchTag("NamespaceNotFound", () => Effect.undefined),
146 );
147 if (byId !== undefined) {
148 return byId;
149 }
150 }
151 const summary = yield* findNamespaceByName(type, name);
152 if (summary?.Id === undefined) {
153 return undefined;
154 }
155 // hydrate the summary into the full Namespace shape (keeps one return
156 // type; also tolerates a delete race between list and get)
157 return yield* sd.getNamespace({ Id: summary.Id }).pipe(
158 Effect.map((r) => r.Namespace),
159 Effect.catchTag("NamespaceNotFound", () => Effect.undefined),
160 );
161 });
162
163 /**
164 * Ensure a namespace exists: submit `create`, await its async operation, and
165 * observe the created namespace **by the operation's target id** — the
166 * `listNamespaces` name lookup is eventually consistent and can miss a
167 * namespace created milliseconds earlier.
168 *
169 * A same-name predecessor still mid-deletion (e.g. the old physical resource
170 * of a replacement, or an out-of-band cleaner) surfaces the create as
171 * `NamespaceAlreadyExists` while remaining invisible to observation; the
172 * whole create+observe sequence retries (bounded, ~40s) until the deletion
173 * completes and the create goes through. A `DuplicateRequest` means an
174 * identical create is already in flight — its operation is awaited instead.
175 */
176 const retryWhileNamespaceNotVisible = <A, E extends { _tag: string }, R>(
177 self: Effect.Effect<A, E, R>,
178 ): Effect.Effect<A, E, R> =>
179 Effect.retry(self, {
180 while: (e) => e._tag === "NamespaceNotFound",
181 schedule: Schedule.max([Schedule.spaced("5 seconds"), Schedule.recurs(8)]),
182 });
183
184 /**
185 * The (identical) typed error union of the three namespace create operations.
186 * Kept concrete — a generic error parameter here would flow into
187 * `Effect.catchTag`, leaving an un-narrowable `{ _tag: unknown }` residue in
188 * the handler under TypeScript 7.
189 */
190 type CreateNamespaceError =
191 | sd.CreateHttpNamespaceError
192 | sd.CreatePrivateDnsNamespaceError
193 | sd.CreatePublicDnsNamespaceError;
194
195 export const ensureNamespace = <R>(
196 type: NamespaceKind,
197 name: string,
198 create: Effect.Effect<{ OperationId?: string | undefined }, CreateNamespaceError, R>,
199 ) =>
200 retryWhileNamespaceNotVisible(
201 Effect.gen(function* () {
202 const created: {
203 OperationId?: string | undefined;
204 NamespaceId?: string | undefined;
205 } = yield* create.pipe(
206 Effect.catchTag(["NamespaceAlreadyExists", "DuplicateRequest"], (e) =>
207 e._tag === "NamespaceAlreadyExists"
208 ? // the name is taken — by an ACTIVE namespace (observed below)
209 // or by one still deleting (observation misses it and the
210 // bounded outer retry re-submits the create)
211 Effect.succeed({
212 OperationId: undefined,
213 NamespaceId: e.NamespaceId,
214 })
215 : // an identical create is already in flight — await THAT one
216 Effect.succeed({
217 OperationId: e.DuplicateOperationId,
218 NamespaceId: undefined,
219 }),
220 ),
221 );
222 let namespaceId = created.NamespaceId;
223 if (created.OperationId !== undefined) {
224 const operation = yield* awaitOperation(created.OperationId);
225 namespaceId = operation?.Targets?.NAMESPACE ?? namespaceId;
226 }
227 const namespace = yield* observeNamespace(type, name, namespaceId);
228 if (namespace?.Id === undefined) {
229 return yield* sd.NamespaceNotFound.make({
230 message: `namespace ${name} not visible after create`,
231 });
232 }
233 return namespace;
234 }),
235 );
236
237 /**
238 * Fetch the observed Cloud Map tags for a resource ARN as a plain record,
239 * tolerating a missing resource (race during create/delete) as `{}`.
240 */
241 export const fetchObservedTags = Effect.fn("AWS.CloudMap.fetchObservedTags")(function* (
242 resourceArn: string,
243 ) {
244 const tags = yield* sd.listTagsForResource({ ResourceARN: resourceArn }).pipe(
245 Effect.map((response) => response.Tags ?? []),
246 Effect.orElseSucceed(() => [] as sd.Tag[]),
247 );
248 return Object.fromEntries(tags.map((tag) => [tag.Key, tag.Value]));
249 });
250
251 /**
252 * Sync a Cloud Map resource's tags: diff the OBSERVED cloud tags against the
253 * desired set and apply only the delta via tagResource/untagResource.
254 */
255 export const syncTags = Effect.fn("AWS.CloudMap.syncTags")(function* (
256 resourceArn: string,
257 observed: Record<string, string>,
258 desired: Record<string, string>,
259 ) {
260 const { upsert, removed } = diffTags(observed, desired);
261 if (upsert.length > 0) {
262 yield* sd.tagResource({ ResourceARN: resourceArn, Tags: upsert });
263 }
264 if (removed.length > 0) {
265 yield* sd.untagResource({ ResourceARN: resourceArn, TagKeys: removed });
266 }
267 });