Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 2 additions & 6 deletions packages/aws-cdk-lib/aws-cloudfront/lib/distribution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import { CacheBehavior } from './private/cache-behavior';
import { formatDistributionArn, grant } from './private/utils';
import * as acm from '../../aws-certificatemanager';
import * as cloudwatch from '../../aws-cloudwatch';
import * as elasticloadbalancingv2 from '../../aws-elasticloadbalancingv2';
import * as iam from '../../aws-iam';
import * as lambda from '../../aws-lambda';
import * as s3 from '../../aws-s3';
Expand Down Expand Up @@ -717,9 +716,7 @@ export class Distribution extends Resource implements IDistribution {
const generatedId = Names.uniqueId(scope).slice(-ORIGIN_ID_MAX_LENGTH);
const distributionId = this.distributionId;
const originBindConfig = origin.bind(scope, { originId: generatedId, distributionId: Lazy.string({ produce: () => this.distributionId }) });
const originId = (originBindConfig.originProperty?.id as elasticloadbalancingv2.ILoadBalancerRef)?.loadBalancerRef?.loadBalancerArn
?? originBindConfig.originProperty?.id
?? generatedId;
const originId = originBindConfig.originProperty?.id ?? generatedId;
const duplicateId = this.boundOrigins.find(boundOrigin => boundOrigin.originProperty?.id === originBindConfig.originProperty?.id);
if (duplicateId) {
throw new ValidationError(`Origin with id ${duplicateId.originProperty?.id} already exists. OriginIds must be unique within a distribution`, this);
Expand All @@ -744,8 +741,7 @@ export class Distribution extends Resource implements IDistribution {
);
return originGroupId;
}
return (originBindConfig.originProperty?.id as elasticloadbalancingv2.ILoadBalancerRef)?.loadBalancerRef?.loadBalancerArn
?? originBindConfig.originProperty?.id ?? originId;
return originBindConfig.originProperty?.id ?? originId;
}
}

Expand Down
169 changes: 14 additions & 155 deletions packages/aws-cdk-lib/aws-lambda/test/function.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5046,27 +5046,19 @@ describe('Lambda Function log group behavior', () => {
});

