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

main
ts 444 lines 15.7 KB
Raw
1 import * as Context from "effect/Context";
2 import * as Duration from "effect/Duration";
3 import * as Effect from "effect/Effect";
4 import * as Formatter from "effect/Formatter";
5 import * as Schedule from "effect/Schedule";
6 import picomatch from "picomatch";
7 import { emit, type ApplyStatus } from "./Events.ts";
8 import {
9 isProviderCollectionService,
10 isProviderService,
11 providerForMode,
12 type ProviderService,
13 } from "./Provider.ts";
14 import type { ProviderMode } from "./ProviderMode.ts";
15 import { stronglyConnectedComponents } from "./Util/scc.ts";
16
17 // Account-wide teardown: enumerate everything the registered providers can see
18 // and delete it, ignoring stack state entirely. This is the engine behind
19 // `alchemy nuke` — a blunt instrument for cleaning a test account, not part of
20 // any stack's lifecycle.
21
22 /** A provider call that failed. These are collected into results, never thrown. */
23 export interface ProviderFailure {
24 readonly provider: string;
25 readonly operation: "list" | "delete";
26 readonly message: string;
27 }
28
29 /** One cloud object a provider's `list()` turned up, bound to its provider. */
30 export interface Target {
31 /** Unique within a scan; names the target's row in progress events and views. */
32 readonly key: string;
33 readonly providerId: string;
34 readonly displayName: string;
35 readonly attributes: Record<string, unknown>;
36 readonly provider: ProviderService;
37 }
38
39 export interface DiscoverOptions {
40 readonly mode: ProviderMode;
41 /** Provider-id globs to include. Omitted means every provider. */
42 readonly include?: ReadonlyArray<string>;
43 /** Provider-id globs to exclude. Applied after {@link DiscoverOptions.include}. */
44 readonly exclude?: ReadonlyArray<string>;
45 }
46
47 export interface ListOptions extends DiscoverOptions {
48 /** The built provider context — what a stack's `providers` layer produced. */
49 readonly context: Context.Context<never>;
50 readonly concurrency?: number | "unbounded";
51 readonly timeoutSeconds?: number;
52 }
53
54 export type Strategy =
55 /** Delete in dependency order, retrying a wave until it stops making progress. */
56 | { readonly type: "coordinated" }
57 /** Delete everything at once, retrying each object on its own. */
58 | { readonly type: "independent"; readonly retries: number };
59
60 export interface DestroyOptions {
61 readonly targets: ReadonlyArray<Target>;
62 readonly context: Context.Context<never>;
63 readonly strategy: Strategy;
64 readonly concurrency?: number | "unbounded";
65 readonly timeoutSeconds?: number;
66 }
67
68 export interface Result {
69 readonly requested: number;
70 readonly deleted: ReadonlyArray<Target>;
71 readonly failed: ReadonlyArray<{
72 readonly resource: Target;
73 readonly failure: ProviderFailure;
74 }>;
75 /** Skipped because something they depend on could not be deleted first. */
76 readonly held: ReadonlyArray<{
77 readonly resource: Target;
78 readonly blockedBy: ReadonlyArray<string>;
79 }>;
80 readonly passes: number;
81 }
82
83 interface DiscoveredProvider {
84 readonly id: string;
85 readonly provider: ProviderService;
86 }
87
88 const failure = (
89 provider: string,
90 operation: ProviderFailure["operation"],
91 cause: unknown,
92 ): ProviderFailure => ({
93 provider,
94 operation,
95 message: typeof cause === "string" ? cause : Formatter.format(cause),
96 });
97
98 /**
99 * One provider's failure, typed or defect, must not abort an account-wide
100 * sweep: credential layers die on a rejected token, so collect both.
101 */
102 const settle = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
103 Effect.result(effect.pipe(Effect.catchDefect((defect) => Effect.fail(defect))));
104
105 /** Deletions here run out-of-band, so nothing reports through an apply session. */
106 const silent = {
107 note: () => Effect.void,
108 };
109
110 /**
111 * Walk the built provider context for everything deletable. A provider opts
112 * out with `nuke.skip` (not ours to delete) or `nuke.singleton` (an
113 * account-level object that has to survive).
114 *
115 * Dual registrations (`ProviderLayer.dual`) build nothing until asked and
116 * keep their `nuke` metadata on the variants, so each provider is resolved
117 * to the scan mode's variant first — mode-agnostic providers resolve to
118 * themselves in a live scan and are not part of a local one.
119 */
120 const discover = Effect.fn(function* (
121 context: Context.Context<never>,
122 { mode, include, exclude }: DiscoverOptions,
123 ) {
124 const registered = new Map<string, ProviderService>();
125 for (const [key, value] of context.mapUnsafe.entries()) {
126 if (isProviderCollectionService(value)) {
127 for (const [id, provider] of Object.entries(value.providers)) {
128 registered.set(id, provider);
129 }
130 } else if (typeof key === "string" && key.includes(".") && isProviderService(value)) {
131 registered.set(key, value);
132 }
133 }
134 const included = include?.length ? picomatch([...include]) : () => true;
135 const excluded = exclude?.length ? picomatch([...exclude]) : () => false;
136 const output: DiscoveredProvider[] = [];
137 for (const [id, registration] of registered) {
138 if (!included(id) || excluded(id)) continue;
139 if (mode === "local" && registration.modes === undefined) continue;
140 const provider = yield* providerForMode(registration, mode);
141 if (provider.nuke?.singleton || provider.nuke?.skip) continue;
142 output.push({ id, provider });
143 }
144 return output.sort((a, b) => a.id.localeCompare(b.id));
145 });
146 const nameKeys = [
147 "workerName",
148 "functionName",
149 "bucketName",
150 "tableName",
151 "queueName",
152 "repositoryName",
153 "databaseName",
154 "projectName",
155 "domainName",
156 "hostname",
157 "displayName",
158 "name",
159 ];
160
161 const displayName = (attributes: Record<string, unknown>) =>
162 nameKeys
163 .map((key) => attributes[key])
164 .find((value): value is string => typeof value === "string" && value.length > 0) ??
165 Object.values(attributes).find(
166 (value): value is string => typeof value === "string" && value.length > 0,
167 ) ??
168 "unknown";
169
170 const groupBy = <T>(items: ReadonlyArray<T>, key: (item: T) => string) => {
171 const groups = new Map<string, T[]>();
172 for (const item of items) {
173 const id = key(item);
174 groups.set(id, [...(groups.get(id) ?? []), item]);
175 }
176 return groups;
177 };
178
179 const addEdge = (edges: Map<string, Set<string>>, from: string, to: string) => {
180 const values = edges.get(from) ?? new Set<string>();
181 values.add(to);
182 edges.set(from, values);
183 };
184
185 /** Ask every selected provider what exists. Provider failures are collected, not thrown. */
186 export const list = (
187 options: ListOptions,
188 ): Effect.Effect<{
189 readonly resources: ReadonlyArray<Target>;
190 readonly failures: ReadonlyArray<ProviderFailure>;
191 }> =>
192 Effect.gen(function* () {
193 const failures: ProviderFailure[] = [];
194 const resources: Target[] = [];
195 const providers = yield* discover(options.context, options).pipe(
196 Effect.provide(options.context),
197 );
198 yield* emit({ type: "nuke.scan.started", total: providers.length });
199 yield* Effect.forEach(
200 providers,
201 ({ id, provider }) =>
202 Effect.gen(function* () {
203 yield* emit({ type: "nuke.scan.provider.started", provider: id });
204 const result = yield* settle(
205 Effect.gen(function* () {
206 const listed = yield* provider
207 .list()
208 .pipe(Effect.timeout(Duration.seconds(options.timeoutSeconds ?? 120)));
209 return { provider, listed };
210 }).pipe(Effect.provide(options.context)),
211 );
212 if (result._tag === "Failure") {
213 const error = failure(id, "list", result.failure);
214 failures.push(error);
215 yield* emit({
216 type: "nuke.scan.provider.completed",
217 provider: id,
218 resources: 0,
219 error: error.message,
220 });
221 return;
222 }
223 for (const raw of result.success.listed) {
224 const attributes = (raw ?? {}) as Record<string, unknown>;
225 resources.push({
226 key: `${id}/${resources.length}`,
227 providerId: id,
228 displayName: displayName(attributes),
229 attributes,
230 provider: result.success.provider,
231 });
232 }
233 yield* emit({
234 type: "nuke.scan.provider.completed",
235 provider: id,
236 resources: result.success.listed.length,
237 });
238 }),
239 { concurrency: options.concurrency ?? 16, discard: true },
240 );
241 return { resources, failures };
242 });
243
244 /** Delete the given targets under the chosen {@link Strategy}. */
245 export const destroy = ({
246 targets,
247 context,
248 strategy,
249 concurrency = 16,
250 timeoutSeconds = 120,
251 }: DestroyOptions): Effect.Effect<Result> =>
252 Effect.gen(function* () {
253 // Each target reports as an apply row under its `key`.
254 const status = (resource: Target, status: ApplyStatus, message?: string) =>
255 emit({
256 type: "apply.resource.status",
257 fqn: resource.key,
258 id: resource.providerId,
259 resourceType: resource.providerId,
260 status,
261 message,
262 });
263 const onPass = (pass: number) => emit({ type: "nuke.pass.started", pass });
264 const onDeleted = (resource: Target) =>
265 status(resource, "deleted").pipe(
266 Effect.andThen(
267 emit({
268 type: "nuke.resource.deleted",
269 provider: resource.providerId,
270 resource: resource.displayName,
271 }),
272 ),
273 );
274 const onFailed = (resource: Target, message: string) =>
275 status(resource, "fail", message).pipe(
276 Effect.andThen(
277 emit({
278 type: "nuke.resource.failed",
279 provider: resource.providerId,
280 resource: resource.displayName,
281 message,
282 }),
283 ),
284 );
285 const deleted: Target[] = [];
286 const failed: Array<Result["failed"][number]> = [];
287 const held: Array<Result["held"][number]> = [];
288 let passes = 0;
289 // Account-wide scans have no state rows: delete must derive identity from
290 // `output` alone — `olds` just mirrors it and `instanceId` is unavailable.
291 const attempt = (resource: Target) =>
292 Effect.gen(function* () {
293 yield* status(resource, "deleting");
294 return yield* resource.provider
295 .delete({
296 id: resource.displayName,
297 fqn: resource.displayName,
298 instanceId: "",
299 olds: resource.attributes as never,
300 output: resource.attributes as never,
301 session: silent,
302 bindings: [],
303 force: true,
304 })
305 .pipe(Effect.timeout(Duration.seconds(timeoutSeconds)), Effect.provide(context));
306 });
307
308 if (strategy.type === "independent") {
309 passes = 1;
310 yield* onPass(passes);
311 yield* Effect.forEach(
312 targets,
313 (resource) =>
314 settle(
315 attempt(resource).pipe(
316 Effect.retry({
317 schedule: Schedule.min([
318 Schedule.exponential("1 second"),
319 Schedule.spaced("15 seconds"),
320 ]),
321 times: strategy.retries,
322 }),
323 ),
324 ).pipe(
325 Effect.tap((result) => {
326 if (result._tag === "Success") {
327 deleted.push(resource);
328 return onDeleted(resource);
329 }
330 const why = failure(resource.providerId, "delete", result.failure);
331 failed.push({ resource, failure: why });
332 return onFailed(resource, why.message);
333 }),
334 ),
335 { concurrency: concurrency, discard: true },
336 );
337 } else {
338 const typeIds = [...new Set(targets.map(({ providerId }) => providerId))];
339 const providerOf = new Map(targets.map(({ providerId, provider }) => [providerId, provider]));
340 const successors = new Map<string, Set<string>>();
341 const predecessors = new Map<string, Set<string>>();
342 for (const id of typeIds) {
343 const globs = providerOf.get(id)?.nuke?.dependsOn;
344 if (!globs?.length) continue;
345 const matches = picomatch([...globs]);
346 for (const other of typeIds) {
347 if (other === id || !matches(other)) continue;
348 addEdge(successors, id, other);
349 addEdge(predecessors, other, id);
350 }
351 }
352 const grouped = stronglyConnectedComponents(typeIds, (id) => successors.get(id) ?? []);
353 const componentOf = new Map<string, number>();
354 grouped.forEach((component, index) => component.forEach((id) => componentOf.set(id, index)));
355 const layerOf = grouped.map(() => 0);
356 for (let index = grouped.length - 1; index >= 0; index--) {
357 for (const id of grouped[index]!) {
358 for (const predecessor of predecessors.get(id) ?? []) {
359 const predecessorComponent = componentOf.get(predecessor)!;
360 if (predecessorComponent !== index) {
361 layerOf[index] = Math.max(layerOf[index]!, layerOf[predecessorComponent]! + 1);
362 }
363 }
364 }
365 }
366 const waves: string[][] = [];
367 grouped.forEach((component, index) => (waves[layerOf[index]!] ??= []).push(...component));
368 const byType = groupBy(targets, ({ providerId }) => providerId);
369 const remainingCount = new Map([...byType].map(([id, resources]) => [id, resources.length]));
370 for (const wave of waves) {
371 let runnable: Target[] = [];
372 const heldTypes = new Set<string>();
373 for (const typeId of wave) {
374 const resources = byType.get(typeId) ?? [];
375 const blockers = [...(predecessors.get(typeId) ?? [])].filter(
376 (predecessor) =>
377 componentOf.get(predecessor) !== componentOf.get(typeId) &&
378 (remainingCount.get(predecessor) ?? 0) > 0,
379 );
380 if (blockers.length > 0) {
381 heldTypes.add(typeId);
382 yield* Effect.forEach(resources, (resource) =>
383 status(resource, "skipped", `Held back by ${blockers.join(", ")}`),
384 );
385 held.push(
386 ...resources.map((resource) => ({
387 resource,
388 blockedBy: blockers,
389 })),
390 );
391 } else runnable = [...runnable, ...resources];
392 }
393 let remaining = runnable;
394 while (remaining.length > 0) {
395 passes += 1;
396 yield* onPass(passes);
397 const results = yield* Effect.forEach(
398 remaining,
399 (resource) =>
400 Effect.gen(function* () {
401 const result = yield* settle(attempt(resource));
402 if (result._tag === "Success") {
403 deleted.push(resource);
404 yield* onDeleted(resource);
405 }
406 return { resource, result };
407 }),
408 { concurrency: concurrency },
409 );
410 const next: Target[] = [];
411 for (const { resource, result } of results) {
412 if (result._tag === "Failure") next.push(resource);
413 }
414 if (next.length === remaining.length) {
415 for (const { resource, result } of results) {
416 if (result._tag !== "Failure") continue;
417 const why = failure(resource.providerId, "delete", result.failure);
418 failed.push({ resource, failure: why });
419 yield* onFailed(resource, why.message);
420 }
421 break;
422 }
423 remaining = next;
424 }
425 const failuresByType = groupBy(
426 failed.map(({ resource }) => resource),
427 ({ providerId }) => providerId,
428 );
429 for (const typeId of wave) {
430 // Held types were never attempted: keep their full count so waves
431 // gated on them stay blocked instead of seeing a spurious zero.
432 if (heldTypes.has(typeId)) continue;
433 remainingCount.set(typeId, failuresByType.get(typeId)?.length ?? 0);
434 }
435 }
436 }
437 return {
438 requested: targets.length,
439 deleted,
440 failed,
441 held,
442 passes,
443 } satisfies Result;
444 });