@cdkd/cli 0.334.0 → 0.334.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{asg-provider-1ln_ANde.js → asg-provider-DFD40oJv.js} +2 -2
- package/dist/{asg-provider-1ln_ANde.js.map → asg-provider-DFD40oJv.js.map} +1 -1
- package/dist/cli.js +13 -7
- package/dist/cli.js.map +1 -1
- package/dist/{db-instance-modify-retry-BCMjrw0H.js → db-instance-modify-retry-Dpj04RL2.js} +2 -2
- package/dist/{db-instance-modify-retry-BCMjrw0H.js.map → db-instance-modify-retry-Dpj04RL2.js.map} +1 -1
- package/dist/{deploy-engine-DIK2cLmn.js → deploy-engine-BO_w6XzZ.js} +2852 -2459
- package/dist/deploy-engine-BO_w6XzZ.js.map +1 -0
- package/dist/{iam-role-provider-I4_WshA4.js → iam-role-provider-Bfiu3VQU.js} +2 -2
- package/dist/{iam-role-provider-I4_WshA4.js.map → iam-role-provider-Bfiu3VQU.js.map} +1 -1
- package/dist/index.d.ts +6 -42
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/{neptune-provider-D4YDyGKt.js → neptune-provider-hIgTrVEI.js} +3 -3
- package/dist/{neptune-provider-D4YDyGKt.js.map → neptune-provider-hIgTrVEI.js.map} +1 -1
- package/dist/{program-Dipucz4X.js → program-Ctf5zWf1.js} +874 -627
- package/dist/program-Ctf5zWf1.js.map +1 -0
- package/dist/{provider-classes-BBtEm3us.js → provider-classes-IuPgHvuR.js} +8 -8
- package/dist/{provider-classes-BBtEm3us.js.map → provider-classes-IuPgHvuR.js.map} +1 -1
- package/dist/{rds-provider-BOcleXHf.js → rds-provider-mY4c2UdN.js} +3 -3
- package/dist/{rds-provider-BOcleXHf.js.map → rds-provider-mY4c2UdN.js.map} +1 -1
- package/dist/{version-CXL6Ontw.js → version-FHU_Fu1I.js} +2 -2
- package/dist/{version-CXL6Ontw.js.map → version-FHU_Fu1I.js.map} +1 -1
- package/package.json +2 -2
- package/dist/deploy-engine-DIK2cLmn.js.map +0 -1
- package/dist/program-Dipucz4X.js.map +0 -1
|
@@ -2,8 +2,9 @@ import { a as runWithStackAwsClients, i as resetAwsClients, l as s3ClientDefault
|
|
|
2
2
|
import { $ as safeMsg, B as SAFE_MSG_ALTERED_CHAR, C as PATTERN_B_RESOURCE_TYPES, F as isNameGeneration, G as cutMarker, H as STACK_REF_MAX_CODE_POINTS, J as displaySafe, K as displayAwsMessage, L as withSkipPrefix, Q as plainIdentOr, R as withStackScope, S as PATTERN_B_NAME_PROPERTIES, T as generateResourceName, U as UNRENDERABLE, V as SECRET_REF_MAX_CODE_POINTS, W as asIsMessage, X as isPasteableIdent, Y as displayStackName, _ as explicitNamePropertyFor, a as safeStringify, c as isStdoutReservedForPayload, d as runStackBuffered, et as stringifyJsonPayload, l as reserveStdoutForPayload, m as getLiveRenderer, n as describeAwsFailure, nt as truncateCodePoints, q as displayIdent, s as getLogger, tt as terminalSafe, w as derivesPatternBName, x as PATTERN_B_NAME_OPTIONS } from "./aws-failure-text-CoS1huLy.js";
|
|
3
3
|
import { $n as markNonRetryable, $t as formatLockExpiry, Ar as shellQuote, Bn as stripForDisplay, Dn as StackHasActiveImportsError, Dr as plainOrDescribed, En as ResourceUpdateNotSupportedError, Et as logicalIdShown, H as assertRegionMatch, Jn as isTransientServerError, M as VALUE_NOT_SHOWN, Mr as setPasteableRunFlags, Nr as setPasteableVerbFlags, On as StackTerminationProtectionError, Or as quotedOrDescribed, Ot as resourceTypeShown, Qn as isThrottlingError, Qt as forceQuitRecoveryClause, Rn as escapeRegExp, Sr as commandHole, Tn as PartialFailureError, Tr as pasteableCommand, U as isMarkedNotGone, V as RESOURCE_NOT_FOUND, Wn as isAmbiguousOutcomeError, Xt as buildForceUnlockCommand, Yn as retryClassificationText, Yt as UNREPRODUCIBLE_LOCK_CLAUSE, Zn as isMarkedNonRetryable, Zt as buildLockContentionMessage, _n as formatError, _t as beginCommandInterruptScope, an as DEFAULT_STATE_PREFIX, ar as MalformedProducerRecordRefusalError, bn as LocalStartServiceError, br as SHELL_ACTIVE_WHY, bt as isInterruptedWaitError, cn as producerCoordinateKey, cr as CdkdError, dn as withPasteableAwsProfile, dr as LocalInvokeBuildError$1, en as formatLockOperation, fn as ambientClientDefaults, gn as normalizeAwsError, gr as SynthesisError, hn as credentialFingerprint, hr as StateError, in as CUSTOM_RESOURCE_RESPONSE_PREFIX, ir as IntrinsicResolutionRefusalError, it as runDeleteAttempt, jr as withheldTargetClause, kr as shellBoundedDisplay, ln as producerRecordKey, lr as DeployCancelledError, m as RESOLVED_PREVIOUS_PRINCIPAL_KEYS, mn as clientDefaultsFor, mr as ResourceTimeoutError, nr as CrossAccountSecretRefusalError, on as injectiveKey, or as AccountIdUnavailableError, p as IAM_PRINCIPAL_NAME, pn as ambientCredentialConfig, pr as ProvisioningError, qn as isRetryableTransientError, rr as DynamicReferenceRegionAmbiguousError, tn as formatLockOwner, un as setPasteableAwsProfile, ut as isAwsCliLiteral, vr as TIMEOUT_FLAG_RESOURCE_TYPE, vt as endCommandInterruptScope, wn as NestedStackChildDirectDestroyError, wr as isInertUnquoted, y as readRecordedPrincipals, yn as withErrorHandling, yt as interruptWatchListenerCount, z as remedyLogicalId, zn as stripControlChars } from "./update-removal-C_x1-FM4.js";
|
|
4
4
|
import { a as setAssumedRoleCredentials, d as formatAuthority, i as getPreAssumeEnvCredentials, n as awsClientDefaults, r as getAssumedRoleCredentials, u as runInStackAwsScope } from "./aws-client-defaults-BLXFsfMa.js";
|
|
5
|
-
import { $a as classifyRecordedSecretRegion, $l as stackInstanceIdOf, $n as nameGenerationCarriedFrom, $r as addSuperseded, $s as malformedOutputsWarning, $t as deleteJournaledOrphans, $u as runDockerForeground, Ad as AssemblyReader, Ai as isFinalSnapshotError, Al as recordPhysicalNameCopy, An as equalModuloMarkedMask, Ao as unsettledItemsField, Ar as formatDestructiveChange, As as refuseMalformedResourceEntriesForImport, At as isSecretBearingReferenceString, Au as isCrossRegionRedirect, Ba as resolveDynamicReferences, Bc as maskAtCoordinates, Bd as ownValue, Bi as ledgerForStack, Bl as wholeStringLeavesOf, Bn as replacementNeverSwapped, Bo as renderStatefulReason, Br as proposeRenames, Bs as refuseMalformedResourcePropertiesForOrphan, Bt as NESTED_PENDING_PARENT_REASON, Bu as describeDockerExecFailure, Ca as deleteLeftInPlace, Cc as findHandledUnwrittenCreateOnly, Cd as CUSTOM_RESOURCE_RESPONSE_OBJECT_DESCRIPTION, Ci as secretNamedRecordNeedles, Cl as pathCrossesDottedKey, Cn as replayFailedOperations, Co as carriesFetchableDynamicReference, Cr as isExportAliasCollision, Cs as malformedLocalResourcesWarning, Ct as conditionInputsFrom, Cu as createAssetRedirectResolver, Dc as NO_CC_HANDLERS_REASON, Dd as canonicalizeRegion, Di as PRE_DELETE_SNAPSHOT_TYPES, Dn as settleUnsettledPrevious, Do as withSharedDrainBudget, Dr as maskingRetryLogger, Ds as refuseMalformedResourceEntries, Du as ensureAssetStorage, Ed as PARTITION_TABLE, Ei as ATOMIC_FINAL_SNAPSHOT_TYPES, El as inheritNestedStackParameterAssociations, En as recordAfterRollbackUpdate, Eo as keepsSecretReferenceToken, Er as DEFAULT_RESOURCE_WARN_AFTER_MS, Es as refuseMalformedResourceAttributesForOrphan, Eu as AssetModeResolver, Fa as DiffCalculator, Fd as utf8ByteLength, Fl as recordMaskOnlyValue, Fn as isReplacementOrphan, Fo as findReplacedReadersOfRecreateTargets, Fr as withMovedTo, Fs as malformedDriftResourcePropertiesWarning, Ft as planOrphanAdoption, Fu as validateContainerRepoName, Ga as assertSendableRoleArn, Gc as noEchoLeavesOf, Gd as resolveAssemblyPath, Gi as DeploymentEventsStore, Gl as S3StateBackend, Gr as withStackRecords, Gs as malformedOrphansWarning, Gt as nestedChildStackName$1, Gu as dockerSpawnEnvWithSensitive, Ha as refuseUnreadableCdkCrossAccountRefs, Hc as maskWholeValue, Hd as describeFileReadFailure, Hi as withCreateTokenLedger, Hl as isSingleDynamicReferenceToken, Hn as seedsDeleteFirstGuard, Hs as UNREADABLE_ORPHANS_CONTAINER_ROW, Ht as displacedPhysicalIdShown, Hu as redactedCause, Ia as IntrinsicFunctionResolver, Ic as DagBuilder, Id as defineOwnKey, Il as recordMaskOnlyValuesIn, In as planFailedOps, Io as shownType, Ir as isPairableType, Is as malformedResourcePropertiesWarning, It as pendingRequestCount, Iu as BOOTSTRAP_MARKER_PREFIX, Ja as sendableAssumeRoleCommand, Jc as readbackPathFor, Jl as CrossPrefixScanCache, Jr as cyan, Js as repairMalformedOrphansForReadOnly, Jt as revertedNestedRowIds, Ju as warnFinchArgvExposure, Ka as explicitRoleArnOrThrow, Kc as noEchoOutputsComparison, Kd as injectAwsRegion, Ki as extractDeploymentEventError, Kl as rebuildClientForBucketRegion, Kn as inheritProducerRegions, Ko as coerceCfnBoolean, Ks as refuseMalformedOrphans, Kt as recordDisplacedSkips, Ku as finchSecretArgvRefusal, La as isAlwaysLiveAttribute, Lc as TemplateParser, Ld as hasOwnKey, Li as secretSegmentsOfState, Ll as recordNoEchoAttributeValues, Ln as planRollback, Lo as MULTI_REGION_RECREATE_BLOCKED_TYPES, Lr as looselyEqual, Ls as refuseMalformedResourcePropertiesForDestroy, Lt as resolvePendingCloudControlRequests, Lu as buildDockerImage, Md as processStackMessages, Mi as unsupportedFinalSnapshotError, Ml as splitGetAttStringForm, Mn as undeclaredEmptyObservedKeys, Mo as unsettledPropertiesOf, Mr as hintSidesOf, Ms as refuseMalformedResourceEntriesForOrphan, Mt as mergeNoChangeOutputs, Mu as parseBootstrapMarker, Nd as describeJsonParseFailure, Ni as createPreDeleteFinalSnapshot, Nl as carriesSecretMask, Nn as demoteSupersededOrphans, No as withUnsettledProperties, Nr as movedToHint, Ns as repairMalformedResourceEntriesForReadOnly, Nt as makeCanonicalizePropertiesFn, Nu as readBootstrapMarkerBody, Oc as hasNoCloudControlHandlers, Od as derivePartitionAndUrlSuffix, Oi as ccRoutedFinalSnapshotError, Ol as physicalNameCopiesOf, On as withUnprovenUnsettled, Oo as INTRINSIC_KEYS, Or as constructPathOf$1, Os as refuseMalformedResourceEntriesForDeploy, Ot as withResourceDeadline, Ou as buildDenyExternalAccessPolicy, Pa as isWaitAbandonedError, Pd as parseFailureDebugDetail, Pi as buildFinalSnapshotIdentifier, Pl as provenPublicValue, Pn as isJournaledOrphan, Po as withoutUnsettledProperties, Pr as rollbackOrphanIds, Ps as unreadableResourceEntries, Pt as makeSiblingClaimReader, Pu as validateAssetBucketName, Qa as envCredentialsAreAssumedRole, Qc as liveMatchesUnresolvedTokenFrame, Ql as isNotImplemented, Qn as updatePartialReason, Qr as yellow, Qs as malformedOutputsRefusalMessage, Qt as withNestedStackContext, Qu as getDockerCmd, Ra as poisonRenderedSpellingsCollidingIn, Rc as canonicalCoordinates, Rd as hasPlainPrototype, Ri as withSecretPhysicalIdsMaskedInState, Rl as recordNoEchoParameterFreshValue, Rn as recheckFailedPlan, Ro as isStatefulRecreateTargetForReplace, Rr as mappingPairs, Rs as refuseMalformedResourcePropertiesForDrift, Rt as keptForRetainedRecord, Ru as resolveDockerContextDirectory, S as setResolvedResourceTimeouts, Sa as deleteIndeterminateGuards, Sc as findActionableSdkUnwired, Sd as uploadCfnTemplate, Sl as isUncertifiedBaselineMaskPosition, Sn as refusePendingMovesOut, So as isImpossibleEmptyStoredAttribute, Sr as collectPublishedOutputNames, Ss as malformedLocalResourceEntriesWarning, St as conditionFingerprint, Su as buildAssetRedirectMap, Tc as unwrittenCreateOnlyReplacement, Td as expectedOwnerParam, Ti as storedSecretNameNeedles, Tl as identityKeyFor, Tn as removeProtectionTypeList, To as carriesDynamicReference, Tr as DEFAULT_RESOURCE_TIMEOUT_MS, Ts as malformedScrubResourceEntriesRefusalMessage, Tt as readRecordedConditionVerdicts, Tu as rewriteTemplateAssetReferences, Ua as applyRoleArnIfSet, Uc as maskedLeafCoordinatesOf, Ud as displayAssemblyPath, Ul as LockManager, Un as orphanNeedsIdentity, Ur as destroyStackRecordsView, Us as hasReadableOrphans, Ut as dropSettledNestedJournals, Uu as redactedDockerCause, Va as producerLookupOver, Vc as maskReadbackAtCoordinates, Vd as absoluteAssemblyPathEscape, Vl as WHOLE_DYNAMIC_REFERENCE_PATTERN, Vn as resolveReplacementOldType, Vs as repairMalformedResourcePropertiesForReadOnly, Vt as displacedOpClause, Vu as describeDockerFailure, Wa as assertFlagRoleArn, Wc as noEchoCoordinatesOf, Wd as renderAssemblyPathEscape, Wi as DeploymentEventsReader, Wl as isLockInfoExpired, Wn as findNestedStackTypeChanges, Ws as malformedOrphansRefusalMessage, Wu as redactDockerArgvValues, Xa as applyCallerIdentityCredentials, Xc as recordedNoEchoValuesOf, Xl as crossPrefixDeniedWarning, Xr as green, Xs as malformedExportSourceWarning, Xt as collectNestedChildUnaddressed, Xu as isMalformedEnvKey, Ya as AWS_CREDENTIAL_ENV_KEYS, Yc as readsNoEchoSource, Yd as resolveBucketRegion, Yl as applyCrossPrefixScan, Yr as gray, Ys as malformedExportNamesWarning, Yt as withNestedRevertRun, Yu as isDockerClientEnvKey, Za as callerEnvCredentials, Zc as valueAtCoordinate, Zl as isAccessDenied, Zn as updatePartialMessage, Zr as red, Zs as malformedLocalOutputsWarning, Zt as getCurrentNestedStackContext, Zu as formatDockerLoginError, _c as STATE_RESOURCES_MALFORMED, _d as ssmResolvedValueType, _i as maskEventTextWithBoundBags, _l as scrubResourceRecord, _n as sameMove, _o as keepHeldTokenProvenance, _r as exportNameNoEchoParameters, _s as refuseMalformedOrphansForOrphan, _t as findNestedTemplateTreeDefect, _u as timePhase, a as isProtectionValueActive, aa as ProviderRegistry, ac as refuseDivergentRecordRegionForDestroy, ad as getDefaultStateBucketName, ai as supersededHeldByOtherTypeWarning, al as hasMaskableValues, an as makeForeignHolderScan, ar as withNameGenerationReached, as as withRetry, au as hasReadableExportSet, ba as RollbackInlinePolicyWriters, bc as hasReadableOutputs, bd as MIGRATE_TMP_PREFIX, bi as secretNamePrintingBag, bl as DYNAMIC_REFERENCE_TOKEN_SCAN, bn as pendingMovesOutOf, bo as recordedReferenceRegions, br as noEchoParameterValueSeed, bs as unreadableOrphanRecords, bt as renderNestedTemplateTreeDefect, bu as stringifyValue, ca as wouldReturnToSdkProvider, cc as malformedStateRefusalMessage, cd as resolveApp, ci as withoutSuperseded, cl as printingCorpusOf, co as coerceParameterTypedValue, cr as reachableDivergentParameters, cs as declaresNoEcho, cu as importableOutputKeys, da as customResourceResponseExpirationWarning, dc as refuseMalformedResourcesForExport, dd as resolveSkipPrefix, di as noEchoExactEchoLeavesOf, dl as shareLogOnlyValues, do as AWS_NO_VALUE, dr as displayTextOrWithheld, ds as malformedOrphanRecordsRefusalMessage, dt as crossStackOutputProvenanceSource, du as orphansAfterRollback, ed as runDockerStreaming, ei as deleteSupersededEntry, el as redactForState, en as dropFailedCommands, eo as classifyReplaySecretRegion, er as nameGenerationHighWaterOf, eu as withStackInstanceIdWithheld, fa as TemplateNoEchoReresolver, fc as refuseMalformedState, fd as resolveStateBucketWithDefault, fi as noEchoParameterNamesOf, fl as unionOfSecretBags, fn as readRefactorMarker, fo as cfnRefValueFromPhysicalId, fr as exportAliasCollisionScrubWarning, fs as malformedOrphanRecordsWarning, ft as inheritedProvenanceForChildDiff, fu as orphansCarriedFrom, ga as withPrintingSecrets, gc as withheldAccountClause, gd as warnDeprecatedNoPrefixCliFlag, gi as journaledOrphanPrintingBag, gl as maskSecretsInText, gn as refuseRefactorMarker, gr as carriedExportAliasExposure, gs as refuseMalformedOrphanRecordsForDestroy, gt as childTemplateLoader, gu as renderPhaseTimings, hc as accountArgs, hd as stateBucketExistenceConfirmed, hi as completedReplayEntries, hl as maskSecretsInError, hn as refactorMarkerRefusalMessage, ho as refStateLookupFromResource, hr as secretSafeKeyDisplay, hs as refuseMalformedOrphanRecords, ht as serviceTokenBlockingReason, hu as PhaseClock, i as PROTECTION_PROPERTY_BY_TYPE, ia as CC_BROKEN_REASON, ic as STATE_REGION_DIVERGED, id as synthesisStatusMessage, ii as supersededAfterRollback, il as createUnionSecretMasker, in as loadJournaledOrphans, ir as retiredNameGenerationsLeaving, is as describeTypeWithThrottleRetry, iu as exportNamesCarriedFrom, jd as StageLoadError, ji as refusesFinalSnapshot, jl as recordNestedStackParameterExpressions, jn as equalModuloMask, jo as unsettledItemsOf, jr as findRefactorHints, js as refuseMalformedResourceEntriesForImportSave, jt as keptWholeReasonText, ju as getBootstrapMarkerKey, kd as refuseFailedLookups, ki as effectiveDeletionPolicy, kn as calculateResourceDrift, kr as findDestructiveChanges, ks as refuseMalformedResourceEntriesForDestroy, kt as diffSecurity, ku as assertAssetBucketRegion, la as CUSTOM_RESOURCE_RESPONSE_LIFECYCLE_RULE_ID, lc as refuseMalformedResourcesForDeploy, ld as resolveAutoAssetStorage, li as noEchoAttributeNamesOf, ll as recordLogOnlyParameterValue, lo as isUnboundTemplateParameter, lr as resourcesNamingDeclaredParameter, ls as deployRefusesOrphanRowsReason, lt as IMPLICIT_DELETE_DEPENDENCIES, lu as importableOutputs, ma as isCustomResourceType$1, mc as JSON_LISTING_HOLE_VALUE, md as resolveUseCdkBootstrapAssets, mi as createReadOnlyAttributeHealerFactory, ml as errorCauseChain, mn as refactorMarkerMovesOf, mo as lacksRecordedTableArn, mr as secretBearingStateKeyWarning, ms as previewableOrphanRecords, mt as findServiceTokenRefusals, mu as stackInstanceIdCarriedFrom, n as recordedProtectionEvidence, nc as refuseMalformedOutputsForDestroy, nd as getDockerImageBySourceHash, ni as isSupersededResourceRecord, nn as isHandledOrphan, no as regionLessSecretName, nr as retiredAfterRollback, ns as prefetchCreateOnlyPropertyPaths, nu as acceptedCreateOnlyDropsOf, o as perType, oa as ccBrokenReason, oc as malformedRenderedContainersWarning, od as getLegacyStateBucketName, oi as supersededHolderOf, ol as literalSplitDelimitersOf, on as sameJournaledOrphans, or as computeParameterTaint, os as parameterInputsFor, ou as hasReasonlessBaselineRefusal, pa as readsNoEchoDeleteValues, pc as repairMalformedResourcesForReadOnly, pd as resolveStateBucketWithDefaultAndSource, pi as withAttemptedItemsMasked, pl as createSecretMasker, pn as readRefactorMarkerOnce, po as isStalePlaceholderArnAttribute, pr as secretBearing, ps as malformedOrphanRowsKeptWarning, pt as deferredServiceTokenWarning, pu as shouldRetainResource, qa as isIamRoleArn, qd as injectedAwsRegionValue, ql as CrossPrefixReadError, qr as bold, qs as refuseMalformedOrphansForDestroy, qu as partitionSensitiveEnv, r as recordedProtectionNote, rc as repairMalformedOutputsForReadOnly, rd as Synthesizer, ri as removeSuperseded, rl as carryLogOnlyValues, rn as journaledOrphanLines, rr as retiredNameGenerationsAfter, rs as templateResourceTypes, ru as describeRegionValueKind, s as readProtection, sa as isCustomResource, sc as malformedResourcesWarning, sd as loadCdkJson, si as supersededResourcesOf, sl as logOnlyValueCount, sn as formatResourceLine, sr as namesAnyDeclaredParameter, su as hasUnverifiableParameterRefusal, t as DeployEngine, tc as refuseMalformedOutputs, td as AssetManifestLoader, ti as holdsSupersededResources, tn as dropFailedHint, to as producerRegionsFromState, tr as nameScopeOf, tu as splitImportedOps, ua as applyCustomResourceResponseExpiration, uc as refuseMalformedResourcesForDestroy, ud as resolveCaptureObservedState, ui as noEchoComparisonForTemplate, ul as recordLogOnlyValue, uo as parameterTypeMayLoseSecretIdentity, ur as WITHHELD_NAME_DISPLAY, us as isReadableOrphanRecord, ut as computeImplicitDeleteEdges, uu as isReadableBag, va as CloudControlProvider, vc as UNREADABLE_RESOURCES_MAP_ROW, vd as CFN_TEMPLATE_BODY_LIMIT, vi as namingSecretsWithRecordedNoEcho, vl as withPhysicalNameCopies, vn as updateRefactorMarker, vr as exportNameSecretExposure, vs as repairMalformedOrphanRecordsForReadOnly, vt as isAbsoluteAssetPath, vu as AssetPublisher, wa as deleteSkipReason, wd as decodeListingKey, wi as stateSecretNameNeedles, wl as spelledKeysOf, wn as replayRollback, wo as isNamelessDynamicReferenceError, wr as bindingSkippedOutputs, ws as malformedResourceEntriesWarning, wt as parentSuppliedValues, wu as loadPublishableAssetManifest, xa as UNSPECIFIED_SKIP_REASON, xc as hasReadableResources, xd as findLargeInlineResources, xi as secretNamePrintingBags, xl as dynamicReferenceTokens, xn as pendingMovesRefusalMessage, xo as getAccountInfo, xr as collectDeclaredOutputNames, xs as isReadableResourceEntry, xt as templateIdentity, xu as WorkGraph, ya as slowCcOperationTimeoutMs, yc as displayLogicalId, yd as CFN_TEMPLATE_URL_LIMIT, yi as orphanRecordsPrintingBag, yn as hasPendingMovesOut, yo as recordedOutputReferenceRegions, yr as isWholeDynamicReferenceValue, ys as unpreviewableOrphanRecords, yt as listNestedTemplateRows, yu as isSensitiveAttributeName, zc as isMarkedCoordinate, zd as nullPrototypeRecord, zl as recordProvenPublicExpression, zn as recordUnderIdIsNotOwn, zo as isStatefulRecreateTargetSync, zr as parseMappingFile, zs as refuseMalformedResourcePropertiesForExport, zt as recordRetainedForReadoption, zu as describeDockerCapturedOutput } from "./deploy-engine-DIK2cLmn.js";
|
|
6
|
-
import { t as getCdkdVersion } from "./version-
|
|
5
|
+
import { $a as classifyRecordedSecretRegion, $l as importableOutputKeys, $n as retiredAfterRollback, $r as isSupersededResourceRecord, $s as malformedOutputsWarning, $t as isHandledOrphan, $u as runDockerForeground, Ad as AssemblyReader, Ai as createPreDeleteFinalSnapshot, Al as recordPhysicalNameCopy, An as demoteSupersededOrphans, Ao as unsettledItemsField, Ar as movedToHint, As as refuseMalformedResourceEntriesForImport, At as makeCanonicalizePropertiesFn, Au as isCrossRegionRedirect, Ba as resolveDynamicReferences, Bc as maskAtCoordinates, Bd as ownValue, Bl as wholeStringLeavesOf, Bn as orphanNeedsIdentity, Bo as renderStatefulReason, Br as destroyStackRecordsView, Bs as refuseMalformedResourcePropertiesForOrphan, Bt as dropSettledNestedJournals, Bu as describeDockerExecFailure, Ca as deleteLeftInPlace, Cc as findHandledUnwrittenCreateOnly, Cd as CUSTOM_RESOURCE_RESPONSE_OBJECT_DESCRIPTION, Ci as ATOMIC_FINAL_SNAPSHOT_TYPES, Cl as spelledKeysOf, Cn as recordAfterRollbackUpdate, Co as carriesFetchableDynamicReference, Cr as DEFAULT_RESOURCE_WARN_AFTER_MS, Cs as malformedLocalResourcesWarning, Cu as createAssetRedirectResolver, Dc as NO_CC_HANDLERS_REASON, Dd as canonicalizeRegion, Di as isFinalSnapshotError, Dn as equalModuloMarkedMask, Do as withSharedDrainBudget, Dr as formatDestructiveChange, Ds as refuseMalformedResourceEntries, Dt as isSecretBearingReferenceString, Du as ensureAssetStorage, Ed as PARTITION_TABLE, Ei as effectiveDeletionPolicy, El as inheritNestedStackParameterAssociations, En as calculateResourceDrift, Eo as keepsSecretReferenceToken, Er as findDestructiveChanges, Es as refuseMalformedResourceAttributesForOrphan, Et as diffSecurity, Eu as AssetModeResolver, Fa as DiffCalculator, Fd as utf8ByteLength, Fi as withSecretPhysicalIdsMaskedInState, Fl as recordMaskOnlyValue, Fn as recheckFailedPlan, Fo as findReplacedReadersOfRecreateTargets, Fr as mappingPairs, Fs as malformedDriftResourcePropertiesWarning, Ft as keptForRetainedRecord, Fu as validateContainerRepoName, Ga as assertSendableRoleArn, Gc as noEchoLeavesOf, Gd as resolveAssemblyPath, Gl as S3StateBackend, Gr as cyan, Gs as malformedOrphansWarning, Gt as revertedNestedRowIds, Gu as dockerSpawnEnvWithSensitive, Ha as refuseUnreadableCdkCrossAccountRefs, Hc as maskWholeValue, Hd as describeFileReadFailure, Hi as DeploymentEventsStore, Hl as isSingleDynamicReferenceToken, Hr as withStackRecords, Hs as UNREADABLE_ORPHANS_CONTAINER_ROW, Ht as nestedChildStackName$1, Hu as redactedCause, Ia as IntrinsicFunctionResolver, Ic as DagBuilder, Id as defineOwnKey, Il as recordMaskOnlyValuesIn, In as recordUnderIdIsNotOwn, Io as shownType, Ir as parseMappingFile, Is as malformedResourcePropertiesWarning, It as recordRetainedForReadoption, Iu as BOOTSTRAP_MARKER_PREFIX, Ja as sendableAssumeRoleCommand, Jc as readbackPathFor, Jl as describeRegionValueKind, Jn as updatePartialMessage, Jr as red, Js as repairMalformedOrphansForReadOnly, Jt as getCurrentNestedStackContext, Ju as warnFinchArgvExposure, Ka as explicitRoleArnOrThrow, Kc as noEchoOutputsComparison, Kd as injectAwsRegion, Kl as splitImportedOps, Ko as coerceCfnBoolean, Kr as gray, Ks as refuseMalformedOrphans, Kt as withNestedRevertRun, Ku as finchSecretArgvRefusal, La as isAlwaysLiveAttribute, Lc as TemplateParser, Ld as hasOwnKey, Li as ledgerForStack, Ll as recordNoEchoAttributeValues, Ln as replacementNeverSwapped, Lo as MULTI_REGION_RECREATE_BLOCKED_TYPES, Lr as proposeRenames, Ls as refuseMalformedResourcePropertiesForDestroy, Lt as NESTED_PENDING_PARENT_REASON, Lu as buildDockerImage, Md as processStackMessages, Ml as splitGetAttStringForm, Mn as isReplacementOrphan, Mo as unsettledPropertiesOf, Mr as withMovedTo, Ms as refuseMalformedResourceEntriesForOrphan, Mt as planOrphanAdoption, Mu as parseBootstrapMarker, Nd as describeJsonParseFailure, Nl as carriesSecretMask, Nn as planFailedOps, No as withUnsettledProperties, Nr as isPairableType, Ns as repairMalformedResourceEntriesForReadOnly, Nt as pendingRequestCount, Nu as readBootstrapMarkerBody, Oc as hasNoCloudControlHandlers, Od as derivePartitionAndUrlSuffix, Oi as refusesFinalSnapshot, Ol as physicalNameCopiesOf, On as equalModuloMask, Oo as INTRINSIC_KEYS, Or as findRefactorHints, Os as refuseMalformedResourceEntriesForDeploy, Ot as keptWholeReasonText, Ou as buildDenyExternalAccessPolicy, Pa as isWaitAbandonedError, Pd as parseFailureDebugDetail, Pi as secretSegmentsOfState, Pl as provenPublicValue, Pn as planRollback, Po as withoutUnsettledProperties, Pr as looselyEqual, Ps as unreadableResourceEntries, Pt as resolvePendingCloudControlRequests, Pu as validateAssetBucketName, Qa as envCredentialsAreAssumedRole, Qc as liveMatchesUnresolvedTokenFrame, Ql as hasUnverifiableParameterRefusal, Qn as nameScopeOf, Qr as holdsSupersededResources, Qs as malformedOutputsRefusalMessage, Qt as dropFailedHint, Qu as getDockerCmd, Ra as poisonRenderedSpellingsCollidingIn, Rc as canonicalCoordinates, Rd as hasPlainPrototype, Rl as recordNoEchoParameterFreshValue, Rn as resolveReplacementOldType, Ro as isStatefulRecreateTargetForReplace, Rs as refuseMalformedResourcePropertiesForDrift, Rt as displacedOpClause, Ru as resolveDockerContextDirectory, Sa as deleteIndeterminateGuards, Sc as findActionableSdkUnwired, Sd as uploadCfnTemplate, Si as storedSecretNameNeedles, Sl as isUncertifiedBaselineMaskPosition, Sn as removeProtectionTypeList, So as isImpossibleEmptyStoredAttribute, Sr as DEFAULT_RESOURCE_TIMEOUT_MS, Ss as malformedLocalResourceEntriesWarning, St as readRecordedConditionVerdicts, Su as buildAssetRedirectMap, Tc as unwrittenCreateOnlyReplacement, Td as expectedOwnerParam, Ti as ccRoutedFinalSnapshotError, Tl as identityKeyFor, Tn as withUnprovenUnsettled, To as carriesDynamicReference, Tr as constructPathOf$1, Ts as malformedScrubResourceEntriesRefusalMessage, Tt as withResourceDeadline, Tu as rewriteTemplateAssetReferences, Ua as applyRoleArnIfSet, Uc as maskedLeafCoordinatesOf, Ud as displayAssemblyPath, Ui as extractDeploymentEventError, Ul as LockManager, Un as inheritProducerRegions, Us as hasReadableOrphans, Ut as recordDisplacedSkips, Uu as redactedDockerCause, Va as producerLookupOver, Vc as maskReadbackAtCoordinates, Vd as absoluteAssemblyPathEscape, Vi as DeploymentEventsReader, Vl as WHOLE_DYNAMIC_REFERENCE_PATTERN, Vn as findNestedStackTypeChanges, Vs as repairMalformedResourcePropertiesForReadOnly, Vu as describeDockerFailure, Wa as assertFlagRoleArn, Wc as noEchoCoordinatesOf, Wd as renderAssemblyPathEscape, Wl as isLockInfoExpired, Wr as bold, Ws as malformedOrphansRefusalMessage, Wu as redactDockerArgvValues, Xa as applyCallerIdentityCredentials, Xc as recordedNoEchoValuesOf, Xl as hasReadableExportSet, Xn as nameGenerationCarriedFrom, Xr as addSuperseded, Xs as malformedExportSourceWarning, Xt as deleteJournaledOrphans, Xu as isMalformedEnvKey, Ya as AWS_CREDENTIAL_ENV_KEYS, Yc as readsNoEchoSource, Yd as resolveBucketRegion, Yl as exportNamesCarriedFrom, Yn as updatePartialReason, Yr as yellow, Ys as malformedExportNamesWarning, Yt as withNestedStackContext, Yu as isDockerClientEnvKey, Za as callerEnvCredentials, Zc as valueAtCoordinate, Zl as hasReasonlessBaselineRefusal, Zn as nameGenerationHighWaterOf, Zr as deleteSupersededEntry, Zs as malformedLocalOutputsWarning, Zt as dropFailedCommands, Zu as formatDockerLoginError, _c as STATE_RESOURCES_MALFORMED, _d as ssmResolvedValueType, _i as secretNamePrintingBag, _l as scrubResourceRecord, _n as pendingMovesOutOf, _o as keepHeldTokenProvenance, _r as noEchoParameterValueSeed, _s as refuseMalformedOrphansForOrphan, _t as renderNestedTemplateTreeDefect, _u as withStackInstanceIdWithheld, a as isProtectionValueActive, aa as wouldReturnToSdkProvider, ac as refuseDivergentRecordRegionForDestroy, ad as getDefaultStateBucketName, ai as withoutSuperseded, al as hasMaskableValues, ar as reachableDivergentParameters, as as withRetry, au as stackInstanceIdCarriedFrom, ba as RollbackInlinePolicyWriters, bc as hasReadableOutputs, bd as MIGRATE_TMP_PREFIX, bi as secretNamedRecordNeedles, bl as DYNAMIC_REFERENCE_TOKEN_SCAN, bn as replayFailedOperations, bo as recordedReferenceRegions, br as isExportAliasCollision, bs as unreadableOrphanRecords, bt as conditionInputsFrom, bu as stringifyValue, ca as customResourceResponseExpirationWarning, cc as malformedStateRefusalMessage, cd as resolveApp, ci as noEchoExactEchoLeavesOf, cl as printingCorpusOf, co as coerceParameterTypedValue, cr as displayTextOrWithheld, cs as declaresNoEcho, ct as crossStackOutputProvenanceSource, cu as timePhase, da as isCustomResourceType$1, dc as refuseMalformedResourcesForExport, dd as resolveSkipPrefix, di as createReadOnlyAttributeHealerFactory, dl as shareLogOnlyValues, dn as refactorMarkerMovesOf, do as AWS_NO_VALUE, dr as secretBearingStateKeyWarning, ds as malformedOrphanRecordsRefusalMessage, dt as findServiceTokenRefusals, du as CrossPrefixScanCache, ed as runDockerStreaming, ei as removeSuperseded, el as redactForState, en as journaledOrphanLines, eo as classifyReplaySecretRegion, er as retiredNameGenerationsAfter, eu as importableOutputs, fc as refuseMalformedState, fd as resolveStateBucketWithDefault, fi as completedReplayEntries, fl as unionOfSecretBags, fn as refactorMarkerRefusalMessage, fo as cfnRefValueFromPhysicalId, fr as secretSafeKeyDisplay, fs as malformedOrphanRecordsWarning, ft as serviceTokenBlockingReason, fu as applyCrossPrefixScan, gc as withheldAccountClause, gd as warnDeprecatedNoPrefixCliFlag, gi as orphanRecordsPrintingBag, gl as maskSecretsInText, gn as hasPendingMovesOut, gr as isWholeDynamicReferenceValue, gs as refuseMalformedOrphanRecordsForDestroy, gt as listNestedTemplateRows, gu as stackInstanceIdOf, ha as CloudControlProvider, hc as accountArgs, hd as stateBucketExistenceConfirmed, hi as namingSecretsWithRecordedNoEcho, hl as maskSecretsInError, hn as updateRefactorMarker, ho as refStateLookupFromResource, hr as exportNameSecretExposure, hs as refuseMalformedOrphanRecords, ht as isAbsoluteAssetPath, hu as isNotImplemented, i as PROTECTION_PROPERTY_BY_TYPE, ia as isCustomResource, ic as STATE_REGION_DIVERGED, id as synthesisStatusMessage, ii as supersededResourcesOf, il as createUnionSecretMasker, in as formatResourceLine, ir as namesAnyDeclaredParameter, is as describeTypeWithThrottleRetry, iu as shouldRetainResource, jd as StageLoadError, ji as buildFinalSnapshotIdentifier, jl as recordNestedStackParameterExpressions, jn as isJournaledOrphan, jo as unsettledItemsOf, jr as rollbackOrphanIds, js as refuseMalformedResourceEntriesForImportSave, jt as makeSiblingClaimReader, ju as getBootstrapMarkerKey, kd as refuseFailedLookups, ki as unsupportedFinalSnapshotError, kn as undeclaredEmptyObservedKeys, kr as hintSidesOf, ks as refuseMalformedResourceEntriesForDestroy, kt as mergeNoChangeOutputs, ku as assertAssetBucketRegion, la as TemplateNoEchoReresolver, lc as refuseMalformedResourcesForDeploy, ld as resolveAutoAssetStorage, li as noEchoParameterNamesOf, ll as recordLogOnlyParameterValue, ln as readRefactorMarker, lo as isUnboundTemplateParameter, lr as exportAliasCollisionScrubWarning, ls as deployRefusesOrphanRowsReason, lt as inheritedProvenanceForChildDiff, lu as rebuildClientForBucketRegion, mc as JSON_LISTING_HOLE_VALUE, md as resolveUseCdkBootstrapAssets, mi as maskEventTextWithBoundBags, ml as errorCauseChain, mn as sameMove, mo as lacksRecordedTableArn, mr as exportNameNoEchoParameters, ms as previewableOrphanRecords, mt as findNestedTemplateTreeDefect, mu as isAccessDenied, n as recordedProtectionEvidence, na as ProviderRegistry, nc as refuseMalformedOutputsForDestroy, nd as getDockerImageBySourceHash, ni as supersededHeldByOtherTypeWarning, nn as sameJournaledOrphans, no as regionLessSecretName, nr as withNameGenerationReached, ns as prefetchCreateOnlyPropertyPaths, nu as orphansAfterRollback, o as perType, oa as CUSTOM_RESOURCE_RESPONSE_LIFECYCLE_RULE_ID, oc as malformedRenderedContainersWarning, od as getLegacyStateBucketName, oi as noEchoAttributeNamesOf, ol as literalSplitDelimitersOf, or as resourcesNamingDeclaredParameter, os as parameterInputsFor, ot as IMPLICIT_DELETE_DEPENDENCIES, ou as PhaseClock, pa as withPrintingSecrets, pc as repairMalformedResourcesForReadOnly, pd as resolveStateBucketWithDefaultAndSource, pi as journaledOrphanPrintingBag, pl as createSecretMasker, pn as refuseRefactorMarker, po as isStalePlaceholderArnAttribute, pr as carriedExportAliasExposure, ps as malformedOrphanRowsKeptWarning, pt as childTemplateLoader, pu as crossPrefixDeniedWarning, qa as isIamRoleArn, qd as injectedAwsRegionValue, ql as acceptedCreateOnlyDropsOf, qr as green, qs as refuseMalformedOrphansForDestroy, qt as collectNestedChildUnaddressed, qu as partitionSensitiveEnv, r as recordedProtectionNote, ra as ccBrokenReason, rc as repairMalformedOutputsForReadOnly, rd as Synthesizer, ri as supersededHolderOf, rl as carryLogOnlyValues, rn as makeForeignHolderScan, rr as computeParameterTaint, rs as templateResourceTypes, ru as orphansCarriedFrom, s as readProtection, sa as applyCustomResourceResponseExpiration, sc as malformedResourcesWarning, sd as loadCdkJson, si as noEchoComparisonForTemplate, sl as logOnlyValueCount, sr as WITHHELD_NAME_DISPLAY, st as computeImplicitDeleteEdges, su as renderPhaseTimings, t as DeployEngine, ta as CC_BROKEN_REASON, tc as refuseMalformedOutputs, td as AssetManifestLoader, ti as supersededAfterRollback, tn as loadJournaledOrphans, to as producerRegionsFromState, tr as retiredNameGenerationsLeaving, tu as isReadableBag, ua as readsNoEchoDeleteValues, uc as refuseMalformedResourcesForDestroy, ud as resolveCaptureObservedState, ui as withAttemptedItemsMasked, ul as recordLogOnlyValue, un as readRefactorMarkerOnce, uo as parameterTypeMayLoseSecretIdentity, ur as secretBearing, us as isReadableOrphanRecord, ut as deferredServiceTokenWarning, uu as CrossPrefixReadError, va as setResolvedResourceTimeouts, vc as UNREADABLE_RESOURCES_MAP_ROW, vd as CFN_TEMPLATE_BODY_LIMIT, vi as secretNamePrintingBags, vl as withPhysicalNameCopies, vn as pendingMovesRefusalMessage, vr as collectDeclaredOutputNames, vs as repairMalformedOrphanRecordsForReadOnly, vt as templateIdentity, vu as AssetPublisher, wa as deleteSkipReason, wd as decodeListingKey, wi as PRE_DELETE_SNAPSHOT_TYPES, wl as pathCrossesDottedKey, wn as settleUnsettledPrevious, wo as isNamelessDynamicReferenceError, wr as maskingRetryLogger, ws as malformedResourceEntriesWarning, wu as loadPublishableAssetManifest, xa as UNSPECIFIED_SKIP_REASON, xc as hasReadableResources, xd as findLargeInlineResources, xi as stateSecretNameNeedles, xl as dynamicReferenceTokens, xn as replayRollback, xo as getAccountInfo, xr as bindingSkippedOutputs, xs as isReadableResourceEntry, xt as parentSuppliedValues, xu as WorkGraph, ya as slowCcOperationTimeoutMs, yc as displayLogicalId, yd as CFN_TEMPLATE_URL_LIMIT, yn as refusePendingMovesOut, yo as recordedOutputReferenceRegions, yr as collectPublishedOutputNames, ys as unpreviewableOrphanRecords, yt as conditionFingerprint, yu as isSensitiveAttributeName, zc as isMarkedCoordinate, zd as nullPrototypeRecord, zi as withCreateTokenLedger, zl as recordProvenPublicExpression, zn as seedsDeleteFirstGuard, zo as isStatefulRecreateTargetSync, zs as refuseMalformedResourcePropertiesForExport, zt as displacedPhysicalIdShown, zu as describeDockerCapturedOutput } from "./deploy-engine-BO_w6XzZ.js";
|
|
6
|
+
import { t as getCdkdVersion } from "./version-FHU_Fu1I.js";
|
|
7
|
+
import { t as cdkdCacheHome } from "./cli.js";
|
|
7
8
|
import { randomBytes, randomUUID } from "node:crypto";
|
|
8
9
|
import { CopyObjectCommand, CreateBucketCommand, DeleteBucketCommand, DeleteObjectsCommand, GetBucketLocationCommand, GetObjectCommand, HeadBucketCommand, ListObjectVersionsCommand, ListObjectsV2Command, NoSuchBucket, NotFound, PutBucketEncryptionCommand, PutBucketPolicyCommand, PutBucketVersioningCommand, PutObjectCommand, S3Client, S3ServiceException } from "@aws-sdk/client-s3";
|
|
9
10
|
import { GetRoleCommand, GetUserCommand } from "@aws-sdk/client-iam";
|
|
@@ -14,7 +15,7 @@ import { GetSecretValueCommand, SecretsManagerClient } from "@aws-sdk/client-sec
|
|
|
14
15
|
import { GetParameterCommand, SSMClient } from "@aws-sdk/client-ssm";
|
|
15
16
|
import { DescribeLogStreamsCommand, ResourceNotFoundException as ResourceNotFoundException$1 } from "@aws-sdk/client-cloudwatch-logs";
|
|
16
17
|
import * as fs from "node:fs";
|
|
17
|
-
import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
|
|
18
|
+
import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, promises, readFileSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
|
|
18
19
|
import * as path from "node:path";
|
|
19
20
|
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
20
21
|
import { execFile, spawn } from "node:child_process";
|
|
@@ -1851,7 +1852,7 @@ function collectCrossStackRefs(node, onRef, unconditional) {
|
|
|
1851
1852
|
// src/provisioning/register-providers.ts
|
|
1852
1853
|
let providerClasses;
|
|
1853
1854
|
function loadProviderClasses() {
|
|
1854
|
-
providerClasses ??= import("./provider-classes-
|
|
1855
|
+
providerClasses ??= import("./provider-classes-IuPgHvuR.js");
|
|
1855
1856
|
return providerClasses;
|
|
1856
1857
|
}
|
|
1857
1858
|
function registerAllProviders(registry, classes) {
|
|
@@ -13936,140 +13937,6 @@ function createDestroyCommand() {
|
|
|
13936
13937
|
return cmd;
|
|
13937
13938
|
}
|
|
13938
13939
|
|
|
13939
|
-
// src/cli/commands/rollback-drop-failed.ts
|
|
13940
|
-
function refuseDropFailedConflicts(options) {
|
|
13941
|
-
const conflicting = [
|
|
13942
|
-
...(options.orphan ?? []).length > 0 ? ["--orphan"] : [],
|
|
13943
|
-
...options.revertFailed === true ? ["--revert-failed"] : [],
|
|
13944
|
-
...options.skipFinalSnapshot === true ? ["--skip-final-snapshot"] : []
|
|
13945
|
-
];
|
|
13946
|
-
if (conflicting.length === 0) return;
|
|
13947
|
-
throw new CdkdError(`--drop-failed cannot be combined with ${conflicting.join(", ")}: it replays nothing, it only removes one entry from the rollback journal. Run the rollback and the drop as separate commands.`, "ROLLBACK_DROP_FAILED_CONFLICT");
|
|
13948
|
-
}
|
|
13949
|
-
function selectDropTarget(segments, logicalId, stackShown) {
|
|
13950
|
-
const named = logicalIdShown(logicalId);
|
|
13951
|
-
const droppable = [];
|
|
13952
|
-
let otherFailed = 0;
|
|
13953
|
-
let completed = 0;
|
|
13954
|
-
const droppableIds = /* @__PURE__ */ new Set();
|
|
13955
|
-
segments.forEach((segment, index) => {
|
|
13956
|
-
const failed = segment.failedOperations ?? [];
|
|
13957
|
-
const replay = segment.reason === "nested-pending-parent" ? [] : splitImportedOps(failed, segment).replay;
|
|
13958
|
-
for (const op of replay) if (isDroppable(op)) droppableIds.add(op.logicalId);
|
|
13959
|
-
for (const op of failed) {
|
|
13960
|
-
if (op.logicalId !== logicalId) continue;
|
|
13961
|
-
if (replay.includes(op) && isDroppable(op)) droppable.push({
|
|
13962
|
-
segment,
|
|
13963
|
-
segmentNumber: index + 1,
|
|
13964
|
-
op,
|
|
13965
|
-
companions: replay.filter((c) => c.changeType === "UPDATE" && replacementNeverSwapped(c, [op]))
|
|
13966
|
-
});
|
|
13967
|
-
else otherFailed++;
|
|
13968
|
-
}
|
|
13969
|
-
completed += segment.operations.filter((op) => op.logicalId === logicalId).length;
|
|
13970
|
-
});
|
|
13971
|
-
if (droppable.length === 1) return droppable[0];
|
|
13972
|
-
if (droppable.length > 1) throw new CdkdError(`The rollback journal of ${stackShown} holds ${droppable.length} entries for ${named} that --drop-failed could drop (segments ${droppable.map((d) => d.segmentNumber).join(", ")}), and it drops exactly one, so it does not choose. Nothing was changed. Remove the entry you mean from the stack's rollback-journal.json (next to its state.json) by hand.`, "ROLLBACK_DROP_FAILED_AMBIGUOUS");
|
|
13973
|
-
if (otherFailed > 0) throw new CdkdError(`The rollback journal of ${stackShown} holds no entry for ${named} that --drop-failed can drop: it drops only a failed CREATE whose resource cdkd proved it made, journaled as its only record, the entry cdkd destroy and cdkd deploy keep retrying. ${named}'s failed operation(s) are of another kind, or one a newer journal entry may own; neither blocks either command. Nothing was changed.`, "ROLLBACK_DROP_FAILED_NOT_ORPHAN");
|
|
13974
|
-
if (completed > 0) throw new CdkdError(`${named} is a completed operation in the rollback journal of ${stackShown}, not a failed one; --drop-failed drops failed operations only. Nothing was changed. To leave a completed operation out of a rollback, pass --orphan with its logical id.`, "ROLLBACK_DROP_FAILED_COMPLETED");
|
|
13975
|
-
const ids = [...droppableIds].map(logicalIdShown);
|
|
13976
|
-
throw new CdkdError(`The rollback journal of ${stackShown} has no entry for ${named}. Nothing was changed. ` + (ids.length === 0 ? "It holds no entry --drop-failed can drop." : `Entries --drop-failed can drop: ${ids.join(", ")}.`), "ROLLBACK_DROP_FAILED_UNKNOWN");
|
|
13977
|
-
}
|
|
13978
|
-
function isDroppable(op) {
|
|
13979
|
-
return isJournaledOrphan(op) && op.physicalIdRecoveredFromError === true || op.changeType === "CREATE" && op.pendingCloudControlRequest !== void 0;
|
|
13980
|
-
}
|
|
13981
|
-
const POLICY_TARGETS = {
|
|
13982
|
-
"AWS::SQS::QueuePolicy": "Queues",
|
|
13983
|
-
"AWS::SNS::TopicPolicy": "Topics"
|
|
13984
|
-
};
|
|
13985
|
-
function dropTargetLines(target, segmentCount, logger) {
|
|
13986
|
-
const { op } = target;
|
|
13987
|
-
const lines = [` - ${logicalIdShown(op.logicalId)} (${resourceTypeShown(op.resourceType)}) ${op.pendingCloudControlRequest !== void 0 ? "an abandoned Cloud Control request" : displacedPhysicalIdShown(op, logger) ?? "a physical id"} [failed CREATE, segment ${target.segmentNumber}/${segmentCount}]`];
|
|
13988
|
-
const targetsKey = Object.hasOwn(POLICY_TARGETS, op.resourceType) ? POLICY_TARGETS[op.resourceType] : void 0;
|
|
13989
|
-
const targets = targetsKey === void 0 ? void 0 : op.attemptedProperties?.[targetsKey];
|
|
13990
|
-
if (Array.isArray(targets) && targets.length > 0) {
|
|
13991
|
-
lines.push(` ${targetsKey} it was attached to:`);
|
|
13992
|
-
for (const t of targets) lines.push(` - ${typeof t === "string" && t !== "" ? displacedPhysicalIdShown(op, logger, t) ?? "a value" : "a value that is not a string"}`);
|
|
13993
|
-
}
|
|
13994
|
-
if (target.companions.length > 0) lines.push(` (with the failed replacement UPDATE recorded beside it, which names no resource of its own)`);
|
|
13995
|
-
return lines;
|
|
13996
|
-
}
|
|
13997
|
-
async function confirmDrop(question) {
|
|
13998
|
-
return confirmOrRefuse(question, {
|
|
13999
|
-
suffix: " (y/N): ",
|
|
14000
|
-
refusal: "The cdkd rollback --drop-failed confirmation prompt cannot run in a non-interactive environment. Pass --force (or -y / --yes) to confirm the drop, or run the command from a real terminal."
|
|
14001
|
-
});
|
|
14002
|
-
}
|
|
14003
|
-
async function dropFailedJournalEntry(args) {
|
|
14004
|
-
const { stateBackend, lockManager, stackName, region, logicalId, logger } = args;
|
|
14005
|
-
const stackShown = `stack ${plainOrDescribed(stackName, "stack name")} (${plainOrDescribed(region, "region")})`;
|
|
14006
|
-
let interrupted = false;
|
|
14007
|
-
const sigintHandler = () => {
|
|
14008
|
-
process.stderr.write("\nInterrupted — the rollback journal is not changed.\n");
|
|
14009
|
-
interrupted = true;
|
|
14010
|
-
};
|
|
14011
|
-
process.on("SIGINT", sigintHandler);
|
|
14012
|
-
const unforwardSigterm = forwardSigtermToSigint();
|
|
14013
|
-
try {
|
|
14014
|
-
await lockManager.acquireLockWithRetry(stackName, region, void 0, "rollback");
|
|
14015
|
-
} catch (error) {
|
|
14016
|
-
process.removeListener("SIGINT", sigintHandler);
|
|
14017
|
-
unforwardSigterm();
|
|
14018
|
-
throw error;
|
|
14019
|
-
}
|
|
14020
|
-
try {
|
|
14021
|
-
const journal = await stateBackend.loadRollbackJournal(stackName, region);
|
|
14022
|
-
if (!journal || journal.segments.length === 0) throw new CdkdError(`${stackShown.charAt(0).toUpperCase()}${stackShown.slice(1)} has no rollback journal; nothing to drop.`, "ROLLBACK_DROP_FAILED_NO_JOURNAL");
|
|
14023
|
-
let stateData;
|
|
14024
|
-
try {
|
|
14025
|
-
stateData = await stateBackend.getState(stackName, region);
|
|
14026
|
-
} catch (err) {
|
|
14027
|
-
throw new CdkdError(`Could not read the state record of ${stackShown} (${err instanceof Error ? err.name : "an error"}), which the drop needs to mask the entry. Nothing was changed; re-run once it can be read.`, "ROLLBACK_DROP_FAILED_STATE_UNREADABLE");
|
|
14028
|
-
}
|
|
14029
|
-
const resources = stateData ? stateData.state.resources : {};
|
|
14030
|
-
if (!isReadableBag(resources)) throw new CdkdError(`The state record of ${stackShown} holds resources that cannot be read, which the drop needs to mask the entry. Nothing was changed.`, "ROLLBACK_DROP_FAILED_STATE_UNREADABLE");
|
|
14031
|
-
const stateResources = resources;
|
|
14032
|
-
const judged = structuredClone(journal.segments);
|
|
14033
|
-
demoteSupersededOrphans(judged);
|
|
14034
|
-
const target = selectDropTarget(judged, logicalId, stackShown);
|
|
14035
|
-
const drop = [target.op, ...target.companions].map((op) => ({
|
|
14036
|
-
segment: target.segment,
|
|
14037
|
-
op
|
|
14038
|
-
}));
|
|
14039
|
-
if (journal.segments.reduce((n, segment) => n + (segment.failedOperations ?? []).filter((op) => isHandledOrphan(drop, segment, op)).length, 0) !== drop.length) throw new CdkdError(`The rollback journal of ${stackShown} holds another entry identical to ${logicalIdShown(logicalId)}'s, so dropping it by its identity would drop more than one. Nothing was changed. Remove the entry you mean from the stack's rollback-journal.json (next to its state.json) by hand.`, "ROLLBACK_DROP_FAILED_AMBIGUOUS");
|
|
14040
|
-
const printing = journaledOrphanPrintingBag(judged.flatMap((segment) => segment.failedOperations ?? []), stateResources);
|
|
14041
|
-
withPrintingSecrets(printing, () => {
|
|
14042
|
-
logger.info(safeMsg`\nDrop one entry from the rollback journal of ${stackShown}:`);
|
|
14043
|
-
for (const line of dropTargetLines(target, journal.segments.length, logger)) logger.info(line);
|
|
14044
|
-
logger.info("\nThis removes only the journal entry, which is cdkd's last record of that resource. Nothing is deleted in AWS: check the resource above by hand, and delete it yourself if it should not stay. cdkd destroy and cdkd deploy then no longer act on it.\n");
|
|
14045
|
-
});
|
|
14046
|
-
const stopIfInterrupted = () => {
|
|
14047
|
-
if (!interrupted) return;
|
|
14048
|
-
throw new CdkdError("Interrupted before the rollback journal was changed; nothing was dropped.", "ROLLBACK_DROP_FAILED_INTERRUPTED");
|
|
14049
|
-
};
|
|
14050
|
-
stopIfInterrupted();
|
|
14051
|
-
if (!args.skipConfirmation) {
|
|
14052
|
-
if (!await (args.confirm ?? confirmDrop)("Drop this entry from the rollback journal?")) {
|
|
14053
|
-
logger.info("Drop cancelled; the rollback journal is not changed.");
|
|
14054
|
-
return;
|
|
14055
|
-
}
|
|
14056
|
-
}
|
|
14057
|
-
stopIfInterrupted();
|
|
14058
|
-
const removed = await stateBackend.dropRollbackJournalFailedOperations(stackName, region, (op, segment) => isHandledOrphan(drop, segment, op));
|
|
14059
|
-
if (removed !== drop.length) throw new CdkdError(`The rollback journal of ${stackShown} was rewritten with ${removed} entr${removed === 1 ? "y" : "ies"} removed where ${drop.length} ${drop.length === 1 ? "was" : "were"} expected: it changed under the stack lock. Inspect the stack's rollback-journal.json (next to its state.json).`, "ROLLBACK_DROP_FAILED_CHANGED");
|
|
14060
|
-
logger.info(safeMsg`Dropped ${logicalIdShown(logicalId)}'s entry from the rollback journal of ${stackShown}. ` + "Nothing was deleted in AWS; every other entry is kept.");
|
|
14061
|
-
} finally {
|
|
14062
|
-
try {
|
|
14063
|
-
await lockManager.releaseLock(stackName, region).catch((err) => {
|
|
14064
|
-
logger.warn(safeMsg`Failed to release the lock of ${stackShown}: ${err instanceof Error ? err.name : "an error"}`);
|
|
14065
|
-
});
|
|
14066
|
-
} finally {
|
|
14067
|
-
process.removeListener("SIGINT", sigintHandler);
|
|
14068
|
-
unforwardSigterm();
|
|
14069
|
-
}
|
|
14070
|
-
}
|
|
14071
|
-
}
|
|
14072
|
-
|
|
14073
13940
|
// src/cli/commands/state-migrate.ts
|
|
14074
13941
|
async function stateMigrateCommand(options) {
|
|
14075
13942
|
const logger = getLogger();
|
|
@@ -20300,27 +20167,7 @@ function createStateCommand() {
|
|
|
20300
20167
|
return cmd;
|
|
20301
20168
|
}
|
|
20302
20169
|
|
|
20303
|
-
// src/cli/commands/rollback.ts
|
|
20304
|
-
function rerunRollback(stackName) {
|
|
20305
|
-
const rerun = pasteableCommand("cdkd rollback", [{
|
|
20306
|
-
value: stackName,
|
|
20307
|
-
hole: "stack",
|
|
20308
|
-
opts: { plainIdent: true }
|
|
20309
|
-
}]);
|
|
20310
|
-
return withheldTargetClause(rerun, "stack", "cdkd rollback", "This stack's name") + `\nRe-run with: ${rerun.command}`;
|
|
20311
|
-
}
|
|
20312
|
-
function backendErrorText(error, stackName, region) {
|
|
20313
|
-
if (!isPasteableIdent(stackName) || !isPasteableIdent(region)) return "its error text names a stack or region that is not a plain identifier, so it is not shown";
|
|
20314
|
-
return displaySafe(describeAwsFailure(error).detail);
|
|
20315
|
-
}
|
|
20316
|
-
function stackRegionShown(stackName, region) {
|
|
20317
|
-
return `${plainOrDescribed(stackName, "stack name")} (${plainOrDescribed(region, "region")})`;
|
|
20318
|
-
}
|
|
20319
|
-
function stackRegionIsPlain(stackName, region) {
|
|
20320
|
-
return isPasteableIdent(stackName) && isPasteableIdent(region);
|
|
20321
|
-
}
|
|
20322
|
-
const NESTED_NAME_DESCRIBED_NOTE = "(The nested stack's name is not a plain identifier, so it is described, not named; list the records as stored with 'cdkd state list --long'.)";
|
|
20323
|
-
const STACK_REGION_DESCRIBED_NOTE = " (The stack name or region is not a plain identifier, so it is described, not named; list the records as stored with 'cdkd state list --long'.)";
|
|
20170
|
+
// src/cli/commands/rollback/options.ts
|
|
20324
20171
|
function stackRegionOption() {
|
|
20325
20172
|
return new Option("--stack-region <region>", "Region of the target stack when the same name has state in multiple regions").argParser(parseStackRegion);
|
|
20326
20173
|
}
|
|
@@ -20345,58 +20192,204 @@ async function findJournalCandidates(backend, prefix) {
|
|
|
20345
20192
|
}
|
|
20346
20193
|
return refs;
|
|
20347
20194
|
}
|
|
20348
|
-
|
|
20349
|
-
|
|
20350
|
-
|
|
20351
|
-
|
|
20352
|
-
|
|
20353
|
-
|
|
20354
|
-
|
|
20355
|
-
|
|
20356
|
-
|
|
20357
|
-
|
|
20358
|
-
}
|
|
20359
|
-
function safeRoleArn(value) {
|
|
20360
|
-
return displayIdent(value, { maxCodePoints: 613 });
|
|
20361
|
-
}
|
|
20362
|
-
function refuseDivergentRecordRegionForRollback(state, stackName, keyRegion, divergentBodyRegion, provenOrphans) {
|
|
20363
|
-
if (divergentBodyRegion === void 0) return;
|
|
20364
|
-
const resourceCount = isReadableBag(state.resources) ? Object.keys(state.resources).length : void 0;
|
|
20365
|
-
if (resourceCount === 0 && provenOrphans === 0) return;
|
|
20366
|
-
const lists = resourceCount === void 0 ? "its resources map cannot be read" : resourceCount > 0 ? `it still lists ${resourceCount} resource${resourceCount === 1 ? "" : "s"}` : `its journal holds ${provenOrphans} failed create${provenOrphans === 1 ? "" : "s"} whose resource the rollback would delete`;
|
|
20367
|
-
throw markNonRetryable(new CdkdError(`cdkd will not roll back ${plainOrDescribed(stackName, "stack name")} (${plainOrDescribed(keyRegion, "region")}): the state record read from that region's key carries a 'region' of its own (${describeRegionValueKind(divergentBodyRegion)}) that is not the key's, and ${lists} — so cdkd cannot tell which region they are in. cdkd stamps the key's region into every record it writes, so this record was not written by cdkd. The replay would issue every delete and revert against the key's region; if the record's own region is the honest half, each delete comes back not-found, which the replay reads as ALREADY DELETED — it would report the resource rolled back, drop it from the record, and leave it standing in the other region. Nothing was changed. Re-run with --verbose to see what the record's region field holds, repair that field to match the key it is stored under, and run the rollback again.`, STATE_REGION_DIVERGED));
|
|
20195
|
+
|
|
20196
|
+
// src/cli/commands/rollback-drop-failed.ts
|
|
20197
|
+
function refuseDropFailedConflicts(options) {
|
|
20198
|
+
const conflicting = [
|
|
20199
|
+
...(options.orphan ?? []).length > 0 ? ["--orphan"] : [],
|
|
20200
|
+
...options.revertFailed === true ? ["--revert-failed"] : [],
|
|
20201
|
+
...options.skipFinalSnapshot === true ? ["--skip-final-snapshot"] : []
|
|
20202
|
+
];
|
|
20203
|
+
if (conflicting.length === 0) return;
|
|
20204
|
+
throw new CdkdError(`--drop-failed cannot be combined with ${conflicting.join(", ")}: it replays nothing, it only removes one entry from the rollback journal. Run the rollback and the drop as separate commands.`, "ROLLBACK_DROP_FAILED_CONFLICT");
|
|
20368
20205
|
}
|
|
20369
|
-
function
|
|
20370
|
-
|
|
20206
|
+
function selectDropTarget(segments, logicalId, stackShown) {
|
|
20207
|
+
const named = logicalIdShown(logicalId);
|
|
20208
|
+
const droppable = [];
|
|
20209
|
+
let otherFailed = 0;
|
|
20210
|
+
let completed = 0;
|
|
20211
|
+
const droppableIds = /* @__PURE__ */ new Set();
|
|
20212
|
+
segments.forEach((segment, index) => {
|
|
20213
|
+
const failed = segment.failedOperations ?? [];
|
|
20214
|
+
const replay = segment.reason === "nested-pending-parent" ? [] : splitImportedOps(failed, segment).replay;
|
|
20215
|
+
for (const op of replay) if (isDroppable(op)) droppableIds.add(op.logicalId);
|
|
20216
|
+
for (const op of failed) {
|
|
20217
|
+
if (op.logicalId !== logicalId) continue;
|
|
20218
|
+
if (replay.includes(op) && isDroppable(op)) droppable.push({
|
|
20219
|
+
segment,
|
|
20220
|
+
segmentNumber: index + 1,
|
|
20221
|
+
op,
|
|
20222
|
+
companions: replay.filter((c) => c.changeType === "UPDATE" && replacementNeverSwapped(c, [op]))
|
|
20223
|
+
});
|
|
20224
|
+
else otherFailed++;
|
|
20225
|
+
}
|
|
20226
|
+
completed += segment.operations.filter((op) => op.logicalId === logicalId).length;
|
|
20227
|
+
});
|
|
20228
|
+
if (droppable.length === 1) return droppable[0];
|
|
20229
|
+
if (droppable.length > 1) throw new CdkdError(`The rollback journal of ${stackShown} holds ${droppable.length} entries for ${named} that --drop-failed could drop (segments ${droppable.map((d) => d.segmentNumber).join(", ")}), and it drops exactly one, so it does not choose. Nothing was changed. Remove the entry you mean from the stack's rollback-journal.json (next to its state.json) by hand.`, "ROLLBACK_DROP_FAILED_AMBIGUOUS");
|
|
20230
|
+
if (otherFailed > 0) throw new CdkdError(`The rollback journal of ${stackShown} holds no entry for ${named} that --drop-failed can drop: it drops only a failed CREATE whose resource cdkd proved it made, journaled as its only record, the entry cdkd destroy and cdkd deploy keep retrying. ${named}'s failed operation(s) are of another kind, or one a newer journal entry may own; neither blocks either command. Nothing was changed.`, "ROLLBACK_DROP_FAILED_NOT_ORPHAN");
|
|
20231
|
+
if (completed > 0) throw new CdkdError(`${named} is a completed operation in the rollback journal of ${stackShown}, not a failed one; --drop-failed drops failed operations only. Nothing was changed. To leave a completed operation out of a rollback, pass --orphan with its logical id.`, "ROLLBACK_DROP_FAILED_COMPLETED");
|
|
20232
|
+
const ids = [...droppableIds].map(logicalIdShown);
|
|
20233
|
+
throw new CdkdError(`The rollback journal of ${stackShown} has no entry for ${named}. Nothing was changed. ` + (ids.length === 0 ? "It holds no entry --drop-failed can drop." : `Entries --drop-failed can drop: ${ids.join(", ")}.`), "ROLLBACK_DROP_FAILED_UNKNOWN");
|
|
20371
20234
|
}
|
|
20372
|
-
function
|
|
20373
|
-
|
|
20374
|
-
return routing.ok && routing.oldType !== op.resourceType ? `from ${safe(op.resourceType)} to ${safe(routing.oldType)}` : safe(op.resourceType);
|
|
20235
|
+
function isDroppable(op) {
|
|
20236
|
+
return isJournaledOrphan(op) && op.physicalIdRecoveredFromError === true || op.changeType === "CREATE" && op.pendingCloudControlRequest !== void 0;
|
|
20375
20237
|
}
|
|
20376
|
-
|
|
20377
|
-
|
|
20378
|
-
|
|
20379
|
-
|
|
20380
|
-
|
|
20381
|
-
|
|
20382
|
-
|
|
20383
|
-
|
|
20384
|
-
|
|
20385
|
-
|
|
20386
|
-
|
|
20387
|
-
|
|
20388
|
-
case "reverse-replacement-readopt": return item.retainsNewResource ? ` - reverse-replace ${safe(op.logicalId)} (${replacementTypes(op)}) [re-adopt retained old resource; new one RETAINED (UpdateReplacePolicy: Retain) and left untracked]` : ` - reverse-replace ${safe(op.logicalId)} (${replacementTypes(op)}) [delete new, re-adopt retained old resource]`;
|
|
20389
|
-
case "unrecoverable-delete": return ` - (cannot restore) ${safe(op.logicalId)} (${safe(op.resourceType)}) — was DELETED, unrecoverable`;
|
|
20390
|
-
case "skip-mismatch": return ` - skip ${safe(op.logicalId)} (${safe(op.resourceType)}) — physical id changed, needs manual attention`;
|
|
20391
|
-
case "skip-absent": return ` - skip ${safe(op.logicalId)} (${safe(op.resourceType)}) — no longer in state`;
|
|
20392
|
-
case "refuse-replacement-routing": {
|
|
20393
|
-
const routing = resolveReplacementOldType(op);
|
|
20394
|
-
return ` - (REFUSED) ${safe(op.logicalId)} (${safe(op.resourceType)}) — cannot reverse the replacement: ${routing.ok ? "its old type could not be routed" : routing.reason}`;
|
|
20395
|
-
}
|
|
20396
|
-
case "skip-already-done": return ` - skip ${safe(op.logicalId)} (${safe(op.resourceType)}) — already reverted`;
|
|
20238
|
+
const POLICY_TARGETS = {
|
|
20239
|
+
"AWS::SQS::QueuePolicy": "Queues",
|
|
20240
|
+
"AWS::SNS::TopicPolicy": "Topics"
|
|
20241
|
+
};
|
|
20242
|
+
function dropTargetLines(target, segmentCount, logger) {
|
|
20243
|
+
const { op } = target;
|
|
20244
|
+
const lines = [` - ${logicalIdShown(op.logicalId)} (${resourceTypeShown(op.resourceType)}) ${op.pendingCloudControlRequest !== void 0 ? "an abandoned Cloud Control request" : displacedPhysicalIdShown(op, logger) ?? "a physical id"} [failed CREATE, segment ${target.segmentNumber}/${segmentCount}]`];
|
|
20245
|
+
const targetsKey = Object.hasOwn(POLICY_TARGETS, op.resourceType) ? POLICY_TARGETS[op.resourceType] : void 0;
|
|
20246
|
+
const targets = targetsKey === void 0 ? void 0 : op.attemptedProperties?.[targetsKey];
|
|
20247
|
+
if (Array.isArray(targets) && targets.length > 0) {
|
|
20248
|
+
lines.push(` ${targetsKey} it was attached to:`);
|
|
20249
|
+
for (const t of targets) lines.push(` - ${typeof t === "string" && t !== "" ? displacedPhysicalIdShown(op, logger, t) ?? "a value" : "a value that is not a string"}`);
|
|
20397
20250
|
}
|
|
20251
|
+
if (target.companions.length > 0) lines.push(` (with the failed replacement UPDATE recorded beside it, which names no resource of its own)`);
|
|
20252
|
+
return lines;
|
|
20398
20253
|
}
|
|
20399
|
-
function
|
|
20254
|
+
async function confirmDrop(question) {
|
|
20255
|
+
return confirmOrRefuse(question, {
|
|
20256
|
+
suffix: " (y/N): ",
|
|
20257
|
+
refusal: "The cdkd rollback --drop-failed confirmation prompt cannot run in a non-interactive environment. Pass --force (or -y / --yes) to confirm the drop, or run the command from a real terminal."
|
|
20258
|
+
});
|
|
20259
|
+
}
|
|
20260
|
+
async function dropFailedJournalEntry(args) {
|
|
20261
|
+
const { stateBackend, lockManager, stackName, region, logicalId, logger } = args;
|
|
20262
|
+
const stackShown = `stack ${plainOrDescribed(stackName, "stack name")} (${plainOrDescribed(region, "region")})`;
|
|
20263
|
+
let interrupted = false;
|
|
20264
|
+
const sigintHandler = () => {
|
|
20265
|
+
process.stderr.write("\nInterrupted — the rollback journal is not changed.\n");
|
|
20266
|
+
interrupted = true;
|
|
20267
|
+
};
|
|
20268
|
+
process.on("SIGINT", sigintHandler);
|
|
20269
|
+
const unforwardSigterm = forwardSigtermToSigint();
|
|
20270
|
+
try {
|
|
20271
|
+
await lockManager.acquireLockWithRetry(stackName, region, void 0, "rollback");
|
|
20272
|
+
} catch (error) {
|
|
20273
|
+
process.removeListener("SIGINT", sigintHandler);
|
|
20274
|
+
unforwardSigterm();
|
|
20275
|
+
throw error;
|
|
20276
|
+
}
|
|
20277
|
+
try {
|
|
20278
|
+
const journal = await stateBackend.loadRollbackJournal(stackName, region);
|
|
20279
|
+
if (!journal || journal.segments.length === 0) throw new CdkdError(`${stackShown.charAt(0).toUpperCase()}${stackShown.slice(1)} has no rollback journal; nothing to drop.`, "ROLLBACK_DROP_FAILED_NO_JOURNAL");
|
|
20280
|
+
let stateData;
|
|
20281
|
+
try {
|
|
20282
|
+
stateData = await stateBackend.getState(stackName, region);
|
|
20283
|
+
} catch (err) {
|
|
20284
|
+
throw new CdkdError(`Could not read the state record of ${stackShown} (${err instanceof Error ? err.name : "an error"}), which the drop needs to mask the entry. Nothing was changed; re-run once it can be read.`, "ROLLBACK_DROP_FAILED_STATE_UNREADABLE");
|
|
20285
|
+
}
|
|
20286
|
+
const resources = stateData ? stateData.state.resources : {};
|
|
20287
|
+
if (!isReadableBag(resources)) throw new CdkdError(`The state record of ${stackShown} holds resources that cannot be read, which the drop needs to mask the entry. Nothing was changed.`, "ROLLBACK_DROP_FAILED_STATE_UNREADABLE");
|
|
20288
|
+
const stateResources = resources;
|
|
20289
|
+
const judged = structuredClone(journal.segments);
|
|
20290
|
+
demoteSupersededOrphans(judged);
|
|
20291
|
+
const target = selectDropTarget(judged, logicalId, stackShown);
|
|
20292
|
+
const drop = [target.op, ...target.companions].map((op) => ({
|
|
20293
|
+
segment: target.segment,
|
|
20294
|
+
op
|
|
20295
|
+
}));
|
|
20296
|
+
if (journal.segments.reduce((n, segment) => n + (segment.failedOperations ?? []).filter((op) => isHandledOrphan(drop, segment, op)).length, 0) !== drop.length) throw new CdkdError(`The rollback journal of ${stackShown} holds another entry identical to ${logicalIdShown(logicalId)}'s, so dropping it by its identity would drop more than one. Nothing was changed. Remove the entry you mean from the stack's rollback-journal.json (next to its state.json) by hand.`, "ROLLBACK_DROP_FAILED_AMBIGUOUS");
|
|
20297
|
+
const printing = journaledOrphanPrintingBag(judged.flatMap((segment) => segment.failedOperations ?? []), stateResources);
|
|
20298
|
+
withPrintingSecrets(printing, () => {
|
|
20299
|
+
logger.info(safeMsg`\nDrop one entry from the rollback journal of ${stackShown}:`);
|
|
20300
|
+
for (const line of dropTargetLines(target, journal.segments.length, logger)) logger.info(line);
|
|
20301
|
+
logger.info("\nThis removes only the journal entry, which is cdkd's last record of that resource. Nothing is deleted in AWS: check the resource above by hand, and delete it yourself if it should not stay. cdkd destroy and cdkd deploy then no longer act on it.\n");
|
|
20302
|
+
});
|
|
20303
|
+
const stopIfInterrupted = () => {
|
|
20304
|
+
if (!interrupted) return;
|
|
20305
|
+
throw new CdkdError("Interrupted before the rollback journal was changed; nothing was dropped.", "ROLLBACK_DROP_FAILED_INTERRUPTED");
|
|
20306
|
+
};
|
|
20307
|
+
stopIfInterrupted();
|
|
20308
|
+
if (!args.skipConfirmation) {
|
|
20309
|
+
if (!await (args.confirm ?? confirmDrop)("Drop this entry from the rollback journal?")) {
|
|
20310
|
+
logger.info("Drop cancelled; the rollback journal is not changed.");
|
|
20311
|
+
return;
|
|
20312
|
+
}
|
|
20313
|
+
}
|
|
20314
|
+
stopIfInterrupted();
|
|
20315
|
+
const removed = await stateBackend.dropRollbackJournalFailedOperations(stackName, region, (op, segment) => isHandledOrphan(drop, segment, op));
|
|
20316
|
+
if (removed !== drop.length) throw new CdkdError(`The rollback journal of ${stackShown} was rewritten with ${removed} entr${removed === 1 ? "y" : "ies"} removed where ${drop.length} ${drop.length === 1 ? "was" : "were"} expected: it changed under the stack lock. Inspect the stack's rollback-journal.json (next to its state.json).`, "ROLLBACK_DROP_FAILED_CHANGED");
|
|
20317
|
+
logger.info(safeMsg`Dropped ${logicalIdShown(logicalId)}'s entry from the rollback journal of ${stackShown}. ` + "Nothing was deleted in AWS; every other entry is kept.");
|
|
20318
|
+
} finally {
|
|
20319
|
+
try {
|
|
20320
|
+
await lockManager.releaseLock(stackName, region).catch((err) => {
|
|
20321
|
+
logger.warn(safeMsg`Failed to release the lock of ${stackShown}: ${err instanceof Error ? err.name : "an error"}`);
|
|
20322
|
+
});
|
|
20323
|
+
} finally {
|
|
20324
|
+
process.removeListener("SIGINT", sigintHandler);
|
|
20325
|
+
unforwardSigterm();
|
|
20326
|
+
}
|
|
20327
|
+
}
|
|
20328
|
+
}
|
|
20329
|
+
|
|
20330
|
+
// src/cli/commands/rollback/render.ts
|
|
20331
|
+
function rerunRollback(stackName) {
|
|
20332
|
+
const rerun = pasteableCommand("cdkd rollback", [{
|
|
20333
|
+
value: stackName,
|
|
20334
|
+
hole: "stack",
|
|
20335
|
+
opts: { plainIdent: true }
|
|
20336
|
+
}]);
|
|
20337
|
+
return withheldTargetClause(rerun, "stack", "cdkd rollback", "This stack's name") + `\nRe-run with: ${rerun.command}`;
|
|
20338
|
+
}
|
|
20339
|
+
function backendErrorText(error, stackName, region) {
|
|
20340
|
+
if (!isPasteableIdent(stackName) || !isPasteableIdent(region)) return "its error text names a stack or region that is not a plain identifier, so it is not shown";
|
|
20341
|
+
return displaySafe(describeAwsFailure(error).detail);
|
|
20342
|
+
}
|
|
20343
|
+
function stackRegionShown(stackName, region) {
|
|
20344
|
+
return `${plainOrDescribed(stackName, "stack name")} (${plainOrDescribed(region, "region")})`;
|
|
20345
|
+
}
|
|
20346
|
+
function stackRegionIsPlain(stackName, region) {
|
|
20347
|
+
return isPasteableIdent(stackName) && isPasteableIdent(region);
|
|
20348
|
+
}
|
|
20349
|
+
const NESTED_NAME_DESCRIBED_NOTE = "(The nested stack's name is not a plain identifier, so it is described, not named; list the records as stored with 'cdkd state list --long'.)";
|
|
20350
|
+
const STACK_REGION_DESCRIBED_NOTE = " (The stack name or region is not a plain identifier, so it is described, not named; list the records as stored with 'cdkd state list --long'.)";
|
|
20351
|
+
function snapshotNote(resourceType, effectiveProvisionedBy, skipFinalSnapshot) {
|
|
20352
|
+
if (skipFinalSnapshot) return "DeletionPolicy Snapshot — NO final snapshot (--skip-final-snapshot)";
|
|
20353
|
+
if (refusesFinalSnapshot(resourceType, effectiveProvisionedBy)) return "DeletionPolicy Snapshot — cdkd cannot snapshot this resource; the rollback will REFUSE it (re-run with --skip-final-snapshot to delete without one)";
|
|
20354
|
+
return "DeletionPolicy Snapshot — final snapshot, then delete";
|
|
20355
|
+
}
|
|
20356
|
+
function safe(value) {
|
|
20357
|
+
return displayIdent(value);
|
|
20358
|
+
}
|
|
20359
|
+
function safeStack(value) {
|
|
20360
|
+
return displayIdent(value, { maxCodePoints: STACK_REF_MAX_CODE_POINTS });
|
|
20361
|
+
}
|
|
20362
|
+
function safeRoleArn(value) {
|
|
20363
|
+
return displayIdent(value, { maxCodePoints: 613 });
|
|
20364
|
+
}
|
|
20365
|
+
function replacementTypes(op) {
|
|
20366
|
+
const routing = resolveReplacementOldType(op);
|
|
20367
|
+
return routing.ok && routing.oldType !== op.resourceType ? `from ${safe(op.resourceType)} to ${safe(routing.oldType)}` : safe(op.resourceType);
|
|
20368
|
+
}
|
|
20369
|
+
function actionLabel(item, skipFinalSnapshot) {
|
|
20370
|
+
const { op, action, replacement } = item;
|
|
20371
|
+
const rep = replacement ? " [replacement occurred, best-effort revert]" : "";
|
|
20372
|
+
switch (action) {
|
|
20373
|
+
case "delete": return ` - delete ${safe(op.logicalId)} (${safe(op.resourceType)})${rep}`;
|
|
20374
|
+
case "delete-with-final-snapshot": return ` - delete ${logicalIdShown(op.logicalId)} (${resourceTypeShown(op.resourceType)}) [${snapshotNote(op.resourceType, item.effectiveProvisionedBy, skipFinalSnapshot)}]`;
|
|
20375
|
+
case "orphan-retain": return ` - orphan ${safe(op.logicalId)} (${safe(op.resourceType)}) [DeletionPolicy Retain — left in AWS]`;
|
|
20376
|
+
case "orphan-flag": return ` - orphan ${safe(op.logicalId)} (${safe(op.resourceType)}) [--orphan]`;
|
|
20377
|
+
case "revert": return ` - revert ${safe(op.logicalId)} (${safe(op.resourceType)})${rep}`;
|
|
20378
|
+
case "reverse-replacement":
|
|
20379
|
+
if (op.oldResourceMaySurvive !== void 0) return ` - reverse-replace ${safe(op.logicalId)} (${replacementTypes(op)}) [the deploy did not confirm deleting the old resource: re-create it if AWS reports it gone, ` + (op.oldResourceMaySurvive === "kept" ? `re-adopt it if AWS still has it (its delete was refused or never sent), ` : `REFUSED if AWS still has it (its delete may still be running, or only partly ran), `) + `REFUSED if cdkd cannot tell; ` + (item.retainsNewResource ? `new one RETAINED (UpdateReplacePolicy: Retain) and left untracked]` : `delete new]`);
|
|
20380
|
+
return item.retainsNewResource ? ` - reverse-replace ${safe(op.logicalId)} (${replacementTypes(op)}) [re-create old resource; new one RETAINED (UpdateReplacePolicy: Retain) and left untracked — REFUSED instead if the re-create collides with the name the retained resource still holds]` : ` - reverse-replace ${safe(op.logicalId)} (${replacementTypes(op)}) [re-create old resource, delete new]`;
|
|
20381
|
+
case "reverse-replacement-readopt": return item.retainsNewResource ? ` - reverse-replace ${safe(op.logicalId)} (${replacementTypes(op)}) [re-adopt retained old resource; new one RETAINED (UpdateReplacePolicy: Retain) and left untracked]` : ` - reverse-replace ${safe(op.logicalId)} (${replacementTypes(op)}) [delete new, re-adopt retained old resource]`;
|
|
20382
|
+
case "unrecoverable-delete": return ` - (cannot restore) ${safe(op.logicalId)} (${safe(op.resourceType)}) — was DELETED, unrecoverable`;
|
|
20383
|
+
case "skip-mismatch": return ` - skip ${safe(op.logicalId)} (${safe(op.resourceType)}) — physical id changed, needs manual attention`;
|
|
20384
|
+
case "skip-absent": return ` - skip ${safe(op.logicalId)} (${safe(op.resourceType)}) — no longer in state`;
|
|
20385
|
+
case "refuse-replacement-routing": {
|
|
20386
|
+
const routing = resolveReplacementOldType(op);
|
|
20387
|
+
return ` - (REFUSED) ${safe(op.logicalId)} (${safe(op.resourceType)}) — cannot reverse the replacement: ${routing.ok ? "its old type could not be routed" : routing.reason}`;
|
|
20388
|
+
}
|
|
20389
|
+
case "skip-already-done": return ` - skip ${safe(op.logicalId)} (${safe(op.resourceType)}) — already reverted`;
|
|
20390
|
+
}
|
|
20391
|
+
}
|
|
20392
|
+
function importedOpLabel(op) {
|
|
20400
20393
|
return ` - skip ${logicalIdShown(op.logicalId)} (${resourceTypeShown(op.resourceType)}) — adopted by cdkd import after this deploy, left as it is`;
|
|
20401
20394
|
}
|
|
20402
20395
|
function displacedOpLabel(op, segment) {
|
|
@@ -20427,6 +20420,453 @@ async function confirm(question) {
|
|
|
20427
20420
|
refusal: "The cdkd rollback confirmation prompt cannot run in a non-interactive environment. Pass --force (or -y / --yes) to confirm the rollback, or run the command from a real terminal."
|
|
20428
20421
|
});
|
|
20429
20422
|
}
|
|
20423
|
+
|
|
20424
|
+
// src/cli/commands/rollback/guards.ts
|
|
20425
|
+
function refuseDivergentRecordRegionForRollback(state, stackName, keyRegion, divergentBodyRegion, provenOrphans) {
|
|
20426
|
+
if (divergentBodyRegion === void 0) return;
|
|
20427
|
+
const resourceCount = isReadableBag(state.resources) ? Object.keys(state.resources).length : void 0;
|
|
20428
|
+
if (resourceCount === 0 && provenOrphans === 0) return;
|
|
20429
|
+
const lists = resourceCount === void 0 ? "its resources map cannot be read" : resourceCount > 0 ? `it still lists ${resourceCount} resource${resourceCount === 1 ? "" : "s"}` : `its journal holds ${provenOrphans} failed create${provenOrphans === 1 ? "" : "s"} whose resource the rollback would delete`;
|
|
20430
|
+
throw markNonRetryable(new CdkdError(`cdkd will not roll back ${plainOrDescribed(stackName, "stack name")} (${plainOrDescribed(keyRegion, "region")}): the state record read from that region's key carries a 'region' of its own (${describeRegionValueKind(divergentBodyRegion)}) that is not the key's, and ${lists} — so cdkd cannot tell which region they are in. cdkd stamps the key's region into every record it writes, so this record was not written by cdkd. The replay would issue every delete and revert against the key's region; if the record's own region is the honest half, each delete comes back not-found, which the replay reads as ALREADY DELETED — it would report the resource rolled back, drop it from the record, and leave it standing in the other region. Nothing was changed. Re-run with --verbose to see what the record's region field holds, repair that field to match the key it is stored under, and run the rollback again.`, STATE_REGION_DIVERGED));
|
|
20431
|
+
}
|
|
20432
|
+
function divergedDuringRollbackMessage(divergentBodyRegion) {
|
|
20433
|
+
return `the state record was rewritten during this rollback, and the rewrite carries a 'region' of its own (${describeRegionValueKind(divergentBodyRegion)}) that is not the region of its key, so cdkd did not write over it`;
|
|
20434
|
+
}
|
|
20435
|
+
async function judgeNestedPendingRecords(setup, stackName, region, segments) {
|
|
20436
|
+
const pending = segments.filter((s) => s.reason === NESTED_PENDING_PARENT_REASON);
|
|
20437
|
+
if (pending.length === 0) return 0;
|
|
20438
|
+
const lastCut = stackName.lastIndexOf("~");
|
|
20439
|
+
const parent = lastCut > 0 ? stackName.slice(0, lastCut) : void 0;
|
|
20440
|
+
const topLevel = stackName.split("~")[0];
|
|
20441
|
+
const refuse = (detail) => {
|
|
20442
|
+
throw new Error(`The rollback journal of nested stack ${safeStack(stackName)} (${safe(region)}) holds the record of a nested deploy that ${detail} Roll back the top-level stack ${safeStack(topLevel)} instead, or re-deploy it, which clears the record.`);
|
|
20443
|
+
};
|
|
20444
|
+
if (parent === void 0) return pending.length;
|
|
20445
|
+
let parentJournal;
|
|
20446
|
+
try {
|
|
20447
|
+
parentJournal = await setup.stateBackend.loadRollbackJournal(parent, region);
|
|
20448
|
+
} catch (error) {
|
|
20449
|
+
return refuse(`cannot be judged: the journal of its parent ${safeStack(parent)} could not be read (${backendErrorText(error, parent, region)}), so the record may still be needed.`);
|
|
20450
|
+
}
|
|
20451
|
+
const parentRuns = new Set((parentJournal?.segments ?? []).flatMap((s) => s.runId !== void 0 ? [s.runId] : []));
|
|
20452
|
+
if (pending.some((s) => s.runId !== void 0 && parentRuns.has(s.runId))) refuse(`its parent has not settled, which only a rollback of the top-level stack may replay.`);
|
|
20453
|
+
let lock;
|
|
20454
|
+
try {
|
|
20455
|
+
lock = await setup.lockManager.getLockInfo(topLevel, region);
|
|
20456
|
+
} catch (error) {
|
|
20457
|
+
return refuse(`cannot be judged: the lock of the top-level stack could not be read (${backendErrorText(error, topLevel, region)}).`);
|
|
20458
|
+
}
|
|
20459
|
+
if (lock && !isLockInfoExpired(lock)) refuse("may belong to a deploy still running: the top-level stack is locked. Retry once it is free.");
|
|
20460
|
+
return pending.length;
|
|
20461
|
+
}
|
|
20462
|
+
|
|
20463
|
+
// src/cli/commands/rollback/preview.ts
|
|
20464
|
+
async function printRollbackPlanSegments(ctx) {
|
|
20465
|
+
const { journal, logger, options, inSegmentScope, planStateView, providerRegistry, region, setup, stackName, orphanLogicalIds } = ctx;
|
|
20466
|
+
for (let s = journal.segments.length - 1; s >= 0; s--) {
|
|
20467
|
+
const segment = journal.segments[s];
|
|
20468
|
+
logger.info(`\n Segment ${s + 1}/${journal.segments.length} (${safe(segment.reason)}${segment.runId ? `, run ${safe(segment.runId)}` : ""}):`);
|
|
20469
|
+
const failedOps = splitImportedOps(segment.failedOperations ?? [], segment);
|
|
20470
|
+
const completedOps = splitImportedOps(segment.operations, segment, orphanLogicalIds);
|
|
20471
|
+
for (const op of [...failedOps.imported, ...completedOps.imported]) logger.info(importedOpLabel(op));
|
|
20472
|
+
for (const op of [...failedOps.displaced, ...completedOps.displaced]) logger.info(displacedOpLabel(op, segment));
|
|
20473
|
+
const failedToReplay = failedOpsToReplay(failedOps.replay, options.revertFailed === true);
|
|
20474
|
+
if (failedOps.replay.length > 0) {
|
|
20475
|
+
if (failedToReplay.length > 0) {
|
|
20476
|
+
const failedPlan = await inSegmentScope(segment, () => recheckFailedPlan(planFailedOps(failedToReplay, planStateView), planStateView, {
|
|
20477
|
+
providerRegistry,
|
|
20478
|
+
region,
|
|
20479
|
+
logger
|
|
20480
|
+
}));
|
|
20481
|
+
for (const item of failedPlan) {
|
|
20482
|
+
logger.info(failedActionLabel(item, options.skipFinalSnapshot === true));
|
|
20483
|
+
if (revertedNestedRowIds([item.op]).length > 0) for (const line of await previewNestedChildRevert(setup.stateBackend, nestedChildStackName$1(stackName, item.op.logicalId), region, segment.runId, options.skipFinalSnapshot === true)) logger.info(line);
|
|
20484
|
+
}
|
|
20485
|
+
applyFailedPlanToPreview(failedPlan, planStateView, options.skipFinalSnapshot === true);
|
|
20486
|
+
}
|
|
20487
|
+
for (const fop of failedOps.replay.filter((op) => !failedToReplay.includes(op))) logger.info(` - (left as-is) ${logicalIdShown(fop.logicalId)} (${resourceTypeShown(fop.resourceType)}) — its ${plainOrDescribed(fop.changeType, "change type")} FAILED mid-deploy; pass --revert-failed to attempt reverting it`);
|
|
20488
|
+
}
|
|
20489
|
+
const plan = planRollback(completedOps.replay, planStateView, orphanLogicalIds);
|
|
20490
|
+
for (const item of plan) {
|
|
20491
|
+
logger.info(actionLabel(item, options.skipFinalSnapshot === true));
|
|
20492
|
+
if (revertedNestedRowIds([item.op]).length > 0) for (const line of await previewNestedChildRevert(setup.stateBackend, nestedChildStackName$1(stackName, item.op.logicalId), region, segment.runId, options.skipFinalSnapshot === true)) logger.info(line);
|
|
20493
|
+
}
|
|
20494
|
+
applyPlanToPreview(plan, planStateView, options.skipFinalSnapshot === true);
|
|
20495
|
+
}
|
|
20496
|
+
}
|
|
20497
|
+
async function previewNestedChildRevert(backend, childStackName, region, runId, skipFinalSnapshot) {
|
|
20498
|
+
const plain = isPasteableIdent(childStackName);
|
|
20499
|
+
const shown = plain ? `nested stack ${childStackName}` : "a nested stack whose name is not a plain identifier";
|
|
20500
|
+
const withPointer = (lines) => plain ? lines : [...lines, ` ${NESTED_NAME_DESCRIBED_NOTE}`];
|
|
20501
|
+
if (runId === void 0) return withPointer([` (${shown}: this segment carries no deploy run id — its revert will FAIL and the segment is kept)`]);
|
|
20502
|
+
try {
|
|
20503
|
+
const [childState, journal] = await Promise.all([backend.getState(childStackName, region), backend.loadRollbackJournal(childStackName, region)]);
|
|
20504
|
+
const segments = (journal?.segments ?? []).filter((s) => s.runId === runId);
|
|
20505
|
+
if (!childState || segments.length === 0) return withPointer([` (${shown}: no journal record for this run — its revert will FAIL and the segment is kept)`]);
|
|
20506
|
+
const view = { ...childState.state.resources };
|
|
20507
|
+
const lines = [` ${shown} replays its own journal:`];
|
|
20508
|
+
for (let s = segments.length - 1; s >= 0; s--) {
|
|
20509
|
+
const childOps = splitImportedOps(segments[s].operations, segments[s]);
|
|
20510
|
+
for (const op of childOps.imported) lines.push(` ${importedOpLabel(op)}`);
|
|
20511
|
+
for (const op of childOps.displaced) lines.push(` ${displacedOpLabel(op, segments[s])}`);
|
|
20512
|
+
const childPlan = planRollback(childOps.replay, view, /* @__PURE__ */ new Set());
|
|
20513
|
+
for (const item of childPlan) lines.push(` ${actionLabel(item, skipFinalSnapshot)}`);
|
|
20514
|
+
applyPlanToPreview(childPlan, view, skipFinalSnapshot);
|
|
20515
|
+
}
|
|
20516
|
+
if (lines.length === 1) lines.push(" (nothing to undo)");
|
|
20517
|
+
return withPointer(lines);
|
|
20518
|
+
} catch (error) {
|
|
20519
|
+
return withPointer([` (${shown}: could not preview its revert: ${backendErrorText(error, childStackName, region)})`]);
|
|
20520
|
+
}
|
|
20521
|
+
}
|
|
20522
|
+
function planItemWillBeRefused(resourceType, effectiveProvisionedBy, skipFinalSnapshot) {
|
|
20523
|
+
if (skipFinalSnapshot) return false;
|
|
20524
|
+
return refusesFinalSnapshot(resourceType, effectiveProvisionedBy);
|
|
20525
|
+
}
|
|
20526
|
+
function applyPlanToPreview(plan, previewState, skipFinalSnapshot) {
|
|
20527
|
+
for (const item of plan) {
|
|
20528
|
+
const { op, action } = item;
|
|
20529
|
+
switch (action) {
|
|
20530
|
+
case "delete-with-final-snapshot":
|
|
20531
|
+
if (planItemWillBeRefused(op.resourceType, item.effectiveProvisionedBy, skipFinalSnapshot)) break;
|
|
20532
|
+
if (op.changeType === "CREATE") delete previewState[op.logicalId];
|
|
20533
|
+
break;
|
|
20534
|
+
case "delete":
|
|
20535
|
+
case "orphan-retain":
|
|
20536
|
+
case "orphan-flag":
|
|
20537
|
+
if (op.changeType === "CREATE") delete previewState[op.logicalId];
|
|
20538
|
+
break;
|
|
20539
|
+
case "revert":
|
|
20540
|
+
case "reverse-replacement":
|
|
20541
|
+
case "reverse-replacement-readopt": if (op.previousState) previewState[op.logicalId] = op.previousState;
|
|
20542
|
+
}
|
|
20543
|
+
}
|
|
20544
|
+
}
|
|
20545
|
+
function applyFailedPlanToPreview(plan, previewState, skipFinalSnapshot) {
|
|
20546
|
+
for (const item of plan) {
|
|
20547
|
+
const { op, action } = item;
|
|
20548
|
+
switch (action) {
|
|
20549
|
+
case "delete-failed-create-with-final-snapshot":
|
|
20550
|
+
if (planItemWillBeRefused(op.resourceType, item.effectiveProvisionedBy, skipFinalSnapshot)) break;
|
|
20551
|
+
if (!recordUnderIdIsNotOwn(op, previewState)) delete previewState[op.logicalId];
|
|
20552
|
+
break;
|
|
20553
|
+
case "delete-failed-create":
|
|
20554
|
+
case "orphan-failed-create-retain":
|
|
20555
|
+
if (!recordUnderIdIsNotOwn(op, previewState)) delete previewState[op.logicalId];
|
|
20556
|
+
break;
|
|
20557
|
+
case "revert-failed-update": if (op.previousState) previewState[op.logicalId] = op.previousState;
|
|
20558
|
+
}
|
|
20559
|
+
}
|
|
20560
|
+
}
|
|
20561
|
+
|
|
20562
|
+
// src/cli/commands/rollback/replay.ts
|
|
20563
|
+
async function runRollbackReplay(ctx) {
|
|
20564
|
+
const { providerClasses, setup, options, logger, stackName, region, crossPrefixScan, finalSnapshotClients, skipConfirmation } = ctx;
|
|
20565
|
+
const providerRegistry = new ProviderRegistry();
|
|
20566
|
+
registerAllProviders(providerRegistry, providerClasses);
|
|
20567
|
+
providerRegistry.setCustomResourceResponseBucket(setup.bucket);
|
|
20568
|
+
let interrupted = false;
|
|
20569
|
+
let declinedDivergentRewrite = false;
|
|
20570
|
+
let declinedDivergentReason = "";
|
|
20571
|
+
const sigintHandler = () => {
|
|
20572
|
+
process.stderr.write("\nInterrupted — stopping rollback after the current operation...\n");
|
|
20573
|
+
interrupted = true;
|
|
20574
|
+
};
|
|
20575
|
+
process.on("SIGINT", sigintHandler);
|
|
20576
|
+
const unforwardSigterm = forwardSigtermToSigint();
|
|
20577
|
+
try {
|
|
20578
|
+
await setup.lockManager.acquireLockWithRetry(stackName, region, void 0, "rollback");
|
|
20579
|
+
} catch (error) {
|
|
20580
|
+
process.removeListener("SIGINT", sigintHandler);
|
|
20581
|
+
unforwardSigterm();
|
|
20582
|
+
throw error;
|
|
20583
|
+
}
|
|
20584
|
+
try {
|
|
20585
|
+
const stateData = await setup.stateBackend.getState(stackName, region);
|
|
20586
|
+
const stackInstanceId = stackInstanceIdOf(stateData?.state, displayStackName(stackName));
|
|
20587
|
+
let journal = await setup.stateBackend.loadRollbackJournal(stackName, region);
|
|
20588
|
+
if (await resolvePendingCloudControlRequests({
|
|
20589
|
+
journal: setup.stateBackend,
|
|
20590
|
+
loaded: journal,
|
|
20591
|
+
reader: () => providerRegistry.getCloudControlProvider(),
|
|
20592
|
+
stackName,
|
|
20593
|
+
region,
|
|
20594
|
+
command: "rollback",
|
|
20595
|
+
logger,
|
|
20596
|
+
stateResources: stateData?.state.resources,
|
|
20597
|
+
stackInstanceId: stateData === null ? () => setup.stateBackend.readStackInstanceSibling(stackName, region) : stackInstanceId
|
|
20598
|
+
})) journal = await setup.stateBackend.loadRollbackJournal(stackName, region);
|
|
20599
|
+
const orphanedPending = journal ? await judgeNestedPendingRecords(setup, stackName, region, journal.segments) : 0;
|
|
20600
|
+
if (journal && orphanedPending > 0) journal = {
|
|
20601
|
+
...journal,
|
|
20602
|
+
segments: journal.segments.filter((s) => s.reason !== NESTED_PENDING_PARENT_REASON)
|
|
20603
|
+
};
|
|
20604
|
+
if (!journal || journal.segments.length === 0 && orphanedPending === 0) throw new Error(`Nothing to roll back for ${plainOrDescribed(stackName, "stack name")} (${plainOrDescribed(region, "region")}). Run 'cdkd deploy' to (re)deploy, or 'cdkd destroy' to clean up.`);
|
|
20605
|
+
applyCrossPrefixScan(await crossPrefixScan, {
|
|
20606
|
+
stackName,
|
|
20607
|
+
region,
|
|
20608
|
+
bucket: setup.bucket,
|
|
20609
|
+
recovery: {
|
|
20610
|
+
profile: options.profile,
|
|
20611
|
+
stateBucket: setup.bucket
|
|
20612
|
+
}
|
|
20613
|
+
}, "rollback", (message) => logger.warn(message), (message) => logger.info(message));
|
|
20614
|
+
if (!stateData) throw new Error(`Rollback journal exists for ${safeStack(stackName)} (${safe(region)}) but its state.json is missing (keys: ${safe(setup.prefix)}/${safeStack(stackName)}/${safe(region)}/state.json and .../rollback-journal.json). State appears corrupted — inspect the bucket manually.`);
|
|
20615
|
+
demoteSupersededOrphans(journal.segments, Array.isArray(stateData.state.orphans) ? stateData.state.orphans : []);
|
|
20616
|
+
if (!options.revertFailed) for (const segment of journal.segments) {
|
|
20617
|
+
const failedRows = splitImportedOps(segment.failedOperations ?? [], segment).replay;
|
|
20618
|
+
for (const logicalId of revertedNestedRowIds(failedRows)) {
|
|
20619
|
+
const child = nestedChildStackName$1(stackName, logicalId);
|
|
20620
|
+
if (((await setup.stateBackend.loadRollbackJournal(child, region).catch(() => null))?.segments ?? []).some((s) => s.runId === segment.runId && s.reason !== "nested-pending-parent" && splitImportedOps(s.operations, s).replay.length > 0)) throw new Error(`Nested stack ${plainOrDescribed(child, "nested stack name")} failed during a deploy this journal records, and its own journal still holds that deploy's completed operations. Re-run with --revert-failed so they are reverted in order with the parent's.`);
|
|
20621
|
+
}
|
|
20622
|
+
}
|
|
20623
|
+
const baseState = stateData.state;
|
|
20624
|
+
const refusalRecovery = {
|
|
20625
|
+
profile: options.profile,
|
|
20626
|
+
stateBucket: setup.bucket,
|
|
20627
|
+
statePrefix: options.statePrefix
|
|
20628
|
+
};
|
|
20629
|
+
refuseMalformedState(baseState, stackName, region, refusalRecovery);
|
|
20630
|
+
refuseMalformedOrphans(baseState, stackName, region, refusalRecovery);
|
|
20631
|
+
refuseMalformedOrphanRecords(baseState, stackName, region, refusalRecovery);
|
|
20632
|
+
refuseDivergentRecordRegionForRollback(baseState, stackName, region, stateData.divergentBodyRegion, journal.segments.flatMap((seg) => seg.failedOperations ?? []).filter((op) => op.physicalIdRecoveredFromError === true).length);
|
|
20633
|
+
const stateResources = { ...baseState.resources };
|
|
20634
|
+
const mintedOrphans = [];
|
|
20635
|
+
const rolledBackCreates = [];
|
|
20636
|
+
const supersededHost = {};
|
|
20637
|
+
const orphanLogicalIds = new Set(options.orphan ?? []);
|
|
20638
|
+
const newestSegment = journal.segments[journal.segments.length - 1];
|
|
20639
|
+
if (newestSegment?.roleArn && !options.roleArn) {
|
|
20640
|
+
const roleArnIsPlain = isIamRoleArn(newestSegment.roleArn) && safeRoleArn(newestSegment.roleArn) === newestSegment.roleArn;
|
|
20641
|
+
logger.info((roleArnIsPlain ? `Note: the failed deploy ran with --role-arn ${safeRoleArn(newestSegment.roleArn)}; ` : "Note: the failed deploy ran with --role-arn and a role ARN that is not a plain identifier (read it from the rollback journal); ") + `this rollback is running with ambient credentials (pass --role-arn to match).`);
|
|
20642
|
+
}
|
|
20643
|
+
let fallbackSkipPrefix;
|
|
20644
|
+
const legacySkipPrefix = () => fallbackSkipPrefix ??= resolveSkipPrefix({ quiet: true });
|
|
20645
|
+
const legacySegments = journal.segments.filter((s) => s.skipPrefix === void 0).length;
|
|
20646
|
+
if (legacySegments > 0) logger.warn(safeMsg`${legacySegments} of ${journal.segments.length} rollback journal segment(s) ` + "were recorded by a cdkd that did not record the user-supplied-name prefix setting; replaying them with the stack-name prefix " + (legacySkipPrefix() ? "SKIPPED" : "KEPT") + " on user-supplied physical names (CDKD_PREFIX_USER_SUPPLIED_NAMES / context.cdkd.prefixUserSuppliedNames in ./cdk.json / the default). If the failed deploy ran with --prefix-user-supplied-names, re-run with CDKD_PREFIX_USER_SUPPLIED_NAMES=true instead.");
|
|
20647
|
+
const createTokenLedger = ledgerForStack(setup.stateBackend, stackName, region);
|
|
20648
|
+
const inSegmentScope = (segment, fn) => withSkipPrefix(segment.skipPrefix ?? legacySkipPrefix(), () => withStackScope(nameScopeOf(stackName, stackInstanceId, stateData?.state), () => withCreateTokenLedger(createTokenLedger, fn)));
|
|
20649
|
+
logger.info(`\nRollback plan for ${stackRegionShown(stackName, region)}:`);
|
|
20650
|
+
if (!stackRegionIsPlain(stackName, region)) logger.info(STACK_REGION_DESCRIBED_NOTE);
|
|
20651
|
+
if (orphanedPending > 0) logger.info(safeMsg`\n Discard ${orphanedPending} record(s) of nested deploys whose parent run no longer ` + `has a journal to replay them (nothing else would ever replay them).`);
|
|
20652
|
+
const planStateView = { ...stateResources };
|
|
20653
|
+
await printRollbackPlanSegments({
|
|
20654
|
+
journal,
|
|
20655
|
+
logger,
|
|
20656
|
+
options,
|
|
20657
|
+
inSegmentScope,
|
|
20658
|
+
planStateView,
|
|
20659
|
+
providerRegistry,
|
|
20660
|
+
region,
|
|
20661
|
+
setup,
|
|
20662
|
+
stackName,
|
|
20663
|
+
orphanLogicalIds
|
|
20664
|
+
});
|
|
20665
|
+
logger.info("");
|
|
20666
|
+
if (!skipConfirmation) {
|
|
20667
|
+
if (!await confirm(`Roll back ${stackRegionShown(stackName, region)}` + (options.removeProtection === true ? ", TURNING DELETION PROTECTION OFF on the resources it deletes from this stack and the nested stacks it reverts?" : "?"))) {
|
|
20668
|
+
logger.info("Rollback cancelled");
|
|
20669
|
+
return;
|
|
20670
|
+
}
|
|
20671
|
+
}
|
|
20672
|
+
if (orphanedPending > 0) {
|
|
20673
|
+
const discarded = await setup.stateBackend.dropRollbackJournalSegments(stackName, region, (s) => s.reason === NESTED_PENDING_PARENT_REASON);
|
|
20674
|
+
logger.info(safeMsg`Discarded ${discarded} record(s) of nested deploys whose parent run no longer has a ` + `journal to replay them.`);
|
|
20675
|
+
}
|
|
20676
|
+
const eventRecorder = startRunRecorder({
|
|
20677
|
+
backend: setup.stateBackend,
|
|
20678
|
+
stackName,
|
|
20679
|
+
region,
|
|
20680
|
+
command: "rollback"
|
|
20681
|
+
});
|
|
20682
|
+
const ctx = {
|
|
20683
|
+
providerRegistry,
|
|
20684
|
+
region,
|
|
20685
|
+
logger: logger.child("rollback"),
|
|
20686
|
+
recordEvent: (e) => eventRecorder.record(maskEventTextWithBoundBags(e)),
|
|
20687
|
+
finalSnapshotClients,
|
|
20688
|
+
skipFinalSnapshot: options.skipFinalSnapshot === true,
|
|
20689
|
+
...options.removeProtection === true && { removeProtection: true },
|
|
20690
|
+
foreignHolder: makeForeignHolderScan(setup.stateBackend)({
|
|
20691
|
+
stackName,
|
|
20692
|
+
region
|
|
20693
|
+
}),
|
|
20694
|
+
importedProducerRegions: producerRegionsFromState(baseState),
|
|
20695
|
+
...(stackName.includes("~") || baseState.parentStack !== void 0) && { producerRegionsIncomplete: true }
|
|
20696
|
+
};
|
|
20697
|
+
let currentEtag = stateData.etag;
|
|
20698
|
+
const saveState = async () => {
|
|
20699
|
+
if (declinedDivergentRewrite) return;
|
|
20700
|
+
const { skippedOutputs: _droppedByRollback, ...carriedState } = baseState;
|
|
20701
|
+
const next = () => ({
|
|
20702
|
+
...carriedState,
|
|
20703
|
+
...stackInstanceIdCarriedFrom(baseState),
|
|
20704
|
+
...supersededAfterRollback(baseState, supersededHost),
|
|
20705
|
+
version: 15,
|
|
20706
|
+
region,
|
|
20707
|
+
resources: { ...stateResources },
|
|
20708
|
+
...orphansAfterRollback(baseState, mintedOrphans),
|
|
20709
|
+
...retiredAfterRollback(baseState, mintedOrphans, rolledBackCreates),
|
|
20710
|
+
lastModified: Date.now()
|
|
20711
|
+
});
|
|
20712
|
+
try {
|
|
20713
|
+
currentEtag = await setup.stateBackend.saveState(stackName, region, next(), { ...currentEtag !== void 0 && { expectedEtag: currentEtag } });
|
|
20714
|
+
} catch {
|
|
20715
|
+
try {
|
|
20716
|
+
const fresh = await setup.stateBackend.getState(stackName, region);
|
|
20717
|
+
if (fresh?.divergentBodyRegion !== void 0) {
|
|
20718
|
+
declinedDivergentRewrite = true;
|
|
20719
|
+
declinedDivergentReason = divergedDuringRollbackMessage(fresh.divergentBodyRegion);
|
|
20720
|
+
throw new Error(declinedDivergentReason);
|
|
20721
|
+
}
|
|
20722
|
+
currentEtag = await setup.stateBackend.saveState(stackName, region, next(), { ...fresh?.etag !== void 0 && { expectedEtag: fresh.etag } });
|
|
20723
|
+
} catch (retryError) {
|
|
20724
|
+
if (declinedDivergentRewrite) {
|
|
20725
|
+
logger.warn(`Did not persist state after a rollback operation: ${declinedDivergentReason}. The resource was reverted in AWS. Repair the record's region field to match the key it is stored under, then run the rollback again to reconcile state.`);
|
|
20726
|
+
return;
|
|
20727
|
+
}
|
|
20728
|
+
logger.warn(`Failed to persist state after a rollback operation: ${backendErrorText(retryError, stackName, region)}. The resource was reverted in AWS; re-run the rollback to reconcile state.` + rerunRollback(stackName));
|
|
20729
|
+
}
|
|
20730
|
+
}
|
|
20731
|
+
};
|
|
20732
|
+
const oldestInitialDeploy = journal.segments[0]?.initialDeploy === true;
|
|
20733
|
+
let totalFailures = 0;
|
|
20734
|
+
let totalWarnings = 0;
|
|
20735
|
+
const failedOrphanIds = [];
|
|
20736
|
+
const inlinePolicyWriters = new RollbackInlinePolicyWriters();
|
|
20737
|
+
const failedOpsPrinting = journaledOrphanPrintingBag(journal.segments.flatMap((s) => s.failedOperations ?? []), stateResources);
|
|
20738
|
+
try {
|
|
20739
|
+
while (journal.segments.length > 0) {
|
|
20740
|
+
if (interrupted) break;
|
|
20741
|
+
const segment = journal.segments[journal.segments.length - 1];
|
|
20742
|
+
const completedSplit = splitImportedOps(segment.operations, segment, orphanLogicalIds);
|
|
20743
|
+
const completedOps = completedSplit.replay;
|
|
20744
|
+
const displaced = [...completedSplit.displaced, ...splitImportedOps(segment.failedOperations ?? [], segment).displaced];
|
|
20745
|
+
for (const op of displaced) logger.warn(displacedOpLabel(op, segment).trim());
|
|
20746
|
+
recordDisplacedSkips(ctx.recordEvent, stackName, displaced);
|
|
20747
|
+
let nestedRun;
|
|
20748
|
+
const result = await withNestedStackContext({
|
|
20749
|
+
stateBackend: setup.stateBackend,
|
|
20750
|
+
lockManager: setup.lockManager,
|
|
20751
|
+
providerRegistry,
|
|
20752
|
+
parentStackName: stackName,
|
|
20753
|
+
parentRegion: region,
|
|
20754
|
+
accountId: "unknown",
|
|
20755
|
+
awsClients: finalSnapshotClients,
|
|
20756
|
+
stateBucket: setup.bucket,
|
|
20757
|
+
exportIndexStore: setup.exportIndexStore,
|
|
20758
|
+
destroyOptions: {
|
|
20759
|
+
...options.profile && { profile: options.profile },
|
|
20760
|
+
statePrefix: options.statePrefix,
|
|
20761
|
+
...options.skipFinalSnapshot === true && { skipFinalSnapshot: true },
|
|
20762
|
+
...options.removeProtection === true && { removeProtection: true }
|
|
20763
|
+
}
|
|
20764
|
+
}, () => withNestedRevertRun(segment.runId, (run) => {
|
|
20765
|
+
nestedRun = run;
|
|
20766
|
+
return inSegmentScope(segment, async () => {
|
|
20767
|
+
let failedOpFailures = 0;
|
|
20768
|
+
let failedOpWarnings = 0;
|
|
20769
|
+
const failedOps = splitImportedOps(segment.failedOperations ?? [], segment);
|
|
20770
|
+
const failedForGuard = segment.failedOperations ?? [];
|
|
20771
|
+
const failedToReplay = failedOpsToReplay(failedOps.replay, options.revertFailed === true);
|
|
20772
|
+
if (failedToReplay.length > 0) {
|
|
20773
|
+
const failedResult = await withPrintingSecrets(failedOpsPrinting, () => withPrintingSecrets(journaledOrphanPrintingBag(failedToReplay, stateResources), () => replayFailedOperations(failedToReplay, stateResources, stackName, ctx, {
|
|
20774
|
+
afterOp: saveState,
|
|
20775
|
+
isInterrupted: () => interrupted,
|
|
20776
|
+
emitEnvelope: completedOps.length === 0,
|
|
20777
|
+
onOrphan: (record) => mintedOrphans.push(record),
|
|
20778
|
+
onRolledBackCreate: (create) => rolledBackCreates.push(create),
|
|
20779
|
+
inlinePolicyWriters
|
|
20780
|
+
})));
|
|
20781
|
+
failedOpFailures = failedResult.failures;
|
|
20782
|
+
failedOpWarnings = failedResult.warnings;
|
|
20783
|
+
for (const op of failedResult.remainingFailedOps) if (isJournaledOrphan(op) && op.physicalIdRecoveredFromError === true) failedOrphanIds.push(op.logicalId);
|
|
20784
|
+
const remaining = [
|
|
20785
|
+
...failedOps.imported,
|
|
20786
|
+
...failedOps.displaced,
|
|
20787
|
+
...failedOps.replay.filter((op) => !failedToReplay.includes(op)),
|
|
20788
|
+
...failedResult.remainingFailedOps,
|
|
20789
|
+
...completedOps.length > 0 ? failedToReplay.filter((op) => seedsDeleteFirstGuard(op) && !failedResult.remainingFailedOps.includes(op)) : []
|
|
20790
|
+
];
|
|
20791
|
+
if (!declinedDivergentRewrite && remaining.length !== (segment.failedOperations ?? []).length) try {
|
|
20792
|
+
await setup.stateBackend.setRollbackJournalFailedOperations(stackName, region, remaining);
|
|
20793
|
+
if (remaining.length === 0) delete segment.failedOperations;
|
|
20794
|
+
else segment.failedOperations = remaining;
|
|
20795
|
+
} catch (stripError) {
|
|
20796
|
+
logger.warn(safeMsg`Failed to strip replayed failed-ops from the journal: ${backendErrorText(stripError, stackName, region)}`);
|
|
20797
|
+
}
|
|
20798
|
+
if (failedResult.interrupted) return {
|
|
20799
|
+
failures: failedOpFailures,
|
|
20800
|
+
warnings: failedOpWarnings,
|
|
20801
|
+
interrupted: true
|
|
20802
|
+
};
|
|
20803
|
+
}
|
|
20804
|
+
const replayResult = await withPrintingSecrets(journaledOrphanPrintingBag(completedReplayEntries(completedOps), stateResources), () => replayRollback(completedOps, stateResources, stackName, ctx, {
|
|
20805
|
+
orphanLogicalIds,
|
|
20806
|
+
afterOp: saveState,
|
|
20807
|
+
isInterrupted: () => interrupted,
|
|
20808
|
+
onOrphan: (record) => mintedOrphans.push(record),
|
|
20809
|
+
onRolledBackCreate: (create) => rolledBackCreates.push(create),
|
|
20810
|
+
inlinePolicyWriters,
|
|
20811
|
+
failedOperations: failedForGuard,
|
|
20812
|
+
onSuperseded: (entry) => addSuperseded(supersededHost, entry),
|
|
20813
|
+
onSupersededSettled: (entry) => removeSuperseded(supersededHost, entry)
|
|
20814
|
+
}));
|
|
20815
|
+
return {
|
|
20816
|
+
failures: replayResult.failures + failedOpFailures,
|
|
20817
|
+
warnings: replayResult.warnings + failedOpWarnings,
|
|
20818
|
+
interrupted: replayResult.interrupted
|
|
20819
|
+
};
|
|
20820
|
+
});
|
|
20821
|
+
}));
|
|
20822
|
+
totalFailures += result.failures;
|
|
20823
|
+
totalWarnings += result.warnings + (nestedRun?.warnings ?? 0) + displaced.length;
|
|
20824
|
+
if (declinedDivergentRewrite) break;
|
|
20825
|
+
if (result.interrupted) {
|
|
20826
|
+
interrupted = true;
|
|
20827
|
+
break;
|
|
20828
|
+
}
|
|
20829
|
+
if (result.failures > 0) break;
|
|
20830
|
+
await setup.stateBackend.popRollbackJournalSegment(stackName, region);
|
|
20831
|
+
journal.segments.pop();
|
|
20832
|
+
await dropSettledNestedJournals({
|
|
20833
|
+
stateBackend: setup.stateBackend,
|
|
20834
|
+
lockManager: setup.lockManager,
|
|
20835
|
+
parentStackName: stackName,
|
|
20836
|
+
region,
|
|
20837
|
+
settled: nestedRun?.settled ?? /* @__PURE__ */ new Map(),
|
|
20838
|
+
runId: segment.runId,
|
|
20839
|
+
logger
|
|
20840
|
+
});
|
|
20841
|
+
}
|
|
20842
|
+
} finally {
|
|
20843
|
+
await eventRecorder.finalize(totalFailures > 0 || interrupted || declinedDivergentRewrite ? "FAILED" : "SUCCEEDED");
|
|
20844
|
+
}
|
|
20845
|
+
const survivingOrphans = orphansAfterRollback(baseState, mintedOrphans).orphans ?? [];
|
|
20846
|
+
if (journal.segments.length === 0 && oldestInitialDeploy && Object.keys(stateResources).length === 0 && survivingOrphans.length === 0 && !holdsSupersededResources(baseState)) {
|
|
20847
|
+
await setup.stateBackend.deleteState(stackName, region);
|
|
20848
|
+
await recordRetainedForReadoption(setup.stateBackend, stackName, region, [], logger);
|
|
20849
|
+
await releaseRegistryMarkerQuietly(setup.stateBackend, stackName, region, logger);
|
|
20850
|
+
logger.info(`State for ${stackRegionShown(stackName, region)} removed (stack fully rolled back).`);
|
|
20851
|
+
}
|
|
20852
|
+
if (declinedDivergentRewrite) throw new PartialFailureError(`Rollback stopped: ${declinedDivergentReason}.` + (totalFailures > 0 ? ` ${totalFailures} operation(s) also failed.` : "") + " Journal preserved (this segment, any older ones, and their failed operations) — re-run the rollback once the record's region field matches its key.");
|
|
20853
|
+
if (interrupted) throw new PartialFailureError(`Rollback interrupted. Journal preserved — re-run the rollback to finish.` + rerunRollback(stackName));
|
|
20854
|
+
if (totalFailures > 0) throw new PartialFailureError(`Rollback completed with ${totalFailures} failed operation(s). Journal preserved — re-run the rollback to retry.` + dropFailedHint(stackName, region, failedOrphanIds) + rerunRollback(stackName));
|
|
20855
|
+
if (totalWarnings > 0) throw new PartialFailureError(`Rollback completed with ${totalWarnings} skipped/unrecoverable operation(s) (see warnings above).`);
|
|
20856
|
+
logger.info(`\nRollback of ${stackRegionShown(stackName, region)} complete.`);
|
|
20857
|
+
} finally {
|
|
20858
|
+
try {
|
|
20859
|
+
await setup.lockManager.releaseLock(stackName, region).catch((err) => {
|
|
20860
|
+
logger.warn(`Failed to release lock for ${quotedOrDescribed(stackName, "stack name")} (${plainOrDescribed(region, "region")}): ${backendErrorText(err, stackName, region)}`);
|
|
20861
|
+
});
|
|
20862
|
+
} finally {
|
|
20863
|
+
process.removeListener("SIGINT", sigintHandler);
|
|
20864
|
+
unforwardSigterm();
|
|
20865
|
+
}
|
|
20866
|
+
}
|
|
20867
|
+
}
|
|
20868
|
+
|
|
20869
|
+
// src/cli/commands/rollback/command.ts
|
|
20430
20870
|
async function rollbackCommand(stackArg, options) {
|
|
20431
20871
|
const providerClasses = await loadProviderClasses();
|
|
20432
20872
|
const logger = getLogger();
|
|
@@ -20485,328 +20925,17 @@ async function rollbackCommand(stackArg, options) {
|
|
|
20485
20925
|
});
|
|
20486
20926
|
setAwsClients(stackAwsClients);
|
|
20487
20927
|
const finalSnapshotClients = stackAwsClients;
|
|
20488
|
-
await runWithStackAwsClients(stackAwsClients,
|
|
20489
|
-
|
|
20490
|
-
|
|
20491
|
-
|
|
20492
|
-
|
|
20493
|
-
|
|
20494
|
-
|
|
20495
|
-
|
|
20496
|
-
|
|
20497
|
-
|
|
20498
|
-
|
|
20499
|
-
process.on("SIGINT", sigintHandler);
|
|
20500
|
-
const unforwardSigterm = forwardSigtermToSigint();
|
|
20501
|
-
try {
|
|
20502
|
-
await setup.lockManager.acquireLockWithRetry(stackName, region, void 0, "rollback");
|
|
20503
|
-
} catch (error) {
|
|
20504
|
-
process.removeListener("SIGINT", sigintHandler);
|
|
20505
|
-
unforwardSigterm();
|
|
20506
|
-
throw error;
|
|
20507
|
-
}
|
|
20508
|
-
try {
|
|
20509
|
-
const stateData = await setup.stateBackend.getState(stackName, region);
|
|
20510
|
-
const stackInstanceId = stackInstanceIdOf(stateData?.state, displayStackName(stackName));
|
|
20511
|
-
let journal = await setup.stateBackend.loadRollbackJournal(stackName, region);
|
|
20512
|
-
if (await resolvePendingCloudControlRequests({
|
|
20513
|
-
journal: setup.stateBackend,
|
|
20514
|
-
loaded: journal,
|
|
20515
|
-
reader: () => providerRegistry.getCloudControlProvider(),
|
|
20516
|
-
stackName,
|
|
20517
|
-
region,
|
|
20518
|
-
command: "rollback",
|
|
20519
|
-
logger,
|
|
20520
|
-
stateResources: stateData?.state.resources,
|
|
20521
|
-
stackInstanceId: stateData === null ? () => setup.stateBackend.readStackInstanceSibling(stackName, region) : stackInstanceId
|
|
20522
|
-
})) journal = await setup.stateBackend.loadRollbackJournal(stackName, region);
|
|
20523
|
-
const orphanedPending = journal ? await judgeNestedPendingRecords(setup, stackName, region, journal.segments) : 0;
|
|
20524
|
-
if (journal && orphanedPending > 0) journal = {
|
|
20525
|
-
...journal,
|
|
20526
|
-
segments: journal.segments.filter((s) => s.reason !== NESTED_PENDING_PARENT_REASON)
|
|
20527
|
-
};
|
|
20528
|
-
if (!journal || journal.segments.length === 0 && orphanedPending === 0) throw new Error(`Nothing to roll back for ${plainOrDescribed(stackName, "stack name")} (${plainOrDescribed(region, "region")}). Run 'cdkd deploy' to (re)deploy, or 'cdkd destroy' to clean up.`);
|
|
20529
|
-
applyCrossPrefixScan(await crossPrefixScan, {
|
|
20530
|
-
stackName,
|
|
20531
|
-
region,
|
|
20532
|
-
bucket: setup.bucket,
|
|
20533
|
-
recovery: {
|
|
20534
|
-
profile: options.profile,
|
|
20535
|
-
stateBucket: setup.bucket
|
|
20536
|
-
}
|
|
20537
|
-
}, "rollback", (message) => logger.warn(message), (message) => logger.info(message));
|
|
20538
|
-
if (!stateData) throw new Error(`Rollback journal exists for ${safeStack(stackName)} (${safe(region)}) but its state.json is missing (keys: ${safe(setup.prefix)}/${safeStack(stackName)}/${safe(region)}/state.json and .../rollback-journal.json). State appears corrupted — inspect the bucket manually.`);
|
|
20539
|
-
demoteSupersededOrphans(journal.segments, Array.isArray(stateData.state.orphans) ? stateData.state.orphans : []);
|
|
20540
|
-
if (!options.revertFailed) for (const segment of journal.segments) {
|
|
20541
|
-
const failedRows = splitImportedOps(segment.failedOperations ?? [], segment).replay;
|
|
20542
|
-
for (const logicalId of revertedNestedRowIds(failedRows)) {
|
|
20543
|
-
const child = nestedChildStackName$1(stackName, logicalId);
|
|
20544
|
-
if (((await setup.stateBackend.loadRollbackJournal(child, region).catch(() => null))?.segments ?? []).some((s) => s.runId === segment.runId && s.reason !== "nested-pending-parent" && splitImportedOps(s.operations, s).replay.length > 0)) throw new Error(`Nested stack ${plainOrDescribed(child, "nested stack name")} failed during a deploy this journal records, and its own journal still holds that deploy's completed operations. Re-run with --revert-failed so they are reverted in order with the parent's.`);
|
|
20545
|
-
}
|
|
20546
|
-
}
|
|
20547
|
-
const baseState = stateData.state;
|
|
20548
|
-
const refusalRecovery = {
|
|
20549
|
-
profile: options.profile,
|
|
20550
|
-
stateBucket: setup.bucket,
|
|
20551
|
-
statePrefix: options.statePrefix
|
|
20552
|
-
};
|
|
20553
|
-
refuseMalformedState(baseState, stackName, region, refusalRecovery);
|
|
20554
|
-
refuseMalformedOrphans(baseState, stackName, region, refusalRecovery);
|
|
20555
|
-
refuseMalformedOrphanRecords(baseState, stackName, region, refusalRecovery);
|
|
20556
|
-
refuseDivergentRecordRegionForRollback(baseState, stackName, region, stateData.divergentBodyRegion, journal.segments.flatMap((seg) => seg.failedOperations ?? []).filter((op) => op.physicalIdRecoveredFromError === true).length);
|
|
20557
|
-
const stateResources = { ...baseState.resources };
|
|
20558
|
-
const mintedOrphans = [];
|
|
20559
|
-
const rolledBackCreates = [];
|
|
20560
|
-
const supersededHost = {};
|
|
20561
|
-
const orphanLogicalIds = new Set(options.orphan ?? []);
|
|
20562
|
-
const newestSegment = journal.segments[journal.segments.length - 1];
|
|
20563
|
-
if (newestSegment?.roleArn && !options.roleArn) {
|
|
20564
|
-
const roleArnIsPlain = isIamRoleArn(newestSegment.roleArn) && safeRoleArn(newestSegment.roleArn) === newestSegment.roleArn;
|
|
20565
|
-
logger.info((roleArnIsPlain ? `Note: the failed deploy ran with --role-arn ${safeRoleArn(newestSegment.roleArn)}; ` : "Note: the failed deploy ran with --role-arn and a role ARN that is not a plain identifier (read it from the rollback journal); ") + `this rollback is running with ambient credentials (pass --role-arn to match).`);
|
|
20566
|
-
}
|
|
20567
|
-
let fallbackSkipPrefix;
|
|
20568
|
-
const legacySkipPrefix = () => fallbackSkipPrefix ??= resolveSkipPrefix({ quiet: true });
|
|
20569
|
-
const legacySegments = journal.segments.filter((s) => s.skipPrefix === void 0).length;
|
|
20570
|
-
if (legacySegments > 0) logger.warn(safeMsg`${legacySegments} of ${journal.segments.length} rollback journal segment(s) ` + "were recorded by a cdkd that did not record the user-supplied-name prefix setting; replaying them with the stack-name prefix " + (legacySkipPrefix() ? "SKIPPED" : "KEPT") + " on user-supplied physical names (CDKD_PREFIX_USER_SUPPLIED_NAMES / context.cdkd.prefixUserSuppliedNames in ./cdk.json / the default). If the failed deploy ran with --prefix-user-supplied-names, re-run with CDKD_PREFIX_USER_SUPPLIED_NAMES=true instead.");
|
|
20571
|
-
const createTokenLedger = ledgerForStack(setup.stateBackend, stackName, region);
|
|
20572
|
-
const inSegmentScope = (segment, fn) => withSkipPrefix(segment.skipPrefix ?? legacySkipPrefix(), () => withStackScope(nameScopeOf(stackName, stackInstanceId, stateData?.state), () => withCreateTokenLedger(createTokenLedger, fn)));
|
|
20573
|
-
logger.info(`\nRollback plan for ${stackRegionShown(stackName, region)}:`);
|
|
20574
|
-
if (!stackRegionIsPlain(stackName, region)) logger.info(STACK_REGION_DESCRIBED_NOTE);
|
|
20575
|
-
if (orphanedPending > 0) logger.info(safeMsg`\n Discard ${orphanedPending} record(s) of nested deploys whose parent run no longer ` + `has a journal to replay them (nothing else would ever replay them).`);
|
|
20576
|
-
const planStateView = { ...stateResources };
|
|
20577
|
-
for (let s = journal.segments.length - 1; s >= 0; s--) {
|
|
20578
|
-
const segment = journal.segments[s];
|
|
20579
|
-
logger.info(`\n Segment ${s + 1}/${journal.segments.length} (${safe(segment.reason)}${segment.runId ? `, run ${safe(segment.runId)}` : ""}):`);
|
|
20580
|
-
const failedOps = splitImportedOps(segment.failedOperations ?? [], segment);
|
|
20581
|
-
const completedOps = splitImportedOps(segment.operations, segment, orphanLogicalIds);
|
|
20582
|
-
for (const op of [...failedOps.imported, ...completedOps.imported]) logger.info(importedOpLabel(op));
|
|
20583
|
-
for (const op of [...failedOps.displaced, ...completedOps.displaced]) logger.info(displacedOpLabel(op, segment));
|
|
20584
|
-
const failedToReplay = failedOpsToReplay(failedOps.replay, options.revertFailed === true);
|
|
20585
|
-
if (failedOps.replay.length > 0) {
|
|
20586
|
-
if (failedToReplay.length > 0) {
|
|
20587
|
-
const failedPlan = await inSegmentScope(segment, () => recheckFailedPlan(planFailedOps(failedToReplay, planStateView), planStateView, {
|
|
20588
|
-
providerRegistry,
|
|
20589
|
-
region,
|
|
20590
|
-
logger
|
|
20591
|
-
}));
|
|
20592
|
-
for (const item of failedPlan) {
|
|
20593
|
-
logger.info(failedActionLabel(item, options.skipFinalSnapshot === true));
|
|
20594
|
-
if (revertedNestedRowIds([item.op]).length > 0) for (const line of await previewNestedChildRevert(setup.stateBackend, nestedChildStackName$1(stackName, item.op.logicalId), region, segment.runId, options.skipFinalSnapshot === true)) logger.info(line);
|
|
20595
|
-
}
|
|
20596
|
-
applyFailedPlanToPreview(failedPlan, planStateView, options.skipFinalSnapshot === true);
|
|
20597
|
-
}
|
|
20598
|
-
for (const fop of failedOps.replay.filter((op) => !failedToReplay.includes(op))) logger.info(` - (left as-is) ${logicalIdShown(fop.logicalId)} (${resourceTypeShown(fop.resourceType)}) — its ${plainOrDescribed(fop.changeType, "change type")} FAILED mid-deploy; pass --revert-failed to attempt reverting it`);
|
|
20599
|
-
}
|
|
20600
|
-
const plan = planRollback(completedOps.replay, planStateView, orphanLogicalIds);
|
|
20601
|
-
for (const item of plan) {
|
|
20602
|
-
logger.info(actionLabel(item, options.skipFinalSnapshot === true));
|
|
20603
|
-
if (revertedNestedRowIds([item.op]).length > 0) for (const line of await previewNestedChildRevert(setup.stateBackend, nestedChildStackName$1(stackName, item.op.logicalId), region, segment.runId, options.skipFinalSnapshot === true)) logger.info(line);
|
|
20604
|
-
}
|
|
20605
|
-
applyPlanToPreview(plan, planStateView, options.skipFinalSnapshot === true);
|
|
20606
|
-
}
|
|
20607
|
-
logger.info("");
|
|
20608
|
-
if (!skipConfirmation) {
|
|
20609
|
-
if (!await confirm(`Roll back ${stackRegionShown(stackName, region)}` + (options.removeProtection === true ? ", TURNING DELETION PROTECTION OFF on the resources it deletes from this stack and the nested stacks it reverts?" : "?"))) {
|
|
20610
|
-
logger.info("Rollback cancelled");
|
|
20611
|
-
return;
|
|
20612
|
-
}
|
|
20613
|
-
}
|
|
20614
|
-
if (orphanedPending > 0) {
|
|
20615
|
-
const discarded = await setup.stateBackend.dropRollbackJournalSegments(stackName, region, (s) => s.reason === NESTED_PENDING_PARENT_REASON);
|
|
20616
|
-
logger.info(safeMsg`Discarded ${discarded} record(s) of nested deploys whose parent run no longer has a ` + `journal to replay them.`);
|
|
20617
|
-
}
|
|
20618
|
-
const eventRecorder = startRunRecorder({
|
|
20619
|
-
backend: setup.stateBackend,
|
|
20620
|
-
stackName,
|
|
20621
|
-
region,
|
|
20622
|
-
command: "rollback"
|
|
20623
|
-
});
|
|
20624
|
-
const ctx = {
|
|
20625
|
-
providerRegistry,
|
|
20626
|
-
region,
|
|
20627
|
-
logger: logger.child("rollback"),
|
|
20628
|
-
recordEvent: (e) => eventRecorder.record(maskEventTextWithBoundBags(e)),
|
|
20629
|
-
finalSnapshotClients,
|
|
20630
|
-
skipFinalSnapshot: options.skipFinalSnapshot === true,
|
|
20631
|
-
...options.removeProtection === true && { removeProtection: true },
|
|
20632
|
-
foreignHolder: makeForeignHolderScan(setup.stateBackend)({
|
|
20633
|
-
stackName,
|
|
20634
|
-
region
|
|
20635
|
-
}),
|
|
20636
|
-
importedProducerRegions: producerRegionsFromState(baseState),
|
|
20637
|
-
...(stackName.includes("~") || baseState.parentStack !== void 0) && { producerRegionsIncomplete: true }
|
|
20638
|
-
};
|
|
20639
|
-
let currentEtag = stateData.etag;
|
|
20640
|
-
const saveState = async () => {
|
|
20641
|
-
if (declinedDivergentRewrite) return;
|
|
20642
|
-
const { skippedOutputs: _droppedByRollback, ...carriedState } = baseState;
|
|
20643
|
-
const next = () => ({
|
|
20644
|
-
...carriedState,
|
|
20645
|
-
...stackInstanceIdCarriedFrom(baseState),
|
|
20646
|
-
...supersededAfterRollback(baseState, supersededHost),
|
|
20647
|
-
version: 15,
|
|
20648
|
-
region,
|
|
20649
|
-
resources: { ...stateResources },
|
|
20650
|
-
...orphansAfterRollback(baseState, mintedOrphans),
|
|
20651
|
-
...retiredAfterRollback(baseState, mintedOrphans, rolledBackCreates),
|
|
20652
|
-
lastModified: Date.now()
|
|
20653
|
-
});
|
|
20654
|
-
try {
|
|
20655
|
-
currentEtag = await setup.stateBackend.saveState(stackName, region, next(), { ...currentEtag !== void 0 && { expectedEtag: currentEtag } });
|
|
20656
|
-
} catch {
|
|
20657
|
-
try {
|
|
20658
|
-
const fresh = await setup.stateBackend.getState(stackName, region);
|
|
20659
|
-
if (fresh?.divergentBodyRegion !== void 0) {
|
|
20660
|
-
declinedDivergentRewrite = true;
|
|
20661
|
-
declinedDivergentReason = divergedDuringRollbackMessage(fresh.divergentBodyRegion);
|
|
20662
|
-
throw new Error(declinedDivergentReason);
|
|
20663
|
-
}
|
|
20664
|
-
currentEtag = await setup.stateBackend.saveState(stackName, region, next(), { ...fresh?.etag !== void 0 && { expectedEtag: fresh.etag } });
|
|
20665
|
-
} catch (retryError) {
|
|
20666
|
-
if (declinedDivergentRewrite) {
|
|
20667
|
-
logger.warn(`Did not persist state after a rollback operation: ${declinedDivergentReason}. The resource was reverted in AWS. Repair the record's region field to match the key it is stored under, then run the rollback again to reconcile state.`);
|
|
20668
|
-
return;
|
|
20669
|
-
}
|
|
20670
|
-
logger.warn(`Failed to persist state after a rollback operation: ${backendErrorText(retryError, stackName, region)}. The resource was reverted in AWS; re-run the rollback to reconcile state.` + rerunRollback(stackName));
|
|
20671
|
-
}
|
|
20672
|
-
}
|
|
20673
|
-
};
|
|
20674
|
-
const oldestInitialDeploy = journal.segments[0]?.initialDeploy === true;
|
|
20675
|
-
let totalFailures = 0;
|
|
20676
|
-
let totalWarnings = 0;
|
|
20677
|
-
const failedOrphanIds = [];
|
|
20678
|
-
const inlinePolicyWriters = new RollbackInlinePolicyWriters();
|
|
20679
|
-
const failedOpsPrinting = journaledOrphanPrintingBag(journal.segments.flatMap((s) => s.failedOperations ?? []), stateResources);
|
|
20680
|
-
try {
|
|
20681
|
-
while (journal.segments.length > 0) {
|
|
20682
|
-
if (interrupted) break;
|
|
20683
|
-
const segment = journal.segments[journal.segments.length - 1];
|
|
20684
|
-
const completedSplit = splitImportedOps(segment.operations, segment, orphanLogicalIds);
|
|
20685
|
-
const completedOps = completedSplit.replay;
|
|
20686
|
-
const displaced = [...completedSplit.displaced, ...splitImportedOps(segment.failedOperations ?? [], segment).displaced];
|
|
20687
|
-
for (const op of displaced) logger.warn(displacedOpLabel(op, segment).trim());
|
|
20688
|
-
recordDisplacedSkips(ctx.recordEvent, stackName, displaced);
|
|
20689
|
-
let nestedRun;
|
|
20690
|
-
const result = await withNestedStackContext({
|
|
20691
|
-
stateBackend: setup.stateBackend,
|
|
20692
|
-
lockManager: setup.lockManager,
|
|
20693
|
-
providerRegistry,
|
|
20694
|
-
parentStackName: stackName,
|
|
20695
|
-
parentRegion: region,
|
|
20696
|
-
accountId: "unknown",
|
|
20697
|
-
awsClients: finalSnapshotClients,
|
|
20698
|
-
stateBucket: setup.bucket,
|
|
20699
|
-
exportIndexStore: setup.exportIndexStore,
|
|
20700
|
-
destroyOptions: {
|
|
20701
|
-
...options.profile && { profile: options.profile },
|
|
20702
|
-
statePrefix: options.statePrefix,
|
|
20703
|
-
...options.skipFinalSnapshot === true && { skipFinalSnapshot: true },
|
|
20704
|
-
...options.removeProtection === true && { removeProtection: true }
|
|
20705
|
-
}
|
|
20706
|
-
}, () => withNestedRevertRun(segment.runId, (run) => {
|
|
20707
|
-
nestedRun = run;
|
|
20708
|
-
return inSegmentScope(segment, async () => {
|
|
20709
|
-
let failedOpFailures = 0;
|
|
20710
|
-
let failedOpWarnings = 0;
|
|
20711
|
-
const failedOps = splitImportedOps(segment.failedOperations ?? [], segment);
|
|
20712
|
-
const failedForGuard = segment.failedOperations ?? [];
|
|
20713
|
-
const failedToReplay = failedOpsToReplay(failedOps.replay, options.revertFailed === true);
|
|
20714
|
-
if (failedToReplay.length > 0) {
|
|
20715
|
-
const failedResult = await withPrintingSecrets(failedOpsPrinting, () => withPrintingSecrets(journaledOrphanPrintingBag(failedToReplay, stateResources), () => replayFailedOperations(failedToReplay, stateResources, stackName, ctx, {
|
|
20716
|
-
afterOp: saveState,
|
|
20717
|
-
isInterrupted: () => interrupted,
|
|
20718
|
-
emitEnvelope: completedOps.length === 0,
|
|
20719
|
-
onOrphan: (record) => mintedOrphans.push(record),
|
|
20720
|
-
onRolledBackCreate: (create) => rolledBackCreates.push(create),
|
|
20721
|
-
inlinePolicyWriters
|
|
20722
|
-
})));
|
|
20723
|
-
failedOpFailures = failedResult.failures;
|
|
20724
|
-
failedOpWarnings = failedResult.warnings;
|
|
20725
|
-
for (const op of failedResult.remainingFailedOps) if (isJournaledOrphan(op) && op.physicalIdRecoveredFromError === true) failedOrphanIds.push(op.logicalId);
|
|
20726
|
-
const remaining = [
|
|
20727
|
-
...failedOps.imported,
|
|
20728
|
-
...failedOps.displaced,
|
|
20729
|
-
...failedOps.replay.filter((op) => !failedToReplay.includes(op)),
|
|
20730
|
-
...failedResult.remainingFailedOps,
|
|
20731
|
-
...completedOps.length > 0 ? failedToReplay.filter((op) => seedsDeleteFirstGuard(op) && !failedResult.remainingFailedOps.includes(op)) : []
|
|
20732
|
-
];
|
|
20733
|
-
if (!declinedDivergentRewrite && remaining.length !== (segment.failedOperations ?? []).length) try {
|
|
20734
|
-
await setup.stateBackend.setRollbackJournalFailedOperations(stackName, region, remaining);
|
|
20735
|
-
if (remaining.length === 0) delete segment.failedOperations;
|
|
20736
|
-
else segment.failedOperations = remaining;
|
|
20737
|
-
} catch (stripError) {
|
|
20738
|
-
logger.warn(safeMsg`Failed to strip replayed failed-ops from the journal: ${backendErrorText(stripError, stackName, region)}`);
|
|
20739
|
-
}
|
|
20740
|
-
if (failedResult.interrupted) return {
|
|
20741
|
-
failures: failedOpFailures,
|
|
20742
|
-
warnings: failedOpWarnings,
|
|
20743
|
-
interrupted: true
|
|
20744
|
-
};
|
|
20745
|
-
}
|
|
20746
|
-
const replayResult = await withPrintingSecrets(journaledOrphanPrintingBag(completedReplayEntries(completedOps), stateResources), () => replayRollback(completedOps, stateResources, stackName, ctx, {
|
|
20747
|
-
orphanLogicalIds,
|
|
20748
|
-
afterOp: saveState,
|
|
20749
|
-
isInterrupted: () => interrupted,
|
|
20750
|
-
onOrphan: (record) => mintedOrphans.push(record),
|
|
20751
|
-
onRolledBackCreate: (create) => rolledBackCreates.push(create),
|
|
20752
|
-
inlinePolicyWriters,
|
|
20753
|
-
failedOperations: failedForGuard,
|
|
20754
|
-
onSuperseded: (entry) => addSuperseded(supersededHost, entry),
|
|
20755
|
-
onSupersededSettled: (entry) => removeSuperseded(supersededHost, entry)
|
|
20756
|
-
}));
|
|
20757
|
-
return {
|
|
20758
|
-
failures: replayResult.failures + failedOpFailures,
|
|
20759
|
-
warnings: replayResult.warnings + failedOpWarnings,
|
|
20760
|
-
interrupted: replayResult.interrupted
|
|
20761
|
-
};
|
|
20762
|
-
});
|
|
20763
|
-
}));
|
|
20764
|
-
totalFailures += result.failures;
|
|
20765
|
-
totalWarnings += result.warnings + (nestedRun?.warnings ?? 0) + displaced.length;
|
|
20766
|
-
if (declinedDivergentRewrite) break;
|
|
20767
|
-
if (result.interrupted) {
|
|
20768
|
-
interrupted = true;
|
|
20769
|
-
break;
|
|
20770
|
-
}
|
|
20771
|
-
if (result.failures > 0) break;
|
|
20772
|
-
await setup.stateBackend.popRollbackJournalSegment(stackName, region);
|
|
20773
|
-
journal.segments.pop();
|
|
20774
|
-
await dropSettledNestedJournals({
|
|
20775
|
-
stateBackend: setup.stateBackend,
|
|
20776
|
-
lockManager: setup.lockManager,
|
|
20777
|
-
parentStackName: stackName,
|
|
20778
|
-
region,
|
|
20779
|
-
settled: nestedRun?.settled ?? /* @__PURE__ */ new Map(),
|
|
20780
|
-
runId: segment.runId,
|
|
20781
|
-
logger
|
|
20782
|
-
});
|
|
20783
|
-
}
|
|
20784
|
-
} finally {
|
|
20785
|
-
await eventRecorder.finalize(totalFailures > 0 || interrupted || declinedDivergentRewrite ? "FAILED" : "SUCCEEDED");
|
|
20786
|
-
}
|
|
20787
|
-
const survivingOrphans = orphansAfterRollback(baseState, mintedOrphans).orphans ?? [];
|
|
20788
|
-
if (journal.segments.length === 0 && oldestInitialDeploy && Object.keys(stateResources).length === 0 && survivingOrphans.length === 0 && !holdsSupersededResources(baseState)) {
|
|
20789
|
-
await setup.stateBackend.deleteState(stackName, region);
|
|
20790
|
-
await recordRetainedForReadoption(setup.stateBackend, stackName, region, [], logger);
|
|
20791
|
-
await releaseRegistryMarkerQuietly(setup.stateBackend, stackName, region, logger);
|
|
20792
|
-
logger.info(`State for ${stackRegionShown(stackName, region)} removed (stack fully rolled back).`);
|
|
20793
|
-
}
|
|
20794
|
-
if (declinedDivergentRewrite) throw new PartialFailureError(`Rollback stopped: ${declinedDivergentReason}.` + (totalFailures > 0 ? ` ${totalFailures} operation(s) also failed.` : "") + " Journal preserved (this segment, any older ones, and their failed operations) — re-run the rollback once the record's region field matches its key.");
|
|
20795
|
-
if (interrupted) throw new PartialFailureError(`Rollback interrupted. Journal preserved — re-run the rollback to finish.` + rerunRollback(stackName));
|
|
20796
|
-
if (totalFailures > 0) throw new PartialFailureError(`Rollback completed with ${totalFailures} failed operation(s). Journal preserved — re-run the rollback to retry.` + dropFailedHint(stackName, region, failedOrphanIds) + rerunRollback(stackName));
|
|
20797
|
-
if (totalWarnings > 0) throw new PartialFailureError(`Rollback completed with ${totalWarnings} skipped/unrecoverable operation(s) (see warnings above).`);
|
|
20798
|
-
logger.info(`\nRollback of ${stackRegionShown(stackName, region)} complete.`);
|
|
20799
|
-
} finally {
|
|
20800
|
-
try {
|
|
20801
|
-
await setup.lockManager.releaseLock(stackName, region).catch((err) => {
|
|
20802
|
-
logger.warn(`Failed to release lock for ${quotedOrDescribed(stackName, "stack name")} (${plainOrDescribed(region, "region")}): ${backendErrorText(err, stackName, region)}`);
|
|
20803
|
-
});
|
|
20804
|
-
} finally {
|
|
20805
|
-
process.removeListener("SIGINT", sigintHandler);
|
|
20806
|
-
unforwardSigterm();
|
|
20807
|
-
}
|
|
20808
|
-
}
|
|
20809
|
-
});
|
|
20928
|
+
await runWithStackAwsClients(stackAwsClients, () => runRollbackReplay({
|
|
20929
|
+
providerClasses,
|
|
20930
|
+
setup,
|
|
20931
|
+
options,
|
|
20932
|
+
logger,
|
|
20933
|
+
stackName,
|
|
20934
|
+
region,
|
|
20935
|
+
crossPrefixScan,
|
|
20936
|
+
finalSnapshotClients,
|
|
20937
|
+
skipConfirmation
|
|
20938
|
+
}));
|
|
20810
20939
|
} finally {
|
|
20811
20940
|
if (stackAwsClients) {
|
|
20812
20941
|
setAwsClients(setup.awsClients);
|
|
@@ -20815,97 +20944,8 @@ async function rollbackCommand(stackArg, options) {
|
|
|
20815
20944
|
setup.dispose();
|
|
20816
20945
|
}
|
|
20817
20946
|
}
|
|
20818
|
-
|
|
20819
|
-
|
|
20820
|
-
if (pending.length === 0) return 0;
|
|
20821
|
-
const lastCut = stackName.lastIndexOf("~");
|
|
20822
|
-
const parent = lastCut > 0 ? stackName.slice(0, lastCut) : void 0;
|
|
20823
|
-
const topLevel = stackName.split("~")[0];
|
|
20824
|
-
const refuse = (detail) => {
|
|
20825
|
-
throw new Error(`The rollback journal of nested stack ${safeStack(stackName)} (${safe(region)}) holds the record of a nested deploy that ${detail} Roll back the top-level stack ${safeStack(topLevel)} instead, or re-deploy it, which clears the record.`);
|
|
20826
|
-
};
|
|
20827
|
-
if (parent === void 0) return pending.length;
|
|
20828
|
-
let parentJournal;
|
|
20829
|
-
try {
|
|
20830
|
-
parentJournal = await setup.stateBackend.loadRollbackJournal(parent, region);
|
|
20831
|
-
} catch (error) {
|
|
20832
|
-
return refuse(`cannot be judged: the journal of its parent ${safeStack(parent)} could not be read (${backendErrorText(error, parent, region)}), so the record may still be needed.`);
|
|
20833
|
-
}
|
|
20834
|
-
const parentRuns = new Set((parentJournal?.segments ?? []).flatMap((s) => s.runId !== void 0 ? [s.runId] : []));
|
|
20835
|
-
if (pending.some((s) => s.runId !== void 0 && parentRuns.has(s.runId))) refuse(`its parent has not settled, which only a rollback of the top-level stack may replay.`);
|
|
20836
|
-
let lock;
|
|
20837
|
-
try {
|
|
20838
|
-
lock = await setup.lockManager.getLockInfo(topLevel, region);
|
|
20839
|
-
} catch (error) {
|
|
20840
|
-
return refuse(`cannot be judged: the lock of the top-level stack could not be read (${backendErrorText(error, topLevel, region)}).`);
|
|
20841
|
-
}
|
|
20842
|
-
if (lock && !isLockInfoExpired(lock)) refuse("may belong to a deploy still running: the top-level stack is locked. Retry once it is free.");
|
|
20843
|
-
return pending.length;
|
|
20844
|
-
}
|
|
20845
|
-
async function previewNestedChildRevert(backend, childStackName, region, runId, skipFinalSnapshot) {
|
|
20846
|
-
const plain = isPasteableIdent(childStackName);
|
|
20847
|
-
const shown = plain ? `nested stack ${childStackName}` : "a nested stack whose name is not a plain identifier";
|
|
20848
|
-
const withPointer = (lines) => plain ? lines : [...lines, ` ${NESTED_NAME_DESCRIBED_NOTE}`];
|
|
20849
|
-
if (runId === void 0) return withPointer([` (${shown}: this segment carries no deploy run id — its revert will FAIL and the segment is kept)`]);
|
|
20850
|
-
try {
|
|
20851
|
-
const [childState, journal] = await Promise.all([backend.getState(childStackName, region), backend.loadRollbackJournal(childStackName, region)]);
|
|
20852
|
-
const segments = (journal?.segments ?? []).filter((s) => s.runId === runId);
|
|
20853
|
-
if (!childState || segments.length === 0) return withPointer([` (${shown}: no journal record for this run — its revert will FAIL and the segment is kept)`]);
|
|
20854
|
-
const view = { ...childState.state.resources };
|
|
20855
|
-
const lines = [` ${shown} replays its own journal:`];
|
|
20856
|
-
for (let s = segments.length - 1; s >= 0; s--) {
|
|
20857
|
-
const childOps = splitImportedOps(segments[s].operations, segments[s]);
|
|
20858
|
-
for (const op of childOps.imported) lines.push(` ${importedOpLabel(op)}`);
|
|
20859
|
-
for (const op of childOps.displaced) lines.push(` ${displacedOpLabel(op, segments[s])}`);
|
|
20860
|
-
const childPlan = planRollback(childOps.replay, view, /* @__PURE__ */ new Set());
|
|
20861
|
-
for (const item of childPlan) lines.push(` ${actionLabel(item, skipFinalSnapshot)}`);
|
|
20862
|
-
applyPlanToPreview(childPlan, view, skipFinalSnapshot);
|
|
20863
|
-
}
|
|
20864
|
-
if (lines.length === 1) lines.push(" (nothing to undo)");
|
|
20865
|
-
return withPointer(lines);
|
|
20866
|
-
} catch (error) {
|
|
20867
|
-
return withPointer([` (${shown}: could not preview its revert: ${backendErrorText(error, childStackName, region)})`]);
|
|
20868
|
-
}
|
|
20869
|
-
}
|
|
20870
|
-
function planItemWillBeRefused(resourceType, effectiveProvisionedBy, skipFinalSnapshot) {
|
|
20871
|
-
if (skipFinalSnapshot) return false;
|
|
20872
|
-
return refusesFinalSnapshot(resourceType, effectiveProvisionedBy);
|
|
20873
|
-
}
|
|
20874
|
-
function applyPlanToPreview(plan, previewState, skipFinalSnapshot) {
|
|
20875
|
-
for (const item of plan) {
|
|
20876
|
-
const { op, action } = item;
|
|
20877
|
-
switch (action) {
|
|
20878
|
-
case "delete-with-final-snapshot":
|
|
20879
|
-
if (planItemWillBeRefused(op.resourceType, item.effectiveProvisionedBy, skipFinalSnapshot)) break;
|
|
20880
|
-
if (op.changeType === "CREATE") delete previewState[op.logicalId];
|
|
20881
|
-
break;
|
|
20882
|
-
case "delete":
|
|
20883
|
-
case "orphan-retain":
|
|
20884
|
-
case "orphan-flag":
|
|
20885
|
-
if (op.changeType === "CREATE") delete previewState[op.logicalId];
|
|
20886
|
-
break;
|
|
20887
|
-
case "revert":
|
|
20888
|
-
case "reverse-replacement":
|
|
20889
|
-
case "reverse-replacement-readopt": if (op.previousState) previewState[op.logicalId] = op.previousState;
|
|
20890
|
-
}
|
|
20891
|
-
}
|
|
20892
|
-
}
|
|
20893
|
-
function applyFailedPlanToPreview(plan, previewState, skipFinalSnapshot) {
|
|
20894
|
-
for (const item of plan) {
|
|
20895
|
-
const { op, action } = item;
|
|
20896
|
-
switch (action) {
|
|
20897
|
-
case "delete-failed-create-with-final-snapshot":
|
|
20898
|
-
if (planItemWillBeRefused(op.resourceType, item.effectiveProvisionedBy, skipFinalSnapshot)) break;
|
|
20899
|
-
if (!recordUnderIdIsNotOwn(op, previewState)) delete previewState[op.logicalId];
|
|
20900
|
-
break;
|
|
20901
|
-
case "delete-failed-create":
|
|
20902
|
-
case "orphan-failed-create-retain":
|
|
20903
|
-
if (!recordUnderIdIsNotOwn(op, previewState)) delete previewState[op.logicalId];
|
|
20904
|
-
break;
|
|
20905
|
-
case "revert-failed-update": if (op.previousState) previewState[op.logicalId] = op.previousState;
|
|
20906
|
-
}
|
|
20907
|
-
}
|
|
20908
|
-
}
|
|
20947
|
+
|
|
20948
|
+
// src/cli/commands/rollback.ts
|
|
20909
20949
|
function createRollbackCommand() {
|
|
20910
20950
|
const cmd = new Command("rollback").description("Revert a stack to its pre-deploy state after a failed --no-rollback / interrupted deploy or a partially-failed automatic rollback (state-driven, no synth needed).").argument("[stack]", "Stack name to roll back (defaults to the single journaled stack)").addOption(new Option("--force", "Skip the confirmation prompt").default(false)).addOption(new Option("--orphan <logicalId>", "Skip the given resource during replay (repeatable). Mirrors cdk rollback --orphan.").argParser((value, previous) => [...previous ?? [], value])).addOption(new Option("--revert-failed", "Also attempt to revert the resource whose operation FAILED mid-deploy. Off by default: the remote state of the failed resource is unknown, so force-applying its previous state is opt-in.").default(false)).addOption(new Option("--drop-failed <logicalId>", "Remove ONE journaled failed CREATE (a resource cdkd proved it made, journaled as its only record) from the rollback journal, after checking that resource by hand. Replays nothing and deletes nothing in AWS; every other entry is kept.")).addOption(skipFinalSnapshotOption).addOption(new Option("--remove-protection", `Turn deletion protection off before this stack's rollback deletes a resource the failed deploy left: one its state records from a completed CREATE, or one a failed CREATE left behind (a journaled orphan, or under --revert-failed the failed CREATE itself) when cdkd can prove it is that resource and no other stack holds it. A nested stack it deletes cascades the flag to that child's resources, and a nested stack it reverts carries it into that child's revert. Covers ${removeProtectionTypeList()}.`).default(false)).addOption(stackRegionOption()).addHelpText("after", [
|
|
20911
20951
|
"",
|
|
@@ -25424,6 +25464,7 @@ const SENSITIVE_ENV_KEYS = /* @__PURE__ */ new Set([
|
|
|
25424
25464
|
|
|
25425
25465
|
// src/local/rie-client.ts
|
|
25426
25466
|
const INVOKE_PATH = "/2015-03-31/functions/function/invocations";
|
|
25467
|
+
const NOT_AN_RIE_STATUS = /* @__PURE__ */ new Set([404, 405]);
|
|
25427
25468
|
async function waitForRieReady(host, port, timeoutMs = 5e3) {
|
|
25428
25469
|
const deadline = Date.now() + timeoutMs;
|
|
25429
25470
|
let lastError;
|
|
@@ -25484,6 +25525,7 @@ async function invokeRie(host, port, event, timeoutMs) {
|
|
|
25484
25525
|
clearTimeout(timer);
|
|
25485
25526
|
}
|
|
25486
25527
|
const raw = await response.text();
|
|
25528
|
+
if (NOT_AN_RIE_STATUS.has(response.status)) throw new Error(`The container answered the invoke at ${url} with HTTP ${response.status}, which the Lambda Runtime Interface Emulator never sends for that path: something else is listening on the container's port 8080 (the function's own server?). Check the container logs.`);
|
|
25487
25529
|
let payload = raw;
|
|
25488
25530
|
try {
|
|
25489
25531
|
payload = JSON.parse(raw);
|
|
@@ -25579,11 +25621,11 @@ function createContainerPool(specs, options) {
|
|
|
25579
25621
|
} else containerId = await removedIfDisposedOnFailure(name, runDetached({
|
|
25580
25622
|
image: spec.image,
|
|
25581
25623
|
mounts: [],
|
|
25582
|
-
...spec.
|
|
25624
|
+
extraMounts: [...spec.rieMount ? [spec.rieMount] : [], ...spec.profileCredentialsFile ? [{
|
|
25583
25625
|
hostPath: spec.profileCredentialsFile.hostPath,
|
|
25584
25626
|
containerPath: spec.profileCredentialsFile.containerPath,
|
|
25585
25627
|
readOnly: true
|
|
25586
|
-
}]
|
|
25628
|
+
}] : []],
|
|
25587
25629
|
env: spec.env,
|
|
25588
25630
|
...spec.sensitiveEnvKeys !== void 0 && { sensitiveEnvKeys: spec.sensitiveEnvKeys },
|
|
25589
25631
|
cmd: spec.command,
|
|
@@ -27023,6 +27065,192 @@ async function verifyImageInLocalCache(imageUri) {
|
|
|
27023
27065
|
}
|
|
27024
27066
|
}
|
|
27025
27067
|
|
|
27068
|
+
// src/local/rie-mount.ts
|
|
27069
|
+
const RIE_CONTAINER_PATH = "/var/rapid/aws-lambda-rie";
|
|
27070
|
+
const RIE_SOURCE_IMAGE = "public.ecr.aws/lambda/provided:al2023";
|
|
27071
|
+
const RIE_SOURCE_PATH = "/usr/local/bin/aws-lambda-rie";
|
|
27072
|
+
const RIE_BASENAME = "aws-lambda-rie";
|
|
27073
|
+
const ELF_MACHINE_BY_PLATFORM = {
|
|
27074
|
+
"linux/amd64": 62,
|
|
27075
|
+
"linux/arm64": 183
|
|
27076
|
+
};
|
|
27077
|
+
function rieCacheDirectory(env = process.env) {
|
|
27078
|
+
const root = cdkdCacheHome(env);
|
|
27079
|
+
return root === void 0 ? void 0 : join(root, "lambda-rie");
|
|
27080
|
+
}
|
|
27081
|
+
const inFlight = /* @__PURE__ */ new Map();
|
|
27082
|
+
const warnedNoBinary = /* @__PURE__ */ new Set();
|
|
27083
|
+
async function resolveRieWrap(input) {
|
|
27084
|
+
const logger = getLogger().child("rie");
|
|
27085
|
+
let program;
|
|
27086
|
+
try {
|
|
27087
|
+
const own = nonEmpty(input.entryPoint) && nonEmpty(input.command) ? {
|
|
27088
|
+
entrypoint: [],
|
|
27089
|
+
cmd: []
|
|
27090
|
+
} : await inspectImageEntrypointCmd(input.image);
|
|
27091
|
+
const entryPoint = nonEmpty(input.entryPoint) ? [...input.entryPoint] : own.entrypoint;
|
|
27092
|
+
const cmd = nonEmpty(input.command) ? [...input.command] : own.cmd;
|
|
27093
|
+
program = [...entryPoint, ...cmd];
|
|
27094
|
+
} catch (err) {
|
|
27095
|
+
logger.warn(safeMsg`Could not read the ENTRYPOINT / CMD of image ${input.image} (${messageOf(err)}), so no Lambda Runtime Interface Emulator is mounted into it; it runs as built.`);
|
|
27096
|
+
return;
|
|
27097
|
+
}
|
|
27098
|
+
const ownRie = program.find(isRieExecutable);
|
|
27099
|
+
if (ownRie !== void 0) {
|
|
27100
|
+
logger.debug(safeMsg`Image ${input.image} already starts ${ownRie}; not mounting another RIE`);
|
|
27101
|
+
return;
|
|
27102
|
+
}
|
|
27103
|
+
let hostPath;
|
|
27104
|
+
try {
|
|
27105
|
+
hostPath = await ensureRieBinary(input.platform, input.skipPull === true);
|
|
27106
|
+
} catch (err) {
|
|
27107
|
+
if (!warnedNoBinary.has(input.platform)) {
|
|
27108
|
+
warnedNoBinary.add(input.platform);
|
|
27109
|
+
logger.warn(safeMsg`Could not mount the Lambda Runtime Interface Emulator into container-image functions (${messageOf(err)}). ` + "They run as built, so only images that ship their own emulator (the AWS Lambda base images do) can be invoked.");
|
|
27110
|
+
} else logger.debug(safeMsg`RIE mount skipped for ${input.image}: ${messageOf(err)}`);
|
|
27111
|
+
return;
|
|
27112
|
+
}
|
|
27113
|
+
return {
|
|
27114
|
+
mount: {
|
|
27115
|
+
hostPath,
|
|
27116
|
+
containerPath: RIE_CONTAINER_PATH,
|
|
27117
|
+
readOnly: true
|
|
27118
|
+
},
|
|
27119
|
+
entryPoint: [RIE_CONTAINER_PATH],
|
|
27120
|
+
cmd: program
|
|
27121
|
+
};
|
|
27122
|
+
}
|
|
27123
|
+
function isRieExecutable(path) {
|
|
27124
|
+
return basename(path).startsWith(RIE_BASENAME);
|
|
27125
|
+
}
|
|
27126
|
+
function messageOf(err) {
|
|
27127
|
+
return err instanceof Error ? err.message : String(err);
|
|
27128
|
+
}
|
|
27129
|
+
function nonEmpty(v) {
|
|
27130
|
+
return v !== void 0 && v.length > 0;
|
|
27131
|
+
}
|
|
27132
|
+
async function inspectImageEntrypointCmd(image) {
|
|
27133
|
+
const args = [
|
|
27134
|
+
"image",
|
|
27135
|
+
"inspect",
|
|
27136
|
+
"--format",
|
|
27137
|
+
"{{json .Config}}",
|
|
27138
|
+
image
|
|
27139
|
+
];
|
|
27140
|
+
let stdout;
|
|
27141
|
+
try {
|
|
27142
|
+
({stdout} = await runDockerStreaming(args, { streamLive: false }));
|
|
27143
|
+
} catch (err) {
|
|
27144
|
+
throw new Error(`docker image inspect failed: ${describeDockerFailure(err, args)}`);
|
|
27145
|
+
}
|
|
27146
|
+
const config = JSON.parse(stdout.trim());
|
|
27147
|
+
return {
|
|
27148
|
+
entrypoint: stringArray(config?.Entrypoint),
|
|
27149
|
+
cmd: stringArray(config?.Cmd)
|
|
27150
|
+
};
|
|
27151
|
+
}
|
|
27152
|
+
function stringArray(v) {
|
|
27153
|
+
return Array.isArray(v) && v.every((s) => typeof s === "string") ? v : [];
|
|
27154
|
+
}
|
|
27155
|
+
async function ensureRieBinary(platform, skipPull) {
|
|
27156
|
+
const machine = ELF_MACHINE_BY_PLATFORM[platform];
|
|
27157
|
+
if (machine === void 0) throw new Error(`unsupported platform '${platform}'`);
|
|
27158
|
+
const root = rieCacheDirectory();
|
|
27159
|
+
if (root === void 0) throw new Error("no cache directory (HOME is not set)");
|
|
27160
|
+
const target = join(root, platform.replace("/", "-"), RIE_BASENAME);
|
|
27161
|
+
let run = inFlight.get(target);
|
|
27162
|
+
if (run === void 0) {
|
|
27163
|
+
run = (async () => {
|
|
27164
|
+
if (await isRegularFile(target) && await isElfFor(target, machine)) return target;
|
|
27165
|
+
await extractRie(platform, target, machine, skipPull);
|
|
27166
|
+
return target;
|
|
27167
|
+
})();
|
|
27168
|
+
inFlight.set(target, run);
|
|
27169
|
+
run.catch(() => inFlight.delete(target));
|
|
27170
|
+
}
|
|
27171
|
+
return run;
|
|
27172
|
+
}
|
|
27173
|
+
async function isRegularFile(path) {
|
|
27174
|
+
try {
|
|
27175
|
+
return (await promises.lstat(path)).isFile();
|
|
27176
|
+
} catch {
|
|
27177
|
+
return false;
|
|
27178
|
+
}
|
|
27179
|
+
}
|
|
27180
|
+
async function isElfFor(path, machine) {
|
|
27181
|
+
let handle;
|
|
27182
|
+
try {
|
|
27183
|
+
handle = await promises.open(path, "r");
|
|
27184
|
+
const header = Buffer.alloc(20);
|
|
27185
|
+
const { bytesRead } = await handle.read(header, 0, 20, 0);
|
|
27186
|
+
return bytesRead === 20 && header.readUInt32BE(0) === 2135247942 && header.readUInt16LE(18) === machine;
|
|
27187
|
+
} catch {
|
|
27188
|
+
return false;
|
|
27189
|
+
} finally {
|
|
27190
|
+
await handle?.close().catch(() => void 0);
|
|
27191
|
+
}
|
|
27192
|
+
}
|
|
27193
|
+
async function extractRie(platform, target, machine, skipPull) {
|
|
27194
|
+
getLogger().child("rie").info(skipPull ? safeMsg`Copying the Lambda Runtime Interface Emulator for ${platform} out of the local ${RIE_SOURCE_IMAGE} image (one time)...` : safeMsg`Fetching the Lambda Runtime Interface Emulator for ${platform} from ${RIE_SOURCE_IMAGE} (one time)...`);
|
|
27195
|
+
const dir = join(target, "..");
|
|
27196
|
+
await promises.mkdir(dir, {
|
|
27197
|
+
recursive: true,
|
|
27198
|
+
mode: 448
|
|
27199
|
+
});
|
|
27200
|
+
if (!skipPull) {
|
|
27201
|
+
const pullArgs = [
|
|
27202
|
+
"pull",
|
|
27203
|
+
"--platform",
|
|
27204
|
+
platform,
|
|
27205
|
+
RIE_SOURCE_IMAGE
|
|
27206
|
+
];
|
|
27207
|
+
try {
|
|
27208
|
+
await runDockerStreaming(pullArgs, { streamLive: false });
|
|
27209
|
+
} catch (err) {
|
|
27210
|
+
throw new Error(`docker pull failed: ${describeDockerFailure(err, pullArgs)}`);
|
|
27211
|
+
}
|
|
27212
|
+
}
|
|
27213
|
+
const createArgs = [
|
|
27214
|
+
"create",
|
|
27215
|
+
...skipPull ? ["--pull", "never"] : [],
|
|
27216
|
+
"--platform",
|
|
27217
|
+
platform,
|
|
27218
|
+
RIE_SOURCE_IMAGE
|
|
27219
|
+
];
|
|
27220
|
+
let containerId;
|
|
27221
|
+
try {
|
|
27222
|
+
containerId = (await runDockerStreaming(createArgs, { streamLive: false })).stdout.trim();
|
|
27223
|
+
} catch (err) {
|
|
27224
|
+
throw new Error(`docker create failed: ${describeDockerFailure(err, createArgs)}`);
|
|
27225
|
+
}
|
|
27226
|
+
const tmp = join(dir, `.${RIE_BASENAME}.${process.pid}.${randomBytes(4).toString("hex")}`);
|
|
27227
|
+
try {
|
|
27228
|
+
const cpArgs = [
|
|
27229
|
+
"cp",
|
|
27230
|
+
`${containerId}:${RIE_SOURCE_PATH}`,
|
|
27231
|
+
tmp
|
|
27232
|
+
];
|
|
27233
|
+
try {
|
|
27234
|
+
await runDockerStreaming(cpArgs, { streamLive: false });
|
|
27235
|
+
} catch (err) {
|
|
27236
|
+
throw new Error(`docker cp failed: ${describeDockerFailure(err, cpArgs)}`);
|
|
27237
|
+
}
|
|
27238
|
+
if (!await isRegularFile(tmp) || !await isElfFor(tmp, machine)) throw new Error(`the copied ${RIE_SOURCE_PATH} is not a ${platform} executable`);
|
|
27239
|
+
await promises.chmod(tmp, 493);
|
|
27240
|
+
await promises.rename(tmp, target);
|
|
27241
|
+
} finally {
|
|
27242
|
+
await promises.rm(tmp, {
|
|
27243
|
+
force: true,
|
|
27244
|
+
recursive: true
|
|
27245
|
+
}).catch(() => void 0);
|
|
27246
|
+
await runDockerStreaming([
|
|
27247
|
+
"rm",
|
|
27248
|
+
"-f",
|
|
27249
|
+
containerId
|
|
27250
|
+
], { streamLive: false }).catch(() => void 0);
|
|
27251
|
+
}
|
|
27252
|
+
}
|
|
27253
|
+
|
|
27026
27254
|
// src/local/lambda-resolver/types.ts
|
|
27027
27255
|
var LocalInvokeResolutionError = class LocalInvokeResolutionError extends Error {
|
|
27028
27256
|
constructor(message) {
|
|
@@ -27684,13 +27912,24 @@ async function buildContainerSpec(args) {
|
|
|
27684
27912
|
containerPath: profileCredsFile.containerPath
|
|
27685
27913
|
} }
|
|
27686
27914
|
};
|
|
27915
|
+
const rie = await resolveRieWrap({
|
|
27916
|
+
image: imageRef,
|
|
27917
|
+
platform,
|
|
27918
|
+
entryPoint: lambda.imageConfig.entryPoint,
|
|
27919
|
+
command: lambda.imageConfig.command,
|
|
27920
|
+
skipPull
|
|
27921
|
+
});
|
|
27687
27922
|
return {
|
|
27688
27923
|
kind: "image",
|
|
27689
27924
|
lambda,
|
|
27690
27925
|
image: imageRef,
|
|
27691
27926
|
platform,
|
|
27692
|
-
command: lambda.imageConfig.command ?? [],
|
|
27693
|
-
...
|
|
27927
|
+
command: rie ? rie.cmd : lambda.imageConfig.command ?? [],
|
|
27928
|
+
...rie && {
|
|
27929
|
+
entryPoint: rie.entryPoint,
|
|
27930
|
+
rieMount: rie.mount
|
|
27931
|
+
},
|
|
27932
|
+
...!rie && lambda.imageConfig.entryPoint !== void 0 && lambda.imageConfig.entryPoint.length > 0 && { entryPoint: lambda.imageConfig.entryPoint },
|
|
27694
27933
|
...lambda.imageConfig.workingDirectory !== void 0 && { workingDir: lambda.imageConfig.workingDirectory },
|
|
27695
27934
|
env: dockerEnv,
|
|
27696
27935
|
...sensitiveEnvKeys !== void 0 && { sensitiveEnvKeys },
|
|
@@ -32386,13 +32625,21 @@ async function resolveContainerImagePlan(lambda, options) {
|
|
|
32386
32625
|
});
|
|
32387
32626
|
}
|
|
32388
32627
|
const tmpfs = resolveTmpfsForLambda(lambda);
|
|
32628
|
+
const rie = await resolveRieWrap({
|
|
32629
|
+
image: imageRef,
|
|
32630
|
+
platform,
|
|
32631
|
+
entryPoint: lambda.imageConfig.entryPoint,
|
|
32632
|
+
command: lambda.imageConfig.command,
|
|
32633
|
+
skipPull: options.pull === false
|
|
32634
|
+
});
|
|
32389
32635
|
return {
|
|
32390
32636
|
image: imageRef,
|
|
32391
32637
|
mounts: [],
|
|
32392
|
-
extraMounts: [],
|
|
32393
|
-
cmd: lambda.imageConfig.command ?? [],
|
|
32638
|
+
extraMounts: rie ? [rie.mount] : [],
|
|
32639
|
+
cmd: rie ? rie.cmd : lambda.imageConfig.command ?? [],
|
|
32394
32640
|
platform,
|
|
32395
|
-
...
|
|
32641
|
+
...rie && { entryPoint: rie.entryPoint },
|
|
32642
|
+
...!rie && lambda.imageConfig.entryPoint && lambda.imageConfig.entryPoint.length > 0 && { entryPoint: lambda.imageConfig.entryPoint },
|
|
32396
32643
|
...lambda.imageConfig.workingDirectory !== void 0 && { workingDir: lambda.imageConfig.workingDirectory },
|
|
32397
32644
|
...tmpfs !== void 0 && { tmpfs }
|
|
32398
32645
|
};
|
|
@@ -32512,4 +32759,4 @@ function collectVerbFlags(program) {
|
|
|
32512
32759
|
}
|
|
32513
32760
|
|
|
32514
32761
|
export { resolveSecretDerivedPrincipals as a, buildProgram, isResolvableSecretPrincipalList as i, runDestroyForStack as n, canonicalizeIpProtocolValue as o, holdsUnprovenSecretPrincipalToken as r, canonicalizeIpv4Cidr as t };
|
|
32515
|
-
//# sourceMappingURL=program-
|
|
32762
|
+
//# sourceMappingURL=program-Ctf5zWf1.js.map
|