describe('telemetry metadata', () => {
let getPrototypeOfSpy: jest.SpyInstance;
it('redaction happens when feature flag is enabled', () => {
const app = new cdk.App();
app.node.setContext(cxapi.ENABLE_ADDITIONAL_METADATA_COLLECTION, true);
const stack = new cdk.Stack(app);

beforeEach(() => {
const mockConstructor = {
[JSII_RUNTIME_SYMBOL]: {
fqn: 'aws-cdk-lib.aws-lambda.Function',
},
};
getPrototypeOfSpy = jest.spyOn(Object, 'getPrototypeOf').mockReturnValue({
jest.spyOn(Object, 'getPrototypeOf').mockReturnValue({
constructor: mockConstructor,
});
});

afterEach(() => {
getPrototypeOfSpy.mockRestore();
});

it('redaction happens when feature flag is enabled', () => {
const app = new cdk.App();
app.node.setContext(cxapi.ENABLE_ADDITIONAL_METADATA_COLLECTION, true);
const stack = new cdk.Stack(app);

const fn = new lambda.Function(stack, 'Lambda', {
code: lambda.Code.fromInline('foo'),
Expand Down Expand Up @@ -5097,6 +5089,15 @@ describe('telemetry metadata', () => {
app.node.setContext(cxapi.ENABLE_ADDITIONAL_METADATA_COLLECTION, false);
const stack = new cdk.Stack(app);

const mockConstructor = {
[JSII_RUNTIME_SYMBOL]: {
fqn: 'aws-cdk-lib.aws-lambda.Function',
},
};
jest.spyOn(Object, 'getPrototypeOf').mockReturnValue({
constructor: mockConstructor,
});

const fn = new lambda.Function(stack, 'Lambda', {
code: lambda.Code.fromInline('foo'),
handler: 'index.handler',
Expand All @@ -5106,148 +5107,6 @@ describe('telemetry metadata', () => {
expect(fn.node.metadata).toStrictEqual([]);
});
});
describe('L1 Relationships', () => {
it('simple union', () => {
const stack = new cdk.Stack();
const role = new iam.Role(stack, 'SomeRole', {
assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
});
new lambda.CfnFunction(stack, 'MyLambda', {
code: { zipFile: 'foo' },
role: role, // Simple Union
});
Template.fromStack(stack).hasResource('AWS::Lambda::Function', {
Properties: {
Role: { 'Fn::GetAtt': ['SomeRole6DDC54DD', 'Arn'] },
},
});
});

it('array of unions', () => {
const stack = new cdk.Stack();
const role = new iam.Role(stack, 'SomeRole', {
assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
});
const layer1 = new lambda.LayerVersion(stack, 'LayerVersion1', {
code: lambda.Code.fromAsset(path.join(__dirname, 'my-lambda-handler')),
compatibleRuntimes: [lambda.Runtime.PYTHON_3_13],
});
const layer2 = new lambda.LayerVersion(stack, 'LayerVersion2', {
code: lambda.Code.fromAsset(path.join(__dirname, 'my-lambda-handler')),
compatibleRuntimes: [lambda.Runtime.PYTHON_3_13],
});
new lambda.CfnFunction(stack, 'MyLambda', {
code: { zipFile: 'foo' },
role: role,
layers: [layer1, layer2], // Array of Unions
});
Template.fromStack(stack).hasResource('AWS::Lambda::Function', {
Properties: {
Role: { 'Fn::GetAtt': ['SomeRole6DDC54DD', 'Arn'] },
Layers: [{ Ref: 'LayerVersion139D4D7A8' }, { Ref: 'LayerVersion23E5F3CEA' }],
},
});
});

it('nested union', () => {
const stack = new cdk.Stack();
const role = new iam.Role(stack, 'SomeRole', {
assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
});
const bucket = new s3.Bucket(stack, 'MyBucket');

new lambda.CfnFunction(stack, 'MyLambda', {
code: {
s3Bucket: bucket, // Nested union
},
role: role,
});
Template.fromStack(stack).hasResource('AWS::Lambda::Function', {
Properties: {
Role: { 'Fn::GetAtt': ['SomeRole6DDC54DD', 'Arn'] },
Code: { S3Bucket: { Ref: 'MyBucketF68F3FF0' } },
},
});
});

it('deeply nested union', () => {
const stack = new cdk.Stack();
const topic = new sns.CfnTopic(stack, 'Topic');

new lambda.CfnEventInvokeConfig(stack, 'EventConfig', {
functionName: 'myFunction',
qualifier: '$LATEST',
destinationConfig: {
onFailure: {
destination: topic, // Deeply nested: destinationConfig -> onFailure -> destination (union)
},
},
});
Template.fromStack(stack).hasResource('AWS::Lambda::EventInvokeConfig', {
Properties: {
DestinationConfig: {
OnFailure: {
Destination: { Ref: 'Topic' },
},
},
},
});
});

it('nested array of unions', () => {
const stack = new cdk.Stack();
const role = new iam.Role(stack, 'SomeRole', {
assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
});
const securityGroup = new ec2.SecurityGroup(stack, 'SG', {
vpc: new ec2.Vpc(stack, 'VPC'),
});
new lambda.CfnFunction(stack, 'MyLambda', {
code: { zipFile: 'foo' },
role: role,
vpcConfig: {
securityGroupIds: [securityGroup], // Nested array of union
},
});
Template.fromStack(stack).hasResource('AWS::Lambda::Function', {
Properties: {
Role: { 'Fn::GetAtt': ['SomeRole6DDC54DD', 'Arn'] },
VpcConfig: {
SecurityGroupIds: [{ 'Fn::GetAtt': ['SGADB53937', 'GroupId'] }],
},
},
});
});

it('tokens should be passed as is', () => {
const stack = new cdk.Stack();
const role = new iam.Role(stack, 'SomeRole', {
assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
});
const bucket = new s3.Bucket(stack, 'MyBucket');

const codeToken = cdk.Token.asAny({
resolve: () => ({ s3Bucket: bucket.bucketName }),
});

const fsConfigToken = cdk.Token.asAny({
resolve: () => ([{ arn: 'TestArn', localMountPath: '/mnt' }]),
});

new lambda.CfnFunction(stack, 'MyLambda', {
code: codeToken,
role: role,
fileSystemConfigs: fsConfigToken,
});
Template.fromStack(stack).hasResource('AWS::Lambda::Function', {
Properties: {
Role: { 'Fn::GetAtt': ['SomeRole6DDC54DD', 'Arn'] },
Code: { S3Bucket: { Ref: 'MyBucketF68F3FF0' } },
FileSystemConfigs: [{ Arn: 'TestArn', LocalMountPath: '/mnt' }],
},
});
});
});

function newTestLambda(scope: constructs.Construct) {
return new lambda.Function(scope, 'MyLambda', {
Expand Down
2 changes: 1 addition & 1 deletion packages/aws-cdk-lib/aws-s3/lib/bucket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2354,7 +2354,7 @@ export class Bucket extends BucketBase {

const objectLockConfiguration = this.parseObjectLockConfig(props);
const replicationConfiguration = this.renderReplicationConfiguration(props);
this.replicationRoleArn = (replicationConfiguration?.role as iam.IRoleRef)?.roleRef?.roleArn ?? replicationConfiguration?.role;
this.replicationRoleArn = replicationConfiguration?.role;
this.objectOwnership = props.objectOwnership;
this.transitionDefaultMinimumObjectSize = props.transitionDefaultMinimumObjectSize;
const resource = new CfnBucket(this, 'Resource', {
Expand Down
36 changes: 1 addition & 35 deletions tools/@aws-cdk/spec2cdk/lib/cdk/ast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { Module } from '@cdklabs/typewriter';
import { AugmentationsModule } from './augmentation-generator';
import { CannedMetricsModule } from './canned-metrics';
import { CDK_CORE, CONSTRUCTS, ModuleImportLocations } from './cdk';
import { SelectiveImport } from './relationship-decider';
import { ResourceClass } from './resource-class';

/**
Expand Down Expand Up @@ -60,7 +59,7 @@ export class AstBuilder<T extends Module> {
for (const link of resources) {
ast.addResource(link.entity);
}
ast.renderImports();

return ast;
}

Expand All @@ -75,7 +74,6 @@ export class AstBuilder<T extends Module> {

const ast = new AstBuilder(scope, props, aug, metrics);
ast.addResource(resource);
ast.renderImports();

return ast;
}
Expand All @@ -87,8 +85,6 @@ export class AstBuilder<T extends Module> {
public readonly resources: Record<string, string> = {};
private nameSuffix?: string;
private deprecated?: string;
public readonly selectiveImports = new Array<SelectiveImport>();
private readonly modulesRootLocation: string;

protected constructor(
public readonly module: T,
Expand All @@ -99,7 +95,6 @@ export class AstBuilder<T extends Module> {
this.db = props.db;
this.nameSuffix = props.nameSuffix;
this.deprecated = props.deprecated;
this.modulesRootLocation = props.importLocations?.modulesRoot ?? '../..';

CDK_CORE.import(this.module, 'cdk', { fromLocation: props.importLocations?.core });
CONSTRUCTS.import(this.module, 'constructs');
Expand All @@ -116,35 +111,6 @@ export class AstBuilder<T extends Module> {

resourceClass.build();

this.addImports(resourceClass);
this.augmentations?.augmentResource(resource, resourceClass);
}

private addImports(resourceClass: ResourceClass) {
for (const selectiveImport of resourceClass.imports) {
const existingModuleImport = this.selectiveImports.find(
(imp) => imp.moduleName === selectiveImport.moduleName,
);
if (!existingModuleImport) {
this.selectiveImports.push(selectiveImport);
} else {
// We need to avoid importing the same reference multiple times
for (const type of selectiveImport.types) {
if (!existingModuleImport.types.find((t) =>
t.originalType === type.originalType && t.aliasedType === type.aliasedType,
)) {
existingModuleImport.types.push(type);
}
}
}
}
}

public renderImports() {
const sortedImports = this.selectiveImports.sort((a, b) => a.moduleName.localeCompare(b.moduleName));
for (const selectiveImport of sortedImports) {
const sourceModule = new Module(selectiveImport.moduleName);
sourceModule.importSelective(this.module, selectiveImport.types.map((t) => `${t.originalType} as ${t.aliasedType}`), { fromLocation: `${this.modulesRootLocation}/${sourceModule.name}` });
}
}
}
5 changes: 0 additions & 5 deletions tools/@aws-cdk/spec2cdk/lib/cdk/cdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,6 @@ export interface ModuleImportLocations {
* @default 'aws-cdk-lib/aws-cloudwatch'
*/
readonly cloudwatch?: string;
/**
* The root location of all the modules
* @default '../..'
*/
readonly modulesRoot?: string;
}

export class CdkCore extends ExternalModule {
Expand Down
Loading
Loading