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

main
ts 2,551 lines 108 KB
Raw
1 /** @effect-diagnostics anyUnknownInErrorContext:off */
2 /** @effect-diagnostics missingEffectError:off */
3 import * as Cause from "effect/Cause";
4 import * as Config from "effect/Config";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Exit from "effect/Exit";
8 import * as Layer from "effect/Layer";
9 import * as Option from "effect/Option";
10 import * as Ref from "effect/Ref";
11 import { asEffect } from ".//Util/types.ts";
12 import { isAction, type ActionLike } from "./Action.ts";
13 import {
14 AdoptPolicy,
15 OwnedBySomeoneElse,
16 stripUnowned,
17 Unowned,
18 UnverifiableReplacement,
19 } from "./AdoptPolicy.ts";
20 import { AlchemyContext } from "./AlchemyContext.ts";
21 import {
22 Artifacts,
23 ArtifactStore,
24 createArtifactStore,
25 ensureArtifactStore,
26 makeScopedArtifacts,
27 } from "./Artifacts.ts";
28 import { demandRemoteCredentials, failCredentialsRequired } from "./Auth/Demand.ts";
29 import {
30 dedupeBindings,
31 diffBindings,
32 havePropsChanged,
33 isResolved,
34 type NoopDiff,
35 type ReplaceDiff,
36 type UpdateDiff,
37 } from "./Diff.ts";
38 import { emit, type PlannedAction, type PlannedBinding, type PlannedResource } from "./Events.ts";
39 import { parseFqn } from "./FQN.ts";
40 import { generateInstanceId } from "./InstanceId.ts";
41 import * as Output from "./Output.ts";
42 import {
43 tryFindProviderRegistrationByType,
44 missingProviderError,
45 Provider,
46 providerForMode,
47 tryFindProviderByType,
48 type ProviderService,
49 } from "./Provider.ts";
50 import { defaultProviderMode, stampedMode, type ProviderMode } from "./ProviderMode.ts";
51 import {
52 isResource,
53 missingImplementation,
54 type ResourceBinding,
55 type ResourceLike,
56 } from "./Resource.ts";
57 import { ResourceContext } from "./ResourceContext.ts";
58 import {
59 InvalidResourceSelection,
60 UnsafeSelectionBoundary,
61 selectResources,
62 type ResourceSelection,
63 type SelectionOutput,
64 } from "./ResourceSelection.ts";
65 import { capturedEnvKeys } from "./RuntimeContext.ts";
66 import { cachedInScope } from "./Util/Memoize.ts";
67 export { InvalidResourceSelection, UnsafeSelectionBoundary } from "./ResourceSelection.ts";
68 import { type StackSpec } from "./Stack.ts";
69 import {
70 isActionState,
71 State,
72 type ActionState,
73 type CreatedResourceState,
74 type CreatingResourceState,
75 type RanActionState,
76 type ReplacedResourceState,
77 type ReplacingResourceState,
78 type ResourceState,
79 type StateStoreError,
80 type UpdatedResourceState,
81 type UpdatingReourceState,
82 } from "./State/index.ts";
83 import { isPlainData, mapPlainData } from "./Util/data.ts";
84 import { findCycleMembers } from "./Util/scc.ts";
85 import { hashInput } from "./Util/sha256.ts";
86
87 export type PlanError = never;
88
89 /**
90 * A node in the plan that represents a resource CRUD operation.
91 */
92 export type CRUD<R extends ResourceLike = ResourceLike> =
93 | Create<R>
94 | Update<R>
95 | Delete<R>
96 | Replace<R>
97 | NoopUpdate<R>;
98
99 export type Apply<R extends ResourceLike = ResourceLike> =
100 | Create<R>
101 | Update<R>
102 | Replace<R>
103 | NoopUpdate<R>;
104
105 export type BindingAction = "create" | "update" | "delete" | "noop";
106
107 export interface BindingNode<Data = any> extends ResourceBinding {
108 action: BindingAction;
109 data: Data;
110 }
111
112 export interface BaseNode<R extends ResourceLike<string> = ResourceLike<string>> {
113 resource: R;
114 provider: ProviderService<R>;
115 /**
116 * The {@link ProviderMode} this node's `provider` was resolved for.
117 * `undefined` for mode-agnostic providers (a single implementation
118 * serves both dev and deploy) — such resources never persist a mode and
119 * never replace on a mode switch. Apply stamps this onto every state
120 * commit as `providerMode`.
121 */
122 mode: ProviderMode | undefined;
123 downstream: string[];
124 bindings: BindingNode<R["Binding"]>[];
125 }
126
127 /**
128 * Base for the apply-side nodes (create/update/replace/noop) — the nodes a
129 * DECLARED resource plans to. Only these can carry a rename: a `Delete`
130 * node is an orphaned row with no declaration, so nothing can claim to
131 * have renamed it (migrating rows are excluded from the orphan pass
132 * entirely).
133 */
134 export interface ApplyNodeBase<
135 R extends ResourceLike<string> = ResourceLike<string>,
136 > extends BaseNode<R> {
137 /** Cloud attribute drift attached to synthetic drift-repair plans. */
138 drift?: {
139 readonly expected: unknown;
140 readonly actual: unknown;
141 readonly missing?: boolean;
142 };
143 /**
144 * Set when this resource's persisted row was found under former FQNs
145 * (`renamedFrom(...)`) — the migration source (no row at the current FQN
146 * yet) and/or stale leftovers from interrupted migrations (same
147 * `instanceId` as the resource's row; a rename chain with repeated
148 * partial failures can leave several). Apply persists the move up-front,
149 * before any lifecycle operation runs: commit `state` at the current
150 * FQN, then delete every former row.
151 */
152 renamedFrom?: string[] | undefined;
153 /** Preserve the FQN-reuse exclusion across generations and state transitions. */
154 adoptionBlocked?: "migrated-fqn";
155 }
156
157 export interface Create<R extends ResourceLike = ResourceLike> extends ApplyNodeBase<R> {
158 action: "create";
159 props: R["Props"];
160 state: CreatingResourceState | undefined;
161 /** Ownership probe deferred until upstream identities resolve during apply. */
162 deferredAdoption?: { adopt: boolean };
163 }
164
165 export interface Update<R extends ResourceLike = ResourceLike> extends ApplyNodeBase<R> {
166 action: "update" | "adopted";
167 /** True while this is the first reconcile after a cold adoption. */
168 adopting?: boolean;
169 props: R["Props"];
170 state:
171 | CreatedResourceState
172 | UpdatedResourceState
173 | UpdatingReourceState
174 // the props can change after creating the replacement resource,
175 // so Apply needs to handle updates and then continue with cleaning up the replaced graph
176 | ReplacedResourceState;
177 }
178
179 export interface Delete<R extends ResourceLike = ResourceLike> extends BaseNode<R> {
180 action: "delete" | "orphaned";
181 // a resource can be deleted no matter what state it's in
182 state: ResourceState;
183 }
184
185 export interface NoopUpdate<R extends ResourceLike = ResourceLike> extends ApplyNodeBase<R> {
186 action: "noop";
187 state: CreatedResourceState | UpdatedResourceState;
188 }
189
190 export interface Replace<R extends ResourceLike = ResourceLike> extends ApplyNodeBase<R> {
191 action: "replace";
192 props: any;
193 deleteFirst: boolean;
194 restart?: boolean;
195 /** Ownership probe of the replacement's physical identity, run before any mutation. */
196 deferredAdoption?: { adopt: boolean };
197 state:
198 | CreatingResourceState
199 | CreatedResourceState
200 | UpdatingReourceState
201 | UpdatedResourceState
202 | ReplacingResourceState
203 | ReplacedResourceState;
204 }
205
206 // ── Tasks ──────────────────────────────────────────────────────────────────
207 //
208 // Tasks live in the same FQN namespace as resources and participate in the
209 // same DAG (downstream/upstream edges, cycle detection). Their plan nodes
210 // have a different shape because they have no provider lifecycle.
211
212 export type ActionApply<T extends ActionLike = ActionLike> = ActionRun<T> | ActionNoop<T>;
213
214 export interface ActionNodeBase<T extends ActionLike = ActionLike> {
215 readonly kind: "action";
216 def: T;
217 downstream: string[];
218 }
219
220 export interface ActionRun<T extends ActionLike = ActionLike> extends ActionNodeBase<T> {
221 action: "run";
222 /** Input expression — resolved against tracker outputs during apply. */
223 input: T["Input"];
224 /** Previous state, if any. `undefined` on the first run. */
225 state: ActionState | undefined;
226 /** True when `--force` triggered the re-run regardless of input drift. */
227 forced: boolean;
228 }
229
230 export interface ActionNoop<T extends ActionLike = ActionLike> extends ActionNodeBase<T> {
231 action: "noop";
232 state: RanActionState;
233 }
234
235 export interface ActionDelete<T extends ActionLike = ActionLike> extends ActionNodeBase<T> {
236 action: "delete";
237 state: ActionState;
238 }
239
240 export type Plan<Output = any> = {
241 /** Closed selection for partial apply and GC; absent for a full plan. */
242 selectedFqns?: ReadonlySet<string>;
243 resources: {
244 [id in string]: Apply<any>;
245 };
246 /**
247 * Tasks scheduled for this apply. Keyed by FQN, same namespace as
248 * `resources` — Apply's scheduler merges both into a single DAG.
249 */
250 actions: {
251 [id in string]: ActionApply;
252 };
253 deletions: {
254 [id in string]?: Delete<ResourceLike>;
255 };
256 /** Tasks whose state should be dropped (no body invoked on removal). */
257 actionDeletions: {
258 [id in string]?: ActionDelete;
259 };
260 output: Output;
261 /**
262 * FQNs of resources that participate in a strongly-connected component
263 * of the upstream dependency graph (or have a self-edge). The scheduler
264 * uses this to decide whether an `update` node must publish its prior
265 * attr early to break the cycle, or can simply wait for upstreams and
266 * publish a fresh attr (the common, linear case).
267 */
268 cycleMembers: ReadonlySet<string>;
269 /**
270 * The run-level default {@link ProviderMode} this plan was built with
271 * (`alchemy dev` → `"local"`, `alchemy deploy` → `"live"`). Renderers use
272 * it to tag only the EXCEPTIONS — rows whose resolved mode differs from
273 * the run default. `undefined` (plans built by older/auxiliary builders)
274 * is treated as `"live"`.
275 */
276 defaultMode?: ProviderMode;
277 /**
278 * Marks a plan built by {@link destroy}. `apply` finishes a destroy plan
279 * by deleting the stage's remaining persisted state — notably the stack
280 * output record written by the last deploy — instead of persisting a new
281 * (empty) output.
282 */
283 destroy?: boolean;
284 };
285
286 const describeBinding = (binding: BindingNode): PlannedBinding => ({
287 sid: binding.sid,
288 action: binding.action,
289 });
290
291 /** The serializable row view of one resource node (see {@link describePlan}). */
292 export const describeResource = (node: CRUD): PlannedResource => ({
293 fqn: node.resource.FQN,
294 logicalId: node.resource.LogicalId,
295 resourceType: node.resource.Type,
296 action: node.action,
297 bindings: node.bindings.map(describeBinding),
298 providerMode: node.mode,
299 fromProviderMode:
300 node.action === "replace" &&
301 node.mode !== undefined &&
302 node.state.providerMode !== undefined &&
303 node.state.providerMode !== node.mode
304 ? node.state.providerMode
305 : undefined,
306 });
307
308 /** The serializable row view of one stack-action node. */
309 export const describeAction = (node: ActionApply | ActionDelete): PlannedAction => ({
310 fqn: node.def.FQN,
311 logicalId: node.def.LogicalId,
312 actionType: node.def.Type,
313 action: node.action,
314 });
315
316 /**
317 * Serializable per-row views of a plan — everything a renderer or remote
318 * consumer needs without holding the native plan: resource rows with their
319 * bindings and provider modes, orphan deletions, and stack actions.
320 */
321 export const describePlan = (
322 plan: Plan,
323 ): {
324 readonly resources: ReadonlyArray<PlannedResource>;
325 readonly actions: ReadonlyArray<PlannedAction>;
326 } => ({
327 resources: [
328 ...Object.values(plan.resources),
329 ...Object.values(plan.deletions).filter((node): node is Delete => node !== undefined),
330 ].map(describeResource),
331 actions: [...Object.values(plan.actions ?? {}), ...Object.values(plan.actionDeletions ?? {})]
332 .filter((node): node is ActionApply | ActionDelete => node !== undefined)
333 .map(describeAction),
334 });
335
336 export interface MakePlanOptions {
337 force?: boolean;
338 include?: never;
339 exclude?: never;
340 }
341
342 export interface FilteredPlanOptions
343 extends Omit<MakePlanOptions, keyof ResourceSelection>, ResourceSelection {
344 /**
345 * Exact FQNs, unique logical IDs, or FQN globs, plus transitive input, capture,
346 * and binding dependencies. An empty selection is an error. Other rows
347 * and persisted stack outputs are untouched; filtered apply returns void.
348 * The entire stack declaration still evaluates before selection. Renames
349 * with persisted former rows require a full deployment. Replacement/GC
350 * fails when prior or declared dependents are outside the selection.
351 * Detaching a selected intermediate also requires selecting all consumers
352 * reachable through its declared or historical downstream paths.
353 * Historical bindings require selecting every persisted resource and Action
354 * for replacement/GC. Clearing the last binding evidence also requires that
355 * complete selection, since stored payloads cannot recover binding-cycle edges.
356 * Only already-persisted, continuously retained bindings count as evidence.
357 * Reconciling a row with incomplete downstream history requires that selection.
358 * Exclusions are hard barriers, even for unchanged dependencies. Quote globs
359 * in the CLI: `--include 'App/**' --exclude 'App/Legacy'`. Each occurrence
360 * supplies one pattern; commas are literal. Dependencies hidden inside
361 * callbacks must be declared explicitly.
362 */
363 include?: ReadonlyArray<string>;
364 }
365
366 type FullPlanCall = [options?: MakePlanOptions];
367
368 export function make<A, Call extends [options?: FilteredPlanOptions] = FullPlanCall>(
369 stack: StackSpec<A>,
370 ...call: Call
371 ): Effect.Effect<Plan<SelectionOutput<A, Call[0]>>, never, State>;
372 export function make<A>(stack: StackSpec<A>, options: FilteredPlanOptions = {}) {
373 return makePlan(stack, options);
374 }
375
376 /**
377 * Bind every ref to a resource this program declares in its own stack and
378 * stage, so the ref is a dependency like a direct reference: the target is
379 * created first and deleted last, and the ref resolves to the target's fresh
380 * attributes (see `Output.bindRef`). A ref is matched by its id against the
381 * declared resource's FQN, which is what the ref reads from state. A
382 * resource's ref to itself stays unbound: it reads its own persisted state.
383 */
384 const bindSameStackRefs = (
385 stack: StackSpec<any>,
386 resources: ReadonlyArray<ResourceLike>,
387 actions: ReadonlyArray<ActionLike>,
388 ) => {
389 const byFqn = new Map(resources.map((resource) => [resource.FQN, resource]));
390 const bind = (owner: string, value: unknown) => {
391 for (const ref of Output.collectRefs(value)) {
392 if ((ref.stack ?? stack.name) !== stack.name) continue;
393 if ((ref.stage ?? stack.stage) !== stack.stage) continue;
394 if (ref.resourceId === owner) continue;
395 const target = byFqn.get(ref.resourceId);
396 if (target !== undefined) Output.bindRef(ref, target);
397 }
398 };
399 for (const resource of resources) {
400 bind(resource.FQN, resource.Props);
401 bind(resource.FQN, stack.bindings[resource.FQN] ?? []);
402 }
403 for (const action of actions) {
404 bind(action.FQN, [action.Input, action.Captures]);
405 }
406 };
407
408 const makePlan = <A>(
409 stack: StackSpec<A>,
410 options: FilteredPlanOptions = {},
411 ): Effect.Effect<Plan<A | undefined>, never, State> =>
412 // @ts-expect-error
413 Effect.gen(function* () {
414 // Per-resource plan progress and phase markers are reported through
415 // events as the work happens, so a renderer can show
416 // plan computation while it runs. The default reporter is a no-op.
417
418 const declaredResources = Object.values(stack.resources);
419 const declaredActions = Object.values(stack.actions ?? {});
420 const declared = [...declaredResources, ...declaredActions];
421 bindSameStackRefs(stack, declaredResources, declaredActions);
422 const upstream = (node: ResourceLike | ActionLike) =>
423 Object.keys(
424 Output.upstreamAny(
425 isAction(node)
426 ? [node.Input, node.Captures]
427 : [node.Props, stack.bindings[node.FQN] ?? []],
428 ),
429 );
430 const selected = yield* selectResources(declared, upstream, options);
431 const resources = declaredResources.filter((node) => !selected || selected.has(node.FQN));
432 const actions = declaredActions.filter((node) => !selected || selected.has(node.FQN));
433
434 // Resolving the state service may bootstrap a remote store.
435 yield* emit({ type: "plan.phase", phase: "loading-state" });
436 const state = yield* yield* State;
437
438 // A bare platform tag yields a forward reference registered with
439 // `undefined` props (and `RequiresImplementation`); its `.make(props,
440 // impl)` Layer repairs the props when it builds (in either order — the
441 // #874 circular env-tag pattern). Props still `undefined` after the
442 // whole program evaluated means the tag was yielded but its Layer was
443 // never provided — fail fast naming the class and its Layer instead of
444 // letting a provider read `undefined` props (#1054). Plain resources
445 // may legitimately be yielded without props (a reference to
446 // already-deployed state), so the check is scoped to platform tags.
447 for (const resource of resources) {
448 if (resource.RequiresImplementation && resource.Props === undefined) {
449 return yield* Effect.die(missingImplementation(resource.Type, resource.LogicalId));
450 }
451 }
452
453 // TODO(sam): rename terminology to Stack
454 const stackName = stack.name;
455 const stage = stack.stage;
456
457 // Resolve the effective adoption setting for this plan. AdoptPolicy
458 // (provided by the CLI or scoped via `adopt(...)`) takes precedence; if
459 // unset, fall back to the AlchemyContext's `adopt` default; otherwise
460 // adoption is disabled.
461 const shouldAdopt = Effect.gen(function* () {
462 const fromService = yield* Effect.serviceOption(AdoptPolicy);
463 if (Option.isSome(fromService)) return fromService.value;
464 const ctx = yield* Effect.serviceOption(AlchemyContext);
465 return Option.match(ctx, {
466 onNone: () => false,
467 onSome: (c) => c.adopt,
468 });
469 });
470
471 // The run-level default provider mode (`alchemy dev` → "local",
472 // `alchemy deploy` → "live"). A resource-scoped `remote()` (captured on
473 // the resource at registration as `Mode`) opts out of local emulation.
474 const runDefaultMode = yield* defaultProviderMode;
475
476 /**
477 * Resolve the effective provider mode and the concrete provider
478 * service for a resource.
479 *
480 * The mode only "sticks" when the provider actually distinguishes
481 * modes (registered via `ProviderLayer.dual`). Mode-agnostic providers
482 * satisfy any requested mode with their single implementation — in a
483 * dev run, a construct that mixes emulatable resources with live-only
484 * ones (e.g. R2 buckets) just works.
485 */
486 const resolveProviderAndMode = Effect.fn(function* (resource: {
487 Type: string;
488 Mode?: ProviderMode | undefined;
489 }) {
490 const base = yield* tryFindProviderRegistrationByType(resource.Type).pipe(
491 Effect.flatMap(
492 Option.match({
493 onNone: () => Effect.die(`Provider not found for ${resource.Type}`),
494 onSome: Effect.succeed,
495 }),
496 ),
497 );
498 const mode = base.modes !== undefined ? (resource.Mode ?? runDefaultMode) : undefined;
499 const provider = yield* providerForMode(base, mode);
500 return { provider, mode };
501 });
502
503 /**
504 * Has this resource switched provider modes since it was last
505 * reconciled? Rows without a persisted mode were written by a
506 * pre-provider-mode engine (or a provider that only became dual-mode
507 * later) — their physical resource is LIVE unless its attrs carry a
508 * `dev:` identity marker proving it was reconciled locally (see
509 * {@link stampedMode}). A dev run replaces unstamped live rows exactly
510 * like stamped live rows; live runs replace unstamped marker rows.
511 */
512 const hasModeSwitched = (
513 mode: ProviderMode | undefined,
514 oldState: ResourceState | undefined,
515 ): boolean => mode !== undefined && oldState !== undefined && stampedMode(oldState) !== mode;
516
517 const resourceFqns = yield* state.list({
518 stack: stackName,
519 stage: stage,
520 });
521 const oldResources = yield* Effect.forEach(
522 resourceFqns,
523 (fqn) => state.get({ stack: stackName, stage: stage, fqn }),
524 { concurrency: "unbounded" },
525 );
526
527 // Snapshot of every persisted row, keyed by FQN. The rename resolution
528 // below reads from this map instead of issuing per-FQN `state.get`s —
529 // every renamedFrom-decorated resource (each StaticSite carries one
530 // forever) would otherwise add two round-trips per resource to every
531 // plan against a remote state store. Plan is read-only, so the
532 // snapshot cannot go stale within this run.
533 const persistedRows = new Map(resourceFqns.map((fqn, i) => [fqn, oldResources[i]]));
534
535 // Updating snapshots also retain prior bindings and downstream metadata.
536 type DependencySnapshot = {
537 downstream?: ReadonlyArray<string>;
538 bindings?: ReadonlyArray<unknown>;
539 old?: DependencySnapshot;
540 };
541 function* historicalRows(row: DependencySnapshot | undefined) {
542 while (row) {
543 yield row;
544 row = row.old;
545 }
546 }
547
548 if (selected) {
549 for (const action of actions) {
550 const row = persistedRows.get(action.FQN);
551 if (row && !isActionState(row)) {
552 return yield* Effect.die(
553 new UnsafeSelectionBoundary({
554 message: `Filtered Action '${action.FQN}' cannot overwrite persisted resource state. Finish resource cleanup before reusing its FQN for an Action.`,
555 }),
556 );
557 }
558 }
559 for (const resource of declaredResources) {
560 for (const former of resource.FormerFqns ?? []) {
561 if (former === resource.FQN) continue;
562 if (
563 (selected.has(resource.FQN) && persistedRows.has(former)) ||
564 (!selected.has(resource.FQN) && selected.has(former))
565 ) {
566 return yield* Effect.die(
567 new UnsafeSelectionBoundary({
568 message: `Filtered reconciliation cannot migrate '${former}' to '${resource.FQN}'. Run a full deployment for renames.`,
569 }),
570 );
571 }
572 }
573 }
574 }
575
576 // Credential-free dev: the adoption probe below runs each new row's
577 // `read` — for `Alchemy.remote()` rows that is a real cloud call, and
578 // it happens before apply's demand gate. Demand those credentials up
579 // front so a dev plan with nothing configured fails with the typed
580 // CredentialsRequired rather than the first read's raw auth error.
581 if (runDefaultMode === "local") {
582 const remote: Array<{ Type: string; FQN: string }> = [];
583 for (const resource of resources) {
584 const { mode } = yield* resolveProviderAndMode(resource);
585 if (mode === "live") remote.push(resource);
586 }
587 if (remote.length > 0) yield* demandRemoteCredentials(remote);
588 }
589
590 yield* emit({ type: "plan.phase", phase: "computing-plan" });
591
592 // ── FQN renames ──────────────────────────────────────────────────────
593 // Map every former FQN claimed via `renamedFrom(...)` to its claimant's
594 // current FQN. Two resources claiming the same former FQN is ambiguous
595 // and fatal. A former FQN MAY still be actively declared — that is the
596 // "old id reused by a new resource" case: the rename claim wins the
597 // row (it is an explicit user statement that the row was theirs), and
598 // the reusing resource plans a fresh create.
599 const formerFqnClaims = new Map<string, string>();
600 for (const resource of resources) {
601 for (const formerFqn of resource.FormerFqns ?? []) {
602 if (formerFqn === resource.FQN) continue;
603 const claimant = formerFqnClaims.get(formerFqn);
604 if (claimant !== undefined && claimant !== resource.FQN) {
605 return yield* Effect.die(
606 new Error(
607 `Resources '${claimant}' and '${resource.FQN}' both claim ` +
608 `former FQN '${formerFqn}' via renamedFrom(...). A former ` +
609 "FQN can migrate to exactly one resource — remove the " +
610 "decoration from one of them.",
611 ),
612 );
613 }
614 formerFqnClaims.set(formerFqn, resource.FQN);
615 }
616 }
617
618 // Resolve every rename migration up-front against the state snapshot,
619 // BEFORE any node is built — other resources' planning depends on the
620 // outcome (a resource declared at a former FQN whose row is migrating
621 // away must start from scratch).
622 //
623 // For each renamer, in former-id declaration order (most recent
624 // first):
625 //
626 // - `source` is the row that defines the resource's physical identity:
627 // the row at its own FQN when present AND type-matching, otherwise
628 // the first type-matching former row (→ `moved`).
629 // - every OTHER type-matching former row sharing `source.instanceId`
630 // is a leftover from an interrupted migration (only migration copies
631 // instanceIds) — collected for state-only cleanup.
632 // - former rows with a different instanceId belong to someone else and
633 // are left to normal orphan handling; former rows with a different
634 // resourceType (modulo registered type-aliases) can never be this
635 // resource's row and are skipped entirely.
636 // - a FOREIGN-typed row at the renamer's own FQN blocks the migration
637 // fatally: landing the migrated row there would silently abandon
638 // that row's cloud resource.
639 const renameMigrations = new Map<
640 string,
641 { row: ResourceState; renamedFrom: string[]; moved: boolean }
642 >();
643 const migratedRowFqns = new Set<string>();
644
645 const resolveRenamer = Effect.fn(function* (resource: ResourceLike) {
646 const provider = Option.getOrUndefined(
647 yield* tryFindProviderRegistrationByType(resource.Type),
648 );
649 const allowedTypes = new Set([resource.Type, ...(provider?.aliases ?? [])]);
650 const persisted = persistedRows.get(resource.FQN);
651 const persistedRow = isActionState(persisted)
652 ? undefined
653 : (persisted as ResourceState | undefined);
654 // A row at this resource's own FQN that a PREVIOUSLY RESOLVED
655 // renamer claimed (a same-deploy shift: A→B while B→C — C took the
656 // row at B) is moving away: it is not ours to keep and it does not
657 // block the migration landing here.
658 const rowTaken = migratedRowFqns.has(resource.FQN);
659 const ownRow =
660 !rowTaken && persistedRow !== undefined && allowedTypes.has(persistedRow.resourceType)
661 ? persistedRow
662 : undefined;
663
664 let source: ResourceState | undefined = ownRow;
665 let adopted: ResourceState | undefined = ownRow;
666 const renamedFrom: string[] = [];
667 for (const formerFqn of resource.FormerFqns!) {
668 if (formerFqnClaims.get(formerFqn) !== resource.FQN) continue;
669 // The same former id may be listed twice (or resolve identically);
670 // collect each former row once.
671 if (renamedFrom.includes(formerFqn)) continue;
672 const formerPersisted = persistedRows.get(formerFqn);
673 if (formerPersisted === undefined || isActionState(formerPersisted)) {
674 continue;
675 }
676 const formerRow = formerPersisted as ResourceState;
677 if (!allowedTypes.has(formerRow.resourceType)) continue;
678 if (source === undefined) {
679 source = formerRow;
680 adopted = {
681 ...formerRow,
682 fqn: resource.FQN,
683 logicalId: resource.LogicalId,
684 namespace: resource.Namespace,
685 } as ResourceState;
686 renamedFrom.push(formerFqn);
687 } else if (source.instanceId === formerRow.instanceId) {
688 renamedFrom.push(formerFqn);
689 }
690 }
691 if (renamedFrom.length === 0) return;
692 if (persistedRow !== undefined && ownRow === undefined && !rowTaken) {
693 return yield* Effect.die(
694 new Error(
695 `Cannot migrate '${renamedFrom[0]}' to '${resource.FQN}': a ` +
696 `state row of a different type ('${persistedRow.resourceType}') ` +
697 `already occupies '${resource.FQN}'. Migrating over it would ` +
698 "silently abandon that row's cloud resource. Delete or " +
699 "rename the conflicting resource first, then re-deploy.",
700 ),
701 );
702 }
703 renameMigrations.set(resource.FQN, {
704 row: adopted!,
705 renamedFrom,
706 moved: adopted !== ownRow,
707 });
708 for (const formerFqn of renamedFrom) migratedRowFqns.add(formerFqn);
709 });
710
711 // Resolve renamers in claim-dependency order: when resource R's OWN
712 // FQN is claimed as a former id by resource S (a same-deploy shift:
713 // A→B while B→C), S must resolve first — whether S takes R's row
714 // decides whether R still owns it, or falls back to ITS former rows.
715 // Iterate to fixpoint; anything left is a claim CYCLE (a swap: A⇄B),
716 // which cannot be persisted safely — the migrations would overwrite
717 // and delete each other's rows — and dies loudly.
718 let pendingRenamers = resources.filter((r) => r.FormerFqns?.length);
719 const resolvedRenamers = new Set<string>();
720 while (pendingRenamers.length > 0) {
721 const ready = pendingRenamers.filter((resource) => {
722 const claimant = formerFqnClaims.get(resource.FQN);
723 return claimant === undefined || resolvedRenamers.has(claimant);
724 });
725 if (ready.length === 0) {
726 return yield* Effect.die(
727 new Error(
728 `Rename cycle detected among [${pendingRenamers
729 .map((r) => `'${r.FQN}'`)
730 .join(", ")}]: their renamedFrom(...) declarations claim each other's ` +
731 "FQNs. Swapping ids in one deploy is not supported — rename " +
732 "through a temporary id across two deploys instead.",
733 ),
734 );
735 }
736 for (const resource of ready) {
737 yield* resolveRenamer(resource);
738 resolvedRenamers.add(resource.FQN);
739 }
740 pendingRenamers = pendingRenamers.filter((r) => !resolvedRenamers.has(r.FQN));
741 }
742
743 /**
744 * Fetch the persisted row for a declared resource, resolving renames
745 * (see the pre-computed `renameMigrations` above):
746 *
747 * - a renamer plans from its migrated row (`renamedFrom` rides onto
748 * the plan node; apply persists the move before any lifecycle op)
749 * - a resource declared at a former FQN whose row is migrating away
750 * starts from scratch — the row is NOT its state, whatever the FQN
751 * says
752 */
753 const getPersistedRow = Effect.fn(function* (resource: Pick<ResourceLike, "FQN">) {
754 const migration = renameMigrations.get(resource.FQN);
755 if (migration !== undefined) {
756 return {
757 row: migration.row,
758 renamedFrom: migration.renamedFrom,
759 renameMoved: migration.moved,
760 };
761 }
762 const persisted = yield* state.get({
763 stack: stackName,
764 stage: stage,
765 fqn: resource.FQN,
766 });
767 const row = isActionState(persisted) ? undefined : (persisted as ResourceState | undefined);
768 if (row !== undefined && migratedRowFqns.has(resource.FQN)) {
769 return { row: undefined, renamedFrom: undefined, renameMoved: false };
770 }
771 return { row, renamedFrom: undefined, renameMoved: false };
772 });
773
774 // Shared resolutions run in fibers of the plan's own scope (see
775 // `cachedInScope`): a diff that fails or is cancelled must not take the
776 // resolution every other diff is waiting on down with it.
777 const memoScope = yield* Effect.scope;
778 const resolvedResources: Record<string, Effect.Effect<any>> = {};
779
780 const resolveResource = (
781 resourceExpr: Output.ResourceExpr<any, any>,
782 ): Effect.Effect<any, Config.ConfigError | StateStoreError> =>
783 Effect.gen(function* () {
784 if (selected && !selected.has(resourceExpr.src.FQN)) {
785 return yield* Effect.die(
786 new UnsafeSelectionBoundary({
787 message: `Output evaluation discovered unselected dependency '${resourceExpr.src.FQN}'. Declare the dependency explicitly or run a full deployment.`,
788 }),
789 );
790 }
791 if (isAction(resourceExpr.src)) {
792 const node = yield* diffAction(resourceExpr.src);
793 return node.action === "noop" ? node.state.output : resourceExpr;
794 }
795 // @ts-expect-error
796 return yield* (resolvedResources[resourceExpr.src.FQN] ??= yield* cachedInScope(memoScope)(
797 Effect.gen(function* () {
798 const resource = resourceExpr.src;
799
800 const { provider, mode } = yield* resolveProviderAndMode(resource);
801 const props = materializeStableRefs(yield* resolveInput(resource.Props));
802 // Falls back to the row at a former FQN (`renamedFrom`) so a
803 // renamed resource's stable attributes keep flowing to
804 // downstream diffs across the migration.
805 const { row: oldState } = yield* getPersistedRow(resource);
806
807 if (!oldState || oldState.status === "creating") {
808 return resourceExpr;
809 }
810
811 // The resource is switching provider modes (local ⇄ live):
812 // it will be replaced, so nothing about the persisted attrs
813 // is stable for downstream consumers.
814 if (hasModeSwitched(mode, oldState)) {
815 return resourceExpr;
816 }
817
818 const oldProps = oldState.status === "updating" ? oldState.old.props : oldState.props;
819
820 // Normalize both sides through `dedupeBindings` so the binding
821 // sets handed to `diff` are deduped AND sid-sorted — provider
822 // diffs that hash/compare the arrays never churn on
823 // registration-order flips (or on legacy unsorted state).
824 const oldBindings = dedupeBindings(oldState.bindings ?? []);
825 const bindings = stack.bindings[resource.FQN] ?? [];
826 const newBindings = dedupeBindings(
827 combinedCycleMembers.has(resource.FQN) ? bindings : yield* resolveInput(bindings),
828 );
829
830 const diff = yield* provider.diff
831 ? provider
832 .diff({
833 id: resource.LogicalId,
834 fqn: resource.FQN,
835 olds: oldProps,
836 instanceId: oldState.instanceId,
837 news: props,
838 output: oldState.attr,
839 oldBindings,
840 newBindings,
841 })
842 .pipe(providePlanScope(resource, oldState.instanceId))
843 : Effect.undefined;
844
845 // A present `diff.stables` is authoritative for this update and
846 // overrides `provider.stables`. We only fall back to the
847 // provider-level "always stable" list when the diff does not
848 // return one (e.g. no diff fn, or a diff that omits `stables`).
849 const stables: string[] = diff?.stables ?? provider.stables ?? [];
850
851 const withStables = (output: any) =>
852 stables.length > 0
853 ? new Output.ResourceExpr(
854 resourceExpr.src,
855 Object.fromEntries(stables.map((stable) => [stable, output?.[stable]])),
856 )
857 : // if there are no stable properties, treat every property as changed
858 resourceExpr;
859
860 if (diff == null) {
861 if (
862 havePropsChanged(oldProps, props) ||
863 (!combinedCycleMembers.has(resource.FQN) &&
864 diffBindings(oldBindings, newBindings).some(
865 (binding) => binding.action !== "noop",
866 ))
867 ) {
868 // the props have changed but the provider did not provide any hints as to what is stable
869 // so we must assume everything has changed
870 return withStables(oldState?.attr);
871 }
872 } else if (diff.action === "update") {
873 return withStables(oldState?.attr);
874 } else if (diff.action === "replace") {
875 return resourceExpr;
876 }
877 // `--force` upgrades this resource's noop to an update (see the
878 // diff mapping in the resource-graph pass below), so its
879 // `reconcile` WILL re-run and may produce fresh attributes —
880 // that is the point of --force. Returning the persisted attr
881 // snapshot here would bake potentially-stale values into every
882 // consumer's plan props and binding data, so consumers would
883 // keep the stale attrs even though the upstream just
884 // re-reconciled. Expose only the stable attributes and let
885 // apply re-evaluate the rest against the forced reconcile's
886 // fresh output. A noop diff may carry `stables` for exactly this
887 // case (conditional stables such as a rename-mutable `name`);
888 // without them the forced upstream would only expose
889 // `provider.stables` and identity-sensitive consumers would
890 // falsely plan a replacement (#1832).
891 if (options.force) {
892 return withStables(oldState?.attr);
893 }
894 if (
895 oldState.status === "created" ||
896 oldState.status === "updated" ||
897 oldState.status === "replaced"
898 ) {
899 // we can safely return the attributes if we know they have stabilized
900 return oldState?.attr;
901 } else {
902 // we must assume the resource doesn't exist if it hasn't stabilized
903 return resourceExpr;
904 }
905 }),
906 ));
907 });
908
909 /**
910 * Resolve an input value as far as *truth* permits, keeping everything
911 * else evaluable. A whole-resource reference to an updating upstream
912 * stays a `ResourceExpr` (its stable attributes riding along): the
913 * non-stable attributes are unknown at plan time and MUST be
914 * re-evaluated — Apply runs `Output.evaluate(node.props, outputs)`
915 * against the upstream's fresh post-reconcile attributes right before
916 * `reconcile`. This is the value plan nodes carry; the diff-facing view
917 * is derived from it by {@link materializeStableRefs}.
918 */
919 const resolveInput = (
920 input: any,
921 // Ancestor chain of the current walk. A value that appears on its own
922 // ancestor path is a true cycle and is cut to `undefined` (a cycle can
923 // never persist or serialize anyway); an immutable per-level set (not
924 // a shared visited-set) keeps legitimately-shared diamond references
925 // intact and is race-free under `concurrency: "unbounded"` (#1082).
926 ancestors: ReadonlySet<object> = new Set(),
927 ): Effect.Effect<any, Config.ConfigError | StateStoreError> =>
928 Effect.gen(function* () {
929 if (!input) {
930 return input;
931 } else if (Output.isExpr(input)) {
932 return yield* resolveOutput(input);
933 } else if (Config.isConfig(input)) {
934 // Config is a lazy reference to the deploy environment. Resolve it
935 // here so the concrete value flows into diffing/hashing (an opaque
936 // Config hashes the same regardless of the underlying value) and so
937 // providers receive a resolved value instead of a Config object.
938 // `Config.Redacted` resolves to a `Redacted`, which stays opaque via
939 // the branch below.
940 return yield* resolveInput(yield* input, ancestors);
941 } else if (isResource(input)) {
942 // Resource objects have dynamic properties (path, hash, etc.) that are
943 // created on-demand by a Proxy getter and aren't enumerable via Object.entries.
944 // Resolve the ResourceExpr to get the actual resource output, then continue
945 // resolving any nested outputs in the result.
946 const resourceExpr = Output.of(input);
947 const resolved = yield* resolveOutput(resourceExpr);
948 if (Output.isResourceExpr(resolved)) {
949 // Still-unresolved reference (creating, replacing, or updating
950 // upstream) — keep it evaluable for Apply.
951 return resolved;
952 }
953 return yield* resolveInput(resolved, ancestors);
954 } else if (isPlainData(input)) {
955 if (ancestors.has(input)) {
956 return undefined;
957 }
958 const nested = new Set(ancestors).add(input);
959 if (Array.isArray(input)) {
960 return yield* Effect.forEach(input, (item) => resolveInput(item, nested), {
961 concurrency: "unbounded",
962 });
963 }
964 return Object.fromEntries(
965 yield* Effect.forEach(
966 Object.entries(input),
967 ([key, value]) =>
968 resolveInput(value, nested).pipe(Effect.map((value) => [key, value])),
969 { concurrency: "unbounded" },
970 ),
971 );
972 }
973 // Everything else is an opaque leaf returned by identity: Duration,
974 // Redacted, Date, and effect runtime values (a Worker's `exports`
975 // carries each DO's `constructor` Effect and captured `services`
976 // Context). Rebuilding a class instance entry-by-entry would strip
977 // its prototype, and effect ≥4.0.0-beta.103's Context is cyclic
978 // (#1082). Redacted additionally stays wrapped to preserve the
979 // secrecy boundary. This sits after `Config.isConfig` on purpose —
980 // Configs are Effects but must still resolve.
981 return input;
982 });
983
984 /**
985 * Project a {@link resolveInput} resolution into the DIFF-facing view:
986 * replace each whole-resource `ResourceExpr` that carries stable
987 * attributes (an upstream being *updated* in place — see `withStables` in
988 * `resolveResource`) with a plain object of those stables, so the known
989 * values flow into the consumer's `diff` and `havePropsChanged` instead
990 * of the whole reference looking unresolved and `isResolved`
991 * short-circuiting (#670 — this forced the Neon `Branch` to hand-extract
992 * `project.projectId`).
993 *
994 * The projection is deliberately lossy — diffs compare VALUES. Plan nodes
995 * never carry it: they keep the evaluable resolution so `reconcile` sees
996 * the upstream's fresh non-stable attributes (e.g. a Lambda Version's
997 * `version` number — #993's alias promotion bug).
998 */
999 const materializeStableRefs = (
1000 input: any,
1001 // Ancestor-path cycle guard — see resolveInput (#1082). Sync DFS, so
1002 // add/delete around the recursion is race-free.
1003 ancestors: WeakSet<object> = new WeakSet(),
1004 ): any => {
1005 // Expr checks come first: Output proxies are callable, so a plain
1006 // `typeof input === "object"` guard would let them slip through.
1007 if (Output.isResourceExpr(input) && input.stables) {
1008 return materializeStableRefs(input.stables, ancestors);
1009 } else if (Output.isExpr(input)) {
1010 // Genuinely unknown (e.g. a creating upstream) — nothing to show diff.
1011 return input;
1012 } else if (!input || !isPlainData(input)) {
1013 // Primitives and non-plain instances (Duration, Redacted, Date,
1014 // Effect/Layer/Context) are leaves — see isPlainData (#1082).
1015 return input;
1016 }
1017 return mapPlainData(input, ancestors, (child) => materializeStableRefs(child, ancestors));
1018 };
1019
1020 const resolveOutput = (
1021 expr: Output.Expr<any>,
1022 ): Effect.Effect<any, Config.ConfigError | StateStoreError> =>
1023 Effect.gen(function* () {
1024 if (Output.isResourceExpr(expr)) {
1025 return yield* resolveResource(expr);
1026 } else if (Output.isPropExpr(expr)) {
1027 const upstream = yield* resolveOutput(expr.expr);
1028 return upstream?.[expr.identifier];
1029 } else if (Output.isApplyExpr(expr)) {
1030 const upstream = yield* resolveOutput(expr.expr);
1031 return Output.hasOutputs(upstream) ? expr : expr.f(upstream);
1032 } else if (Output.isEffectExpr(expr)) {
1033 const upstream = yield* resolveOutput(expr.expr);
1034 return Output.hasOutputs(upstream) ? expr : yield* expr.f(upstream);
1035 } else if (Output.isFlatMapExpr(expr)) {
1036 const upstream = yield* resolveOutput(expr.expr);
1037 // Source still unresolved -> keep the flatMap intact for a later pass.
1038 // Otherwise run `f` to produce the next Output and resolve into it.
1039 return Output.hasOutputs(upstream)
1040 ? expr
1041 : yield* resolveOutput(Output.asOutput(expr.f(upstream)) as Output.Expr<any>);
1042 } else if (Output.isAllExpr(expr)) {
1043 return yield* Effect.forEach(expr.outs, resolveOutput, {
1044 concurrency: "unbounded",
1045 });
1046 } else if (Output.isLiteralExpr(expr)) {
1047 return expr.value;
1048 } else if (Output.isRefExpr(expr)) {
1049 // A ref bound to a declared resource resolves like a direct
1050 // reference: unknown while that resource is being created.
1051 const target = Output.refTarget(expr);
1052 if (target !== undefined) {
1053 return yield* resolveResource(
1054 Output.of(target as any) as Output.ResourceExpr<any, any>,
1055 );
1056 }
1057 const refStack = expr.stack ?? stackName;
1058 const refStage = expr.stage ?? stage;
1059 const refState = yield* state
1060 .get({
1061 stack: refStack,
1062 stage: refStage,
1063 fqn: expr.resourceId,
1064 })
1065 .pipe(Effect.orDie);
1066 if (!refState) {
1067 return yield* Effect.die(
1068 new Output.InvalidReferenceError({
1069 message: `Reference to '${expr.resourceId}' in stack '${refStack}' and stage '${refStage}' not found. Have you deployed '${refStage}' of '${refStack}'?`,
1070 stack: refStack,
1071 stage: refStage,
1072 resourceId: expr.resourceId,
1073 }),
1074 );
1075 }
1076 return (refState as any).attr ?? (refState as any).output;
1077 } else if (Output.isStackRefExpr(expr)) {
1078 const refStack = expr.stack;
1079 const refStage = expr.stage ?? stage;
1080 const output = yield* state
1081 .getOutput({
1082 stack: refStack,
1083 stage: refStage,
1084 })
1085 .pipe(Effect.orDie);
1086 if (output == null) {
1087 return yield* Effect.die(
1088 new Output.InvalidReferenceError({
1089 message: `Reference to stack '${refStack}' at stage '${refStage}' not found. Have you deployed stage '${refStage}' of '${refStack}'?`,
1090 stack: refStack,
1091 stage: refStage,
1092 resourceId: refStack,
1093 }),
1094 );
1095 }
1096 return output;
1097 } else if (Output.isNamedExpr(expr)) {
1098 return yield* resolveOutput(expr.expr);
1099 }
1100 return yield* Effect.die(new Error("Not implemented yet" + (expr as any).kind));
1101 });
1102
1103 // Build a set of FQNs for the new resources to detect orphans
1104 const newResourceFqns = new Set(resources.map((r) => r.FQN));
1105 const newActionFqns = new Set(actions.map((t) => t.FQN));
1106 // Unified set used wherever the DAG must include both kinds.
1107 const newNodeFqns = new Set<string>([...newResourceFqns, ...newActionFqns]);
1108
1109 // Map FQN -> list of upstream FQNs (resources this one depends on via props).
1110 // Tasks contribute upstream edges through their `Input` expression.
1111 const newUpstreamDependencies: {
1112 [fqn: string]: string[];
1113 } = Object.fromEntries([
1114 ...resources.map(
1115 (resource) =>
1116 [
1117 resource.FQN,
1118 Object.values(Output.upstreamAny(resource.Props)).map((r) => r.FQN),
1119 ] as const,
1120 ),
1121 ...actions.map(
1122 (action) =>
1123 [
1124 action.FQN,
1125 // An Action depends on the resources referenced by its Input *and*
1126 // any Output captured via `yield* output` inside its init Effect.
1127 Array.from(
1128 new Set([
1129 ...Object.values(Output.upstreamAny(action.Input)).map((r) => r.FQN),
1130 ...Object.values(Output.upstreamAny(action.Captures)).map((r) => r.FQN),
1131 ]),
1132 ),
1133 ] as const,
1134 ),
1135 ]);
1136
1137 // Map FQN -> list of upstream FQNs from bindings
1138 const bindingUpstreamDependencies: {
1139 [fqn: string]: string[];
1140 } = Object.fromEntries(
1141 resources.map((resource) => [
1142 resource.FQN,
1143 Object.values(Output.upstreamAny(stack.bindings[resource.FQN] ?? [])).map((r) => r.FQN),
1144 ]),
1145 );
1146
1147 // Combined prop + binding upstream for the desired graph, including
1148 // references to resources outside the current graph so delete validation can
1149 // tell whether any surviving resource still points at an orphan.
1150 const rawUpstreamDependencies: {
1151 [fqn: string]: string[];
1152 } = Object.fromEntries<string[]>([
1153 ...resources.map((resource): [string, string[]] => {
1154 const fqn = resource.FQN;
1155 const propDeps = newUpstreamDependencies[fqn] ?? [];
1156 const bindDeps = bindingUpstreamDependencies[fqn] ?? [];
1157 return [fqn, [...new Set([...propDeps, ...bindDeps])]];
1158 }),
1159 // Actions have no bindings — their upstream is input + init captures,
1160 // both already folded into newUpstreamDependencies above.
1161 ...actions.map((action): [string, string[]] => {
1162 const fqn = action.FQN;
1163 return [fqn, newUpstreamDependencies[fqn] ?? []];
1164 }),
1165 ]);
1166
1167 // Combined prop + binding upstream, filtered to resources/tasks in this
1168 // graph for scheduling and cycle detection.
1169 const allUpstreamDependencies: {
1170 [fqn: string]: string[];
1171 } = Object.fromEntries([
1172 ...resources.map((resource) => {
1173 const fqn = resource.FQN;
1174 const deps = rawUpstreamDependencies[fqn] ?? [];
1175 return [fqn, deps.filter((dep) => newNodeFqns.has(dep))] as const;
1176 }),
1177 ...actions.map((action) => {
1178 const fqn = action.FQN;
1179 const deps = newUpstreamDependencies[fqn] ?? [];
1180 return [fqn, deps.filter((dep) => newNodeFqns.has(dep))] as const;
1181 }),
1182 ]);
1183
1184 // Resources that participate in a cycle when both prop and binding
1185 // edges are considered. Used below to decide whether an acyclic
1186 // binding edge should also become a downstream edge.
1187 const combinedCycleMembers = findCycleMembers(allUpstreamDependencies);
1188 const inputCycleMembers = findCycleMembers({
1189 ...newUpstreamDependencies,
1190 ...Object.fromEntries(
1191 actions.map((action) => [
1192 action.FQN,
1193 Object.values(Output.upstreamAny(action.Input)).map((r) => r.FQN),
1194 ]),
1195 ),
1196 });
1197
1198 // Map FQN -> list of downstream FQNs (resources/actions that depend on
1199 // this one).
1200 //
1201 // Prop edges always become downstream edges — they can't form cycles
1202 // (the resource graph is a DAG by construction once props are fully
1203 // resolved). Binding edges become downstream edges too, except when
1204 // they participate in a cycle in the combined graph: mutual bindings
1205 // (A binds to B's data, B binds to A's data) intentionally do not
1206 // create downstream edges, so deletion does not deadlock waiting on
1207 // each other (see the "binding-only cycles inside a construct" test
1208 // in `plan.test.ts`).
1209 //
1210 // Including acyclic binding edges is required for cloud APIs that
1211 // enforce the binding at the provider level — e.g. a Cloudflare
1212 // Worker with a `service` binding to another Worker cannot delete
1213 // the upstream worker until the downstream worker's binding has been
1214 // removed. Without the binding edge in `downstream`, the two delete
1215 // concurrently and the upstream delete fails with
1216 // `ServiceBindingConflict`.
1217 //
1218 // Actions don't have bindings, so for action upstreams we use only
1219 // prop edges (which collapse to `newUpstreamDependencies` lookups).
1220 //
1221 // The edges are inverted in one pass (in `rawUpstreamDependencies` order,
1222 // so each downstream list keeps that order) — scanning every node's
1223 // upstream list per node was quadratic in resource count (#2400).
1224 const directDownstream = new Map<string, string[]>();
1225 for (const [downFqn, upstreams] of Object.entries(rawUpstreamDependencies)) {
1226 const propDeps = new Set(newUpstreamDependencies[downFqn]);
1227 for (const upFqn of upstreams) {
1228 if (downFqn === upFqn) continue;
1229 // Binding-only edge — exclude when both endpoints sit inside
1230 // the same SCC of the combined graph.
1231 if (
1232 !propDeps.has(upFqn) &&
1233 combinedCycleMembers.has(upFqn) &&
1234 combinedCycleMembers.has(downFqn)
1235 ) {
1236 continue;
1237 }
1238 let downstream = directDownstream.get(upFqn);
1239 if (!downstream) directDownstream.set(upFqn, (downstream = []));
1240 downstream.push(downFqn);
1241 }
1242 }
1243
1244 const computeDownstream = (upFqn: string): string[] => {
1245 const downstream = [...(directDownstream.get(upFqn) ?? [])];
1246 if (selected) {
1247 for (const row of historicalRows(persistedRows.get(upFqn))) {
1248 for (const dep of row.downstream ?? []) {
1249 if (!selected.has(dep) && !downstream.includes(dep)) downstream.push(dep);
1250 }
1251 }
1252 }
1253 return downstream;
1254 };
1255
1256 const newDownstreamDependencies: {
1257 [fqn: string]: string[];
1258 } = Object.fromEntries([
1259 ...resources.map((resource) => [resource.FQN, computeDownstream(resource.FQN)] as const),
1260 ...actions.map((action) => [action.FQN, computeDownstream(action.FQN)] as const),
1261 ]);
1262
1263 const actionPlans: Record<
1264 string,
1265 Effect.Effect<ActionRun | ActionNoop, Config.ConfigError | StateStoreError>
1266 > = {};
1267 const diffAction = Effect.fn("plan.diff.action")(function* (action: ActionLike) {
1268 return yield* (actionPlans[action.FQN] ??= yield* cachedInScope(memoScope)(
1269 Effect.gen(function* () {
1270 const fqn = action.FQN;
1271 const downstream = newDownstreamDependencies[fqn] ?? [];
1272 const oldState = yield* state.get({ stack: stackName, stage, fqn });
1273 const prior = isActionState(oldState) ? oldState : undefined;
1274 const resolvedInput = inputCycleMembers.has(fqn)
1275 ? action.Input
1276 : yield* resolveInput(action.Input);
1277 // Actions are pure in their inputs. Only a completed, unforced run
1278 // with fully known, identical inputs has a reusable output.
1279 if (
1280 prior?.status === "ran" &&
1281 !options.force &&
1282 !inputCycleMembers.has(fqn) &&
1283 isResolved(resolvedInput) &&
1284 prior.inputHash === (yield* hashInput(resolvedInput))
1285 ) {
1286 return {
1287 kind: "action",
1288 action: "noop",
1289 def: action,
1290 state: prior,
1291 downstream,
1292 } satisfies ActionNoop;
1293 }
1294 return {
1295 kind: "action",
1296 action: "run",
1297 def: action,
1298 input: action.Input,
1299 state: prior,
1300 downstream,
1301 forced: !!options.force,
1302 } satisfies ActionRun;
1303 }),
1304 ));
1305 });
1306
1307 const plannedCount = yield* Ref.make(0);
1308 const resourcePlanned = (node: CRUD) =>
1309 Ref.updateAndGet(plannedCount, (count) => count + 1).pipe(
1310 Effect.flatMap((completed) =>
1311 emit({
1312 type: "plan.resource.completed",
1313 ...describeResource(node),
1314 completed,
1315 total: resources.length,
1316 }),
1317 ),
1318 );
1319
1320 const diffResource = Effect.fn("plan.diff.resource")(function* (resource: ResourceLike) {
1321 const { provider, mode } = yield* resolveProviderAndMode(resource);
1322 const id = resource.LogicalId;
1323 const fqn = resource.FQN;
1324 // Paired with the resource-planned completion below so renderers can
1325 // show what is actually in flight (diffs may read the cloud and run
1326 // concurrently — completions alone hide the slow tail).
1327 yield* emit({
1328 type: "plan.resource.started",
1329 fqn,
1330 logicalId: id,
1331 resourceType: resource.Type,
1332 total: resources.length,
1333 });
1334 // Apply-facing props (stored on the plan node): whole-resource
1335 // references to updating upstreams stay evaluable `ResourceExpr`s.
1336 // Apply runs `Output.evaluate(node.props, outputs)` right before
1337 // `reconcile`, so these references resolve to the upstream's
1338 // fresh post-reconcile attributes.
1339 const applyProps = yield* resolveInput(resource.Props);
1340 // Diff-facing view of the same resolution: stable attributes
1341 // materialized so their known values flow into `diff` /
1342 // `havePropsChanged`.
1343 const news = materializeStableRefs(applyProps);
1344 const downstream = newDownstreamDependencies[fqn] ?? [];
1345
1346 // Apply-facing binding rows, mirroring `applyProps`: payloads
1347 // whose data embeds a whole-resource reference to an updating
1348 // upstream keep it as an evaluable `ResourceExpr`. Apply runs
1349 // `Output.evaluate(node.bindings, outputs)` right before
1350 // `reconcile`, so the host receives the upstream's fresh
1351 // post-reconcile attributes. Collapse duplicates by sid so the
1352 // binding set handed to `diff` matches what `reconcile` receives
1353 // (see `dedupeBindings`).
1354 const applyBindings: ResourceBinding[] = dedupeBindings(
1355 yield* resolveInput(stack.bindings[fqn] ?? []),
1356 );
1357 // Diff-facing view of the same rows: stable attributes
1358 // materialized so `diffBindings` / `provider.diff` compare known
1359 // values. Terminal commits still persist the payload the provider
1360 // actually reconciled with (#874) — Apply commits the evaluated
1361 // `bindingOutputs`, not these plan-time shapes.
1362 const newBindings: ResourceBinding[] = materializeStableRefs(applyBindings);
1363 // The row is looked up at the resource's FQN with a fallback to
1364 // its former FQNs (`renamedFrom`); a row found under a former
1365 // FQN arrives here already remapped to the new identity, and
1366 // `renamedFrom` rides onto the plan node so apply persists the
1367 // move. (A Task previously holding this FQN is treated as no
1368 // prior state — its row is reaped by `actionDeletions` below.)
1369 const { row: persistedRow, renamedFrom, renameMoved } = yield* getPersistedRow(resource);
1370 let oldState: ResourceState | undefined = persistedRow;
1371
1372 // Engine-level adoption. When there is no prior state, always
1373 // consult `provider.read` (if implemented) so the engine — not
1374 // each lifecycle method — owns the existence/ownership decision.
1375 //
1376 // The provider returns one of:
1377 // - `undefined` → resource doesn't exist; create it
1378 // - plain attrs → exists and is owned by us; silent adopt
1379 // - `Unowned(attrs)` → exists but is *not* ours
1380 //
1381 // Routing:
1382 // - owned → adopt the `created` state
1383 // from attrs and continue
1384 // through the normal diff
1385 // path (so subsequent props
1386 // drift produces an update).
1387 // - unowned + adopt enabled → take over: adopt the
1388 // `created` state and let the
1389 // next update overwrite tags.
1390 // - unowned + adopt disabled → fail with
1391 // `OwnedBySomeoneElse`.
1392 //
1393 // Plan construction is side-effect-free: the adopted `created`
1394 // state is only held in-memory here (to drive the diff) and rides
1395 // onto the plan node as `node.state`. Persisting it to the state
1396 // store happens exclusively during APPLY of that node (the update
1397 // lifecycle commits `updating` / `updated` carrying this state).
1398 // If planning persisted here, a mere `alchemy plan` / `--dry-run`
1399 // would claim ownership of an unowned cloud resource, arming a
1400 // later unrelated deploy to orphan-delete it. See
1401 // https://github.com/alchemy-run/alchemy/issues/793.
1402 //
1403 // After a cold-start adoption (engine just discovered an
1404 // existing cloud resource via `read`), force the engine's
1405 // normal `update` path so the provider can re-sync ownership
1406 // tags, configuration, etc. against the desired props.
1407 // Adoption carries state with `props: news`, so the default
1408 // diff sees no drift and would noop — which would leave any
1409 // foreign-owned tags / divergent config in place. Forcing
1410 // update keeps the deploy idempotent: if cloud state already
1411 // matches news, the provider's update is a no-op write.
1412 //
1413 // Skip the adoption probe entirely when `news` still contains
1414 // unresolved upstream Outputs (e.g. a `streamArn` referencing
1415 // a stream being created in the same plan). Calling `read` with
1416 // an unresolved value would surface as `ParseError` from the
1417 // SDK protocol layer. Upstream creation can produce existing children
1418 // (e.g. a cloned branch's Auth integration), so Apply must perform the
1419 // deferred ownership probe once those identities resolve.
1420 // A resource declared at a former FQN whose row just migrated
1421 // away is genuinely NEW by declaration — skip the probe. Its
1422 // predecessor's physical resource still carries tags branded
1423 // with THIS logical id (the migrated row's reconcile hasn't
1424 // re-branded them yet), so a tag-based `read` would find it
1425 // and silently adopt the very resource that was renamed away.
1426 const claimant = formerFqnClaims.get(fqn);
1427 const claimantRow = claimant === undefined ? undefined : persistedRows.get(claimant);
1428 const reusesMigratedFqn =
1429 migratedRowFqns.has(fqn) ||
1430 oldState?.adoptionBlocked === "migrated-fqn" ||
1431 // Migration can commit before the fresh create records its exclusion.
1432 (oldState === undefined && claimantRow !== undefined && !isActionState(claimantRow));
1433 let forceUpdateAfterAdoption = false;
1434 if (oldState === undefined && provider.read && isResolved(news) && !reusesMigratedFqn) {
1435 const adoptInstanceId = yield* generateInstanceId();
1436 const readResult = yield* provider
1437 .read({
1438 id,
1439 fqn,
1440 instanceId: adoptInstanceId,
1441 olds: news,
1442 output: undefined,
1443 })
1444 .pipe(providePlanScope(resource, adoptInstanceId));
1445 if (readResult !== undefined) {
1446 const isUnowned = Unowned.is(readResult);
1447 // A resource-scoped `adopt(...)` (captured on the resource at
1448 // registration) overrides the stack/CLI default.
1449 const adoptThis = resource.Adopt ?? (yield* shouldAdopt);
1450 if (isUnowned && !adoptThis) {
1451 return yield* new OwnedBySomeoneElse({
1452 message:
1453 `Cannot adopt resource '${fqn}' (${resource.Type}): ` +
1454 "it exists in the cloud but is not owned by this " +
1455 "stack/stage/logical-id. Re-run with `--adopt` (or " +
1456 "wrap the effect in `adopt(true)`) to take it over.",
1457 resourceType: resource.Type,
1458 logicalId: id,
1459 });
1460 }
1461 const adoptedState = {
1462 status: "created" as const,
1463 fqn,
1464 logicalId: id,
1465 instanceId: adoptInstanceId,
1466 namespace: resource.Namespace,
1467 resourceType: resource.Type,
1468 props: news,
1469 attr: stripUnowned(readResult),
1470 providerVersion: provider.version ?? 0,
1471 bindings: [],
1472 downstream,
1473 removalPolicy: resource.RemovalPolicy,
1474 providerMode: mode,
1475 } satisfies CreatedResourceState;
1476 // In-memory only — do NOT persist here. Plan.make runs for
1477 // `alchemy plan` / `deploy --dry-run` too, so a `state.set`
1478 // would mutate persistent state during a read-only preview.
1479 // The adopted state rides onto the plan node via `oldState`
1480 // (→ `node.state`) and is persisted at APPLY time by the
1481 // update lifecycle's `updating` / `updated` commits. See
1482 // https://github.com/alchemy-run/alchemy/issues/793.
1483 oldState = adoptedState;
1484 forceUpdateAfterAdoption = true;
1485 }
1486 }
1487
1488 // Sid-sorted like `newBindings` (see the resolveResource note).
1489 const oldBindings = dedupeBindings(oldState?.bindings ?? []);
1490 // Actions come from the materialized comparison (`newBindings`);
1491 // the payloads the node carries into Apply come from the
1492 // apply-faithful rows, joined by sid — both are views of the same
1493 // deduped `stack.bindings[fqn]` rows, so action and payload can
1494 // never drift. `delete` rows keep the persisted old data.
1495 const applyBindingData = new Map(applyBindings.map((b) => [b.sid, b.data]));
1496 const bindingDiffs = diffBindings(oldBindings, newBindings).map((b) =>
1497 b.action === "delete" || !applyBindingData.has(b.sid)
1498 ? b
1499 : { ...b, data: applyBindingData.get(b.sid) },
1500 );
1501
1502 // Local ⇄ live switch: the persisted row was reconciled by a
1503 // different provider mode than the one resolved for this run.
1504 // The two runtimes host distinct physical instances, so this is
1505 // always a replacement — the new instance is created with the
1506 // new mode's provider, and Apply deletes the old generation
1507 // with the provider of the mode that created it (see
1508 // `deleteOldGenerations` / `collectGarbage`).
1509 const modeSwitched = hasModeSwitched(mode, oldState);
1510 if (selected && modeSwitched && oldState?.status === "deleting") {
1511 return yield* Effect.die(
1512 new UnsafeSelectionBoundary({
1513 message: `Cannot switch provider mode for '${fqn}' during filtered recovery from deleting. Finish interrupted destruction in its recorded '${stampedMode(oldState)}' mode before deploying in '${mode}' mode; a full mode-switch deployment is not a safe recovery.`,
1514 }),
1515 );
1516 }
1517
1518 const adoptThis = resource.Adopt ?? (yield* shouldAdopt);
1519 const Node = <T extends Apply>(
1520 node: Omit<T, "provider" | "resource" | "bindings" | "downstream" | "mode">,
1521 ) =>
1522 ({
1523 ...node,
1524 provider,
1525 resource,
1526 bindings: bindingDiffs,
1527 downstream,
1528 mode,
1529 renamedFrom,
1530 adoptionBlocked: reusesMigratedFqn ? "migrated-fqn" : undefined,
1531 deferredAdoption:
1532 (provider.read || provider.observe) &&
1533 !reusesMigratedFqn &&
1534 // A replacement targets a new physical identity, which may belong
1535 // to someone else — admit it like a fresh create.
1536 (node.action === "replace" ||
1537 (node.action === "create" &&
1538 // Plan reads resolved props itself; without `read`, Apply
1539 // admits them through `observe`.
1540 ((oldState === undefined && (!isResolved(news) || !provider.read)) ||
1541 (oldState?.status === "creating" && oldState.attr === undefined))))
1542 ? { adopt: adoptThis }
1543 : undefined,
1544 }) as any as T;
1545
1546 // Plan against the persisted state we have, not the ideal final state we
1547 // hoped to reach last time. Recovery is expressed by mapping each
1548 // intermediate state back onto a fresh CRUD action.
1549 if (oldState === undefined) {
1550 return Node<Create>({
1551 action: "create",
1552 props: applyProps,
1553 state: oldState,
1554 });
1555 } else if (!modeSwitched && oldState.status === "creating" && oldState.attr === undefined) {
1556 // A create may have succeeded before state persistence failed. If the
1557 // provider can recover an attribute snapshot, keep driving the same
1558 // create instead of starting over blindly.
1559 //
1560 // Early `creating` checkpoints contain raw plan-time props, which may
1561 // still contain unresolved Output expressions (e.g. a name
1562 // referencing an upstream created in the same failed deploy).
1563 // `read` implementations derive identity from `olds` when
1564 // `output` is undefined (as it is here), so handing them
1565 // unresolved exprs crashes. Skip the probe — same behavior as
1566 // a read that found nothing — and re-drive the create.
1567 //
1568 // A checkpoint whose unresolved props were stripped (`propsIncomplete`)
1569 // can't identify the attempt at all: a lookup could match a different
1570 // resource. Skip it too and let the diff below decide.
1571 if (
1572 provider.read &&
1573 !reusesMigratedFqn &&
1574 !oldState.propsIncomplete &&
1575 isResolved(oldState.props)
1576 ) {
1577 const attr = yield* provider
1578 .read({
1579 id,
1580 fqn,
1581 instanceId: oldState.instanceId,
1582 olds: oldState.props,
1583 output: oldState.attr,
1584 })
1585 .pipe(
1586 providePlanScope(resource, oldState.instanceId),
1587 // `creating` props pass `isResolved` yet can still carry
1588 // holes where unresolved Outputs were stripped at commit
1589 // time (see stripUnresolved) — e.g. a parent reference
1590 // persisted as `{}`. A provider that dereferences one
1591 // crashes deep inside its SDK client (a SchemaError
1592 // defect), which would brick every subsequent plan on
1593 // the stage. Recovery is best-effort: degrade the defect
1594 // to "nothing recovered" and re-drive the create (#995).
1595 Effect.catchDefect((defect) =>
1596 Effect.logWarning(
1597 `Recovery read for '${fqn}' crashed; treating the ` +
1598 "interrupted create as not recoverable and " +
1599 "re-driving it.",
1600 defect,
1601 ).pipe(Effect.as(undefined)),
1602 ),
1603 );
1604 if (attr !== undefined) {
1605 // The recovered resource may be foreign: our interrupted
1606 // create could have lost a name race, or died before
1607 // stamping ownership. Route `Unowned` through the same
1608 // adoption table as the cold-start probe above — never
1609 // silently take over (and later mutate/delete) a resource
1610 // we cannot prove we created.
1611 if (Unowned.is(attr)) {
1612 const adoptThis = resource.Adopt ?? (yield* shouldAdopt);
1613 if (!adoptThis) {
1614 return yield* new OwnedBySomeoneElse({
1615 message:
1616 `Cannot resume creating resource '${fqn}' ` +
1617 `(${resource.Type}): a resource with its physical ` +
1618 "identity exists in the cloud but is not owned by " +
1619 "this stack/stage/logical-id. Re-run with `--adopt` " +
1620 "(or wrap the effect in `adopt(true)`) to take it " +
1621 "over.",
1622 resourceType: resource.Type,
1623 logicalId: id,
1624 });
1625 }
1626 }
1627 // Continue through the normal diff below with the recovered
1628 // live snapshot. Desired props may have changed while the
1629 // previous create was interrupted; bypassing diff here can
1630 // drive an immutable change through reconcile and falsely
1631 // persist the old physical resource as converged.
1632 oldState = { ...oldState, attr: stripUnowned(attr) };
1633 }
1634 }
1635 }
1636
1637 // Diff against whatever props represent the best-known current attempt.
1638 // For replacement recovery that means the top-level replacement props,
1639 // not the older generations stored under `old`.
1640 const oldProps = oldState.props;
1641
1642 // On a mode switch the provider diff is skipped entirely:
1643 // comparing props across runtimes is meaningless (and the new
1644 // mode's provider has never seen the old mode's state). The
1645 // action is a replacement by definition.
1646 const diff = modeSwitched
1647 ? ({
1648 action: "replace",
1649 deleteFirst: false,
1650 } satisfies ReplaceDiff)
1651 : yield* asEffect(
1652 provider
1653 ?.diff?.({
1654 id,
1655 fqn,
1656 olds: oldProps,
1657 instanceId: oldState.instanceId,
1658 output: oldState.attr,
1659 news,
1660 oldBindings,
1661 newBindings,
1662 })
1663 .pipe(providePlanScope(resource, oldState.instanceId)),
1664 ).pipe(
1665 Effect.map(
1666 (diff) =>
1667 diff ??
1668 ({
1669 action:
1670 havePropsChanged(oldProps, news) ||
1671 bindingDiffs.some((b) => b.action !== "noop")
1672 ? "update"
1673 : "noop",
1674 } as UpdateDiff | NoopDiff),
1675 ),
1676 // Values a Platform's Init captured (`yield* Config.x(...)`,
1677 // `yield* output`) reach the provider only through `props.env`,
1678 // and a provider's diff may not compare `env` (#1831). The engine
1679 // compares them itself so a changed value always deploys.
1680 Effect.map((diff) =>
1681 diff.action === "noop" && capturedEnvChanged(resource, oldProps, news)
1682 ? ({ action: "update" } satisfies UpdateDiff)
1683 : diff,
1684 ),
1685 Effect.map((diff) =>
1686 options.force && diff.action === "noop"
1687 ? ({
1688 action: "update",
1689 } satisfies UpdateDiff)
1690 : diff,
1691 ),
1692 // After a cold-start adoption (silent or takeover), force at
1693 // least an update so the provider re-syncs ownership tags /
1694 // config against the desired props (otherwise the engine
1695 // would noop and any drift between the existing cloud
1696 // resource and `news` — including foreign-owned tags after a
1697 // takeover — would persist).
1698 //
1699 // A row that just migrated from a former FQN (`renameMoved`)
1700 // gets the same treatment: its cloud resource is still
1701 // branded with the OLD logical id's tags, and if the old id
1702 // is being reused by a new resource, leaving them stale
1703 // would let the reuser's future adoption probes match the
1704 // wrong physical resource.
1705 Effect.map((diff) =>
1706 (forceUpdateAfterAdoption || renameMoved) && diff.action === "noop"
1707 ? ({ action: "update" } satisfies UpdateDiff)
1708 : diff,
1709 ),
1710 );
1711
1712 if (oldState.status === "creating") {
1713 if (diff.action === "noop") {
1714 // we're in the creating state and props are un-changed
1715 // let's just continue where we left off
1716 return Node<Create>({
1717 action: "create",
1718 props: applyProps,
1719 state: oldState,
1720 });
1721 } else if (diff.action === "update") {
1722 // props have changed in a way that is updatable
1723 // again, just continue with the create
1724 // TODO(sam): should we maybe try an update instead?
1725 return Node<Create>({
1726 action: "create",
1727 props: applyProps,
1728 state: oldState,
1729 });
1730 } else {
1731 // props have changed in an incompatible way
1732 // because it's possible that an un-updatable resource has already been created
1733 // we must use a replace step to create a new one and delete the potential old one
1734 return Node<Replace>({
1735 action: "replace",
1736 props: applyProps,
1737 deleteFirst: diff.deleteFirst ?? false,
1738 state: oldState,
1739 });
1740 }
1741 } else if (oldState.status === "updating") {
1742 // Updating already targets the live resource, so noop/update both mean
1743 // "finish the interrupted update". Only a replace diff escalates it
1744 // into a fresh replacement.
1745 if (diff.action === "update" || diff.action === "noop") {
1746 // we can continue where we left off
1747 return Node<Update>({
1748 action: "update",
1749 props: applyProps,
1750 state: oldState,
1751 });
1752 } else {
1753 // we started to update a resource but now believe we should replace it
1754 return Node<Replace>({
1755 action: "replace",
1756 deleteFirst: diff.deleteFirst ?? false,
1757 props: applyProps,
1758 // TODO(sam): can Apply handle replacements when the oldState is UpdatingResourceState?
1759 // -> or should we do a provider.read to try and reconcile back to UpdatedResourceState?
1760 state: oldState,
1761 });
1762 }
1763 } else if (oldState.status === "replacing") {
1764 // The replacement candidate is still being created. Noop/update keep
1765 // driving the same generation; replace means that candidate itself is
1766 // now obsolete and must be wrapped in a new outer generation.
1767 if (diff.action === "noop") {
1768 // this is the stable case - noop means just continue with the replacement
1769 return Node<Replace>({
1770 action: "replace",
1771 deleteFirst: oldState.deleteFirst,
1772 props: applyProps,
1773 state: oldState,
1774 });
1775 } else if (diff.action === "update") {
1776 // potential problem here - the props have changed since we tried to replace,
1777 // but not enough to trigger another replacement. the resource provider should
1778 // be designed as idempotent to converge to the right state when creating the new resource
1779 // the newly generated instanceId is intended to assist with this
1780 return Node<Replace>({
1781 action: "replace",
1782 deleteFirst: oldState.deleteFirst,
1783 props: applyProps,
1784 state: oldState,
1785 });
1786 } else {
1787 // The in-flight replacement candidate itself now needs replacement.
1788 // Mark this as a restart so Apply creates a fresh generation instead
1789 // of resuming the old replacement instance.
1790 return Node<Replace>({
1791 restart: true,
1792 action: "replace",
1793 deleteFirst: diff.deleteFirst ?? oldState.deleteFirst,
1794 props: applyProps,
1795 state: oldState,
1796 });
1797 }
1798 } else if (oldState.status === "replaced") {
1799 // The new resource already exists. Noop means "just let GC finish",
1800 // update means "mutate the current replacement before GC finishes",
1801 // and replace means "the current replacement also became obsolete".
1802 if (diff.action === "noop") {
1803 // this is the stable case - noop means just continue cleaning up the replacement
1804 return Node<Replace>({
1805 action: "replace",
1806 deleteFirst: oldState.deleteFirst,
1807 props: applyProps,
1808 state: oldState,
1809 });
1810 } else if (diff.action === "update") {
1811 // the replacement has been created but now also needs to be updated
1812 // the resource provider should:
1813 // 1. Update the newly created replacement resource
1814 // 2. Then proceed as normal to delete the replaced resources (after all downstream references are updated)
1815 return Node<Update>({
1816 action: "update",
1817 props: applyProps,
1818 state: oldState,
1819 });
1820 } else {
1821 // Cleanup is still pending, but the current "new" resource has already
1822 // become obsolete. Start another replacement generation and preserve
1823 // the existing replaced node as part of the recursive old chain.
1824 return Node<Replace>({
1825 restart: true,
1826 action: "replace",
1827 deleteFirst: diff.deleteFirst ?? oldState.deleteFirst,
1828 props: applyProps,
1829 state: oldState,
1830 });
1831 }
1832 } else if (oldState.status === "deleting") {
1833 // we're in a partially deleted state, it is unclear whether it was or was not deleted
1834 // so continue by re-creating it with the same instanceId and desired props
1835 return Node<Create>({
1836 action: "create",
1837 props: applyProps,
1838 state: {
1839 ...oldState,
1840 status: "creating",
1841 props: news,
1842 },
1843 });
1844 } else if (diff.action === "update") {
1845 // Stable created/updated resources follow the normal CRUD mapping.
1846 return Node<Update>({
1847 action: forceUpdateAfterAdoption ? "adopted" : "update",
1848 adopting: forceUpdateAfterAdoption,
1849 props: applyProps,
1850 state: oldState,
1851 });
1852 } else if (diff.action === "replace") {
1853 return Node<Replace>({
1854 action: "replace",
1855 props: applyProps,
1856 state: oldState,
1857 deleteFirst: diff?.deleteFirst ?? false,
1858 });
1859 } else {
1860 return Node<NoopUpdate>({
1861 action: "noop",
1862 state: oldState,
1863 });
1864 }
1865 });
1866
1867 // Every diff runs to completion and every failure is reported. With
1868 // fail-fast `Effect.all`, the first exit to arrive wins the aggregate
1869 // cause — and when a diff is cancelled by a sibling's failure (or ends
1870 // interrupt-only for any other reason) that can be a bare interruption,
1871 // hiding the InvalidReferenceError or provider error that actually
1872 // broke the plan.
1873 const diffExits = yield* Effect.forEach(
1874 resources,
1875 (resource) => Effect.exit(Effect.tap(diffResource(resource), resourcePlanned)),
1876 { concurrency: "unbounded" },
1877 );
1878 const diffFailures = diffExits.filter(Exit.isFailure);
1879 if (diffFailures.length > 0) {
1880 const reasons = diffFailures.flatMap((exit) => exit.cause.reasons);
1881 const failures = reasons.filter((reason) => !Cause.isInterruptReason(reason));
1882 return yield* Effect.failCause(Cause.fromReasons(failures.length > 0 ? failures : reasons));
1883 }
1884 const resourceGraph = Object.fromEntries(
1885 diffExits.filter(Exit.isSuccess).map((exit) => [exit.value.resource.FQN, exit.value]),
1886 ) as Plan["resources"];
1887
1888 if (selected) {
1889 const downstream = new Map<string, Set<string>>();
1890 const addEdge = (source: string, consumer: string) => {
1891 let edges = downstream.get(source);
1892 if (!edges) downstream.set(source, (edges = new Set()));
1893 edges.add(consumer);
1894 };
1895 for (const node of declared) {
1896 for (const source of upstream(node)) addEdge(source, node.FQN);
1897 }
1898 let bindingEvidence: string | undefined;
1899 let incompleteHistory: string | undefined;
1900 for (const [fqn, row] of persistedRows) {
1901 for (const snapshot of historicalRows(row)) {
1902 for (const consumer of snapshot.downstream ?? []) {
1903 addEdge(fqn, consumer);
1904 }
1905 if (snapshot.bindings?.length) bindingEvidence ??= fqn;
1906 if (snapshot.downstream === undefined) incompleteHistory ??= fqn;
1907 }
1908 }
1909 const unselectedConsumers = (fqn: string) => {
1910 const reachable = new Set([fqn]);
1911 const outside = new Set<string>();
1912 for (const source of reachable) {
1913 for (const consumer of downstream.get(source) ?? []) {
1914 reachable.add(consumer);
1915 if (!selected.has(consumer)) outside.add(consumer);
1916 }
1917 }
1918 return outside;
1919 };
1920 for (const source of selected) {
1921 for (const row of historicalRows(persistedRows.get(source))) {
1922 for (const consumer of row.downstream ?? []) {
1923 // SCC filtering alone does not detach an edge in the desired graph.
1924 if (!selected.has(consumer) || rawUpstreamDependencies[consumer]?.includes(source))
1925 continue;
1926 const outside = unselectedConsumers(consumer);
1927 if (outside.size > 0) {
1928 return yield* Effect.die(
1929 new UnsafeSelectionBoundary({
1930 message: `Cannot detach '${source}' from '${consumer}' while downstream consumers are unselected: ${[...outside].sort().join(", ")}. Select them or run a full deployment.`,
1931 }),
1932 );
1933 }
1934 }
1935 }
1936 }
1937 const excludedRows = [...persistedRows].filter(([fqn, row]) => row && !selected.has(fqn));
1938 const excluded = excludedRows[0];
1939 for (const [fqn, node] of Object.entries(resourceGraph)) {
1940 const pending = node.state?.status === "replacing" || node.state?.status === "replaced";
1941 if (node.action !== "replace" && !pending) continue;
1942 // Resolved payloads do not identify binding sources, including cycles
1943 // omitted from downstream. Evidence anywhere can involve this resource.
1944 if (excluded && (bindingEvidence || incompleteHistory)) {
1945 return yield* Effect.die(
1946 new UnsafeSelectionBoundary({
1947 message: `Cannot replace or collect old generations of '${fqn}' while '${String(excluded[0])}' is unselected. ${bindingEvidence ? `Historical binding-cycle dependencies recorded on '${bindingEvidence}'` : `Historical dependencies missing from '${incompleteHistory}'`} cannot be proven safe; run a full deployment.`,
1948 }),
1949 );
1950 }
1951 const outside = unselectedConsumers(fqn);
1952 if (outside.size > 0) {
1953 return yield* Effect.die(
1954 new UnsafeSelectionBoundary({
1955 message: `Cannot replace or collect old generations of '${fqn}' while dependents are unselected: ${[...outside].sort().join(", ")}. Select them or run a full deployment.`,
1956 }),
1957 );
1958 }
1959 }
1960 if (excludedRows.length > 0) {
1961 for (const fqn of selected) {
1962 if (
1963 [...historicalRows(persistedRows.get(fqn))].some(
1964 (snapshot) => snapshot.downstream === undefined,
1965 )
1966 ) {
1967 return yield* Effect.die(
1968 new UnsafeSelectionBoundary({
1969 message: `Cannot reconcile '${fqn}' with incomplete historical downstream metadata while persisted nodes are unselected: ${excludedRows
1970 .map(([id]) => id)
1971 .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
1972 .join(", ")}. Select them or run a full deployment.`,
1973 }),
1974 );
1975 }
1976 }
1977 }
1978 if (bindingEvidence && excludedRows.length > 0) {
1979 const hasHistoricalBindings = (row: DependencySnapshot | undefined) =>
1980 [...historicalRows(row)].some((snapshot) => snapshot.bindings?.length);
1981 // Independent writes can fail before planned replacement evidence is durable.
1982 const survivingBindings =
1983 excludedRows.some(([, row]) => hasHistoricalBindings(row)) ||
1984 Object.entries(resourceGraph).some(([fqn, node]) => {
1985 const persisted = persistedRows.get(fqn);
1986 if (!persisted || isActionState(persisted) || !hasHistoricalBindings(persisted))
1987 return false;
1988 if (node.action === "noop") return true;
1989 return (
1990 (node.action === "update" ||
1991 node.action === "adopted" ||
1992 (node.action === "create" && persisted.status === "creating")) &&
1993 persisted.status !== "deleting" &&
1994 persisted.status !== "replacing" &&
1995 persisted.status !== "replaced" &&
1996 node.bindings.some((binding) => binding.action !== "delete")
1997 );
1998 });
1999 if (!survivingBindings) {
2000 return yield* Effect.die(
2001 new UnsafeSelectionBoundary({
2002 message: `Cannot discard the last historical binding evidence while persisted nodes are unselected: ${excludedRows
2003 .map(([fqn]) => fqn)
2004 .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
2005 .join(", ")}. Select them or run a full deployment.`,
2006 }),
2007 );
2008 }
2009 }
2010 }
2011
2012 // ── Action plan nodes ────────────────────────────────────────────────
2013 // Per-action plan progress, mirroring the resource pass.
2014 const actionCount = yield* Ref.make(0);
2015 const actionPlanned = (entry: readonly [string, ActionApply]) =>
2016 Ref.updateAndGet(actionCount, (count) => count + 1).pipe(
2017 Effect.flatMap((completed) =>
2018 emit({
2019 type: "plan.action.completed",
2020 ...describeAction(entry[1]),
2021 completed,
2022 total: actions.length,
2023 }),
2024 ),
2025 );
2026
2027 const actionGraph = Object.fromEntries(
2028 (yield* Effect.forEach(
2029 actions,
2030 (action) =>
2031 diffAction(action).pipe(
2032 Effect.map((node) => [action.FQN, node] as const),
2033 Effect.tap(actionPlanned),
2034 ),
2035 { concurrency: "unbounded" },
2036 )) as ReadonlyArray<readonly [string, ActionApply]>,
2037 ) as Plan["actions"];
2038
2039 // SCC membership of the combined upstream graph. Apply uses it to
2040 // decide whether an update node must publish its prior attr early to
2041 // break a cycle, or can simply wait for upstreams like a DAG node
2042 // (the common case). Computed once, above, for the downstream graph.
2043 const cycleMembers = combinedCycleMembers;
2044
2045 // Detect unsatisfiable dependency cycles among create/replace nodes.
2046 // Update/noop nodes signal their Deferred before waitForDeps when in a
2047 // cycle so they cannot deadlock. Create/replace nodes only signal
2048 // early when they have a precreate handler. Simulate the concurrent
2049 // execution: precreate nodes are immediately "resolved", then
2050 // iteratively resolve any node whose deps are all resolved. Remaining
2051 // nodes would deadlock.
2052 {
2053 const createReplaceNodes = new Set(
2054 Object.entries(resourceGraph)
2055 .filter(([, node]) => node.action === "create" || node.action === "replace")
2056 .map(([fqn]) => fqn),
2057 );
2058
2059 if (createReplaceNodes.size > 0) {
2060 const hasPrecreate = new Set(
2061 [...createReplaceNodes].filter((fqn) => !!resourceGraph[fqn]?.provider?.precreate),
2062 );
2063
2064 const resolved = new Set(hasPrecreate);
2065 let changed = true;
2066 while (changed) {
2067 changed = false;
2068 for (const fqn of createReplaceNodes) {
2069 if (resolved.has(fqn)) continue;
2070 const deps = (allUpstreamDependencies[fqn] ?? []).filter((dep) =>
2071 createReplaceNodes.has(dep),
2072 );
2073 if (deps.every((dep) => resolved.has(dep))) {
2074 resolved.add(fqn);
2075 changed = true;
2076 }
2077 }
2078 }
2079
2080 const deadlocked = [...createReplaceNodes].filter((fqn) => !resolved.has(fqn));
2081 if (deadlocked.length > 0) {
2082 const missingPrecreate = deadlocked.filter((fqn) => !hasPrecreate.has(fqn));
2083 return yield* Effect.die(
2084 new UnsatisfiedResourceCycle({
2085 message:
2086 `Circular dependency detected that cannot be resolved: [${deadlocked.join(", ")}]. ` +
2087 `Resources lacking a precreate handler: [${missingPrecreate.join(", ")}]. ` +
2088 `All resources in a dependency cycle must implement precreate to allow early signaling.`,
2089 cycle: deadlocked,
2090 missingPrecreate,
2091 }),
2092 );
2093 }
2094 }
2095 }
2096
2097 // A delete-first replacement in a cycle deletes its previous generation
2098 // before precreate. Apply resolves the props that upstreams outside the
2099 // cycle determine first, so only props derived from a cycle peer are
2100 // still unresolved then, and only the provider's `observe` can check
2101 // ownership before that delete. Without it, refuse here — before apply
2102 // touches anything — unless adoption is allowed.
2103 for (const [fqn, node] of Object.entries(resourceGraph)) {
2104 if (
2105 node.action === "replace" &&
2106 node.deleteFirst &&
2107 cycleMembers.has(fqn) &&
2108 !node.provider.observe &&
2109 node.deferredAdoption?.adopt === false &&
2110 !isResolved(node.props) &&
2111 Object.keys(Output.resolveUpstream(node.props)).some((dep) => cycleMembers.has(dep)) &&
2112 // A resumed replacement already holds its precreated identity.
2113 !(node.state.status === "replacing" && !node.restart && node.state.attr !== undefined)
2114 ) {
2115 return yield* new UnverifiableReplacement({
2116 message:
2117 `Cannot replace resource '${fqn}' (${node.resource.Type}): ` +
2118 "it must be deleted before its replacement is pre-created, but " +
2119 "the replacement's identity depends on outputs that are not " +
2120 "resolved yet, so its ownership cannot be checked first. Re-run " +
2121 "with `--adopt` (or wrap the effect in `adopt(true)`) to replace it anyway.",
2122 resourceType: node.resource.Type,
2123 logicalId: node.resource.LogicalId,
2124 });
2125 }
2126 }
2127
2128 // Both orphan passes (task rows below, resource rows further down)
2129 // examine every persisted row of this stack instance.
2130 const persistedFqns = selected ? [] : yield* state.list({ stack: stackName, stage });
2131
2132 // Orphan progress mirrors the diff passes: every persisted row is
2133 // examined, but only rows that actually become deletion nodes are
2134 // reported — `completed` tracks examination so progress stays monotonic.
2135 const actionExaminedCount = yield* Ref.make(0);
2136 const actionDeletionPlanned = (entry: readonly [string, ActionDelete] | undefined) =>
2137 Ref.updateAndGet(actionExaminedCount, (count) => count + 1).pipe(
2138 Effect.flatMap((completed) =>
2139 entry === undefined
2140 ? Effect.void
2141 : emit({
2142 type: "plan.action.completed",
2143 ...describeAction(entry[1]),
2144 completed,
2145 total: persistedFqns.length,
2146 }),
2147 ),
2148 );
2149
2150 // Task deletions: state rows previously written by tasks that no
2151 // longer appear in the stack. The body is NOT invoked — we just drop
2152 // the row.
2153 const diffActionDeletion = Effect.fn("plan.diff.actionDeletion")(function* (fqn: string) {
2154 if (newActionFqns.has(fqn) || newResourceFqns.has(fqn)) return;
2155 const persisted = yield* state.get({
2156 stack: stackName,
2157 stage,
2158 fqn,
2159 });
2160 if (!isActionState(persisted)) return;
2161 const { logicalId } = parseFqn(fqn);
2162 return [
2163 fqn,
2164 {
2165 kind: "action",
2166 action: "delete",
2167 state: persisted,
2168 downstream: persisted.downstream ?? [],
2169 def: {
2170 Kind: "action",
2171 Namespace: persisted.namespace,
2172 FQN: fqn,
2173 LogicalId: logicalId,
2174 Type: persisted.actionType,
2175 Input: persisted.input,
2176 Captures: {},
2177 Run: () => undefined as any,
2178 Output: undefined as any,
2179 } satisfies ActionLike,
2180 } satisfies ActionDelete,
2181 ] as const;
2182 });
2183
2184 const actionDeletions: Plan["actionDeletions"] = Object.fromEntries(
2185 (yield* Effect.forEach(
2186 persistedFqns,
2187 (fqn) =>
2188 diffActionDeletion(fqn).pipe(
2189 Effect.tap((entry) => actionDeletionPlanned(entry ?? undefined)),
2190 ),
2191 { concurrency: "unbounded" },
2192 )).filter((v): v is NonNullable<typeof v> => !!v),
2193 );
2194
2195 // Deletion progress mirrors the resource pass: every persisted row is
2196 // examined, but only rows that actually become deletion nodes are
2197 // reported — `completed` tracks examination so progress stays monotonic.
2198 const deletionCandidates = persistedFqns;
2199 const examinedCount = yield* Ref.make(0);
2200 const deletionPlanned = (entry: readonly [string, Delete] | undefined) =>
2201 Ref.updateAndGet(examinedCount, (count) => count + 1).pipe(
2202 Effect.flatMap((completed) =>
2203 entry === undefined
2204 ? Effect.void
2205 : emit({
2206 type: "plan.resource.completed",
2207 ...describeResource(entry[1]),
2208 completed,
2209 total: deletionCandidates.length,
2210 }),
2211 ),
2212 );
2213
2214 const diffDeletion = Effect.fn("plan.diff.deletion")(function* (fqn: string) {
2215 if (newResourceFqns.has(fqn) || newActionFqns.has(fqn)) {
2216 return;
2217 }
2218 const persisted = yield* state.get({
2219 stack: stackName,
2220 stage: stage,
2221 fqn,
2222 });
2223 // Tasks are routed through `actionDeletions` above.
2224 if (isActionState(persisted)) return;
2225 const oldState = persisted as ResourceState | undefined;
2226 if (oldState) {
2227 // A row being migrated by a rename (`renameMigrations`) is
2228 // moving, not orphaned — apply drops it state-only after
2229 // committing the migrated row at its new FQN. Rows at former
2230 // FQNs that did NOT migrate (foreign type, different
2231 // instanceId, unclaimed) are absent from this set and fall
2232 // through to normal orphan deletion.
2233 if (migratedRowFqns.has(fqn)) {
2234 return;
2235 }
2236 const { logicalId } = parseFqn(fqn);
2237 const resourceType = oldState.resourceType;
2238 // A "zombie" row references a type with no registered provider
2239 // (removed from the program, or renamed without an alias).
2240 // That is fatal: the program and state disagree, and without
2241 // the provider the row's physical resource cannot be deleted
2242 // anyway. Die at plan time with a typed error naming the row
2243 // and the remediation instead of limping into a partial apply.
2244 //
2245 // Orphan deletes resolve the provider variant for the mode
2246 // that created the row (`providerMode`, or the `dev:` marker
2247 // inference for legacy unstamped rows), so e.g. a local dev
2248 // worker's row is deleted by the local provider even during a
2249 // live deploy — and vice versa. Unstamped rows are physically
2250 // live unless their attrs carry the marker (see stampedMode),
2251 // never the run default.
2252 const rowMode = stampedMode(oldState);
2253 const providerOption = yield* tryFindProviderByType(resourceType, rowMode);
2254 if (Option.isNone(providerOption)) {
2255 return yield* Effect.die(missingProviderError(resourceType, fqn));
2256 }
2257 const provider = providerOption.value;
2258 const downstream = new Set(oldState.downstream);
2259 let generation = oldState;
2260 while (generation.status === "replacing" || generation.status === "replaced") {
2261 generation = generation.old;
2262 for (const dep of generation.downstream) downstream.add(dep);
2263 }
2264 // NOTE: an attr-less row (interrupted create) is NOT recovered
2265 // here. Apply's `deleteResource` performs the authoritative
2266 // read-then-delete recovery — it also covers replaced-chain
2267 // old generations that never pass through plan, and routes
2268 // `Unowned` results away from `provider.delete`.
2269 return [
2270 fqn,
2271 {
2272 action: oldState.removalPolicy === "retain" ? "orphaned" : "delete",
2273 state: oldState,
2274 provider: provider,
2275 mode: oldState.providerMode,
2276 resource: {
2277 Namespace: oldState.namespace,
2278 FQN: fqn,
2279 LogicalId: logicalId,
2280 Type: oldState.resourceType,
2281 Attributes: oldState.attr,
2282 Props: oldState.props,
2283 Binding: undefined!,
2284 Provider: Provider(resourceType),
2285 RemovalPolicy: oldState.removalPolicy,
2286 Adopt: undefined,
2287 RequiresImplementation: undefined,
2288 Mode: oldState.providerMode,
2289 FormerFqns: undefined,
2290 RuntimeContext: undefined!,
2291 Providers: undefined,
2292 } as ResourceLike,
2293 downstream: [...downstream],
2294 bindings: oldState.bindings.map((binding) => ({
2295 sid: binding.sid,
2296 action: "delete" as const,
2297 data: binding.data,
2298 })),
2299 } satisfies Delete,
2300 ] as const;
2301 }
2302 });
2303
2304 const deletions = Object.fromEntries(
2305 (yield* Effect.forEach(
2306 deletionCandidates,
2307 (fqn) => diffDeletion(fqn).pipe(Effect.tap((entry) => deletionPlanned(entry ?? undefined))),
2308 { concurrency: "unbounded" },
2309 )).filter((v) => !!v),
2310 );
2311
2312 for (const resourceFqn of Object.keys(deletions)) {
2313 const dependencies = Object.entries(rawUpstreamDependencies)
2314 .filter(
2315 ([survivorFqn, upstream]) =>
2316 survivorFqn in resourceGraph && upstream.includes(resourceFqn),
2317 )
2318 .map(([survivorFqn]) => survivorFqn);
2319 if (dependencies.length > 0) {
2320 return yield* new DeleteResourceHasDownstreamDependencies({
2321 message: `Resource ${resourceFqn} has downstream dependencies`,
2322 resourceId: resourceFqn,
2323 dependencies,
2324 });
2325 }
2326 }
2327
2328 return {
2329 resources: resourceGraph,
2330 actions: actionGraph,
2331 deletions,
2332 actionDeletions,
2333 output: selected ? undefined : stack.output,
2334 selectedFqns: selected,
2335 cycleMembers,
2336 defaultMode: runDefaultMode,
2337 } satisfies Plan<A | undefined> as Plan<A | undefined>;
2338 }).pipe(
2339 // Owns the memoized resolutions' fibers for the plan's duration.
2340 Effect.scoped,
2341 ensureArtifactStore,
2342 Effect.withSpan("plan.make", {
2343 attributes: {
2344 "alchemy.stack": stack.name,
2345 "alchemy.stage": stack.stage,
2346 "alchemy.resources.count": Object.keys(stack.resources).length,
2347 "alchemy.force": !!options.force,
2348 },
2349 }),
2350 );
2351
2352 /**
2353 * Build the plan that destroys every resource of `(stack.name, stack.stage)`.
2354 *
2355 * The spec is emptied out so every persisted resource becomes an orphan
2356 * deletion, and `output` is left undefined so `apply` does not overwrite the
2357 * last deploy's persisted stack output with an empty husk. `apply` recognizes
2358 * the `destroy` marker and deletes the stage's remaining persisted state (the
2359 * stack output record) once the destroy has converged, so `state.getOutput`
2360 * and `state.listStages` agree the stage is gone.
2361 *
2362 * @see https://github.com/alchemy-run/alchemy/issues/961
2363 */
2364 export const destroy = (stack: {
2365 name: string;
2366 stage: string;
2367 include?: never;
2368 exclude?: never;
2369 }): Effect.Effect<Plan<undefined>, never, State> =>
2370 stack.include !== undefined || stack.exclude !== undefined
2371 ? Effect.die(
2372 new InvalidResourceSelection({
2373 message: "Filtered destroy is not supported.",
2374 }),
2375 )
2376 : make({
2377 name: stack.name,
2378 stage: stack.stage,
2379 resources: {},
2380 bindings: {},
2381 actions: {},
2382 output: undefined,
2383 }).pipe(Effect.map((plan) => ({ ...plan, destroy: true })));
2384
2385 /**
2386 * Whether any `env` value a Platform's Init captured differs from the
2387 * persisted props. An unresolved value counts as changed.
2388 */
2389 const capturedEnvChanged = (
2390 resource: ResourceLike,
2391 olds: { env?: Record<string, unknown> } | undefined,
2392 news: { env?: Record<string, unknown> } | undefined,
2393 ): boolean => {
2394 const keys = capturedEnvKeys(resource);
2395 if (keys.length === 0) return false;
2396 const pick = (props: { env?: Record<string, unknown> } | undefined) =>
2397 Object.fromEntries(keys.map((key) => [key, props?.env?.[key]]));
2398 return havePropsChanged(pick(olds), pick(news));
2399 };
2400
2401 const providePlanScope =
2402 (resource: ResourceLike, instanceId: string) =>
2403 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
2404 Effect.serviceOption(ArtifactStore).pipe(
2405 Effect.map(Option.getOrElse(createArtifactStore)),
2406 Effect.flatMap((store) =>
2407 effect.pipe(
2408 failCredentialsRequired(resource.FQN),
2409 Effect.provide([
2410 Layer.succeed(Artifacts, makeScopedArtifacts(store, resource.FQN)),
2411 Layer.succeed(ResourceContext, {
2412 logicalId: resource.LogicalId,
2413 fqn: resource.FQN,
2414 instanceId,
2415 type: resource.Type,
2416 }),
2417 ]),
2418 ),
2419 ),
2420 );
2421
2422 export class DeleteResourceHasDownstreamDependencies extends Data.TaggedError(
2423 "DeleteResourceHasDownstreamDependencies",
2424 )<{
2425 message: string;
2426 resourceId: string;
2427 dependencies: string[];
2428 }> {}
2429
2430 export class UnsatisfiedResourceCycle extends Data.TaggedError("UnsatisfiedResourceCycle")<{
2431 message: string;
2432 cycle: string[];
2433 missingPrecreate: string[];
2434 }> {}
2435
2436 // TODO(sam): compare props
2437 // oldBinding.props !== newBinding.props;
2438
2439 /**
2440 * Print a plan in a human-readable format that shows the graph topology.
2441 */
2442 export const printPlan = (plan: Plan): string => {
2443 const lines: string[] = [];
2444 const allNodes = { ...plan.resources, ...plan.deletions };
2445
2446 // Build reverse mapping: upstream -> downstream
2447 const upstreamMap: Record<string, string[]> = {};
2448 for (const [id] of Object.entries(allNodes)) {
2449 upstreamMap[id] = [];
2450 }
2451 for (const [id, node] of Object.entries(allNodes)) {
2452 if (!node) continue;
2453 for (const downstreamId of node.state?.downstream ?? []) {
2454 if (upstreamMap[downstreamId]) {
2455 upstreamMap[downstreamId].push(id);
2456 }
2457 }
2458 }
2459
2460 // Action symbols
2461 const actionSymbol = (action: string) => {
2462 switch (action) {
2463 case "create":
2464 return "+";
2465 case "update":
2466 return "~";
2467 case "adopted":
2468 return "(+)";
2469 case "delete":
2470 return "-";
2471 case "orphaned":
2472 return "(-)";
2473 case "replace":
2474 return "±";
2475 case "noop":
2476 return "=";
2477 default:
2478 return "?";
2479 }
2480 };
2481
2482 // Print header
2483 lines.push("╔════════════════════════════════════════════════════════════════╗");
2484 lines.push("║ PLAN ║");
2485 lines.push("╠════════════════════════════════════════════════════════════════╣");
2486 lines.push("║ Legend: + create, ~ update, - delete, ± replace, = noop, ║");
2487 lines.push("║ λ run task, · skip task ║");
2488 lines.push("╚════════════════════════════════════════════════════════════════╝");
2489 lines.push("");
2490
2491 // Print resources section
2492 lines.push("┌─ Resources ────────────────────────────────────────────────────┐");
2493 const resourceIds = Object.keys(plan.resources).sort();
2494 for (const id of resourceIds) {
2495 const node = plan.resources[id];
2496 const symbol = actionSymbol(node.action);
2497 const type = node.resource?.type ?? "unknown";
2498 const downstream = node.state?.downstream?.length
2499 ? ` → [${node.state?.downstream.join(", ")}]`
2500 : "";
2501 const renamed = node.renamedFrom?.length
2502 ? ` (renamed from ${node.renamedFrom.join(", ")})`
2503 : "";
2504 lines.push(`│ [${symbol}] ${id} (${type})${downstream}${renamed}`);
2505 }
2506 if (resourceIds.length === 0) {
2507 lines.push("│ (none)");
2508 }
2509 lines.push("└────────────────────────────────────────────────────────────────┘");
2510 lines.push("");
2511
2512 // Print tasks section
2513 lines.push("┌─ Tasks ────────────────────────────────────────────────────────┐");
2514 const taskIds = Object.keys(plan.actions ?? {}).sort();
2515 for (const id of taskIds) {
2516 const node = plan.actions[id];
2517 const symbol = node.action === "run" ? "λ" : "·";
2518 const type = node.def.Type;
2519 const downstream = node.downstream.length ? ` → [${node.downstream.join(", ")}]` : "";
2520 lines.push(`│ [${symbol}] ${id} (${type})${downstream}`);
2521 }
2522 if (taskIds.length === 0) {
2523 lines.push("│ (none)");
2524 }
2525 lines.push("└────────────────────────────────────────────────────────────────┘");
2526 lines.push("");
2527
2528 // Print deletions section
2529 lines.push("┌─ Deletions ────────────────────────────────────────────────────┐");
2530 const deletionIds = Object.keys(plan.deletions).sort();
2531 for (const id of deletionIds) {
2532 const node = plan.deletions[id]!;
2533 const type = node.resource?.Type ?? "unknown";
2534 const downstream = node.state.downstream?.length
2535 ? ` → [${node.state.downstream.join(", ")}]`
2536 : "";
2537 lines.push(`│ [-] ${id} (${type})${downstream}`);
2538 }
2539 const taskDeletionIds = Object.keys(plan.actionDeletions ?? {}).sort();
2540 for (const id of taskDeletionIds) {
2541 const node = plan.actionDeletions[id]!;
2542 lines.push(`│ [-] ${id} (${node.def.Type}) [action]`);
2543 }
2544 if (deletionIds.length === 0 && taskDeletionIds.length === 0) {
2545 lines.push("│ (none)");
2546 }
2547 lines.push("└────────────────────────────────────────────────────────────────┘");
2548 lines.push("");
2549
2550 return lines.join("\n");
2551 };