From adacf1040249a82c71a1c01f06fce071d8fead23 Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Tue, 6 Oct 2026 22:19:23 -0400 Subject: [PATCH] fix(cleanup): handle token expiry and run daily without limits Refresh Docker Hub and registry tokens on unauthorized requests, retain Themerr releases for legacy themerr-plex containers, and make deletion limits optional. --- .github/scripts/cleanup-containers.mjs | 97 ++++-- .github/workflows/__cleanup-containers.yml | 3 +- .github/workflows/__cleanup.yml | 3 +- tests/cleanup-containers.test.mjs | 382 +++++++++++++++++++-- 4 files changed, 418 insertions(+), 67 deletions(-) diff --git a/.github/scripts/cleanup-containers.mjs b/.github/scripts/cleanup-containers.mjs index aa1fd4d8..38d55fef 100644 --- a/.github/scripts/cleanup-containers.mjs +++ b/.github/scripts/cleanup-containers.mjs @@ -199,8 +199,8 @@ async function responseError(response) { return new Error(`${response.status} ${response.statusText}: ${body.slice(0, 500)}`); } -async function fetchJson(url, options = {}) { - const response = await fetch(url, options); +async function fetchJson(url, options = {}, request = fetch) { + const response = await request(url, options); if (!response.ok) { throw await responseError(response); } @@ -220,11 +220,33 @@ async function dockerHubToken(username, accessToken) { return token; } -async function paginatedHubResults(url, token) { - return collectPages(url, async (cursor) => { - const page = await fetchJson(cursor, { - headers: {Authorization: `Bearer ${token}`}, +/** + * Cache a Docker bearer token and refresh it once when a request is unauthorized. + * The refreshed token is reused by subsequent requests during long cleanups. + * + * @param {() => Promise} loadToken Docker Hub or scoped registry token loader. + * @returns {Promise} Authenticated request function. + */ +async function refreshingDockerRequest(loadToken) { + let token = await loadToken(); + return async (url, options = {}) => { + const request = () => fetch(url, { + ...options, + headers: {...options.headers, Authorization: `Bearer ${token}`}, }); + let response = await request(); + if (response.status === 401) { + await response.body?.cancel(); + token = await loadToken(); + response = await request(); + } + return response; + }; +} + +async function paginatedHubResults(url, request) { + return collectPages(url, async (cursor) => { + const page = await fetchJson(cursor, {}, request); return {items: page.results, nextCursor: page.next || null}; }); } @@ -243,21 +265,21 @@ async function dockerRegistryToken({namespace, repository, username, accessToken return response.token; } -async function deleteDockerHubTag({namespace, repository, tag, token}) { - const response = await fetch( +async function deleteDockerHubTag({namespace, repository, tag, request}) { + const response = await request( `${DOCKER_HUB_API}/namespaces/${encodeURIComponent(namespace)}` + `/repositories/${encodeURIComponent(repository)}/tags/${encodeURIComponent(tag)}`, - {method: 'DELETE', headers: {Authorization: `Bearer ${token}`}}, + {method: 'DELETE'}, ); if (!response.ok && response.status !== 404) { throw await responseError(response); } } -async function deleteDockerManifest({namespace, repository, digest, token}) { - const response = await fetch( +async function deleteDockerManifest({namespace, repository, digest, request}) { + const response = await request( `${DOCKER_REGISTRY}/v2/${namespace}/${repository}/manifests/${digest}`, - {method: 'DELETE', headers: {Authorization: `Bearer ${token}`}}, + {method: 'DELETE'}, ); if (!response.ok && response.status !== 404) { throw await responseError(response); @@ -282,7 +304,28 @@ async function loadReleaseTags(github, organization, repository) { } function repositoryLookup(repositories) { - return new Map(repositories.map(({name}) => [name.toLowerCase(), name])); + const lookup = new Map(repositories.map(({name}) => [name.toLowerCase(), name])); + // Legacy containers retain releases from the renamed GitHub repository in both registries. + if (lookup.has('themerr') && !lookup.has('themerr-plex')) { + lookup.set('themerr-plex', lookup.get('themerr')); + } + return lookup; +} + +/** + * Resolve the shared deletion budget, allowing omitted limits and GitHub's numeric default of zero. + * + * @param {number} [maxDeletions] Maximum delete operations; omitted or zero means unlimited. + * @returns {number} Positive deletion budget or Infinity. + */ +function deletionBudget(maxDeletions) { + if (maxDeletions === undefined || maxDeletions === 0) { + return Infinity; + } + if (!Number.isInteger(maxDeletions) || maxDeletions < 1) { + throw new Error('maxDeletions must be a positive integer, zero, or omitted.'); + } + return maxDeletions; } /** @@ -301,22 +344,19 @@ export async function cleanupDockerHub({ organization = 'LizardByte', namespace = 'lizardbyte', }) { - if (!Number.isInteger(maxDeletions) || maxDeletions < 1) { - throw new Error('maxDeletions must be a positive integer.'); - } - const [hubToken, repositories] = await Promise.all([ - dockerHubToken(username, accessToken), + let remaining = deletionBudget(maxDeletions); + const [hubRequest, repositories] = await Promise.all([ + refreshingDockerRequest(() => dockerHubToken(username, accessToken)), loadRepositories(github, organization), ]); const githubRepositories = repositoryLookup(repositories); const hubRepositories = await paginatedHubResults( `${DOCKER_HUB_API}/namespaces/${namespace}/repositories?page_size=100`, - hubToken, + hubRequest, ); let scanned = 0; let selectedTags = 0; let deletedActions = 0; - let remaining = maxDeletions; let deferredActions = 0; // Keep repository budgets and registry mutations in deterministic order. @@ -332,7 +372,7 @@ export async function cleanupDockerHub({ paginatedHubResults( `${DOCKER_HUB_API}/namespaces/${namespace}/repositories/` + `${encodeURIComponent(hubRepository.name)}/tags?page_size=100`, - hubToken, + hubRequest, ), loadReleaseTags(github, organization, githubRepository), ]); @@ -341,7 +381,7 @@ export async function cleanupDockerHub({ selectedTags += plan.selectedTags; const selectedActions = plan.actions.slice(0, Math.max(remaining, 0)); deferredActions += plan.actions.length - selectedActions.length; - let registryToken; + let registryRequest; await forEachSequential(selectedActions, async (action) => { const description = action.kind === 'manifest' @@ -350,18 +390,18 @@ export async function cleanupDockerHub({ if (dryRun) { core.info(`[dry-run] Delete ${description}.`); } else if (action.kind === 'manifest') { - registryToken ??= await dockerRegistryToken({ + registryRequest ??= await refreshingDockerRequest(() => dockerRegistryToken({ namespace, repository: hubRepository.name, username, accessToken, - }); + })); core.info(`Deleting ${description}.`); await deleteDockerManifest({ namespace, repository: hubRepository.name, digest: action.digest, - token: registryToken, + request: registryRequest, }); } else { core.info(`Deleting ${description}.`); @@ -369,7 +409,7 @@ export async function cleanupDockerHub({ namespace, repository: hubRepository.name, tag: action.tag, - token: hubToken, + request: hubRequest, }); } deletedActions += 1; @@ -474,9 +514,7 @@ export async function cleanupGhcr({ organization = 'LizardByte', namespace = 'lizardbyte', }) { - if (!Number.isInteger(maxDeletions) || maxDeletions < 1) { - throw new Error('maxDeletions must be a positive integer.'); - } + let remaining = deletionBudget(maxDeletions); const [packages, repositories] = await Promise.all([ github.paginate('GET /orgs/{org}/packages', { org: organization, @@ -490,7 +528,6 @@ export async function cleanupGhcr({ let selected = 0; let operations = 0; let deferred = 0; - let remaining = maxDeletions; // Finish each package before consuming the shared deletion budget for the next. await forEachSequential(packages.sort((a, b) => a.name.localeCompare(b.name)), async (packageData) => { diff --git a/.github/workflows/__cleanup-containers.yml b/.github/workflows/__cleanup-containers.yml index 50322e36..71fbc00e 100644 --- a/.github/workflows/__cleanup-containers.yml +++ b/.github/workflows/__cleanup-containers.yml @@ -21,10 +21,9 @@ on: required: true type: string max_deletions: - description: Maximum delete operations per registry and run + description: Maximum delete operations per registry and run; omit or set to 0 for no limit required: false type: number - default: 1000 secrets: DOCKER_HUB_ACCESS_TOKEN: description: Docker Hub token with read, write, and delete access diff --git a/.github/workflows/__cleanup.yml b/.github/workflows/__cleanup.yml index 61c4b96b..0a30dce0 100644 --- a/.github/workflows/__cleanup.yml +++ b/.github/workflows/__cleanup.yml @@ -6,7 +6,7 @@ permissions: {} on: schedule: - - cron: '30 1/6 * * *' # every 6 hours at 01:30, 07:30, 13:30, and 19:30 UTC + - cron: '30 1 * * *' # daily at 01:30 UTC workflow_dispatch: inputs: dry_run: @@ -43,7 +43,6 @@ jobs: docker_hub_username: ${{ vars.DOCKER_HUB_USERNAME }} dry_run: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }} gh_bot_name: ${{ vars.GH_BOT_NAME }} - max_deletions: 1000 secrets: DOCKER_HUB_ACCESS_TOKEN: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} GH_BOT_TOKEN: ${{ secrets.GH_BOT_TOKEN }} diff --git a/tests/cleanup-containers.test.mjs b/tests/cleanup-containers.test.mjs index f2a59eba..03b8ab00 100644 --- a/tests/cleanup-containers.test.mjs +++ b/tests/cleanup-containers.test.mjs @@ -133,6 +133,310 @@ function summaryCore() { return {info() {}, warning() {}, summary}; } +function cleanupGithub(repositories = ['Alpha'], releases = []) { + return { + rest: {repos: {listForOrg: 'repos', listReleases: 'releases'}}, + async paginate(route) { + return route === 'repos' ? repositories.map((name) => ({name})) : releases; + }, + }; +} + +for (const kind of ['manifest', 'tag']) { + test(`Docker Hub refreshes an expired token during ${kind} deletion and reuses it`, async (t) => { + const old = '2020-01-01T00:00:00Z'; + let hubAuthentications = 0; + let registryAuthentications = 0; + const attempts = []; + const scopes = []; + t.mock.method(globalThis, 'fetch', async (input, options = {}) => { + const url = new URL(input); + if (url.pathname === '/v2/auth/token') { + hubAuthentications += 1; + return Response.json({access_token: `hub-${hubAuthentications}`}); + } + if (url.hostname === 'auth.docker.io') { + registryAuthentications += 1; + scopes.push(url.searchParams.get('scope')); + assert.equal(options.headers.Authorization, `Basic ${Buffer.from('user:token').toString('base64')}`); + return Response.json({token: `registry-${registryAuthentications}`}); + } + if (options.method === 'DELETE') { + attempts.push({path: url.pathname, authorization: options.headers.Authorization}); + return attempts.length === 2 + ? new Response('token expired', {status: 401}) + : new Response(null, {status: 204}); + } + if (url.pathname.endsWith('/repositories')) { + return Response.json({results: [{name: 'alpha'}], next: null}); + } + assert.ok(url.pathname.endsWith('/alpha/tags')); + const tags = [1, 2, 3].map((id) => ({ + name: `old-${id}`, digest: kind === 'tag' ? 'sha256:keep' : `sha256:${id}`, last_updated: old, + })); + tags.push({name: 'latest', digest: 'sha256:keep', last_updated: old}); + return Response.json({results: tags, next: null}); + }); + + const result = await cleanupDockerHub({ + github: cleanupGithub(), core: summaryCore(), username: 'user', accessToken: 'token', + dryRun: false, maxDeletions: 3, + }); + const service = kind === 'manifest' ? 'registry' : 'hub'; + assert.deepEqual(attempts.map(({authorization}) => authorization), [ + `Bearer ${service}-1`, `Bearer ${service}-1`, `Bearer ${service}-2`, `Bearer ${service}-2`, + ]); + assert.equal(attempts[1].path, attempts[2].path); + assert.notEqual(attempts[2].path, attempts[3].path); + assert.equal(hubAuthentications, kind === 'tag' ? 2 : 1); + assert.equal(registryAuthentications, kind === 'manifest' ? 2 : 0); + assert.deepEqual(scopes, kind === 'manifest' + ? Array(2).fill('repository:lizardbyte/alpha:pull,push,delete') : []); + assert.deepEqual(result, { + repositories: 1, scanned: 4, selectedTags: 3, deletedActions: 3, deferredActions: 0, + }); + }); +} + +for (const pageType of ['repository', 'tag']) { + test(`Docker Hub refreshes an expired Hub token during ${pageType} pagination`, async (t) => { + let hubAuthentications = 0; + const secondPageAttempts = []; + const tagDeleteTokens = []; + t.mock.method(globalThis, 'fetch', async (input, options = {}) => { + const url = new URL(input); + if (url.pathname === '/v2/auth/token') { + hubAuthentications += 1; + return Response.json({access_token: `hub-${hubAuthentications}`}); + } + if (options.method === 'DELETE') { + tagDeleteTokens.push(options.headers.Authorization); + return new Response(null, {status: 204}); + } + const isRepositories = url.pathname.endsWith('/repositories'); + const paginate = isRepositories === (pageType === 'repository'); + const secondPage = url.searchParams.has('page'); + if (paginate && secondPage) { + secondPageAttempts.push(options.headers.Authorization); + if (secondPageAttempts.length === 1) { + return new Response('token expired', {status: 401}); + } + } + const results = isRepositories + ? [{name: secondPage ? 'beta' : 'alpha'}] + : [{name: secondPage ? 'old-2' : 'old-1', last_updated: '2020-01-01T00:00:00Z'}]; + return Response.json({ + results, next: paginate && !secondPage ? `${url.origin}${url.pathname}?page=2` : null, + }); + }); + + const result = await cleanupDockerHub({ + github: cleanupGithub(['Alpha', 'Beta']), core: summaryCore(), username: 'user', accessToken: 'token', + dryRun: false, maxDeletions: 2, + }); + assert.deepEqual(secondPageAttempts, ['Bearer hub-1', 'Bearer hub-2']); + assert.deepEqual(tagDeleteTokens, ['Bearer hub-2', 'Bearer hub-2']); + assert.equal(hubAuthentications, 2); + assert.equal(result.scanned, 2); + assert.equal(result.deletedActions, 2); + assert.equal(result.deferredActions, 0); + }); +} + +for (const status of [401, 403, 500]) { + test(`Docker Hub stops on persistent ${status} without unbounded retries`, async (t) => { + let registryAuthentications = 0; + let attempts = 0; + t.mock.method(globalThis, 'fetch', async (input, options = {}) => { + const url = new URL(input); + if (url.pathname === '/v2/auth/token') { + return Response.json({access_token: 'hub-token'}); + } + if (url.hostname === 'auth.docker.io') { + registryAuthentications += 1; + return Response.json({token: `registry-${registryAuthentications}`}); + } + if (options.method === 'DELETE') { + attempts += 1; + assert.ok(url.pathname.endsWith('/manifests/sha256:1')); + return new Response('access denied', {status}); + } + return Response.json({results: url.pathname.endsWith('/repositories') ? [{name: 'alpha'}] + : [1, 2].map((id) => ({name: `old-${id}`, digest: `sha256:${id}`, last_updated: '2020-01-01'}))}); + }); + + await assert.rejects(cleanupDockerHub({ + github: cleanupGithub(), core: summaryCore(), username: 'user', accessToken: 'token', + dryRun: false, maxDeletions: 2, + }), new RegExp(`^Error: ${status} .*access denied`)); + assert.equal(attempts, status === 401 ? 2 : 1); + assert.equal(registryAuthentications, status === 401 ? 2 : 1); + }); +} + +for (const maxDeletions of [undefined, 0]) { + test(`Docker Hub cleans over 10000 stale entries without a limit (maxDeletions=${maxDeletions})`, async (t) => { + const tags = Array.from({length: 10001}, (_, id) => ({ + name: `old-${id}`, digest: `sha256:${id}`, last_updated: '2020-01-01T00:00:00Z', + })); + // A retained alias on the final page must protect a digest seen on the first page. + tags.push({name: 'latest', digest: 'sha256:0', last_updated: '2020-01-01T00:00:00Z'}); + let tagPages = 0; + const deleted = []; + t.mock.method(globalThis, 'fetch', async (input, options = {}) => { + const url = new URL(input); + if (url.pathname === '/v2/auth/token') { + return Response.json({access_token: 'hub-token'}); + } + if (url.hostname === 'auth.docker.io') { + return Response.json({token: 'registry-token'}); + } + if (options.method === 'DELETE') { + deleted.push(url.pathname); + return new Response(null, {status: 204}); + } + if (url.pathname.endsWith('/repositories')) { + return Response.json({results: [{name: 'alpha'}]}); + } + assert.ok(url.pathname.endsWith('/alpha/tags')); + tagPages += 1; + const page = Number(url.searchParams.get('page') ?? 1); + return Response.json({ + results: tags.slice((page - 1) * 100, page * 100), + next: page * 100 < tags.length ? `${url.origin}${url.pathname}?page=${page + 1}` : null, + }); + }); + + const result = await cleanupDockerHub({ + github: cleanupGithub(), core: summaryCore(), username: 'user', accessToken: 'token', + dryRun: false, maxDeletions, + }); + assert.deepEqual(result, { + repositories: 1, scanned: 10002, selectedTags: 10001, deletedActions: 10001, deferredActions: 0, + }); + assert.equal(tagPages, 101); + assert.equal(deleted.length, 10001); + assert.ok(deleted.includes('/v2/namespaces/lizardbyte/repositories/alpha/tags/old-0')); + assert.ok(!deleted.includes('/v2/lizardbyte/alpha/manifests/sha256:0')); + }); +} + +for (const cleanup of [cleanupDockerHub, cleanupGhcr]) { + test(`${cleanup.name} rejects invalid deletion limits before accessing either registry`, async (t) => { + t.mock.method(globalThis, 'fetch', () => assert.fail('Unexpected registry request')); + const github = {paginate() { assert.fail('Unexpected GitHub request'); }}; + await Promise.all([-1, 1.5, NaN, Infinity, null, '3'].map((maxDeletions) => assert.rejects(cleanup({ + github, core: summaryCore(), username: 'user', accessToken: 'token', dryRun: false, maxDeletions, + }), /maxDeletions must be a positive integer, zero, or omitted/))); + }); +} + +for (const dryRun of [false, true]) { + test(`Docker Hub cleans themerr and themerr-plex using Themerr releases (dryRun=${dryRun})`, async (t) => { + const releaseRepositories = []; + const deleted = []; + const scopes = []; + const core = summaryCore(); + const warnings = []; + core.warning = (message) => warnings.push(message); + const github = cleanupGithub(['Themerr'], [{tag_name: 'v1.0.0', draft: false}]); + const paginate = github.paginate; + github.paginate = async (route, options) => { + if (route === 'releases') { + releaseRepositories.push(options.repo); + } + return paginate(route, options); + }; + t.mock.method(globalThis, 'fetch', async (input, options = {}) => { + const url = new URL(input); + if (url.pathname === '/v2/auth/token') { + return Response.json({access_token: 'hub-token'}); + } + if (url.hostname === 'auth.docker.io') { + scopes.push(url.searchParams.get('scope')); + return Response.json({token: 'registry-token'}); + } + if (options.method === 'DELETE') { + deleted.push(url.pathname); + return new Response(null, {status: 204}); + } + if (url.pathname.endsWith('/repositories')) { + return Response.json({results: [{name: 'themerr-plex'}, {name: 'themerr'}, {name: 'unmapped'}]}); + } + assert.match(url.pathname, /\/repositories\/themerr(?:-plex)?\/tags$/); + return Response.json({results: [ + ...['v1.0.0', 'v1.0.0-ubuntu', 'latest', 'stale-build'].map((name) => ({ + name, digest: `sha256:${name}`, last_updated: '2020-01-01T00:00:00Z', + })), + {name: 'recent-build', digest: 'sha256:recent', last_updated: new Date().toISOString()}, + ]}); + }); + + const result = await cleanupDockerHub({ + github, core, username: 'user', accessToken: 'token', dryRun, + }); + assert.deepEqual(releaseRepositories, ['Themerr', 'Themerr']); + assert.deepEqual(deleted, dryRun ? [] : [ + '/v2/lizardbyte/themerr/manifests/sha256:stale-build', + '/v2/lizardbyte/themerr-plex/manifests/sha256:stale-build', + ]); + assert.deepEqual(scopes, dryRun ? [] : [ + 'repository:lizardbyte/themerr:pull,push,delete', + 'repository:lizardbyte/themerr-plex:pull,push,delete', + ]); + assert.equal(warnings.length, 1); + assert.match(warnings[0], /unmapped: no matching GitHub repository/); + assert.deepEqual(result, { + repositories: 3, scanned: 10, selectedTags: 2, deletedActions: 2, deferredActions: 0, + }); + }); +} + +test('GHCR cleans legacy themerr-plex versions against Themerr releases and preserves children', async (t) => { + t.mock.method(globalThis, 'fetch', async (input) => { + const url = new URL(input); + if (url.pathname === '/token') { + assert.equal(url.searchParams.get('scope'), 'repository:lizardbyte/themerr-plex:pull'); + return Response.json({token: 'registry-token'}); + } + return Response.json(url.pathname.endsWith('/manifests/sha256:root') + ? {manifests: [{digest: 'sha256:child'}]} : {}); + }); + const deleted = []; + const github = { + rest: {repos: {listForOrg: 'repos', listReleases: 'releases'}}, + async paginate(route, options) { + if (route === 'repos') { + return [{name: 'Themerr'}]; + } + if (route === 'releases') { + assert.equal(options.repo, 'Themerr'); + return [{tag_name: 'v1.0.0', draft: false}]; + } + if (!options.package_name) { + return [{name: 'themerr-plex'}]; + } + assert.equal(options.package_name, 'themerr-plex'); + return [ + {id: 'root', name: 'sha256:root', metadata: {container: {tags: ['v1.0.0']}}}, + {id: 'stale', name: 'sha256:stale', metadata: {container: {tags: ['stale-build']}}}, + {id: 'child', name: 'sha256:child', metadata: {container: {tags: []}}}, + {id: 'orphan', name: 'sha256:orphan', metadata: {container: {tags: []}}}, + ]; + }, + async request(route, options) { + assert.equal(options.package_name, 'themerr-plex'); + deleted.push(options.package_version_id); + }, + }; + + const result = await cleanupGhcr({ + github, core: summaryCore(), username: 'user', accessToken: 'token', dryRun: false, + }); + assert.deepEqual(deleted, ['stale', 'orphan']); + assert.deepEqual(result, {packages: 1, scanned: 4, selected: 2, operations: 2, deferred: 0}); +}); + for (const dryRun of [false, true]) { test(`Docker Hub cleanup respects pagination and a shared deletion budget (dryRun=${dryRun})`, async (t) => { const old = '2020-01-01T00:00:00Z'; @@ -186,40 +490,52 @@ for (const dryRun of [false, true]) { }); } -test('GHCR deletes parents before children and carries its deletion budget across packages', async (t) => { - t.mock.method(globalThis, 'fetch', async () => Response.json({token: 'registry-token'})); - const events = []; - const github = { - rest: {repos: {listForOrg: 'repos', listReleases: 'releases'}}, - async paginate(route, options) { - if (route === 'repos') { - return [{name: 'Alpha'}, {name: 'Beta'}]; +for (const maxDeletions of [3, undefined, 0]) { + for (const dryRun of [false, true]) { + const description = `GHCR respects package ordering and limits (maxDeletions=${maxDeletions}, dryRun=${dryRun})`; + test(description, async (t) => { + t.mock.method(globalThis, 'fetch', async () => Response.json({token: 'registry-token'})); + const events = []; + const github = { + rest: {repos: {listForOrg: 'repos', listReleases: 'releases'}}, + async paginate(route, options) { + if (route === 'repos') { + return [{name: 'Alpha'}, {name: 'Beta'}]; + } + if (route === 'releases') { + return []; + } + if (options.package_name) { + return [ + {id: 'child', name: 'child', metadata: {container: {tags: []}}}, + {id: 'parent', name: 'parent', metadata: {container: {tags: ['old']}}}, + ]; + } + return [{name: 'beta'}, {name: 'alpha'}]; + }, + async request(route, options) { + const label = `${options.package_name}/${options.package_version_id}`; + events.push(`start ${label}`); + await setImmediate(); + events.push(`end ${label}`); + }, + }; + const result = await cleanupGhcr({ + github, core: summaryCore(), username: 'user', accessToken: 'token', dryRun, maxDeletions, + }); + const limited = maxDeletions === 3; + assert.deepEqual(result, { + packages: 2, scanned: 4, selected: 4, operations: limited ? 3 : 4, deferred: limited ? 1 : 0, + }); + const expectedEvents = ['start alpha/parent', 'end alpha/parent', 'start alpha/child', 'end alpha/child', + 'start beta/parent', 'end beta/parent']; + if (!limited) { + expectedEvents.push('start beta/child', 'end beta/child'); } - if (route === 'releases') { - return []; - } - if (options.package_name) { - return [ - {id: 'child', name: 'child', metadata: {container: {tags: []}}}, - {id: 'parent', name: 'parent', metadata: {container: {tags: ['old']}}}, - ]; - } - return [{name: 'beta'}, {name: 'alpha'}]; - }, - async request(route, options) { - const label = `${options.package_name}/${options.package_version_id}`; - events.push(`start ${label}`); - await setImmediate(); - events.push(`end ${label}`); - }, - }; - const result = await cleanupGhcr({ - github, core: summaryCore(), username: 'user', accessToken: 'token', dryRun: false, maxDeletions: 3, - }); - assert.deepEqual(result, {packages: 2, scanned: 4, selected: 4, operations: 3, deferred: 1}); - assert.deepEqual(events, ['start alpha/parent', 'end alpha/parent', 'start alpha/child', 'end alpha/child', - 'start beta/parent', 'end beta/parent']); -}); + assert.deepEqual(events, dryRun ? [] : expectedEvents); + }); + } +} test('GHCR makes no deletions when a retained manifest cannot be read', async (t) => { t.mock.method(globalThis, 'fetch', async (input) => {