Skip to content

Commit 3fa5b23

Browse files
authored
chore: don't add the same Aspect more than once (#32880)
There is no observable behavior from adding the same Aspect more than once at the same priority, but we are adding multiple `AspectApplication`s for it (and then only executing once). Make the proptest results a bit easier to read by not allowing this in the first place. ---- *By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
1 parent 5f060f4 commit 3fa5b23

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

packages/aws-cdk-lib/core/lib/aspect.ts

+5-1
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,11 @@ export class Aspects {
8282
* @param options Options to apply on this aspect.
8383
*/
8484
public add(aspect: IAspect, options?: AspectOptions) {
85-
this._appliedAspects.push(new AspectApplication(this._scope, aspect, options?.priority ?? AspectPriority.DEFAULT));
85+
const newApplication = new AspectApplication(this._scope, aspect, options?.priority ?? AspectPriority.DEFAULT);
86+
if (this._appliedAspects.some(a => a.aspect === newApplication.aspect && a.priority === newApplication.priority)) {
87+
return;
88+
}
89+
this._appliedAspects.push(newApplication);
8690
}
8791

8892
/**

packages/aws-cdk-lib/core/test/aspect.test.ts

+15-1
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,20 @@ describe('aspect', () => {
7474
expect(root.visitCounter).toEqual(1);
7575
});
7676

77+
test('Adding the same aspect twice to the same construct only adds 1', () => {
78+
// GIVEN
79+
const app = new App();
80+
const root = new MyConstruct(app, 'MyConstruct');
81+
82+
// WHEN
83+
const asp = new VisitOnce();
84+
Aspects.of(root).add(asp);
85+
Aspects.of(root).add(asp);
86+
87+
// THEN
88+
expect(Aspects.of(root).all.length).toEqual(1);
89+
});
90+
7791
test('if stabilization is disabled, warn if an Aspect is added via another Aspect', () => {
7892
const app = new App({ context: { '@aws-cdk/core:aspectStabilization': false } });
7993
const root = new MyConstruct(app, 'MyConstruct');
@@ -91,7 +105,7 @@ describe('aspect', () => {
91105
expect(root.node.metadata[0].type).toEqual(cxschema.ArtifactMetadataEntryType.WARN);
92106
expect(root.node.metadata[0].data).toEqual('We detected an Aspect was added via another Aspect, and will not be applied [ack: @aws-cdk/core:ignoredAspect]');
93107
// warning is not added to child construct
94-
expect(child.node.metadata.length).toEqual(0);
108+
expect(child.node.metadata).toEqual([]);
95109
});
96110

97111
test('Do not warn if an Aspect is added directly (not by another aspect)', () => {

0 commit comments

Comments
 (0)