@go-to-k/cdkd 0.195.0 → 0.197.0
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/{aws-clients-B15NAPbL.js → aws-clients-DWUnLza1.js} +18 -2
- package/dist/{aws-clients-B15NAPbL.js.map → aws-clients-DWUnLza1.js.map} +1 -1
- package/dist/cli.js +128 -1156
- package/dist/cli.js.map +1 -1
- package/dist/{deploy-engine-BDmJX4ss.js → deploy-engine-z5g_l5ER.js} +1002 -9
- package/dist/deploy-engine-z5g_l5ER.js.map +1 -0
- package/dist/index.js +2 -3
- package/package.json +1 -1
- package/dist/deploy-engine-BDmJX4ss.js.map +0 -1
- package/dist/docker-cmd-iDMcWcre.js +0 -1004
- package/dist/docker-cmd-iDMcWcre.js.map +0 -1
- package/dist/rolldown-runtime-CjeV3_4I.js +0 -18
package/dist/cli.js
CHANGED
|
@@ -1,14 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
import { A as S3StateBackend, B as
|
|
4
|
-
import { a as setAwsClients, i as resetAwsClients, r as getAwsClients, t as AwsClients } from "./aws-clients-B15NAPbL.js";
|
|
2
|
+
import { a as setAwsClients, i as resetAwsClients, r as getAwsClients, t as AwsClients } from "./aws-clients-DWUnLza1.js";
|
|
3
|
+
import { $ as uploadCfnTemplate, A as S3StateBackend, At as PATTERN_B_NAME_PROPERTIES, B as Synthesizer, C as assertRegionMatch, Ct as normalizeAwsError, D as DagBuilder, E as DiffCalculator, Et as getLogger, F as buildDockerImage, Ft as withStackName, G as resolveSkipPrefix, H as getLegacyStateBucketName, I as formatDockerLoginError, J as warnDeprecatedNoPrefixCliFlag, K as resolveStateBucketWithDefault, L as getDockerCmd, M as AssetPublisher, Mt as generateResourceName, N as stringifyValue, Nt as generateResourceNameWithFallback, O as TemplateParser, Ot as runStackBuffered, P as WorkGraph, Pt as withSkipPrefix, Q as findLargeInlineResources, R as runDockerForeground, S as CloudControlProvider, T as applyRoleArnIfSet, U as resolveApp, V as getDefaultStateBucketName, W as resolveCaptureObservedState, X as CFN_TEMPLATE_URL_LIMIT, Y as CFN_TEMPLATE_BODY_LIMIT, Z as MIGRATE_TMP_PREFIX, _ as matchesCdkPath, _t as StackHasActiveImportsError, a as withRetry, b as ProviderRegistry, c as bold, ct as LocalMigrateError, d as green, dt as MissingCdkCliError, et as AssemblyReader, f as red, ft as NestedStackChildDirectDestroyError, g as CDK_PATH_TAG, gt as ResourceUpdateNotSupportedError, h as collectInlinePolicyNamesManagedBySiblings, ht as ResourceTimeoutError, i as withResourceDeadline, it as CdkdError, j as shouldRetainResource, jt as PATTERN_B_RESOURCE_TYPES, k as LockManager, kt as getLiveRenderer, l as cyan, lt as LocalStartServiceError, m as IAMRoleProvider, mt as ProvisioningError, n as DEFAULT_RESOURCE_WARN_AFTER_MS, nt as resolveBucketRegion, o as IMPLICIT_DELETE_DEPENDENCIES, p as yellow, pt as PartialFailureError, q as resolveStateBucketWithDefaultAndSource, r as DeployEngine, s as formatResourceLine, st as LocalInvokeBuildError$1, t as DEFAULT_RESOURCE_TIMEOUT_MS, u as gray, v as normalizeAwsTagsToCfn, vt as StackTerminationProtectionError, w as IntrinsicFunctionResolver, wt as withErrorHandling, x as findActionableSilentDrops, y as resolveExplicitPhysicalId, z as runDockerStreaming } from "./deploy-engine-z5g_l5ER.js";
|
|
5
4
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
6
5
|
import { randomBytes, randomUUID } from "node:crypto";
|
|
7
6
|
import { CopyObjectCommand, CreateBucketCommand, DeleteBucketAnalyticsConfigurationCommand, DeleteBucketCommand, DeleteBucketCorsCommand, DeleteBucketIntelligentTieringConfigurationCommand, DeleteBucketInventoryConfigurationCommand, DeleteBucketLifecycleCommand, DeleteBucketMetricsConfigurationCommand, DeleteBucketPolicyCommand, DeleteBucketReplicationCommand, DeleteBucketTaggingCommand, DeleteBucketWebsiteCommand, DeleteObjectsCommand, GetBucketAccelerateConfigurationCommand, GetBucketCorsCommand, GetBucketEncryptionCommand, GetBucketLifecycleConfigurationCommand, GetBucketLocationCommand, GetBucketLoggingCommand, GetBucketNotificationConfigurationCommand, GetBucketPolicyCommand, GetBucketReplicationCommand, GetBucketTaggingCommand, GetBucketVersioningCommand, GetBucketWebsiteCommand, GetObjectCommand, GetObjectLockConfigurationCommand, GetPublicAccessBlockCommand, HeadBucketCommand, ListBucketAnalyticsConfigurationsCommand, ListBucketIntelligentTieringConfigurationsCommand, ListBucketInventoryConfigurationsCommand, ListBucketMetricsConfigurationsCommand, ListBucketsCommand, ListDirectoryBucketsCommand, ListObjectVersionsCommand, ListObjectsV2Command, NoSuchBucket, PutBucketAccelerateConfigurationCommand, PutBucketAnalyticsConfigurationCommand, PutBucketCorsCommand, PutBucketEncryptionCommand, PutBucketIntelligentTieringConfigurationCommand, PutBucketInventoryConfigurationCommand, PutBucketLifecycleConfigurationCommand, PutBucketLoggingCommand, PutBucketMetricsConfigurationCommand, PutBucketNotificationConfigurationCommand, PutBucketOwnershipControlsCommand, PutBucketPolicyCommand, PutBucketReplicationCommand, PutBucketTaggingCommand, PutBucketVersioningCommand, PutBucketWebsiteCommand, PutObjectCommand, PutObjectLockConfigurationCommand, PutPublicAccessBlockCommand, S3Client, S3ServiceException } from "@aws-sdk/client-s3";
|
|
8
7
|
import { AddRoleToInstanceProfileCommand, AddUserToGroupCommand, AttachGroupPolicyCommand, AttachRolePolicyCommand, AttachUserPolicyCommand, CreateGroupCommand, CreateInstanceProfileCommand, CreateLoginProfileCommand, CreatePolicyCommand, CreatePolicyVersionCommand, CreateUserCommand, DeleteAccessKeyCommand, DeleteGroupCommand, DeleteGroupPolicyCommand, DeleteInstanceProfileCommand, DeleteLoginProfileCommand, DeletePolicyCommand, DeletePolicyVersionCommand, DeleteRolePolicyCommand, DeleteUserCommand, DeleteUserPermissionsBoundaryCommand, DeleteUserPolicyCommand, DetachGroupPolicyCommand, DetachRolePolicyCommand, DetachUserPolicyCommand, GetGroupCommand, GetGroupPolicyCommand, GetInstanceProfileCommand, GetPolicyCommand, GetPolicyVersionCommand, GetRolePolicyCommand, GetUserCommand, GetUserPolicyCommand, IAMClient, ListAccessKeysCommand, ListAttachedGroupPoliciesCommand, ListAttachedUserPoliciesCommand, ListEntitiesForPolicyCommand, ListGroupPoliciesCommand, ListGroupsForUserCommand, ListInstanceProfilesCommand, ListPoliciesCommand, ListPolicyTagsCommand, ListPolicyVersionsCommand, ListUserPoliciesCommand, ListUserTagsCommand, ListUsersCommand, NoSuchEntityException, PutGroupPolicyCommand, PutRolePolicyCommand, PutUserPermissionsBoundaryCommand, PutUserPolicyCommand, RemoveRoleFromInstanceProfileCommand, RemoveUserFromGroupCommand, TagPolicyCommand, TagUserCommand, UntagPolicyCommand, UntagUserCommand, UpdateLoginProfileCommand } from "@aws-sdk/client-iam";
|
|
9
8
|
import { CreateQueueCommand, DeleteQueueCommand, GetQueueAttributesCommand, GetQueueUrlCommand, ListQueueTagsCommand, ListQueuesCommand, QueueDoesNotExist, SQSClient, SetQueueAttributesCommand, TagQueueCommand, UntagQueueCommand } from "@aws-sdk/client-sqs";
|
|
10
9
|
import { CreateTopicCommand, DeleteTopicCommand, GetSubscriptionAttributesCommand, GetTopicAttributesCommand, ListTagsForResourceCommand, ListTopicsCommand, NotFoundException, SNSClient, SetTopicAttributesCommand, SubscribeCommand, TagResourceCommand, UnsubscribeCommand, UntagResourceCommand } from "@aws-sdk/client-sns";
|
|
11
|
-
import { AddPermissionCommand, CreateEventSourceMappingCommand, CreateFunctionCommand, CreateFunctionUrlConfigCommand, DeleteEventSourceMappingCommand, DeleteFunctionCommand, DeleteFunctionUrlConfigCommand, DeleteLayerVersionCommand, GetEventSourceMappingCommand, GetFunctionCommand, GetFunctionRecursionConfigCommand, GetFunctionUrlConfigCommand, GetLayerVersionByArnCommand, GetPolicyCommand as GetPolicyCommand$1, LambdaClient, ListFunctionsCommand, ListLayersCommand, ListTagsCommand, PublishLayerVersionCommand, PutFunctionRecursionConfigCommand, RemovePermissionCommand, ResourceNotFoundException, TagResourceCommand as TagResourceCommand$1, UntagResourceCommand as UntagResourceCommand$1, UpdateEventSourceMappingCommand, UpdateFunctionCodeCommand, UpdateFunctionConfigurationCommand, UpdateFunctionUrlConfigCommand, waitUntilFunctionUpdatedV2 } from "@aws-sdk/client-lambda";
|
|
10
|
+
import { AddPermissionCommand, CreateEventSourceMappingCommand, CreateFunctionCommand, CreateFunctionUrlConfigCommand, DeleteEventSourceMappingCommand, DeleteFunctionCommand, DeleteFunctionConcurrencyCommand, DeleteFunctionUrlConfigCommand, DeleteLayerVersionCommand, GetEventSourceMappingCommand, GetFunctionCommand, GetFunctionConcurrencyCommand, GetFunctionRecursionConfigCommand, GetFunctionUrlConfigCommand, GetLayerVersionByArnCommand, GetPolicyCommand as GetPolicyCommand$1, LambdaClient, ListFunctionsCommand, ListLayersCommand, ListTagsCommand, PublishLayerVersionCommand, PutFunctionConcurrencyCommand, PutFunctionRecursionConfigCommand, RemovePermissionCommand, ResourceNotFoundException, TagResourceCommand as TagResourceCommand$1, UntagResourceCommand as UntagResourceCommand$1, UpdateEventSourceMappingCommand, UpdateFunctionCodeCommand, UpdateFunctionConfigurationCommand, UpdateFunctionUrlConfigCommand, waitUntilFunctionUpdatedV2 } from "@aws-sdk/client-lambda";
|
|
12
11
|
import { AssumeRoleCommand, GetCallerIdentityCommand, STSClient } from "@aws-sdk/client-sts";
|
|
13
12
|
import { AssociateRouteTableCommand, AttachInternetGatewayCommand, AuthorizeSecurityGroupEgressCommand, AuthorizeSecurityGroupIngressCommand, CreateInternetGatewayCommand, CreateNatGatewayCommand, CreateNetworkAclCommand, CreateNetworkAclEntryCommand, CreateRouteCommand, CreateRouteTableCommand, CreateSecurityGroupCommand, CreateSubnetCommand, CreateTagsCommand, CreateVpcCommand, DeleteInternetGatewayCommand, DeleteNatGatewayCommand, DeleteNetworkAclCommand, DeleteNetworkAclEntryCommand, DeleteNetworkInterfaceCommand, DeleteRouteCommand, DeleteRouteTableCommand, DeleteSecurityGroupCommand, DeleteSubnetCommand, DeleteTagsCommand, DeleteVpcCommand, DescribeAvailabilityZonesCommand, DescribeInstanceAttributeCommand, DescribeInstancesCommand, DescribeInternetGatewaysCommand, DescribeNatGatewaysCommand, DescribeNetworkAclsCommand, DescribeNetworkInterfacesCommand, DescribeRouteTablesCommand, DescribeSecurityGroupsCommand, DescribeSubnetsCommand, DescribeVolumesCommand, DescribeVpcAttributeCommand, DescribeVpcsCommand, DetachInternetGatewayCommand, DisassociateRouteTableCommand, EC2Client, ModifyInstanceAttributeCommand, ModifySubnetAttributeCommand, ModifyVpcAttributeCommand, ReplaceNetworkAclAssociationCommand, RevokeSecurityGroupEgressCommand, RevokeSecurityGroupIngressCommand, RunInstancesCommand, TerminateInstancesCommand, waitUntilInstanceRunning, waitUntilInstanceTerminated, waitUntilNatGatewayAvailable, waitUntilNatGatewayDeleted } from "@aws-sdk/client-ec2";
|
|
14
13
|
import { CreateTableCommand, DeleteTableCommand, DescribeContinuousBackupsCommand, DescribeContributorInsightsCommand, DescribeKinesisStreamingDestinationCommand, DescribeTableCommand, DescribeTimeToLiveCommand, DynamoDBClient, ListTablesCommand, ListTagsOfResourceCommand, ResourceNotFoundException as ResourceNotFoundException$1, TagResourceCommand as TagResourceCommand$2, UntagResourceCommand as UntagResourceCommand$2, UpdateContinuousBackupsCommand, UpdateTableCommand, UpdateTimeToLiveCommand } from "@aws-sdk/client-dynamodb";
|
|
@@ -63,7 +62,7 @@ import { CreateNamespaceCommand, CreateTableBucketCommand, CreateTableCommand as
|
|
|
63
62
|
import { AttachLoadBalancerTargetGroupsCommand, AttachLoadBalancersCommand, AttachTrafficSourcesCommand, AutoScalingClient, CreateAutoScalingGroupCommand, CreateOrUpdateTagsCommand, DeleteAutoScalingGroupCommand, DeleteLifecycleHookCommand, DeleteNotificationConfigurationCommand, DeleteTagsCommand as DeleteTagsCommand$1, DescribeAutoScalingGroupsCommand, DescribeLifecycleHooksCommand, DescribeNotificationConfigurationsCommand, DescribeTrafficSourcesCommand, DetachLoadBalancerTargetGroupsCommand, DetachLoadBalancersCommand, DetachTrafficSourcesCommand, DisableMetricsCollectionCommand, EnableMetricsCollectionCommand, PutLifecycleHookCommand, PutNotificationConfigurationCommand, UpdateAutoScalingGroupCommand } from "@aws-sdk/client-auto-scaling";
|
|
64
63
|
import { Document, Pair, Scalar, YAMLMap, YAMLSeq, parse as parse$1, stringify } from "yaml";
|
|
65
64
|
import { createLocalStateProvider, getEmbedConfig, isCfnFlagPresent, listTargets, rejectExplicitCfnStackWithMultipleStacks, resolveCfnFallbackRegion, setEmbedConfig, substituteAgainstState, substituteAgainstStateAsync, substituteEnvVarsFromState, substituteEnvVarsFromStateAsync } from "cdk-local";
|
|
66
|
-
import { A2A_CONTAINER_PORT, A2A_PATH, AGENTCORE_A2A_PROTOCOL, AGENTCORE_AGUI_PROTOCOL, AGENTCORE_MCP_PROTOCOL,
|
|
65
|
+
import { A2A_CONTAINER_PORT, A2A_PATH, AGENTCORE_A2A_PROTOCOL, AGENTCORE_AGUI_PROTOCOL, AGENTCORE_MCP_PROTOCOL, ConnectionRegistry, EcsTaskResolutionError, HOST_GATEWAY_MIN_VERSION, LocalInvokeBuildError, MCP_CONTAINER_PORT, MCP_PATH, a2aInvokeOnce, addCommonEcsServiceOptions, architectureToPlatform, attachAuthorizers, attachStageContext, availableApiIdentifiers, bufferToBody, buildAgentCoreCodeImage, buildCognitoJwksUrl, buildConnectEvent, buildContainerImage, buildCorsConfigByApiId, buildCorsConfigFromCloudFrontChain, buildDisconnectEvent, buildJwksUrlFromIssuer, buildMessageEvent, buildMgmtEndpointEnvUrl, buildStageMap, createAuthorizerCache, createFileWatcher, createJwksCache, createWatchPredicates, defaultCredentialsLoader, derivePseudoParametersFromRegion, discoverRoutes, discoverWebSocketApis, downloadAndExtractS3Bundle, filterRoutesByApiIdentifier, groupRoutesByServer, handleConnectionsRequest, invokeAgentCore, invokeAgentCoreWs, isApplicationLoadBalancer, materializeLayerFromArn, mcpInvokeOnce, parseConnectionsPath, parseSelectionExpressionPath, pickAgentCoreCandidateStack, probeHostGatewaySupport, readMtlsMaterialsFromDisk, resolveAgentCoreTarget, resolveAlbFrontDoor, resolveEnvVars, resolveRuntimeCodeMountPath, resolveRuntimeFileExtension, resolveRuntimeImage, resolveSingleTarget, resolveWatchConfig, runEcsServiceEmulator, signAgentCoreInvocation, startApiServer, substituteImagePlaceholders, tryResolveImageFnJoin, verifyJwtViaDiscovery, waitForAgentCorePing } from "cdk-local/internal";
|
|
67
66
|
import { createServer } from "node:net";
|
|
68
67
|
import { promisify } from "node:util";
|
|
69
68
|
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
@@ -7054,7 +7053,8 @@ var LambdaFunctionProvider = class {
|
|
|
7054
7053
|
"ImageConfig",
|
|
7055
7054
|
"SnapStart",
|
|
7056
7055
|
"LoggingConfig",
|
|
7057
|
-
"RecursiveLoop"
|
|
7056
|
+
"RecursiveLoop",
|
|
7057
|
+
"ReservedConcurrentExecutions"
|
|
7058
7058
|
])]]);
|
|
7059
7059
|
eniWaitTimeoutMs = 600 * 1e3;
|
|
7060
7060
|
eniWaitInitialDelayMs = 1e4;
|
|
@@ -7125,6 +7125,21 @@ var LambdaFunctionProvider = class {
|
|
|
7125
7125
|
}
|
|
7126
7126
|
throw new ProvisioningError(`Failed to set RecursiveLoop on Lambda function ${logicalId} (function was deleted to maintain atomicity): ${rlError instanceof Error ? rlError.message : String(rlError)}`, resourceType, logicalId, functionName, rlError instanceof Error ? rlError : void 0);
|
|
7127
7127
|
}
|
|
7128
|
+
const reservedConcurrentExecutions = properties["ReservedConcurrentExecutions"];
|
|
7129
|
+
if (reservedConcurrentExecutions !== void 0) try {
|
|
7130
|
+
await this.lambdaClient.send(new PutFunctionConcurrencyCommand({
|
|
7131
|
+
FunctionName: functionName,
|
|
7132
|
+
ReservedConcurrentExecutions: reservedConcurrentExecutions
|
|
7133
|
+
}));
|
|
7134
|
+
} catch (pcError) {
|
|
7135
|
+
this.logger.warn(`PutFunctionConcurrency failed for ${logicalId}: ${pcError instanceof Error ? pcError.message : String(pcError)} — deleting partially-created function to maintain atomicity`);
|
|
7136
|
+
try {
|
|
7137
|
+
await this.lambdaClient.send(new DeleteFunctionCommand({ FunctionName: functionName }));
|
|
7138
|
+
} catch (deleteError) {
|
|
7139
|
+
this.logger.error(`Cleanup DeleteFunction failed for ${logicalId} after PutFunctionConcurrency failure — function may be orphaned: ${deleteError instanceof Error ? deleteError.message : String(deleteError)}`);
|
|
7140
|
+
}
|
|
7141
|
+
throw new ProvisioningError(`Failed to set ReservedConcurrentExecutions on Lambda function ${logicalId} (function was deleted to maintain atomicity): ${pcError instanceof Error ? pcError.message : String(pcError)}`, resourceType, logicalId, functionName, pcError instanceof Error ? pcError : void 0);
|
|
7142
|
+
}
|
|
7128
7143
|
this.logger.debug(`Successfully created Lambda function ${logicalId}: ${functionName}`);
|
|
7129
7144
|
return {
|
|
7130
7145
|
physicalId: response.FunctionName || functionName,
|
|
@@ -7218,6 +7233,17 @@ var LambdaFunctionProvider = class {
|
|
|
7218
7233
|
}));
|
|
7219
7234
|
this.logger.debug(`Updated RecursiveLoop for Lambda function ${physicalId} to '${newRecursiveLoop}'`);
|
|
7220
7235
|
}
|
|
7236
|
+
const newReservedConcurrentExecutions = properties["ReservedConcurrentExecutions"];
|
|
7237
|
+
if (newReservedConcurrentExecutions !== previousProperties["ReservedConcurrentExecutions"]) if (newReservedConcurrentExecutions === void 0) {
|
|
7238
|
+
await this.lambdaClient.send(new DeleteFunctionConcurrencyCommand({ FunctionName: physicalId }));
|
|
7239
|
+
this.logger.debug(`Cleared ReservedConcurrentExecutions for Lambda function ${physicalId} (template removed the property)`);
|
|
7240
|
+
} else {
|
|
7241
|
+
await this.lambdaClient.send(new PutFunctionConcurrencyCommand({
|
|
7242
|
+
FunctionName: physicalId,
|
|
7243
|
+
ReservedConcurrentExecutions: newReservedConcurrentExecutions
|
|
7244
|
+
}));
|
|
7245
|
+
this.logger.debug(`Updated ReservedConcurrentExecutions for Lambda function ${physicalId} to ${newReservedConcurrentExecutions}`);
|
|
7246
|
+
}
|
|
7221
7247
|
const getResponse = await this.lambdaClient.send(new GetFunctionCommand({ FunctionName: physicalId }));
|
|
7222
7248
|
const functionArn = getResponse.Configuration?.FunctionArn;
|
|
7223
7249
|
await this.applyTagDiff(functionArn, previousProperties["Tags"], properties["Tags"]);
|
|
@@ -7743,6 +7769,12 @@ var LambdaFunctionProvider = class {
|
|
|
7743
7769
|
} catch (rlErr) {
|
|
7744
7770
|
if (!(rlErr instanceof ResourceNotFoundException)) this.logger.debug(`GetFunctionRecursionConfig failed for ${physicalId}: ${rlErr instanceof Error ? rlErr.message : String(rlErr)}`);
|
|
7745
7771
|
}
|
|
7772
|
+
try {
|
|
7773
|
+
const pcResp = await this.lambdaClient.send(new GetFunctionConcurrencyCommand({ FunctionName: physicalId }));
|
|
7774
|
+
if (pcResp.ReservedConcurrentExecutions !== void 0) result["ReservedConcurrentExecutions"] = pcResp.ReservedConcurrentExecutions;
|
|
7775
|
+
} catch (pcErr) {
|
|
7776
|
+
if (!(pcErr instanceof ResourceNotFoundException)) this.logger.debug(`GetFunctionConcurrency failed for ${physicalId}: ${pcErr instanceof Error ? pcErr.message : String(pcErr)}`);
|
|
7777
|
+
}
|
|
7746
7778
|
return result;
|
|
7747
7779
|
} catch (err) {
|
|
7748
7780
|
if (err instanceof ResourceNotFoundException) return void 0;
|
|
@@ -31342,7 +31374,11 @@ var S3VectorsProvider = class {
|
|
|
31342
31374
|
client;
|
|
31343
31375
|
providerRegion = process.env["AWS_REGION"];
|
|
31344
31376
|
logger = getLogger().child("S3VectorsProvider");
|
|
31345
|
-
handledProperties = new Map([["AWS::S3Vectors::VectorBucket", new Set([
|
|
31377
|
+
handledProperties = new Map([["AWS::S3Vectors::VectorBucket", new Set([
|
|
31378
|
+
"VectorBucketName",
|
|
31379
|
+
"EncryptionConfiguration",
|
|
31380
|
+
"Tags"
|
|
31381
|
+
])]]);
|
|
31346
31382
|
getClient() {
|
|
31347
31383
|
if (!this.client) this.client = new S3VectorsClient(this.providerRegion ? { region: this.providerRegion } : {});
|
|
31348
31384
|
return this.client;
|
|
@@ -31373,13 +31409,19 @@ var S3VectorsProvider = class {
|
|
|
31373
31409
|
const vectorBucketName = properties["VectorBucketName"];
|
|
31374
31410
|
if (!vectorBucketName) throw new ProvisioningError(`VectorBucketName is required for S3 VectorBucket ${logicalId}`, resourceType, logicalId);
|
|
31375
31411
|
const encryptionConfiguration = properties["EncryptionConfiguration"];
|
|
31412
|
+
const tagsArray = properties["Tags"];
|
|
31413
|
+
const tags = tagsArray && tagsArray.length > 0 ? tagsArray.reduce((acc, t) => {
|
|
31414
|
+
if (t.Key !== void 0 && t.Value !== void 0) acc[t.Key] = t.Value;
|
|
31415
|
+
return acc;
|
|
31416
|
+
}, {}) : void 0;
|
|
31376
31417
|
try {
|
|
31377
31418
|
const vectorBucketArn = (await this.getClient().send(new CreateVectorBucketCommand({
|
|
31378
31419
|
vectorBucketName,
|
|
31379
31420
|
encryptionConfiguration: encryptionConfiguration ? {
|
|
31380
31421
|
sseType: encryptionConfiguration["SSEType"],
|
|
31381
31422
|
kmsKeyArn: encryptionConfiguration["KMSKeyArn"]
|
|
31382
|
-
} : void 0
|
|
31423
|
+
} : void 0,
|
|
31424
|
+
...tags && Object.keys(tags).length > 0 ? { tags } : {}
|
|
31383
31425
|
}))).vectorBucketArn ?? "";
|
|
31384
31426
|
this.logger.debug(`Successfully created S3 VectorBucket ${logicalId}: ${vectorBucketName}`);
|
|
31385
31427
|
return {
|
|
@@ -31460,6 +31502,13 @@ var S3VectorsProvider = class {
|
|
|
31460
31502
|
if (sseType === "aws:kms" && bucket.encryptionConfiguration.kmsKeyArn !== void 0) enc["KMSKeyArn"] = bucket.encryptionConfiguration.kmsKeyArn;
|
|
31461
31503
|
if (Object.keys(enc).length > 0) result["EncryptionConfiguration"] = enc;
|
|
31462
31504
|
}
|
|
31505
|
+
if (bucket?.vectorBucketArn) try {
|
|
31506
|
+
result["Tags"] = normalizeAwsTagsToCfn((await this.getClient().send(new ListTagsForResourceCommand$18({ resourceArn: bucket.vectorBucketArn }))).tags);
|
|
31507
|
+
} catch (err) {
|
|
31508
|
+
this.logger.debug(`S3Vectors ListTagsForResource(${bucket.vectorBucketArn}) failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
31509
|
+
result["Tags"] = [];
|
|
31510
|
+
}
|
|
31511
|
+
else this.logger.debug(`S3Vectors GetVectorBucket(${physicalId}) returned no vectorBucketArn; skipping Tags readback`);
|
|
31463
31512
|
return result;
|
|
31464
31513
|
}
|
|
31465
31514
|
/**
|
|
@@ -43119,14 +43168,14 @@ function parseTarget(target) {
|
|
|
43119
43168
|
function resolveLambdaTarget(target, stacks) {
|
|
43120
43169
|
if (stacks.length === 0) throw new LocalInvokeResolutionError("No stacks found in the synthesized assembly.");
|
|
43121
43170
|
const parsed = parseTarget(target);
|
|
43122
|
-
const stack = pickStack$
|
|
43171
|
+
const stack = pickStack$2(parsed, stacks);
|
|
43123
43172
|
const template = stack.template;
|
|
43124
43173
|
const resources = template.Resources ?? {};
|
|
43125
43174
|
let match;
|
|
43126
43175
|
if (parsed.isPath) {
|
|
43127
43176
|
const index = buildCdkPathIndex(template);
|
|
43128
43177
|
const lambdaMatches = resolveCdkPathToLogicalIds(parsed.pathOrId, index).filter(({ logicalId }) => resources[logicalId]?.Type === "AWS::Lambda::Function");
|
|
43129
|
-
if (lambdaMatches.length === 0) throw notFoundError$
|
|
43178
|
+
if (lambdaMatches.length === 0) throw notFoundError$1(target, stack, resources);
|
|
43130
43179
|
if (lambdaMatches.length > 1) throw new LocalInvokeResolutionError(`Target '${target}' matches ${lambdaMatches.length} Lambda functions in ${stack.stackName}: ` + lambdaMatches.map((m) => m.logicalId).join(", ") + ". Refine the path or use the stack:LogicalId form.");
|
|
43131
43180
|
const m = lambdaMatches[0];
|
|
43132
43181
|
match = {
|
|
@@ -43135,7 +43184,7 @@ function resolveLambdaTarget(target, stacks) {
|
|
|
43135
43184
|
};
|
|
43136
43185
|
} else {
|
|
43137
43186
|
const resource = resources[parsed.pathOrId];
|
|
43138
|
-
if (!resource) throw notFoundError$
|
|
43187
|
+
if (!resource) throw notFoundError$1(target, stack, resources);
|
|
43139
43188
|
match = {
|
|
43140
43189
|
logicalId: parsed.pathOrId,
|
|
43141
43190
|
resource
|
|
@@ -43153,7 +43202,7 @@ function resolveLambdaTarget(target, stacks) {
|
|
|
43153
43202
|
* user may omit the stack prefix. Otherwise an explicit stack pattern is
|
|
43154
43203
|
* required.
|
|
43155
43204
|
*/
|
|
43156
|
-
function pickStack$
|
|
43205
|
+
function pickStack$2(parsed, stacks) {
|
|
43157
43206
|
if (parsed.stackPattern === null) {
|
|
43158
43207
|
if (stacks.length === 1) return stacks[0];
|
|
43159
43208
|
throw new LocalInvokeResolutionError(`Multiple stacks in app, target '${parsed.pathOrId}' is missing a stack prefix. Use 'StackName:${parsed.pathOrId}' or 'StackName/...' (path form). Available stacks: ${stacks.map((s) => s.stackName).join(", ")}.`);
|
|
@@ -43491,7 +43540,7 @@ function describeLayerEntry(entry) {
|
|
|
43491
43540
|
* the resolved stack so the user can copy/paste a valid target. Mirrors
|
|
43492
43541
|
* the format the issue spec calls out.
|
|
43493
43542
|
*/
|
|
43494
|
-
function notFoundError$
|
|
43543
|
+
function notFoundError$1(target, stack, resources) {
|
|
43495
43544
|
const lambdas = [];
|
|
43496
43545
|
for (const [logicalId, resource] of Object.entries(resources)) {
|
|
43497
43546
|
if (resource.Type !== "AWS::Lambda::Function") continue;
|
|
@@ -43776,28 +43825,28 @@ function parseEcsTarget(target) {
|
|
|
43776
43825
|
function resolveEcsTaskTarget(target, stacks, context) {
|
|
43777
43826
|
if (stacks.length === 0) throw new EcsTaskResolutionError("No stacks found in the synthesized assembly.");
|
|
43778
43827
|
const parsed = parseEcsTarget(target);
|
|
43779
|
-
const stack = pickStack$
|
|
43828
|
+
const stack = pickStack$1(parsed, stacks);
|
|
43780
43829
|
const resources = stack.template.Resources ?? {};
|
|
43781
43830
|
let logicalId;
|
|
43782
43831
|
let resource;
|
|
43783
43832
|
if (parsed.isPath) {
|
|
43784
43833
|
const index = buildCdkPathIndex(stack.template);
|
|
43785
43834
|
const taskDefs = resolveCdkPathToLogicalIds(parsed.pathOrId, index).filter(({ logicalId: l }) => resources[l]?.Type === "AWS::ECS::TaskDefinition");
|
|
43786
|
-
if (taskDefs.length === 0) throw notFoundError
|
|
43835
|
+
if (taskDefs.length === 0) throw notFoundError(target, stack, resources);
|
|
43787
43836
|
if (taskDefs.length > 1) throw new EcsTaskResolutionError(`Target '${target}' matches ${taskDefs.length} task definitions in ${stack.stackName}: ` + taskDefs.map((t) => t.logicalId).join(", ") + ". Refine the path or use the stack:LogicalId form.");
|
|
43788
43837
|
logicalId = taskDefs[0].logicalId;
|
|
43789
43838
|
resource = resources[logicalId];
|
|
43790
43839
|
} else {
|
|
43791
43840
|
resource = resources[parsed.pathOrId];
|
|
43792
|
-
if (!resource) throw notFoundError
|
|
43841
|
+
if (!resource) throw notFoundError(target, stack, resources);
|
|
43793
43842
|
logicalId = parsed.pathOrId;
|
|
43794
43843
|
}
|
|
43795
|
-
if (!logicalId || !resource) throw notFoundError
|
|
43844
|
+
if (!logicalId || !resource) throw notFoundError(target, stack, resources);
|
|
43796
43845
|
if (resource.Type === "AWS::Lambda::Function") throw new EcsTaskResolutionError(`Resource '${logicalId}' in ${stack.stackName} is a Lambda function, not an ECS task definition. Use \`cdkd local invoke\` for Lambda; \`cdkd local run-task\` is ECS only.`);
|
|
43797
43846
|
if (resource.Type !== "AWS::ECS::TaskDefinition") throw new EcsTaskResolutionError(`Resource '${logicalId}' in ${stack.stackName} is ${resource.Type}, not an AWS::ECS::TaskDefinition.`);
|
|
43798
43847
|
return extractTaskDefinitionProperties(stack, logicalId, resource, context);
|
|
43799
43848
|
}
|
|
43800
|
-
function pickStack$
|
|
43849
|
+
function pickStack$1(parsed, stacks) {
|
|
43801
43850
|
if (parsed.stackPattern === null) {
|
|
43802
43851
|
if (stacks.length === 1) return stacks[0];
|
|
43803
43852
|
throw new EcsTaskResolutionError(`Multiple stacks in app, target '${parsed.pathOrId}' is missing a stack prefix. Use 'StackName:${parsed.pathOrId}' or 'StackName/...' (path form). Available stacks: ${stacks.map((s) => s.stackName).join(", ")}.`);
|
|
@@ -44323,7 +44372,7 @@ function pickStringArray(value) {
|
|
|
44323
44372
|
for (const v of value) if (typeof v === "string") out.push(v);
|
|
44324
44373
|
return out;
|
|
44325
44374
|
}
|
|
44326
|
-
function notFoundError
|
|
44375
|
+
function notFoundError(target, stack, resources) {
|
|
44327
44376
|
const tasks = [];
|
|
44328
44377
|
for (const [logicalId, resource] of Object.entries(resources)) {
|
|
44329
44378
|
if (resource.Type !== "AWS::ECS::TaskDefinition") continue;
|
|
@@ -46216,7 +46265,7 @@ async function localStartApiCommand(target, options) {
|
|
|
46216
46265
|
await ensureDockerAvailable();
|
|
46217
46266
|
const appCmd = resolveApp(options.app);
|
|
46218
46267
|
if (!appCmd) throw new Error("No CDK app specified. Pass --app, set CDKD_APP, or add \"app\" to cdk.json.");
|
|
46219
|
-
const overrides = readEnvOverridesFile$
|
|
46268
|
+
const overrides = readEnvOverridesFile$3(options.envVars);
|
|
46220
46269
|
const debugPortBase = options.debugPortBase ? parseDebugPort(options.debugPortBase) : void 0;
|
|
46221
46270
|
const perLambdaConcurrency = parsePerLambdaConcurrency(options.perLambdaConcurrency);
|
|
46222
46271
|
const inlineTmpDirs = /* @__PURE__ */ new Set();
|
|
@@ -47182,7 +47231,7 @@ function getTemplateEnv$1(resource) {
|
|
|
47182
47231
|
return vars;
|
|
47183
47232
|
}
|
|
47184
47233
|
/** Read the SAM-shape `--env-vars` JSON file. */
|
|
47185
|
-
function readEnvOverridesFile$
|
|
47234
|
+
function readEnvOverridesFile$3(filePath) {
|
|
47186
47235
|
if (!filePath) return void 0;
|
|
47187
47236
|
let raw;
|
|
47188
47237
|
try {
|
|
@@ -47620,7 +47669,9 @@ const execFileAsync$2 = promisify(execFile);
|
|
|
47620
47669
|
* metadata AND `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=/role/<role-arn>`
|
|
47621
47670
|
* for IAM task-role credentials. cdkd does NOT re-implement the sidecar
|
|
47622
47671
|
* — pulling the AWS-published image keeps cdkd in lock-step with whatever
|
|
47623
|
-
* ECS-Agent fidelity AWS chooses to provide.
|
|
47672
|
+
* ECS-Agent fidelity AWS chooses to provide. The `cdkd local start-service`
|
|
47673
|
+
* / `start-alb` shared-network shape lives in cdk-local's bundled ECS
|
|
47674
|
+
* service emulator engine (see `src/cli/commands/ecs-service-emulator.ts`).
|
|
47624
47675
|
*/
|
|
47625
47676
|
/** AWS-published sidecar image (latest tag). amd64 is the only image AWS ships. */
|
|
47626
47677
|
const METADATA_ENDPOINT_IMAGE = "amazon/amazon-ecs-local-container-endpoints:latest-amd64";
|
|
@@ -47628,29 +47679,18 @@ const METADATA_ENDPOINT_IMAGE = "amazon/amazon-ecs-local-container-endpoints:lat
|
|
|
47628
47679
|
* Default well-known IP for the ECS local-container-endpoints sidecar —
|
|
47629
47680
|
* matches the documented AWS task-metadata endpoint address. Containers
|
|
47630
47681
|
* inject `ECS_CONTAINER_METADATA_URI_V4=http://169.254.170.2/v4/<id>`
|
|
47631
|
-
* to reach it.
|
|
47632
|
-
* start-service` creates ONE shared network at CLI startup (design
|
|
47633
|
-
* § 5 Option A) — the shared sidecar lives at `169.254.171.2` (see
|
|
47634
|
-
* `SHARED_SVC_SUBNET_OCTET` below), one octet up so the two CLI
|
|
47635
|
-
* variants can run on the same host without bridge-pool collision.
|
|
47682
|
+
* to reach it.
|
|
47636
47683
|
*/
|
|
47637
47684
|
const METADATA_ENDPOINT_IP = "169.254.170.2";
|
|
47638
47685
|
/** Default subnet — used when no `subnetOctet` override is supplied. */
|
|
47639
47686
|
const DEFAULT_METADATA_ENDPOINT_SUBNET = "169.254.170.0/24";
|
|
47640
47687
|
/**
|
|
47641
47688
|
* Pure-functional subnet allocator. `cdkd local run-task` uses the
|
|
47642
|
-
* default subnet
|
|
47643
|
-
*
|
|
47644
|
-
*
|
|
47645
|
-
*
|
|
47646
|
-
*
|
|
47647
|
-
* docker's `--subnet` allocator does not reject "Pool overlaps".
|
|
47648
|
-
*
|
|
47649
|
-
* `subnetOctet` is the second-from-last byte of the network: 170 →
|
|
47650
|
-
* 169.254.170.0/24 (default), 171 → 169.254.171.0/24, etc. Valid
|
|
47651
|
-
* range is 1..254; the runner clamps to `(170 + replicaIndex) % 84`
|
|
47652
|
-
* + 170 in practice (rolling window) — exported here so the runner
|
|
47653
|
-
* keeps the allocation logic in one place.
|
|
47689
|
+
* default subnet (`subnetOctet=170`). The link-local 169.254.0.0/16
|
|
47690
|
+
* space is reserved AWS-wide for cloud metadata so collisions with
|
|
47691
|
+
* user workloads are unlikely. `subnetOctet` is the second-from-last
|
|
47692
|
+
* byte of the network: 170 → 169.254.170.0/24 (default). Valid range
|
|
47693
|
+
* is 1..254.
|
|
47654
47694
|
*/
|
|
47655
47695
|
function buildEndpointSubnet(subnetOctet) {
|
|
47656
47696
|
if (subnetOctet < 1 || subnetOctet > 254 || !Number.isInteger(subnetOctet)) throw new Error(`buildEndpointSubnet: subnetOctet must be an integer in 1..254 (got ${subnetOctet}).`);
|
|
@@ -47660,50 +47700,12 @@ function buildEndpointSubnet(subnetOctet) {
|
|
|
47660
47700
|
};
|
|
47661
47701
|
}
|
|
47662
47702
|
/**
|
|
47663
|
-
*
|
|
47664
|
-
*
|
|
47665
|
-
*
|
|
47666
|
-
*
|
|
47667
|
-
*
|
|
47668
|
-
*
|
|
47669
|
-
* container that joins this one network.
|
|
47670
|
-
*/
|
|
47671
|
-
const SHARED_SVC_SUBNET_OCTET = 171;
|
|
47672
|
-
/**
|
|
47673
|
-
* Create the one shared docker network + metadata-endpoints sidecar
|
|
47674
|
-
* used by every service-replica boot in a single
|
|
47675
|
-
* `cdkd local start-service` invocation. This is design doc § 5
|
|
47676
|
-
* Option A — one network per CLI invocation instead of one network
|
|
47677
|
-
* per task — so peer services can reach each other by IP / network
|
|
47678
|
-
* alias without docker `--network connect` choreography (Option B,
|
|
47679
|
-
* rejected in design § 5 as "unwieldy and racy"). The returned
|
|
47680
|
-
* `TaskNetwork` carries `ownedByCaller: true` so `cleanupEcsRun()`
|
|
47681
|
-
* (called per replica by the service runner) does NOT teardown — the
|
|
47682
|
-
* CLI tears down ONCE at the end of the run.
|
|
47683
|
-
*/
|
|
47684
|
-
async function createSharedSvcNetwork(options = {}) {
|
|
47685
|
-
const networkName = `${options.prefix ?? "cdkd-local"}-svc-${randomBytes(4).toString("hex")}`;
|
|
47686
|
-
const { cidr, sidecarIp } = buildEndpointSubnet(171);
|
|
47687
|
-
return {
|
|
47688
|
-
networkName,
|
|
47689
|
-
sidecarContainerId: await createNetworkAndSidecar({
|
|
47690
|
-
networkName,
|
|
47691
|
-
cidr,
|
|
47692
|
-
sidecarIp,
|
|
47693
|
-
skipPull: options.skipPull ?? false,
|
|
47694
|
-
...options.credentials !== void 0 ? { credentials: options.credentials } : {},
|
|
47695
|
-
...options.cluster !== void 0 ? { cluster: options.cluster } : {}
|
|
47696
|
-
}),
|
|
47697
|
-
sidecarIp,
|
|
47698
|
-
ownedByCaller: true
|
|
47699
|
-
};
|
|
47700
|
-
}
|
|
47701
|
-
/**
|
|
47702
|
-
* Internal helper shared by `createTaskNetwork` (per-task) and
|
|
47703
|
-
* `createSharedSvcNetwork` (per-CLI-run). Creates the docker network,
|
|
47704
|
-
* pulls the sidecar image, and starts the sidecar at the documented
|
|
47705
|
-
* IP. Throws `DockerRunnerError` with a hint when the network already
|
|
47706
|
-
* exists (the typical "leftover from previous run" path).
|
|
47703
|
+
* Internal helper that creates the docker network, pulls the sidecar image,
|
|
47704
|
+
* and starts the sidecar at the documented IP. Throws `DockerRunnerError`
|
|
47705
|
+
* with a hint when the network already exists (the typical "leftover from
|
|
47706
|
+
* previous run" path). Used by `createTaskNetwork` (per-task) only;
|
|
47707
|
+
* `cdkd local start-service` / `start-alb` share-network creation is owned
|
|
47708
|
+
* by cdk-local's bundled ECS service emulator engine.
|
|
47707
47709
|
*/
|
|
47708
47710
|
async function createNetworkAndSidecar(args) {
|
|
47709
47711
|
const logger = getLogger().child("ecs-network");
|
|
@@ -48209,7 +48211,7 @@ async function waitForContainerHealthy(containerId, displayName) {
|
|
|
48209
48211
|
if (err instanceof EcsTaskRunnerError) throw err;
|
|
48210
48212
|
logger.debug(`docker inspect on '${displayName}' failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
48211
48213
|
}
|
|
48212
|
-
await sleep
|
|
48214
|
+
await sleep(1e3);
|
|
48213
48215
|
}
|
|
48214
48216
|
throw new EcsTaskRunnerError(`Container '${displayName}' did not become healthy within 5 minutes.`);
|
|
48215
48217
|
}
|
|
@@ -48233,7 +48235,7 @@ async function stopContainer(containerId, graceSeconds) {
|
|
|
48233
48235
|
]);
|
|
48234
48236
|
} catch {}
|
|
48235
48237
|
}
|
|
48236
|
-
function sleep
|
|
48238
|
+
function sleep(ms) {
|
|
48237
48239
|
return new Promise((res) => setTimeout(res, ms));
|
|
48238
48240
|
}
|
|
48239
48241
|
/**
|
|
@@ -48537,9 +48539,9 @@ async function localRunTaskCommand(target, options) {
|
|
|
48537
48539
|
...options.profile && { macroExpandS3ClientOpts: { profile: options.profile } }
|
|
48538
48540
|
};
|
|
48539
48541
|
const { stacks } = await synthesizer.synthesize(synthOpts);
|
|
48540
|
-
const candidate = pickCandidateStack
|
|
48542
|
+
const candidate = pickCandidateStack(parseEcsTarget(target).stackPattern, stacks);
|
|
48541
48543
|
stateProvider = createLocalStateProvider$1(options, candidate?.stackName ?? "", candidate?.region);
|
|
48542
|
-
const imageContext = await buildEcsImageResolutionContext$
|
|
48544
|
+
const imageContext = await buildEcsImageResolutionContext$1(candidate, stateProvider, options);
|
|
48543
48545
|
const task = resolveEcsTaskTarget(target, stacks, imageContext);
|
|
48544
48546
|
logger.info(`Target: ${task.stack.stackName}/${task.taskDefinitionLogicalId} (family=${task.family}, containers=${task.containers.length})`);
|
|
48545
48547
|
const taskNeeds = detectEcsImageResolutionNeeds(stacks.find((s) => s.stackName === task.stack.stackName) ?? task.stack);
|
|
@@ -48567,15 +48569,15 @@ async function localRunTaskCommand(target, options) {
|
|
|
48567
48569
|
let resolvedRoleArn;
|
|
48568
48570
|
if (options.assumeTaskRole === true) {
|
|
48569
48571
|
if (!task.taskRoleArn) throw new Error("--assume-task-role passed without an ARN but the task definition has no resolvable TaskRoleArn. Either the task definition does not set TaskRoleArn, or it points at a resource cdkd cannot resolve to an IAM Role at synth time. Pass the ARN explicitly: --assume-task-role <arn>");
|
|
48570
|
-
resolvedRoleArn = await resolvePlaceholderAccount
|
|
48571
|
-
assumedCredentials = await assumeTaskRole
|
|
48572
|
+
resolvedRoleArn = await resolvePlaceholderAccount(task.taskRoleArn, options.region);
|
|
48573
|
+
assumedCredentials = await assumeTaskRole(resolvedRoleArn, options.region);
|
|
48572
48574
|
} else if (typeof options.assumeTaskRole === "string") {
|
|
48573
48575
|
resolvedRoleArn = options.assumeTaskRole;
|
|
48574
|
-
assumedCredentials = await assumeTaskRole
|
|
48576
|
+
assumedCredentials = await assumeTaskRole(resolvedRoleArn, options.region);
|
|
48575
48577
|
}
|
|
48576
48578
|
const sidecarCredentials = await resolveSidecarCredentials(options, assumedCredentials);
|
|
48577
48579
|
if (options.profile && sidecarCredentials && !assumedCredentials) profileCredsFile = await writeProfileCredentialsFile(options.profile, sidecarCredentials);
|
|
48578
|
-
const envOverrides = readEnvOverridesFile$
|
|
48580
|
+
const envOverrides = readEnvOverridesFile$2(options.envVars);
|
|
48579
48581
|
const runOpts = {
|
|
48580
48582
|
cluster: options.cluster,
|
|
48581
48583
|
containerHost: options.containerHost,
|
|
@@ -48616,7 +48618,7 @@ async function localRunTaskCommand(target, options) {
|
|
|
48616
48618
|
* Lazy: callers should only invoke this when the resolved ARN is actually
|
|
48617
48619
|
* going to be used (i.e. on the bare `--assume-task-role` path).
|
|
48618
48620
|
*/
|
|
48619
|
-
async function resolvePlaceholderAccount
|
|
48621
|
+
async function resolvePlaceholderAccount(arn, region) {
|
|
48620
48622
|
if (!arn.includes("${AWS::AccountId}")) return arn;
|
|
48621
48623
|
const { STSClient, GetCallerIdentityCommand } = await import("@aws-sdk/client-sts");
|
|
48622
48624
|
const sts = new STSClient({ ...region && { region } });
|
|
@@ -48632,7 +48634,7 @@ async function resolvePlaceholderAccount$1(arn, region) {
|
|
|
48632
48634
|
* Assume `roleArn` and return temp credentials. Mirrors the same flow
|
|
48633
48635
|
* `cdkd local invoke --assume-role` uses.
|
|
48634
48636
|
*/
|
|
48635
|
-
async function assumeTaskRole
|
|
48637
|
+
async function assumeTaskRole(roleArn, region) {
|
|
48636
48638
|
const { STSClient, AssumeRoleCommand } = await import("@aws-sdk/client-sts");
|
|
48637
48639
|
const sts = new STSClient({ ...region && { region } });
|
|
48638
48640
|
try {
|
|
@@ -48663,7 +48665,7 @@ async function assumeTaskRole$1(roleArn, region) {
|
|
|
48663
48665
|
* `--from-state` and `--from-cfn-stack` produce the same downstream
|
|
48664
48666
|
* context shape (issue #606).
|
|
48665
48667
|
*/
|
|
48666
|
-
async function buildEcsImageResolutionContext$
|
|
48668
|
+
async function buildEcsImageResolutionContext$1(candidate, stateProvider, options) {
|
|
48667
48669
|
const logger = getLogger();
|
|
48668
48670
|
if (!candidate) return void 0;
|
|
48669
48671
|
const needs = detectEcsImageResolutionNeeds(candidate);
|
|
@@ -48675,7 +48677,7 @@ async function buildEcsImageResolutionContext$2(candidate, stateProvider, option
|
|
|
48675
48677
|
if (!region) logger.warn("Resolver references ${AWS::Region} but cdkd could not determine the target region. Pass --region, set AWS_REGION, or declare env.region on the CDK stack.");
|
|
48676
48678
|
let accountId;
|
|
48677
48679
|
try {
|
|
48678
|
-
accountId = await resolveCallerAccountId$
|
|
48680
|
+
accountId = await resolveCallerAccountId$1(region);
|
|
48679
48681
|
} catch (err) {
|
|
48680
48682
|
logger.warn(`Resolver needs \${AWS::AccountId} but STS GetCallerIdentity failed: ${err instanceof Error ? err.message : String(err)}. Substitution will be skipped; affected env / secret entries will be dropped with per-key warnings.`);
|
|
48681
48683
|
}
|
|
@@ -48697,7 +48699,7 @@ async function buildEcsImageResolutionContext$2(candidate, stateProvider, option
|
|
|
48697
48699
|
else if (!stateProvider && needs.needsEnvOrSecretSubstitution) logger.warn("Container Environment / Secrets entries contain CloudFormation intrinsics (Ref / Fn::GetAtt / Fn::Sub / Fn::Join). Pass --from-state (cdkd-deployed) or --from-cfn-stack (cdk-deployed) to substitute them against deployed state. Without a state source these entries are dropped (per-key warnings will follow).");
|
|
48698
48700
|
return ctx;
|
|
48699
48701
|
}
|
|
48700
|
-
function pickCandidateStack
|
|
48702
|
+
function pickCandidateStack(stackPattern, stacks) {
|
|
48701
48703
|
if (stackPattern === null) {
|
|
48702
48704
|
if (stacks.length === 1) return stacks[0];
|
|
48703
48705
|
return;
|
|
@@ -48705,7 +48707,7 @@ function pickCandidateStack$1(stackPattern, stacks) {
|
|
|
48705
48707
|
const matched = matchStacks(stacks, [stackPattern]);
|
|
48706
48708
|
if (matched.length === 1) return matched[0];
|
|
48707
48709
|
}
|
|
48708
|
-
async function resolveCallerAccountId$
|
|
48710
|
+
async function resolveCallerAccountId$1(region) {
|
|
48709
48711
|
const { STSClient, GetCallerIdentityCommand } = await import("@aws-sdk/client-sts");
|
|
48710
48712
|
const sts = new STSClient({ ...region && { region } });
|
|
48711
48713
|
try {
|
|
@@ -48719,7 +48721,7 @@ async function resolveCallerAccountId$2(region) {
|
|
|
48719
48721
|
* `cdkd local invoke --env-vars`: top-level keys are container names, with
|
|
48720
48722
|
* `Parameters` reserved for global entries.
|
|
48721
48723
|
*/
|
|
48722
|
-
function readEnvOverridesFile$
|
|
48724
|
+
function readEnvOverridesFile$2(filePath) {
|
|
48723
48725
|
if (!filePath) return void 0;
|
|
48724
48726
|
let raw;
|
|
48725
48727
|
try {
|
|
@@ -48771,1072 +48773,42 @@ function createLocalRunTaskCommand() {
|
|
|
48771
48773
|
return cmd;
|
|
48772
48774
|
}
|
|
48773
48775
|
|
|
48774
|
-
//#endregion
|
|
48775
|
-
//#region src/local/ecs-service-resolver.ts
|
|
48776
|
-
/**
|
|
48777
|
-
* Walk the synth template to locate an `AWS::ECS::Service` by display
|
|
48778
|
-
* path or stack-qualified logical id, resolve its `TaskDefinition`
|
|
48779
|
-
* reference, and chain into the existing `resolveEcsTaskTarget` machinery
|
|
48780
|
-
* to produce a `ResolvedEcsService` carrying both the service knobs and
|
|
48781
|
-
* the underlying task descriptor.
|
|
48782
|
-
*
|
|
48783
|
-
* Target shape mirrors `cdkd local run-task`: `<Stack>/<DisplayPath>` or
|
|
48784
|
-
* `<Stack>:<LogicalId>`; single-stack apps may omit the stack prefix.
|
|
48785
|
-
*
|
|
48786
|
-
* Optional `context` (same as the task resolver) carries the ECR image
|
|
48787
|
-
* substitution data — pseudo parameters (Tier 1) + state-recorded
|
|
48788
|
-
* resources (Tier 2). The CLI builds it lazily when the candidate
|
|
48789
|
-
* service's task definition actually needs substitution.
|
|
48790
|
-
*/
|
|
48791
|
-
function resolveEcsServiceTarget(target, stacks, context) {
|
|
48792
|
-
if (stacks.length === 0) throw new EcsTaskResolutionError("No stacks found in the synthesized assembly.");
|
|
48793
|
-
const parsed = parseEcsTarget(target);
|
|
48794
|
-
const stack = pickStack$1(parsed, stacks);
|
|
48795
|
-
const resources = stack.template.Resources ?? {};
|
|
48796
|
-
let serviceLogicalId;
|
|
48797
|
-
let serviceResource;
|
|
48798
|
-
if (parsed.isPath) {
|
|
48799
|
-
const index = buildCdkPathIndex(stack.template);
|
|
48800
|
-
const services = resolveCdkPathToLogicalIds(parsed.pathOrId, index).filter(({ logicalId: l }) => resources[l]?.Type === "AWS::ECS::Service");
|
|
48801
|
-
if (services.length === 0) throw notFoundError(target, stack, resources);
|
|
48802
|
-
if (services.length > 1) throw new EcsTaskResolutionError(`Target '${target}' matches ${services.length} ECS services in ${stack.stackName}: ` + services.map((s) => s.logicalId).join(", ") + ". Refine the path or use the stack:LogicalId form.");
|
|
48803
|
-
serviceLogicalId = services[0].logicalId;
|
|
48804
|
-
serviceResource = resources[serviceLogicalId];
|
|
48805
|
-
} else {
|
|
48806
|
-
serviceResource = resources[parsed.pathOrId];
|
|
48807
|
-
if (!serviceResource) throw notFoundError(target, stack, resources);
|
|
48808
|
-
serviceLogicalId = parsed.pathOrId;
|
|
48809
|
-
}
|
|
48810
|
-
if (!serviceLogicalId || !serviceResource) throw notFoundError(target, stack, resources);
|
|
48811
|
-
if (serviceResource.Type === "AWS::ECS::TaskDefinition") throw new EcsTaskResolutionError(`Resource '${serviceLogicalId}' in ${stack.stackName} is an ECS TaskDefinition, not a Service. Use \`cdkd local run-task\` for one-shot tasks; \`cdkd local start-service\` is Service-only.`);
|
|
48812
|
-
if (serviceResource.Type !== "AWS::ECS::Service") throw new EcsTaskResolutionError(`Resource '${serviceLogicalId}' in ${stack.stackName} is ${serviceResource.Type}, not an AWS::ECS::Service.`);
|
|
48813
|
-
return extractServiceProperties(stack, serviceLogicalId, serviceResource, stacks, context);
|
|
48814
|
-
}
|
|
48815
|
-
/**
|
|
48816
|
-
* Pure-functional extraction from the synth resource. Exposed for unit
|
|
48817
|
-
* testing the per-field resolution rules (DesiredCount default, missing
|
|
48818
|
-
* TaskDefinition, intrinsic shapes).
|
|
48819
|
-
*/
|
|
48820
|
-
function extractServiceProperties(stack, serviceLogicalId, resource, stacks, context) {
|
|
48821
|
-
const props = resource.Properties ?? {};
|
|
48822
|
-
const warnings = [];
|
|
48823
|
-
const taskDefRef = props["TaskDefinition"];
|
|
48824
|
-
if (taskDefRef === void 0 || taskDefRef === null) throw new EcsTaskResolutionError(`ECS Service '${serviceLogicalId}' in ${stack.stackName} has no TaskDefinition property.`);
|
|
48825
|
-
const taskDefLogicalId = resolveTaskDefinitionReference(taskDefRef, stack, serviceLogicalId);
|
|
48826
|
-
const task = resolveEcsTaskTarget(`${stack.stackName}:${taskDefLogicalId}`, stacks, context);
|
|
48827
|
-
const desiredCount = parseDesiredCount(props["DesiredCount"], serviceLogicalId);
|
|
48828
|
-
const healthCheckGracePeriodSeconds = parseHealthCheckGrace(props["HealthCheckGracePeriodSeconds"], serviceLogicalId);
|
|
48829
|
-
const serviceName = parseServiceName(props["ServiceName"], serviceLogicalId);
|
|
48830
|
-
if (Array.isArray(props["LoadBalancers"]) && props["LoadBalancers"].length > 0) warnings.push(`ECS Service '${serviceLogicalId}' declares LoadBalancers, but local load-balancer emulation is deferred to a follow-up PR. Containers are NOT registered to a local listener; reach them via their published ports.`);
|
|
48831
|
-
const serviceConnect = extractServiceConnect(props["ServiceConnectConfiguration"], task);
|
|
48832
|
-
const out = {
|
|
48833
|
-
stack,
|
|
48834
|
-
serviceLogicalId,
|
|
48835
|
-
resource,
|
|
48836
|
-
serviceName,
|
|
48837
|
-
desiredCount,
|
|
48838
|
-
healthCheckGracePeriodSeconds,
|
|
48839
|
-
task,
|
|
48840
|
-
serviceRegistries: extractServiceRegistries(props["ServiceRegistries"], serviceLogicalId, warnings),
|
|
48841
|
-
warnings
|
|
48842
|
-
};
|
|
48843
|
-
if (serviceConnect) out.serviceConnect = serviceConnect;
|
|
48844
|
-
return out;
|
|
48845
|
-
}
|
|
48846
|
-
/**
|
|
48847
|
-
* Parse `ServiceConnectConfiguration` against the producer TaskDef.
|
|
48848
|
-
* Returns `undefined` when the block is missing OR `Enabled: false`.
|
|
48849
|
-
*
|
|
48850
|
-
* Reject conditions (surface as resolver-time errors so the user sees
|
|
48851
|
-
* them BEFORE the docker network is created):
|
|
48852
|
-
* - `Namespace` is not a literal string. CDK 2.x always emits a
|
|
48853
|
-
* literal string here (verified 2026-05-22); cross-stack /
|
|
48854
|
-
* intrinsic shapes are out of scope.
|
|
48855
|
-
* - `Services[].PortName` doesn't match any of the TaskDef's
|
|
48856
|
-
* `ContainerDefinitions[].PortMappings[].Name` entries.
|
|
48857
|
-
*
|
|
48858
|
-
* Note on `clientAliases[]` shape: each ClientAlias can declare a
|
|
48859
|
-
* `DnsName` (the bare short-name peers connect to, e.g. `orders`) AND
|
|
48860
|
-
* a `Port` (the listening port the alias maps to inside the consumer).
|
|
48861
|
-
* cdkd surfaces both verbatim; the registry / `--add-host` overlay
|
|
48862
|
-
* publishes each `DnsName` as a bare alias pointing at the same IP as
|
|
48863
|
-
* the canonical fqdn.
|
|
48864
|
-
*/
|
|
48865
|
-
function extractServiceConnect(raw, task) {
|
|
48866
|
-
if (!raw || typeof raw !== "object") return void 0;
|
|
48867
|
-
const cfg = raw;
|
|
48868
|
-
if (cfg["Enabled"] === false) return void 0;
|
|
48869
|
-
const namespaceName = pickServiceConnectNamespace(cfg["Namespace"]);
|
|
48870
|
-
if (!namespaceName) throw new EcsTaskResolutionError(`ServiceConnectConfiguration.Namespace must be a literal string (the Cloud Map namespace name like 'cdkd-local.local'); got ${JSON.stringify(cfg["Namespace"])}. Intrinsic / cross-stack namespace references are not supported in v1.`);
|
|
48871
|
-
const rawServices = cfg["Services"];
|
|
48872
|
-
if (!Array.isArray(rawServices) || rawServices.length === 0) return {
|
|
48873
|
-
namespaceName,
|
|
48874
|
-
services: []
|
|
48875
|
-
};
|
|
48876
|
-
const portByName = /* @__PURE__ */ new Map();
|
|
48877
|
-
for (const c of task.containers) for (const pm of c.portMappings) if (pm.name) portByName.set(pm.name, pm.containerPort);
|
|
48878
|
-
const services = [];
|
|
48879
|
-
for (const entry of rawServices) {
|
|
48880
|
-
if (!entry || typeof entry !== "object") continue;
|
|
48881
|
-
const e = entry;
|
|
48882
|
-
const portName = typeof e["PortName"] === "string" ? e["PortName"] : void 0;
|
|
48883
|
-
if (!portName) throw new EcsTaskResolutionError(`ServiceConnectConfiguration.Services[] entry has no PortName: ${JSON.stringify(entry)}. Every Service entry must reference a producer-side PortMappings[].Name.`);
|
|
48884
|
-
const containerPort = portByName.get(portName);
|
|
48885
|
-
if (containerPort === void 0) throw new EcsTaskResolutionError(`ServiceConnectConfiguration.Services[].PortName='${portName}' does not match any PortMappings[].Name on the producer TaskDef (available: ${[...portByName.keys()].join(", ") || "(none)"}).`);
|
|
48886
|
-
const clientAliases = [];
|
|
48887
|
-
if (Array.isArray(e["ClientAliases"])) for (const ca of e["ClientAliases"]) {
|
|
48888
|
-
if (!ca || typeof ca !== "object") continue;
|
|
48889
|
-
const caObj = ca;
|
|
48890
|
-
const dnsName = typeof caObj["DnsName"] === "string" ? caObj["DnsName"] : void 0;
|
|
48891
|
-
const aliasEntry = { port: typeof caObj["Port"] === "number" ? caObj["Port"] : containerPort };
|
|
48892
|
-
if (dnsName !== void 0) aliasEntry.dnsName = dnsName;
|
|
48893
|
-
clientAliases.push(aliasEntry);
|
|
48894
|
-
}
|
|
48895
|
-
const discoveryName = clientAliases.find((c) => c.dnsName !== void 0)?.dnsName ?? portName;
|
|
48896
|
-
services.push({
|
|
48897
|
-
portName,
|
|
48898
|
-
containerPort,
|
|
48899
|
-
discoveryName,
|
|
48900
|
-
clientAliases
|
|
48901
|
-
});
|
|
48902
|
-
}
|
|
48903
|
-
return {
|
|
48904
|
-
namespaceName,
|
|
48905
|
-
services
|
|
48906
|
-
};
|
|
48907
|
-
}
|
|
48908
|
-
/**
|
|
48909
|
-
* Parse `ServiceRegistries[]`. Each entry's `RegistryArn` is the
|
|
48910
|
-
* canonical `Fn::GetAtt: [<CloudMapServiceLogicalId>, 'Arn']` shape;
|
|
48911
|
-
* cdkd surfaces the logical id (the AWS-side ARN is irrelevant
|
|
48912
|
-
* locally — the registry is in-process).
|
|
48913
|
-
*
|
|
48914
|
-
* Issue #544 — entries with a literal-string `RegistryArn` (rare
|
|
48915
|
-
* locally — would imply the user bound to an existing Cloud Map
|
|
48916
|
-
* service deployed out-of-band) are skipped with a warning, since the
|
|
48917
|
-
* in-process registry cannot resolve an external Cloud Map service
|
|
48918
|
-
* back to its `(namespace, name)` pair. Pre-fix this was a silent
|
|
48919
|
-
* `continue` and the user got no feedback about why the registration
|
|
48920
|
-
* didn't show up.
|
|
48921
|
-
*/
|
|
48922
|
-
function extractServiceRegistries(raw, serviceLogicalId, warnings) {
|
|
48923
|
-
if (!Array.isArray(raw)) return [];
|
|
48924
|
-
const out = [];
|
|
48925
|
-
for (const entry of raw) {
|
|
48926
|
-
if (!entry || typeof entry !== "object") continue;
|
|
48927
|
-
const e = entry;
|
|
48928
|
-
const registryArn = e["RegistryArn"];
|
|
48929
|
-
let cloudMapServiceLogicalId;
|
|
48930
|
-
if (typeof registryArn === "string") {
|
|
48931
|
-
warnings.push(`ECS Service '${serviceLogicalId}' ServiceRegistries[] entry has a literal-string RegistryArn ('${registryArn}'); cdkd cannot resolve external Cloud Map services locally. Skipping this registration; peer services will not discover this endpoint through the in-process registry. Use Fn::GetAtt: [<CloudMapServiceLogicalId>, "Arn"] instead so cdkd can resolve the namespace + service name from the synthesized template.`);
|
|
48932
|
-
continue;
|
|
48933
|
-
}
|
|
48934
|
-
if (registryArn && typeof registryArn === "object" && !Array.isArray(registryArn)) {
|
|
48935
|
-
const getAtt = registryArn["Fn::GetAtt"];
|
|
48936
|
-
if (Array.isArray(getAtt) && typeof getAtt[0] === "string") cloudMapServiceLogicalId = getAtt[0];
|
|
48937
|
-
}
|
|
48938
|
-
if (!cloudMapServiceLogicalId) continue;
|
|
48939
|
-
const reg = { cloudMapServiceLogicalId };
|
|
48940
|
-
if (typeof e["ContainerName"] === "string") reg.containerName = e["ContainerName"];
|
|
48941
|
-
if (typeof e["ContainerPort"] === "number") reg.containerPort = e["ContainerPort"];
|
|
48942
|
-
out.push(reg);
|
|
48943
|
-
}
|
|
48944
|
-
return out;
|
|
48945
|
-
}
|
|
48946
|
-
function pickServiceConnectNamespace(raw) {
|
|
48947
|
-
if (typeof raw === "string" && raw.length > 0) return raw;
|
|
48948
|
-
}
|
|
48949
|
-
/**
|
|
48950
|
-
* Resolve `Properties.TaskDefinition` to a logical id in the same stack.
|
|
48951
|
-
* Accepted shapes — verified against real CDK 2.x `cdk synth` output on
|
|
48952
|
-
* 2026-05-22 (per `feedback_verify_cdk_synth_shape_before_resolver.md`):
|
|
48953
|
-
* - `{Ref: '<TaskDefLogicalId>'}` — the CDK-canonical shape emitted by
|
|
48954
|
-
* `new ecs.FargateService({ taskDefinition })`.
|
|
48955
|
-
* - flat string `'<TaskDefLogicalId>'` — accepted defensively but CDK
|
|
48956
|
-
* rarely emits this for cross-resource refs.
|
|
48957
|
-
* Other intrinsic shapes (`Fn::ImportValue` / `Fn::GetAtt` / etc.) are
|
|
48958
|
-
* rejected — cross-stack task definitions and `Fn::GetAtt` shapes have
|
|
48959
|
-
* no clean local resolution and would land here only as user errors.
|
|
48960
|
-
*/
|
|
48961
|
-
function resolveTaskDefinitionReference(taskDefRef, stack, serviceLogicalId) {
|
|
48962
|
-
if (typeof taskDefRef === "string") return taskDefRef;
|
|
48963
|
-
if (taskDefRef && typeof taskDefRef === "object" && !Array.isArray(taskDefRef)) {
|
|
48964
|
-
const refValue = taskDefRef["Ref"];
|
|
48965
|
-
if (typeof refValue === "string") {
|
|
48966
|
-
const target = (stack.template.Resources ?? {})[refValue];
|
|
48967
|
-
if (!target) throw new EcsTaskResolutionError(`ECS Service '${serviceLogicalId}' references TaskDefinition '${refValue}' but no such resource exists in ${stack.stackName}.`);
|
|
48968
|
-
if (target.Type !== "AWS::ECS::TaskDefinition") throw new EcsTaskResolutionError(`ECS Service '${serviceLogicalId}' references '${refValue}' as TaskDefinition but it is of type ${target.Type}, not AWS::ECS::TaskDefinition.`);
|
|
48969
|
-
return refValue;
|
|
48970
|
-
}
|
|
48971
|
-
}
|
|
48972
|
-
throw new EcsTaskResolutionError(`ECS Service '${serviceLogicalId}' has an unsupported TaskDefinition reference shape: ${JSON.stringify(taskDefRef)}. cdkd local start-service v1 supports only Ref to a same-stack AWS::ECS::TaskDefinition; cross-stack TaskDefinitions are deferred.`);
|
|
48973
|
-
}
|
|
48974
|
-
function parseDesiredCount(raw, serviceLogicalId) {
|
|
48975
|
-
if (raw === void 0 || raw === null) return 1;
|
|
48976
|
-
if (typeof raw === "number" && Number.isFinite(raw) && raw >= 0) return Math.floor(raw);
|
|
48977
|
-
if (typeof raw === "string" && /^\d+$/.test(raw)) return parseInt(raw, 10);
|
|
48978
|
-
throw new EcsTaskResolutionError(`ECS Service '${serviceLogicalId}' has an unsupported DesiredCount value: ${JSON.stringify(raw)}. Must be a non-negative integer.`);
|
|
48979
|
-
}
|
|
48980
|
-
function parseHealthCheckGrace(raw, _serviceLogicalId) {
|
|
48981
|
-
if (raw === void 0 || raw === null) return 30;
|
|
48982
|
-
if (typeof raw === "number" && Number.isFinite(raw) && raw >= 0) return Math.floor(raw);
|
|
48983
|
-
if (typeof raw === "string" && /^\d+$/.test(raw)) return parseInt(raw, 10);
|
|
48984
|
-
return 30;
|
|
48985
|
-
}
|
|
48986
|
-
function parseServiceName(raw, serviceLogicalId) {
|
|
48987
|
-
if (typeof raw === "string" && raw.length > 0) return raw;
|
|
48988
|
-
return serviceLogicalId;
|
|
48989
|
-
}
|
|
48990
|
-
/**
|
|
48991
|
-
* Local copy of the same `pickStack` helper used by the task resolver.
|
|
48992
|
-
* Kept in-file rather than exported from `ecs-task-resolver.ts` so future
|
|
48993
|
-
* service-specific extensions (e.g. cross-stack service-to-task refs)
|
|
48994
|
-
* can diverge without breaking the run-task code path.
|
|
48995
|
-
*/
|
|
48996
|
-
function pickStack$1(parsed, stacks) {
|
|
48997
|
-
if (parsed.stackPattern === null) {
|
|
48998
|
-
if (stacks.length === 1) return stacks[0];
|
|
48999
|
-
throw new EcsTaskResolutionError(`Target has no stack prefix, and the assembly contains ${stacks.length} stacks: ${stacks.map((s) => s.stackName).join(", ")}. Pass the target as 'Stack/Path' or 'Stack:LogicalId'.`);
|
|
49000
|
-
}
|
|
49001
|
-
const matched = matchStacks(stacks, [parsed.stackPattern]);
|
|
49002
|
-
if (matched.length === 0) throw new EcsTaskResolutionError(`No stack matches '${parsed.stackPattern}'. Available stacks: ${stacks.map((s) => s.stackName).join(", ")}.`);
|
|
49003
|
-
if (matched.length > 1) throw new EcsTaskResolutionError(`Multiple stacks match '${parsed.stackPattern}': ${matched.map((s) => s.stackName).join(", ")}. Refine the pattern.`);
|
|
49004
|
-
return matched[0];
|
|
49005
|
-
}
|
|
49006
|
-
function notFoundError(target, stack, resources) {
|
|
49007
|
-
const services = Object.entries(resources).filter(([, r]) => r.Type === "AWS::ECS::Service").map(([id]) => id);
|
|
49008
|
-
if (services.length === 0) return new EcsTaskResolutionError(`Target '${target}' did not match any resource in ${stack.stackName}, and the stack declares no AWS::ECS::Service resources at all.`);
|
|
49009
|
-
return new EcsTaskResolutionError(`Target '${target}' did not match any ECS Service in ${stack.stackName}. Available services: ${services.join(", ")}.`);
|
|
49010
|
-
}
|
|
49011
|
-
|
|
49012
|
-
//#endregion
|
|
49013
|
-
//#region src/local/ecs-service-runner.ts
|
|
49014
|
-
/**
|
|
49015
|
-
* Phase 2 of #262 — long-running ECS Service emulator. Wraps the existing
|
|
49016
|
-
* `ecs-task-runner` machinery in a replica pool: N concurrent task
|
|
49017
|
-
* instances per `DesiredCount`, each with its own docker network +
|
|
49018
|
-
* metadata sidecar + container set. Tasks that exit non-zero AFTER the
|
|
49019
|
-
* health-check grace period are restarted with exponential backoff so a
|
|
49020
|
-
* crash-looping container does not hammer docker.
|
|
49021
|
-
*
|
|
49022
|
-
* v1 scope (per the issue's PR-split recommendation):
|
|
49023
|
-
* - Replica pool sizing via `DesiredCount` clamped by `--max-tasks`.
|
|
49024
|
-
* - Restart-on-exit with exponential backoff (1s → 30s, capped) +
|
|
49025
|
-
* a per-instance retry counter so a permanently-broken container
|
|
49026
|
-
* stops compounding cleanup work.
|
|
49027
|
-
* - Long-running lifecycle (returns only on shutdown).
|
|
49028
|
-
*
|
|
49029
|
-
* Phase 3 of #262 (Issue #460) — Cloud Map / Service Connect peer
|
|
49030
|
-
* discovery is wired through `ServiceRunnerOptions.discovery`. When
|
|
49031
|
-
* supplied, every booted replica discovers its docker IP, registers
|
|
49032
|
-
* itself into the shared in-process `CloudMapRegistry`, and emits
|
|
49033
|
-
* `--add-host` flags so consumer containers reach peer services via
|
|
49034
|
-
* the canonical `<discoveryName>.<namespace>` fqdn. Envoy L7 sidecar
|
|
49035
|
-
* emulation (design Layer B) is deferred to a follow-up PR per the
|
|
49036
|
-
* design's §O5 "--no-envoy by default" recommendation.
|
|
49037
|
-
*
|
|
49038
|
-
* Deferred to follow-up PRs:
|
|
49039
|
-
* - Local load-balancer emulation (LB listener + target-group health
|
|
49040
|
-
* check + round-robin) — separate PR per the issue's PR-split.
|
|
49041
|
-
* - Envoy sidecar for Service Connect L7 routing / retries / circuit
|
|
49042
|
-
* breaking (Cloud Map DNS-only mode ships now).
|
|
49043
|
-
* - Rolling deployment (`--reload` / `--watch`).
|
|
49044
|
-
*/
|
|
49045
|
-
var EcsServiceRunnerError = class EcsServiceRunnerError extends Error {
|
|
49046
|
-
constructor(message) {
|
|
49047
|
-
super(message);
|
|
49048
|
-
this.name = "EcsServiceRunnerError";
|
|
49049
|
-
Object.setPrototypeOf(this, EcsServiceRunnerError.prototype);
|
|
49050
|
-
}
|
|
49051
|
-
};
|
|
49052
|
-
function createServiceRunState() {
|
|
49053
|
-
return {
|
|
49054
|
-
replicas: [],
|
|
49055
|
-
shuttingDown: false
|
|
49056
|
-
};
|
|
49057
|
-
}
|
|
49058
|
-
/**
|
|
49059
|
-
* Compute the effective replica count for a service: the smaller of
|
|
49060
|
-
* `service.desiredCount` and `--max-tasks`, floored at 1. Pure-
|
|
49061
|
-
* functional so the CLI can show the user what cdkd is about to do
|
|
49062
|
-
* before any docker calls fire.
|
|
49063
|
-
*/
|
|
49064
|
-
function computeReplicaCount(desiredCount, maxTasks) {
|
|
49065
|
-
if (maxTasks < 1) throw new EcsServiceRunnerError(`--max-tasks must be >= 1 (got ${maxTasks}); local dev needs at least one running replica.`);
|
|
49066
|
-
if (desiredCount <= 0) return 1;
|
|
49067
|
-
return Math.min(desiredCount, maxTasks);
|
|
49068
|
-
}
|
|
49069
|
-
/**
|
|
49070
|
-
* Exponential backoff schedule: 1s, 2s, 4s, 8s, 16s, 30s, 30s, ... Used
|
|
49071
|
-
* between restarts of a crash-looping replica so docker is not hammered
|
|
49072
|
-
* by the watcher loop. Exposed for unit testing.
|
|
49073
|
-
*/
|
|
49074
|
-
function backoffDelayMs(restartCount) {
|
|
49075
|
-
return Math.min(1e3 * Math.pow(2, Math.min(restartCount, 10)), 3e4);
|
|
49076
|
-
}
|
|
49077
|
-
/**
|
|
49078
|
-
* Maximum number of replica indices the per-replica subnet allocator
|
|
49079
|
-
* can serve without modulo-wrap collision. The allocator below walks
|
|
49080
|
-
* the link-local /24 range `169.254.170.0..169.254.253.0` (84 octets)
|
|
49081
|
-
* and **skips 171** because that octet is owned by the shared-service
|
|
49082
|
-
* network in design § 5 Option A (see `SHARED_SVC_SUBNET_OCTET`), so
|
|
49083
|
-
* the usable count is 83. The CLI's `--max-tasks` parser enforces this
|
|
49084
|
-
* cap before any boot work fires.
|
|
49085
|
-
*/
|
|
49086
|
-
const SUBNET_ALLOCATOR_RANGE = 83;
|
|
49087
|
-
/**
|
|
49088
|
-
* Defensive per-replica subnet octet allocator (Issue #544). Only used
|
|
49089
|
-
* when callers bypass the CLI's `sharedNetwork` construction — i.e.
|
|
49090
|
-
* test paths that hand-build `ServiceRunnerOptions.discovery` without
|
|
49091
|
-
* `sharedNetwork`, or the bare `cdkd local run-task`-shaped path that
|
|
49092
|
-
* runs one network per task. Production `cdkd local start-service`
|
|
49093
|
-
* runs always go through the shared network (design § 5 Option A) so
|
|
49094
|
-
* this allocator is unreachable in the standard path.
|
|
49095
|
-
*
|
|
49096
|
-
* Returns the second-from-last octet of the per-replica /24 (170 →
|
|
49097
|
-
* `169.254.170.0/24`). Walks the 83-slot output range
|
|
49098
|
-
* `[170, 172, 173, ..., 253]` — 171 is intentionally **skipped**
|
|
49099
|
-
* because it's reserved for the shared-service network sidecar
|
|
49100
|
-
* (`SHARED_SVC_SUBNET_OCTET`), and assigning a per-replica network
|
|
49101
|
-
* the same /24 would have docker reject the duplicate-subnet
|
|
49102
|
-
* `network create` with the cryptic "Pool overlaps with other one on
|
|
49103
|
-
* this address space" error.
|
|
49104
|
-
*/
|
|
49105
|
-
function pickSubnetOctet(index) {
|
|
49106
|
-
const candidate = 170 + (index % 83 + 83) % 83;
|
|
49107
|
-
return candidate < 171 ? candidate : candidate + 1;
|
|
49108
|
-
}
|
|
49109
|
-
/**
|
|
49110
|
-
* Decide whether a replica that just exited should restart. Pure-
|
|
49111
|
-
* functional so the watcher loop's policy is easy to unit-test.
|
|
49112
|
-
*/
|
|
49113
|
-
function shouldRestart(exitCode, policy) {
|
|
49114
|
-
if (policy === "none") return false;
|
|
49115
|
-
if (policy === "always") return true;
|
|
49116
|
-
return exitCode !== 0;
|
|
49117
|
-
}
|
|
49118
|
-
/**
|
|
49119
|
-
* Long-running entry point. Boots `replicaCount` instances of the
|
|
49120
|
-
* service's task descriptor, returns a controller object the CLI uses
|
|
49121
|
-
* to (1) wait for the first failure that gives up restarting and (2)
|
|
49122
|
-
* shut every replica down on SIGINT / SIGTERM.
|
|
49123
|
-
*
|
|
49124
|
-
* The returned `shutdown()` is idempotent and safe to call from
|
|
49125
|
-
* multiple SIGINT handlers (CLI's single-flight pattern wraps it
|
|
49126
|
-
* anyway).
|
|
49127
|
-
*/
|
|
49128
|
-
async function startEcsService(service, options, runState) {
|
|
49129
|
-
const logger = getLogger().child("ecs-service");
|
|
49130
|
-
for (const w of service.warnings) logger.warn(w);
|
|
49131
|
-
const replicaCount = computeReplicaCount(service.desiredCount, options.maxTasks);
|
|
49132
|
-
if (replicaCount < service.desiredCount) logger.warn(`Service '${service.serviceName}' template DesiredCount=${service.desiredCount} exceeds --max-tasks=${options.maxTasks}; running ${replicaCount} replica(s) locally. Raise --max-tasks to lift the cap, or accept the reduced concurrency for local dev.`);
|
|
49133
|
-
logger.info(`Starting ECS service '${service.serviceName}' with ${replicaCount} replica(s) (restartPolicy=${options.restartPolicy})`);
|
|
49134
|
-
for (let i = 0; i < replicaCount; i++) {
|
|
49135
|
-
const instance = {
|
|
49136
|
-
index: i,
|
|
49137
|
-
state: createEcsRunState(),
|
|
49138
|
-
restartCount: 0,
|
|
49139
|
-
shuttingDown: false,
|
|
49140
|
-
inFlightBoot: void 0,
|
|
49141
|
-
cloudMapHandles: []
|
|
49142
|
-
};
|
|
49143
|
-
runState.replicas.push(instance);
|
|
49144
|
-
const bootPromise = bootReplica(service, options, instance);
|
|
49145
|
-
instance.inFlightBoot = bootPromise;
|
|
49146
|
-
try {
|
|
49147
|
-
await bootPromise;
|
|
49148
|
-
} catch (err) {
|
|
49149
|
-
instance.lastError = err instanceof Error ? err : new Error(String(err));
|
|
49150
|
-
throw new EcsServiceRunnerError(`Failed to boot replica ${i} of service '${service.serviceName}': ${instance.lastError.message}`);
|
|
49151
|
-
} finally {
|
|
49152
|
-
instance.inFlightBoot = void 0;
|
|
49153
|
-
}
|
|
49154
|
-
}
|
|
49155
|
-
for (const instance of runState.replicas) watchReplica(service, options, instance, runState);
|
|
49156
|
-
return new ServiceController(service, runState, options);
|
|
49157
|
-
}
|
|
49158
|
-
/**
|
|
49159
|
-
* Public controller surface. The CLI awaits `controller.waitForShutdown()`
|
|
49160
|
-
* to block until the user ^Cs. `controller.shutdown()` is wired into the
|
|
49161
|
-
* SIGINT / SIGTERM handlers.
|
|
49162
|
-
*/
|
|
49163
|
-
var ServiceController = class {
|
|
49164
|
-
service;
|
|
49165
|
-
runState;
|
|
49166
|
-
options;
|
|
49167
|
-
shutdownResolve;
|
|
49168
|
-
shutdownPromise;
|
|
49169
|
-
/**
|
|
49170
|
-
* Single-flight wrapper for `shutdown()` so the fan-out cleanup runs
|
|
49171
|
-
* exactly once even when SIGINT and the CLI's outer `finally` both
|
|
49172
|
-
* fire (the canonical pattern documented in
|
|
49173
|
-
* `feedback_sigint_finally_cleanup_singleflight.md`). Built in the
|
|
49174
|
-
* constructor so every call to `shutdown()` resolves against the same
|
|
49175
|
-
* underlying promise.
|
|
49176
|
-
*/
|
|
49177
|
-
runShutdown;
|
|
49178
|
-
constructor(service, runState, options) {
|
|
49179
|
-
this.service = service;
|
|
49180
|
-
this.runState = runState;
|
|
49181
|
-
this.options = options;
|
|
49182
|
-
this.shutdownPromise = new Promise((resolve) => {
|
|
49183
|
-
this.shutdownResolve = resolve;
|
|
49184
|
-
});
|
|
49185
|
-
this.runShutdown = singleFlight(() => this.doShutdown());
|
|
49186
|
-
}
|
|
49187
|
-
/**
|
|
49188
|
-
* Returns the count of currently-active (non-shutting-down) replicas.
|
|
49189
|
-
* Exposed so the CLI can surface a one-line "service is degraded"
|
|
49190
|
-
* banner when restarts stop firing.
|
|
49191
|
-
*/
|
|
49192
|
-
activeReplicaCount() {
|
|
49193
|
-
return this.runState.replicas.filter((r) => !r.shuttingDown).length;
|
|
49194
|
-
}
|
|
49195
|
-
/**
|
|
49196
|
-
* Block until `shutdown()` is called. Used by the CLI as the
|
|
49197
|
-
* long-running blocking point — the SIGINT handler resolves it.
|
|
49198
|
-
*/
|
|
49199
|
-
waitForShutdown() {
|
|
49200
|
-
return this.shutdownPromise;
|
|
49201
|
-
}
|
|
49202
|
-
/**
|
|
49203
|
-
* Idempotent fan-out shutdown across every active replica. Wired into
|
|
49204
|
-
* both SIGINT and the outer `finally` of the CLI command; the
|
|
49205
|
-
* `singleFlight`-wrapped `runShutdown` collapses concurrent / repeated
|
|
49206
|
-
* callers to one underlying invocation.
|
|
49207
|
-
*/
|
|
49208
|
-
async shutdown() {
|
|
49209
|
-
await this.runShutdown();
|
|
49210
|
-
return this.shutdownPromise;
|
|
49211
|
-
}
|
|
49212
|
-
async doShutdown() {
|
|
49213
|
-
this.runState.shuttingDown = true;
|
|
49214
|
-
const logger = getLogger().child("ecs-service");
|
|
49215
|
-
logger.info(`Shutting down service '${this.service.serviceName}'...`);
|
|
49216
|
-
for (const r of this.runState.replicas) r.shuttingDown = true;
|
|
49217
|
-
const inFlightBoots = this.runState.replicas.map((r) => r.inFlightBoot).filter((p) => p !== void 0);
|
|
49218
|
-
if (inFlightBoots.length > 0) {
|
|
49219
|
-
logger.debug(`Awaiting ${inFlightBoots.length} in-flight bootReplica() call(s) before cleanup...`);
|
|
49220
|
-
await Promise.allSettled(inFlightBoots);
|
|
49221
|
-
}
|
|
49222
|
-
await Promise.allSettled(this.runState.replicas.map(async (instance) => {
|
|
49223
|
-
if (this.options.discovery) {
|
|
49224
|
-
for (const handle of instance.cloudMapHandles) try {
|
|
49225
|
-
this.options.discovery.registry.unregister(handle);
|
|
49226
|
-
} catch {}
|
|
49227
|
-
instance.cloudMapHandles = [];
|
|
49228
|
-
}
|
|
49229
|
-
try {
|
|
49230
|
-
await cleanupEcsRun(instance.state, { keepRunning: this.options.taskOptions.keepRunning });
|
|
49231
|
-
} catch (err) {
|
|
49232
|
-
logger.debug(`Replica ${instance.index} cleanup failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
49233
|
-
}
|
|
49234
|
-
}));
|
|
49235
|
-
this.shutdownResolve?.();
|
|
49236
|
-
}
|
|
49237
|
-
};
|
|
49238
|
-
/**
|
|
49239
|
-
* Build the `--network-alias` map for one service's containers (design
|
|
49240
|
-
* doc § 5 Option A). For every Service Connect entry, attach the
|
|
49241
|
-
* fqdn (`<discoveryName>.<namespaceName>`), the bare discoveryName,
|
|
49242
|
-
* AND every ClientAlias DnsName to the container that owns the
|
|
49243
|
-
* matching PortName. Other containers in the task get NO extra
|
|
49244
|
-
* aliases (only their default `--name`-derived alias from
|
|
49245
|
-
* `buildDockerRunArgs`).
|
|
49246
|
-
*
|
|
49247
|
-
* Aliases per container are de-duplicated so docker doesn't reject
|
|
49248
|
-
* a `--network-alias X` repeated against the same container.
|
|
49249
|
-
*
|
|
49250
|
-
* Returns an empty map when the service has no Service Connect — the
|
|
49251
|
-
* runner's `... .size > 0 ? { networkAliasesByContainer } : {}` guard
|
|
49252
|
-
* short-circuits in that case so backward-compat callers pay no cost.
|
|
49253
|
-
*/
|
|
49254
|
-
function buildNetworkAliasesByContainer(service) {
|
|
49255
|
-
const out = /* @__PURE__ */ new Map();
|
|
49256
|
-
const sc = service.serviceConnect;
|
|
49257
|
-
if (!sc) return out;
|
|
49258
|
-
for (const entry of sc.services) {
|
|
49259
|
-
const owner = service.task.containers.find((c) => c.portMappings.some((pm) => pm.name === entry.portName));
|
|
49260
|
-
if (!owner) continue;
|
|
49261
|
-
const aliases = [];
|
|
49262
|
-
aliases.push(entry.discoveryName);
|
|
49263
|
-
aliases.push(`${entry.discoveryName}.${sc.namespaceName}`);
|
|
49264
|
-
for (const ca of entry.clientAliases) if (ca.dnsName) aliases.push(ca.dnsName);
|
|
49265
|
-
const existing = out.get(owner.name) ?? [];
|
|
49266
|
-
for (const a of aliases) if (!existing.includes(a)) existing.push(a);
|
|
49267
|
-
out.set(owner.name, existing);
|
|
49268
|
-
}
|
|
49269
|
-
return out;
|
|
49270
|
-
}
|
|
49271
|
-
/**
|
|
49272
|
-
* Boot a single replica. Mutates the supplied `instance.state` so the
|
|
49273
|
-
* shutdown path's `cleanupEcsRun(instance.state)` covers every partial
|
|
49274
|
-
* side effect. Network names are suffixed with the replica index so
|
|
49275
|
-
* docker doesn't collide on shared per-task network names when N > 1.
|
|
49276
|
-
*/
|
|
49277
|
-
async function bootReplica(service, options, instance) {
|
|
49278
|
-
const logger = getLogger().child("ecs-service");
|
|
49279
|
-
const perReplicaCluster = `${options.taskOptions.cluster}-svc-${service.serviceLogicalId.toLowerCase()}-r${instance.index}`;
|
|
49280
|
-
const ownerKeyPrefix = `${service.serviceLogicalId}:r${instance.index}`;
|
|
49281
|
-
const addHostFlags = options.discovery?.registry ? options.discovery.registry.buildAddHostFlags(ownerKeyPrefix) : [];
|
|
49282
|
-
const sharedNetwork = options.discovery?.sharedNetwork;
|
|
49283
|
-
const networkAliasesByContainer = buildNetworkAliasesByContainer(service);
|
|
49284
|
-
const skipHostPortPublish = computeReplicaCount(service.desiredCount, options.maxTasks) > 1;
|
|
49285
|
-
const perReplicaTaskOptions = {
|
|
49286
|
-
...options.taskOptions,
|
|
49287
|
-
cluster: perReplicaCluster,
|
|
49288
|
-
detach: true,
|
|
49289
|
-
...skipHostPortPublish ? { skipHostPortPublish: true } : {},
|
|
49290
|
-
...sharedNetwork ? { existingNetwork: sharedNetwork } : { subnetOctet: pickSubnetOctet(instance.index) },
|
|
49291
|
-
...addHostFlags.length > 0 ? { addHostFlags } : {},
|
|
49292
|
-
...networkAliasesByContainer.size > 0 ? { networkAliasesByContainer } : {}
|
|
49293
|
-
};
|
|
49294
|
-
logger.info(`Booting replica ${instance.index} (${perReplicaCluster})`);
|
|
49295
|
-
await runEcsTask(service.task, perReplicaTaskOptions, instance.state);
|
|
49296
|
-
if (options.discovery) await publishReplicaToCloudMap(service, instance, options.discovery, ownerKeyPrefix);
|
|
49297
|
-
}
|
|
49298
|
-
/**
|
|
49299
|
-
* After the replica's main container is up, discover its docker
|
|
49300
|
-
* network IP and publish the configured Service Connect + Cloud Map
|
|
49301
|
-
* endpoints into the shared registry. The handles are tracked on the
|
|
49302
|
-
* instance so the shutdown / restart path can unregister symmetrically.
|
|
49303
|
-
*
|
|
49304
|
-
* Errors here are best-effort: docker inspect can fail right after run
|
|
49305
|
-
* (container vanished, network not fully wired), and the registry is
|
|
49306
|
-
* advisory — losing one replica's registration means peer services
|
|
49307
|
-
* can't reach it via the overlay, but it doesn't break that replica's
|
|
49308
|
-
* own work or AWS SDK calls.
|
|
49309
|
-
*/
|
|
49310
|
-
async function publishReplicaToCloudMap(service, instance, discovery, ownerKeyPrefix) {
|
|
49311
|
-
const logger = getLogger().child("ecs-service");
|
|
49312
|
-
const networkName = instance.state.network?.networkName;
|
|
49313
|
-
if (!networkName) return;
|
|
49314
|
-
const essential = service.task.containers.find((c) => c.essential) ?? service.task.containers[0];
|
|
49315
|
-
if (!essential) return;
|
|
49316
|
-
const started = instance.state.startedContainers.find((c) => c.name === essential.name);
|
|
49317
|
-
if (!started) return;
|
|
49318
|
-
let ip;
|
|
49319
|
-
try {
|
|
49320
|
-
ip = await getContainerNetworkIp(started.id, networkName);
|
|
49321
|
-
} catch (err) {
|
|
49322
|
-
logger.warn(`Replica ${instance.index}: docker inspect failed before Cloud Map publish: ${err instanceof Error ? err.message : String(err)}`);
|
|
49323
|
-
return;
|
|
49324
|
-
}
|
|
49325
|
-
if (!ip) {
|
|
49326
|
-
logger.warn(`Replica ${instance.index}: no docker IP discovered on network ${networkName}; skipping Cloud Map publish for this replica.`);
|
|
49327
|
-
return;
|
|
49328
|
-
}
|
|
49329
|
-
if (service.serviceConnect) {
|
|
49330
|
-
const ns = service.serviceConnect.namespaceName;
|
|
49331
|
-
const index = discovery.cloudMapIndexByStack.get(service.stack.stackName);
|
|
49332
|
-
if (index && !index.namespacesByName.has(ns)) logger.warn(`ECS Service '${service.serviceLogicalId}' ServiceConnectConfiguration.Namespace='${ns}' does not match any AWS::ServiceDiscovery::PrivateDnsNamespace declared in stack ${service.stack.stackName}. Publishing under the literal name anyway; peer services using the same literal will still discover this endpoint.`);
|
|
49333
|
-
let i = 0;
|
|
49334
|
-
for (const entry of service.serviceConnect.services) {
|
|
49335
|
-
const ownerKey = `${ownerKeyPrefix}:sc:${i}`;
|
|
49336
|
-
const handle = discovery.registry.register(ns, entry.discoveryName, {
|
|
49337
|
-
ip,
|
|
49338
|
-
port: entry.containerPort,
|
|
49339
|
-
ownerKey
|
|
49340
|
-
});
|
|
49341
|
-
instance.cloudMapHandles.push(handle);
|
|
49342
|
-
for (const alias of entry.clientAliases) if (alias.dnsName) discovery.registry.registerAlias(alias.dnsName, handle.fqdn);
|
|
49343
|
-
i++;
|
|
49344
|
-
}
|
|
49345
|
-
}
|
|
49346
|
-
if (service.serviceRegistries.length > 0) {
|
|
49347
|
-
const index = discovery.cloudMapIndexByStack.get(service.stack.stackName);
|
|
49348
|
-
if (!index) {
|
|
49349
|
-
logger.warn(`ECS Service '${service.serviceLogicalId}' declares ServiceRegistries[] but cdkd has no Cloud Map index for stack ${service.stack.stackName}. Skipping registration.`);
|
|
49350
|
-
return;
|
|
49351
|
-
}
|
|
49352
|
-
let j = 0;
|
|
49353
|
-
for (const reg of service.serviceRegistries) {
|
|
49354
|
-
const cm = index.servicesByLogicalId.get(reg.cloudMapServiceLogicalId);
|
|
49355
|
-
if (!cm) {
|
|
49356
|
-
logger.warn(`ECS Service '${service.serviceLogicalId}' ServiceRegistries[].cloudMapServiceLogicalId='${reg.cloudMapServiceLogicalId}' did not resolve to an AWS::ServiceDiscovery::Service in stack ${service.stack.stackName}. Skipping this registration.`);
|
|
49357
|
-
continue;
|
|
49358
|
-
}
|
|
49359
|
-
let port = reg.containerPort;
|
|
49360
|
-
if (port === void 0 && essential.portMappings.length > 0) port = essential.portMappings[0].containerPort;
|
|
49361
|
-
if (port === void 0) {
|
|
49362
|
-
logger.warn(`ECS Service '${service.serviceLogicalId}' ServiceRegistries[] entry for Cloud Map service '${cm.logicalId}' has no resolvable container port; skipping.`);
|
|
49363
|
-
continue;
|
|
49364
|
-
}
|
|
49365
|
-
const ownerKey = `${ownerKeyPrefix}:sr:${j}`;
|
|
49366
|
-
const handle = discovery.registry.register(cm.namespaceName, cm.name, {
|
|
49367
|
-
ip,
|
|
49368
|
-
port,
|
|
49369
|
-
ownerKey
|
|
49370
|
-
});
|
|
49371
|
-
instance.cloudMapHandles.push(handle);
|
|
49372
|
-
j++;
|
|
49373
|
-
}
|
|
49374
|
-
}
|
|
49375
|
-
}
|
|
49376
|
-
/**
|
|
49377
|
-
* Long-running watcher loop for one replica. Polls the essential
|
|
49378
|
-
* container's exit code via `docker wait`; on exit, decides whether to
|
|
49379
|
-
* restart per `restartPolicy` + applies exponential backoff. The loop
|
|
49380
|
-
* exits only when the replica's `shuttingDown` flag is set.
|
|
49381
|
-
*/
|
|
49382
|
-
async function watchReplica(service, options, instance, runState) {
|
|
49383
|
-
const logger = getLogger().child("ecs-service");
|
|
49384
|
-
while (!instance.shuttingDown && !runState.shuttingDown) {
|
|
49385
|
-
const essentialId = pickEssentialContainerId(instance, service);
|
|
49386
|
-
if (!essentialId) {
|
|
49387
|
-
await sleep(500);
|
|
49388
|
-
continue;
|
|
49389
|
-
}
|
|
49390
|
-
let exitCode;
|
|
49391
|
-
try {
|
|
49392
|
-
exitCode = await waitForExitImpl(essentialId);
|
|
49393
|
-
} catch (err) {
|
|
49394
|
-
logger.debug(`docker wait failed for replica ${instance.index}: ${err instanceof Error ? err.message : String(err)}`);
|
|
49395
|
-
exitCode = -1;
|
|
49396
|
-
}
|
|
49397
|
-
if (instance.shuttingDown || runState.shuttingDown) return;
|
|
49398
|
-
logger.warn(`Replica ${instance.index} essential container exited with code ${exitCode} (restartCount=${instance.restartCount}).`);
|
|
49399
|
-
if (!shouldRestart(exitCode, options.restartPolicy)) {
|
|
49400
|
-
logger.warn(`Replica ${instance.index} not restarting (policy=${options.restartPolicy}, exit=${exitCode}). Service running in degraded mode.`);
|
|
49401
|
-
instance.shuttingDown = true;
|
|
49402
|
-
return;
|
|
49403
|
-
}
|
|
49404
|
-
const delay = backoffDelayMs(instance.restartCount);
|
|
49405
|
-
logger.info(`Restarting replica ${instance.index} in ${delay}ms...`);
|
|
49406
|
-
await sleep(delay);
|
|
49407
|
-
if (instance.shuttingDown || runState.shuttingDown) return;
|
|
49408
|
-
if (options.discovery) {
|
|
49409
|
-
for (const handle of instance.cloudMapHandles) try {
|
|
49410
|
-
options.discovery.registry.unregister(handle);
|
|
49411
|
-
} catch {}
|
|
49412
|
-
instance.cloudMapHandles = [];
|
|
49413
|
-
}
|
|
49414
|
-
try {
|
|
49415
|
-
await cleanupEcsRun(instance.state, { keepRunning: false });
|
|
49416
|
-
} catch (err) {
|
|
49417
|
-
logger.debug(`Replica ${instance.index} pre-restart cleanup failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
49418
|
-
}
|
|
49419
|
-
instance.state = createEcsRunState();
|
|
49420
|
-
instance.restartCount += 1;
|
|
49421
|
-
const bootPromise = bootReplica(service, options, instance);
|
|
49422
|
-
instance.inFlightBoot = bootPromise;
|
|
49423
|
-
try {
|
|
49424
|
-
await bootPromise;
|
|
49425
|
-
} catch (err) {
|
|
49426
|
-
instance.lastError = err instanceof Error ? err : new Error(String(err));
|
|
49427
|
-
logger.error(`Replica ${instance.index} restart failed: ${instance.lastError.message}. Service running in degraded mode.`);
|
|
49428
|
-
instance.shuttingDown = true;
|
|
49429
|
-
return;
|
|
49430
|
-
} finally {
|
|
49431
|
-
instance.inFlightBoot = void 0;
|
|
49432
|
-
}
|
|
49433
|
-
}
|
|
49434
|
-
}
|
|
49435
|
-
function pickEssentialContainerId(instance, service) {
|
|
49436
|
-
if (service) {
|
|
49437
|
-
const essential = service.task.containers.find((c) => c.essential) ?? service.task.containers[0];
|
|
49438
|
-
if (essential) {
|
|
49439
|
-
const started = instance.state.startedContainers.find((c) => c.name === essential.name);
|
|
49440
|
-
if (started) return started.id;
|
|
49441
|
-
}
|
|
49442
|
-
}
|
|
49443
|
-
return instance.state.startedContainers[0]?.id;
|
|
49444
|
-
}
|
|
49445
|
-
/**
|
|
49446
|
-
* Production `docker wait <id>` implementation. Captured once so the
|
|
49447
|
-
* test override can restore it without duplicating the body.
|
|
49448
|
-
*/
|
|
49449
|
-
const defaultWaitForExitImpl = async (containerId) => {
|
|
49450
|
-
const { execFile } = await import("node:child_process");
|
|
49451
|
-
const { promisify } = await import("node:util");
|
|
49452
|
-
const { getDockerCmd } = await import("./docker-cmd-iDMcWcre.js").then((n) => n.t);
|
|
49453
|
-
const { stdout } = await promisify(execFile)(getDockerCmd(), ["wait", containerId], { maxBuffer: 1024 * 1024 });
|
|
49454
|
-
const code = parseInt(stdout.trim(), 10);
|
|
49455
|
-
return Number.isFinite(code) ? code : -1;
|
|
49456
|
-
};
|
|
49457
|
-
/**
|
|
49458
|
-
* `docker wait <id>` returns the exit code on stdout. Extracted as a
|
|
49459
|
-
* test-overridable function so unit tests do not need a real container.
|
|
49460
|
-
*/
|
|
49461
|
-
let waitForExitImpl = defaultWaitForExitImpl;
|
|
49462
|
-
const defaultSleepImpl = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
49463
|
-
let sleepImpl = defaultSleepImpl;
|
|
49464
|
-
function sleep(ms) {
|
|
49465
|
-
return sleepImpl(ms);
|
|
49466
|
-
}
|
|
49467
|
-
|
|
49468
48776
|
//#endregion
|
|
49469
48777
|
//#region src/cli/commands/local-start-service.ts
|
|
49470
48778
|
/**
|
|
49471
|
-
* `
|
|
49472
|
-
*
|
|
49473
|
-
*
|
|
49474
|
-
*
|
|
49475
|
-
*
|
|
49476
|
-
* Deferred to follow-up PRs (matches the issue's PR-split):
|
|
49477
|
-
* - Local LB emulator (listener + round-robin + target-group health
|
|
49478
|
-
* check) — PR C of #466.
|
|
49479
|
-
* - Rolling deployment (`--watch` / `--reload`) — PR D of #466.
|
|
49480
|
-
* - Service Connect / Cloud Map — tracked separately in #460.
|
|
49481
|
-
*/
|
|
49482
|
-
async function localStartServiceCommand(targets, options) {
|
|
49483
|
-
const logger = getLogger();
|
|
49484
|
-
if (options.verbose) logger.setLevel("debug");
|
|
49485
|
-
warnIfDeprecatedRegion(options);
|
|
49486
|
-
const skipPull = options.pull === false;
|
|
49487
|
-
if (!targets || targets.length === 0) throw new LocalStartServiceError("cdkd local start-service requires at least one <target>. Pass one or more service paths like 'Stack/Orders' 'Stack/Frontend'.");
|
|
49488
|
-
rejectExplicitCfnStackWithMultipleStacks(options, targets.length);
|
|
49489
|
-
const perTarget = targets.map((t) => ({
|
|
49490
|
-
target: t,
|
|
49491
|
-
runState: createServiceRunState()
|
|
49492
|
-
}));
|
|
49493
|
-
let sigintHandler;
|
|
49494
|
-
let sigintCount = 0;
|
|
49495
|
-
let sharedNetwork;
|
|
49496
|
-
let profileCredsFile;
|
|
49497
|
-
const cleanup = singleFlight(async () => {
|
|
49498
|
-
await Promise.allSettled(perTarget.map(async (pt) => {
|
|
49499
|
-
if (pt.controller) await pt.controller.shutdown();
|
|
49500
|
-
else {
|
|
49501
|
-
await Promise.allSettled(pt.runState.replicas.map((r) => r.inFlightBoot).filter((p) => p !== void 0));
|
|
49502
|
-
await Promise.allSettled(pt.runState.replicas.map((r) => cleanupEcsRun(r.state, { keepRunning: false }).catch(() => void 0)));
|
|
49503
|
-
}
|
|
49504
|
-
}));
|
|
49505
|
-
if (profileCredsFile) {
|
|
49506
|
-
try {
|
|
49507
|
-
await profileCredsFile.dispose();
|
|
49508
|
-
} catch (err) {
|
|
49509
|
-
getLogger().warn(`Failed to remove profile credentials tmpdir ${profileCredsFile.hostPath}: ${err instanceof Error ? err.message : String(err)}`);
|
|
49510
|
-
}
|
|
49511
|
-
profileCredsFile = void 0;
|
|
49512
|
-
}
|
|
49513
|
-
if (sharedNetwork) {
|
|
49514
|
-
try {
|
|
49515
|
-
await destroyTaskNetwork(sharedNetwork);
|
|
49516
|
-
} catch (err) {
|
|
49517
|
-
getLogger().warn(`shared service network teardown failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
49518
|
-
}
|
|
49519
|
-
sharedNetwork = void 0;
|
|
49520
|
-
}
|
|
49521
|
-
}, (err) => getLogger().warn(`service cleanup failed: ${err instanceof Error ? err.message : String(err)}`));
|
|
49522
|
-
try {
|
|
49523
|
-
await applyRoleArnIfSet({
|
|
49524
|
-
roleArn: options.roleArn,
|
|
49525
|
-
region: options.region
|
|
49526
|
-
});
|
|
49527
|
-
await ensureDockerAvailable();
|
|
49528
|
-
const appCmd = resolveApp(options.app);
|
|
49529
|
-
if (!appCmd) throw new Error("No CDK app specified. Pass --app, set CDKD_APP, or add \"app\" to cdk.json.");
|
|
49530
|
-
logger.info("Synthesizing CDK app...");
|
|
49531
|
-
const synthesizer = new Synthesizer();
|
|
49532
|
-
const context = parseContextOptions(options.context);
|
|
49533
|
-
const synthOpts = {
|
|
49534
|
-
app: appCmd,
|
|
49535
|
-
output: options.output,
|
|
49536
|
-
...options.region && { region: options.region },
|
|
49537
|
-
...options.profile && { profile: options.profile },
|
|
49538
|
-
...Object.keys(context).length > 0 && { context },
|
|
49539
|
-
...options.stateBucket && { stateBucket: options.stateBucket },
|
|
49540
|
-
...options.profile && { macroExpandS3ClientOpts: { profile: options.profile } }
|
|
49541
|
-
};
|
|
49542
|
-
const { stacks } = await synthesizer.synthesize(synthOpts);
|
|
49543
|
-
const cloudMapIndexByStack = /* @__PURE__ */ new Map();
|
|
49544
|
-
for (const stack of stacks) {
|
|
49545
|
-
const index = buildCloudMapIndex(stack);
|
|
49546
|
-
cloudMapIndexByStack.set(stack.stackName, index);
|
|
49547
|
-
for (const w of index.warnings) logger.warn(w);
|
|
49548
|
-
}
|
|
49549
|
-
const registry = new CloudMapRegistry();
|
|
49550
|
-
const sidecarCredentials = await resolveSharedSidecarCredentials$1(options);
|
|
49551
|
-
try {
|
|
49552
|
-
sharedNetwork = await createSharedSvcNetwork({
|
|
49553
|
-
prefix: options.cluster,
|
|
49554
|
-
skipPull,
|
|
49555
|
-
cluster: options.cluster,
|
|
49556
|
-
...sidecarCredentials !== void 0 && { credentials: sidecarCredentials }
|
|
49557
|
-
});
|
|
49558
|
-
} catch (err) {
|
|
49559
|
-
throw new LocalStartServiceError(`Failed to create shared service network: ${err instanceof Error ? err.message : String(err)}`);
|
|
49560
|
-
}
|
|
49561
|
-
if (options.profile && sidecarCredentials) profileCredsFile = await writeProfileCredentialsFile(options.profile, sidecarCredentials);
|
|
49562
|
-
const discovery = {
|
|
49563
|
-
registry,
|
|
49564
|
-
cloudMapIndexByStack,
|
|
49565
|
-
sharedNetwork
|
|
49566
|
-
};
|
|
49567
|
-
sigintHandler = () => {
|
|
49568
|
-
sigintCount += 1;
|
|
49569
|
-
if (sigintCount >= 2) {
|
|
49570
|
-
process.stderr.write("Force-exit on second ^C; container cleanup skipped.\n");
|
|
49571
|
-
process.exit(130);
|
|
49572
|
-
}
|
|
49573
|
-
logger.info("Stopping service(s)...");
|
|
49574
|
-
cleanup().then(() => process.exit(130));
|
|
49575
|
-
};
|
|
49576
|
-
process.on("SIGINT", sigintHandler);
|
|
49577
|
-
process.on("SIGTERM", sigintHandler);
|
|
49578
|
-
for (const pt of perTarget) pt.controller = await bootOneTarget(pt.target, pt.runState, stacks, options, discovery, skipPull, profileCredsFile);
|
|
49579
|
-
const summary = perTarget.map((pt) => `${pt.controller.service.serviceName} (${pt.controller.activeReplicaCount()} replica(s))`).join(", ");
|
|
49580
|
-
logger.info(`Service(s) running: ${summary}. Press ^C to shut down.`);
|
|
49581
|
-
await Promise.all(perTarget.map((pt) => pt.controller.waitForShutdown()));
|
|
49582
|
-
} finally {
|
|
49583
|
-
if (sigintHandler) {
|
|
49584
|
-
process.off("SIGINT", sigintHandler);
|
|
49585
|
-
process.off("SIGTERM", sigintHandler);
|
|
49586
|
-
}
|
|
49587
|
-
await cleanup();
|
|
49588
|
-
}
|
|
49589
|
-
}
|
|
49590
|
-
/**
|
|
49591
|
-
* Boot one target. Extracted from the loop so each per-service block
|
|
49592
|
-
* (image context, cross-stack resolver, task-role credentials, runner
|
|
49593
|
-
* options) is scoped locally. Returns the started controller for the
|
|
49594
|
-
* outer code to wait + tear down.
|
|
48779
|
+
* `cdkl start-service` strategy — name one or more ECS services and the engine
|
|
48780
|
+
* boots their replicas. There is no front-door listener (services are reached
|
|
48781
|
+
* directly via their published container ports). Mirrors `albStrategy` in
|
|
48782
|
+
* shape, with `frontDoor` omitted and `lbPortOverrides` empty.
|
|
49595
48783
|
*/
|
|
49596
|
-
|
|
49597
|
-
|
|
49598
|
-
|
|
49599
|
-
|
|
49600
|
-
|
|
49601
|
-
|
|
49602
|
-
|
|
49603
|
-
|
|
49604
|
-
|
|
49605
|
-
|
|
49606
|
-
|
|
49607
|
-
const imageContext = await buildEcsImageResolutionContext$1(target, stacks, options, stateProvider);
|
|
49608
|
-
const service = resolveEcsServiceTarget(target, stacks, imageContext);
|
|
49609
|
-
logger.info(`Target: ${service.stack.stackName}/${service.serviceLogicalId} (service=${service.serviceName}, desiredCount=${service.desiredCount}, task=${service.task.taskDefinitionLogicalId})`);
|
|
49610
|
-
for (const w of service.warnings) logger.warn(w);
|
|
49611
|
-
if (service.serviceConnect) logger.info(`Service Connect: namespace='${service.serviceConnect.namespaceName}', ${service.serviceConnect.services.length} service(s) registered for peer discovery.`);
|
|
49612
|
-
if (service.serviceRegistries.length > 0) logger.info(`Cloud Map: ${service.serviceRegistries.length} ServiceRegistry binding(s).`);
|
|
49613
|
-
const taskNeeds = detectEcsImageResolutionNeeds(stacks.find((s) => s.stackName === service.stack.stackName) ?? service.stack);
|
|
49614
|
-
if (stateProvider && taskNeeds.needsCrossStackResolver) {
|
|
49615
|
-
const consumerRegion = options.region ?? process.env["AWS_REGION"] ?? process.env["AWS_DEFAULT_REGION"] ?? service.stack.region ?? "us-east-1";
|
|
49616
|
-
const resolver = await stateProvider.buildCrossStackResolver(consumerRegion);
|
|
49617
|
-
if (resolver) {
|
|
49618
|
-
const subContext = {
|
|
49619
|
-
resources: imageContext?.stateResources ?? {},
|
|
49620
|
-
...imageContext?.pseudoParameters && { pseudoParameters: imageContext.pseudoParameters },
|
|
49621
|
-
consumerRegion,
|
|
49622
|
-
crossStackResolver: resolver
|
|
49623
|
-
};
|
|
49624
|
-
await applyCrossStackResolverToTask(service.task, subContext);
|
|
49625
|
-
}
|
|
49626
|
-
} else if (!stateProvider && taskNeeds.needsCrossStackResolver) logger.warn("Container Environment / Secrets entries contain Fn::ImportValue / Fn::GetStackOutput intrinsics. Pass --from-state (cdkd-deployed) or --from-cfn-stack (cdk-deployed) to substitute them against deployed state.");
|
|
49627
|
-
let assumedCredentials;
|
|
49628
|
-
let resolvedRoleArn;
|
|
49629
|
-
if (options.assumeTaskRole === true) {
|
|
49630
|
-
if (!service.task.taskRoleArn) throw new LocalStartServiceError(`--assume-task-role passed without an ARN but service '${service.serviceLogicalId}' has no resolvable TaskRoleArn. Pass the ARN explicitly: --assume-task-role <arn>`);
|
|
49631
|
-
resolvedRoleArn = await resolvePlaceholderAccount(service.task.taskRoleArn, options.region);
|
|
49632
|
-
assumedCredentials = await assumeTaskRole(resolvedRoleArn, options.region);
|
|
49633
|
-
} else if (typeof options.assumeTaskRole === "string") {
|
|
49634
|
-
resolvedRoleArn = options.assumeTaskRole;
|
|
49635
|
-
assumedCredentials = await assumeTaskRole(resolvedRoleArn, options.region);
|
|
49636
|
-
}
|
|
49637
|
-
const envOverrides = readEnvOverridesFile$2(options.envVars);
|
|
49638
|
-
const taskOpts = {
|
|
49639
|
-
cluster: options.cluster,
|
|
49640
|
-
containerHost: options.containerHost,
|
|
49641
|
-
skipPull,
|
|
49642
|
-
keepRunning: false,
|
|
49643
|
-
detach: true
|
|
49644
|
-
};
|
|
49645
|
-
if (envOverrides) taskOpts.envOverrides = envOverrides;
|
|
49646
|
-
if (assumedCredentials) taskOpts.taskCredentials = assumedCredentials;
|
|
49647
|
-
if (resolvedRoleArn) taskOpts.taskRoleArn = resolvedRoleArn;
|
|
49648
|
-
if (options.platform) taskOpts.platformOverride = options.platform;
|
|
49649
|
-
if (options.region) taskOpts.region = options.region;
|
|
49650
|
-
if (options.ecrRoleArn) taskOpts.ecrRoleArn = options.ecrRoleArn;
|
|
49651
|
-
if (profileCredsFile && !assumedCredentials) taskOpts.profileCredentialsFile = {
|
|
49652
|
-
hostPath: profileCredsFile.hostPath,
|
|
49653
|
-
containerPath: profileCredsFile.containerPath,
|
|
49654
|
-
profileName: profileCredsFile.profileName
|
|
48784
|
+
function serviceStrategy(_options) {
|
|
48785
|
+
return {
|
|
48786
|
+
pickEntries: (stacks) => listTargets(stacks).ecsServices,
|
|
48787
|
+
pickerMessage: "Select one or more ECS services to run",
|
|
48788
|
+
pickerNoun: "ECS services",
|
|
48789
|
+
onMissing: () => new LocalStartServiceError(`${getEmbedConfig().cliName} start-service requires at least one <target>. Pass one or more service paths like 'Stack/Orders' 'Stack/Frontend', or run it in a TTY to pick interactively.`),
|
|
48790
|
+
resolveBoots: (_stacks, chosenTargets) => ({
|
|
48791
|
+
boots: chosenTargets.map((target) => ({ target })),
|
|
48792
|
+
warnings: []
|
|
48793
|
+
}),
|
|
48794
|
+
lbPortOverrides: {}
|
|
49655
48795
|
};
|
|
49656
|
-
return startEcsService(service, {
|
|
49657
|
-
maxTasks: options.maxTasks,
|
|
49658
|
-
restartPolicy: options.restartPolicy,
|
|
49659
|
-
taskOptions: taskOpts,
|
|
49660
|
-
discovery
|
|
49661
|
-
}, runState);
|
|
49662
|
-
}
|
|
49663
|
-
async function resolvePlaceholderAccount(arn, region) {
|
|
49664
|
-
if (!arn.includes("${AWS::AccountId}")) return arn;
|
|
49665
|
-
const { STSClient, GetCallerIdentityCommand } = await import("@aws-sdk/client-sts");
|
|
49666
|
-
const sts = new STSClient({ ...region && { region } });
|
|
49667
|
-
try {
|
|
49668
|
-
const account = (await sts.send(new GetCallerIdentityCommand({}))).Account;
|
|
49669
|
-
if (!account) throw new LocalStartServiceError(`--assume-task-role: GetCallerIdentity returned no Account; cannot resolve placeholder ARN '${arn}'.`);
|
|
49670
|
-
return arn.split(TASK_ROLE_ACCOUNT_PLACEHOLDER).join(account);
|
|
49671
|
-
} finally {
|
|
49672
|
-
sts.destroy();
|
|
49673
|
-
}
|
|
49674
|
-
}
|
|
49675
|
-
async function assumeTaskRole(roleArn, region) {
|
|
49676
|
-
const { STSClient, AssumeRoleCommand } = await import("@aws-sdk/client-sts");
|
|
49677
|
-
const sts = new STSClient({ ...region && { region } });
|
|
49678
|
-
try {
|
|
49679
|
-
const creds = (await sts.send(new AssumeRoleCommand({
|
|
49680
|
-
RoleArn: roleArn,
|
|
49681
|
-
RoleSessionName: `cdkd-local-start-service-${Date.now()}`,
|
|
49682
|
-
DurationSeconds: 3600
|
|
49683
|
-
}))).Credentials;
|
|
49684
|
-
if (!creds?.AccessKeyId || !creds.SecretAccessKey || !creds.SessionToken) throw new LocalStartServiceError(`AssumeRole(${roleArn}) returned no usable credentials.`);
|
|
49685
|
-
return {
|
|
49686
|
-
accessKeyId: creds.AccessKeyId,
|
|
49687
|
-
secretAccessKey: creds.SecretAccessKey,
|
|
49688
|
-
sessionToken: creds.SessionToken
|
|
49689
|
-
};
|
|
49690
|
-
} finally {
|
|
49691
|
-
sts.destroy();
|
|
49692
|
-
}
|
|
49693
48796
|
}
|
|
49694
48797
|
/**
|
|
49695
|
-
*
|
|
49696
|
-
*
|
|
49697
|
-
*
|
|
49698
|
-
*
|
|
48798
|
+
* `cdkl start-service <Stack/Service>...` — run one or more `AWS::ECS::Service`
|
|
48799
|
+
* resources locally as a long-running emulator. Spins up DesiredCount task
|
|
48800
|
+
* replicas per service (clamped by --max-tasks) using the same per-task
|
|
48801
|
+
* docker network + metadata sidecar pattern as `cdkd local run-task`, then
|
|
48802
|
+
* keeps each replica running and restarts it on exit per --restart-policy.
|
|
48803
|
+
* ^C tears every replica + sidecar + network down. When two or more
|
|
48804
|
+
* <target>s are supplied, every service is booted into a shared Cloud Map /
|
|
48805
|
+
* Service Connect registry so peer services discover each other via docker
|
|
48806
|
+
* --add-host overlay (Issue #460).
|
|
49699
48807
|
*/
|
|
49700
|
-
async function buildEcsImageResolutionContext$1(target, stacks, options, stateProvider) {
|
|
49701
|
-
const logger = getLogger();
|
|
49702
|
-
const candidate = pickCandidateStack(parseEcsTarget(target).stackPattern, stacks);
|
|
49703
|
-
if (!candidate) return void 0;
|
|
49704
|
-
const needs = detectEcsImageResolutionNeeds(candidate);
|
|
49705
|
-
if (!needs.needsPseudoParameters && !needs.needsStateResources && !needs.needsEnvOrSecretSubstitution) return;
|
|
49706
|
-
const ctx = {};
|
|
49707
|
-
const wantsPseudoForEnvOrSecret = !!stateProvider && needs.needsEnvOrSecretSubstitution;
|
|
49708
|
-
if (needs.needsPseudoParameters || wantsPseudoForEnvOrSecret) {
|
|
49709
|
-
const region = options.region ?? process.env["AWS_REGION"] ?? process.env["AWS_DEFAULT_REGION"] ?? candidate.region;
|
|
49710
|
-
if (!region) logger.warn("Resolver references ${AWS::Region} but cdkd could not determine the target region. Pass --region, set AWS_REGION, or declare env.region on the CDK stack.");
|
|
49711
|
-
let accountId;
|
|
49712
|
-
try {
|
|
49713
|
-
accountId = await resolveCallerAccountId$1(region);
|
|
49714
|
-
} catch (err) {
|
|
49715
|
-
logger.warn(`Resolver needs \${AWS::AccountId} but STS GetCallerIdentity failed: ${err instanceof Error ? err.message : String(err)}. Substitution will be skipped; affected env / secret entries will be dropped with per-key warnings.`);
|
|
49716
|
-
}
|
|
49717
|
-
const partitionAndSuffix = region ? derivePartitionAndUrlSuffix(region) : void 0;
|
|
49718
|
-
ctx.pseudoParameters = {
|
|
49719
|
-
...accountId !== void 0 && { accountId },
|
|
49720
|
-
...region !== void 0 && { region },
|
|
49721
|
-
...partitionAndSuffix && {
|
|
49722
|
-
partition: partitionAndSuffix.partition,
|
|
49723
|
-
urlSuffix: partitionAndSuffix.urlSuffix
|
|
49724
|
-
}
|
|
49725
|
-
};
|
|
49726
|
-
}
|
|
49727
|
-
const wantsState = needs.needsStateResources || needs.needsEnvOrSecretSubstitution;
|
|
49728
|
-
if (stateProvider && wantsState) {
|
|
49729
|
-
const loaded = await stateProvider.load(candidate.stackName, candidate.region);
|
|
49730
|
-
if (loaded) ctx.stateResources = loaded.resources;
|
|
49731
|
-
} else if (!stateProvider && needs.needsStateResources) logger.warn("Container Image references a same-stack AWS::ECR::Repository. Pass --from-state (cdkd-deployed) or --from-cfn-stack (cdk-deployed) to substitute the deployed repository URI.");
|
|
49732
|
-
else if (!stateProvider && needs.needsEnvOrSecretSubstitution) logger.warn("Container Environment / Secrets entries contain CloudFormation intrinsics. Pass --from-state (cdkd-deployed) or --from-cfn-stack (cdk-deployed) to substitute them against the deployed cdkd state.");
|
|
49733
|
-
return ctx;
|
|
49734
|
-
}
|
|
49735
|
-
function pickCandidateStack(stackPattern, stacks) {
|
|
49736
|
-
if (stackPattern === null) {
|
|
49737
|
-
if (stacks.length === 1) return stacks[0];
|
|
49738
|
-
return;
|
|
49739
|
-
}
|
|
49740
|
-
const matched = matchStacks(stacks, [stackPattern]);
|
|
49741
|
-
if (matched.length === 1) return matched[0];
|
|
49742
|
-
}
|
|
49743
|
-
async function resolveCallerAccountId$1(region) {
|
|
49744
|
-
const { STSClient, GetCallerIdentityCommand } = await import("@aws-sdk/client-sts");
|
|
49745
|
-
const sts = new STSClient({ ...region && { region } });
|
|
49746
|
-
try {
|
|
49747
|
-
return (await sts.send(new GetCallerIdentityCommand({}))).Account;
|
|
49748
|
-
} finally {
|
|
49749
|
-
sts.destroy();
|
|
49750
|
-
}
|
|
49751
|
-
}
|
|
49752
|
-
function readEnvOverridesFile$2(filePath) {
|
|
49753
|
-
if (!filePath) return void 0;
|
|
49754
|
-
let raw;
|
|
49755
|
-
try {
|
|
49756
|
-
raw = readFileSync(filePath, "utf-8");
|
|
49757
|
-
} catch (err) {
|
|
49758
|
-
throw new LocalStartServiceError(`Failed to read --env-vars file '${filePath}': ${err instanceof Error ? err.message : String(err)}`);
|
|
49759
|
-
}
|
|
49760
|
-
let parsed;
|
|
49761
|
-
try {
|
|
49762
|
-
parsed = JSON.parse(raw);
|
|
49763
|
-
} catch (err) {
|
|
49764
|
-
throw new LocalStartServiceError(`Failed to parse --env-vars file '${filePath}' as JSON: ${err instanceof Error ? err.message : String(err)}`);
|
|
49765
|
-
}
|
|
49766
|
-
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new LocalStartServiceError(`--env-vars file '${filePath}' must contain a JSON object at the top level.`);
|
|
49767
|
-
return parsed;
|
|
49768
|
-
}
|
|
49769
|
-
function parsePositiveInt(raw, flagName) {
|
|
49770
|
-
const parsed = parseInt(raw, 10);
|
|
49771
|
-
if (!Number.isFinite(parsed) || parsed < 1) throw new LocalStartServiceError(`${flagName} must be a positive integer (got '${raw}').`);
|
|
49772
|
-
return parsed;
|
|
49773
|
-
}
|
|
49774
|
-
/**
|
|
49775
|
-
* Hard cap on `--max-tasks` driven by the per-replica subnet allocator
|
|
49776
|
-
* in `ecs-service-runner.ts:pickSubnetOctet`. The allocator walks the
|
|
49777
|
-
* link-local /24 range `169.254.170.0..169.254.253.0` and **skips 171**
|
|
49778
|
-
* because that octet is owned by the shared-service network
|
|
49779
|
-
* (`SHARED_SVC_SUBNET_OCTET`) — assigning a per-replica network the
|
|
49780
|
-
* same /24 would have docker reject the duplicate-subnet `network
|
|
49781
|
-
* create`. The usable count is therefore 83 (Issue #544); beyond
|
|
49782
|
-
* that, the modulo-wrap collapses replica N's `/24` onto replica 0's
|
|
49783
|
-
* allocation and docker rejects the duplicate-subnet network creation
|
|
49784
|
-
* with a cryptic "Pool overlaps with other one on this address space"
|
|
49785
|
-
* error 30s into the boot — by which time some early replicas may
|
|
49786
|
-
* have spent docker-run budget. Reject at parse time so the user
|
|
49787
|
-
* gets an actionable error before any boot work fires.
|
|
49788
|
-
*
|
|
49789
|
-
* Raising this requires extending the allocator to walk a different
|
|
49790
|
-
* IP range.
|
|
49791
|
-
*/
|
|
49792
|
-
const MAX_TASKS_SUBNET_RANGE_CAP$1 = 83;
|
|
49793
|
-
function parseMaxTasks$1(raw) {
|
|
49794
|
-
const parsed = parsePositiveInt(raw, "--max-tasks");
|
|
49795
|
-
if (parsed > 83) throw new LocalStartServiceError(`--max-tasks ${parsed} exceeds the per-replica link-local /24 subnet allocator's range (${83}). The allocator in ecs-service-runner.ts assigns each replica its own 169.254.x.0/24 from the range 169.254.170.0..169.254.253.0; replica indices >= ${83} would collide with earlier replicas via modulo wrap. Lower --max-tasks to <= ${83}, or accept reduced local concurrency for high-DesiredCount services.`);
|
|
49796
|
-
return parsed;
|
|
49797
|
-
}
|
|
49798
|
-
function parseRestartPolicy$1(raw) {
|
|
49799
|
-
if (raw === "on-failure" || raw === "always" || raw === "none") return raw;
|
|
49800
|
-
throw new LocalStartServiceError(`--restart-policy must be one of 'on-failure', 'always', or 'none' (got '${raw}').`);
|
|
49801
|
-
}
|
|
49802
|
-
/**
|
|
49803
|
-
* Issue #658: pick the credentials forwarded to the AWS-published
|
|
49804
|
-
* `amazon-ecs-local-container-endpoints` sidecar. `cdkd local
|
|
49805
|
-
* start-service`'s sidecar is SHARED across every replica boot in one
|
|
49806
|
-
* CLI invocation (design § 5 Option A), so this resolves ONCE at
|
|
49807
|
-
* startup. Precedence:
|
|
49808
|
-
* 1. `--profile <p>` → resolved via {@link resolveProfileCredentials}
|
|
49809
|
-
* (the SDK's default credential provider chain — SSO / IAM
|
|
49810
|
-
* Identity Center / fromIni / role-assumption). NEW in this PR.
|
|
49811
|
-
* 2. Not set → `undefined`; the sidecar runs with its own default
|
|
49812
|
-
* credential chain (typically empty inside a fresh container —
|
|
49813
|
-
* user containers will get 4xx from the credentials endpoint).
|
|
49814
|
-
*
|
|
49815
|
-
* Note: per-service `--assume-task-role <Service>=<arn>` overrides are
|
|
49816
|
-
* INTENTIONALLY NOT consulted here. The shared sidecar has no concept
|
|
49817
|
-
* of per-service IAM — per-service `TaskRoleArn` flows into each
|
|
49818
|
-
* container's env via `buildMetadataEnv` at boot time, where the
|
|
49819
|
-
* sidecar's `/role/<role-arn>` path resolves per-request. The shared
|
|
49820
|
-
* sidecar's OWN startup credentials govern only the fallback path
|
|
49821
|
-
* (containers that did not bind a `TaskRoleArn`).
|
|
49822
|
-
*
|
|
49823
|
-
* Extracted as an exported helper so a unit test can exercise both
|
|
49824
|
-
* branches without having to mock the full Synth + Docker + AWS
|
|
49825
|
-
* pipeline (the strategy PR #655 used for the Lambda container path).
|
|
49826
|
-
*/
|
|
49827
|
-
async function resolveSharedSidecarCredentials$1(options) {
|
|
49828
|
-
if (options.profile) return resolveProfileCredentials(options.profile);
|
|
49829
|
-
}
|
|
49830
48808
|
function createLocalStartServiceCommand() {
|
|
49831
|
-
|
|
49832
|
-
|
|
49833
|
-
|
|
49834
|
-
...appOptions,
|
|
49835
|
-
...contextOptions,
|
|
49836
|
-
...stateOptions
|
|
49837
|
-
].forEach((opt) => cmd.addOption(opt));
|
|
49838
|
-
cmd.addOption(deprecatedRegionOption);
|
|
49839
|
-
return cmd;
|
|
48809
|
+
return addCommonEcsServiceOptions(new Command("start-service").description("Run one or more AWS::ECS::Service resources locally as a long-running emulator. Spins up DesiredCount task replicas per service (clamped by --max-tasks) using the same per-task docker network + metadata sidecar pattern as `cdkd local run-task`, then keeps each replica running and restarts it on exit per --restart-policy. ^C tears every replica + sidecar + network down. Each <target> accepts a CDK display path (MyStack/MyService) or stack-qualified logical ID (MyStack:MyServiceXYZ); single-stack apps may omit the stack prefix. When two or more <target>s are supplied, every service is booted into a shared Cloud Map / Service Connect registry so peer services discover each other via docker --add-host overlay (Issue #460). Omit <targets> in an interactive terminal to multi-select the ECS services from a list.").argument("[targets...]", "One or more CDK display paths or stack-qualified logical IDs of the AWS::ECS::Service resources to run (omit to multi-select interactively in a TTY)").addOption(new Option("--from-state", "Read cdkd's S3 state for the target stack and substitute Ref / Fn::GetAtt / Fn::Sub / Fn::ImportValue / Fn::GetStackOutput intrinsics in container images, environment variables, secrets, role ARNs, and volumes. Mutually exclusive with --from-cfn-stack.").default(false)).addOption(new Option("--state-bucket <bucket>", "S3 bucket for --from-state. Falls back to CDKD_STATE_BUCKET env or cdk.json context.cdkd.stateBucket.")).addOption(new Option("--state-prefix <prefix>", "S3 key prefix for --from-state state files.").default("cdkd")).action(withErrorHandling(async (targets, options) => {
|
|
48810
|
+
await runEcsServiceEmulator(targets, options, serviceStrategy(options), cdkdExtraStateProviders);
|
|
48811
|
+
})));
|
|
49840
48812
|
}
|
|
49841
48813
|
|
|
49842
48814
|
//#endregion
|
|
@@ -52744,7 +51716,7 @@ function reorderArgs(argv) {
|
|
|
52744
51716
|
*/
|
|
52745
51717
|
async function main() {
|
|
52746
51718
|
const program = new Command();
|
|
52747
|
-
program.name("cdkd").description("CDK Direct - Deploy AWS CDK apps directly via SDK/Cloud Control API").version("0.
|
|
51719
|
+
program.name("cdkd").description("CDK Direct - Deploy AWS CDK apps directly via SDK/Cloud Control API").version("0.197.0");
|
|
52748
51720
|
program.addCommand(createBootstrapCommand());
|
|
52749
51721
|
program.addCommand(createSynthCommand());
|
|
52750
51722
|
program.addCommand(createListCommand());
|