diff --git a/e2e-playwright/dashboard-cujs/adhoc-filters-cujs.spec.ts b/e2e-playwright/dashboard-cujs/adhoc-filters-cujs.spec.ts index 038fe099eeb..2a0f6932141 100644 --- a/e2e-playwright/dashboard-cujs/adhoc-filters-cujs.spec.ts +++ b/e2e-playwright/dashboard-cujs/adhoc-filters-cujs.spec.ts @@ -1,6 +1,7 @@ import { test, expect } from '@grafana/plugin-e2e'; -import { setScopes } from '../utils/scope-helpers'; +import { setScopes, setupScopeRoutes } from '../utils/scope-helpers'; +import { testScopes } from '../utils/scopes'; import { getAdHocFilterOptionValues, @@ -13,6 +14,7 @@ import { } from './cuj-selectors'; import { prepareAPIMocks } from './utils'; +const USE_LIVE_DATA = Boolean(process.env.API_CONFIG_PATH); const DASHBOARD_UNDER_TEST = 'cuj-dashboard-1'; test.use({ @@ -34,6 +36,11 @@ test.describe( const adHocFilterPills = getAdHocFilterPills(page); const scopesSelectorInput = getScopesSelectorInput(page); + // Set up routes before any navigation (only for mocked mode) + if (!USE_LIVE_DATA) { + await setupScopeRoutes(page, testScopes()); + } + await test.step('1.Apply filtering to a whole dashboard', async () => { const dashboardPage = await gotoDashboardPage({ uid: DASHBOARD_UNDER_TEST }); diff --git a/e2e-playwright/dashboard-cujs/cuj-selectors.ts b/e2e-playwright/dashboard-cujs/cuj-selectors.ts index f2366fd2ef1..548c183ef3f 100644 --- a/e2e-playwright/dashboard-cujs/cuj-selectors.ts +++ b/e2e-playwright/dashboard-cujs/cuj-selectors.ts @@ -66,6 +66,17 @@ export function getScopesDashboards(page: Page) { return page.locator('[data-testid^="scopes-dashboards-"][role="treeitem"]'); } +/** + * Clicks the first available dashboard in the scopes dashboard list. + */ +export async function clickFirstScopesDashboard(page: Page) { + const dashboards = getScopesDashboards(page); + // Wait for at least one dashboard to be visible + await expect(dashboards.first()).toBeVisible({ timeout: 10000 }); + // Click - Playwright will automatically wait for the element to be actionable + await dashboards.first().click(); +} + export function getScopesDashboardsSearchInput(page: Page) { return page.getByTestId('scopes-dashboards-search'); } diff --git a/e2e-playwright/dashboard-cujs/dashboard-navigation.spec.ts b/e2e-playwright/dashboard-cujs/dashboard-navigation.spec.ts index 008e1e5538c..c941c40f6ef 100644 --- a/e2e-playwright/dashboard-cujs/dashboard-navigation.spec.ts +++ b/e2e-playwright/dashboard-cujs/dashboard-navigation.spec.ts @@ -1,8 +1,10 @@ import { test, expect } from '@grafana/plugin-e2e'; -import { setScopes } from '../utils/scope-helpers'; +import { setScopes, setupScopeRoutes } from '../utils/scope-helpers'; +import { testScopes } from '../utils/scopes'; import { + clickFirstScopesDashboard, getAdHocFilterPills, getGroupByInput, getGroupByValues, @@ -21,6 +23,7 @@ test.use({ }, }); +const USE_LIVE_DATA = Boolean(process.env.API_CONFIG_PATH); const DASHBOARD_UNDER_TEST = 'cuj-dashboard-1'; const DASHBOARD_UNDER_TEST_2 = 'cuj-dashboard-2'; const NAVIGATE_TO = 'cuj-dashboard-3'; @@ -38,6 +41,11 @@ test.describe( const adhocFilterPills = getAdHocFilterPills(page); const groupByValues = getGroupByValues(page); + // Set up routes before any navigation (only for mocked mode) + if (!USE_LIVE_DATA) { + await setupScopeRoutes(page, testScopes()); + } + await test.step('1.Search dashboard', async () => { await gotoDashboardPage({ uid: DASHBOARD_UNDER_TEST }); @@ -74,7 +82,7 @@ test.describe( await expect(markdownContent).toContainText(`now-12h`); - await scopesDashboards.first().click(); + await clickFirstScopesDashboard(page); await page.waitForURL('**/d/**'); await expect(markdownContent).toBeVisible(); @@ -117,10 +125,10 @@ test.describe( await groupByVariable.press('Enter'); await groupByVariable.press('Escape'); - await expect(scopesDashboards.first()).toBeVisible(); - const { getRequests, waitForExpectedRequests } = await trackDashboardReloadRequests(page); - await scopesDashboards.first().click(); + + await clickFirstScopesDashboard(page); + await page.waitForURL('**/d/**'); await waitForExpectedRequests(); await page.waitForLoadState('networkidle'); @@ -158,8 +166,7 @@ test.describe( const oldFilters = `GroupByVar: ${selectedValues}\n\nAdHocVar: ${processedPills}`; await expect(markdownContent).toContainText(oldFilters); - await expect(scopesDashboards.first()).toBeVisible(); - await scopesDashboards.first().click(); + await clickFirstScopesDashboard(page); await page.waitForURL('**/d/**'); const newPillCount = await adhocFilterPills.count(); diff --git a/e2e-playwright/dashboard-cujs/dashboard-view.spec.ts b/e2e-playwright/dashboard-cujs/dashboard-view.spec.ts index 53dd02a0314..e9c1370bbc6 100644 --- a/e2e-playwright/dashboard-cujs/dashboard-view.spec.ts +++ b/e2e-playwright/dashboard-cujs/dashboard-view.spec.ts @@ -165,9 +165,8 @@ test.describe( await refreshBtn.click(); - await page.waitForLoadState('networkidle'); - - expect(await panelContent.textContent()).not.toBe(panelContents); + // Wait for the panel content to change (not just for network to complete) + await expect(panelContent).not.toHaveText(panelContents!, { timeout: 10000 }); }); await test.step('6.Turn off refresh', async () => { diff --git a/e2e-playwright/dashboard-cujs/scope-cujs.spec.ts b/e2e-playwright/dashboard-cujs/scope-cujs.spec.ts index 54ec3ca7a8b..dd1cd50c35f 100644 --- a/e2e-playwright/dashboard-cujs/scope-cujs.spec.ts +++ b/e2e-playwright/dashboard-cujs/scope-cujs.spec.ts @@ -9,6 +9,7 @@ import { openScopesSelector, searchScopes, selectScope, + setupScopeRoutes, } from '../utils/scope-helpers'; import { testScopes } from '../utils/scopes'; @@ -36,32 +37,37 @@ test.describe( const scopesSelector = getScopesSelectorInput(page); const recentScopesSelector = getRecentScopesSelector(page); const scopeTreeCheckboxes = getScopeTreeCheckboxes(page); + const scopes = testScopes(); + + // Set up routes once before any navigation (only for mocked mode) + if (!USE_LIVE_DATA) { + await setupScopeRoutes(page, scopes); + } await test.step('1.View and select any scope', async () => { await gotoDashboardPage({ uid: DASHBOARD_UNDER_TEST }); expect.soft(scopesSelector).toHaveAttribute('data-value', ''); - const scopes = testScopes(); - await openScopesSelector(page, USE_LIVE_DATA ? undefined : scopes); //used only in mocked scopes version + await openScopesSelector(page, USE_LIVE_DATA ? undefined : scopes); let scopeName = await getScopeTreeName(page, 0); - const firstLevelScopes = scopes[0].children!; //used only in mocked scopes version + const firstLevelScopes = scopes[0].children!; await expandScopesSelection(page, scopeName, USE_LIVE_DATA ? undefined : firstLevelScopes); scopeName = await getScopeTreeName(page, 1); - const secondLevelScopes = firstLevelScopes[0].children!; //used only in mocked scopes version + const secondLevelScopes = firstLevelScopes[0].children!; await expandScopesSelection(page, scopeName, USE_LIVE_DATA ? undefined : secondLevelScopes); - const selectedScopes = [secondLevelScopes[0]]; //used only in mocked scopes version + const selectedScopes = [secondLevelScopes[0]]; scopeName = await getScopeLeafName(page, 0); let scopeTitle = await getScopeLeafTitle(page, 0); await selectScope(page, scopeName, USE_LIVE_DATA ? undefined : selectedScopes[0]); - await applyScopes(page, USE_LIVE_DATA ? undefined : selectedScopes); //used only in mocked scopes version + await applyScopes(page, USE_LIVE_DATA ? undefined : selectedScopes); expect.soft(scopesSelector).toHaveAttribute('data-value', scopeTitle); }); @@ -70,28 +76,27 @@ test.describe( await gotoDashboardPage({ uid: DASHBOARD_UNDER_TEST }); expect.soft(scopesSelector).toHaveAttribute('data-value', ''); - const scopes = testScopes(); - await openScopesSelector(page, USE_LIVE_DATA ? undefined : scopes); //used only in mocked scopes version + await openScopesSelector(page, USE_LIVE_DATA ? undefined : scopes); let scopeName = await getScopeTreeName(page, 0); - const firstLevelScopes = scopes[0].children!; //used only in mocked scopes version + const firstLevelScopes = scopes[0].children!; await expandScopesSelection(page, scopeName, USE_LIVE_DATA ? undefined : firstLevelScopes); scopeName = await getScopeTreeName(page, 1); - const secondLevelScopes = firstLevelScopes[0].children!; //used only in mocked scopes version + const secondLevelScopes = firstLevelScopes[0].children!; await expandScopesSelection(page, scopeName, USE_LIVE_DATA ? undefined : secondLevelScopes); const scopeTitles: string[] = []; - const selectedScopes = [secondLevelScopes[0], secondLevelScopes[1]]; //used only in mocked scopes version + const selectedScopes = [secondLevelScopes[0], secondLevelScopes[1]]; for (let i = 0; i < selectedScopes.length; i++) { scopeName = await getScopeLeafName(page, i); scopeTitles.push(await getScopeLeafTitle(page, i)); - await selectScope(page, scopeName, USE_LIVE_DATA ? undefined : selectedScopes[i]); //used only in mocked scopes version + await selectScope(page, scopeName, USE_LIVE_DATA ? undefined : selectedScopes[i]); } - await applyScopes(page, USE_LIVE_DATA ? undefined : selectedScopes); //used only in mocked scopes version + await applyScopes(page, USE_LIVE_DATA ? undefined : selectedScopes); await expect.soft(scopesSelector).toHaveAttribute('data-value', scopeTitles.join(' + ')); }); @@ -102,8 +107,7 @@ test.describe( expect.soft(scopesSelector).toHaveAttribute('data-value', ''); - const scopes = testScopes(); - await openScopesSelector(page, USE_LIVE_DATA ? undefined : scopes); //used only in mocked scopes version + await openScopesSelector(page, USE_LIVE_DATA ? undefined : scopes); await recentScopesSelector.click(); @@ -121,26 +125,25 @@ test.describe( expect.soft(scopesSelector).toHaveAttribute('data-value', ''); - const scopes = testScopes(); await openScopesSelector(page, USE_LIVE_DATA ? undefined : scopes); let scopeName = await getScopeTreeName(page, 1); - const firstLevelScopes = scopes[2].children!; //used only in mocked scopes version + const firstLevelScopes = scopes[2].children!; await expandScopesSelection(page, scopeName, USE_LIVE_DATA ? undefined : firstLevelScopes); scopeName = await getScopeTreeName(page, 1); - const secondLevelScopes = firstLevelScopes[0].children!; //used only in mocked scopes version + const secondLevelScopes = firstLevelScopes[0].children!; await expandScopesSelection(page, scopeName, USE_LIVE_DATA ? undefined : secondLevelScopes); - const selectedScopes = [secondLevelScopes[0]]; //used only in mocked scopes version + const selectedScopes = [secondLevelScopes[0]]; scopeName = await getScopeLeafName(page, 0); let scopeTitle = await getScopeLeafTitle(page, 0); await selectScope(page, scopeName, USE_LIVE_DATA ? undefined : selectedScopes[0]); - await applyScopes(page, USE_LIVE_DATA ? undefined : []); //used only in mocked scopes version + await applyScopes(page, USE_LIVE_DATA ? undefined : []); expect.soft(scopesSelector).toHaveAttribute('data-value', new RegExp(`^${scopeTitle}`)); }); @@ -148,17 +151,16 @@ test.describe( await test.step('5.View pre-completed production entity values as I type', async () => { await gotoDashboardPage({ uid: DASHBOARD_UNDER_TEST }); - const scopes = testScopes(); - await openScopesSelector(page, USE_LIVE_DATA ? undefined : scopes); //used only in mocked scopes version + await openScopesSelector(page, USE_LIVE_DATA ? undefined : scopes); let scopeName = await getScopeTreeName(page, 0); - const firstLevelScopes = scopes[0].children!; //used only in mocked scopes version + const firstLevelScopes = scopes[0].children!; await expandScopesSelection(page, scopeName, USE_LIVE_DATA ? undefined : firstLevelScopes); scopeName = await getScopeTreeName(page, 1); - const secondLevelScopes = firstLevelScopes[0].children!; //used only in mocked scopes version + const secondLevelScopes = firstLevelScopes[0].children!; await expandScopesSelection(page, scopeName, USE_LIVE_DATA ? undefined : secondLevelScopes); const scopeSearchOne = await getScopeLeafTitle(page, 0); diff --git a/e2e-playwright/dashboard-cujs/scope-redirect.spec.ts b/e2e-playwright/dashboard-cujs/scope-redirect.spec.ts index 952e8a3da63..b140e7a9838 100644 --- a/e2e-playwright/dashboard-cujs/scope-redirect.spec.ts +++ b/e2e-playwright/dashboard-cujs/scope-redirect.spec.ts @@ -1,6 +1,6 @@ import { test, expect } from '@grafana/plugin-e2e'; -import { applyScopes, openScopesSelector, selectScope } from '../utils/scope-helpers'; +import { applyScopes, openScopesSelector, selectScope, setupScopeRoutes } from '../utils/scope-helpers'; import { testScopesWithRedirect } from '../utils/scopes'; test.use({ @@ -16,8 +16,13 @@ test.describe('Scope Redirect Functionality', () => { test('should redirect to custom URL when scope has redirectUrl', async ({ page, gotoDashboardPage }) => { const scopes = testScopesWithRedirect(); - await test.step('Navigate to dashboard and open scopes selector', async () => { + await test.step('Set up routes and navigate to dashboard', async () => { + // Set up routes BEFORE navigation to ensure all requests are mocked + await setupScopeRoutes(page, scopes); await gotoDashboardPage({ uid: 'cuj-dashboard-1' }); + }); + + await test.step('Open scopes selector', async () => { await openScopesSelector(page, scopes); }); @@ -40,8 +45,12 @@ test.describe('Scope Redirect Functionality', () => { test('should prioritize redirectUrl over scope navigation fallback', async ({ page, gotoDashboardPage }) => { const scopes = testScopesWithRedirect(); - await test.step('Navigate to dashboard and open scopes selector', async () => { + await test.step('Set up routes and navigate to dashboard', async () => { + await setupScopeRoutes(page, scopes); await gotoDashboardPage({ uid: 'cuj-dashboard-1' }); + }); + + await test.step('Open scopes selector', async () => { await openScopesSelector(page, scopes); }); @@ -68,8 +77,12 @@ test.describe('Scope Redirect Functionality', () => { }) => { const scopes = testScopesWithRedirect(); - await test.step('Navigate to dashboard and select scope', async () => { + await test.step('Set up routes and navigate to dashboard', async () => { + await setupScopeRoutes(page, scopes); await gotoDashboardPage({ uid: 'cuj-dashboard-1' }); + }); + + await test.step('Select and apply scope', async () => { await openScopesSelector(page, scopes); await selectScope(page, 'sn-redirect-fallback', scopes[1]); await applyScopes(page, [scopes[1]]); @@ -112,8 +125,12 @@ test.describe('Scope Redirect Functionality', () => { }) => { const scopes = testScopesWithRedirect(); - await test.step('Navigate to dashboard and select scope', async () => { + await test.step('Set up routes and navigate to dashboard', async () => { + await setupScopeRoutes(page, scopes); await gotoDashboardPage({ uid: 'cuj-dashboard-1' }); + }); + + await test.step('Select and apply scope', async () => { await openScopesSelector(page, scopes); await selectScope(page, 'sn-redirect-fallback', scopes[1]); await applyScopes(page, [scopes[1]]); @@ -151,9 +168,13 @@ test.describe('Scope Redirect Functionality', () => { test('should not redirect to redirectPath when on active scope navigation', async ({ page, gotoDashboardPage }) => { const scopes = testScopesWithRedirect(); + await test.step('Set up routes and navigate to dashboard', async () => { + await setupScopeRoutes(page, scopes); + await gotoDashboardPage({ uid: 'cuj-dashboard-1' }); + }); + await test.step('Set up scope navigation to dashboard-1', async () => { // First, apply a scope that creates scope navigation to dashboard-1 (without redirectPath) - await gotoDashboardPage({ uid: 'cuj-dashboard-1' }); await openScopesSelector(page, scopes); await selectScope(page, 'sn-redirect-setup', scopes[2]); await applyScopes(page, [scopes[2]]); diff --git a/e2e-playwright/utils/scope-helpers.ts b/e2e-playwright/utils/scope-helpers.ts index fc88a79d8fa..df11644a396 100644 --- a/e2e-playwright/utils/scope-helpers.ts +++ b/e2e-playwright/utils/scope-helpers.ts @@ -6,7 +6,150 @@ import { Resource } from '../../public/app/features/apiserver/types'; import { testScopes } from './scopes'; -const USE_LIVE_DATA = Boolean(process.env.API_CALLS_CONFIG_PATH); +const USE_LIVE_DATA = Boolean(process.env.API_CONFIG_PATH); + +/** + * Sets up all scope-related API routes before navigation. + * This ensures that ALL scope API requests (including those made during initial page load) + * are intercepted by the mocks, preventing RTK Query from caching real API responses. + * + * Call this BEFORE navigating to a page (e.g., before gotoDashboardPage). + */ +export async function setupScopeRoutes(page: Page, scopes: TestScope[]): Promise { + // Route for scope node children (tree structure) + await page.route(`**/apis/scope.grafana.app/v0alpha1/namespaces/*/find/scope_node_children*`, async (route) => { + const url = new URL(route.request().url()); + const parentParam = url.searchParams.get('parent'); + const queryParam = url.searchParams.get('query'); + + // Find the appropriate scopes based on parent + let scopesToReturn = scopes; + if (parentParam) { + // Find nested scopes based on parent name + const findChildren = (items: TestScope[]): TestScope[] => { + for (const item of items) { + if (item.name === parentParam && item.children) { + return item.children; + } + if (item.children) { + const found = findChildren(item.children); + if (found.length > 0) { + return found; + } + } + } + return []; + }; + scopesToReturn = findChildren(scopes); + if (scopesToReturn.length === 0) { + scopesToReturn = scopes; // Fallback to root scopes + } + } + + // Filter by search query if provided + if (queryParam) { + const query = queryParam.toLowerCase(); + const filterByQuery = (items: TestScope[]): TestScope[] => { + const results: TestScope[] = []; + for (const item of items) { + // Exact match on name or title containing the query + if (item.name.toLowerCase() === query || item.title.toLowerCase() === query) { + results.push(item); + } else if (item.name.toLowerCase().includes(query) || item.title.toLowerCase().includes(query)) { + results.push(item); + } + // Also search in children + if (item.children) { + results.push(...filterByQuery(item.children)); + } + } + return results; + }; + scopesToReturn = filterByQuery(scopesToReturn); + } + + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + apiVersion: 'scope.grafana.app/v0alpha1', + kind: 'FindScopeNodeChildrenResults', + metadata: {}, + items: scopesToReturn.map((scope) => ({ + kind: 'ScopeNode', + apiVersion: 'scope.grafana.app/v0alpha1', + metadata: { + name: scope.name, + namespace: 'default', + }, + spec: { + title: scope.title, + description: scope.title, + disableMultiSelect: scope.disableMultiSelect ?? false, + nodeType: scope.children ? 'container' : 'leaf', + ...(parentParam && { parentName: parentParam }), + ...((scope.addLinks || scope.children) && { + linkType: 'scope', + linkId: `scope-${scope.name}`, + }), + ...(scope.redirectPath && { redirectPath: scope.redirectPath }), + }, + })), + }), + }); + }); + + // Route for individual scope fetching + await page.route(`**/apis/scope.grafana.app/v0alpha1/namespaces/*/scopes/*`, async (route) => { + const url = route.request().url(); + const scopeName = url.split('/scopes/')[1]?.split('?')[0]; + + // Find the scope in the test data + const findScope = (items: TestScope[]): TestScope | undefined => { + for (const item of items) { + if (`scope-${item.name}` === scopeName) { + return item; + } + if (item.children) { + const found = findScope(item.children); + if (found) { + return found; + } + } + } + return undefined; + }; + + const scope = findScope(scopes); + + if (scope) { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + kind: 'Scope', + apiVersion: 'scope.grafana.app/v0alpha1', + metadata: { + name: `scope-${scope.name}`, + namespace: 'default', + }, + spec: { + title: scope.title, + description: '', + filters: scope.filters, + category: scope.category, + type: scope.type, + }, + }), + }); + } else { + await route.fulfill({ status: 404 }); + } + }); + + // Note: Dashboard bindings and navigations routes are set up dynamically in applyScopes() + // with scope-specific URL patterns to avoid cache issues. They are not set up here. +} export type TestScope = { name: string; @@ -24,6 +167,9 @@ export type TestScope = { type ScopeDashboardBinding = Resource; +/** + * Sets up a route for scope node children requests and waits for the response. + */ export async function scopeNodeChildrenRequest( page: Page, scopes: TestScope[], @@ -68,10 +214,13 @@ export async function scopeNodeChildrenRequest( return page.waitForResponse((response) => response.url().includes(`/find/scope_node_children`)); } +/** + * Opens the scopes selector dropdown and waits for the tree to load. + */ export async function openScopesSelector(page: Page, scopes?: TestScope[]) { const click = async () => await page.getByTestId('scopes-selector-input').click(); - if (!scopes) { + if (!scopes || USE_LIVE_DATA) { await click(); return; } @@ -82,10 +231,13 @@ export async function openScopesSelector(page: Page, scopes?: TestScope[]) { await responsePromise; } +/** + * Expands a scope tree node and waits for children to load. + */ export async function expandScopesSelection(page: Page, parentScope: string, scopes?: TestScope[]) { const click = async () => await page.getByTestId(`scopes-tree-${parentScope}-expand`).click(); - if (!scopes) { + if (!scopes || USE_LIVE_DATA) { await click(); return; } @@ -96,6 +248,9 @@ export async function expandScopesSelection(page: Page, parentScope: string, sco await responsePromise; } +/** + * Sets up a route for individual scope requests and waits for the response. + */ export async function scopeSelectRequest(page: Page, selectedScope: TestScope): Promise { await page.route( `**/apis/scope.grafana.app/v0alpha1/namespaces/*/scopes/scope-${selectedScope.name}`, @@ -125,6 +280,9 @@ export async function scopeSelectRequest(page: Page, selectedScope: TestScope): return page.waitForResponse((response) => response.url().includes(`/scopes/scope-${selectedScope.name}`)); } +/** + * Selects a scope in the tree. + */ export async function selectScope(page: Page, scopeName: string, selectedScope?: TestScope) { const click = async () => { const element = page.locator( @@ -134,7 +292,7 @@ export async function selectScope(page: Page, scopeName: string, selectedScope?: await element.click({ force: true }); }; - if (!selectedScope) { + if (!selectedScope || USE_LIVE_DATA) { await click(); return; } @@ -145,14 +303,22 @@ export async function selectScope(page: Page, scopeName: string, selectedScope?: await responsePromise; } +/** + * Applies the selected scopes and waits for the selector to close and page to settle. + * Sets up routes dynamically with scope-specific URL patterns to avoid cache issues. + */ export async function applyScopes(page: Page, scopes?: TestScope[]) { const click = async () => { await page.getByTestId('scopes-selector-apply').scrollIntoViewIfNeeded(); await page.getByTestId('scopes-selector-apply').click({ force: true }); }; - if (!scopes) { + if (!scopes || USE_LIVE_DATA) { await click(); + // Wait for the apply button to disappear (selector closed) + await page.waitForSelector('[data-testid="scopes-selector-apply"]', { state: 'hidden', timeout: 5000 }); + // Wait for any resulting API calls (dashboard bindings, etc.) to complete + await page.waitForLoadState('networkidle'); return; } @@ -166,7 +332,7 @@ export async function applyScopes(page: Page, scopes?: TestScope[]) { const groups: string[] = ['Most relevant', 'Dashboards', 'Something else', '']; - // Mock scope_dashboard_bindings endpoint + // Mock scope_dashboard_bindings endpoint with scope-specific URL pattern await page.route(dashboardBindingsUrl, async (route) => { await route.fulfill({ status: 200, @@ -220,7 +386,7 @@ export async function applyScopes(page: Page, scopes?: TestScope[]) { }); }); - // Mock scope_navigations endpoint + // Mock scope_navigations endpoint with scope-specific URL pattern await page.route(scopeNavigationsUrl, async (route) => { await route.fulfill({ status: 200, @@ -266,21 +432,23 @@ export async function applyScopes(page: Page, scopes?: TestScope[]) { (response) => response.url().includes(`/find/scope_dashboard_bindings`) || response.url().includes(`/find/scope_navigations`) ); - const scopeRequestPromises: Array> = []; - - for (const scope of scopes) { - scopeRequestPromises.push(scopeSelectRequest(page, scope)); - } await click(); await responsePromise; - await Promise.all(scopeRequestPromises); + // Wait for the apply button to disappear (selector closed) + await page.waitForSelector('[data-testid="scopes-selector-apply"]', { state: 'hidden', timeout: 5000 }); + // Wait for any resulting API calls to complete + await page.waitForLoadState('networkidle'); } -export async function searchScopes(page: Page, value: string, resultScopes: TestScope[]) { +/** + * Searches for scopes in the tree and waits for results. + * Sets up a route dynamically with filtered results to return only matching scopes. + */ +export async function searchScopes(page: Page, value: string, resultScopes?: TestScope[]) { const click = async () => await page.getByTestId('scopes-tree-search').fill(value); - if (!resultScopes) { + if (!resultScopes || USE_LIVE_DATA) { await click(); return; } diff --git a/packages/grafana-api-clients/src/clients/rtkq/createBaseQuery.ts b/packages/grafana-api-clients/src/clients/rtkq/createBaseQuery.ts index 477e139faac..c6216cc13b5 100644 --- a/packages/grafana-api-clients/src/clients/rtkq/createBaseQuery.ts +++ b/packages/grafana-api-clients/src/clients/rtkq/createBaseQuery.ts @@ -34,6 +34,8 @@ export function createBaseQuery({ baseURL }: CreateBaseQueryOptions): BaseQueryF getBackendSrv().fetch({ ...requestOptions, url: baseURL + requestOptions.url, + // Default to GET so backend_srv correctly skips success alerts for queries + method: requestOptions.method ?? 'GET', showErrorAlert: requestOptions.showErrorAlert ?? false, data: requestOptions.body, headers, diff --git a/packages/grafana-test-utils/src/fixtures/scopes.ts b/packages/grafana-test-utils/src/fixtures/scopes.ts new file mode 100644 index 00000000000..1d7c6ee0143 --- /dev/null +++ b/packages/grafana-test-utils/src/fixtures/scopes.ts @@ -0,0 +1,500 @@ +/** + * Types for Scopes API - matching @grafana/data types + */ + +export interface ScopeFilter { + key: string; + value: string; + operator: 'equals' | 'not-equals' | 'regex-match' | 'regex-not-match'; +} + +export interface ScopeSpec { + title: string; + filters: ScopeFilter[]; +} + +export interface Scope { + metadata: { + name: string; + }; + spec: ScopeSpec; +} + +export interface ScopeNodeSpec { + nodeType: 'container' | 'leaf'; + title: string; + description?: string; + disableMultiSelect?: boolean; + linkType?: 'scope'; + linkId?: string; + parentName: string; +} + +export interface ScopeNode { + metadata: { + name: string; + }; + spec: ScopeNodeSpec; +} + +export interface ScopeDashboardBindingSpec { + dashboard: string; + scope: string; +} + +export interface ScopeDashboardBindingStatus { + dashboardTitle: string; + groups?: string[]; +} + +export interface ScopeDashboardBinding { + metadata: { + name: string; + }; + spec: ScopeDashboardBindingSpec; + status: ScopeDashboardBindingStatus; +} + +export interface ScopeNavigation { + metadata: { + name: string; + }; + spec: { + url: string; + scope: string; + subScope?: string; + preLoadSubScopeChildren?: boolean; + expandOnLoad?: boolean; + disableSubScopeSelection?: boolean; + }; + status: { + title: string; + groups?: string[]; + }; +} + +export const MOCK_SCOPES: Scope[] = [ + { + metadata: { name: 'cloud' }, + spec: { + title: 'Cloud', + filters: [{ key: 'cloud', value: '.*', operator: 'regex-match' }], + }, + }, + { + metadata: { name: 'dev' }, + spec: { + title: 'Dev', + filters: [{ key: 'cloud', value: 'dev', operator: 'equals' }], + }, + }, + { + metadata: { name: 'ops' }, + spec: { + title: 'Ops', + filters: [{ key: 'cloud', value: 'ops', operator: 'equals' }], + }, + }, + { + metadata: { name: 'prod' }, + spec: { + title: 'Prod', + filters: [{ key: 'cloud', value: 'prod', operator: 'equals' }], + }, + }, + { + metadata: { name: 'grafana' }, + spec: { + title: 'Grafana', + filters: [{ key: 'app', value: 'grafana', operator: 'equals' }], + }, + }, + { + metadata: { name: 'mimir' }, + spec: { + title: 'Mimir', + filters: [{ key: 'app', value: 'mimir', operator: 'equals' }], + }, + }, + { + metadata: { name: 'loki' }, + spec: { + title: 'Loki', + filters: [{ key: 'app', value: 'loki', operator: 'equals' }], + }, + }, + { + metadata: { name: 'tempo' }, + spec: { + title: 'Tempo', + filters: [{ key: 'app', value: 'tempo', operator: 'equals' }], + }, + }, + { + metadata: { name: 'dev-env' }, + spec: { + title: 'Development', + filters: [{ key: 'environment', value: 'dev', operator: 'equals' }], + }, + }, + { + metadata: { name: 'prod-env' }, + spec: { + title: 'Production', + filters: [{ key: 'environment', value: 'prod', operator: 'equals' }], + }, + }, +]; + +const dashboardBindingsGenerator = ( + scopes: string[], + dashboards: Array<{ dashboardTitle: string; dashboardKey?: string; groups?: string[] }> +) => + scopes.reduce((scopeAcc, scopeTitle) => { + const scope = scopeTitle.toLowerCase().replaceAll(' ', '-').replaceAll('/', '-'); + + return [ + ...scopeAcc, + ...dashboards.reduce((acc, { dashboardTitle, groups, dashboardKey }, idx) => { + dashboardKey = dashboardKey ?? dashboardTitle.toLowerCase().replaceAll(' ', '-').replaceAll('/', '-'); + const group = !groups + ? '' + : groups.length === 1 + ? groups[0] === '' + ? '' + : `${groups[0].toLowerCase().replaceAll(' ', '-').replaceAll('/', '-')}-` + : `multiple${idx}-`; + const dashboard = `${group}${dashboardKey}`; + + return [ + ...acc, + { + metadata: { name: `${scope}-${dashboard}` }, + spec: { + dashboard, + scope, + }, + status: { + dashboardTitle, + groups, + }, + }, + ]; + }, []), + ]; + }, []); + +export const MOCK_SCOPE_DASHBOARD_BINDINGS: ScopeDashboardBinding[] = [ + ...dashboardBindingsGenerator( + ['Grafana'], + [ + { dashboardTitle: 'Data Sources', groups: ['General'] }, + { dashboardTitle: 'Usage', groups: ['General'] }, + { dashboardTitle: 'Frontend Errors', groups: ['Observability'] }, + { dashboardTitle: 'Frontend Logs', groups: ['Observability'] }, + { dashboardTitle: 'Backend Errors', groups: ['Observability'] }, + { dashboardTitle: 'Backend Logs', groups: ['Observability'] }, + { dashboardTitle: 'Usage Overview', groups: ['Usage'] }, + { dashboardTitle: 'Data Sources', groups: ['Usage'] }, + { dashboardTitle: 'Stats', groups: ['Usage'] }, + { dashboardTitle: 'Overview', groups: [''] }, + { dashboardTitle: 'Frontend' }, + { dashboardTitle: 'Stats' }, + ] + ), + ...dashboardBindingsGenerator( + ['Loki', 'Tempo', 'Mimir'], + [ + { dashboardTitle: 'Ingester', groups: ['Components', 'Investigations'] }, + { dashboardTitle: 'Distributor', groups: ['Components', 'Investigations'] }, + { dashboardTitle: 'Compacter', groups: ['Components', 'Investigations'] }, + { dashboardTitle: 'Datasource Errors', groups: ['Observability', 'Investigations'] }, + { dashboardTitle: 'Datasource Logs', groups: ['Observability', 'Investigations'] }, + { dashboardTitle: 'Overview' }, + { dashboardTitle: 'Stats', dashboardKey: 'another-stats' }, + ] + ), + ...dashboardBindingsGenerator( + ['Dev', 'Ops', 'Prod'], + [ + { dashboardTitle: 'Overview', groups: ['Cardinality Management'] }, + { dashboardTitle: 'Metrics', groups: ['Cardinality Management'] }, + { dashboardTitle: 'Labels', groups: ['Cardinality Management'] }, + { dashboardTitle: 'Overview', groups: ['Usage Insights'] }, + { dashboardTitle: 'Data Sources', groups: ['Usage Insights'] }, + { dashboardTitle: 'Query Errors', groups: ['Usage Insights'] }, + { dashboardTitle: 'Alertmanager', groups: ['Usage Insights'] }, + { dashboardTitle: 'Metrics Ingestion', groups: ['Usage Insights'] }, + { dashboardTitle: 'Billing/Usage' }, + ] + ), +]; + +export const MOCK_NODES: ScopeNode[] = [ + { + metadata: { name: 'applications' }, + spec: { + nodeType: 'container', + title: 'Applications', + description: 'Application Scopes', + parentName: '', + }, + }, + { + metadata: { name: 'cloud' }, + spec: { + nodeType: 'container', + title: 'Cloud', + description: 'Cloud Scopes', + disableMultiSelect: true, + linkType: 'scope', + linkId: 'cloud', + parentName: '', + }, + }, + { + metadata: { name: 'applications-grafana' }, + spec: { + nodeType: 'leaf', + title: 'Grafana', + description: 'Grafana', + linkType: 'scope', + linkId: 'grafana', + parentName: 'applications', + }, + }, + { + metadata: { name: 'applications-mimir' }, + spec: { + nodeType: 'leaf', + title: 'Mimir', + description: 'Mimir', + linkType: 'scope', + linkId: 'mimir', + parentName: 'applications', + }, + }, + { + metadata: { name: 'applications-loki' }, + spec: { + nodeType: 'leaf', + title: 'Loki', + description: 'Loki', + linkType: 'scope', + linkId: 'loki', + parentName: 'applications', + }, + }, + { + metadata: { name: 'applications-tempo' }, + spec: { + nodeType: 'leaf', + title: 'Tempo', + description: 'Tempo', + linkType: 'scope', + linkId: 'tempo', + parentName: 'applications', + }, + }, + { + metadata: { name: 'applications-cloud' }, + spec: { + nodeType: 'container', + title: 'Cloud', + description: 'Application/Cloud Scopes', + linkType: 'scope', + linkId: 'cloud', + parentName: 'applications', + }, + }, + { + metadata: { name: 'applications-cloud-dev' }, + spec: { + nodeType: 'leaf', + title: 'Dev', + description: 'Dev', + linkType: 'scope', + linkId: 'dev', + parentName: 'applications-cloud', + }, + }, + { + metadata: { name: 'applications-cloud-ops' }, + spec: { + nodeType: 'leaf', + title: 'Ops', + description: 'Ops', + linkType: 'scope', + linkId: 'ops', + parentName: 'applications-cloud', + }, + }, + { + metadata: { name: 'applications-cloud-prod' }, + spec: { + nodeType: 'leaf', + title: 'Prod', + description: 'Prod', + linkType: 'scope', + linkId: 'prod', + parentName: 'applications-cloud', + }, + }, + { + metadata: { name: 'cloud-dev' }, + spec: { + nodeType: 'leaf', + title: 'Dev', + description: 'Dev', + linkType: 'scope', + linkId: 'dev', + parentName: 'cloud', + }, + }, + { + metadata: { name: 'cloud-ops' }, + spec: { + nodeType: 'leaf', + title: 'Ops', + description: 'Ops', + linkType: 'scope', + linkId: 'ops', + parentName: 'cloud', + }, + }, + { + metadata: { name: 'cloud-prod' }, + spec: { + nodeType: 'leaf', + title: 'Prod', + description: 'Prod', + linkType: 'scope', + linkId: 'prod', + parentName: 'cloud', + }, + }, + { + metadata: { name: 'cloud-applications' }, + spec: { + nodeType: 'container', + title: 'Applications', + description: 'Cloud/Application Scopes', + parentName: 'cloud', + }, + }, + { + metadata: { name: 'cloud-applications-grafana' }, + spec: { + nodeType: 'leaf', + title: 'Grafana', + description: 'Grafana', + linkType: 'scope', + linkId: 'grafana', + parentName: 'cloud-applications', + }, + }, + { + metadata: { name: 'cloud-applications-mimir' }, + spec: { + nodeType: 'leaf', + title: 'Mimir', + description: 'Mimir', + linkType: 'scope', + linkId: 'mimir', + parentName: 'cloud-applications', + }, + }, + { + metadata: { name: 'cloud-applications-loki' }, + spec: { + nodeType: 'leaf', + title: 'Loki', + description: 'Loki', + linkType: 'scope', + linkId: 'loki', + parentName: 'cloud-applications', + }, + }, + { + metadata: { name: 'cloud-applications-tempo' }, + spec: { + nodeType: 'leaf', + title: 'Tempo', + description: 'Tempo', + linkType: 'scope', + linkId: 'tempo', + parentName: 'cloud-applications', + }, + }, + { + metadata: { name: 'environments' }, + spec: { + nodeType: 'container', + title: 'Environments', + description: 'Environment Scopes', + disableMultiSelect: true, + parentName: '', + }, + }, + { + metadata: { name: 'environments-dev' }, + spec: { + nodeType: 'container', + title: 'Development', + description: 'Development Environment', + linkType: 'scope', + linkId: 'dev-env', + parentName: 'environments', + }, + }, + { + metadata: { name: 'environments-prod' }, + spec: { + nodeType: 'container', + title: 'Production', + description: 'Production Environment', + linkType: 'scope', + linkId: 'prod-env', + parentName: 'environments', + }, + }, +]; + +export const MOCK_SUB_SCOPE_MIMIR_ITEMS: ScopeNavigation[] = [ + { + metadata: { name: 'mimir-item-1' }, + spec: { + scope: 'mimir', + url: '/d/mimir-dashboard-1', + }, + status: { + title: 'Mimir Dashboard 1', + groups: ['General'], + }, + }, + { + metadata: { name: 'mimir-item-2' }, + spec: { + scope: 'mimir', + url: '/d/mimir-dashboard-2', + }, + status: { + title: 'Mimir Dashboard 2', + groups: ['Observability'], + }, + }, +]; + +export const MOCK_SUB_SCOPE_LOKI_ITEMS: ScopeNavigation[] = [ + { + metadata: { name: 'loki-item-1' }, + spec: { + scope: 'loki', + url: '/d/loki-dashboard-1', + }, + status: { + title: 'Loki Dashboard 1', + groups: ['General'], + }, + }, +]; diff --git a/packages/grafana-test-utils/src/handlers/all-handlers.ts b/packages/grafana-test-utils/src/handlers/all-handlers.ts index 5fa473b55d5..83a34d7455f 100644 --- a/packages/grafana-test-utils/src/handlers/all-handlers.ts +++ b/packages/grafana-test-utils/src/handlers/all-handlers.ts @@ -12,6 +12,7 @@ import appPlatformDashboardv0alpha1Handlers from './apis/dashboard.grafana.app/v import appPlatformDashboardv1beta1Handlers from './apis/dashboard.grafana.app/v1beta1/handlers'; import appPlatformFolderv1beta1Handlers from './apis/folder.grafana.app/v1beta1/handlers'; import appPlatformIamv0alpha1Handlers from './apis/iam.grafana.app/v0alpha1/handlers'; +import appPlatformScopev0alpha1Handlers from './apis/scope.grafana.app/v0alpha1/handlers'; const allHandlers: HttpHandler[] = [ // Legacy handlers @@ -29,6 +30,7 @@ const allHandlers: HttpHandler[] = [ ...appPlatformFolderv1beta1Handlers, ...appPlatformIamv0alpha1Handlers, ...appPlatformCollectionsv1alpha1Handlers, + ...appPlatformScopev0alpha1Handlers, ]; export default allHandlers; diff --git a/packages/grafana-test-utils/src/handlers/apis/scope.grafana.app/v0alpha1/handlers.ts b/packages/grafana-test-utils/src/handlers/apis/scope.grafana.app/v0alpha1/handlers.ts new file mode 100644 index 00000000000..098548caad7 --- /dev/null +++ b/packages/grafana-test-utils/src/handlers/apis/scope.grafana.app/v0alpha1/handlers.ts @@ -0,0 +1,131 @@ +import { HttpResponse, http } from 'msw'; + +import { + MOCK_NODES, + MOCK_SCOPES, + MOCK_SCOPE_DASHBOARD_BINDINGS, + MOCK_SUB_SCOPE_LOKI_ITEMS, + MOCK_SUB_SCOPE_MIMIR_ITEMS, + ScopeNavigation, +} from '../../../../fixtures/scopes'; +import { getErrorResponse } from '../../../helpers'; + +const API_BASE = '/apis/scope.grafana.app/v0alpha1/namespaces/:namespace'; + +/** + * GET /apis/scope.grafana.app/v0alpha1/namespaces/:namespace/scopes/:name + * + * Fetches a single scope by name. + */ +const getScopeHandler = () => + http.get<{ namespace: string; name: string }>(`${API_BASE}/scopes/:name`, ({ params }) => { + const { name } = params; + const scope = MOCK_SCOPES.find((s) => s.metadata.name === name); + + if (!scope) { + return HttpResponse.json(getErrorResponse(`scopes.scope.grafana.app "${name}" not found`, 404), { + status: 404, + }); + } + + return HttpResponse.json(scope); + }); + +/** + * GET /apis/scope.grafana.app/v0alpha1/namespaces/:namespace/scopenodes/:name + * + * Fetches a single scope node by name. + */ +const getScopeNodeHandler = () => + http.get<{ namespace: string; name: string }>(`${API_BASE}/scopenodes/:name`, ({ params }) => { + const { name } = params; + const node = MOCK_NODES.find((n) => n.metadata.name === name); + + if (!node) { + return HttpResponse.json(getErrorResponse(`scopenodes.scope.grafana.app "${name}" not found`, 404), { + status: 404, + }); + } + + return HttpResponse.json(node); + }); + +/** + * GET /apis/scope.grafana.app/v0alpha1/namespaces/:namespace/find/scope_node_children + * + * Finds scope node children based on parent and query filters. + */ +const findScopeNodeChildrenHandler = () => + http.get(`${API_BASE}/find/scope_node_children`, ({ request }) => { + const url = new URL(request.url); + const parent = url.searchParams.get('parent') ?? ''; + const query = url.searchParams.get('query') ?? ''; + const limitParam = url.searchParams.get('limit'); + const names = url.searchParams.getAll('names'); + + let filtered = MOCK_NODES.filter( + (node) => node.spec.parentName === parent && node.spec.title.toLowerCase().includes(query.toLowerCase()) + ); + + if (names.length > 0) { + filtered = MOCK_NODES.filter((node) => names.includes(node.metadata.name)); + } + + if (limitParam) { + const limit = parseInt(limitParam, 10); + filtered = filtered.slice(0, limit); + } + + return HttpResponse.json({ + items: filtered, + }); + }); + +/** + * GET /apis/scope.grafana.app/v0alpha1/namespaces/:namespace/find/scope_dashboard_bindings + * + * Finds scope dashboard bindings for the given scope names. + */ +const findScopeDashboardBindingsHandler = () => + http.get(`${API_BASE}/find/scope_dashboard_bindings`, ({ request }) => { + const url = new URL(request.url); + const scopeNames = url.searchParams.getAll('scope'); + + const bindings = MOCK_SCOPE_DASHBOARD_BINDINGS.filter((b) => scopeNames.includes(b.spec.scope)); + + return HttpResponse.json({ + items: bindings, + }); + }); + +/** + * GET /apis/scope.grafana.app/v0alpha1/namespaces/:namespace/find/scope_navigations + * + * Finds scope navigations for the given scope names. + */ +const findScopeNavigationsHandler = () => + http.get(`${API_BASE}/find/scope_navigations`, ({ request }) => { + const url = new URL(request.url); + const scopeNames = url.searchParams.getAll('scope'); + + let items: ScopeNavigation[] = []; + + if (scopeNames.includes('mimir')) { + items = [...items, ...MOCK_SUB_SCOPE_MIMIR_ITEMS]; + } + if (scopeNames.includes('loki')) { + items = [...items, ...MOCK_SUB_SCOPE_LOKI_ITEMS]; + } + + return HttpResponse.json({ + items, + }); + }); + +export default [ + getScopeHandler(), + getScopeNodeHandler(), + findScopeNodeChildrenHandler(), + findScopeDashboardBindingsHandler(), + findScopeNavigationsHandler(), +]; diff --git a/packages/grafana-test-utils/src/unstable.ts b/packages/grafana-test-utils/src/unstable.ts index d03bc685d9e..698d57a774c 100644 --- a/packages/grafana-test-utils/src/unstable.ts +++ b/packages/grafana-test-utils/src/unstable.ts @@ -2,3 +2,12 @@ import { wellFormedTree } from './fixtures/folders'; export const getFolderFixtures = wellFormedTree; export { MOCK_TEAMS, MOCK_TEAM_GROUPS } from './fixtures/teams'; +export { + MOCK_SCOPES, + MOCK_NODES, + MOCK_SCOPE_DASHBOARD_BINDINGS, + MOCK_SUB_SCOPE_MIMIR_ITEMS, + MOCK_SUB_SCOPE_LOKI_ITEMS, +} from './fixtures/scopes'; +export { default as allHandlers } from './handlers/all-handlers'; +export { default as scopeHandlers } from './handlers/apis/scope.grafana.app/v0alpha1/handlers'; diff --git a/public/app/api/clients/scope/v0alpha1/baseAPI.ts b/public/app/api/clients/scope/v0alpha1/baseAPI.ts new file mode 100644 index 00000000000..bdec3014c1e --- /dev/null +++ b/public/app/api/clients/scope/v0alpha1/baseAPI.ts @@ -0,0 +1,16 @@ +import { createApi } from '@reduxjs/toolkit/query/react'; + +import { getAPIBaseURL } from '@grafana/api-clients'; +import { createBaseQuery } from '@grafana/api-clients/rtkq'; + +export const API_GROUP = 'scope.grafana.app' as const; +export const API_VERSION = 'v0alpha1' as const; +export const BASE_URL = getAPIBaseURL(API_GROUP, API_VERSION); + +export const api = createApi({ + reducerPath: 'scopeAPIv0alpha1', + baseQuery: createBaseQuery({ + baseURL: BASE_URL, + }), + endpoints: () => ({}), +}); diff --git a/public/app/api/clients/scope/v0alpha1/endpoints.gen.ts b/public/app/api/clients/scope/v0alpha1/endpoints.gen.ts new file mode 100644 index 00000000000..0bd43fc2b05 --- /dev/null +++ b/public/app/api/clients/scope/v0alpha1/endpoints.gen.ts @@ -0,0 +1,1727 @@ +import { api } from './baseAPI'; +export const addTagTypes = [ + 'API Discovery', + 'FindScopeDashboardBindingsResults', + 'FindScopeNavigationsResults', + 'FindScopeNodeChildrenResults', + 'ScopeDashboardBinding', + 'ScopeNavigation', + 'ScopeNode', + 'Scope', +] as const; +const injectedRtkApi = api + .enhanceEndpoints({ + addTagTypes, + }) + .injectEndpoints({ + endpoints: (build) => ({ + getApiResources: build.query({ + query: () => ({ url: `/` }), + providesTags: ['API Discovery'], + }), + getFindScopeDashboardBindingsResults: build.query< + GetFindScopeDashboardBindingsResultsApiResponse, + GetFindScopeDashboardBindingsResultsApiArg + >({ + query: (queryArg) => ({ + url: `/find/scope_dashboard_bindings`, + params: { + scope: queryArg.scope, + }, + }), + providesTags: ['FindScopeDashboardBindingsResults'], + }), + getFindScopeNavigationsResults: build.query< + GetFindScopeNavigationsResultsApiResponse, + GetFindScopeNavigationsResultsApiArg + >({ + query: (queryArg) => ({ + url: `/find/scope_navigations`, + params: { + scope: queryArg.scope, + }, + }), + providesTags: ['FindScopeNavigationsResults'], + }), + getFindScopeNodeChildrenResults: build.query< + GetFindScopeNodeChildrenResultsApiResponse, + GetFindScopeNodeChildrenResultsApiArg + >({ + query: (queryArg) => ({ + url: `/find/scope_node_children`, + params: { + parent: queryArg.parent, + query: queryArg.query, + names: queryArg.names, + limit: queryArg.limit, + }, + }), + providesTags: ['FindScopeNodeChildrenResults'], + }), + listScopeDashboardBinding: build.query({ + query: (queryArg) => ({ + url: `/scopedashboardbindings`, + params: { + pretty: queryArg.pretty, + allowWatchBookmarks: queryArg.allowWatchBookmarks, + continue: queryArg['continue'], + fieldSelector: queryArg.fieldSelector, + labelSelector: queryArg.labelSelector, + limit: queryArg.limit, + resourceVersion: queryArg.resourceVersion, + resourceVersionMatch: queryArg.resourceVersionMatch, + sendInitialEvents: queryArg.sendInitialEvents, + timeoutSeconds: queryArg.timeoutSeconds, + watch: queryArg.watch, + }, + }), + providesTags: ['ScopeDashboardBinding'], + }), + createScopeDashboardBinding: build.mutation< + CreateScopeDashboardBindingApiResponse, + CreateScopeDashboardBindingApiArg + >({ + query: (queryArg) => ({ + url: `/scopedashboardbindings`, + method: 'POST', + body: queryArg.scopeDashboardBinding, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + }, + }), + invalidatesTags: ['ScopeDashboardBinding'], + }), + deletecollectionScopeDashboardBinding: build.mutation< + DeletecollectionScopeDashboardBindingApiResponse, + DeletecollectionScopeDashboardBindingApiArg + >({ + query: (queryArg) => ({ + url: `/scopedashboardbindings`, + method: 'DELETE', + params: { + pretty: queryArg.pretty, + continue: queryArg['continue'], + dryRun: queryArg.dryRun, + fieldSelector: queryArg.fieldSelector, + gracePeriodSeconds: queryArg.gracePeriodSeconds, + ignoreStoreReadErrorWithClusterBreakingPotential: queryArg.ignoreStoreReadErrorWithClusterBreakingPotential, + labelSelector: queryArg.labelSelector, + limit: queryArg.limit, + orphanDependents: queryArg.orphanDependents, + propagationPolicy: queryArg.propagationPolicy, + resourceVersion: queryArg.resourceVersion, + resourceVersionMatch: queryArg.resourceVersionMatch, + sendInitialEvents: queryArg.sendInitialEvents, + timeoutSeconds: queryArg.timeoutSeconds, + }, + }), + invalidatesTags: ['ScopeDashboardBinding'], + }), + getScopeDashboardBinding: build.query({ + query: (queryArg) => ({ + url: `/scopedashboardbindings/${queryArg.name}`, + params: { + pretty: queryArg.pretty, + }, + }), + providesTags: ['ScopeDashboardBinding'], + }), + replaceScopeDashboardBinding: build.mutation< + ReplaceScopeDashboardBindingApiResponse, + ReplaceScopeDashboardBindingApiArg + >({ + query: (queryArg) => ({ + url: `/scopedashboardbindings/${queryArg.name}`, + method: 'PUT', + body: queryArg.scopeDashboardBinding, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + }, + }), + invalidatesTags: ['ScopeDashboardBinding'], + }), + deleteScopeDashboardBinding: build.mutation< + DeleteScopeDashboardBindingApiResponse, + DeleteScopeDashboardBindingApiArg + >({ + query: (queryArg) => ({ + url: `/scopedashboardbindings/${queryArg.name}`, + method: 'DELETE', + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + gracePeriodSeconds: queryArg.gracePeriodSeconds, + ignoreStoreReadErrorWithClusterBreakingPotential: queryArg.ignoreStoreReadErrorWithClusterBreakingPotential, + orphanDependents: queryArg.orphanDependents, + propagationPolicy: queryArg.propagationPolicy, + }, + }), + invalidatesTags: ['ScopeDashboardBinding'], + }), + updateScopeDashboardBinding: build.mutation< + UpdateScopeDashboardBindingApiResponse, + UpdateScopeDashboardBindingApiArg + >({ + query: (queryArg) => ({ + url: `/scopedashboardbindings/${queryArg.name}`, + method: 'PATCH', + body: queryArg.patch, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + force: queryArg.force, + }, + }), + invalidatesTags: ['ScopeDashboardBinding'], + }), + getScopeDashboardBindingStatus: build.query< + GetScopeDashboardBindingStatusApiResponse, + GetScopeDashboardBindingStatusApiArg + >({ + query: (queryArg) => ({ + url: `/scopedashboardbindings/${queryArg.name}/status`, + params: { + pretty: queryArg.pretty, + }, + }), + providesTags: ['ScopeDashboardBinding'], + }), + replaceScopeDashboardBindingStatus: build.mutation< + ReplaceScopeDashboardBindingStatusApiResponse, + ReplaceScopeDashboardBindingStatusApiArg + >({ + query: (queryArg) => ({ + url: `/scopedashboardbindings/${queryArg.name}/status`, + method: 'PUT', + body: queryArg.scopeDashboardBinding, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + }, + }), + invalidatesTags: ['ScopeDashboardBinding'], + }), + updateScopeDashboardBindingStatus: build.mutation< + UpdateScopeDashboardBindingStatusApiResponse, + UpdateScopeDashboardBindingStatusApiArg + >({ + query: (queryArg) => ({ + url: `/scopedashboardbindings/${queryArg.name}/status`, + method: 'PATCH', + body: queryArg.patch, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + force: queryArg.force, + }, + }), + invalidatesTags: ['ScopeDashboardBinding'], + }), + listScopeNavigation: build.query({ + query: (queryArg) => ({ + url: `/scopenavigations`, + params: { + pretty: queryArg.pretty, + allowWatchBookmarks: queryArg.allowWatchBookmarks, + continue: queryArg['continue'], + fieldSelector: queryArg.fieldSelector, + labelSelector: queryArg.labelSelector, + limit: queryArg.limit, + resourceVersion: queryArg.resourceVersion, + resourceVersionMatch: queryArg.resourceVersionMatch, + sendInitialEvents: queryArg.sendInitialEvents, + timeoutSeconds: queryArg.timeoutSeconds, + watch: queryArg.watch, + }, + }), + providesTags: ['ScopeNavigation'], + }), + createScopeNavigation: build.mutation({ + query: (queryArg) => ({ + url: `/scopenavigations`, + method: 'POST', + body: queryArg.scopeNavigation, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + }, + }), + invalidatesTags: ['ScopeNavigation'], + }), + deletecollectionScopeNavigation: build.mutation< + DeletecollectionScopeNavigationApiResponse, + DeletecollectionScopeNavigationApiArg + >({ + query: (queryArg) => ({ + url: `/scopenavigations`, + method: 'DELETE', + params: { + pretty: queryArg.pretty, + continue: queryArg['continue'], + dryRun: queryArg.dryRun, + fieldSelector: queryArg.fieldSelector, + gracePeriodSeconds: queryArg.gracePeriodSeconds, + ignoreStoreReadErrorWithClusterBreakingPotential: queryArg.ignoreStoreReadErrorWithClusterBreakingPotential, + labelSelector: queryArg.labelSelector, + limit: queryArg.limit, + orphanDependents: queryArg.orphanDependents, + propagationPolicy: queryArg.propagationPolicy, + resourceVersion: queryArg.resourceVersion, + resourceVersionMatch: queryArg.resourceVersionMatch, + sendInitialEvents: queryArg.sendInitialEvents, + timeoutSeconds: queryArg.timeoutSeconds, + }, + }), + invalidatesTags: ['ScopeNavigation'], + }), + getScopeNavigation: build.query({ + query: (queryArg) => ({ + url: `/scopenavigations/${queryArg.name}`, + params: { + pretty: queryArg.pretty, + }, + }), + providesTags: ['ScopeNavigation'], + }), + replaceScopeNavigation: build.mutation({ + query: (queryArg) => ({ + url: `/scopenavigations/${queryArg.name}`, + method: 'PUT', + body: queryArg.scopeNavigation, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + }, + }), + invalidatesTags: ['ScopeNavigation'], + }), + deleteScopeNavigation: build.mutation({ + query: (queryArg) => ({ + url: `/scopenavigations/${queryArg.name}`, + method: 'DELETE', + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + gracePeriodSeconds: queryArg.gracePeriodSeconds, + ignoreStoreReadErrorWithClusterBreakingPotential: queryArg.ignoreStoreReadErrorWithClusterBreakingPotential, + orphanDependents: queryArg.orphanDependents, + propagationPolicy: queryArg.propagationPolicy, + }, + }), + invalidatesTags: ['ScopeNavigation'], + }), + updateScopeNavigation: build.mutation({ + query: (queryArg) => ({ + url: `/scopenavigations/${queryArg.name}`, + method: 'PATCH', + body: queryArg.patch, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + force: queryArg.force, + }, + }), + invalidatesTags: ['ScopeNavigation'], + }), + getScopeNavigationStatus: build.query({ + query: (queryArg) => ({ + url: `/scopenavigations/${queryArg.name}/status`, + params: { + pretty: queryArg.pretty, + }, + }), + providesTags: ['ScopeNavigation'], + }), + replaceScopeNavigationStatus: build.mutation< + ReplaceScopeNavigationStatusApiResponse, + ReplaceScopeNavigationStatusApiArg + >({ + query: (queryArg) => ({ + url: `/scopenavigations/${queryArg.name}/status`, + method: 'PUT', + body: queryArg.scopeNavigation, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + }, + }), + invalidatesTags: ['ScopeNavigation'], + }), + updateScopeNavigationStatus: build.mutation< + UpdateScopeNavigationStatusApiResponse, + UpdateScopeNavigationStatusApiArg + >({ + query: (queryArg) => ({ + url: `/scopenavigations/${queryArg.name}/status`, + method: 'PATCH', + body: queryArg.patch, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + force: queryArg.force, + }, + }), + invalidatesTags: ['ScopeNavigation'], + }), + listScopeNode: build.query({ + query: (queryArg) => ({ + url: `/scopenodes`, + params: { + pretty: queryArg.pretty, + allowWatchBookmarks: queryArg.allowWatchBookmarks, + continue: queryArg['continue'], + fieldSelector: queryArg.fieldSelector, + labelSelector: queryArg.labelSelector, + limit: queryArg.limit, + resourceVersion: queryArg.resourceVersion, + resourceVersionMatch: queryArg.resourceVersionMatch, + sendInitialEvents: queryArg.sendInitialEvents, + timeoutSeconds: queryArg.timeoutSeconds, + watch: queryArg.watch, + }, + }), + providesTags: ['ScopeNode'], + }), + createScopeNode: build.mutation({ + query: (queryArg) => ({ + url: `/scopenodes`, + method: 'POST', + body: queryArg.scopeNode, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + }, + }), + invalidatesTags: ['ScopeNode'], + }), + deletecollectionScopeNode: build.mutation({ + query: (queryArg) => ({ + url: `/scopenodes`, + method: 'DELETE', + params: { + pretty: queryArg.pretty, + continue: queryArg['continue'], + dryRun: queryArg.dryRun, + fieldSelector: queryArg.fieldSelector, + gracePeriodSeconds: queryArg.gracePeriodSeconds, + ignoreStoreReadErrorWithClusterBreakingPotential: queryArg.ignoreStoreReadErrorWithClusterBreakingPotential, + labelSelector: queryArg.labelSelector, + limit: queryArg.limit, + orphanDependents: queryArg.orphanDependents, + propagationPolicy: queryArg.propagationPolicy, + resourceVersion: queryArg.resourceVersion, + resourceVersionMatch: queryArg.resourceVersionMatch, + sendInitialEvents: queryArg.sendInitialEvents, + timeoutSeconds: queryArg.timeoutSeconds, + }, + }), + invalidatesTags: ['ScopeNode'], + }), + getScopeNode: build.query({ + query: (queryArg) => ({ + url: `/scopenodes/${queryArg.name}`, + params: { + pretty: queryArg.pretty, + }, + }), + providesTags: ['ScopeNode'], + }), + replaceScopeNode: build.mutation({ + query: (queryArg) => ({ + url: `/scopenodes/${queryArg.name}`, + method: 'PUT', + body: queryArg.scopeNode, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + }, + }), + invalidatesTags: ['ScopeNode'], + }), + deleteScopeNode: build.mutation({ + query: (queryArg) => ({ + url: `/scopenodes/${queryArg.name}`, + method: 'DELETE', + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + gracePeriodSeconds: queryArg.gracePeriodSeconds, + ignoreStoreReadErrorWithClusterBreakingPotential: queryArg.ignoreStoreReadErrorWithClusterBreakingPotential, + orphanDependents: queryArg.orphanDependents, + propagationPolicy: queryArg.propagationPolicy, + }, + }), + invalidatesTags: ['ScopeNode'], + }), + updateScopeNode: build.mutation({ + query: (queryArg) => ({ + url: `/scopenodes/${queryArg.name}`, + method: 'PATCH', + body: queryArg.patch, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + force: queryArg.force, + }, + }), + invalidatesTags: ['ScopeNode'], + }), + listScope: build.query({ + query: (queryArg) => ({ + url: `/scopes`, + params: { + pretty: queryArg.pretty, + allowWatchBookmarks: queryArg.allowWatchBookmarks, + continue: queryArg['continue'], + fieldSelector: queryArg.fieldSelector, + labelSelector: queryArg.labelSelector, + limit: queryArg.limit, + resourceVersion: queryArg.resourceVersion, + resourceVersionMatch: queryArg.resourceVersionMatch, + sendInitialEvents: queryArg.sendInitialEvents, + timeoutSeconds: queryArg.timeoutSeconds, + watch: queryArg.watch, + }, + }), + providesTags: ['Scope'], + }), + createScope: build.mutation({ + query: (queryArg) => ({ + url: `/scopes`, + method: 'POST', + body: queryArg.scope, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + }, + }), + invalidatesTags: ['Scope'], + }), + deletecollectionScope: build.mutation({ + query: (queryArg) => ({ + url: `/scopes`, + method: 'DELETE', + params: { + pretty: queryArg.pretty, + continue: queryArg['continue'], + dryRun: queryArg.dryRun, + fieldSelector: queryArg.fieldSelector, + gracePeriodSeconds: queryArg.gracePeriodSeconds, + ignoreStoreReadErrorWithClusterBreakingPotential: queryArg.ignoreStoreReadErrorWithClusterBreakingPotential, + labelSelector: queryArg.labelSelector, + limit: queryArg.limit, + orphanDependents: queryArg.orphanDependents, + propagationPolicy: queryArg.propagationPolicy, + resourceVersion: queryArg.resourceVersion, + resourceVersionMatch: queryArg.resourceVersionMatch, + sendInitialEvents: queryArg.sendInitialEvents, + timeoutSeconds: queryArg.timeoutSeconds, + }, + }), + invalidatesTags: ['Scope'], + }), + getScope: build.query({ + query: (queryArg) => ({ + url: `/scopes/${queryArg.name}`, + params: { + pretty: queryArg.pretty, + }, + }), + providesTags: ['Scope'], + }), + replaceScope: build.mutation({ + query: (queryArg) => ({ + url: `/scopes/${queryArg.name}`, + method: 'PUT', + body: queryArg.scope, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + }, + }), + invalidatesTags: ['Scope'], + }), + deleteScope: build.mutation({ + query: (queryArg) => ({ + url: `/scopes/${queryArg.name}`, + method: 'DELETE', + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + gracePeriodSeconds: queryArg.gracePeriodSeconds, + ignoreStoreReadErrorWithClusterBreakingPotential: queryArg.ignoreStoreReadErrorWithClusterBreakingPotential, + orphanDependents: queryArg.orphanDependents, + propagationPolicy: queryArg.propagationPolicy, + }, + }), + invalidatesTags: ['Scope'], + }), + updateScope: build.mutation({ + query: (queryArg) => ({ + url: `/scopes/${queryArg.name}`, + method: 'PATCH', + body: queryArg.patch, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + force: queryArg.force, + }, + }), + invalidatesTags: ['Scope'], + }), + }), + overrideExisting: false, + }); +export { injectedRtkApi as generatedAPI }; +export type GetApiResourcesApiResponse = /** status 200 OK */ ApiResourceList; +export type GetApiResourcesApiArg = void; +export type GetFindScopeDashboardBindingsResultsApiResponse = /** status 200 OK */ FindScopeDashboardBindingsResults; +export type GetFindScopeDashboardBindingsResultsApiArg = { + /** name of the FindScopeDashboardBindingsResults */ + name: string; + /** A scope name (id) to match against, this parameter may be repeated */ + scope?: string[]; +}; +export type GetFindScopeNavigationsResultsApiResponse = /** status 200 OK */ FindScopeNavigationsResults; +export type GetFindScopeNavigationsResultsApiArg = { + /** name of the FindScopeNavigationsResults */ + name: string; + /** A scope name (id) to match against, this parameter may be repeated */ + scope?: string[]; +}; +export type GetFindScopeNodeChildrenResultsApiResponse = /** status 200 OK */ FindScopeNodeChildrenResults; +export type GetFindScopeNodeChildrenResultsApiArg = { + /** The parent scope node */ + parent?: string; + query?: string; + names?: string[]; + limit?: number; +}; +export type ListScopeDashboardBindingApiResponse = /** status 200 OK */ ScopeDashboardBindingList; +export type ListScopeDashboardBindingApiArg = { + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. */ + allowWatchBookmarks?: boolean; + /** The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". + + This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. */ + continue?: string; + /** A selector to restrict the list of returned objects by their fields. Defaults to everything. */ + fieldSelector?: string; + /** A selector to restrict the list of returned objects by their labels. Defaults to everything. */ + labelSelector?: string; + /** limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. + + The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. */ + limit?: number; + /** resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. + + Defaults to unset */ + resourceVersion?: string; + /** resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. + + Defaults to unset */ + resourceVersionMatch?: string; + /** `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic "Bookmark" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `"k8s.io/initial-events-end": "true"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. + + When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan + is interpreted as "data at least as new as the provided `resourceVersion`" + and the bookmark event is send when the state is synced + to a `resourceVersion` at least as fresh as the one provided by the ListOptions. + If `resourceVersion` is unset, this is interpreted as "consistent read" and the + bookmark event is send when the state is synced at least to the moment + when request started being processed. + - `resourceVersionMatch` set to any other value or unset + Invalid error is returned. + + Defaults to true if `resourceVersion=""` or `resourceVersion="0"` (for backward compatibility reasons) and to false otherwise. */ + sendInitialEvents?: boolean; + /** Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. */ + timeoutSeconds?: number; + /** Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. */ + watch?: boolean; +}; +export type CreateScopeDashboardBindingApiResponse = /** status 200 OK */ + | ScopeDashboardBinding + | /** status 201 Created */ ScopeDashboardBinding + | /** status 202 Accepted */ ScopeDashboardBinding; +export type CreateScopeDashboardBindingApiArg = { + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + scopeDashboardBinding: ScopeDashboardBinding; +}; +export type DeletecollectionScopeDashboardBindingApiResponse = /** status 200 OK */ Status; +export type DeletecollectionScopeDashboardBindingApiArg = { + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". + + This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. */ + continue?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** A selector to restrict the list of returned objects by their fields. Defaults to everything. */ + fieldSelector?: string; + /** The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. */ + gracePeriodSeconds?: number; + /** if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it */ + ignoreStoreReadErrorWithClusterBreakingPotential?: boolean; + /** A selector to restrict the list of returned objects by their labels. Defaults to everything. */ + labelSelector?: string; + /** limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. + + The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. */ + limit?: number; + /** Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. */ + orphanDependents?: boolean; + /** Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. */ + propagationPolicy?: string; + /** resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. + + Defaults to unset */ + resourceVersion?: string; + /** resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. + + Defaults to unset */ + resourceVersionMatch?: string; + /** `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic "Bookmark" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `"k8s.io/initial-events-end": "true"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. + + When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan + is interpreted as "data at least as new as the provided `resourceVersion`" + and the bookmark event is send when the state is synced + to a `resourceVersion` at least as fresh as the one provided by the ListOptions. + If `resourceVersion` is unset, this is interpreted as "consistent read" and the + bookmark event is send when the state is synced at least to the moment + when request started being processed. + - `resourceVersionMatch` set to any other value or unset + Invalid error is returned. + + Defaults to true if `resourceVersion=""` or `resourceVersion="0"` (for backward compatibility reasons) and to false otherwise. */ + sendInitialEvents?: boolean; + /** Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. */ + timeoutSeconds?: number; +}; +export type GetScopeDashboardBindingApiResponse = /** status 200 OK */ ScopeDashboardBinding; +export type GetScopeDashboardBindingApiArg = { + /** name of the ScopeDashboardBinding */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; +}; +export type ReplaceScopeDashboardBindingApiResponse = /** status 200 OK */ + | ScopeDashboardBinding + | /** status 201 Created */ ScopeDashboardBinding; +export type ReplaceScopeDashboardBindingApiArg = { + /** name of the ScopeDashboardBinding */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + scopeDashboardBinding: ScopeDashboardBinding; +}; +export type DeleteScopeDashboardBindingApiResponse = /** status 200 OK */ Status | /** status 202 Accepted */ Status; +export type DeleteScopeDashboardBindingApiArg = { + /** name of the ScopeDashboardBinding */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. */ + gracePeriodSeconds?: number; + /** if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it */ + ignoreStoreReadErrorWithClusterBreakingPotential?: boolean; + /** Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. */ + orphanDependents?: boolean; + /** Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. */ + propagationPolicy?: string; +}; +export type UpdateScopeDashboardBindingApiResponse = /** status 200 OK */ + | ScopeDashboardBinding + | /** status 201 Created */ ScopeDashboardBinding; +export type UpdateScopeDashboardBindingApiArg = { + /** name of the ScopeDashboardBinding */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + /** Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. */ + force?: boolean; + patch: Patch; +}; +export type GetScopeDashboardBindingStatusApiResponse = /** status 200 OK */ ScopeDashboardBinding; +export type GetScopeDashboardBindingStatusApiArg = { + /** name of the ScopeDashboardBinding */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; +}; +export type ReplaceScopeDashboardBindingStatusApiResponse = /** status 200 OK */ + | ScopeDashboardBinding + | /** status 201 Created */ ScopeDashboardBinding; +export type ReplaceScopeDashboardBindingStatusApiArg = { + /** name of the ScopeDashboardBinding */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + scopeDashboardBinding: ScopeDashboardBinding; +}; +export type UpdateScopeDashboardBindingStatusApiResponse = /** status 200 OK */ + | ScopeDashboardBinding + | /** status 201 Created */ ScopeDashboardBinding; +export type UpdateScopeDashboardBindingStatusApiArg = { + /** name of the ScopeDashboardBinding */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + /** Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. */ + force?: boolean; + patch: Patch; +}; +export type ListScopeNavigationApiResponse = /** status 200 OK */ ScopeNavigationList; +export type ListScopeNavigationApiArg = { + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. */ + allowWatchBookmarks?: boolean; + /** The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". + + This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. */ + continue?: string; + /** A selector to restrict the list of returned objects by their fields. Defaults to everything. */ + fieldSelector?: string; + /** A selector to restrict the list of returned objects by their labels. Defaults to everything. */ + labelSelector?: string; + /** limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. + + The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. */ + limit?: number; + /** resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. + + Defaults to unset */ + resourceVersion?: string; + /** resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. + + Defaults to unset */ + resourceVersionMatch?: string; + /** `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic "Bookmark" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `"k8s.io/initial-events-end": "true"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. + + When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan + is interpreted as "data at least as new as the provided `resourceVersion`" + and the bookmark event is send when the state is synced + to a `resourceVersion` at least as fresh as the one provided by the ListOptions. + If `resourceVersion` is unset, this is interpreted as "consistent read" and the + bookmark event is send when the state is synced at least to the moment + when request started being processed. + - `resourceVersionMatch` set to any other value or unset + Invalid error is returned. + + Defaults to true if `resourceVersion=""` or `resourceVersion="0"` (for backward compatibility reasons) and to false otherwise. */ + sendInitialEvents?: boolean; + /** Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. */ + timeoutSeconds?: number; + /** Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. */ + watch?: boolean; +}; +export type CreateScopeNavigationApiResponse = /** status 200 OK */ + | ScopeNavigation + | /** status 201 Created */ ScopeNavigation + | /** status 202 Accepted */ ScopeNavigation; +export type CreateScopeNavigationApiArg = { + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + scopeNavigation: ScopeNavigation; +}; +export type DeletecollectionScopeNavigationApiResponse = /** status 200 OK */ Status; +export type DeletecollectionScopeNavigationApiArg = { + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". + + This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. */ + continue?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** A selector to restrict the list of returned objects by their fields. Defaults to everything. */ + fieldSelector?: string; + /** The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. */ + gracePeriodSeconds?: number; + /** if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it */ + ignoreStoreReadErrorWithClusterBreakingPotential?: boolean; + /** A selector to restrict the list of returned objects by their labels. Defaults to everything. */ + labelSelector?: string; + /** limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. + + The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. */ + limit?: number; + /** Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. */ + orphanDependents?: boolean; + /** Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. */ + propagationPolicy?: string; + /** resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. + + Defaults to unset */ + resourceVersion?: string; + /** resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. + + Defaults to unset */ + resourceVersionMatch?: string; + /** `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic "Bookmark" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `"k8s.io/initial-events-end": "true"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. + + When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan + is interpreted as "data at least as new as the provided `resourceVersion`" + and the bookmark event is send when the state is synced + to a `resourceVersion` at least as fresh as the one provided by the ListOptions. + If `resourceVersion` is unset, this is interpreted as "consistent read" and the + bookmark event is send when the state is synced at least to the moment + when request started being processed. + - `resourceVersionMatch` set to any other value or unset + Invalid error is returned. + + Defaults to true if `resourceVersion=""` or `resourceVersion="0"` (for backward compatibility reasons) and to false otherwise. */ + sendInitialEvents?: boolean; + /** Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. */ + timeoutSeconds?: number; +}; +export type GetScopeNavigationApiResponse = /** status 200 OK */ ScopeNavigation; +export type GetScopeNavigationApiArg = { + /** name of the ScopeNavigation */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; +}; +export type ReplaceScopeNavigationApiResponse = /** status 200 OK */ + | ScopeNavigation + | /** status 201 Created */ ScopeNavigation; +export type ReplaceScopeNavigationApiArg = { + /** name of the ScopeNavigation */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + scopeNavigation: ScopeNavigation; +}; +export type DeleteScopeNavigationApiResponse = /** status 200 OK */ Status | /** status 202 Accepted */ Status; +export type DeleteScopeNavigationApiArg = { + /** name of the ScopeNavigation */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. */ + gracePeriodSeconds?: number; + /** if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it */ + ignoreStoreReadErrorWithClusterBreakingPotential?: boolean; + /** Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. */ + orphanDependents?: boolean; + /** Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. */ + propagationPolicy?: string; +}; +export type UpdateScopeNavigationApiResponse = /** status 200 OK */ + | ScopeNavigation + | /** status 201 Created */ ScopeNavigation; +export type UpdateScopeNavigationApiArg = { + /** name of the ScopeNavigation */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + /** Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. */ + force?: boolean; + patch: Patch; +}; +export type GetScopeNavigationStatusApiResponse = /** status 200 OK */ ScopeNavigation; +export type GetScopeNavigationStatusApiArg = { + /** name of the ScopeNavigation */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; +}; +export type ReplaceScopeNavigationStatusApiResponse = /** status 200 OK */ + | ScopeNavigation + | /** status 201 Created */ ScopeNavigation; +export type ReplaceScopeNavigationStatusApiArg = { + /** name of the ScopeNavigation */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + scopeNavigation: ScopeNavigation; +}; +export type UpdateScopeNavigationStatusApiResponse = /** status 200 OK */ + | ScopeNavigation + | /** status 201 Created */ ScopeNavigation; +export type UpdateScopeNavigationStatusApiArg = { + /** name of the ScopeNavigation */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + /** Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. */ + force?: boolean; + patch: Patch; +}; +export type ListScopeNodeApiResponse = /** status 200 OK */ ScopeNodeList; +export type ListScopeNodeApiArg = { + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. */ + allowWatchBookmarks?: boolean; + /** The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". + + This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. */ + continue?: string; + /** A selector to restrict the list of returned objects by their fields. Defaults to everything. */ + fieldSelector?: string; + /** A selector to restrict the list of returned objects by their labels. Defaults to everything. */ + labelSelector?: string; + /** limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. + + The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. */ + limit?: number; + /** resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. + + Defaults to unset */ + resourceVersion?: string; + /** resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. + + Defaults to unset */ + resourceVersionMatch?: string; + /** `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic "Bookmark" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `"k8s.io/initial-events-end": "true"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. + + When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan + is interpreted as "data at least as new as the provided `resourceVersion`" + and the bookmark event is send when the state is synced + to a `resourceVersion` at least as fresh as the one provided by the ListOptions. + If `resourceVersion` is unset, this is interpreted as "consistent read" and the + bookmark event is send when the state is synced at least to the moment + when request started being processed. + - `resourceVersionMatch` set to any other value or unset + Invalid error is returned. + + Defaults to true if `resourceVersion=""` or `resourceVersion="0"` (for backward compatibility reasons) and to false otherwise. */ + sendInitialEvents?: boolean; + /** Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. */ + timeoutSeconds?: number; + /** Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. */ + watch?: boolean; +}; +export type CreateScopeNodeApiResponse = /** status 200 OK */ + | ScopeNode + | /** status 201 Created */ ScopeNode + | /** status 202 Accepted */ ScopeNode; +export type CreateScopeNodeApiArg = { + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + scopeNode: ScopeNode; +}; +export type DeletecollectionScopeNodeApiResponse = /** status 200 OK */ Status; +export type DeletecollectionScopeNodeApiArg = { + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". + + This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. */ + continue?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** A selector to restrict the list of returned objects by their fields. Defaults to everything. */ + fieldSelector?: string; + /** The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. */ + gracePeriodSeconds?: number; + /** if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it */ + ignoreStoreReadErrorWithClusterBreakingPotential?: boolean; + /** A selector to restrict the list of returned objects by their labels. Defaults to everything. */ + labelSelector?: string; + /** limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. + + The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. */ + limit?: number; + /** Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. */ + orphanDependents?: boolean; + /** Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. */ + propagationPolicy?: string; + /** resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. + + Defaults to unset */ + resourceVersion?: string; + /** resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. + + Defaults to unset */ + resourceVersionMatch?: string; + /** `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic "Bookmark" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `"k8s.io/initial-events-end": "true"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. + + When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan + is interpreted as "data at least as new as the provided `resourceVersion`" + and the bookmark event is send when the state is synced + to a `resourceVersion` at least as fresh as the one provided by the ListOptions. + If `resourceVersion` is unset, this is interpreted as "consistent read" and the + bookmark event is send when the state is synced at least to the moment + when request started being processed. + - `resourceVersionMatch` set to any other value or unset + Invalid error is returned. + + Defaults to true if `resourceVersion=""` or `resourceVersion="0"` (for backward compatibility reasons) and to false otherwise. */ + sendInitialEvents?: boolean; + /** Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. */ + timeoutSeconds?: number; +}; +export type GetScopeNodeApiResponse = /** status 200 OK */ ScopeNode; +export type GetScopeNodeApiArg = { + /** name of the ScopeNode */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; +}; +export type ReplaceScopeNodeApiResponse = /** status 200 OK */ ScopeNode | /** status 201 Created */ ScopeNode; +export type ReplaceScopeNodeApiArg = { + /** name of the ScopeNode */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + scopeNode: ScopeNode; +}; +export type DeleteScopeNodeApiResponse = /** status 200 OK */ Status | /** status 202 Accepted */ Status; +export type DeleteScopeNodeApiArg = { + /** name of the ScopeNode */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. */ + gracePeriodSeconds?: number; + /** if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it */ + ignoreStoreReadErrorWithClusterBreakingPotential?: boolean; + /** Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. */ + orphanDependents?: boolean; + /** Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. */ + propagationPolicy?: string; +}; +export type UpdateScopeNodeApiResponse = /** status 200 OK */ ScopeNode | /** status 201 Created */ ScopeNode; +export type UpdateScopeNodeApiArg = { + /** name of the ScopeNode */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + /** Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. */ + force?: boolean; + patch: Patch; +}; +export type ListScopeApiResponse = /** status 200 OK */ ScopeList; +export type ListScopeApiArg = { + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. */ + allowWatchBookmarks?: boolean; + /** The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". + + This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. */ + continue?: string; + /** A selector to restrict the list of returned objects by their fields. Defaults to everything. */ + fieldSelector?: string; + /** A selector to restrict the list of returned objects by their labels. Defaults to everything. */ + labelSelector?: string; + /** limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. + + The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. */ + limit?: number; + /** resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. + + Defaults to unset */ + resourceVersion?: string; + /** resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. + + Defaults to unset */ + resourceVersionMatch?: string; + /** `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic "Bookmark" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `"k8s.io/initial-events-end": "true"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. + + When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan + is interpreted as "data at least as new as the provided `resourceVersion`" + and the bookmark event is send when the state is synced + to a `resourceVersion` at least as fresh as the one provided by the ListOptions. + If `resourceVersion` is unset, this is interpreted as "consistent read" and the + bookmark event is send when the state is synced at least to the moment + when request started being processed. + - `resourceVersionMatch` set to any other value or unset + Invalid error is returned. + + Defaults to true if `resourceVersion=""` or `resourceVersion="0"` (for backward compatibility reasons) and to false otherwise. */ + sendInitialEvents?: boolean; + /** Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. */ + timeoutSeconds?: number; + /** Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. */ + watch?: boolean; +}; +export type CreateScopeApiResponse = /** status 200 OK */ + | Scope + | /** status 201 Created */ Scope + | /** status 202 Accepted */ Scope; +export type CreateScopeApiArg = { + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + scope: Scope; +}; +export type DeletecollectionScopeApiResponse = /** status 200 OK */ Status; +export type DeletecollectionScopeApiArg = { + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". + + This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. */ + continue?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** A selector to restrict the list of returned objects by their fields. Defaults to everything. */ + fieldSelector?: string; + /** The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. */ + gracePeriodSeconds?: number; + /** if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it */ + ignoreStoreReadErrorWithClusterBreakingPotential?: boolean; + /** A selector to restrict the list of returned objects by their labels. Defaults to everything. */ + labelSelector?: string; + /** limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. + + The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. */ + limit?: number; + /** Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. */ + orphanDependents?: boolean; + /** Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. */ + propagationPolicy?: string; + /** resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. + + Defaults to unset */ + resourceVersion?: string; + /** resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. + + Defaults to unset */ + resourceVersionMatch?: string; + /** `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic "Bookmark" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `"k8s.io/initial-events-end": "true"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. + + When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan + is interpreted as "data at least as new as the provided `resourceVersion`" + and the bookmark event is send when the state is synced + to a `resourceVersion` at least as fresh as the one provided by the ListOptions. + If `resourceVersion` is unset, this is interpreted as "consistent read" and the + bookmark event is send when the state is synced at least to the moment + when request started being processed. + - `resourceVersionMatch` set to any other value or unset + Invalid error is returned. + + Defaults to true if `resourceVersion=""` or `resourceVersion="0"` (for backward compatibility reasons) and to false otherwise. */ + sendInitialEvents?: boolean; + /** Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. */ + timeoutSeconds?: number; +}; +export type GetScopeApiResponse = /** status 200 OK */ Scope; +export type GetScopeApiArg = { + /** name of the Scope */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; +}; +export type ReplaceScopeApiResponse = /** status 200 OK */ Scope | /** status 201 Created */ Scope; +export type ReplaceScopeApiArg = { + /** name of the Scope */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + scope: Scope; +}; +export type DeleteScopeApiResponse = /** status 200 OK */ Status | /** status 202 Accepted */ Status; +export type DeleteScopeApiArg = { + /** name of the Scope */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. */ + gracePeriodSeconds?: number; + /** if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it */ + ignoreStoreReadErrorWithClusterBreakingPotential?: boolean; + /** Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. */ + orphanDependents?: boolean; + /** Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. */ + propagationPolicy?: string; +}; +export type UpdateScopeApiResponse = /** status 200 OK */ Scope | /** status 201 Created */ Scope; +export type UpdateScopeApiArg = { + /** name of the Scope */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + /** Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. */ + force?: boolean; + patch: Patch; +}; +export type ApiResource = { + /** categories is a list of the grouped resources this resource belongs to (e.g. 'all') */ + categories?: string[]; + /** group is the preferred group of the resource. Empty implies the group of the containing resource list. For subresources, this may have a different value, for example: Scale". */ + group?: string; + /** kind is the kind for the resource (e.g. 'Foo' is the kind for a resource 'foo') */ + kind: string; + /** name is the plural name of the resource. */ + name: string; + /** namespaced indicates if a resource is namespaced or not. */ + namespaced: boolean; + /** shortNames is a list of suggested short names of the resource. */ + shortNames?: string[]; + /** singularName is the singular name of the resource. This allows clients to handle plural and singular opaquely. The singularName is more correct for reporting status on a single item and both singular and plural are allowed from the kubectl CLI interface. */ + singularName: string; + /** The hash value of the storage version, the version this resource is converted to when written to the data store. Value must be treated as opaque by clients. Only equality comparison on the value is valid. This is an alpha feature and may change or be removed in the future. The field is populated by the apiserver only if the StorageVersionHash feature gate is enabled. This field will remain optional even if it graduates. */ + storageVersionHash?: string; + /** verbs is a list of supported kube verbs (this includes get, list, watch, create, update, patch, delete, deletecollection, and proxy) */ + verbs: string[]; + /** version is the preferred version of the resource. Empty implies the version of the containing resource list For subresources, this may have a different value, for example: v1 (while inside a v1beta1 version of the core resource's group)". */ + version?: string; +}; +export type ApiResourceList = { + /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ + apiVersion?: string; + /** groupVersion is the group and version this APIResourceList is for. */ + groupVersion: string; + /** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ + kind?: string; + /** resources contains the name of the resources and if they are namespaced. */ + resources: ApiResource[]; +}; +export type Time = string; +export type FieldsV1 = object; +export type ManagedFieldsEntry = { + /** APIVersion defines the version of this resource that this field set applies to. The format is "group/version" just like the top-level APIVersion field. It is necessary to track the version of a field set because it cannot be automatically converted. */ + apiVersion?: string; + /** FieldsType is the discriminator for the different fields format and version. There is currently only one possible value: "FieldsV1" */ + fieldsType?: string; + /** FieldsV1 holds the first JSON version format as described in the "FieldsV1" type. */ + fieldsV1?: FieldsV1; + /** Manager is an identifier of the workflow managing these fields. */ + manager?: string; + /** Operation is the type of operation which lead to this ManagedFieldsEntry being created. The only valid values for this field are 'Apply' and 'Update'. */ + operation?: string; + /** Subresource is the name of the subresource used to update that object, or empty string if the object was updated through the main resource. The value of this field is used to distinguish between managers, even if they share the same name. For example, a status update will be distinct from a regular update using the same manager name. Note that the APIVersion field is not related to the Subresource field and it always corresponds to the version of the main resource. */ + subresource?: string; + /** Time is the timestamp of when the ManagedFields entry was added. The timestamp will also be updated if a field is added, the manager changes any of the owned fields value or removes a field. The timestamp does not update when a field is removed from the entry because another manager took it over. */ + time?: Time; +}; +export type OwnerReference = { + /** API version of the referent. */ + apiVersion: string; + /** If true, AND if the owner has the "foregroundDeletion" finalizer, then the owner cannot be deleted from the key-value store until this reference is removed. See https://kubernetes.io/docs/concepts/architecture/garbage-collection/#foreground-deletion for how the garbage collector interacts with this field and enforces the foreground deletion. Defaults to false. To set this field, a user needs "delete" permission of the owner, otherwise 422 (Unprocessable Entity) will be returned. */ + blockOwnerDeletion?: boolean; + /** If true, this reference points to the managing controller. */ + controller?: boolean; + /** Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ + kind: string; + /** Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names */ + name: string; + /** UID of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids */ + uid: string; +}; +export type ObjectMeta = { + /** Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations */ + annotations?: { + [key: string]: string; + }; + /** CreationTimestamp is a timestamp representing the server time when this object was created. It is not guaranteed to be set in happens-before order across separate operations. Clients may not set this value. It is represented in RFC3339 form and is in UTC. + + Populated by the system. Read-only. Null for lists. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata */ + creationTimestamp?: Time; + /** Number of seconds allowed for this object to gracefully terminate before it will be removed from the system. Only set when deletionTimestamp is also set. May only be shortened. Read-only. */ + deletionGracePeriodSeconds?: number; + /** DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This field is set by the server when a graceful deletion is requested by the user, and is not directly settable by a client. The resource is expected to be deleted (no longer visible from resource lists, and not reachable by name) after the time in this field, once the finalizers list is empty. As long as the finalizers list contains items, deletion is blocked. Once the deletionTimestamp is set, this value may not be unset or be set further into the future, although it may be shortened or the resource may be deleted prior to this time. For example, a user may request that a pod is deleted in 30 seconds. The Kubelet will react by sending a graceful termination signal to the containers in the pod. After that 30 seconds, the Kubelet will send a hard termination signal (SIGKILL) to the container and after cleanup, remove the pod from the API. In the presence of network partitions, this object may still exist after this timestamp, until an administrator or automated process can determine the resource is fully terminated. If not set, graceful deletion of the object has not been requested. + + Populated by the system when a graceful deletion is requested. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata */ + deletionTimestamp?: Time; + /** Must be empty before the object is deleted from the registry. Each entry is an identifier for the responsible component that will remove the entry from the list. If the deletionTimestamp of the object is non-nil, entries in this list can only be removed. Finalizers may be processed and removed in any order. Order is NOT enforced because it introduces significant risk of stuck finalizers. finalizers is a shared field, any actor with permission can reorder it. If the finalizer list is processed in order, then this can lead to a situation in which the component responsible for the first finalizer in the list is waiting for a signal (field value, external system, or other) produced by a component responsible for a finalizer later in the list, resulting in a deadlock. Without enforced ordering finalizers are free to order amongst themselves and are not vulnerable to ordering changes in the list. */ + finalizers?: string[]; + /** GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server. + + If this field is specified and the generated name exists, the server will return a 409. + + Applied only if Name is not specified. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency */ + generateName?: string; + /** A sequence number representing a specific generation of the desired state. Populated by the system. Read-only. */ + generation?: number; + /** Map of string keys and values that can be used to organize and categorize (scope and select) objects. May match selectors of replication controllers and services. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels */ + labels?: { + [key: string]: string; + }; + /** ManagedFields maps workflow-id and version to the set of fields that are managed by that workflow. This is mostly for internal housekeeping, and users typically shouldn't need to set or understand this field. A workflow can be the user's name, a controller's name, or the name of a specific apply path like "ci-cd". The set of fields is always in the version that the workflow used when modifying the object. */ + managedFields?: ManagedFieldsEntry[]; + /** Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names */ + name?: string; + /** Namespace defines the space within which each name must be unique. An empty namespace is equivalent to the "default" namespace, but "default" is the canonical representation. Not all objects are required to be scoped to a namespace - the value of this field for those objects will be empty. + + Must be a DNS_LABEL. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces */ + namespace?: string; + /** List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller. */ + ownerReferences?: OwnerReference[]; + /** An opaque value that represents the internal version of this object that can be used by clients to determine when objects have changed. May be used for optimistic concurrency, change detection, and the watch operation on a resource or set of resources. Clients must treat these values as opaque and passed unmodified back to the server. They may only be valid for a particular resource or set of resources. + + Populated by the system. Read-only. Value must be treated as opaque by clients and . More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency */ + resourceVersion?: string; + /** Deprecated: selfLink is a legacy read-only field that is no longer populated by the system. */ + selfLink?: string; + /** UID is the unique in time and space value for this object. It is typically generated by the server on successful creation of a resource and is not allowed to change on PUT operations. + + Populated by the system. Read-only. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids */ + uid?: string; +}; +export type ScopeDashboardBindingSpec = { + dashboard: string; + scope: string; +}; +export type Condition = { + /** lastTransitionTime is the last time the condition transitioned from one status to another. This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. */ + lastTransitionTime: Time; + /** message is a human readable message indicating details about the transition. This may be an empty string. */ + message: string; + /** observedGeneration represents the .metadata.generation that the condition was set based upon. For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date with respect to the current state of the instance. */ + observedGeneration?: number; + /** reason contains a programmatic identifier indicating the reason for the condition's last transition. Producers of specific condition types may define expected values and meanings for this field, and whether the values are considered a guaranteed API. The value should be a CamelCase string. This field may not be empty. */ + reason: string; + /** status of the condition, one of True, False, Unknown. */ + status: string; + /** type of condition in CamelCase or in foo.example.com/CamelCase. */ + type: string; +}; +export type ScopeDashboardBindingStatus = { + /** DashboardTitle should be populated and update from the dashboard */ + dashboardTitle: string; + /** DashboardTitleConditions is a list of conditions that are used to determine if the dashboard title is valid. */ + dashboardTitleConditions?: Condition[]; + /** Groups is used for the grouping of dashboards that are suggested based on a scope. The source of truth for this information has not been determined yet. */ + groups?: string[]; + /** DashboardTitleConditions is a list of conditions that are used to determine if the list of groups is valid. */ + groupsConditions?: Condition[]; +}; +export type ScopeDashboardBinding = { + /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ + apiVersion?: string; + /** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ + kind?: string; + metadata?: ObjectMeta; + spec?: ScopeDashboardBindingSpec; + status?: ScopeDashboardBindingStatus; +}; +export type FindScopeDashboardBindingsResults = { + /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ + apiVersion?: string; + items?: ScopeDashboardBinding[]; + /** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ + kind?: string; + message?: string; +}; +export type ScopeNavigationSpec = { + /** Makes the subscope not selectable, only serving as a way to build the tree. */ + disableSubScopeSelection?: boolean; + + /** Preload the subscope children, as soon as the ScopeNavigation is loaded. */ + preLoadSubScopeChildren?: boolean; + scope: string; + /** Used to navigate to a sub-scope of the main scope. URL will not be used if this is set. */ + subScope?: string; + url: string; +}; +export type ScopeNavigationStatus = { + /** Groups is used for the grouping of dashboards that are suggested based on a scope. The source of truth for this information has not been determined yet. */ + groups?: string[]; + /** GroupsConditions is a list of conditions that are used to determine if the list of groups is valid. */ + groupsConditions?: Condition[]; + /** Title should be populated and update from the dashboard */ + title: string; + /** TitleConditions is a list of conditions that are used to determine if the title is valid. */ + titleConditions?: Condition[]; +}; +export type ScopeNavigation = { + /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ + apiVersion?: string; + /** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ + kind?: string; + metadata?: ObjectMeta; + spec?: ScopeNavigationSpec; + status?: ScopeNavigationStatus; +}; +export type FindScopeNavigationsResults = { + /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ + apiVersion?: string; + items?: ScopeNavigation[]; + /** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ + kind?: string; + message?: string; +}; +export type ScopeNodeSpec = { + description?: string; + disableMultiSelect: boolean; + /** scope (later more things) */ + linkId?: string; + /** Possible enum values: + - `"scope"` */ + linkType?: 'scope'; + nodeType: string; + parentName?: string; + /** Redirect to a specific path when this node is selected. */ + redirectPath?: string; + /** Displays next to the title to provide more context. */ + subTitle?: string; + title: string; +}; +export type ScopeNode = { + /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ + apiVersion?: string; + /** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ + kind?: string; + metadata?: ObjectMeta; + spec?: ScopeNodeSpec; +}; +export type ListMeta = { + /** continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message. */ + continue?: string; + /** remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact. */ + remainingItemCount?: number; + /** String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency */ + resourceVersion?: string; + /** Deprecated: selfLink is a legacy read-only field that is no longer populated by the system. */ + selfLink?: string; +}; +export type FindScopeNodeChildrenResults = { + /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ + apiVersion?: string; + items?: ScopeNode[]; + /** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ + kind?: string; + metadata?: ListMeta; +}; +export type ScopeDashboardBindingList = { + /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ + apiVersion?: string; + items?: ScopeDashboardBinding[]; + /** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ + kind?: string; + metadata?: ListMeta; +}; +export type StatusCause = { + /** The field of the resource that has caused this error, as named by its JSON serialization. May include dot and postfix notation for nested attributes. Arrays are zero-indexed. Fields may appear more than once in an array of causes due to fields having multiple errors. Optional. + + Examples: + "name" - the field "name" on the current resource + "items[0].name" - the field "name" on the first array entry in "items" */ + field?: string; + /** A human-readable description of the cause of the error. This field may be presented as-is to a reader. */ + message?: string; + /** A machine-readable description of the cause of the error. If this value is empty there is no information available. */ + reason?: string; +}; +export type StatusDetails = { + /** The Causes array includes more details associated with the StatusReason failure. Not all StatusReasons may provide detailed causes. */ + causes?: StatusCause[]; + /** The group attribute of the resource associated with the status StatusReason. */ + group?: string; + /** The kind attribute of the resource associated with the status StatusReason. On some operations may differ from the requested resource Kind. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ + kind?: string; + /** The name attribute of the resource associated with the status StatusReason (when there is a single name which can be described). */ + name?: string; + /** If specified, the time in seconds before the operation should be retried. Some errors may indicate the client must take an alternate action - for those errors this field may indicate how long to wait before taking the alternate action. */ + retryAfterSeconds?: number; + /** UID of the resource. (when there is a single resource which can be described). More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids */ + uid?: string; +}; +export type Status = { + /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ + apiVersion?: string; + /** Suggested HTTP return code for this status, 0 if not set. */ + code?: number; + /** Extended data associated with the reason. Each reason may define its own extended details. This field is optional and the data returned is not guaranteed to conform to any schema except that defined by the reason type. */ + details?: StatusDetails; + /** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ + kind?: string; + /** A human-readable description of the status of this operation. */ + message?: string; + /** Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ + metadata?: ListMeta; + /** A machine-readable description of why this operation is in the "Failure" status. If this value is empty there is no information available. A Reason clarifies an HTTP status code but does not override it. */ + reason?: string; + /** Status of the operation. One of: "Success" or "Failure". More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status */ + status?: string; +}; +export type Patch = object; +export type ScopeNavigationList = { + /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ + apiVersion?: string; + items?: ScopeNavigation[]; + /** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ + kind?: string; + metadata?: ListMeta; +}; +export type ScopeNodeList = { + /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ + apiVersion?: string; + items?: ScopeNode[]; + /** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ + kind?: string; + metadata?: ListMeta; +}; +export type ScopeFilter = { + key: string; + /** Possible enum values: + - `"equals"` + - `"not-equals"` + - `"not-one-of"` + - `"one-of"` + - `"regex-match"` + - `"regex-not-match"` */ + operator: 'equals' | 'not-equals' | 'not-one-of' | 'one-of' | 'regex-match' | 'regex-not-match'; + value: string; + /** Values is used for operators that require multiple values (e.g. one-of and not-one-of). */ + values?: string[]; +}; +export type ScopeSpec = { + /** Provides a default path for the scope. This refers to a list of nodes in the selector. This is used to display the title next to the selected scope and expand the selector to the proper path. This will override whichever is selected from in the selector. The path is a list of node ids, starting at the direct parent of the selected node towards the root. */ + defaultPath?: string[]; + filters?: ScopeFilter[]; + title: string; +}; +export type Scope = { + /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ + apiVersion?: string; + /** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ + kind?: string; + metadata?: ObjectMeta; + spec?: ScopeSpec; +}; +export type ScopeList = { + /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ + apiVersion?: string; + items?: Scope[]; + /** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ + kind?: string; + metadata?: ListMeta; +}; diff --git a/public/app/api/clients/scope/v0alpha1/index.ts b/public/app/api/clients/scope/v0alpha1/index.ts new file mode 100644 index 00000000000..9b1365f667e --- /dev/null +++ b/public/app/api/clients/scope/v0alpha1/index.ts @@ -0,0 +1,3 @@ +import { generatedAPI } from './endpoints.gen'; + +export const scopeAPIv0alpha1 = generatedAPI; diff --git a/public/app/api/clients/scope/v0alpha1/sync-from-enterprise.sh b/public/app/api/clients/scope/v0alpha1/sync-from-enterprise.sh new file mode 100755 index 00000000000..2e5cfa2c762 --- /dev/null +++ b/public/app/api/clients/scope/v0alpha1/sync-from-enterprise.sh @@ -0,0 +1,43 @@ +#!/bin/bash +# Syncs the scope API client from Enterprise to OSS. +# +# This script: +# 1. Regenerates the Enterprise API client from the OpenAPI spec +# 2. Copies the generated endpoints.gen.ts to OSS +# +# Prerequisites: +# - The OpenAPI spec must exist at data/openapi/scope.grafana.app-v0alpha1.json +# (generated by running TestIntegrationOpenAPIs in pkg/extensions/apiserver/tests/) +# +# Usage: ./sync-from-enterprise.sh + +set -e + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +GRAFANA_ROOT="$(cd "$SCRIPT_DIR/../../../../.." && pwd)" + +# Source and destination directories for the generated API client +ENTERPRISE_SCOPE_API_DIR="$GRAFANA_ROOT/public/app/extensions/api/clients/scope/v0alpha1" +OSS_SCOPE_API_DIR="$SCRIPT_DIR" + +cd "$GRAFANA_ROOT" + +# Check if OpenAPI spec exists +if [ ! -f "data/openapi/scope.grafana.app-v0alpha1.json" ]; then + echo "Error: OpenAPI spec not found at data/openapi/scope.grafana.app-v0alpha1.json" + echo "Run TestIntegrationOpenAPIs in pkg/extensions/apiserver/tests/ to generate it." + exit 1 +fi + +echo "Step 1: Generating Enterprise API client from OpenAPI spec..." +yarn workspace @grafana/api-clients process-specs && npx rtk-query-codegen-openapi ./local/generate-enterprise-apis.ts + +if [ ! -f "$ENTERPRISE_SCOPE_API_DIR/endpoints.gen.ts" ]; then + echo "Error: Enterprise endpoints.gen.ts not found after generation" + exit 1 +fi + +echo "Step 2: Copying endpoints.gen.ts from Enterprise to OSS..." +cp "$ENTERPRISE_SCOPE_API_DIR/endpoints.gen.ts" "$OSS_SCOPE_API_DIR/endpoints.gen.ts" + +echo "Done! Scope API client synced from Enterprise." diff --git a/public/app/core/reducers/root.ts b/public/app/core/reducers/root.ts index d22835ac69e..5c817bf74cd 100644 --- a/public/app/core/reducers/root.ts +++ b/public/app/core/reducers/root.ts @@ -3,6 +3,7 @@ import { AnyAction, combineReducers } from 'redux'; import { allReducers as allApiClientReducers } from '@grafana/api-clients/rtkq'; import { generatedAPI as legacyAPI } from '@grafana/api-clients/rtkq/legacy'; +import { scopeAPIv0alpha1 } from 'app/api/clients/scope/v0alpha1'; import sharedReducers from 'app/core/reducers'; import ldapReducers from 'app/features/admin/state/reducers'; import alertingReducers from 'app/features/alerting/state/reducers'; @@ -52,6 +53,7 @@ const rootReducers = { [alertingApi.reducerPath]: alertingApi.reducer, [publicDashboardApi.reducerPath]: publicDashboardApi.reducer, [browseDashboardsAPI.reducerPath]: browseDashboardsAPI.reducer, + [scopeAPIv0alpha1.reducerPath]: scopeAPIv0alpha1.reducer, ...allApiClientReducers, }; diff --git a/public/app/features/scopes/ScopesApiClient.test.ts b/public/app/features/scopes/ScopesApiClient.test.ts index 979da40b6ce..77d9051999d 100644 --- a/public/app/features/scopes/ScopesApiClient.test.ts +++ b/public/app/features/scopes/ScopesApiClient.test.ts @@ -1,74 +1,194 @@ -import { getBackendSrv, config } from '@grafana/runtime'; +import { config } from '@grafana/runtime'; +import { MOCK_NODES, MOCK_SCOPES } from '@grafana/test-utils/unstable'; +import { scopeAPIv0alpha1 } from 'app/api/clients/scope/v0alpha1'; import { ScopesApiClient } from './ScopesApiClient'; -// Mock the runtime dependencies -jest.mock('@grafana/runtime', () => ({ - getBackendSrv: jest.fn(), - config: { - featureToggles: { - useMultipleScopeNodesEndpoint: true, - useScopeSingleNodeEndpoint: true, +// Helper to create a mock subscription with unsubscribe method +const createMockSubscription = (data: T): Promise & { unsubscribe: jest.Mock } => { + const subscription = Promise.resolve(data) as Promise & { unsubscribe: jest.Mock }; + subscription.unsubscribe = jest.fn(); + return subscription; +}; + +// Mock the RTK Query API and dispatch +jest.mock('app/api/clients/scope/v0alpha1', () => ({ + scopeAPIv0alpha1: { + endpoints: { + getScope: { + initiate: jest.fn(), + }, + getScopeNode: { + initiate: jest.fn(), + }, + getFindScopeNodeChildrenResults: { + initiate: jest.fn(), + }, + getFindScopeDashboardBindingsResults: { + initiate: jest.fn(), + }, + getFindScopeNavigationsResults: { + initiate: jest.fn(), + }, }, }, })); -jest.mock('@grafana/api-clients', () => ({ - getAPIBaseURL: jest.fn().mockReturnValue('/apis/scope.grafana.app/v0alpha1'), +jest.mock('app/store/store', () => ({ + dispatch: jest.fn((action) => action), })); describe('ScopesApiClient', () => { let apiClient: ScopesApiClient; - let mockBackendSrv: jest.Mocked<{ get: jest.Mock }>; beforeEach(() => { - mockBackendSrv = { - get: jest.fn(), - }; - (getBackendSrv as jest.Mock).mockReturnValue(mockBackendSrv); apiClient = new ScopesApiClient(); + config.featureToggles.useMultipleScopeNodesEndpoint = true; + config.featureToggles.useScopeSingleNodeEndpoint = true; + jest.clearAllMocks(); }); afterEach(() => { jest.clearAllMocks(); }); + describe('fetchScope', () => { + it('should fetch a scope by name', async () => { + // Expected: MOCK_SCOPES contains a scope with name 'grafana' + const expectedScope = MOCK_SCOPES.find((s) => s.metadata.name === 'grafana'); + expect(expectedScope).toBeDefined(); + + const mockSubscription = createMockSubscription({ data: expectedScope }); + (scopeAPIv0alpha1.endpoints.getScope.initiate as jest.Mock).mockReturnValue(mockSubscription); + + const result = await apiClient.fetchScope('grafana'); + + // Validate: result matches the expected scope from MOCK_SCOPES + expect(result).toEqual(expectedScope); + expect(scopeAPIv0alpha1.endpoints.getScope.initiate).toHaveBeenCalledWith( + { name: 'grafana' }, + { subscribe: false } + ); + }); + + it('should return undefined when scope is not found', async () => { + // Expected: No scope with this name exists in MOCK_SCOPES + const nonExistentScopeName = 'non-existent-scope'; + const errorResponse = { + kind: 'Status', + apiVersion: 'v1', + status: 'Failure', + message: `scopes.scope.grafana.app "${nonExistentScopeName}" not found`, + code: 404, + }; + const mockSubscription = createMockSubscription({ data: errorResponse }); + (scopeAPIv0alpha1.endpoints.getScope.initiate as jest.Mock).mockReturnValue(mockSubscription); + const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(); + + const result = await apiClient.fetchScope(nonExistentScopeName); + + // Validate: returns undefined for non-existent scope + expect(result).toBeUndefined(); + expect(consoleErrorSpy).toHaveBeenCalled(); + consoleErrorSpy.mockRestore(); + }); + }); + + describe('fetchMultipleScopes', () => { + it('should fetch multiple scopes in parallel', async () => { + // Expected: Both 'grafana' and 'mimir' exist in MOCK_SCOPES + const scopeNames = ['grafana', 'mimir']; + const expectedScopes = MOCK_SCOPES.filter((s) => scopeNames.includes(s.metadata.name)); + + const mockSubscriptions = expectedScopes.map((scope) => createMockSubscription({ data: scope })); + (scopeAPIv0alpha1.endpoints.getScope.initiate as jest.Mock) + .mockReturnValueOnce(mockSubscriptions[0]) + .mockReturnValueOnce(mockSubscriptions[1]); + + const result = await apiClient.fetchMultipleScopes(scopeNames); + + // Validate: returns both scopes from MOCK_SCOPES + expect(result).toHaveLength(2); + expect(result.map((s) => s.metadata.name)).toContain('grafana'); + expect(result.map((s) => s.metadata.name)).toContain('mimir'); + expect(result).toEqual(expect.arrayContaining(expectedScopes)); + }); + + it('should filter out undefined scopes when some fail', async () => { + // Expected: 'grafana' exists in MOCK_SCOPES, 'non-existent' does not + const scopeNames = ['grafana', 'non-existent']; + const expectedScope = MOCK_SCOPES.find((s) => s.metadata.name === 'grafana'); + const errorResponse = { + kind: 'Status', + apiVersion: 'v1', + status: 'Failure', + message: 'scopes.scope.grafana.app "non-existent" not found', + code: 404, + }; + + const mockSubscriptions = [ + createMockSubscription({ data: expectedScope }), + createMockSubscription({ data: errorResponse }), + ]; + (scopeAPIv0alpha1.endpoints.getScope.initiate as jest.Mock) + .mockReturnValueOnce(mockSubscriptions[0]) + .mockReturnValueOnce(mockSubscriptions[1]); + const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(); + const consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation(); + + const result = await apiClient.fetchMultipleScopes(scopeNames); + + // Validate: only returns the existing scope from MOCK_SCOPES, filters out the non-existent one + expect(result).toHaveLength(1); + expect(result[0]).toEqual(expectedScope); + expect(result[0].metadata.name).toBe('grafana'); + // Validate: console.warn is called when some scopes fail + expect(consoleWarnSpy).toHaveBeenCalled(); + consoleErrorSpy.mockRestore(); + consoleWarnSpy.mockRestore(); + }); + + it('should return empty array when no scopes provided', async () => { + const result = await apiClient.fetchMultipleScopes([]); + + // Validate: empty input returns empty array + expect(result).toEqual([]); + }); + }); + describe('fetchMultipleScopeNodes', () => { it('should fetch multiple nodes by names', async () => { - const mockNodes = [ - { - metadata: { name: 'node-1' }, - spec: { nodeType: 'container', title: 'Node 1', parentName: '' }, - }, - { - metadata: { name: 'node-2' }, - spec: { nodeType: 'leaf', title: 'Node 2', parentName: 'node-1' }, - }, - ]; + // Expected: Both nodes exist in MOCK_NODES + const nodeNames = ['applications-grafana', 'applications-mimir']; + const expectedNodes = MOCK_NODES.filter((n) => nodeNames.includes(n.metadata.name)); - mockBackendSrv.get.mockResolvedValue({ items: mockNodes }); - - const result = await apiClient.fetchMultipleScopeNodes(['node-1', 'node-2']); - - expect(mockBackendSrv.get).toHaveBeenCalledWith('/apis/scope.grafana.app/v0alpha1/find/scope_node_children', { - names: ['node-1', 'node-2'], + const mockSubscription = createMockSubscription({ + data: { items: expectedNodes }, }); - expect(result).toEqual(mockNodes); + (scopeAPIv0alpha1.endpoints.getFindScopeNodeChildrenResults.initiate as jest.Mock).mockReturnValue( + mockSubscription + ); + + const result = await apiClient.fetchMultipleScopeNodes(nodeNames); + + // Validate: returns the expected nodes from MOCK_NODES + expect(result).toHaveLength(2); + expect(result.map((n) => n.metadata.name)).toContain('applications-grafana'); + expect(result.map((n) => n.metadata.name)).toContain('applications-mimir'); + expect(result).toEqual(expect.arrayContaining(expectedNodes)); }); it('should return empty array when names array is empty', async () => { const result = await apiClient.fetchMultipleScopeNodes([]); - expect(mockBackendSrv.get).not.toHaveBeenCalled(); expect(result).toEqual([]); }); it('should return empty array when feature toggle is disabled', async () => { config.featureToggles.useMultipleScopeNodesEndpoint = false; - const result = await apiClient.fetchMultipleScopeNodes(['node-1']); + const result = await apiClient.fetchMultipleScopeNodes(['applications-grafana']); - expect(mockBackendSrv.get).not.toHaveBeenCalled(); expect(result).toEqual([]); // Restore feature toggle @@ -76,79 +196,94 @@ describe('ScopesApiClient', () => { }); it('should handle API errors gracefully', async () => { - mockBackendSrv.get.mockRejectedValue(new Error('Network error')); + // Expected: No node with this name exists in MOCK_NODES + const nonExistentNodeName = 'non-existent-node'; + const mockSubscription = createMockSubscription({ data: { items: [] } }); + (scopeAPIv0alpha1.endpoints.getFindScopeNodeChildrenResults.initiate as jest.Mock).mockReturnValue( + mockSubscription + ); + const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(); - const result = await apiClient.fetchMultipleScopeNodes(['node-1']); + const result = await apiClient.fetchMultipleScopeNodes([nonExistentNodeName]); + // Validate: returns empty array when no matches expect(result).toEqual([]); + consoleErrorSpy.mockRestore(); }); it('should handle response with no items field', async () => { - mockBackendSrv.get.mockResolvedValue({}); + // Expected: Node exists in MOCK_NODES + const nodeName = 'applications-grafana'; + const mockSubscription = createMockSubscription({ data: {} }); + (scopeAPIv0alpha1.endpoints.getFindScopeNodeChildrenResults.initiate as jest.Mock).mockReturnValue( + mockSubscription + ); - const result = await apiClient.fetchMultipleScopeNodes(['node-1']); - - expect(result).toEqual([]); - }); - - it('should handle response with null items', async () => { - mockBackendSrv.get.mockResolvedValue({ items: null }); - - const result = await apiClient.fetchMultipleScopeNodes(['node-1']); + const result = await apiClient.fetchMultipleScopeNodes([nodeName]); + // Validate: returns empty array when items field is missing expect(result).toEqual([]); }); it('should handle large arrays of node names', async () => { - const names = Array.from({ length: 100 }, (_, i) => `node-${i}`); - const mockNodes = names.map((name) => ({ - metadata: { name }, - spec: { nodeType: 'leaf', title: name, parentName: '' }, - })); + // Expected: None of these node names exist in MOCK_NODES + const nonExistentNodeNames = Array.from({ length: 10 }, (_, i) => `node-${i}`); + const mockSubscription = createMockSubscription({ data: { items: [] } }); + (scopeAPIv0alpha1.endpoints.getFindScopeNodeChildrenResults.initiate as jest.Mock).mockReturnValue( + mockSubscription + ); - mockBackendSrv.get.mockResolvedValue({ items: mockNodes }); + const result = await apiClient.fetchMultipleScopeNodes(nonExistentNodeNames); - const result = await apiClient.fetchMultipleScopeNodes(names); - - expect(result).toEqual(mockNodes); - expect(mockBackendSrv.get).toHaveBeenCalledWith('/apis/scope.grafana.app/v0alpha1/find/scope_node_children', { - names, - }); + // Validate: returns empty array when no matches + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual([]); }); it('should pass through node names exactly as provided', async () => { - const names = ['node-with-special-chars_123', 'node.with.dots', 'node-with-dashes']; - mockBackendSrv.get.mockResolvedValue({ items: [] }); + // Expected: Both nodes exist in MOCK_NODES + const nodeNames = ['applications-grafana', 'applications-mimir']; + const expectedNodes = MOCK_NODES.filter((n) => nodeNames.includes(n.metadata.name)); + const mockSubscription = createMockSubscription({ + data: { items: expectedNodes }, + }); + (scopeAPIv0alpha1.endpoints.getFindScopeNodeChildrenResults.initiate as jest.Mock).mockReturnValue( + mockSubscription + ); - await apiClient.fetchMultipleScopeNodes(names); + const result = await apiClient.fetchMultipleScopeNodes(nodeNames); - expect(mockBackendSrv.get).toHaveBeenCalledWith('/apis/scope.grafana.app/v0alpha1/find/scope_node_children', { - names, + // Validate: returns nodes matching the provided names + const resultNames = result.map((n) => n.metadata.name); + expect(resultNames).toEqual(expect.arrayContaining(nodeNames)); + // Verify we got the expected nodes from MOCK_NODES + expectedNodes.forEach((expectedNode) => { + expect(result).toContainEqual(expectedNode); }); }); }); describe('fetchScopeNode', () => { it('should fetch a single scope node by ID', async () => { - const mockNode = { - metadata: { name: 'test-node' }, - spec: { nodeType: 'leaf', title: 'Test Node', parentName: 'parent' }, - }; + // Expected: Node exists in MOCK_NODES + const nodeName = 'applications-grafana'; + const expectedNode = MOCK_NODES.find((n) => n.metadata.name === nodeName); + expect(expectedNode).toBeDefined(); - mockBackendSrv.get.mockResolvedValue(mockNode); + const mockSubscription = createMockSubscription({ data: expectedNode }); + (scopeAPIv0alpha1.endpoints.getScopeNode.initiate as jest.Mock).mockReturnValue(mockSubscription); - const result = await apiClient.fetchScopeNode('test-node'); + const result = await apiClient.fetchScopeNode(nodeName); - expect(mockBackendSrv.get).toHaveBeenCalledWith('/apis/scope.grafana.app/v0alpha1/scopenodes/test-node'); - expect(result).toEqual(mockNode); + // Validate: result matches the expected node from MOCK_NODES + expect(result).toEqual(expectedNode); }); it('should return undefined when feature toggle is disabled', async () => { config.featureToggles.useScopeSingleNodeEndpoint = false; - const result = await apiClient.fetchScopeNode('test-node'); + const result = await apiClient.fetchScopeNode('applications-grafana'); - expect(mockBackendSrv.get).not.toHaveBeenCalled(); expect(result).toBeUndefined(); // Restore feature toggle @@ -156,65 +291,95 @@ describe('ScopesApiClient', () => { }); it('should return undefined on API error', async () => { - mockBackendSrv.get.mockRejectedValue(new Error('Not found')); + // Expected: No node with this name exists in MOCK_NODES + const nonExistentNodeName = 'non-existent-node'; + const errorResponse = { + kind: 'Status', + apiVersion: 'v1', + status: 'Failure', + message: `scopenodes.scope.grafana.app "${nonExistentNodeName}" not found`, + code: 404, + }; + const mockSubscription = createMockSubscription({ data: errorResponse }); + (scopeAPIv0alpha1.endpoints.getScopeNode.initiate as jest.Mock).mockReturnValue(mockSubscription); + const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(); - const result = await apiClient.fetchScopeNode('non-existent'); + const result = await apiClient.fetchScopeNode(nonExistentNodeName); + // Validate: returns undefined for non-existent node expect(result).toBeUndefined(); + consoleErrorSpy.mockRestore(); }); }); describe('fetchNodes', () => { it('should fetch nodes with parent filter', async () => { - const mockNodes = [ - { - metadata: { name: 'child-1' }, - spec: { nodeType: 'leaf', title: 'Child 1', parentName: 'parent' }, - }, - ]; + // Expected: MOCK_NODES contains nodes with parentName 'applications' + const parentName = 'applications'; + const expectedNodes = MOCK_NODES.filter((n) => n.spec.parentName === parentName); - mockBackendSrv.get.mockResolvedValue({ items: mockNodes }); + const mockSubscription = createMockSubscription({ + data: { items: expectedNodes }, + }); + (scopeAPIv0alpha1.endpoints.getFindScopeNodeChildrenResults.initiate as jest.Mock).mockReturnValue( + mockSubscription + ); - const result = await apiClient.fetchNodes({ parent: 'parent' }); + const result = await apiClient.fetchNodes({ parent: parentName }); - expect(mockBackendSrv.get).toHaveBeenCalledWith('/apis/scope.grafana.app/v0alpha1/find/scope_node_children', { - parent: 'parent', - query: undefined, - limit: 1000, + // Validate: returns nodes with matching parentName from MOCK_NODES + expect(Array.isArray(result)).toBe(true); + expect(result.length).toBeGreaterThan(0); + result.forEach((node) => { + expect(node.spec.parentName).toBe(parentName); + }); + // Verify all returned nodes are from the expected set + result.forEach((node) => { + expect(expectedNodes).toContainEqual(node); }); - expect(result).toEqual(mockNodes); }); it('should fetch nodes with query filter', async () => { - const mockNodes = [ - { - metadata: { name: 'matching-node' }, - spec: { nodeType: 'leaf', title: 'Matching Node', parentName: '' }, - }, - ]; + // Expected: MOCK_NODES contains nodes with 'Grafana' in title (case-insensitive) + // When query is provided without parent, the API returns nodes matching the query + // In MOCK_NODES, nodes with 'Grafana' in title have parentName 'applications' or 'cloud-applications' + const query = 'Grafana'; + const expectedNodes = MOCK_NODES.filter((n) => n.spec.title.toLowerCase().includes(query.toLowerCase())); - mockBackendSrv.get.mockResolvedValue({ items: mockNodes }); + const mockSubscription = createMockSubscription({ + data: { items: expectedNodes }, + }); + (scopeAPIv0alpha1.endpoints.getFindScopeNodeChildrenResults.initiate as jest.Mock).mockReturnValue( + mockSubscription + ); - const result = await apiClient.fetchNodes({ query: 'matching' }); + const result = await apiClient.fetchNodes({ query }); - expect(mockBackendSrv.get).toHaveBeenCalledWith('/apis/scope.grafana.app/v0alpha1/find/scope_node_children', { - parent: undefined, - query: 'matching', - limit: 1000, + // Validate: returns nodes matching the query from MOCK_NODES + expect(Array.isArray(result)).toBe(true); + expect(result.length).toBeGreaterThan(0); + result.forEach((node) => { + expect(node.spec.title.toLowerCase()).toContain('grafana'); + }); + // Verify all returned nodes are from the expected set + result.forEach((node) => { + expect(expectedNodes).toContainEqual(node); }); - expect(result).toEqual(mockNodes); }); it('should respect custom limit', async () => { - mockBackendSrv.get.mockResolvedValue({ items: [] }); - - await apiClient.fetchNodes({ limit: 50 }); - - expect(mockBackendSrv.get).toHaveBeenCalledWith('/apis/scope.grafana.app/v0alpha1/find/scope_node_children', { - parent: undefined, - query: undefined, - limit: 50, + const limit = 5; + const mockNodes = MOCK_NODES.slice(0, limit); + const mockSubscription = createMockSubscription({ + data: { items: mockNodes }, }); + (scopeAPIv0alpha1.endpoints.getFindScopeNodeChildrenResults.initiate as jest.Mock).mockReturnValue( + mockSubscription + ); + + const result = await apiClient.fetchNodes({ limit }); + + expect(result.length).toBeLessThanOrEqual(limit); }); it('should throw error for invalid limit (too small)', async () => { @@ -226,137 +391,297 @@ describe('ScopesApiClient', () => { }); it('should use default limit of 1000 when not specified', async () => { - mockBackendSrv.get.mockResolvedValue({ items: [] }); - - await apiClient.fetchNodes({}); - - expect(mockBackendSrv.get).toHaveBeenCalledWith('/apis/scope.grafana.app/v0alpha1/find/scope_node_children', { - parent: undefined, - query: undefined, - limit: 1000, + const mockNodes = MOCK_NODES.slice(0, 1000); + const mockSubscription = createMockSubscription({ + data: { items: mockNodes }, }); + (scopeAPIv0alpha1.endpoints.getFindScopeNodeChildrenResults.initiate as jest.Mock).mockReturnValue( + mockSubscription + ); + + const result = await apiClient.fetchNodes({}); + + expect(Array.isArray(result)).toBe(true); + // Default limit is 1000, so result should not exceed that + expect(result.length).toBeLessThanOrEqual(1000); }); it('should return empty array on API error', async () => { - mockBackendSrv.get.mockRejectedValue(new Error('API Error')); - - const result = await apiClient.fetchNodes({ parent: 'test' }); - - expect(result).toEqual([]); - }); - }); - - describe('fetchScope', () => { - it('should fetch a scope by name', async () => { - const mockScope = { - metadata: { name: 'test-scope' }, - spec: { - title: 'Test Scope', - filters: [], - }, - }; - - mockBackendSrv.get.mockResolvedValue(mockScope); - - const result = await apiClient.fetchScope('test-scope'); - - expect(mockBackendSrv.get).toHaveBeenCalledWith('/apis/scope.grafana.app/v0alpha1/scopes/test-scope'); - expect(result).toEqual(mockScope); - }); - - it('should return undefined on error', async () => { + const mockSubscription = createMockSubscription({ data: { items: [] } }); + (scopeAPIv0alpha1.endpoints.getFindScopeNodeChildrenResults.initiate as jest.Mock).mockReturnValue( + mockSubscription + ); const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(); - mockBackendSrv.get.mockRejectedValue(new Error('Not found')); - const result = await apiClient.fetchScope('non-existent'); + const result = await apiClient.fetchNodes({ parent: 'non-existent-parent' }); - expect(result).toBeUndefined(); + expect(Array.isArray(result)).toBe(true); consoleErrorSpy.mockRestore(); }); - it('should log error to console', async () => { - const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(); - const error = new Error('Not found'); - mockBackendSrv.get.mockRejectedValue(error); + it('should combine parent and query filters', async () => { + // Expected: MOCK_NODES contains nodes with parentName 'applications' and 'Grafana' in title + const parentName = 'applications'; + const query = 'Grafana'; + const expectedNodes = MOCK_NODES.filter( + (n) => n.spec.parentName === parentName && n.spec.title.toLowerCase().includes(query.toLowerCase()) + ); - await apiClient.fetchScope('non-existent'); + const mockSubscription = createMockSubscription({ + data: { items: expectedNodes }, + }); + (scopeAPIv0alpha1.endpoints.getFindScopeNodeChildrenResults.initiate as jest.Mock).mockReturnValue( + mockSubscription + ); - expect(consoleErrorSpy).toHaveBeenCalledWith(error); - consoleErrorSpy.mockRestore(); + const result = await apiClient.fetchNodes({ parent: parentName, query }); + + // Validate: returns nodes matching both filters from MOCK_NODES + expect(Array.isArray(result)).toBe(true); + result.forEach((node) => { + expect(node.spec.parentName).toBe(parentName); + expect(node.spec.title.toLowerCase()).toContain('grafana'); + }); + // Verify all returned nodes are from the expected set + result.forEach((node) => { + expect(expectedNodes).toContainEqual(node); + }); }); }); - describe('fetchMultipleScopes', () => { - it('should fetch multiple scopes in parallel', async () => { - const mockScopes = [ + describe('fetchDashboards', () => { + it('should fetch dashboards for scopes', async () => { + // Expected: MOCK_SCOPE_DASHBOARD_BINDINGS contains bindings for 'grafana' scope + const scopeNames = ['grafana']; + const mockBindings = [ { - metadata: { name: 'scope-1' }, - spec: { title: 'Scope 1', filters: [] }, - }, - { - metadata: { name: 'scope-2' }, - spec: { title: 'Scope 2', filters: [] }, + metadata: { name: 'grafana-binding-1' }, + spec: { dashboard: 'dashboard-1', scope: 'grafana' }, + status: { dashboardTitle: 'Dashboard 1' }, }, ]; + const mockSubscription = createMockSubscription({ + data: { items: mockBindings }, + }); + (scopeAPIv0alpha1.endpoints.getFindScopeDashboardBindingsResults.initiate as jest.Mock).mockReturnValue( + mockSubscription + ); - mockBackendSrv.get.mockResolvedValueOnce(mockScopes[0]).mockResolvedValueOnce(mockScopes[1]); + const result = await apiClient.fetchDashboards(scopeNames); - const result = await apiClient.fetchMultipleScopes(['scope-1', 'scope-2']); - - expect(mockBackendSrv.get).toHaveBeenCalledTimes(2); - expect(result).toEqual(mockScopes); + // Validate: returns bindings for the requested scope + expect(Array.isArray(result)).toBe(true); + result.forEach((binding) => { + expect(binding.spec.scope).toBe('grafana'); + }); }); - it('should filter out undefined scopes', async () => { - const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(); - const mockScope = { - metadata: { name: 'scope-1' }, - spec: { title: 'Scope 1', filters: [] }, - }; + it('should fetch dashboards for multiple scopes', async () => { + // Expected: MOCK_SCOPE_DASHBOARD_BINDINGS contains bindings for 'grafana' and 'mimir' scopes + const scopeNames = ['grafana', 'mimir']; + const mockBindings = [ + { + metadata: { name: 'grafana-binding-1' }, + spec: { dashboard: 'dashboard-1', scope: 'grafana' }, + status: { dashboardTitle: 'Dashboard 1' }, + }, + { + metadata: { name: 'mimir-binding-1' }, + spec: { dashboard: 'dashboard-2', scope: 'mimir' }, + status: { dashboardTitle: 'Dashboard 2' }, + }, + ]; + const mockSubscription = createMockSubscription({ + data: { items: mockBindings }, + }); + (scopeAPIv0alpha1.endpoints.getFindScopeDashboardBindingsResults.initiate as jest.Mock).mockReturnValue( + mockSubscription + ); - mockBackendSrv.get.mockResolvedValueOnce(mockScope).mockRejectedValueOnce(new Error('Not found')); + const result = await apiClient.fetchDashboards(scopeNames); - const result = await apiClient.fetchMultipleScopes(['scope-1', 'non-existent']); - - expect(result).toEqual([mockScope]); - consoleErrorSpy.mockRestore(); + // Validate: returns bindings for either scope + expect(Array.isArray(result)).toBe(true); + result.forEach((binding) => { + expect(scopeNames).toContain(binding.spec.scope); + }); }); - it('should return empty array when no scopes provided', async () => { - const result = await apiClient.fetchMultipleScopes([]); + it('should return empty array when no dashboards found', async () => { + const mockSubscription = createMockSubscription({ + data: { items: [] }, + }); + (scopeAPIv0alpha1.endpoints.getFindScopeDashboardBindingsResults.initiate as jest.Mock).mockReturnValue( + mockSubscription + ); + + const result = await apiClient.fetchDashboards(['non-existent-scope']); expect(result).toEqual([]); - expect(mockBackendSrv.get).not.toHaveBeenCalled(); + }); + + it('should handle API errors gracefully', async () => { + const mockSubscription = createMockSubscription({ + data: { items: [] }, + }); + (scopeAPIv0alpha1.endpoints.getFindScopeDashboardBindingsResults.initiate as jest.Mock).mockReturnValue( + mockSubscription + ); + const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(); + + const result = await apiClient.fetchDashboards(['grafana']); + + expect(Array.isArray(result)).toBe(true); + consoleErrorSpy.mockRestore(); + }); + }); + + describe('fetchScopeNavigations', () => { + it('should fetch navigations for scopes', async () => { + // Expected: MSW handler returns MOCK_SUB_SCOPE_MIMIR_ITEMS for 'mimir' scope + const scopeName = 'mimir'; + const mockNavigations = [ + { + metadata: { name: 'mimir-item-1' }, + spec: { scope: 'mimir', url: '/d/mimir-dashboard-1' }, + status: { title: 'Mimir Dashboard 1' }, + }, + ]; + const mockSubscription = createMockSubscription({ + data: { items: mockNavigations }, + }); + (scopeAPIv0alpha1.endpoints.getFindScopeNavigationsResults.initiate as jest.Mock).mockReturnValue( + mockSubscription + ); + + const result = await apiClient.fetchScopeNavigations([scopeName]); + + // Validate: returns navigations for the requested scope + expect(Array.isArray(result)).toBe(true); + result.forEach((nav) => { + expect(nav.spec.scope).toBe('mimir'); + }); + }); + + it('should fetch navigations for multiple scopes', async () => { + // Expected: Returns navigations for both 'mimir' and 'loki' + const scopeNames = ['mimir', 'loki']; + const mockNavigations = [ + { + metadata: { name: 'mimir-item-1' }, + spec: { scope: 'mimir', url: '/d/mimir-dashboard-1' }, + status: { title: 'Mimir Dashboard 1' }, + }, + { + metadata: { name: 'loki-item-1' }, + spec: { scope: 'loki', url: '/d/loki-dashboard-1' }, + status: { title: 'Loki Dashboard 1' }, + }, + ]; + const mockSubscription = createMockSubscription({ + data: { items: mockNavigations }, + }); + (scopeAPIv0alpha1.endpoints.getFindScopeNavigationsResults.initiate as jest.Mock).mockReturnValue( + mockSubscription + ); + + const result = await apiClient.fetchScopeNavigations(scopeNames); + + // Validate: returns navigations for both scopes + expect(Array.isArray(result)).toBe(true); + const resultScopeNames = result.map((nav) => nav.spec.scope); + expect(resultScopeNames.length).toBeGreaterThan(0); + result.forEach((nav) => { + expect(scopeNames).toContain(nav.spec.scope); + }); + }); + + it('should return empty array when no navigations found', async () => { + const mockSubscription = createMockSubscription({ + data: { items: [] }, + }); + (scopeAPIv0alpha1.endpoints.getFindScopeNavigationsResults.initiate as jest.Mock).mockReturnValue( + mockSubscription + ); + + const result = await apiClient.fetchScopeNavigations(['grafana']); + + expect(Array.isArray(result)).toBe(true); + }); + + it('should handle API errors gracefully', async () => { + const mockSubscription = createMockSubscription({ + data: { items: [] }, + }); + (scopeAPIv0alpha1.endpoints.getFindScopeNavigationsResults.initiate as jest.Mock).mockReturnValue( + mockSubscription + ); + const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(); + + const result = await apiClient.fetchScopeNavigations(['mimir']); + + expect(Array.isArray(result)).toBe(true); + consoleErrorSpy.mockRestore(); }); }); describe('performance considerations', () => { it('should make single batched request with fetchMultipleScopeNodes', async () => { - mockBackendSrv.get.mockResolvedValue({ items: [] }); + // This test verifies that the method uses the batched endpoint + const nodeNames = [ + 'applications-grafana', + 'applications-mimir', + 'applications-loki', + 'applications-tempo', + 'applications-cloud', + ]; + const expectedNodes = MOCK_NODES.filter((n) => nodeNames.includes(n.metadata.name)); + const mockSubscription = createMockSubscription({ + data: { items: expectedNodes }, + }); + (scopeAPIv0alpha1.endpoints.getFindScopeNodeChildrenResults.initiate as jest.Mock).mockReturnValue( + mockSubscription + ); - await apiClient.fetchMultipleScopeNodes(['node-1', 'node-2', 'node-3', 'node-4', 'node-5']); + const result = await apiClient.fetchMultipleScopeNodes(nodeNames); - // Should make exactly 1 API call - expect(mockBackendSrv.get).toHaveBeenCalledTimes(1); + expect(Array.isArray(result)).toBe(true); + // Verify it was called once with all names + expect(scopeAPIv0alpha1.endpoints.getFindScopeNodeChildrenResults.initiate).toHaveBeenCalledTimes(1); + expect(scopeAPIv0alpha1.endpoints.getFindScopeNodeChildrenResults.initiate).toHaveBeenCalledWith( + { names: nodeNames }, + { subscribe: false } + ); }); it('should make N sequential requests with fetchScopeNode (old pattern)', async () => { - mockBackendSrv.get.mockResolvedValue({ - metadata: { name: 'test' }, - spec: { nodeType: 'leaf', title: 'Test', parentName: '' }, + // This test demonstrates the old pattern of fetching nodes one by one + // Each call makes a separate API request + const nodeNames = [ + 'applications-grafana', + 'applications-mimir', + 'applications-loki', + 'applications-tempo', + 'applications-cloud', + ]; + const mockNodes = nodeNames.map((name) => MOCK_NODES.find((n) => n.metadata.name === name)).filter(Boolean); + const mockSubscriptions = mockNodes.map((node) => createMockSubscription({ data: node })); + mockSubscriptions.forEach((sub) => { + (scopeAPIv0alpha1.endpoints.getScopeNode.initiate as jest.Mock).mockReturnValueOnce(sub); }); - // Simulate old pattern of fetching nodes one by one - await Promise.all([ - apiClient.fetchScopeNode('node-1'), - apiClient.fetchScopeNode('node-2'), - apiClient.fetchScopeNode('node-3'), - apiClient.fetchScopeNode('node-4'), - apiClient.fetchScopeNode('node-5'), + const results = await Promise.all([ + apiClient.fetchScopeNode('applications-grafana'), + apiClient.fetchScopeNode('applications-mimir'), + apiClient.fetchScopeNode('applications-loki'), + apiClient.fetchScopeNode('applications-tempo'), + apiClient.fetchScopeNode('applications-cloud'), ]); - // Should make 5 separate API calls - expect(mockBackendSrv.get).toHaveBeenCalledTimes(5); + expect(results).toHaveLength(5); + expect(results.every((r) => r !== undefined)).toBe(true); + // Verify it was called 5 times (once per node) + expect(scopeAPIv0alpha1.endpoints.getScopeNode.initiate).toHaveBeenCalledTimes(5); }); }); }); diff --git a/public/app/features/scopes/ScopesApiClient.ts b/public/app/features/scopes/ScopesApiClient.ts index 1b2c9f9d1a9..bbfbca130f0 100644 --- a/public/app/features/scopes/ScopesApiClient.ts +++ b/public/app/features/scopes/ScopesApiClient.ts @@ -1,25 +1,95 @@ -import { getAPIBaseURL } from '@grafana/api-clients'; import { Scope, ScopeDashboardBinding, ScopeNode } from '@grafana/data'; -import { getBackendSrv, config } from '@grafana/runtime'; +import { config } from '@grafana/runtime'; +import { scopeAPIv0alpha1 } from 'app/api/clients/scope/v0alpha1'; +import { getMessageFromError } from 'app/core/utils/errors'; +import { dispatch } from 'app/store/store'; import { ScopeNavigation } from './dashboards/types'; -const apiUrl = getAPIBaseURL('scope.grafana.app', 'v0alpha1'); - export class ScopesApiClient { + /** + * Checks if the data is a Kubernetes Status error response. + * @param data The data to check + * @returns true if the data is a Status error, false otherwise + */ + private isStatusError(data: unknown): data is { kind: 'Status'; status: 'Failure'; message?: string; code?: number } { + return ( + data !== null && + typeof data === 'object' && + 'kind' in data && + data.kind === 'Status' && + 'status' in data && + data.status === 'Failure' + ); + } + + /** + * Extracts and validates data from an RTK Query result, checking for error responses. + * @param result The RTK Query result + * @param context Context for error logging (e.g., resource name) + * @returns The data if valid, undefined if it's an error response + */ + private extractDataOrHandleError(result: { data?: T; error?: unknown }, context: string): T | undefined { + if ('data' in result && result.data) { + // Check if the data is actually an error response (Kubernetes Status object) + if (this.isStatusError(result.data)) { + const errorMessage = getMessageFromError(result.data); + console.error(`Failed to fetch %s:`, context, errorMessage); + return undefined; + } + return result.data; + } + + if ('error' in result) { + const errorMessage = getMessageFromError(result.error); + console.error(`Failed to fetch %s:`, context, errorMessage); + } + + return undefined; + } async fetchScope(name: string): Promise { + const subscription = dispatch(scopeAPIv0alpha1.endpoints.getScope.initiate({ name }, { subscribe: false })); try { - return await getBackendSrv().get(apiUrl + `/scopes/${name}`); + const result = await subscription; + return this.extractDataOrHandleError(result, `scope: ${name}`); } catch (err) { - // TODO: maybe some better error handling - console.error(err); + const errorMessage = getMessageFromError(err); + console.error('Failed to fetch scope:', name, errorMessage); return undefined; + } finally { + // Unsubscribe for extra safety, even though with subscribe: false and awaiting, + // the request completes before return, so this is mostly a no-op + subscription.unsubscribe(); } } async fetchMultipleScopes(scopesIds: string[]): Promise { - const scopes = await Promise.all(scopesIds.map((id) => this.fetchScope(id))); - return scopes.filter((scope) => scope !== undefined); + if (scopesIds.length === 0) { + return []; + } + + try { + const scopes = await Promise.all(scopesIds.map((id) => this.fetchScope(id))); + const successfulScopes = scopes.filter((scope) => scope !== undefined); + + if (successfulScopes.length < scopesIds.length) { + const failedCount = scopesIds.length - successfulScopes.length; + console.warn( + 'Failed to fetch', + failedCount, + 'of', + scopesIds.length, + 'scope(s). Requested IDs:', + scopesIds.join(', ') + ); + } + + return successfulScopes; + } catch (err) { + const errorMessage = getMessageFromError(err); + console.error('Failed to fetch multiple scopes:', scopesIds, errorMessage); + return []; + } } async fetchMultipleScopeNodes(names: string[]): Promise { @@ -27,13 +97,31 @@ export class ScopesApiClient { return Promise.resolve([]); } + const subscription = dispatch( + scopeAPIv0alpha1.endpoints.getFindScopeNodeChildrenResults.initiate({ names }, { subscribe: false }) + ); try { - const res = await getBackendSrv().get<{ items: ScopeNode[] }>(apiUrl + `/find/scope_node_children`, { - names: names, - }); - return res?.items ?? []; - } catch (err) { + const result = await subscription; + + if ('data' in result && result.data) { + // The generated API returns items compatible with @grafana/data ScopeNode + return result.data.items ?? []; + } + + if ('error' in result) { + const errorMessage = getMessageFromError(result.error); + console.error('Failed to fetch multiple scope nodes:', names, errorMessage); + } + return []; + } catch (err) { + const errorMessage = getMessageFromError(err); + console.error('Failed to fetch multiple scope nodes:', names, errorMessage); + return []; + } finally { + // Unsubscribe for extra safety, even though with subscribe: false and awaiting, + // the request completes before return, so this is mostly a no-op + subscription.unsubscribe(); } } @@ -53,46 +141,128 @@ export class ScopesApiClient { throw new Error('Limit must be between 1 and 10000'); } + const subscription = dispatch( + scopeAPIv0alpha1.endpoints.getFindScopeNodeChildrenResults.initiate( + { + parent: options.parent, + query: options.query, + limit, + }, + { subscribe: false, forceRefetch: true } // Froce refetch for search. Revisit this when necessary + ) + ); try { - const nodes = - ( - await getBackendSrv().get<{ items: ScopeNode[] }>(apiUrl + `/find/scope_node_children`, { - parent: options.parent, - query: options.query, - limit, - }) - )?.items ?? []; + const result = await subscription; + + if ('data' in result && result.data) { + // The generated API returns items compatible with @grafana/data ScopeNode + return result.data.items ?? []; + } + + if ('error' in result) { + const errorMessage = getMessageFromError(result.error); + const contextParts: string[] = []; + if (options.parent) { + contextParts.push('parent="' + options.parent + '"'); + } + if (options.query) { + contextParts.push('query="' + options.query + '"'); + } + contextParts.push('limit=' + limit); + const context = contextParts.join(', '); + console.error('Failed to fetch scope nodes:', context, errorMessage); + } - return nodes; - } catch (err) { return []; + } catch (err) { + const errorMessage = getMessageFromError(err); + const contextParts: string[] = []; + if (options.parent) { + contextParts.push('parent="' + options.parent + '"'); + } + if (options.query) { + contextParts.push('query="' + options.query + '"'); + } + contextParts.push('limit=' + limit); + const context = contextParts.join(', '); + console.error('Failed to fetch scope nodes:', context, errorMessage); + return []; + } finally { + // Unsubscribe for extra safety, even though with subscribe: false and awaiting, + // the request completes before return, so this is mostly a no-op + subscription.unsubscribe(); } } public fetchDashboards = async (scopeNames: string[]): Promise => { - try { - const response = await getBackendSrv().get<{ items: ScopeDashboardBinding[] }>( - apiUrl + `/find/scope_dashboard_bindings`, + const subscription = dispatch( + // Note: `name` is required by generated types but ignored by the query builder (codegen bug) + scopeAPIv0alpha1.endpoints.getFindScopeDashboardBindingsResults.initiate( { + name: '', scope: scopeNames, - } - ); + }, + { subscribe: false } + ) + ); + try { + const result = await subscription; + + if ('data' in result && result.data) { + // The generated API returns items compatible with @grafana/data ScopeDashboardBinding + return result.data.items ?? []; + } + + if ('error' in result) { + const errorMessage = getMessageFromError(result.error); + console.error('Failed to fetch dashboards for scopes:', scopeNames, errorMessage); + } - return response?.items ?? []; - } catch (err) { return []; + } catch (err) { + const errorMessage = getMessageFromError(err); + console.error('Failed to fetch dashboards for scopes:', scopeNames, errorMessage); + return []; + } finally { + // Unsubscribe for extra safety, even though with subscribe: false and awaiting, + // the request completes before return, so this is mostly a no-op + subscription.unsubscribe(); } }; public fetchScopeNavigations = async (scopeNames: string[]): Promise => { + const subscription = dispatch( + // Note: `name` is required by generated types but ignored by the query builder (codegen bug) + scopeAPIv0alpha1.endpoints.getFindScopeNavigationsResults.initiate( + { + name: '', + scope: scopeNames, + }, + { subscribe: false } + ) + ); try { - const response = await getBackendSrv().get<{ items: ScopeNavigation[] }>(apiUrl + `/find/scope_navigations`, { - scope: scopeNames, - }); + const result = await subscription; + + if ('data' in result && result.data) { + // The generated API returns items compatible with ScopeNavigation + return result.data.items ?? []; + } + + if ('error' in result) { + const errorMessage = getMessageFromError(result.error); + console.error('Failed to fetch scope navigations for scopes:', scopeNames, errorMessage); + } - return response?.items ?? []; - } catch (err) { return []; + } catch (err) { + const errorMessage = getMessageFromError(err); + console.error('Failed to fetch scope navigations for scopes:', scopeNames, errorMessage); + return []; + } finally { + // Unsubscribe for extra safety, even though with subscribe: false and awaiting, + // the request completes before return, so this is mostly a no-op + subscription.unsubscribe(); } }; @@ -100,11 +270,21 @@ export class ScopesApiClient { if (!config.featureToggles.useScopeSingleNodeEndpoint) { return Promise.resolve(undefined); } + + const subscription = dispatch( + scopeAPIv0alpha1.endpoints.getScopeNode.initiate({ name: scopeNodeId }, { subscribe: false }) + ); try { - const response = await getBackendSrv().get(apiUrl + `/scopenodes/${scopeNodeId}`); - return response; + const result = await subscription; + return this.extractDataOrHandleError(result, `scope node: ${scopeNodeId}`); } catch (err) { + const errorMessage = getMessageFromError(err); + console.error('Failed to fetch scope node:', scopeNodeId, errorMessage); return undefined; + } finally { + // Unsubscribe for extra safety, even though with subscribe: false and awaiting, + // the request completes before return, so this is mostly a no-op + subscription.unsubscribe(); } }; } diff --git a/public/app/features/scopes/dashboards/ScopesDashboardsService.test.ts b/public/app/features/scopes/dashboards/ScopesDashboardsService.test.ts index 2c5e4b28fc6..97b24dd69ac 100644 --- a/public/app/features/scopes/dashboards/ScopesDashboardsService.test.ts +++ b/public/app/features/scopes/dashboards/ScopesDashboardsService.test.ts @@ -5,7 +5,11 @@ import { config, locationService } from '@grafana/runtime'; import { ScopesApiClient } from '../ScopesApiClient'; // Import mock data for subScope tests -import { navigationWithSubScope, navigationWithSubScope2, navigationWithSubScopeAndGroups } from '../tests/utils/mocks'; +import { + navigationWithSubScope, + navigationWithSubScope2, + navigationWithSubScopeAndGroups, +} from '../tests/utils/mockData'; import { ScopesDashboardsService, filterItemsWithSubScopesInPath } from './ScopesDashboardsService'; import { ScopeNavigation } from './types'; diff --git a/public/app/features/scopes/tests/dashboardReload.test.ts b/public/app/features/scopes/tests/dashboardReload.test.ts index ced8b1a68d3..67b9a6fd1a5 100644 --- a/public/app/features/scopes/tests/dashboardReload.test.ts +++ b/public/app/features/scopes/tests/dashboardReload.test.ts @@ -1,20 +1,24 @@ -import { config } from '@grafana/runtime'; +import { config, setBackendSrv } from '@grafana/runtime'; +import { setupMockServer } from '@grafana/test-utils/server'; +import { backendSrv } from 'app/core/services/backend_srv'; import { setDashboardAPI } from 'app/features/dashboard/api/dashboard_api'; import { getDashboardScenePageStateManager } from 'app/features/dashboard-scene/pages/DashboardScenePageStateManager'; import { enterEditMode, updateMyVar, updateScopes, updateTimeRange } from './utils/actions'; -import { getDatasource, getInstanceSettings, getMock } from './utils/mocks'; +import { getDatasource, getInstanceSettings } from './utils/mocks'; import { renderDashboard, resetScenes } from './utils/render'; jest.mock('@grafana/runtime', () => ({ __esModule: true, ...jest.requireActual('@grafana/runtime'), useChromeHeaderHeight: jest.fn(), - getBackendSrv: () => ({ get: getMock }), getDataSourceSrv: () => ({ get: getDatasource, getInstanceSettings }), usePluginLinks: jest.fn().mockReturnValue({ links: [] }), })); +setBackendSrv(backendSrv); +setupMockServer(); + describe('Dashboard reload', () => { let dashboardReloadSpy: jest.SpyInstance; beforeEach(() => { diff --git a/public/app/features/scopes/tests/dashboardsList.test.ts b/public/app/features/scopes/tests/dashboardsList.test.ts index b4e091bfd6b..db972778705 100644 --- a/public/app/features/scopes/tests/dashboardsList.test.ts +++ b/public/app/features/scopes/tests/dashboardsList.test.ts @@ -1,6 +1,9 @@ import { screen, waitFor } from '@testing-library/react'; -import { config, locationService } from '@grafana/runtime'; +import { config, locationService, setBackendSrv } from '@grafana/runtime'; +import { setupMockServer } from '@grafana/test-utils/server'; +import { MOCK_SUB_SCOPE_MIMIR_ITEMS } from '@grafana/test-utils/unstable'; +import { backendSrv } from 'app/core/services/backend_srv'; import { ScopesApiClient } from '../ScopesApiClient'; import { ScopesService } from '../ScopesService'; @@ -35,26 +38,25 @@ import { dashboardWithRootFolder, dashboardWithRootFolderAndOtherFolder, dashboardWithTwoFolders, - getDatasource, - getInstanceSettings, - getMock, navigationWithSubScope, navigationWithSubScope2, navigationWithSubScopeDifferent, navigationWithSubScopeAndGroups, - subScopeMimirItems, -} from './utils/mocks'; +} from './utils/mockData'; +import { getDatasource, getInstanceSettings } from './utils/mocks'; import { renderDashboard, resetScenes } from './utils/render'; jest.mock('@grafana/runtime', () => ({ __esModule: true, ...jest.requireActual('@grafana/runtime'), useChromeHeaderHeight: jest.fn(), - getBackendSrv: () => ({ get: getMock }), getDataSourceSrv: () => ({ get: getDatasource, getInstanceSettings }), usePluginLinks: jest.fn().mockReturnValue({ links: [] }), })); +setBackendSrv(backendSrv); +setupMockServer(); + describe('Dashboards list', () => { let fetchDashboardsSpy: jest.SpyInstance; let fetchScopeNavigationsSpy: jest.SpyInstance; @@ -539,7 +541,7 @@ describe('Dashboards list', () => { it('Loads subScope items when folder is expanded', async () => { const mockNavigations = [navigationWithSubScope]; - fetchScopeNavigationsSpy.mockResolvedValueOnce(mockNavigations).mockResolvedValueOnce(subScopeMimirItems); + fetchScopeNavigationsSpy.mockResolvedValueOnce(mockNavigations).mockResolvedValueOnce(MOCK_SUB_SCOPE_MIMIR_ITEMS); await toggleDashboards(); await updateScopes(scopesService, ['grafana']); @@ -571,7 +573,7 @@ describe('Dashboards list', () => { it('Shows loading state while fetching subScope items', async () => { const mockNavigations = [navigationWithSubScope]; - fetchScopeNavigationsSpy.mockResolvedValueOnce(mockNavigations).mockResolvedValueOnce(subScopeMimirItems); + fetchScopeNavigationsSpy.mockResolvedValueOnce(mockNavigations).mockResolvedValueOnce(MOCK_SUB_SCOPE_MIMIR_ITEMS); await toggleDashboards(); await updateScopes(scopesService, ['grafana']); @@ -591,7 +593,7 @@ describe('Dashboards list', () => { it('Multiple subScope folders with same subScope load same content', async () => { const mockNavigations = [navigationWithSubScope, navigationWithSubScope2]; - fetchScopeNavigationsSpy.mockResolvedValueOnce(mockNavigations).mockResolvedValue(subScopeMimirItems); + fetchScopeNavigationsSpy.mockResolvedValueOnce(mockNavigations).mockResolvedValue(MOCK_SUB_SCOPE_MIMIR_ITEMS); await toggleDashboards(); await updateScopes(scopesService, ['grafana']); @@ -676,7 +678,7 @@ describe('Dashboards list', () => { it('Filters search works with loaded subScope content', async () => { const mockNavigations = [navigationWithSubScope]; - fetchScopeNavigationsSpy.mockResolvedValueOnce(mockNavigations).mockResolvedValueOnce(subScopeMimirItems); + fetchScopeNavigationsSpy.mockResolvedValueOnce(mockNavigations).mockResolvedValueOnce(MOCK_SUB_SCOPE_MIMIR_ITEMS); await toggleDashboards(); await updateScopes(scopesService, ['grafana']); @@ -715,7 +717,7 @@ describe('Dashboards list', () => { it('Does not fetch subScope items if folder is already loaded', async () => { const mockNavigations = [navigationWithSubScope]; - fetchScopeNavigationsSpy.mockResolvedValueOnce(mockNavigations).mockResolvedValueOnce(subScopeMimirItems); + fetchScopeNavigationsSpy.mockResolvedValueOnce(mockNavigations).mockResolvedValueOnce(MOCK_SUB_SCOPE_MIMIR_ITEMS); await toggleDashboards(); await updateScopes(scopesService, ['grafana']); diff --git a/public/app/features/scopes/tests/selector.test.ts b/public/app/features/scopes/tests/selector.test.ts index 56921ac6f7d..a9a4ab0ac58 100644 --- a/public/app/features/scopes/tests/selector.test.ts +++ b/public/app/features/scopes/tests/selector.test.ts @@ -1,4 +1,7 @@ -import { config, locationService } from '@grafana/runtime'; +import { config, locationService, setBackendSrv } from '@grafana/runtime'; +import { setupMockServer } from '@grafana/test-utils/server'; +import { MOCK_SCOPES } from '@grafana/test-utils/unstable'; +import { backendSrv } from 'app/core/services/backend_srv'; import { getDashboardScenePageStateManager } from '../../dashboard-scene/pages/DashboardScenePageStateManager'; import { ScopesService } from '../ScopesService'; @@ -25,7 +28,7 @@ import { expectResultApplicationsGrafanaSelected, expectScopesSelectorValue, } from './utils/assertions'; -import { getDatasource, getInstanceSettings, getMock, mocksScopes } from './utils/mocks'; +import { getDatasource, getInstanceSettings } from './utils/mocks'; import { renderDashboard, resetScenes } from './utils/render'; import { getListOfScopes } from './utils/selectors'; @@ -33,11 +36,13 @@ jest.mock('@grafana/runtime', () => ({ __esModule: true, ...jest.requireActual('@grafana/runtime'), useChromeHeaderHeight: jest.fn(), - getBackendSrv: () => ({ get: getMock }), getDataSourceSrv: () => ({ get: getDatasource, getInstanceSettings }), usePluginLinks: jest.fn().mockReturnValue({ links: [] }), })); +setBackendSrv(backendSrv); +setupMockServer(); + describe('Selector', () => { let fetchSelectedScopesSpy: jest.SpyInstance; let dashboardReloadSpy: jest.SpyInstance; @@ -67,7 +72,7 @@ describe('Selector', () => { await selectResultCloud(); await applyScopes(); expect(fetchSelectedScopesSpy).toHaveBeenCalled(); - expect(getListOfScopes(scopesService)).toEqual(mocksScopes.filter(({ metadata: { name } }) => name === 'cloud')); + expect(getListOfScopes(scopesService)).toEqual(MOCK_SCOPES.filter(({ metadata: { name } }) => name === 'cloud')); }); it('Does not save the scopes on close', async () => { diff --git a/public/app/features/scopes/tests/tree.test.ts b/public/app/features/scopes/tests/tree.test.ts index f11ec276c0c..d6c4e9cf994 100644 --- a/public/app/features/scopes/tests/tree.test.ts +++ b/public/app/features/scopes/tests/tree.test.ts @@ -1,7 +1,9 @@ import { screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; -import { config, locationService } from '@grafana/runtime'; +import { config, locationService, setBackendSrv } from '@grafana/runtime'; +import { setupMockServer } from '@grafana/test-utils/server'; +import { backendSrv } from 'app/core/services/backend_srv'; import { ScopesService } from '../ScopesService'; @@ -43,18 +45,20 @@ import { expectScopesHeadline, expectScopesSelectorValue, } from './utils/assertions'; -import { getDatasource, getInstanceSettings, getMock } from './utils/mocks'; +import { getDatasource, getInstanceSettings } from './utils/mocks'; import { renderDashboard, resetScenes } from './utils/render'; jest.mock('@grafana/runtime', () => ({ __esModule: true, ...jest.requireActual('@grafana/runtime'), useChromeHeaderHeight: jest.fn(), - getBackendSrv: () => ({ get: getMock }), getDataSourceSrv: () => ({ get: getDatasource, getInstanceSettings }), usePluginLinks: jest.fn().mockReturnValue({ links: [] }), })); +setBackendSrv(backendSrv); +setupMockServer(); + describe('Tree', () => { let fetchNodesSpy: jest.SpyInstance; let fetchScopeSpy: jest.SpyInstance; diff --git a/public/app/features/scopes/tests/utils/mockData.ts b/public/app/features/scopes/tests/utils/mockData.ts new file mode 100644 index 00000000000..fd8b94a6c14 --- /dev/null +++ b/public/app/features/scopes/tests/utils/mockData.ts @@ -0,0 +1,92 @@ +import { ScopeDashboardBinding } from '@grafana/data'; + +import { ScopeNavigation } from '../../dashboards/types'; + +// Mock subScope navigation items (specific to these tests) +export const navigationWithSubScope: ScopeNavigation = { + metadata: { name: 'subscope-nav-1' }, + spec: { + scope: 'grafana', + subScope: 'mimir', + url: '/d/subscope-dashboard-1', + }, + status: { + title: 'Mimir Dashboards', + groups: [], // subScope items ignore groups + }, +}; + +export const navigationWithSubScope2: ScopeNavigation = { + metadata: { name: 'subscope-nav-2' }, + spec: { + scope: 'grafana', + subScope: 'mimir', + url: '/d/subscope-dashboard-2', + }, + status: { + title: 'Mimir Overview', + groups: [], + }, +}; + +export const navigationWithSubScopeDifferent: ScopeNavigation = { + metadata: { name: 'subscope-nav-3' }, + spec: { + scope: 'grafana', + subScope: 'loki', + url: '/d/subscope-dashboard-3', + }, + status: { + title: 'Loki Dashboards', + groups: [], + }, +}; + +export const navigationWithSubScopeAndGroups: ScopeNavigation = { + metadata: { name: 'subscope-nav-groups' }, + spec: { + scope: 'grafana', + subScope: 'mimir', + url: '/d/subscope-dashboard-groups', + }, + status: { + title: 'Mimir with Groups', + groups: ['Group1', 'Group2'], // Should be ignored for subScope items + }, +}; + +const generateScopeDashboardBinding = (dashboardTitle: string, groups?: string[], dashboardId?: string) => ({ + metadata: { name: `${dashboardTitle}-name` }, + spec: { + dashboard: `${dashboardId ?? dashboardTitle}-dashboard`, + scope: `${dashboardTitle}-scope`, + }, + status: { + dashboardTitle, + groups, + }, +}); + +export const dashboardWithoutFolder: ScopeDashboardBinding = generateScopeDashboardBinding('Without Folder'); +export const dashboardWithOneFolder: ScopeDashboardBinding = generateScopeDashboardBinding('With one folder', [ + 'Folder 1', +]); +export const dashboardWithTwoFolders: ScopeDashboardBinding = generateScopeDashboardBinding('With two folders', [ + 'Folder 1', + 'Folder 2', +]); +export const alternativeDashboardWithTwoFolders: ScopeDashboardBinding = generateScopeDashboardBinding( + 'Alternative with two folders', + ['Folder 1', 'Folder 2'], + 'With two folders' +); +export const dashboardWithRootFolder: ScopeDashboardBinding = generateScopeDashboardBinding('With root folder', ['']); +export const alternativeDashboardWithRootFolder: ScopeDashboardBinding = generateScopeDashboardBinding( + 'Alternative With root folder', + [''], + 'With root folder' +); +export const dashboardWithRootFolderAndOtherFolder: ScopeDashboardBinding = generateScopeDashboardBinding( + 'With root folder and other folder', + ['', 'Folder 3'] +); diff --git a/public/app/features/scopes/tests/utils/mocks.ts b/public/app/features/scopes/tests/utils/mocks.ts index c1afb8b0de2..45adee30744 100644 --- a/public/app/features/scopes/tests/utils/mocks.ts +++ b/public/app/features/scopes/tests/utils/mocks.ts @@ -1,594 +1,8 @@ -import { Scope, ScopeDashboardBinding, ScopeNode } from '@grafana/data'; import { DataSourceRef } from '@grafana/schema/dist/esm/common/common.gen'; import { getDashboardScenePageStateManager } from 'app/features/dashboard-scene/pages/DashboardScenePageStateManager'; -import { ScopeNavigation } from '../../dashboards/types'; - -export const mocksScopes: Scope[] = [ - { - metadata: { name: 'cloud' }, - spec: { - title: 'Cloud', - filters: [{ key: 'cloud', value: '.*', operator: 'regex-match' }], - }, - }, - { - metadata: { name: 'dev' }, - spec: { - title: 'Dev', - filters: [{ key: 'cloud', value: 'dev', operator: 'equals' }], - }, - }, - { - metadata: { name: 'ops' }, - spec: { - title: 'Ops', - filters: [{ key: 'cloud', value: 'ops', operator: 'equals' }], - }, - }, - { - metadata: { name: 'prod' }, - spec: { - title: 'Prod', - filters: [{ key: 'cloud', value: 'prod', operator: 'equals' }], - }, - }, - { - metadata: { name: 'grafana' }, - spec: { - title: 'Grafana', - filters: [{ key: 'app', value: 'grafana', operator: 'equals' }], - }, - }, - { - metadata: { name: 'mimir' }, - spec: { - title: 'Mimir', - filters: [{ key: 'app', value: 'mimir', operator: 'equals' }], - }, - }, - { - metadata: { name: 'loki' }, - spec: { - title: 'Loki', - filters: [{ key: 'app', value: 'loki', operator: 'equals' }], - }, - }, - { - metadata: { name: 'tempo' }, - spec: { - title: 'Tempo', - filters: [{ key: 'app', value: 'tempo', operator: 'equals' }], - }, - }, - { - metadata: { name: 'dev-env' }, - spec: { - title: 'Development', - filters: [{ key: 'environment', value: 'dev', operator: 'equals' }], - }, - }, - { - metadata: { name: 'prod-env' }, - spec: { - title: 'Production', - filters: [{ key: 'environment', value: 'prod', operator: 'equals' }], - }, - }, -] as const; - -const dashboardBindingsGenerator = ( - scopes: string[], - dashboards: Array<{ dashboardTitle: string; dashboardKey?: string; groups?: string[] }> -) => - scopes.reduce((scopeAcc, scopeTitle) => { - const scope = scopeTitle.toLowerCase().replaceAll(' ', '-').replaceAll('/', '-'); - - return [ - ...scopeAcc, - ...dashboards.reduce((acc, { dashboardTitle, groups, dashboardKey }, idx) => { - dashboardKey = dashboardKey ?? dashboardTitle.toLowerCase().replaceAll(' ', '-').replaceAll('/', '-'); - const group = !groups - ? '' - : groups.length === 1 - ? groups[0] === '' - ? '' - : `${groups[0].toLowerCase().replaceAll(' ', '-').replaceAll('/', '-')}-` - : `multiple${idx}-`; - const dashboard = `${group}${dashboardKey}`; - - return [ - ...acc, - { - metadata: { name: `${scope}-${dashboard}` }, - spec: { - dashboard, - scope, - }, - status: { - dashboardTitle, - groups, - }, - }, - ]; - }, []), - ]; - }, []); - -export const mocksScopeDashboardBindings: ScopeDashboardBinding[] = [ - ...dashboardBindingsGenerator( - ['Grafana'], - [ - { dashboardTitle: 'Data Sources', groups: ['General'] }, - { dashboardTitle: 'Usage', groups: ['General'] }, - { dashboardTitle: 'Frontend Errors', groups: ['Observability'] }, - { dashboardTitle: 'Frontend Logs', groups: ['Observability'] }, - { dashboardTitle: 'Backend Errors', groups: ['Observability'] }, - { dashboardTitle: 'Backend Logs', groups: ['Observability'] }, - { dashboardTitle: 'Usage Overview', groups: ['Usage'] }, - { dashboardTitle: 'Data Sources', groups: ['Usage'] }, - { dashboardTitle: 'Stats', groups: ['Usage'] }, - { dashboardTitle: 'Overview', groups: [''] }, - { dashboardTitle: 'Frontend' }, - { dashboardTitle: 'Stats' }, - ] - ), - ...dashboardBindingsGenerator( - ['Loki', 'Tempo', 'Mimir'], - [ - { dashboardTitle: 'Ingester', groups: ['Components', 'Investigations'] }, - { dashboardTitle: 'Distributor', groups: ['Components', 'Investigations'] }, - { dashboardTitle: 'Compacter', groups: ['Components', 'Investigations'] }, - { dashboardTitle: 'Datasource Errors', groups: ['Observability', 'Investigations'] }, - { dashboardTitle: 'Datasource Logs', groups: ['Observability', 'Investigations'] }, - { dashboardTitle: 'Overview' }, - { dashboardTitle: 'Stats', dashboardKey: 'another-stats' }, - ] - ), - ...dashboardBindingsGenerator( - ['Dev', 'Ops', 'Prod'], - [ - { dashboardTitle: 'Overview', groups: ['Cardinality Management'] }, - { dashboardTitle: 'Metrics', groups: ['Cardinality Management'] }, - { dashboardTitle: 'Labels', groups: ['Cardinality Management'] }, - { dashboardTitle: 'Overview', groups: ['Usage Insights'] }, - { dashboardTitle: 'Data Sources', groups: ['Usage Insights'] }, - { dashboardTitle: 'Query Errors', groups: ['Usage Insights'] }, - { dashboardTitle: 'Alertmanager', groups: ['Usage Insights'] }, - { dashboardTitle: 'Metrics Ingestion', groups: ['Usage Insights'] }, - { dashboardTitle: 'Billing/Usage' }, - ] - ), -] as const; - -export const mocksNodes: ScopeNode[] = [ - { - metadata: { name: 'applications' }, - spec: { - nodeType: 'container', - title: 'Applications', - description: 'Application Scopes', - parentName: '', - }, - }, - { - metadata: { name: 'cloud' }, - spec: { - nodeType: 'container', - title: 'Cloud', - description: 'Cloud Scopes', - disableMultiSelect: true, - linkType: 'scope', - linkId: 'cloud', - parentName: '', - }, - }, - { - metadata: { name: 'applications-grafana' }, - spec: { - nodeType: 'leaf', - title: 'Grafana', - description: 'Grafana', - linkType: 'scope', - linkId: 'grafana', - parentName: 'applications', - }, - }, - { - metadata: { name: 'applications-mimir' }, - spec: { - nodeType: 'leaf', - title: 'Mimir', - description: 'Mimir', - linkType: 'scope', - linkId: 'mimir', - parentName: 'applications', - }, - }, - { - metadata: { name: 'applications-loki' }, - spec: { - nodeType: 'leaf', - title: 'Loki', - description: 'Loki', - linkType: 'scope', - linkId: 'loki', - parentName: 'applications', - }, - }, - { - metadata: { name: 'applications-tempo' }, - spec: { - nodeType: 'leaf', - title: 'Tempo', - description: 'Tempo', - linkType: 'scope', - linkId: 'tempo', - parentName: 'applications', - }, - }, - { - metadata: { name: 'applications-cloud' }, - spec: { - nodeType: 'container', - title: 'Cloud', - description: 'Application/Cloud Scopes', - linkType: 'scope', - linkId: 'cloud', - parentName: 'applications', - }, - }, - { - metadata: { name: 'applications-cloud-dev' }, - spec: { - nodeType: 'leaf', - title: 'Dev', - description: 'Dev', - linkType: 'scope', - linkId: 'dev', - parentName: 'applications-cloud', - }, - }, - { - metadata: { name: 'applications-cloud-ops' }, - spec: { - nodeType: 'leaf', - title: 'Ops', - description: 'Ops', - linkType: 'scope', - linkId: 'ops', - parentName: 'applications-cloud', - }, - }, - { - metadata: { name: 'applications-cloud-prod' }, - spec: { - nodeType: 'leaf', - title: 'Prod', - description: 'Prod', - linkType: 'scope', - linkId: 'prod', - parentName: 'applications-cloud', - }, - }, - { - metadata: { name: 'cloud-dev' }, - spec: { - nodeType: 'leaf', - title: 'Dev', - description: 'Dev', - linkType: 'scope', - linkId: 'dev', - parentName: 'cloud', - }, - }, - { - metadata: { name: 'cloud-ops' }, - spec: { - nodeType: 'leaf', - title: 'Ops', - description: 'Ops', - linkType: 'scope', - linkId: 'ops', - parentName: 'cloud', - }, - }, - { - metadata: { name: 'cloud-prod' }, - spec: { - nodeType: 'leaf', - title: 'Prod', - description: 'Prod', - linkType: 'scope', - linkId: 'prod', - parentName: 'cloud', - }, - }, - { - metadata: { name: 'cloud-applications' }, - spec: { - nodeType: 'container', - title: 'Applications', - description: 'Cloud/Application Scopes', - parentName: 'cloud', - }, - }, - { - metadata: { name: 'cloud-applications-grafana' }, - spec: { - nodeType: 'leaf', - title: 'Grafana', - description: 'Grafana', - linkType: 'scope', - linkId: 'grafana', - parentName: 'cloud-applications', - }, - }, - { - metadata: { name: 'cloud-applications-mimir' }, - spec: { - nodeType: 'leaf', - title: 'Mimir', - description: 'Mimir', - linkType: 'scope', - linkId: 'mimir', - parentName: 'cloud-applications', - }, - }, - { - metadata: { name: 'cloud-applications-loki' }, - spec: { - nodeType: 'leaf', - title: 'Loki', - description: 'Loki', - linkType: 'scope', - linkId: 'loki', - parentName: 'cloud-applications', - }, - }, - { - metadata: { name: 'cloud-applications-tempo' }, - spec: { - nodeType: 'leaf', - title: 'Tempo', - description: 'Tempo', - linkType: 'scope', - linkId: 'tempo', - parentName: 'cloud-applications', - }, - }, - { - metadata: { name: 'environments' }, - spec: { - nodeType: 'container', - title: 'Environments', - description: 'Environment Scopes', - disableMultiSelect: true, - parentName: '', - }, - }, - { - metadata: { name: 'environments-dev' }, - spec: { - nodeType: 'container', - title: 'Development', - description: 'Development Environment', - linkType: 'scope', - linkId: 'dev-env', - parentName: 'environments', - }, - }, - { - metadata: { name: 'environments-prod' }, - spec: { - nodeType: 'container', - title: 'Production', - description: 'Production Environment', - linkType: 'scope', - linkId: 'prod-env', - parentName: 'environments', - }, - }, -] as const; - export const dashboardReloadSpy = jest.spyOn(getDashboardScenePageStateManager(), 'reloadDashboard'); -export const getMock = jest - .fn() - .mockImplementation( - (url: string, params: { parent: string; scope: string[]; query?: string } & Record) => { - if (url.startsWith('/apis/scope.grafana.app/v0alpha1/namespaces/default/find/scope_node_children')) { - return { - items: mocksNodes.filter( - ({ spec: { title, parentName } }) => - parentName === params.parent && title.toLowerCase().includes((params.query ?? '').toLowerCase()) - ), - }; - } - - if (url.startsWith('/apis/scope.grafana.app/v0alpha1/namespaces/default/scopes/')) { - const name = url.replace('/apis/scope.grafana.app/v0alpha1/namespaces/default/scopes/', ''); - - return mocksScopes.find((scope) => scope.metadata.name.toLowerCase() === name.toLowerCase()) ?? {}; - } - - if (url.startsWith('/apis/scope.grafana.app/v0alpha1/namespaces/default/scopenodes/')) { - const name = url.replace('/apis/scope.grafana.app/v0alpha1/namespaces/default/scopenodes/', ''); - - return mocksNodes.find((node) => node.metadata.name === name); - } - - if (url.startsWith('/apis/scope.grafana.app/v0alpha1/namespaces/default/find/scope_dashboard_bindings')) { - return { - items: mocksScopeDashboardBindings.filter(({ spec: { scope: bindingScope } }) => - params.scope.includes(bindingScope) - ), - }; - } - - if (url.startsWith('/apis/scope.grafana.app/v0alpha1/namespaces/default/find/scope_navigations')) { - // Handle subScope fetch requests - if (params.scope && params.scope.includes('mimir')) { - return { - items: subScopeMimirItems, - }; - } - if (params.scope && params.scope.includes('loki')) { - return { - items: subScopeLokiItems, - }; - } - // Return empty for other scopes - return { - items: [], - }; - } - - if (url.startsWith('/api/dashboards/uid/')) { - return {}; - } - - if (url.startsWith('/apis/dashboard.grafana.app/v0alpha1/namespaces/default/dashboards/')) { - return { - metadata: { - name: '1', - }, - }; - } - - return {}; - } - ); - -const generateScopeDashboardBinding = (dashboardTitle: string, groups?: string[], dashboardId?: string) => ({ - metadata: { name: `${dashboardTitle}-name` }, - spec: { - dashboard: `${dashboardId ?? dashboardTitle}-dashboard`, - scope: `${dashboardTitle}-scope`, - }, - status: { - dashboardTitle, - groups, - }, -}); - -export const dashboardWithoutFolder: ScopeDashboardBinding = generateScopeDashboardBinding('Without Folder'); -export const dashboardWithOneFolder: ScopeDashboardBinding = generateScopeDashboardBinding('With one folder', [ - 'Folder 1', -]); -export const dashboardWithTwoFolders: ScopeDashboardBinding = generateScopeDashboardBinding('With two folders', [ - 'Folder 1', - 'Folder 2', -]); -export const alternativeDashboardWithTwoFolders: ScopeDashboardBinding = generateScopeDashboardBinding( - 'Alternative with two folders', - ['Folder 1', 'Folder 2'], - 'With two folders' -); -export const dashboardWithRootFolder: ScopeDashboardBinding = generateScopeDashboardBinding('With root folder', ['']); -export const alternativeDashboardWithRootFolder: ScopeDashboardBinding = generateScopeDashboardBinding( - 'Alternative With root folder', - [''], - 'With root folder' -); -export const dashboardWithRootFolderAndOtherFolder: ScopeDashboardBinding = generateScopeDashboardBinding( - 'With root folder and other folder', - ['', 'Folder 3'] -); - -// Mock subScope navigation items -export const navigationWithSubScope: ScopeNavigation = { - metadata: { name: 'subscope-nav-1' }, - spec: { - scope: 'grafana', - subScope: 'mimir', - url: '/d/subscope-dashboard-1', - }, - status: { - title: 'Mimir Dashboards', - groups: [], // subScope items ignore groups - }, -}; - -export const navigationWithSubScope2: ScopeNavigation = { - metadata: { name: 'subscope-nav-2' }, - spec: { - scope: 'grafana', - subScope: 'mimir', - url: '/d/subscope-dashboard-2', - }, - status: { - title: 'Mimir Overview', - groups: [], - }, -}; - -export const navigationWithSubScopeDifferent: ScopeNavigation = { - metadata: { name: 'subscope-nav-3' }, - spec: { - scope: 'grafana', - subScope: 'loki', - url: '/d/subscope-dashboard-3', - }, - status: { - title: 'Loki Dashboards', - groups: [], - }, -}; - -export const navigationWithSubScopeAndGroups: ScopeNavigation = { - metadata: { name: 'subscope-nav-groups' }, - spec: { - scope: 'grafana', - subScope: 'mimir', - url: '/d/subscope-dashboard-groups', - }, - status: { - title: 'Mimir with Groups', - groups: ['Group1', 'Group2'], // Should be ignored for subScope items - }, -}; - -// Mock items that will be loaded when subScope folder is expanded -export const subScopeMimirItems: ScopeNavigation[] = [ - { - metadata: { name: 'mimir-item-1' }, - spec: { - scope: 'mimir', - url: '/d/mimir-dashboard-1', - }, - status: { - title: 'Mimir Dashboard 1', - groups: ['General'], - }, - }, - { - metadata: { name: 'mimir-item-2' }, - spec: { - scope: 'mimir', - url: '/d/mimir-dashboard-2', - }, - status: { - title: 'Mimir Dashboard 2', - groups: ['Observability'], - }, - }, -]; - -export const subScopeLokiItems: ScopeNavigation[] = [ - { - metadata: { name: 'loki-item-1' }, - spec: { - scope: 'loki', - url: '/d/loki-dashboard-1', - }, - status: { - title: 'Loki Dashboard 1', - groups: ['General'], - }, - }, -]; - export const getDatasource = async (ref: DataSourceRef) => { if (ref.uid === '-- Grafana --') { return { diff --git a/public/app/features/scopes/tests/utils/render.tsx b/public/app/features/scopes/tests/utils/render.tsx index ed126b5b2d7..5a44727f563 100644 --- a/public/app/features/scopes/tests/utils/render.tsx +++ b/public/app/features/scopes/tests/utils/render.tsx @@ -12,8 +12,6 @@ import { DashboardDataDTO, DashboardDTO, DashboardMeta } from 'app/types/dashboa import { defaultScopesServices, ScopesContextProvider } from '../../ScopesContextProvider'; -import { getMock } from './mocks'; - const getDashboardDTO: ( overrideDashboard: Partial, overrideMeta: Partial @@ -208,7 +206,6 @@ export async function renderDashboard( export async function resetScenes(spies: jest.SpyInstance[] = []) { await jest.runOnlyPendingTimersAsync(); jest.useRealTimers(); - getMock.mockClear(); spies.forEach((spy) => spy.mockClear()); cleanup(); } diff --git a/public/app/features/scopes/tests/viewMode.test.ts b/public/app/features/scopes/tests/viewMode.test.ts index 90ba082b734..97fa480f3e2 100644 --- a/public/app/features/scopes/tests/viewMode.test.ts +++ b/public/app/features/scopes/tests/viewMode.test.ts @@ -1,4 +1,6 @@ -import { config } from '@grafana/runtime'; +import { config, setBackendSrv } from '@grafana/runtime'; +import { setupMockServer } from '@grafana/test-utils/server'; +import { backendSrv } from 'app/core/services/backend_srv'; import { DashboardScene } from 'app/features/dashboard-scene/scene/DashboardScene'; import { ScopesService } from '../ScopesService'; @@ -10,18 +12,20 @@ import { expectScopesSelectorClosed, expectScopesSelectorDisabled, } from './utils/assertions'; -import { getDatasource, getInstanceSettings, getMock } from './utils/mocks'; +import { getDatasource, getInstanceSettings } from './utils/mocks'; import { renderDashboard, resetScenes } from './utils/render'; jest.mock('@grafana/runtime', () => ({ __esModule: true, ...jest.requireActual('@grafana/runtime'), useChromeHeaderHeight: jest.fn(), - getBackendSrv: () => ({ get: getMock }), getDataSourceSrv: () => ({ get: getDatasource, getInstanceSettings }), usePluginLinks: jest.fn().mockReturnValue({ links: [] }), })); +setBackendSrv(backendSrv); +setupMockServer(); + describe('View mode', () => { let dashboardScene: DashboardScene; let scopesService: ScopesService; diff --git a/public/app/store/configureStore.ts b/public/app/store/configureStore.ts index 3b7551c2766..afc367a924c 100644 --- a/public/app/store/configureStore.ts +++ b/public/app/store/configureStore.ts @@ -4,6 +4,7 @@ import { Middleware } from 'redux'; import { allMiddleware as allApiClientMiddleware } from '@grafana/api-clients/rtkq'; import { legacyAPI } from 'app/api/clients/legacy'; +import { scopeAPIv0alpha1 } from 'app/api/clients/scope/v0alpha1'; import { browseDashboardsAPI } from 'app/features/browse-dashboards/api/browseDashboardsAPI'; import { publicDashboardApi } from 'app/features/dashboard/api/publicDashboardApi'; import { StoreState } from 'app/types/store'; @@ -40,6 +41,7 @@ export function configureStore(initialState?: Partial) { publicDashboardApi.middleware, browseDashboardsAPI.middleware, legacyAPI.middleware, + scopeAPIv0alpha1.middleware, ...allApiClientMiddleware, ...extraMiddleware ),