The best way to control Claude Code, Codex and more from any computer or phone
| 1 | /** @effect-diagnostics anyUnknownInErrorContext:off */ |
| 2 | import * as Cause from "effect/Cause"; |
| 3 | import * as Data from "effect/Data"; |
| 4 | import * as Deferred from "effect/Deferred"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import * as Layer from "effect/Layer"; |
| 7 | import * as Option from "effect/Option"; |
| 8 | import * as Ref from "effect/Ref"; |
| 9 | import { stripUnowned } from "./AdoptPolicy.ts"; |
| 10 | import { |
| 11 | Artifacts, |
| 12 | ArtifactStore, |
| 13 | createArtifactStore, |
| 14 | ensureArtifactStore, |
| 15 | makeScopedArtifacts, |
| 16 | } from "./Artifacts.ts"; |
| 17 | import { deepEqual } from "./Diff.ts"; |
| 18 | import { captureEmit, emit } from "./Events.ts"; |
| 19 | import type { Apply, Plan } from "./Plan.ts"; |
| 20 | import { findProviderByType, Provider } from "./Provider.ts"; |
| 21 | import { stampedMode } from "./ProviderMode.ts"; |
| 22 | import { resourceSession } from "./Report.ts"; |
| 23 | import type { ResourceLike } from "./Resource.ts"; |
| 24 | import { ResourceContext } from "./ResourceContext.ts"; |
| 25 | import { |
| 26 | isActionState, |
| 27 | State, |
| 28 | type CreatedResourceState, |
| 29 | type ResourceState, |
| 30 | type UpdatedResourceState, |
| 31 | } from "./State/index.ts"; |
| 32 | import { type ResourceOp, recordResourceOp } from "./Telemetry/Metrics.ts"; |
| 33 | import { findCycleMembers } from "./Util/scc.ts"; |
| 34 | |
| 35 | /** |
| 36 | * The outcome of checking or repairing drift for a single resource. |
| 37 | * |
| 38 | * - `unchanged` — the observed cloud state matches the persisted attributes. |
| 39 | * - `drifted` — (dry-run only) the cloud state diverged from the persisted |
| 40 | * attributes; a non-dry-run drift would repair it. |
| 41 | * - `missing` — (dry-run only) the resource no longer exists in the cloud; |
| 42 | * a non-dry-run drift would recreate it. |
| 43 | * - `repaired` — drift was detected and the resource was reconciled back to |
| 44 | * its desired (last-deployed) state. |
| 45 | * - `recreated` — the resource was missing from the cloud and was reconciled |
| 46 | * from scratch, reusing the persisted instance id so |
| 47 | * deterministic physical names converge to the same values. |
| 48 | * - `skipped` — the resource was not checked; see `reason` (provider has no |
| 49 | * `read`, or the persisted status is not stable). |
| 50 | */ |
| 51 | export type DriftAction = |
| 52 | | "unchanged" |
| 53 | | "drifted" |
| 54 | | "missing" |
| 55 | | "repaired" |
| 56 | | "recreated" |
| 57 | | "skipped"; |
| 58 | |
| 59 | export interface DriftResourceResult { |
| 60 | fqn: string; |
| 61 | logicalId: string; |
| 62 | resourceType: string; |
| 63 | action: DriftAction; |
| 64 | /** Why the resource was skipped (only set when `action === "skipped"`). */ |
| 65 | reason?: string; |
| 66 | /** |
| 67 | * The resource's attributes after the drift: the reconciled attributes for |
| 68 | * `repaired`/`recreated`, the observed cloud attributes for `drifted`, and |
| 69 | * the persisted attributes for `unchanged`. Unset for `missing`/`skipped`. |
| 70 | */ |
| 71 | attr?: any; |
| 72 | } |
| 73 | |
| 74 | export interface DriftResult { |
| 75 | resources: Record<string, DriftResourceResult>; |
| 76 | } |
| 77 | |
| 78 | /** A provider lifecycle failure annotated with the resource being checked. */ |
| 79 | export class DriftResourceError extends Data.TaggedError("DriftResourceError")<{ |
| 80 | readonly message: string; |
| 81 | readonly fqn: string; |
| 82 | readonly logicalId: string; |
| 83 | readonly resourceType: string; |
| 84 | readonly operation: ResourceOp; |
| 85 | readonly cause: unknown; |
| 86 | }> {} |
| 87 | |
| 88 | /** |
| 89 | * Reconcile state drift for every resource persisted under `stack`/`stage`. |
| 90 | * |
| 91 | * Unlike `deploy` (which converges the cloud to a *new* desired state |
| 92 | * computed from the stack program), `drift` converges the cloud back to the |
| 93 | * *last-deployed* desired state recorded in the state store. It needs no |
| 94 | * stack program — only the state store and the resource providers. |
| 95 | * |
| 96 | * The algorithm, per resource, is observe → compare → converge: |
| 97 | * |
| 98 | * 1. **Read** — call `provider.read` with the persisted props/attributes to |
| 99 | * observe the live cloud state. |
| 100 | * 2. **Compare** — deep-compare the observed attributes against the |
| 101 | * persisted attributes. Equal ⇒ `unchanged`. |
| 102 | * 3. **Reconcile** — on drift, call `provider.reconcile` with the persisted |
| 103 | * props as the desired state (`news`) and the *observed* attributes as |
| 104 | * `output`, so the provider diffs against reality rather than a stale |
| 105 | * snapshot. When the resource is missing entirely, reconcile runs |
| 106 | * greenfield (`olds`/`output` undefined) under the *same* instance id so |
| 107 | * deterministic physical names regenerate identically. |
| 108 | * 4. **Persist** — write the fresh attributes back to the state store. |
| 109 | * |
| 110 | * Resources are observed concurrently. Repairs follow the persisted |
| 111 | * `downstream` edges: a recreated topic exists before its subscription is |
| 112 | * recreated. Missing resources are recreated without their bindings first and |
| 113 | * bound once every missing resource exists again, because binding data (an S3 |
| 114 | * notification's target topic) can point at a resource recreated later. A |
| 115 | * failure checking one resource does not interrupt the others; all failures |
| 116 | * are aggregated into a single combined cause after every resource has been |
| 117 | * attempted. |
| 118 | * |
| 119 | * Resources that cannot be checked are reported as `skipped` rather than |
| 120 | * failing the run: providers without `read` (nothing to observe), and |
| 121 | * resources whose persisted status is not stable (`creating`, `updating`, |
| 122 | * `replacing`, `replaced`, `deleting`) — those represent an interrupted |
| 123 | * deploy and must be recovered by `deploy`, which owns replacement chains |
| 124 | * and dependency ordering. Action rows have no cloud state and are ignored. |
| 125 | */ |
| 126 | const runDrift = ( |
| 127 | stack: { name: string; stage: string }, |
| 128 | options: { |
| 129 | readonly dryRun: boolean; |
| 130 | /** Check and repair only these resources; the rest of the stage is untouched. */ |
| 131 | readonly only?: ReadonlyArray<string>; |
| 132 | }, |
| 133 | ): Effect.Effect<DriftResult, any, State> => |
| 134 | Effect.gen(function* () { |
| 135 | // Phase markers and per-resource progress are emitted as events so |
| 136 | // renderers can show the drift check as it runs. |
| 137 | yield* emit({ type: "plan.phase", phase: "loading-state" }); |
| 138 | const state = yield* yield* State; |
| 139 | const reportEvent = yield* captureEmit; |
| 140 | const stackName = stack.name; |
| 141 | const stage = stack.stage; |
| 142 | const dryRun = options.dryRun; |
| 143 | |
| 144 | const driftResource = Effect.fn("drift.resource")(function* (fqn: string) { |
| 145 | const persisted = yield* state.get({ stack: stackName, stage, fqn }); |
| 146 | // Action rows have no cloud state to drift. |
| 147 | if (!persisted || isActionState(persisted)) { |
| 148 | return undefined; |
| 149 | } |
| 150 | const old = persisted as ResourceState; |
| 151 | const { logicalId, instanceId, resourceType, namespace } = old; |
| 152 | |
| 153 | const result = ( |
| 154 | partial: Pick<DriftResourceResult, "action" | "reason" | "attr">, |
| 155 | ): DriftResourceResult => ({ |
| 156 | fqn, |
| 157 | logicalId, |
| 158 | resourceType, |
| 159 | ...partial, |
| 160 | }); |
| 161 | |
| 162 | const scopedSession = resourceSession(reportEvent, fqn, logicalId); |
| 163 | |
| 164 | const report = (status: "updating" | "updated" | "creating" | "created" | "skipped") => |
| 165 | reportEvent({ |
| 166 | type: "apply.resource.status", |
| 167 | fqn, |
| 168 | id: logicalId, |
| 169 | resourceType, |
| 170 | status, |
| 171 | }); |
| 172 | |
| 173 | // Surface the skip reason through the session (the TUI renders it as a |
| 174 | // note under the row; the logging CLI prints it) and settle the row |
| 175 | // with a terminal `skipped` status so it never shows as in-progress. |
| 176 | const skip = (reason: string) => |
| 177 | Effect.gen(function* () { |
| 178 | yield* scopedSession.note(reason); |
| 179 | yield* report("skipped"); |
| 180 | return result({ action: "skipped", reason }); |
| 181 | }); |
| 182 | |
| 183 | if (old.status !== "created" && old.status !== "updated") { |
| 184 | // Anything mid-flight (or with a pending replacement chain) belongs |
| 185 | // to `deploy`'s recovery machinery — replacement generations and |
| 186 | // dependency ordering are not drift's to drive. |
| 187 | return yield* skip( |
| 188 | old.status === "replaced" || old.status === "replacing" |
| 189 | ? `resource has a pending replacement (status '${old.status}'); run deploy to finish it` |
| 190 | : `resource status '${old.status}' is not stable; run deploy to recover`, |
| 191 | ); |
| 192 | } |
| 193 | |
| 194 | // Observe with the provider variant of the mode that created the row — |
| 195 | // a local dev worker's state must be read by the local provider. |
| 196 | // Legacy unstamped rows infer "local" from a `dev:` identity marker. |
| 197 | const provider = yield* findProviderByType(resourceType, stampedMode(old)); |
| 198 | if (!provider.read) { |
| 199 | return yield* skip(`provider '${resourceType}' does not implement read`); |
| 200 | } |
| 201 | |
| 202 | // Persist a repaired row. Everything but the status, attributes and |
| 203 | // bindings carries over from the persisted row — notably the |
| 204 | // `providerMode` stamp, without which a repaired local row would be |
| 205 | // treated as live. |
| 206 | const commit = ( |
| 207 | status: "created" | "updated", |
| 208 | attr: ResourceState["attr"], |
| 209 | bindings: ResourceState["bindings"], |
| 210 | ) => { |
| 211 | const row = { |
| 212 | kind: old.kind, |
| 213 | namespace, |
| 214 | fqn, |
| 215 | logicalId, |
| 216 | instanceId, |
| 217 | resourceType, |
| 218 | props: old.props!, |
| 219 | attr: attr!, |
| 220 | providerVersion: provider.version ?? 0, |
| 221 | bindings, |
| 222 | downstream: old.downstream, |
| 223 | removalPolicy: old.removalPolicy, |
| 224 | providerMode: old.providerMode, |
| 225 | adoptionBlocked: old.adoptionBlocked, |
| 226 | }; |
| 227 | return state.set({ |
| 228 | stack: stackName, |
| 229 | stage, |
| 230 | fqn, |
| 231 | value: |
| 232 | status === "created" |
| 233 | ? ({ ...row, status } satisfies CreatedResourceState) |
| 234 | : ({ ...row, status } satisfies UpdatedResourceState), |
| 235 | }); |
| 236 | }; |
| 237 | |
| 238 | // Paired with the resource-planned completion so renderers can show |
| 239 | // which rows' cloud reads are actually in flight (the slowest part of |
| 240 | // a drift check). Emitted after the skip gates: skipped rows settle |
| 241 | // instantly and never read the cloud. |
| 242 | yield* emit({ |
| 243 | type: "plan.resource.started", |
| 244 | fqn, |
| 245 | logicalId, |
| 246 | resourceType, |
| 247 | total: fqns.length, |
| 248 | }); |
| 249 | const observed = yield* provider |
| 250 | .read({ |
| 251 | id: logicalId, |
| 252 | fqn, |
| 253 | instanceId, |
| 254 | olds: old.props as never, |
| 255 | output: old.attr as never, |
| 256 | }) |
| 257 | .pipe(instrumentLifecycle("read", fqn, resourceType, logicalId, instanceId)); |
| 258 | |
| 259 | if (observed === undefined) { |
| 260 | if (dryRun) { |
| 261 | return result({ action: "missing" }); |
| 262 | } |
| 263 | return { fqn, old, provider, live: undefined, result, scopedSession, report, commit }; |
| 264 | } |
| 265 | |
| 266 | // `read` may brand the attributes as Unowned when ownership markers |
| 267 | // (tags) have drifted out from under us — the brand is a plan-time |
| 268 | // routing hint, never persisted, and here the state store already |
| 269 | // records the resource as ours. Tag drift then surfaces through the |
| 270 | // attribute comparison below and repairs like any other drift. |
| 271 | const live = stripUnowned(observed); |
| 272 | |
| 273 | if (deepEqual(live, old.attr)) { |
| 274 | return result({ action: "unchanged", attr: old.attr }); |
| 275 | } |
| 276 | |
| 277 | if (dryRun) { |
| 278 | return result({ action: "drifted", attr: live }); |
| 279 | } |
| 280 | return { fqn, old, provider, live, result, scopedSession, report, commit }; |
| 281 | }); |
| 282 | type PendingRepair = Extract< |
| 283 | Effect.Success<ReturnType<typeof driftResource>>, |
| 284 | { old: unknown } |
| 285 | >; |
| 286 | const isPendingRepair = ( |
| 287 | observed: DriftResourceResult | PendingRepair | undefined, |
| 288 | ): observed is PendingRepair => observed !== undefined && "old" in observed; |
| 289 | |
| 290 | // ── missing — recreate under the same instance id, without bindings ── |
| 291 | // |
| 292 | // Binding data often points at other resources (an S3 notification |
| 293 | // targets a topic), and a binding edge inside a cycle is not recorded in |
| 294 | // `downstream`. So, like Apply's precreate, missing resources are first |
| 295 | // created bare in `downstream` order; their bindings are attached in the |
| 296 | // second phase, once every missing resource exists again. The bare |
| 297 | // create is committed with no bindings so a crash in between leaves a |
| 298 | // row the next deploy re-binds. |
| 299 | const recreate = Effect.fn("drift.recreate")(function* (pending: PendingRepair) { |
| 300 | const { fqn, old, provider, report, commit, scopedSession, result } = pending; |
| 301 | const { logicalId, instanceId, resourceType } = old; |
| 302 | const bindings = old.bindings ?? []; |
| 303 | yield* report("creating"); |
| 304 | const attr = yield* provider |
| 305 | .reconcile({ |
| 306 | id: logicalId, |
| 307 | fqn, |
| 308 | instanceId, |
| 309 | news: old.props as never, |
| 310 | olds: undefined, |
| 311 | output: undefined, |
| 312 | session: scopedSession, |
| 313 | bindings: [] as never, |
| 314 | }) |
| 315 | .pipe(instrumentLifecycle("create", fqn, resourceType, logicalId, instanceId)); |
| 316 | yield* commit("created", attr, []); |
| 317 | if (bindings.length === 0) { |
| 318 | yield* report("created"); |
| 319 | return { done: result({ action: "recreated", attr }) }; |
| 320 | } |
| 321 | return { rebind: { ...pending, live: attr, recreated: true } }; |
| 322 | }); |
| 323 | |
| 324 | // ── drifted — converge the cloud back to the last-deployed props ── |
| 325 | // |
| 326 | // Also attaches the bindings of resources recreated bare above. |
| 327 | const reconcile = Effect.fn("drift.reconcile")(function* ( |
| 328 | pending: PendingRepair & { recreated: boolean }, |
| 329 | ) { |
| 330 | const { fqn, old, provider, live, report, commit, scopedSession, result, recreated } = |
| 331 | pending; |
| 332 | const { logicalId, instanceId, resourceType } = old; |
| 333 | if (!recreated) yield* report("updating"); |
| 334 | const attr = yield* provider |
| 335 | .reconcile({ |
| 336 | id: logicalId, |
| 337 | fqn, |
| 338 | instanceId, |
| 339 | news: old.props as never, |
| 340 | olds: old.props as never, |
| 341 | // Hand reconcile the OBSERVED attributes, not the stale persisted |
| 342 | // snapshot, so its observed-vs-desired diffing works from reality. |
| 343 | output: live as never, |
| 344 | session: scopedSession, |
| 345 | bindings: old.bindings as never, |
| 346 | }) |
| 347 | .pipe( |
| 348 | instrumentLifecycle( |
| 349 | recreated ? "create" : "update", |
| 350 | fqn, |
| 351 | resourceType, |
| 352 | logicalId, |
| 353 | instanceId, |
| 354 | ), |
| 355 | ); |
| 356 | yield* commit(recreated ? "created" : "updated", attr, old.bindings); |
| 357 | yield* report(recreated ? "created" : "updated"); |
| 358 | return result({ action: recreated ? "recreated" : "repaired", attr }); |
| 359 | }); |
| 360 | |
| 361 | const listed = yield* state.list({ stack: stackName, stage }); |
| 362 | const fqns = |
| 363 | options.only === undefined ? listed : listed.filter((fqn) => options.only!.includes(fqn)); |
| 364 | yield* emit({ type: "plan.phase", phase: "computing-plan" }); |
| 365 | |
| 366 | // Per-resource observation progress: each row is reported through the |
| 367 | // events as its cloud read lands (drift checks are the |
| 368 | // slowest planning path). Failed or action rows advance the count |
| 369 | // without an event, so progress stays monotonic. |
| 370 | const observedCount = yield* Ref.make(0); |
| 371 | const resourceObserved = (observed: DriftResourceResult | PendingRepair | undefined) => |
| 372 | Ref.updateAndGet(observedCount, (count) => count + 1).pipe( |
| 373 | Effect.flatMap((completed) => |
| 374 | observed === undefined |
| 375 | ? Effect.void |
| 376 | : emit({ |
| 377 | type: "plan.resource.completed", |
| 378 | fqn: observed.fqn, |
| 379 | logicalId: isPendingRepair(observed) ? observed.old.logicalId : observed.logicalId, |
| 380 | resourceType: isPendingRepair(observed) |
| 381 | ? observed.old.resourceType |
| 382 | : observed.resourceType, |
| 383 | // Drift observation compares attributes, not binding rows. |
| 384 | bindings: [], |
| 385 | action: isPendingRepair(observed) |
| 386 | ? observed.live === undefined |
| 387 | ? "create" |
| 388 | : "update" |
| 389 | : observed.action === "drifted" |
| 390 | ? "update" |
| 391 | : observed.action === "missing" |
| 392 | ? "create" |
| 393 | : "noop", |
| 394 | completed, |
| 395 | total: fqns.length, |
| 396 | }), |
| 397 | ), |
| 398 | ); |
| 399 | |
| 400 | // Drift every resource even if some fail, then surface all failures as |
| 401 | // one combined cause (mirrors Apply's failure aggregation). |
| 402 | const failures: Cause.Cause<unknown>[] = []; |
| 403 | const recordFailure = (fqn: string) => (cause: Cause.Cause<unknown>) => |
| 404 | Effect.gen(function* () { |
| 405 | failures.push(cause); |
| 406 | const persisted = yield* state |
| 407 | .get({ stack: stackName, stage, fqn }) |
| 408 | .pipe(Effect.orElseSucceed(() => undefined)); |
| 409 | if (persisted && !isActionState(persisted)) { |
| 410 | yield* reportEvent({ |
| 411 | type: "apply.resource.status", |
| 412 | fqn, |
| 413 | id: persisted.logicalId, |
| 414 | resourceType: persisted.resourceType, |
| 415 | status: "fail", |
| 416 | }); |
| 417 | } |
| 418 | return undefined; |
| 419 | }); |
| 420 | |
| 421 | const observed = yield* Effect.forEach( |
| 422 | fqns, |
| 423 | (fqn) => |
| 424 | driftResource(fqn).pipe( |
| 425 | Effect.catchCause(recordFailure(fqn)), |
| 426 | Effect.tap(resourceObserved), |
| 427 | ), |
| 428 | { concurrency: "unbounded" }, |
| 429 | ); |
| 430 | |
| 431 | const pending = observed.filter(isPendingRepair); |
| 432 | |
| 433 | // Upstreams per the persisted `downstream` edges, among the resources |
| 434 | // being repaired (an unchanged or skipped upstream never blocks). Edges |
| 435 | // inside a cycle — only possible through merged historical edges — are |
| 436 | // dropped. |
| 437 | const upstream: Record<string, string[]> = Object.fromEntries( |
| 438 | pending.map((node) => [node.fqn, [] as string[]]), |
| 439 | ); |
| 440 | for (const node of pending) { |
| 441 | for (const down of node.old.downstream ?? []) { |
| 442 | if (down !== node.fqn) upstream[down]?.push(node.fqn); |
| 443 | } |
| 444 | } |
| 445 | const cyclic = findCycleMembers(upstream); |
| 446 | const upstreamOf = (fqn: string) => |
| 447 | upstream[fqn]!.filter((up) => !(cyclic.has(up) && cyclic.has(fqn))); |
| 448 | |
| 449 | // Resources whose repair failed, or was skipped because an upstream's |
| 450 | // did. Like Apply, a dependent never runs against a failed upstream. |
| 451 | const failed = new Set<string>(); |
| 452 | |
| 453 | // Run `run` over `nodes`, each node after its upstreams in `nodes` have |
| 454 | // settled. Upstreams outside `nodes` settled in an earlier phase. |
| 455 | const inDependencyOrder = Effect.fn(function* <N extends PendingRepair, A>( |
| 456 | nodes: ReadonlyArray<N>, |
| 457 | run: (node: N) => Effect.Effect<A, unknown>, |
| 458 | ) { |
| 459 | const settled = new Map<string, Deferred.Deferred<void>>(); |
| 460 | for (const node of nodes) settled.set(node.fqn, yield* Deferred.make<void>()); |
| 461 | return yield* Effect.forEach( |
| 462 | nodes, |
| 463 | (node) => |
| 464 | Effect.gen(function* () { |
| 465 | const ups = upstreamOf(node.fqn); |
| 466 | yield* Effect.all( |
| 467 | ups.flatMap((up) => { |
| 468 | const deferred = settled.get(up); |
| 469 | return deferred ? [Deferred.await(deferred)] : []; |
| 470 | }), |
| 471 | ); |
| 472 | const blocked = ups.filter((up) => failed.has(up)); |
| 473 | if (blocked.length > 0) { |
| 474 | failed.add(node.fqn); |
| 475 | yield* node.scopedSession.note( |
| 476 | `not repaired: upstream ${blocked.map((up) => `'${up}'`).join(", ")} failed`, |
| 477 | ); |
| 478 | yield* node.report("skipped"); |
| 479 | return undefined; |
| 480 | } |
| 481 | return yield* run(node).pipe( |
| 482 | Effect.catchCause((cause) => |
| 483 | Effect.sync(() => failed.add(node.fqn)).pipe( |
| 484 | Effect.andThen(recordFailure(node.fqn)(cause)), |
| 485 | ), |
| 486 | ), |
| 487 | ); |
| 488 | }).pipe(Effect.ensuring(Deferred.succeed(settled.get(node.fqn)!, undefined))), |
| 489 | { concurrency: "unbounded" }, |
| 490 | ); |
| 491 | }); |
| 492 | |
| 493 | const recreated = yield* inDependencyOrder( |
| 494 | pending.filter((node) => node.live === undefined), |
| 495 | recreate, |
| 496 | ); |
| 497 | const rebind = recreated.flatMap((node) => (node?.rebind ? [node.rebind] : [])); |
| 498 | const repaired = yield* inDependencyOrder( |
| 499 | [ |
| 500 | ...pending |
| 501 | .filter((node) => node.live !== undefined) |
| 502 | .map((node) => ({ ...node, recreated: false })), |
| 503 | ...rebind, |
| 504 | ], |
| 505 | reconcile, |
| 506 | ); |
| 507 | |
| 508 | const results = [ |
| 509 | ...observed.filter((r) => !isPendingRepair(r)), |
| 510 | ...recreated.map((r) => r?.done), |
| 511 | ...repaired, |
| 512 | ].filter((r): r is DriftResourceResult => r !== undefined); |
| 513 | |
| 514 | if (failures.length > 0) { |
| 515 | return yield* Effect.failCause(failures.reduce(Cause.combine) as Cause.Cause<never>); |
| 516 | } |
| 517 | |
| 518 | return { |
| 519 | resources: Object.fromEntries( |
| 520 | results.filter((r): r is DriftResourceResult => r !== undefined).map((r) => [r.fqn, r]), |
| 521 | ), |
| 522 | } satisfies DriftResult; |
| 523 | }).pipe( |
| 524 | ensureArtifactStore, |
| 525 | Effect.withSpan("drift", { |
| 526 | attributes: { |
| 527 | "alchemy.stack": stack.name, |
| 528 | "alchemy.stage": stack.stage, |
| 529 | "alchemy.dry_run": !!options.dryRun, |
| 530 | }, |
| 531 | }), |
| 532 | ); |
| 533 | |
| 534 | /** Detect drift without reconciling resources or updating state. */ |
| 535 | export const detect = (stack: { name: string; stage: string }) => runDrift(stack, { dryRun: true }); |
| 536 | |
| 537 | /** |
| 538 | * Reconcile resources back to their last-deployed desired state. With |
| 539 | * `only`, just those resources are re-checked and repaired. |
| 540 | */ |
| 541 | export const repair = ( |
| 542 | stack: { name: string; stage: string }, |
| 543 | options: { readonly only?: ReadonlyArray<string> } = {}, |
| 544 | ) => runDrift(stack, { dryRun: false, only: options.only }); |
| 545 | |
| 546 | /** |
| 547 | * Same shape as Apply's lifecycle instrumentation: scoped artifacts + |
| 548 | * resource context, the resource op metrics, and a `provider.<op>` span. |
| 549 | */ |
| 550 | const instrumentLifecycle = |
| 551 | (op: ResourceOp, fqn: string, resourceType: string, logicalId: string, instanceId: string) => |
| 552 | <A, E, R>( |
| 553 | effect: Effect.Effect<A, E, R>, |
| 554 | ): Effect.Effect<A, E | DriftResourceError, Exclude<R, ResourceContext | Artifacts>> => |
| 555 | // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- generic Exclude on R can't be proven statically |
| 556 | Effect.serviceOption(ArtifactStore).pipe( |
| 557 | Effect.map(Option.getOrElse(createArtifactStore)), |
| 558 | Effect.flatMap((store) => |
| 559 | effect.pipe( |
| 560 | Effect.provide([ |
| 561 | Layer.succeed(Artifacts, makeScopedArtifacts(store, fqn)), |
| 562 | Layer.succeed(ResourceContext, { logicalId, fqn, instanceId, type: resourceType }), |
| 563 | ]), |
| 564 | Effect.catchCauseIf( |
| 565 | (cause: Cause.Cause<E>) => !Cause.hasInterruptsOnly(cause), |
| 566 | (cause) => |
| 567 | Effect.fail( |
| 568 | new DriftResourceError({ |
| 569 | message: `Resource '${fqn}' (${resourceType}) failed during ${op}`, |
| 570 | fqn, |
| 571 | logicalId, |
| 572 | resourceType, |
| 573 | operation: op, |
| 574 | cause: Cause.squash(cause), |
| 575 | }), |
| 576 | ), |
| 577 | ), |
| 578 | ), |
| 579 | ), |
| 580 | recordResourceOp(resourceType, op), |
| 581 | Effect.withSpan(`provider.${op}`, { |
| 582 | attributes: { |
| 583 | "alchemy.resource.fqn": fqn, |
| 584 | "alchemy.resource.type": resourceType, |
| 585 | "alchemy.resource.logical_id": logicalId, |
| 586 | "alchemy.resource.instance_id": instanceId, |
| 587 | "alchemy.resource.op": op, |
| 588 | }, |
| 589 | }), |
| 590 | ) as Effect.Effect<A, E | DriftResourceError, Exclude<R, ResourceContext | Artifacts>>; |
| 591 | |
| 592 | export interface DriftPlan { |
| 593 | /** Per-resource detection outcome (a dry-run {@link DriftResult}). */ |
| 594 | result: DriftResult; |
| 595 | /** |
| 596 | * The detection outcome projected onto the engine's {@link Plan} shape so |
| 597 | * the CLI renders a drift exactly like a deploy plan (ink TUI when |
| 598 | * interactive, plain logging otherwise): `drifted` → `update`, `missing` → |
| 599 | * `create`, `unchanged`/`skipped` → `noop`. |
| 600 | */ |
| 601 | plan: Plan; |
| 602 | } |
| 603 | |
| 604 | /** |
| 605 | * Run the drift-detection pass and project the |
| 606 | * outcome onto a {@link Plan} for display/approval. The plan is a read-only |
| 607 | * view — {@link repair} re-observes the cloud rather than trusting the |
| 608 | * detection snapshot. |
| 609 | */ |
| 610 | export const plan = (stack: { |
| 611 | name: string; |
| 612 | stage: string; |
| 613 | }): Effect.Effect<DriftPlan, any, State> => |
| 614 | Effect.gen(function* () { |
| 615 | const result = yield* detect(stack); |
| 616 | const state = yield* yield* State; |
| 617 | |
| 618 | const resources: Plan["resources"] = {}; |
| 619 | for (const [fqn, r] of Object.entries(result.resources)) { |
| 620 | const persisted = yield* state.get({ |
| 621 | stack: stack.name, |
| 622 | stage: stack.stage, |
| 623 | fqn, |
| 624 | }); |
| 625 | if (!persisted || isActionState(persisted)) continue; |
| 626 | // Repair the row with the provider mode that created it (drift never |
| 627 | // switches modes — a local ⇄ live switch is a plan-time replacement). |
| 628 | const provider = yield* findProviderByType(persisted.resourceType, stampedMode(persisted)); |
| 629 | const action = |
| 630 | r.action === "drifted" |
| 631 | ? ("update" as const) |
| 632 | : r.action === "missing" |
| 633 | ? ("create" as const) |
| 634 | : ("noop" as const); |
| 635 | resources[fqn] = { |
| 636 | action, |
| 637 | props: persisted.props, |
| 638 | drift: |
| 639 | r.action === "drifted" || r.action === "missing" |
| 640 | ? { |
| 641 | expected: persisted.attr, |
| 642 | actual: r.attr, |
| 643 | missing: r.action === "missing", |
| 644 | } |
| 645 | : undefined, |
| 646 | state: persisted, |
| 647 | provider, |
| 648 | mode: persisted.providerMode, |
| 649 | // Synthetic ResourceLike reconstructed from persisted state, the |
| 650 | // same way Plan.make builds its deletion nodes. |
| 651 | resource: { |
| 652 | Namespace: persisted.namespace, |
| 653 | FQN: fqn, |
| 654 | LogicalId: persisted.logicalId, |
| 655 | Type: persisted.resourceType, |
| 656 | Attributes: persisted.attr, |
| 657 | Props: persisted.props, |
| 658 | Binding: undefined!, |
| 659 | Provider: Provider(persisted.resourceType), |
| 660 | RemovalPolicy: persisted.removalPolicy, |
| 661 | Adopt: undefined, |
| 662 | RequiresImplementation: undefined, |
| 663 | FormerFqns: undefined, |
| 664 | Mode: persisted.providerMode, |
| 665 | RuntimeContext: undefined!, |
| 666 | Providers: undefined, |
| 667 | } as ResourceLike, |
| 668 | // Drift repairs from the persisted bindings verbatim — surface them |
| 669 | // as noop rows so the renderer shows the binding topology without |
| 670 | // implying binding changes. |
| 671 | bindings: (persisted.bindings ?? []).map((binding) => ({ |
| 672 | sid: binding.sid, |
| 673 | action: "noop" as const, |
| 674 | data: binding.data, |
| 675 | })), |
| 676 | downstream: persisted.downstream ?? [], |
| 677 | } as Apply; |
| 678 | } |
| 679 | |
| 680 | return { |
| 681 | result, |
| 682 | plan: { |
| 683 | resources, |
| 684 | actions: {}, |
| 685 | deletions: {}, |
| 686 | actionDeletions: {}, |
| 687 | output: undefined, |
| 688 | cycleMembers: new Set<string>(), |
| 689 | }, |
| 690 | } satisfies DriftPlan; |
| 691 | }).pipe( |
| 692 | Effect.withSpan("drift.plan", { |
| 693 | attributes: { |
| 694 | "alchemy.stack": stack.name, |
| 695 | "alchemy.stage": stack.stage, |
| 696 | }, |
| 697 | }), |
| 698 | ); |