From 2d454837ad3f44cb79fd615d4c344cdfbd2cffc2 Mon Sep 17 00:00:00 2001 From: dveldhoen <4952924+dveldhoen@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:52:00 +0100 Subject: [PATCH] fix(toolkit-lib): run cdk gc's S3 tag calls concurrently parallelReadAllTags, parallelTagS3 and parallelUntagS3 awaited each call inside their loop, so the p-limit limiter only ever had one call in flight. Run them through parallelPromises with the same limit of 50. --- .../garbage-collection/garbage-collector.ts | 74 ++++++++----------- .../garbage-collection.test.ts | 67 +++++++++++++++-- 2 files changed, 92 insertions(+), 49 deletions(-) diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/garbage-collection/garbage-collector.ts b/packages/@aws-cdk/toolkit-lib/lib/api/garbage-collection/garbage-collector.ts index f4d3762c8..1908c443a 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/garbage-collection/garbage-collector.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/garbage-collection/garbage-collector.ts @@ -8,6 +8,7 @@ import { DEFAULT_TOOLKIT_STACK_NAME, ToolkitInfo } from '../toolkit-info'; import { ProgressPrinter } from './progress-printer'; import { ActiveAssetCache, BackgroundStackRefresh, refreshStacks } from './stack-refresh'; import { ToolkitError, AbortError } from '../../toolkit/toolkit-error'; +import { parallelPromises } from '../../util'; import { IO, type IoHelper } from '../io/private'; import { Mode } from '../plugin'; @@ -421,11 +422,7 @@ export class GarbageCollector { } private async parallelReadAllTags(s3: IS3Client, objects: ObjectAsset[]) { - const limit = pLimit(P_LIMIT); - - for (const obj of objects) { - await limit(() => obj.allTags(s3)); - } + await parallelPromises(P_LIMIT, objects.map((obj) => () => obj.allTags(s3))); } /** @@ -455,28 +452,21 @@ export class GarbageCollector { * Since this is treated as an implementation detail, we do not print the results in the printer. */ private async parallelUntagS3(s3: IS3Client, bucket: string, untaggables: ObjectAsset[]) { - const limit = pLimit(P_LIMIT); - - for (const obj of untaggables) { + await parallelPromises(P_LIMIT, untaggables.map((obj) => async () => { const tags = await obj.allTags(s3) ?? []; const updatedTags = tags.filter((tag: Tag) => tag.Key !== S3_ISOLATED_TAG); - await limit(() => - s3.deleteObjectTagging({ - Bucket: bucket, - Key: obj.key, - - }), - ); - await limit(() => - s3.putObjectTagging({ - Bucket: bucket, - Key: obj.key, - Tagging: { - TagSet: updatedTags, - }, - }), - ); - } + await s3.deleteObjectTagging({ + Bucket: bucket, + Key: obj.key, + }); + await s3.putObjectTagging({ + Bucket: bucket, + Key: obj.key, + Tagging: { + TagSet: updatedTags, + }, + }); + })); await this.ioHelper.defaults.debug(`Untagged ${untaggables.length} assets`); } @@ -517,28 +507,24 @@ export class GarbageCollector { } /** - * Tag objects in parallel using p-limit. The putObjectTagging API does not + * Tag objects in parallel. The putObjectTagging API does not * support batch tagging so we must handle the parallelism client-side. */ private async parallelTagS3(s3: IS3Client, bucket: string, taggables: ObjectAsset[], date: number, printer: ProgressPrinter) { - const limit = pLimit(P_LIMIT); - - for (const obj of taggables) { - await limit(() => - s3.putObjectTagging({ - Bucket: bucket, - Key: obj.key, - Tagging: { - TagSet: [ - { - Key: S3_ISOLATED_TAG, - Value: String(date), - }, - ], - }, - }), - ); - } + await parallelPromises(P_LIMIT, taggables.map((obj) => async () => + s3.putObjectTagging({ + Bucket: bucket, + Key: obj.key, + Tagging: { + TagSet: [ + { + Key: S3_ISOLATED_TAG, + Value: String(date), + }, + ], + }, + }), + )); printer.reportTaggedAsset(taggables); await this.ioHelper.defaults.debug(`Tagged ${taggables.length} assets`); diff --git a/packages/@aws-cdk/toolkit-lib/test/api/garbage-collection/garbage-collection.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/garbage-collection/garbage-collection.test.ts index 75a2a3e1e..f12bc9e7c 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/garbage-collection/garbage-collection.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/garbage-collection/garbage-collection.test.ts @@ -20,6 +20,7 @@ import { ListObjectsV2Command, PutObjectTaggingCommand, } from '@aws-sdk/client-s3'; +import type { Tag } from '@aws-sdk/client-s3'; import { ECR_ISOLATED_TAG, GarbageCollector, S3_ISOLATED_TAG, ToolkitInfo } from '../../../lib/api'; import type { BackgroundStackRefreshProps } from '../../../lib/api/garbage-collection'; import { @@ -807,6 +808,26 @@ function prepareDefaultS3Mock() { return client; } +/** + * Counts how many calls are in flight at the same time. Each call stays in flight + * until a later microtask, so calls that are awaited one at a time never overlap. + * It does not use timers, because other tests in this file leave fake timers on. + */ +function trackConcurrency() { + const tracker = { + inFlight: 0, + max: 0, + async call(result: T): Promise { + tracker.inFlight++; + tracker.max = Math.max(tracker.max, tracker.inFlight); + await Promise.resolve(); + tracker.inFlight--; + return result; + }, + }; + return tracker; +} + function prepareDefaultEcrMock() { const client = ecrClient; client.reset(); @@ -901,6 +922,38 @@ describe('Garbage Collection with large # of objects', () => { expect(s3Client).toHaveReceivedCommandTimes(DeleteObjectsCommand, 4); // 4000 isolated assets are already tagged, deleted in batches of 1000 }); + test('tag calls run concurrently, at most 50 at a time', async () => { + mockTheToolkitInfo({ + Outputs: [ + { + OutputKey: 'BootstrapVersion', + OutputValue: '999', + }, + ], + }); + + mockClientsForLargeObjects(); + const reads = trackConcurrency(); + const untags = trackConcurrency(); + const tags = trackConcurrency(); + s3Client.on(GetObjectTaggingCommand).callsFake((params) => reads.call(largeObjectTagging(params.Key))); + s3Client.on(DeleteObjectTaggingCommand).callsFake(() => untags.call({})); + // untagging also writes the remaining tags back, so only count writes of the isolated tag + s3Client.on(PutObjectTaggingCommand).callsFake((params) => + params.Tagging.TagSet.some((tag: Tag) => tag.Key === S3_ISOLATED_TAG) ? tags.call({}) : {}); + + garbageCollector = gc({ + type: 's3', + rollbackBufferDays: 1, + action: 'tag', + }); + await garbageCollector.garbageCollect(); + + expect(reads.max).toBe(50); + expect(untags.max).toBe(50); + expect(tags.max).toBe(50); + }); + function mockClientsForLargeObjects() { cfnClient.on(ListStacksCommand).resolves({ StackSummaries: [ @@ -937,13 +990,17 @@ describe('Garbage Collection with large # of objects', () => { KeyCount: keyCount, }); - // every other object has the isolated tag: of the 8000 isolated assets, 4000 already are tagged. - // of the 2000 in use assets, 1000 are tagged. - s3Client.on(GetObjectTaggingCommand).callsFake((params) => ({ - TagSet: Number(params.Key[params.Key.length - 5]) % 2 === 0 + s3Client.on(GetObjectTaggingCommand).callsFake((params) => largeObjectTagging(params.Key)); + } + + // every other object has the isolated tag: of the 8000 isolated assets, 4000 already are tagged. + // of the 2000 in use assets, 1000 are tagged. + function largeObjectTagging(key: string) { + return { + TagSet: Number(key[key.length - 5]) % 2 === 0 ? [{ Key: S3_ISOLATED_TAG, Value: new Date(2000, 1, 1).getTime() }] : [], - })); + }; } });