From 537bbbb7c84057d31d85691d5d71224dc42068db Mon Sep 17 00:00:00 2001 From: Danilo Lakovic Date: Sun, 22 Nov 2026 13:14:49 +0100 Subject: [PATCH 1/3] Bring the repository form and remote policy browser checks up to date The repository form keeps Save off until the protection of a distribution that is offered with it is decided, so the checks that tick the distribution box now choose the Public protection explicitly, and the check that a base path a seeded installation serves is refused presses Save and reads the refusal instead of finding the button disabled for the missing protection. A plugin whose manifest lists no remote screens keeps its own address for them, so the remote policy check uses the address of the framework only for a plugin that has remote screens there. --- e2e/remote/create.spec.ts | 11 +++++++++-- e2e/remote/remote-policy.spec.ts | 7 ++++++- e2e/remote/rpm-python.spec.ts | 2 ++ 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/e2e/remote/create.spec.ts b/e2e/remote/create.spec.ts index 5f990b62..b40479a7 100644 --- a/e2e/remote/create.spec.ts +++ b/e2e/remote/create.spec.ts @@ -45,9 +45,12 @@ async function openCreateForm(page: Page, name: string) { await expect(page.locator('#create_distribution')).not.toBeChecked(); } -// Ticks the box and types a base path. +// Ticks the box, makes the explicit protection choice the form asks for (Save +// stays off until the distribution's protection is decided) and types a base +// path. async function offerDistribution(page: Page, basePath?: string) { await page.locator('#create_distribution').check(); + await page.getByRole('radio', { name: /^Public/ }).check(); if (basePath !== undefined) { await page.locator('#base_path').fill(basePath); } @@ -172,7 +175,11 @@ test('a base path under a prefix the deployment reserves is refused', async ({ fields: 'base_path', }); await page.locator('#base_path').fill(seeded?.['base_path'] as string); - await expect(save(page)).toBeDisabled(); + await save(page).click(); + await expect( + page.getByText(/is already used by or overlaps the distribution/), + 'a base path a seeded installation serves', + ).toBeVisible(); expect(posts, 'POST requests of the page').toEqual([]); }); diff --git a/e2e/remote/remote-policy.spec.ts b/e2e/remote/remote-policy.spec.ts index 8f20bee5..d9eb59a6 100644 --- a/e2e/remote/remote-policy.spec.ts +++ b/e2e/remote/remote-policy.spec.ts @@ -47,8 +47,13 @@ test('a file remote created without touching the policy is stored as on demand', // The address of the form that adds a remote: the new address for a plugin on // the framework, the plugin's own for the others. function addAddress(plugin: string): string { + // a plugin whose manifest has no remote screens keeps its own address for + // them, whatever else of it is on the framework const onFramework = PLUGIN_MANIFESTS.some( - (manifest) => manifest.plugin === plugin && manifest.onFramework, + (manifest) => + manifest.plugin === plugin && + manifest.onFramework && + manifest.resources.includes('remote'), ); return onFramework ? `${plugin}/remote/new` : `${plugin}/remotes/edit/_`; } diff --git a/e2e/remote/rpm-python.spec.ts b/e2e/remote/rpm-python.spec.ts index 1aa0fa6d..0de4b5d4 100644 --- a/e2e/remote/rpm-python.spec.ts +++ b/e2e/remote/rpm-python.spec.ts @@ -187,6 +187,8 @@ for (const plugin of [rpm, python]) { await page.locator('#name').fill(name); await pickRemote(page, remoteName()); await page.locator('#create_distribution').check(); + // Save stays off until the protection of the distribution is decided + await page.getByRole('radio', { name: /^Public/ }).check(); await expect(page.locator('#base_path')).toHaveValue(name); await page.getByRole('button', { name: 'Save' }).click(); await page.waitForURL(repositorySaved(plugin)); From 578b68e584a21266e76e709855c9216f04d8a595 Mon Sep 17 00:00:00 2001 From: Danilo Lakovic Date: Sun, 22 Nov 2026 13:33:00 +0100 Subject: [PATCH 2/3] Add browser checks for creating, editing and deleting distributions Against a real server, a distribution of every installed plugin is created from the list with an explicit protection, opened and deleted from the screens, and the stored object is read back after each write. A file distribution is switched to one publication and the server is checked for the new binding and the cleared ones; a public distribution shows the Public mark and appears under Public only. The served-state labels of the seeded serving distributions are checked on the list, on each distribution's page and on the Distributions tab of its repository, for the administrator and for a viewer that may not read publications (who is told "Cannot be checked"). An editor holding the owner role on single distributions sees Edit and Delete on exactly those rows and on their pages, and nothing on a distribution it may only read. The clean-up helper now also lists and removes the maven, npm, ansible and container distributions and repositories of a run, and treats a plugin the server does not have as holding nothing. --- e2e/remote/distribution-crud.spec.ts | 284 ++++++++++++++++++ .../distribution-permissions.editor.spec.ts | 228 ++++++++++++++ e2e/remote/distribution-warnings.spec.ts | 34 +++ .../distribution-warnings.viewer.spec.ts | 35 +++ e2e/support/api.ts | 33 +- e2e/support/distribution-screens.ts | 178 +++++++++++ e2e/support/framework-list.ts | 14 +- e2e/support/serving-checks.ts | 93 ++++++ e2e/support/serving-states.ts | 112 +++++++ 9 files changed, 1002 insertions(+), 9 deletions(-) create mode 100644 e2e/remote/distribution-crud.spec.ts create mode 100644 e2e/remote/distribution-permissions.editor.spec.ts create mode 100644 e2e/remote/distribution-warnings.spec.ts create mode 100644 e2e/remote/distribution-warnings.viewer.spec.ts create mode 100644 e2e/support/distribution-screens.ts create mode 100644 e2e/support/serving-checks.ts create mode 100644 e2e/support/serving-states.ts diff --git a/e2e/remote/distribution-crud.spec.ts b/e2e/remote/distribution-crud.spec.ts new file mode 100644 index 00000000..5a12966c --- /dev/null +++ b/e2e/remote/distribution-crud.spec.ts @@ -0,0 +1,284 @@ +import { type Page, expect, test } from '@playwright/test'; +import { getContentguardsCoreRbacListUrl } from '@pulp-ui/sdk/core/contentguards-rbac'; +import { getPublicationsFileFileListUrl } from '@pulp-ui/sdk/file/publications-file'; +import { type PulpObject, TestObjects } from '../support/api'; +import { + type DistributionPlugin, + PLUGINS, + SERVING_GUARD, + chooseGuard, + choosePublic, + createButton, + distributionsNamed, + fillNames, + findByName, + listRow, + openCreateForm, + openListFiltered, + pickFromTypeahead, +} from '../support/distribution-screens'; +import { title } from '../support/sign-in'; + +// A distribution of every installed plugin is created, opened, changed and +// deleted through the screens, against a real server, with objects of this +// file's own prefix. The server is asked after each write, so the screen and +// the stored object cannot disagree unnoticed. The lab's shared serving guard +// is read and attached, never changed. + +let objects: TestObjects; +let guard: PulpObject; + +test.beforeAll(async () => { + test.setTimeout(120_000); + objects = await TestObjects.open('dcrud'); + const found = await findByName( + objects.api, + getContentguardsCoreRbacListUrl(), + SERVING_GUARD, + ); + expect( + found, + `the lab holds the content guard ${SERVING_GUARD}`, + ).toBeTruthy(); + guard = found as PulpObject; +}); + +test.afterAll(async () => { + test.setTimeout(180_000); + await objects.cleanUp(); +}); + +const detailAddress = (plugin: DistributionPlugin, name: string) => + new RegExp(`/${plugin}/distributions/${encodeURIComponent(name)}/?$`); + +// Reads one distribution of a plugin from the server, failing when it is not +// there exactly once. +async function stored( + plugin: DistributionPlugin, + name: string, +): Promise { + const found = await distributionsNamed(objects.api, plugin, name); + expect(found, `${plugin} distributions named ${name}`).toHaveLength(1); + return found[0] as PulpObject; +} + +// Waits until the server no longer lists the distribution: a delete is a task +// the page follows in the background. +async function expectGone( + plugin: DistributionPlugin, + name: string, +): Promise { + await expect + .poll( + async () => (await distributionsNamed(objects.api, plugin, name)).length, + { + message: `${plugin} distributions named ${name} on the server`, + timeout: 60_000, + }, + ) + .toBe(0); +} + +// Presses Create and waits for the page of the new distribution, which opens +// when the server has made it. +async function create( + page: Page, + plugin: DistributionPlugin, + name: string, +): Promise { + await expect(createButton(page)).toBeEnabled(); + await createButton(page).click(); + await expect(page).toHaveURL(detailAddress(plugin, name), { + timeout: 60_000, + }); + await expect(title(page, name)).toBeVisible(); + await expect(page.getByText(`Created distribution "${name}"`)).toBeVisible(); +} + +// Confirms the delete dialog that is open. +async function confirmDelete(page: Page): Promise { + const dialog = page.getByRole('dialog'); + await expect(dialog).toContainText('Delete distribution?'); + await dialog.getByRole('button', { name: 'Delete', exact: true }).click(); +} + +test('a file distribution is created with a guard, switched to one publication, and a public one is marked and listed; both are deleted from the screens', async ({ + page, +}) => { + test.setTimeout(240_000); + const repository = await objects.create(PLUGINS.file.repositories, { + name: objects.name('file-repo'), + }); + await objects.upload(repository.pulp_href, 'one.txt', 'one'); + const publication = await objects.create(getPublicationsFileFileListUrl(), { + repository: repository.pulp_href, + }); + + // create with the shared guard and the repository + const guarded = objects.name('file-guarded'); + await openCreateForm(page, 'file'); + await fillNames(page, guarded); + await page + .getByRole('radio', { name: /The repository \(serves its newest/ }) + .check(); + await pickFromTypeahead( + page, + 'Select a repository', + repository.name as string, + ); + await chooseGuard(page, SERVING_GUARD); + await create(page, 'file', guarded); + + const made = await stored('file', guarded); + expect(made['repository'], 'the repository it serves').toBe( + repository.pulp_href, + ); + expect(made['content_guard'], 'its content guard').toBe(guard.pulp_href); + expect(made['publication'], 'no publication is bound').toBeNull(); + + // switch to one publication: the server then holds the publication and no + // repository + await page.getByRole('button', { name: 'Edit', exact: true }).click(); + await expect(page).toHaveURL(/\/edit\/?$/); + await expect(title(page, guarded)).toBeVisible(); + await page.getByRole('radio', { name: 'One publication' }).check(); + await page.locator('#publication').selectOption(publication.pulp_href); + await page.getByRole('button', { name: 'Save', exact: true }).click(); + await expect(page).toHaveURL(detailAddress('file', guarded), { + timeout: 60_000, + }); + await expect + .poll(async () => (await stored('file', guarded))['publication'], { + message: 'the publication the distribution is bound to', + timeout: 60_000, + }) + .toBe(publication.pulp_href); + const switched = await stored('file', guarded); + expect( + switched['repository'], + 'the repository binding is cleared', + ).toBeNull(); + expect( + switched['repository_version'], + 'the version binding is cleared', + ).toBeNull(); + expect(switched['content_guard'], 'the guard was left alone').toBe( + guard.pulp_href, + ); + + // a public one, by the explicit choice + const open = objects.name('file-public'); + await openCreateForm(page, 'file'); + await fillNames(page, open); + await page + .getByRole('radio', { name: /The repository \(serves its newest/ }) + .check(); + await pickFromTypeahead( + page, + 'Select a repository', + repository.name as string, + ); + await choosePublic(page); + await create(page, 'file', open); + // the mark stands beside the address and in the content guard row + await expect( + page.locator('[data-cy=DistributionDetail-details]').getByText('Public', { + exact: true, + }), + ).toHaveCount(2); + expect((await stored('file', open))['content_guard']).toBeNull(); + + // the Public mark on the list, and the public-only filter + await openListFiltered(page, objects.prefix); + await expect(listRow(page, open)).toContainText('Public'); + await expect(listRow(page, guarded)).not.toContainText('Public'); + await openListFiltered(page, objects.prefix, '&public=true'); + await expect(listRow(page, open)).toBeVisible(); + await expect(listRow(page, guarded)).toHaveCount(0); + + // delete the public one from its page and the guarded one from the list + await page.goto(`file/distributions/${encodeURIComponent(open)}`); + await expect(title(page, open)).toBeVisible(); + await page.getByRole('button', { name: 'Delete', exact: true }).click(); + await confirmDelete(page); + await expect(title(page, 'Distributions')).toBeVisible(); + await expectGone('file', open); + + await openListFiltered(page, guarded); + await listRow(page, guarded).locator('[data-cy=kebab-toggle] button').click(); + await page.getByRole('menuitem', { name: 'Delete', exact: true }).click(); + await confirmDelete(page); + await expectGone('file', guarded); + await expect(listRow(page, guarded)).toHaveCount(0); +}); + +const OTHER_PLUGINS: DistributionPlugin[] = [ + 'deb', + 'rpm', + 'python', + 'maven', + 'npm', + 'ansible', + 'container', +]; + +// Plugins that serve from publications ask whether the distribution follows +// the repository or one publication of it. +const SERVES_FROM_PUBLICATION: DistributionPlugin[] = ['file', 'deb', 'rpm']; + +for (const plugin of OTHER_PLUGINS) { + test(`${plugin}: a distribution of a run-scoped repository is created with its protection, opened and deleted`, async ({ + page, + }) => { + test.setTimeout(180_000); + const repository = await objects.create(PLUGINS[plugin].repositories, { + name: objects.name(`${plugin}-repo`), + }); + const name = objects.name(`${plugin}-dist`); + + await openCreateForm(page, plugin); + await fillNames(page, name); + if (SERVES_FROM_PUBLICATION.includes(plugin)) { + await page + .getByRole('radio', { name: /The repository \(serves its newest/ }) + .check(); + } + await pickFromTypeahead( + page, + 'Select a repository', + repository.name as string, + ); + if (plugin === 'container') { + // the server sets the guard of a container distribution; the form offers + // no protection to choose + await expect(page.getByRole('radio', { name: /^Public/ })).toHaveCount(0); + await expect( + page.getByText(/The server manages the content guard/), + ).toBeVisible(); + } else { + await chooseGuard(page, SERVING_GUARD); + } + await create(page, plugin, name); + + const made = await stored(plugin, name); + expect(made['repository'], 'the repository it serves').toBe( + repository.pulp_href, + ); + if (plugin === 'container') { + expect(made['content_guard'], 'the guard the server set').toBeTruthy(); + } else { + expect(made['content_guard'], 'its content guard').toBe(guard.pulp_href); + } + // the page shows what it serves and how it is protected + const details = page.locator('[data-cy=DistributionDetail-details]'); + await expect(details).toContainText(repository.name as string); + if (plugin !== 'container') { + await expect(details).toContainText(SERVING_GUARD); + } + + await page.getByRole('button', { name: 'Delete', exact: true }).click(); + await confirmDelete(page); + await expect(title(page, 'Distributions')).toBeVisible(); + await expectGone(plugin, name); + }); +} diff --git a/e2e/remote/distribution-permissions.editor.spec.ts b/e2e/remote/distribution-permissions.editor.spec.ts new file mode 100644 index 00000000..f5d4be54 --- /dev/null +++ b/e2e/remote/distribution-permissions.editor.spec.ts @@ -0,0 +1,228 @@ +import { + type APIRequestContext, + type Locator, + type Page, + expect, + test, +} from '@playwright/test'; +import { + getDistributionsAnsibleAnsibleAddRoleUrl, + getDistributionsAnsibleAnsibleRemoveRoleUrl, +} from '@pulp-ui/sdk/ansible/distributions-ansible'; +import { getRolesListUrl } from '@pulp-ui/sdk/core/roles'; +import { + getDistributionsPythonPypiAddRoleUrl, + getDistributionsPythonPypiRemoveRoleUrl, +} from '@pulp-ui/sdk/python/distributions-pypi'; +import { account } from '../support/accounts'; +import { type PulpObject, TestObjects } from '../support/api'; +import { PLUGINS } from '../support/distribution-screens'; +import { apiGet, apiPost } from '../support/sdk-request'; +import { isPermissionsRead } from '../support/session'; +import { title } from '../support/sign-in'; + +// What the editor account is shown on the list of every plugin's distributions +// when it holds a role on single distributions. The administrator makes three +// distributions of this run: the editor is given the owner role on one python +// and one ansible distribution, and the viewer role on a second python +// distribution that it may therefore read and not change. The list must offer +// Edit and Delete on the two owned rows and no action on the third, and the +// pages of the distributions must say the same. The screens only hide actions +// the server would refuse; the server still decides each request. The grants +// are removed by this spec, and the distributions with them. + +const PYTHON_OWNER = 'python.pythondistribution_owner'; +const PYTHON_VIEWER = 'python.pythondistribution_viewer'; +const ANSIBLE_OWNER = 'ansible.ansibledistribution_owner'; + +let objects: TestObjects; +let api: APIRequestContext; +let owned: { python: PulpObject; ansible: PulpObject }; +let viewable: PulpObject; +const granted: { href: string; role: string; remove: string }[] = []; + +async function rolePermissions(role: string): Promise> { + const { results } = await apiGet<{ results: { permissions: string[] }[] }>( + api, + getRolesListUrl(), + { name: role }, + ); + expect(results, `the role ${role} exists on the server`).toHaveLength(1); + return new Set(results[0]?.permissions); +} + +async function grant( + href: string, + role: string, + addUrl: string, + removeUrl: string, +): Promise { + await apiPost(api, addUrl, { + role, + users: [account('editor').username], + }); + granted.push({ href, role, remove: removeUrl }); +} + +test.beforeAll(async () => { + test.setTimeout(180_000); + api = (objects = await TestObjects.open('dperm')).api; + const python = await objects.create(PLUGINS.python.distributions, { + name: objects.name('python-owned'), + base_path: objects.name('python-owned'), + }); + const ansible = await objects.create(PLUGINS.ansible.distributions, { + name: objects.name('ansible-owned'), + base_path: objects.name('ansible-owned'), + }); + viewable = await objects.create(PLUGINS.python.distributions, { + name: objects.name('python-viewable'), + base_path: objects.name('python-viewable'), + }); + owned = { python, ansible }; + + await grant( + python.pulp_href, + PYTHON_OWNER, + getDistributionsPythonPypiAddRoleUrl(python.pulp_href), + getDistributionsPythonPypiRemoveRoleUrl(python.pulp_href), + ); + await grant( + ansible.pulp_href, + ANSIBLE_OWNER, + getDistributionsAnsibleAnsibleAddRoleUrl(ansible.pulp_href), + getDistributionsAnsibleAnsibleRemoveRoleUrl(ansible.pulp_href), + ); + await grant( + viewable.pulp_href, + PYTHON_VIEWER, + getDistributionsPythonPypiAddRoleUrl(viewable.pulp_href), + getDistributionsPythonPypiRemoveRoleUrl(viewable.pulp_href), + ); +}); + +test.afterAll(async () => { + test.setTimeout(180_000); + // the grants first, so nothing the editor may reach is left if the clean-up + // of the objects fails + for (const { remove, role } of granted) { + await apiPost(api, remove, { + role, + users: [account('editor').username], + }); + } + granted.length = 0; + await objects.cleanUp(); +}); + +// Opens the list narrowed to this run's distributions once the application has +// read the account's permissions and every column has settled, so an action +// missing from a row is missing because of them and not because they were +// still being read. +async function openRunList(page: Page): Promise { + const permissionsRead = page.waitForResponse(isPermissionsRead); + await page.goto( + `distributions?name__icontains=${encodeURIComponent(objects.prefix)}`, + ); + await permissionsRead; + await expect(title(page, 'Distributions')).toBeVisible(); + await expect( + page.locator( + 'table[aria-label="Distributions"][data-rows-loaded="true"][data-columns-loaded="true"]', + ), + ).toBeVisible(); +} + +const rowOf = (page: Page, name: string): Locator => + page.locator(`[data-cy="DistributionList-row-${name}"]`); + +// Opens the actions menu of a row and returns the actions it offers. +async function offeredActions(row: Locator, page: Page): Promise { + await row.locator('[data-cy=kebab-toggle] button').click(); + const items = page.getByRole('menuitem'); + await expect(items.first()).toBeVisible(); + const names = (await items.allInnerTexts()).map( + (text) => text.split('\n')[0]?.trim() ?? '', + ); + await page.keyboard.press('Escape'); + await expect(items.first()).toBeHidden(); + return names; +} + +test('the roles the editor holds on single distributions give Edit and Delete on those rows only', async ({ + page, +}) => { + const [pythonOwner, ansibleOwner, viewer] = await Promise.all([ + rolePermissions(PYTHON_OWNER), + rolePermissions(ANSIBLE_OWNER), + rolePermissions(PYTHON_VIEWER), + ]); + expect( + pythonOwner.has('python.change_pythondistribution') && + pythonOwner.has('python.delete_pythondistribution'), + 'the python owner role changes and deletes a distribution', + ).toBe(true); + expect( + ansibleOwner.has('ansible.change_ansibledistribution') && + ansibleOwner.has('ansible.delete_ansibledistribution'), + 'the ansible owner role changes and deletes a distribution', + ).toBe(true); + expect( + viewer.has('python.change_pythondistribution') || + viewer.has('python.delete_pythondistribution'), + 'the python viewer role changes or deletes nothing', + ).toBe(false); + + await openRunList(page); + // the rows are the three of this run: an empty or short list would pass the + // checks below without testing anything + await expect(page.locator('tbody tr')).toHaveCount(3); + + for (const distribution of [owned.python, owned.ansible]) { + expect( + await offeredActions(rowOf(page, distribution.name as string), page), + `actions of ${distribution.name}`, + ).toEqual(['Edit', 'Delete']); + } + await expect( + rowOf(page, viewable.name as string), + 'the row the editor may only read', + ).toBeVisible(); + await expect( + rowOf(page, viewable.name as string).locator('[data-cy=kebab-toggle]'), + 'actions menu of the distribution that is not owned', + ).toHaveCount(0); + await expect( + page.getByRole('menuitem', { name: /^(Edit|Delete)/ }), + ).toHaveCount(0); +}); + +test('the pages of the distributions offer Edit and Delete where the list does', async ({ + page, +}) => { + const plugins = [ + ['python', owned.python, true], + ['ansible', owned.ansible, true], + ['python', viewable, false], + ] as const; + + for (const [plugin, distribution, mayChange] of plugins) { + const permissionsRead = page.waitForResponse(isPermissionsRead); + await page.goto( + `${plugin}/distributions/${encodeURIComponent(distribution.name as string)}`, + ); + await permissionsRead; + await expect(title(page, distribution.name as string)).toBeVisible(); + await page.waitForLoadState('networkidle'); + + const edit = page.getByRole('button', { name: 'Edit', exact: true }); + const remove = page.getByRole('button', { name: 'Delete', exact: true }); + if (mayChange) { + await expect(edit, `Edit on ${distribution.name}`).toBeVisible(); + await expect(remove, `Delete on ${distribution.name}`).toBeVisible(); + } else { + await expect(edit, `Edit on ${distribution.name}`).toHaveCount(0); + await expect(remove, `Delete on ${distribution.name}`).toHaveCount(0); + } + } +}); diff --git a/e2e/remote/distribution-warnings.spec.ts b/e2e/remote/distribution-warnings.spec.ts new file mode 100644 index 00000000..27444c88 --- /dev/null +++ b/e2e/remote/distribution-warnings.spec.ts @@ -0,0 +1,34 @@ +import { test } from '@playwright/test'; +import { + expectDetailState, + expectListStates, + expectTabState, +} from '../support/serving-checks'; +import { ADMIN_STATES } from '../support/serving-states'; + +// What the administrator is told about the served state of the lab's serving +// distributions, one for every state a distribution can serve in. The same +// objects are read on the list, on the page of each distribution and on the +// Distributions tab of the repository it serves; this spec writes nothing. + +test('the list shows the served state of every serving distribution', async ({ + page, +}) => { + await expectListStates(page, ADMIN_STATES); +}); + +for (const state of ADMIN_STATES) { + test(`the page of ${state.name} shows ${state.warning ?? 'no warning'}`, async ({ + page, + }) => { + await expectDetailState(page, state); + }); +} + +for (const state of ADMIN_STATES.filter(({ onTab }) => onTab)) { + test(`the tab of the repository of ${state.name} shows ${state.warning ?? 'no warning'}`, async ({ + page, + }) => { + await expectTabState(page, state); + }); +} diff --git a/e2e/remote/distribution-warnings.viewer.spec.ts b/e2e/remote/distribution-warnings.viewer.spec.ts new file mode 100644 index 00000000..a39424d0 --- /dev/null +++ b/e2e/remote/distribution-warnings.viewer.spec.ts @@ -0,0 +1,35 @@ +import { test } from '@playwright/test'; +import { + expectDetailState, + expectListStates, + expectTabState, +} from '../support/serving-checks'; +import { VIEWER_STATES } from '../support/serving-states'; + +// What the read-only viewer is told about the same serving distributions. The +// viewer may read file distributions and may not read any publication, so a +// state that depends on the publications is shown as "Cannot be checked" and +// never as a distribution that serves nothing or is out of date; a state that +// does not depend on them is told as to everyone. This spec writes nothing. + +test('the list shows the served state of every serving distribution the viewer may read', async ({ + page, +}) => { + await expectListStates(page, VIEWER_STATES); +}); + +for (const state of VIEWER_STATES) { + test(`the page of ${state.name} shows ${state.warning ?? 'no warning'}`, async ({ + page, + }) => { + await expectDetailState(page, state); + }); +} + +for (const state of VIEWER_STATES.filter(({ onTab }) => onTab)) { + test(`the tab of the repository of ${state.name} shows ${state.warning ?? 'no warning'}`, async ({ + page, + }) => { + await expectTabState(page, state); + }); +} diff --git a/e2e/support/api.ts b/e2e/support/api.ts index df523008..ef14d5b7 100644 --- a/e2e/support/api.ts +++ b/e2e/support/api.ts @@ -1,5 +1,8 @@ import { type APIRequestContext, request } from '@playwright/test'; +import { getDistributionsAnsibleAnsibleListUrl } from '@pulp-ui/sdk/ansible/distributions-ansible'; import { getRepositoriesAnsibleAnsibleListUrl } from '@pulp-ui/sdk/ansible/repositories-ansible'; +import { getDistributionsContainerContainerListUrl } from '@pulp-ui/sdk/container/distributions-container'; +import { getRepositoriesContainerContainerListUrl } from '@pulp-ui/sdk/container/repositories-container'; import { getContentguardsCoreRbacListUrl } from '@pulp-ui/sdk/core/contentguards-rbac'; import { getGroupsListUrl } from '@pulp-ui/sdk/core/groups'; import type { AsyncOperationResponse } from '@pulp-ui/sdk/core/models/async-operation-response.zod'; @@ -16,6 +19,10 @@ import { getDistributionsFileFileListUrl } from '@pulp-ui/sdk/file/distributions import { getPublicationsFileFileListUrl } from '@pulp-ui/sdk/file/publications-file'; import { getRemotesFileFileListUrl } from '@pulp-ui/sdk/file/remotes-file'; import { getRepositoriesFileFileListUrl } from '@pulp-ui/sdk/file/repositories-file'; +import { getDistributionsMavenMavenListUrl } from '@pulp-ui/sdk/maven/distributions-maven'; +import { getRepositoriesMavenMavenListUrl } from '@pulp-ui/sdk/maven/repositories-maven'; +import { getDistributionsNpmNpmListUrl } from '@pulp-ui/sdk/npm/distributions-npm'; +import { getRepositoriesNpmNpmListUrl } from '@pulp-ui/sdk/npm/repositories-npm'; import { getDistributionsPythonPypiListUrl } from '@pulp-ui/sdk/python/distributions-pypi'; import { getPublicationsPythonPypiListUrl } from '@pulp-ui/sdk/python/publications-pypi'; import { getRemotesPythonPythonListUrl } from '@pulp-ui/sdk/python/remotes-python'; @@ -70,6 +77,13 @@ export function apiContext(): Promise { }); } +// Endpoints of plugins a deployment may leave out; a list the server does not +// know holds nothing to clean up. +const OPTIONAL_ENDPOINTS: string[] = [ + getDistributionsContainerContainerListUrl(), + getRepositoriesContainerContainerListUrl(), +]; + // Every object of a list endpoint matching the filters, all pages, read with // any request context (the one of the account a spec signs in with). export async function listAll( @@ -79,11 +93,15 @@ export async function listAll( ): Promise { const results: PulpObject[] = []; for (let offset = 0; ; offset += 100) { - const page = await apiGet(api, url(path), { - ...params, - limit: '100', - offset: String(offset), + const answer = await apiCall(api, 'GET', url(path), { + params: { ...params, limit: '100', offset: String(offset) }, + accept: OPTIONAL_ENDPOINTS.includes(path) ? [404] : [], }); + // a plugin the deployment does not have answers 404 for its lists + if (answer.status === 404) { + return results; + } + const page = answer.body; results.push(...page.results); if (!page.next) { return results; @@ -119,6 +137,10 @@ const DISTRIBUTIONS = [ getDistributionsDebAptListUrl(), getDistributionsRpmRpmListUrl(), getDistributionsPythonPypiListUrl(), + getDistributionsMavenMavenListUrl(), + getDistributionsNpmNpmListUrl(), + getDistributionsAnsibleAnsibleListUrl(), + getDistributionsContainerContainerListUrl(), ]; const PUBLICATIONS = [ getPublicationsFileFileListUrl(), @@ -132,6 +154,9 @@ const REPOSITORIES = [ getRepositoriesRpmRpmListUrl(), getRepositoriesPythonPythonListUrl(), getRepositoriesAnsibleAnsibleListUrl(), + getRepositoriesMavenMavenListUrl(), + getRepositoriesNpmNpmListUrl(), + getRepositoriesContainerContainerListUrl(), ]; const REMOTES = [ getRemotesFileFileListUrl(), diff --git a/e2e/support/distribution-screens.ts b/e2e/support/distribution-screens.ts new file mode 100644 index 00000000..5a3b4ce9 --- /dev/null +++ b/e2e/support/distribution-screens.ts @@ -0,0 +1,178 @@ +import { + type APIRequestContext, + type Locator, + type Page, + expect, +} from '@playwright/test'; +import { getRepositoriesAnsibleAnsibleListUrl } from '@pulp-ui/sdk/ansible/repositories-ansible'; +import { getRepositoriesContainerContainerListUrl } from '@pulp-ui/sdk/container/repositories-container'; +import { getRepositoriesDebAptListUrl } from '@pulp-ui/sdk/deb/repositories-apt'; +import { getRepositoriesFileFileListUrl } from '@pulp-ui/sdk/file/repositories-file'; +import { getRepositoriesMavenMavenListUrl } from '@pulp-ui/sdk/maven/repositories-maven'; +import { getRepositoriesNpmNpmListUrl } from '@pulp-ui/sdk/npm/repositories-npm'; +import { getRepositoriesPythonPythonListUrl } from '@pulp-ui/sdk/python/repositories-python'; +import { getRepositoriesRpmRpmListUrl } from '@pulp-ui/sdk/rpm/repositories-rpm'; +import { type PulpObject, listAll } from './api'; +import { title } from './sign-in'; + +// What the distribution specs share: the plugins and where each one's +// distributions and repositories live, and the steps of the screens the specs +// drive the way a person does. + +export type DistributionPlugin = + 'file' | 'deb' | 'rpm' | 'python' | 'maven' | 'npm' | 'ansible' | 'container'; + +interface PluginFacts { + // the name the plugin is shown under, as in the "Create distribution" menu + label: string; + // the path of the plugin's distribution and repository endpoints + distributions: string; + repositories: string; +} + +export const PLUGINS: Record = { + file: { + label: 'File', + distributions: 'distributions/file/file/', + repositories: getRepositoriesFileFileListUrl(), + }, + deb: { + label: 'deb', + distributions: 'distributions/deb/apt/', + repositories: getRepositoriesDebAptListUrl(), + }, + rpm: { + label: 'RPM', + distributions: 'distributions/rpm/rpm/', + repositories: getRepositoriesRpmRpmListUrl(), + }, + python: { + label: 'Python', + distributions: 'distributions/python/pypi/', + repositories: getRepositoriesPythonPythonListUrl(), + }, + maven: { + label: 'Maven', + distributions: 'distributions/maven/maven/', + repositories: getRepositoriesMavenMavenListUrl(), + }, + npm: { + label: 'npm', + distributions: 'distributions/npm/npm/', + repositories: getRepositoriesNpmNpmListUrl(), + }, + ansible: { + label: 'Ansible', + distributions: 'distributions/ansible/ansible/', + repositories: getRepositoriesAnsibleAnsibleListUrl(), + }, + container: { + label: 'Container', + distributions: 'distributions/container/container/', + repositories: getRepositoriesContainerContainerListUrl(), + }, +}; + +// The shared guard the lab's serving objects use. The specs read it and attach +// it to their own distributions; they never change it. +export const SERVING_GUARD = 'zz-synth-serving-guard'; + +const escape = (text: string): string => + text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + +// The pulp_href of an object found by exact name, or undefined. +export async function findByName( + api: APIRequestContext, + path: string, + name: string, +): Promise { + const found = await listAll(api, path, { name }); + return found[0]; +} + +// The distributions of a plugin that carry a name, read from the server. +export async function distributionsNamed( + api: APIRequestContext, + plugin: DistributionPlugin, + name: string, +): Promise { + return listAll(api, PLUGINS[plugin].distributions, { name }); +} + +// The result of choosing an option in one of the form's typeaheads: the text +// is typed into the field the placeholder names, and the option that carries it +// is clicked once the list shows it. +export async function pickFromTypeahead( + page: Page, + placeholder: string, + text: string, +): Promise { + const box = page.getByRole('combobox', { name: placeholder }); + await box.click(); + await box.fill(text); + await page + .getByRole('option', { name: new RegExp(escape(text)) }) + .first() + .click(); +} + +// Opens the form that creates a distribution of a plugin from the list of every +// plugin's distributions, through the "Create distribution" menu. +export async function openCreateForm( + page: Page, + plugin: DistributionPlugin, +): Promise { + await page.goto('distributions'); + await expect(title(page, 'Distributions')).toBeVisible(); + await page.getByRole('button', { name: 'Create distribution' }).click(); + await page + .getByRole('menuitem', { name: `${PLUGINS[plugin].label} distribution` }) + .click(); + await expect(title(page, 'Create distribution')).toBeVisible(); +} + +export const createButton = (page: Page): Locator => + page.getByRole('button', { name: 'Create', exact: true }); + +// Chooses to protect the distribution with the content guard of the name. +export async function chooseGuard(page: Page, guard: string): Promise { + await page + .getByRole('radio', { name: /Protected by a content guard/ }) + .check(); + await pickFromTypeahead(page, 'Select a content guard', guard); +} + +// Chooses the explicit Public protection. +export async function choosePublic(page: Page): Promise { + await page.getByRole('radio', { name: /^Public/ }).check(); +} + +// Fills the name and the base path of the create form. +export async function fillNames( + page: Page, + name: string, + basePath = name, +): Promise { + await page.locator('#name').fill(name); + await page.locator('#base_path').fill(basePath); +} + +// The row of the list of every plugin's distributions that carries a name. +export const listRow = (page: Page, name: string): Locator => + page.locator(`[data-cy="DistributionList-row-${name}"]`); + +// Opens the list narrowed to the names that contain the text, once its rows are +// those of the address. +export async function openListFiltered( + page: Page, + text: string, + extra = '', +): Promise { + await page.goto( + `distributions?name__icontains=${encodeURIComponent(text)}${extra}`, + ); + await expect(title(page, 'Distributions')).toBeVisible(); + await expect( + page.locator('table[aria-label="Distributions"][data-rows-loaded="true"]'), + ).toBeVisible(); +} diff --git a/e2e/support/framework-list.ts b/e2e/support/framework-list.ts index bfe26433..d08de218 100644 --- a/e2e/support/framework-list.ts +++ b/e2e/support/framework-list.ts @@ -9,7 +9,7 @@ import { apiGet } from './sdk-request'; // on screen while the new ones are read) and `data-columns-loaded` is true once // every column that comes from a read of its own has settled. -export type ListKind = 'Repositories' | 'Remotes'; +export type ListKind = 'Repositories' | 'Remotes' | 'Distributions'; const tableSelector = (kind: ListKind, attributes: string): string => `table[aria-label="${kind}"]${attributes}`; @@ -86,9 +86,13 @@ export async function openSidebarGroup( // the group the entry sits in first when it is closed. `id` is the entry's id // in the menu, for example `file-repositories`. export async function clickSidebar(page: Page, id: string): Promise { - await openSidebarGroup( - page, - id.endsWith('-remotes') ? 'Remotes' : 'Repositories', - ); + // the list of every plugin's distributions is an entry of its own, not in a + // group + if (id !== 'distributions') { + await openSidebarGroup( + page, + id.endsWith('-remotes') ? 'Remotes' : 'Repositories', + ); + } await page.locator(`[data-cy=pulp-menu-item-${id}]`).click(); } diff --git a/e2e/support/serving-checks.ts b/e2e/support/serving-checks.ts new file mode 100644 index 00000000..b56e5c40 --- /dev/null +++ b/e2e/support/serving-checks.ts @@ -0,0 +1,93 @@ +import { type Page, expect } from '@playwright/test'; +import { listRow, openListFiltered } from './distribution-screens'; +import { ALL_WARNINGS, type ServingState } from './serving-states'; +import { title } from './sign-in'; + +// The checks of what the screens say about the served state of the lab's +// serving distributions, shared by the specs of the administrator and of the +// viewer. Each takes the table of states one account is shown. + +const SERVING_PREFIX = 'zz-synth-serving-'; + +// The column of the list that holds the served state. +const SERVED_COLUMN = 6; + +// The list narrowed to the serving objects shows the served state of every +// row: the cell holds exactly the text the state is drawn with. +export async function expectListStates( + page: Page, + states: ServingState[], +): Promise { + await openListFiltered(page, SERVING_PREFIX, '&page_size=100'); + await expect( + page.locator( + 'table[aria-label="Distributions"][data-columns-loaded="true"]', + ), + ).toBeVisible(); + // the table holds exactly the distributions the account is shown + await expect(page.locator('tbody tr')).toHaveCount(states.length); + + for (const { name, served } of states) { + await expect( + listRow(page, name).locator('td').nth(SERVED_COLUMN), + `served state of ${name} on the list`, + ).toHaveText(served); + } +} + +// The label beside the address on a page that shows the distribution's URL: the +// one of the state, and none of the others. A page that is still reading what +// the distribution serves draws no label yet, so the absence of the others is +// only checked once the page has settled. +async function expectWarning( + page: Page, + scope: ReturnType, + state: ServingState, +): Promise { + if (state.warning !== null) { + await expect( + scope.locator('.pf-v6-c-label', { hasText: state.warning }), + `the label of ${state.name}`, + ).toBeVisible(); + } + await expect(scope.locator('.pf-v6-c-skeleton')).toHaveCount(0); + await page.waitForLoadState('networkidle'); + for (const other of ALL_WARNINGS.filter((text) => text !== state.warning)) { + await expect( + scope.locator('.pf-v6-c-label', { hasText: other }), + `${other} is not drawn for ${state.name}`, + ).toHaveCount(0); + } +} + +// The page of one distribution. +export async function expectDetailState( + page: Page, + state: ServingState, +): Promise { + await page.goto( + `${state.plugin}/distributions/${encodeURIComponent(state.name)}`, + ); + await expect(title(page, state.name)).toBeVisible(); + await expectWarning( + page, + page.locator('[data-cy=DistributionDetail-details]'), + state, + ); +} + +// The Distributions tab of the repository the distribution serves, which has +// the name of the distribution. +export async function expectTabState( + page: Page, + state: ServingState, +): Promise { + await page.goto( + `${state.plugin}/repositories/${encodeURIComponent(state.name)}/distributions`, + ); + await expect(title(page, state.name)).toBeVisible(); + const tab = page.locator('[data-cy=DistributionsTab]').locator('..'); + const row = tab.getByRole('row').filter({ hasText: state.name }); + await expect(row, `${state.name} on the tab of its repository`).toBeVisible(); + await expectWarning(page, row, state); +} diff --git a/e2e/support/serving-states.ts b/e2e/support/serving-states.ts new file mode 100644 index 00000000..46ea53cc --- /dev/null +++ b/e2e/support/serving-states.ts @@ -0,0 +1,112 @@ +import type { DistributionPlugin } from './distribution-screens'; + +// The distributions the lab keeps so that every state a distribution can serve +// in has a real object: `zz-synth-serving--`, each with a +// repository of the same name. Specs read them and never change them. For each +// one the table says what the screens show: the text of the "Served state" +// cell of the list, and the label that stands beside the address on the +// distribution's page and on the repository's Distributions tab (null when the +// state draws none). + +export interface ServingState { + plugin: DistributionPlugin; + state: string; + name: string; + // the "Served state" cell of the list + served: string; + // the label beside the address, or null when there is none + warning: string | null; + // whether the repository's Distributions tab lists it: the plugin has such a + // tab and the distribution serves the repository + onTab: boolean; +} + +export const NOT_BOUND = 'Not bound to anything'; +export const NOTHING = 'Serves nothing (404): no publication'; +export const STALE = 'Serves version 1, latest is 2'; +export const CANNOT_CHECK = 'Cannot be checked'; +export const DEPRECATED = 'Bound to a deprecated publication'; + +// Every label a distribution's page may draw beside its address, so a state +// that draws none can be checked against all of them. +export const ALL_WARNINGS = [ + NOT_BOUND, + NOTHING, + STALE, + CANNOT_CHECK, + DEPRECATED, +]; + +const name = (plugin: DistributionPlugin, state: string) => + `zz-synth-serving-${plugin}-${state}`; + +function state( + plugin: DistributionPlugin, + stateName: string, + served: string, + warning: string | null, + onTab = false, +): ServingState { + return { + plugin, + state: stateName, + name: name(plugin, stateName), + served, + warning, + onTab, + }; +} + +// What the administrator is shown. +export const ADMIN_STATES: ServingState[] = [ + state('file', 'repo-fresh', 'Served', null, true), + state('file', 'repo-stale', STALE, STALE, true), + state('file', 'repo-404', NOTHING, NOTHING, true), + state('file', 'pub-fresh', 'Served', null, true), + state('file', 'pub-stale', STALE, STALE, true), + state('file', 'version-pub', 'Served', null, true), + state('file', 'version-nopub', NOTHING, NOTHING, true), + state('file', 'none', NOT_BOUND, NOT_BOUND), + state('file', 'public', 'Served', null, true), + state('file', 'guarded', 'Served', null, true), + ...(['deb', 'rpm'] as const).flatMap((plugin) => [ + state(plugin, 'repo-fresh', 'Served', null, true), + state(plugin, 'repo-stale', STALE, STALE, true), + state(plugin, 'repo-404', NOTHING, NOTHING, true), + ]), + state('python', 'repo', 'Not applicable', null, true), + state('python', 'pub', DEPRECATED, DEPRECATED, true), + ...(['maven', 'npm', 'ansible', 'container'] as const).map((plugin) => + state(plugin, 'repo', 'Not applicable', null), + ), +]; + +// What the viewer is shown. The viewer reads file distributions and the +// container one and no publication of any plugin, so what depends on the +// publications cannot be told: it says so instead of claiming the +// distribution serves nothing or is out of date. A state that does not depend +// on them is told to everyone. +const NEEDS_PUBLICATIONS = new Set([ + 'repo-fresh', + 'repo-stale', + 'repo-404', + 'version-pub', + 'version-nopub', + 'public', + 'guarded', +]); + +export const VIEWER_STATES: ServingState[] = ADMIN_STATES.filter( + ({ plugin }) => plugin === 'file' || plugin === 'container', +).map((entry) => + entry.plugin === 'file' && NEEDS_PUBLICATIONS.has(entry.state) + ? { ...entry, served: CANNOT_CHECK, warning: CANNOT_CHECK } + : entry.plugin === 'file' && + (entry.state === 'pub-fresh' || entry.state === 'pub-stale') + ? // bound to one publication: it serves that one whoever asks. The + // repository's tab finds such a distribution through the repository's + // publications, which the viewer may not read, so it is not listed + // there. + { ...entry, served: 'Served', warning: null, onTab: false } + : entry, +); From dbd23c4509be8ef2906d2b67aa8d664deea15a5b Mon Sep 17 00:00:00 2001 From: Danilo Lakovic Date: Sun, 22 Nov 2026 13:52:38 +0100 Subject: [PATCH 3/3] Measure the cost of the distribution list at lab scale A browser check, tagged @scale and run on its own, times the list of every plugin's distributions on a server that holds more than 1,300 of them. Each figure is the median of five runs from a fresh load of the application, and no run may take more than twice its budget: the default page of 50 and a page of 500, from the click to the rows shown and to every derived column settled; the public-only filter and a base path filter, from the change to the rows that answer it. The public-only result is recognised by the number of matches the server reports, because the table of the unfiltered list stays on screen for a moment after the switch is pressed. The requests of one load are counted too: none may go to the address of a single object or to the permission read of one, and the total is held to a budget for each page size. The figures are printed and attached to the report, which stays out of the repository. --- e2e/remote/distribution-list-scale.spec.ts | 354 +++++++++++++++++++++ 1 file changed, 354 insertions(+) create mode 100644 e2e/remote/distribution-list-scale.spec.ts diff --git a/e2e/remote/distribution-list-scale.spec.ts b/e2e/remote/distribution-list-scale.spec.ts new file mode 100644 index 00000000..66cd75fd --- /dev/null +++ b/e2e/remote/distribution-list-scale.spec.ts @@ -0,0 +1,354 @@ +import { type Page, expect, test } from '@playwright/test'; +import { apiContext, listAll } from '../support/api'; +import { baseUrl } from '../support/env'; +import { clickSidebar, listTable } from '../support/framework-list'; +import { title } from '../support/sign-in'; + +// How fast the list of every plugin's distributions responds on a server that +// holds 1,300 and more distributions (the lab's seeded data, which this spec +// only reads). Time runs from the click or the move that asks for the screen, +// with the application already loaded and the screen's data not in its cache, +// to the table attribute that says the rows (`data-rows-loaded`) or every +// column that has a read of its own (`data-columns-loaded`) is there. Every +// figure is the median of five runs, and no single run may take more than +// twice its budget. The figures are printed, attached to the report and +// asserted; they are kept in the report folder and never committed. + +const RUNS = 5; +const LIMIT_FACTOR = 2; + +// Budgets in milliseconds. +const BUDGET = { + pageRows: 2_000, + pageColumns: 3_000, + largeRows: 4_000, + largeColumns: 8_000, + publicOnly: 4_000, + basePath: 3_000, +} as const; + +// The most API requests one load of the list may make. +const REQUESTS = { page: 16, large: 48 } as const; + +// An address of one object, not of a list: a uuid or a number is its last +// segment. A list must read objects in batches and never one by one. +const SINGLE_OBJECT = + /\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|\d+)\/$/i; + +interface Figure { + name: string; + runs: number[]; + budget: number; +} + +const median = (values: number[]): number => { + const sorted = [...values].sort((a, b) => a - b); + return sorted[Math.floor(sorted.length / 2)] as number; +}; + +const figures: Figure[] = []; + +// Prints the figure and keeps it for the report, then asserts the median and +// the slowest run against the budget without ending the test, so every figure +// of a test is taken. +function judge(name: string, runs: number[], budget: number): void { + figures.push({ name, runs, budget }); + const slowest = Math.max(...runs); + console.log( + `SCALE ${name}: median ${Math.round(median(runs))} ms, maximum ${Math.round(slowest)} ms, budget ${budget} ms, runs [${runs + .map((run) => Math.round(run)) + .join(', ')}]`, + ); + expect + .soft(median(runs), `${name}: median of ${RUNS} runs`) + .toBeLessThanOrEqual(budget); + expect + .soft(slowest, `${name}: slowest of ${RUNS} runs`) + .toBeLessThanOrEqual(budget * LIMIT_FACTOR); +} + +test.afterAll(async () => { + await test.info().attach('scale-figures.json', { + body: JSON.stringify(figures, null, 2), + contentType: 'application/json', + }); +}); + +const elapsed = (since: number) => performance.now() - since; + +// A fresh load of the application on its Status screen, so no list has been +// read. +async function fresh(page: Page): Promise { + await page.goto('status'); + await expect(title(page, 'Status')).toBeVisible(); + await page.waitForLoadState('networkidle'); +} + +// Moves inside the application to an address, as following a link does: the +// page is not loaded again, so what the application has read stays in its +// cache. The address is below the UI root of the run, which the page must be +// under; a page anywhere else is a mistake of the test and fails here, not as +// a missing table later. +async function moveTo(page: Page, address: string): Promise { + const root = new URL(baseUrl()).pathname; + const here = new URL(page.url()).pathname; + if (!here.startsWith(root)) { + throw new Error(`the page is at ${here}, not under the UI root ${root}`); + } + + await page.evaluate((target) => { + window.history.pushState({}, '', target); + window.dispatchEvent(new PopStateEvent('popstate', { state: {} })); + }, `${root}${address}`); +} + +// Times how long the list takes to show its rows and then to settle every +// column that reads for itself, from the moment `trigger` is called. Both +// waits are started before the trigger and both are always handled: a trigger +// that fails must not leave a wait behind that rejects unhandled later, when +// its timeout runs out, and is reported as a second, misleading failure. +async function timeLoad( + page: Page, + trigger: () => Promise, +): Promise<{ rows: number; columns: number }> { + const start = performance.now(); + const timeUntil = (settled: { rows?: boolean; columns?: boolean }) => + listTable(page, 'Distributions', settled) + .waitFor() + .then(() => elapsed(start)); + const waits = Promise.allSettled([ + timeUntil({ rows: true }), + timeUntil({ rows: true, columns: true }), + ]); + + await trigger(); + const [rows, columns] = await waits; + if (rows.status === 'rejected') { + throw rows.reason; + } + if (columns.status === 'rejected') { + throw columns.reason; + } + return { rows: rows.value, columns: columns.value }; +} + +const requestsOf = (page: Page) => { + const seen: string[] = []; + const listener = (request: { url: () => string }) => { + const { pathname, search } = new URL(request.url()); + if (pathname.startsWith('/pulp/api/')) { + seen.push(`${pathname}${search}`); + } + }; + page.on('request', listener); + return { + seen, + stop: () => page.off('request', listener), + }; +}; + +function expectOnlyListReads(reads: string[], name: string): void { + const offending = reads.filter( + (read) => + read.includes('my_permissions') || + SINGLE_OBJECT.test(read.split('?')[0] ?? ''), + ); + expect( + offending, + `${name}: requests to one object's address or to my_permissions`, + ).toEqual([]); +} + +const settle = (page: Page) => page.waitForTimeout(500); + +// The types the list asks for: the distributions of the installed plugins. +const LISTED_TYPES = [ + 'file.file', + 'deb.apt-distribution', + 'rpm.rpm', + 'python.python', + 'maven.maven', + 'npm.npm', + 'ansible.ansible', + 'container.container', +].join(','); + +// How many distributions the list holds that have no content guard, from the +// server, taken before the clock runs: the public-only result has arrived when +// the list says that many matched. The table of the unfiltered list stays on +// screen for a moment after the switch is pressed, so its attributes alone do +// not tell the two apart. +async function publicDistributions(): Promise { + const api = await apiContext(); + try { + const rows = await listAll(api, 'distributions/', { + pulp_type__in: LISTED_TYPES, + fields: 'pulp_href,content_guard', + }); + return rows.filter((row) => row['content_guard'] === null).length; + } finally { + await api.dispose(); + } +} + +// Picks which filter the search box applies; the box keeps the choice of the +// run before. +async function chooseFilter(page: Page, name: string): Promise { + await page + .locator('[data-cy=compound_filter]') + .getByRole('button') + .first() + .click(); + await page.getByRole('menuitem', { name, exact: true }).click(); +} + +test.describe('@scale the distribution list at 1300 or more distributions', () => { + // A figure over its budget fails its test softly: the tests are independent, + // so a miss never hides the figures of the others. + test.setTimeout(600_000); + + test('@scale D1 the default page of 50 shows its rows, settles its columns and reads within the request budget', async ({ + page, + }) => { + const rows: number[] = []; + const columns: number[] = []; + const counts: number[] = []; + + for (let run = 0; run < RUNS; run += 1) { + await fresh(page); + const requests = requestsOf(page); + + const timed = await timeLoad(page, () => + clickSidebar(page, 'distributions'), + ); + rows.push(timed.rows); + columns.push(timed.columns); + await settle(page); + requests.stop(); + + expect(await page.locator('tbody tr').count(), 'rows of the page').toBe( + 50, + ); + expectOnlyListReads(requests.seen, 'D1'); + counts.push(requests.seen.length); + } + + judge('D1 rows shown (50)', rows, BUDGET.pageRows); + judge('D1 columns settled (50)', columns, BUDGET.pageColumns); + console.log( + `SCALE D3 requests of one load of 50 rows: ${counts.join(', ')}`, + ); + expect + .soft(Math.max(...counts), 'D3 requests of a load of 50 rows') + .toBeLessThanOrEqual(REQUESTS.page); + }); + + test('@scale D2 a page of 500 shows its rows, settles its columns and reads within the request budget', async ({ + page, + }) => { + const rows: number[] = []; + const columns: number[] = []; + const counts: number[] = []; + + for (let run = 0; run < RUNS; run += 1) { + await fresh(page); + const requests = requestsOf(page); + + // the sidebar leads to the default page, so the page of 500 is reached by + // a move inside the application; its data is not in the cache + const timed = await timeLoad(page, () => + moveTo(page, 'distributions?page_size=500'), + ); + rows.push(timed.rows); + columns.push(timed.columns); + await settle(page); + requests.stop(); + + expect(await page.locator('tbody tr').count(), 'rows of the page').toBe( + 500, + ); + expectOnlyListReads(requests.seen, 'D2'); + counts.push(requests.seen.length); + } + + judge('D2 rows shown (500)', rows, BUDGET.largeRows); + judge('D2 columns settled (500)', columns, BUDGET.largeColumns); + console.log( + `SCALE D3 requests of one load of 500 rows: ${counts.join(', ')}`, + ); + expect + .soft(Math.max(...counts), 'D3 requests of a load of 500 rows') + .toBeLessThanOrEqual(REQUESTS.large); + }); + + test('@scale D4 the public-only filter and a base path filter show their rows quickly', async ({ + page, + }) => { + const publicOnly: number[] = []; + const byBasePath: number[] = []; + + // each run asks for a base path the list has not been asked before + const basePaths = [ + 'zz-synth-file-0011', + 'zz-synth-file-0012', + 'zz-synth-file-0013', + 'zz-synth-file-0015', + 'zz-synth-file-0016', + ]; + + const publicCount = await publicDistributions(); + expect(publicCount, 'public distributions on the server').toBeGreaterThan( + 0, + ); + + for (let run = 0; run < RUNS; run += 1) { + await fresh(page); + await clickSidebar(page, 'distributions'); + await expect( + listTable(page, 'Distributions', { rows: true, columns: true }), + ).toBeVisible(); + await settle(page); + + // public only: the result has arrived when the list says how many + // matched and shows that many rows, all public + let start = performance.now(); + // the switch's input sits under its drawn toggle, so the click goes to + // the label that wraps both + await page.locator('label[for="distribution-public-only"]').click(); + await expect(page).toHaveURL(/public=true/); + await expect(page.locator('.pf-v6-c-pagination').first()).toContainText( + new RegExp(`of\\s+${publicCount}\\b`), + ); + await expect( + listTable(page, 'Distributions', { rows: true }), + ).toBeVisible(); + await expect(page.locator('tbody tr')).toHaveCount( + Math.min(publicCount, 50), + ); + await expect(page.locator('tbody tr').first()).toContainText('Public'); + publicOnly.push(elapsed(start)); + + // base path + await moveTo(page, 'distributions'); + await expect(page).not.toHaveURL(/public=|base_path/); + await chooseFilter(page, 'Base path'); + const pathBox = page.getByRole('textbox', { + name: 'base_path__icontains', + }); + await pathBox.fill(basePaths[run] as string); + start = performance.now(); + await pathBox.press('Enter'); + await expect(page).toHaveURL(/base_path__icontains=/); + await expect(page.locator('tbody tr').first()).toContainText( + basePaths[run] as string, + ); + await expect( + listTable(page, 'Distributions', { rows: true }), + ).toBeVisible(); + byBasePath.push(elapsed(start)); + } + + judge('D4 public only applied', publicOnly, BUDGET.publicOnly); + judge('D4 base path filter applied', byBasePath, BUDGET.basePath); + }); +});