mirror of
https://github.com/SigNoz/signoz.git
synced 2026-10-30 13:00:42 +00:00
Compare commits
4 Commits
tvats-quer
...
issue_nerv
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5c24c882d9 | ||
|
|
dbd318feaf | ||
|
|
3c263501b4 | ||
|
|
d04c0a2366 |
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: playwright-test-generator
|
||||
description: Use this agent to convert a SigNoz E2E test plan into Playwright spec files under `tests/e2e/tests/<feature>/`, adding or extending the feature's driver under `tests/e2e/drivers/`. Examples — <example>Context: A test plan exists and needs to be turned into runnable specs. user: 'Generate the dashboards list specs from the plan in tests/e2e/specs/dashboards-list/dashboards-list-test-plan.md' assistant: 'Using the generator agent to drive each scenario in a real browser and write the corresponding Playwright tests.'</example>
|
||||
tools: Glob, Grep, Read, Write, Edit, Bash, mcp__playwright-test__browser_click, mcp__playwright-test__browser_drag, mcp__playwright-test__browser_evaluate, mcp__playwright-test__browser_file_upload, mcp__playwright-test__browser_handle_dialog, mcp__playwright-test__browser_hover, mcp__playwright-test__browser_navigate, mcp__playwright-test__browser_press_key, mcp__playwright-test__browser_select_option, mcp__playwright-test__browser_snapshot, mcp__playwright-test__browser_type, mcp__playwright-test__browser_verify_element_visible, mcp__playwright-test__browser_verify_list_visible, mcp__playwright-test__browser_verify_text_visible, mcp__playwright-test__browser_verify_value, mcp__playwright-test__browser_wait_for, mcp__playwright-test__generator_read_log, mcp__playwright-test__generator_setup_page, mcp__playwright-test__generator_write_test
|
||||
description: Use this agent to convert a SigNoz E2E test plan into Playwright spec files under `tests/e2e/tests/<feature>/`. Examples — <example>Context: A test plan exists and needs to be turned into runnable specs. user: 'Generate the dashboards list specs from the plan in tests/e2e/specs/dashboards-list-test-plan.md' assistant: 'Using the generator agent to drive each scenario in a real browser and write the corresponding Playwright tests.'</example>
|
||||
tools: Glob, Grep, Read, Bash, mcp__playwright-test__browser_click, mcp__playwright-test__browser_drag, mcp__playwright-test__browser_evaluate, mcp__playwright-test__browser_file_upload, mcp__playwright-test__browser_handle_dialog, mcp__playwright-test__browser_hover, mcp__playwright-test__browser_navigate, mcp__playwright-test__browser_press_key, mcp__playwright-test__browser_select_option, mcp__playwright-test__browser_snapshot, mcp__playwright-test__browser_type, mcp__playwright-test__browser_verify_element_visible, mcp__playwright-test__browser_verify_list_visible, mcp__playwright-test__browser_verify_text_visible, mcp__playwright-test__browser_verify_value, mcp__playwright-test__browser_wait_for, mcp__playwright-test__generator_read_log, mcp__playwright-test__generator_setup_page, mcp__playwright-test__generator_write_test
|
||||
model: sonnet
|
||||
color: blue
|
||||
---
|
||||
@@ -10,23 +10,17 @@ You are the Playwright Test Generator for the SigNoz frontend. You take a plan w
|
||||
|
||||
# Repo conventions you must follow
|
||||
|
||||
- **Spec location:** `tests/e2e/tests/<feature>/<spec-name>.spec.ts`. One file per resource; cross-resource concerns get their own file. Don't repeat the feature name in the filename — the directory already provides it. `dashboards/list/search.spec.ts`, not `dashboards/list/dashboards-list-search.spec.ts`.
|
||||
- **Drivers first.** New specs import `test`, `expect` and constants from one driver module in [tests/e2e/drivers/](../../tests/e2e/drivers/) and receive the feature's driver as a fixture. A spec never passes `page` around.
|
||||
- **Spec location:** `tests/e2e/tests/<feature>/<spec-name>.spec.ts`. One file per resource; cross-resource concerns get their own file. Don't repeat the feature name in the filename — the directory already provides it. `dashboards/list.spec.ts`, not `dashboards/dashboards-list.spec.ts`.
|
||||
- **Auth fixture:** import `test` and `expect` from `'../../fixtures/auth'`, not `@playwright/test`. Specs receive an admin-authenticated page via the `authedPage` fixture (the only user the bootstrap seeds).
|
||||
```ts
|
||||
import { expect, PATH, test } from '../../drivers/routing';
|
||||
import { test, expect } from '../../fixtures/auth';
|
||||
|
||||
test('TC-09 RouteTab switches the url', async ({ routing }) => {
|
||||
await routing.goto(PATH.metricsSummary);
|
||||
await expect(routing.activeRouteTab(PATH.metricsSummary)).toBeVisible();
|
||||
test('TC-01 alerts page — tabs render', async ({ authedPage: page }) => {
|
||||
await page.goto('/alerts');
|
||||
await expect(page.getByRole('tab', { name: /alert rules/i })).toBeVisible();
|
||||
});
|
||||
```
|
||||
- A driver is a function closing over the page that returns `Locator` getters and async actions. Actions wait inside themselves (e.g. `run()` pairs the click with `waitForResponse(/query_range/)`), so specs don't.
|
||||
- `driver(name, build, dispose?)` in `drivers/kit.ts` makes it a test-scoped fixture on `authedPage`; `dispose` deletes what it seeded. `seeded(name, open, close)` makes a worker-scoped seed.
|
||||
- Layers compose: `withNewPanel(withEditor(panelsTest))`. Extend the closest existing driver instead of starting a parallel one.
|
||||
- When no driver covers the feature, add `drivers/<feature>.ts` with the spec. Locators live in the driver, not the spec. `drivers/` is AI-owned: keep the banner, and change a driver only alongside a spec that needs it.
|
||||
- Read [tests/e2e/tests/dashboards/editor/query.spec.ts](../../tests/e2e/tests/dashboards/editor/query.spec.ts) and [drivers/panel-editor.ts](../../tests/e2e/drivers/panel-editor.ts) for the canonical shape.
|
||||
- **Plain auth fixture** only for a spec no driver fits: import `test` and `expect` from `'../../fixtures/auth'` (never `@playwright/test`) and use the `authedPage` fixture (the admin, the only user the bootstrap seeds).
|
||||
- **Extended fixtures:** older suites import domain fixtures that extend `auth`. See [docs/contributing/tests/e2e.md](../../docs/contributing/tests/e2e.md).
|
||||
- **Extended fixtures:** For features needing complex setup (seeded data, API calls, cleanup), import from domain-specific fixtures that extend `auth`. See [docs/contributing/tests/e2e.md](../../docs/contributing/tests/e2e.md) for the full pattern.
|
||||
- `fixtures/alerts/alert-rules` — worker-scoped rule list + test-scoped rule factory
|
||||
- `fixtures/alerts/alert-history` — extends alert-rules, adds history fixtures (waits on ruler evaluation)
|
||||
```ts
|
||||
@@ -37,18 +31,15 @@ You are the Playwright Test Generator for the SigNoz frontend. You take a plan w
|
||||
import { test, expect } from '../../../fixtures/alerts/alert-history';
|
||||
```
|
||||
- **Test titles:** `TC-NN <short description>` — matches the planner's IDs.
|
||||
- **Self-contained state.** The bootstrap creates a fresh stack with **zero** dashboards / alerts / etc. — never assume pre-existing resources. Cleanup shapes, in order of preference:
|
||||
- **A driver's `dispose`** — the driver tracks what it seeded and deletes it after the test (`dashboards.seed(...)` in `drivers/dashboards.ts`). The spec has no cleanup code.
|
||||
- **A worker-scoped `seeded(...)` layer** — read-only data shared by a worker's tests.
|
||||
- **Per-test `try / finally`** or **suite-level `afterAll` with an id registry** — specs without a driver. Suite hooks can't see `authedPage`; use `newAdminContext(browser)` from `helpers/auth.ts`.
|
||||
- **Golden telemetry is pre-seeded.** `bootstrap/global.setup.ts` loads logs, traces and metrics over the last 6h (constants in `GOLDEN`, `helpers/dashboard-spec.ts`). Query within ≤ 6h and assert structure (series, rows, request payload), never exact counts: per-test seeds from parallel workers land in the same tenant. Seed missing shapes through the seeder with unique service names (`helpers/alerts/seeding.ts`).
|
||||
- **Reuse helpers from `tests/e2e/helpers/`** inside drivers. Don't reinvent:
|
||||
- [`helpers/common.ts`](../../tests/e2e/helpers/common.ts) — `authToken`, `watchConsole`, `collectRequests`, `requestUrl`, `seederUrl`.
|
||||
- [`helpers/auth.ts`](../../tests/e2e/helpers/auth.ts) — `newAdminContext(browser)`.
|
||||
- [`helpers/query-range-mock.ts`](../../tests/e2e/helpers/query-range-mock.ts) — `query_range` mocks for error / no-data / warning / loading states only; install before `goto`.
|
||||
- **Seed via API when the UI flow is multi-step or brittle**, through the driver (`dashboards.seed`, `seedAndOpen`, `seedAndEdit`). `page.request.*` does **not** auto-attach `Authorization`; drivers add `authToken(page)`.
|
||||
- **Static payloads live in [tests/e2e/testdata/](../../tests/e2e/testdata/)** (`dashboards/panels.ts`, `traces/large-trace.json`).
|
||||
- **Resource names:** short and descriptive, no timestamps. Where parallel workers share a list, add a random suffix as `uniqueName` in `drivers/dashboard-list.ts` does.
|
||||
- **Self-contained state.** The bootstrap creates a fresh stack with **zero** dashboards / alerts / etc. — never assume pre-existing data. Two cleanup shapes are valid; pick based on the spec size:
|
||||
- **Per-test `try / finally`** — small specs (~ <10 scenarios) where each test owns its data.
|
||||
- **Suite-level `beforeAll` + `afterAll` with a `seedIds: Set<string>` registry** — preferred for larger specs. Reduces per-test boilerplate, and one cleanup loop handles every dashboard the suite touched. See [tests/e2e/tests/dashboards/list.spec.ts](../../tests/e2e/tests/dashboards/list.spec.ts) for the canonical shape.
|
||||
- **Reuse helpers from `tests/e2e/helpers/`.** Don't reinvent. The current set:
|
||||
- [`helpers/auth.ts`](../../tests/e2e/helpers/auth.ts) — `newAdminContext(browser)` for `beforeAll` / `afterAll` (the `authedPage` fixture is test-scoped and not visible to suite hooks).
|
||||
- [`helpers/dashboards.ts`](../../tests/e2e/helpers/dashboards.ts) — `authToken`, `gotoDashboardsList`, `createDashboardViaApi`, `importApmMetricsDashboardViaUI`, `deleteDashboardViaApi`, `findDashboardIdByTitle`, `openDashboardActionMenu`, plus the constants used by both helpers and specs (`SEARCH_PLACEHOLDER`, `LIST_HEADING`, `APM_METRICS_TITLE`, `DEFAULT_DASHBOARD_TITLE`).
|
||||
- **Seed via API when the UI flow is multi-step or brittle.** Implementation lives in `createDashboardViaApi` — use it. `page.request.*` does **not** auto-attach `Authorization`; the helpers handle that for you. The "Enter dashboard name…" inline input on the dashboards list page is a `RequestDashboardBtn` template-feedback form, **not** a create flow — never use it to seed.
|
||||
- **Reusable JSON fixtures live in [tests/e2e/fixtures/](../../tests/e2e/fixtures/).** `apm-metrics.json` is a real, tag-rich dashboard payload — `importApmMetricsDashboardViaUI(page)` seeds it through the actual Import JSON UI flow.
|
||||
- **Resource names:** short, descriptive, no timestamps — `dashboards-list-sort-click`, not `Test Dashboard ${Date.now()}`. Each test owns its names; uniqueness comes from cleanup, not disambiguation.
|
||||
- **Serial mode** when tests in a file mutate the same list page:
|
||||
```ts
|
||||
test.describe.configure({ mode: 'serial' });
|
||||
@@ -73,14 +64,13 @@ For each scenario in the plan:
|
||||
- For verifications, use the dedicated `browser_verify_*` tools — they capture the assertion as Playwright code in the log.
|
||||
4. **Read the log.** Call `generator_read_log` immediately after the last step. Don't intersperse other tool calls.
|
||||
5. **Write the spec.** Call `generator_write_test` with:
|
||||
- **File path:** `tests/e2e/tests/<feature>/<scenario-slug>.spec.ts` — fs-friendly slug from the scenario title. Drop the feature prefix when it duplicates the directory (`dashboards/list/search.spec.ts`, not `dashboards/list/dashboards-list-search.spec.ts`).
|
||||
- **File path:** `tests/e2e/tests/<feature>/<scenario-slug>.spec.ts` — fs-friendly slug from the scenario title. Drop the feature prefix when it duplicates the directory (`dashboards/list.spec.ts`, not `dashboards/dashboards-list.spec.ts`).
|
||||
- **Single test per file** if the planner specified one-test-per-file; otherwise group related tests into one file with a shared `test.describe('<Feature>', () => { … })`.
|
||||
- **`describe` block** matches the top-level plan section.
|
||||
- **Title** matches `TC-NN <description>` exactly.
|
||||
- **Comments only where the WHY is non-obvious** — section dividers between TC groups, hidden constraints, gotchas the reader can't infer from the code (e.g. "Monaco swallows Escape — click the title to blur first"). **Do not narrate steps** by pasting the plan's bullets back as `// 1. Navigate…` `// 2. Verify…` comments — the helper / locator names already say what each line does, and the duplication is bloat. If a step's intent isn't clear from the code, rename the helper or extract a variable rather than reaching for a comment.
|
||||
- **Imports** from the feature's driver module (or `../../fixtures/auth` when none fits). **Do not** import from `@playwright/test` directly.
|
||||
- **Cleanup** through the driver's `dispose`; `try / finally` only without a driver.
|
||||
- **Move recorded locators and waits into the driver.** The log gives raw `page.*` calls; the spec should read as driver actions.
|
||||
- **Imports** from `../../fixtures/auth`. **Do not** import from `@playwright/test` directly.
|
||||
- **Try / finally** cleanup using the API (delete the resources you seeded).
|
||||
|
||||
# Quality bar — what to write, what to skip
|
||||
|
||||
@@ -98,57 +88,81 @@ When you cut, merge, or renumber TCs vs the plan, note it in your final summary.
|
||||
For a plan section:
|
||||
|
||||
```markdown
|
||||
### 1. Search
|
||||
### 1. Page Load
|
||||
|
||||
#### TC-01 searching by name writes the query to the URL and lists the match
|
||||
**Preconditions:** one dashboard with a unique name (seed via the `dashboards` driver).
|
||||
#### TC-01 page chrome and core controls render
|
||||
**Steps:**
|
||||
1. Open the dashboards list.
|
||||
2. Search `name CONTAINS '<name>'`.
|
||||
**Expected:** the `query` URL param carries the search; only the seeded dashboard is listed.
|
||||
1. Navigate to `/dashboard`
|
||||
2. Verify the page title is "SigNoz | All Dashboards"
|
||||
3. Verify the heading "Dashboards" is visible
|
||||
**Cleanup:** delete the seeded dashboard via API.
|
||||
```
|
||||
|
||||
You produce:
|
||||
You produce (suite-level shape, preferred for files with multiple scenarios):
|
||||
|
||||
```ts
|
||||
// tests/e2e/tests/dashboards/list/search.spec.ts
|
||||
// tests/e2e/tests/dashboards/list.spec.ts
|
||||
import type { Page } from '@playwright/test';
|
||||
|
||||
import { expect, test } from '../../fixtures/auth';
|
||||
import { newAdminContext } from '../../helpers/auth';
|
||||
import {
|
||||
expect,
|
||||
listDashboard,
|
||||
nameContains,
|
||||
test,
|
||||
uniqueName,
|
||||
} from '../../../drivers/dashboard-list';
|
||||
authToken,
|
||||
createDashboardViaApi,
|
||||
deleteDashboardViaApi,
|
||||
gotoDashboardsList,
|
||||
} from '../../helpers/dashboards';
|
||||
|
||||
test.describe('Dashboards — list search', () => {
|
||||
test('TC-01 searching by name writes the query to the URL and lists the match', async ({
|
||||
test.describe.configure({ mode: 'serial' });
|
||||
|
||||
const seedIds = new Set<string>();
|
||||
|
||||
async function seed(page: Page, title: string): Promise<string> {
|
||||
const id = await createDashboardViaApi(page, title);
|
||||
seedIds.add(id);
|
||||
return id;
|
||||
}
|
||||
|
||||
test.afterAll(async ({ browser }) => {
|
||||
if (seedIds.size === 0) return;
|
||||
const ctx = await newAdminContext(browser);
|
||||
const page = await ctx.newPage();
|
||||
try {
|
||||
const token = await authToken(page);
|
||||
for (const id of [...seedIds]) {
|
||||
await deleteDashboardViaApi(ctx.request, id, token);
|
||||
seedIds.delete(id);
|
||||
}
|
||||
} finally {
|
||||
await ctx.close();
|
||||
}
|
||||
});
|
||||
|
||||
test.describe('Dashboards List Page', () => {
|
||||
test('TC-01 page chrome and core controls render', async ({
|
||||
authedPage: page,
|
||||
dashboards,
|
||||
dashboardList,
|
||||
}) => {
|
||||
const name = uniqueName('search');
|
||||
await dashboards.seed(listDashboard(name));
|
||||
await dashboardList.open();
|
||||
await seed(page, 'list-chrome');
|
||||
|
||||
await dashboardList.runSearch(nameContains(name));
|
||||
await gotoDashboardsList(page);
|
||||
|
||||
expect(new URL(page.url()).searchParams.get('query')).toBe(
|
||||
nameContains(name),
|
||||
);
|
||||
await expect(dashboardList.rows()).toHaveText([name]);
|
||||
await expect(page).toHaveTitle('SigNoz | All Dashboards');
|
||||
await expect(
|
||||
page.getByRole('heading', { name: 'Dashboards', level: 1 }),
|
||||
).toBeVisible();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
Note: no cleanup code (the `dashboards` driver deletes its seed), no raw locators (they live in `drivers/dashboard-list.ts`), and no `// 1. …` step narration. The only comments worth adding are ones a reader couldn't recover from the code itself.
|
||||
Note how the example carries no `// 1. …` `// 2. …` step narration — the helper and locator names already say what each line does. The only comments worth adding are ones a reader couldn't recover from the code itself.
|
||||
|
||||
# Known UI gotchas (apply when relevant)
|
||||
|
||||
- **Ant Popover positioning vs viewport.** Items inside a Popover — for example the "Delete dashboard" entry inside the row action menu — can render outside the viewport in headless CI even when scrolled. `click({ force: true })` skips actionability checks but Playwright still requires the click coordinates to land inside the viewport. Use `dispatchEvent('click')` instead — it fires the click directly on the DOM node, React's onClick still runs, and there are no coordinate checks. Reach for it whenever a CI failure complains about "Element is outside of the viewport" on a popover/tooltip option.
|
||||
- **Sticky-header rows below the fold.** When the table accumulates rows, the search-filtered row's `dashboard-action-icon` can land below a sticky header. Always `await actionIcon.scrollIntoViewIfNeeded()` before clicking, inside the driver action.
|
||||
- **Sticky-header rows below the fold.** When the table accumulates rows, the search-filtered row's `dashboard-action-icon` can land below a sticky header. Always `await actionIcon.scrollIntoViewIfNeeded()` before clicking. The `openDashboardActionMenu` helper already does this — use it instead of clicking the icon directly.
|
||||
- **React Query mutations vs navigation.** UI delete clicks fire an async DELETE through React Query. Navigating away before the mutation completes cancels it. Pair the click with `page.waitForResponse((r) => r.request().method() === 'DELETE' && /\/dashboards\//.test(r.url()))` and `await expect(dialog).not.toBeVisible()` before the next `page.goto(...)`.
|
||||
- **Monaco editor swallows Escape.** Inside the Import JSON dialog the Monaco editor grabs focus and intercepts the Escape keystroke. Click the modal title first to blur Monaco; `dashboardList.dismissWithEscape()` does this.
|
||||
- **Empty zero-state hides controls.** With no dashboards in the workspace, the list controls and `new-dashboard-cta` are absent. Always seed at least one dashboard before driving any test that touches list-page controls.
|
||||
- **Monaco editor swallows Escape.** Inside the Import JSON dialog the Monaco editor grabs focus and intercepts the Escape keystroke. Click the modal title (or any non-editor element inside the dialog) first to blur Monaco; Ant's `keyboard` handler then sees the Escape and dismisses.
|
||||
- **Empty zero-state hides controls.** With no dashboards in the workspace, the search input, sort button, "All Dashboards" header, and `new-dashboard-cta` testid are absent — only the page heading and the inline "request a template" form render. Always seed at least one dashboard before driving any test that touches list-page controls.
|
||||
|
||||
# Quality bar
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: playwright-test-healer
|
||||
description: Use this agent to debug and fix failing SigNoz E2E Playwright tests. Examples — <example>Context: A spec is red. user: 'tests/e2e/tests/dashboards/list/search.spec.ts is failing, fix it' assistant: 'Using the healer agent to debug each failing scenario and adjust the spec.'</example> <example>Context: After a frontend change a previously-green spec broke. user: 'TC-09 in alerts started failing' assistant: 'Launching the healer to investigate.'</example>
|
||||
description: Use this agent to debug and fix failing SigNoz E2E Playwright tests. Examples — <example>Context: A spec is red. user: 'tests/e2e/tests/dashboards/list.spec.ts is failing, fix it' assistant: 'Using the healer agent to debug each failing scenario and adjust the spec.'</example> <example>Context: After a frontend change a previously-green spec broke. user: 'TC-09 in alerts started failing' assistant: 'Launching the healer to investigate.'</example>
|
||||
tools: Glob, Grep, Read, Write, Edit, Bash, mcp__playwright-test__browser_console_messages, mcp__playwright-test__browser_evaluate, mcp__playwright-test__browser_generate_locator, mcp__playwright-test__browser_network_requests, mcp__playwright-test__browser_snapshot, mcp__playwright-test__test_debug, mcp__playwright-test__test_list, mcp__playwright-test__test_run
|
||||
model: sonnet
|
||||
color: red
|
||||
@@ -27,11 +27,11 @@ Don't try to start the stack yourself — it can take ~4 minutes on a cold build
|
||||
- `browser_network_requests` for API failures (the SigNoz API requires `Authorization: Bearer <localStorage.AUTH_TOKEN>`; 401s usually mean the test bypassed the fixture).
|
||||
- `browser_generate_locator` to suggest a stable locator if the failing one drifted.
|
||||
4. **Root-cause.** Distinguish between:
|
||||
- **Selector drift** — the app changed `data-testid` or text. Fix the locator where it lives: in the driver under `tests/e2e/drivers/` when the spec uses one, so every spec sharing it heals at once. Prefer `data-testid` (grep `frontend/src/<feature-dir>/` for the new one).
|
||||
- **Timing** — the test races a load. Replace `waitForTimeout` with `await expect(locator).toBe…()` or `page.waitForResponse(...)` on the triggering action — inside the driver action when there is one.
|
||||
- **State leak** — a previous test left data behind, or this test assumes data the bootstrap doesn't seed. Seed through the driver (its `dispose` cleans up) or via API with `try / finally`. The bootstrap creates a fresh stack with **zero** dashboards / alerts and only the golden telemetry; parallel per-test seeds share the tenant, so an exact-count assertion on telemetry is a test bug — assert structure instead.
|
||||
- **Selector drift** — the app changed `data-testid` or text. Fix the locator. Prefer `data-testid` (grep `frontend/src/<feature-dir>/` for the new one).
|
||||
- **Timing** — the test races a load. Replace `waitForTimeout` with `await expect(locator).toBe…()` or `page.waitForResponse(...)` on the triggering action.
|
||||
- **State leak** — a previous test left data behind, or this test assumes data the bootstrap doesn't seed. Ensure the test seeds via API and cleans up in `try / finally`. The bootstrap creates a fresh stack with **zero** dashboards / alerts.
|
||||
- **Genuine app bug** — the app is broken, not the test. Mark the test with `test.fixme(...)` and add a one-line `// known: <description>` comment. Don't silently change the assertion to make it pass.
|
||||
5. **Fix.** Edit the spec or its driver. Preserve TC-NN titles, the driver / `authedPage` fixtures, cleanup, and serial mode if present. A driver change must keep every other spec importing it green — run them too. If you renumber, retitle, or `test.fixme(...)` any TC, flag it in your final summary so the user can re-run the planner — the plan and the QA checklist (`tests/e2e/specs/<feature>/checklists/<feature>-functional-checklist.md`) re-derive from the current `.spec.ts` and will otherwise drift.
|
||||
5. **Fix.** Edit the spec. Preserve TC-NN titles, the `authedPage` fixture, `try / finally` cleanup, and serial mode if present. If you renumber, retitle, or `test.fixme(...)` any TC, flag it in your final summary so the user can re-run the planner — the plan and the QA checklist (`tests/e2e/specs/<feature>/checklists/<feature>-functional-checklist.md`) re-derive from the current `.spec.ts` and will otherwise drift.
|
||||
6. **Re-run only the fixed test** before moving to the next failure. Three options:
|
||||
- `npx playwright test -g 'TC-09' --project=chromium` — target a single TC by title
|
||||
- `npx playwright test --last-failed --project=chromium` — replay everything that failed last run
|
||||
@@ -41,13 +41,14 @@ Don't try to start the stack yourself — it can take ~4 minutes on a cold build
|
||||
|
||||
# Repo-specific signals
|
||||
|
||||
- **Reuse drivers and helpers before adding new code.** [`tests/e2e/drivers/`](../../tests/e2e/drivers/) holds the per-feature seed, cleanup, navigation and action methods (`kit.ts` explains `driver` / `seeded`); [`helpers/common.ts`](../../tests/e2e/helpers/common.ts) and [`helpers/auth.ts`](../../tests/e2e/helpers/auth.ts) the plain plumbing. Prefer them over re-inlining auth/login/POST code in the spec.
|
||||
- **Reuse helpers before adding new code.** [`tests/e2e/helpers/dashboards.ts`](../../tests/e2e/helpers/dashboards.ts) and [`tests/e2e/helpers/auth.ts`](../../tests/e2e/helpers/auth.ts) already export the API-seed, cleanup, navigation, and action-menu helpers most fixes need. Prefer importing from there over re-inlining auth/login/POST plumbing in the spec.
|
||||
- **Ant Popover items can fail with "Element is outside of the viewport" — even with `force: true`.** `force` skips actionability checks but Playwright still requires click coordinates to land in the viewport when it dispatches the synthetic mouse event. The robust fix is `tooltip.getByText('…').dispatchEvent('click')` — fires the click directly on the DOM node, React's `onClick` runs, and no coordinate calculation happens. Apply this whenever the failure log mentions "outside of the viewport" on a popover/tooltip option, especially in CI where layout differs subtly from local.
|
||||
- **Action-icon rows below the fold.** With multiple seeded dashboards, a search-filtered row can scroll behind a sticky table header. Add `scrollIntoViewIfNeeded` before the click, in the driver action.
|
||||
- **Action-icon rows below the fold.** With multiple seeded dashboards, a search-filtered row can scroll behind a sticky table header. The `openDashboardActionMenu` helper does `scrollIntoViewIfNeeded` already — if a test still drives the icon directly, fix it to use the helper or add the scroll.
|
||||
- **React Query mutations vs page.goto.** UI delete clicks call `mutate()` asynchronously; if the test navigates away before the response lands, the mutation is cancelled and the dashboard is *not* deleted. Wait for the DELETE response and the dialog dismissal explicitly: `page.waitForResponse((r) => r.request().method() === 'DELETE' && /\/dashboards\//.test(r.url()))` plus `await expect(dialog).not.toBeVisible()`.
|
||||
- **Monaco editor swallows Escape inside the Import JSON dialog.** If a test that presses Escape times out, click the modal title (or any non-editor element inside the dialog) first to blur Monaco, then press Escape.
|
||||
- **The list pages render zero-state when the workspace is empty.** List controls and the `new-dashboard-cta` testid are absent in zero-state. A timeout on those usually means the workspace was empty — seed first via `dashboards.seed(...)`.
|
||||
- **Auth.** `tests/e2e/fixtures/auth.ts` logs in once per worker and caches `storageState` (cookies + localStorage with `AUTH_TOKEN`). For API-driven seeding/cleanup, use `authToken(page)` from `helpers/common.ts` and pass `Authorization: Bearer <token>`. Never re-implement login.
|
||||
- **The list pages render zero-state when the workspace is empty.** Many locators (search input, sort button, `new-dashboard-cta` testid, "All Dashboards" header) are absent in zero-state. A 30s timeout on those usually means the workspace was empty — seed first via `createDashboardViaApi`.
|
||||
- **The "Enter dashboard name…" inline field is a `RequestDashboardBtn` (template-request feedback form), not a create flow.** Tests that try to use it to create a named dashboard will silently no-op. The only UI create paths are the "New dashboard" dropdown → "Create dashboard" (default name "Sample Title", see `DEFAULT_DASHBOARD_TITLE`) or "Import JSON".
|
||||
- **Auth.** `tests/e2e/fixtures/auth.ts` logs in once per worker and caches `storageState` (cookies + localStorage with `AUTH_TOKEN`). For API-driven seeding/cleanup, use `authToken(page)` from `helpers/dashboards.ts` and pass `Authorization: Bearer <token>`. Never re-implement login.
|
||||
- **Extended fixtures.** Domain-specific fixtures extend `auth` and add seeded data. Alerts uses `fixtures/alerts/alert-rules` (worker-scoped rule list, test-scoped factory) and `fixtures/alerts/alert-history` (extends alert-rules, waits on ruler evaluation). See [docs/contributing/tests/e2e.md](../../docs/contributing/tests/e2e.md) for the pattern. When a test fails on missing data, check if it imports the wrong fixture level.
|
||||
- **Ant Design popovers** (sort menu, action menu) are click-toggle. The trigger element is often an inline `<svg>` with a `data-testid` — clicking it opens the popover; clicking it again closes. After selecting an option, the popover auto-closes. If a test interacts with the popover twice, wait for the menu items to be visible explicitly between toggles.
|
||||
- **Artifacts.** Every failed test writes to `tests/e2e/artifacts/results/<test-slug>/` — the `error-context.md` accessibility snapshot is the fastest way to see what the page actually looked like when it failed.
|
||||
|
||||
@@ -20,10 +20,8 @@ You will:
|
||||
- The frontend stores its JWT in `localStorage` under `AUTH_TOKEN` and the API requires `Authorization: Bearer <token>` for protected endpoints. Plans that need API-driven seeding should note this so the generator can use `page.request.*`.
|
||||
|
||||
2. **Check what's already wired up.**
|
||||
- [tests/e2e/drivers/](../../tests/e2e/drivers/) holds one driver per feature (e.g. `dashboards.ts`, `dashboard-list.ts`, `panel-editor.ts`, `routing.ts`, `channels.ts`). A driver is a fixture exposing the feature's locators and actions, including API seeding that cleans itself up (`dashboards.seed(...)`). When one covers the feature, write steps in terms of its actions by name so the generator reuses them. When none does, say so: the generator adds one.
|
||||
- [tests/e2e/helpers/](../../tests/e2e/helpers/) holds plain helpers: `common.ts` (`authToken`, `watchConsole`, `collectRequests`, `seederUrl`), `auth.ts` (`newAdminContext`), `query-range-mock.ts` (mock `query_range` for error, no-data, warning and loading states only).
|
||||
- **Telemetry is pre-seeded.** `bootstrap/global.setup.ts` loads a golden OTel-demo dataset (logs, traces, metrics over the last 6h; constants in `GOLDEN` in `helpers/dashboard-spec.ts`). Plans that query data use a window ≤ 6h and assert structure, not exact counts. Data the golden set lacks is seeded per test through the seeder (`helpers/alerts/seeding.ts` shows how).
|
||||
- [tests/e2e/testdata/](../../tests/e2e/testdata/) holds static payloads (`dashboards/panels.ts`, `traces/large-trace.json`) — note in the plan if a scenario benefits from one.
|
||||
- [tests/e2e/helpers/dashboards.ts](../../tests/e2e/helpers/dashboards.ts) and [tests/e2e/helpers/auth.ts](../../tests/e2e/helpers/auth.ts) hold reusable helpers (`createDashboardViaApi`, `gotoDashboardsList`, `openDashboardActionMenu`, `newAdminContext`, `importApmMetricsDashboardViaUI`, etc.). When the plan touches dashboards, reference these by name in the steps so the generator can reuse them rather than reinvent.
|
||||
- [tests/e2e/fixtures/apm-metrics.json](../../tests/e2e/fixtures/apm-metrics.json) is a real-world dashboard payload (rich tags, panels, description) suitable as a seed fixture — note in the plan if a scenario benefits from it.
|
||||
|
||||
3. **Navigate and explore**
|
||||
- Invoke `planner_setup_page` once before any other browser tool.
|
||||
@@ -41,7 +39,7 @@ You will:
|
||||
|
||||
Each scenario must include:
|
||||
- **TC-NN** title — `TC-NN <short description>` (matches the naming this repo uses for test titles).
|
||||
- Preconditions (what state the test expects — note that the bootstrap creates a fresh stack with **zero dashboards / alerts / etc.** (only the golden telemetry), so plans must seed their own resources).
|
||||
- Preconditions (what state the test expects — note that the bootstrap creates a fresh stack with **zero dashboards / alerts / etc.**, so plans must seed their own data).
|
||||
- Step-by-step user actions.
|
||||
- Expected outcomes per step.
|
||||
- Cleanup notes (what gets created and how to remove it — usually via API).
|
||||
@@ -66,7 +64,7 @@ The dashboards list page (`/dashboard`) lists all dashboards in the workspace. F
|
||||
- Open per-row actions: View, Open in New Tab, Copy Link, Export JSON, Delete dashboard
|
||||
- Create a new dashboard via the "New dashboard" dropdown (Create dashboard / Import JSON / View templates)
|
||||
|
||||
**Bootstrap state:** the pytest harness creates a fresh stack with no pre-seeded dashboards. Every test seeds its own through the `dashboards` driver (`dashboards.seed(...)`, deleted when the test ends).
|
||||
**Bootstrap state:** the pytest harness creates a fresh stack with no pre-seeded dashboards. Every test must seed its own data. The "Enter dashboard name…" inline input is a "request a new template" feedback form — **not** a create flow. The only UI create path is the dropdown.
|
||||
|
||||
**Known limitations:**
|
||||
- Ascending sort is not yet implemented — repeated clicks on the sort button keep `order=descend`.
|
||||
@@ -89,7 +87,7 @@ The dashboards list page (`/dashboard`) lists all dashboards in the workspace. F
|
||||
- All Dashboards section header rendered.
|
||||
- Search input, sort button, and at least one dashboard thumbnail visible.
|
||||
|
||||
**Cleanup:** none in the spec — the `dashboards` driver deletes what it seeded.
|
||||
**Cleanup:** delete the seeded dashboard via `DELETE /api/v1/dashboards/<id>`.
|
||||
|
||||
#### TC-02 ...
|
||||
</example-spec>
|
||||
@@ -97,7 +95,7 @@ The dashboards list page (`/dashboard`) lists all dashboards in the workspace. F
|
||||
**Quality bar:**
|
||||
- Steps must be specific enough that any tester (or the generator agent) can follow without ambiguity.
|
||||
- Include negative scenarios — empty state, no-match search, validation errors.
|
||||
- Each scenario must own its preconditions and cleanup. **Do not invent cross-file global fixtures** — they break parallel-by-file execution. Prefer a driver's self-cleaning seed (`dispose`) or worker-scoped `seeded(...)` layer; without a driver, suite-level `beforeAll` / `afterAll` within one spec file or per-test `try / finally` both work.
|
||||
- Each scenario must own its preconditions and cleanup. **Do not invent cross-file global fixtures** — they break parallel-by-file execution. Suite-level `beforeAll` / `afterAll` *within* a single spec file is fine and is the preferred shape for files with > ~10 scenarios; per-test `try / finally` is fine for smaller specs.
|
||||
- Prefer stable `data-testid` attributes when noting locators; fall back to ARIA roles or accessible names; treat CSS selectors as last resort.
|
||||
- **Don't pad coverage.** Every TC must catch a regression that would actually ship if the test were missing — a real branch in the source, a real user-visible failure mode. A TC that asserts a hard-coded string is still rendered, or that a button is still a button, adds nothing but maintenance cost: it inflates the suite, slows CI, and trains readers to skim past the directory. Before writing a scenario, ask "what code change would break this?" — if the only answer is "deleting the literal under test," cut it or fold it into a richer scenario as one assertion among many.
|
||||
- **Collapse near-duplicates.** Two TCs that differ only in input value (search by title vs search by description, when the underlying code path is the same) should merge into one parameterised scenario unless each input genuinely exercises a distinct branch. Prefer one assertion-rich TC over three thin ones.
|
||||
|
||||
@@ -3932,6 +3932,7 @@ components:
|
||||
- logs-field
|
||||
- traces-field
|
||||
- metrics-field
|
||||
- llm-pricing-rule
|
||||
type: string
|
||||
CoretypesObject:
|
||||
properties:
|
||||
@@ -15759,9 +15760,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- llm-pricing-rule:list
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
- llm-pricing-rule:list
|
||||
summary: List pricing rules
|
||||
tags:
|
||||
- llmpricingrules
|
||||
@@ -15806,9 +15807,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- ADMIN
|
||||
- llm-pricing-rule:update
|
||||
- tokenizer:
|
||||
- ADMIN
|
||||
- llm-pricing-rule:update
|
||||
summary: Create or update pricing rules
|
||||
tags:
|
||||
- llmpricingrules
|
||||
@@ -15854,9 +15855,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- ADMIN
|
||||
- llm-pricing-rule:delete
|
||||
- tokenizer:
|
||||
- ADMIN
|
||||
- llm-pricing-rule:delete
|
||||
summary: Delete a pricing rule
|
||||
tags:
|
||||
- llmpricingrules
|
||||
@@ -15912,9 +15913,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- llm-pricing-rule:read
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
- llm-pricing-rule:read
|
||||
summary: Get a pricing rule
|
||||
tags:
|
||||
- llmpricingrules
|
||||
@@ -15967,9 +15968,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- llm-pricing-rule:list
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
- llm-pricing-rule:list
|
||||
summary: List unmapped models
|
||||
tags:
|
||||
- llmpricingrules
|
||||
@@ -16696,9 +16697,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- route-policy:list
|
||||
- VIEWER
|
||||
- tokenizer:
|
||||
- route-policy:list
|
||||
- VIEWER
|
||||
summary: List route policies
|
||||
tags:
|
||||
- routepolicies
|
||||
@@ -16753,13 +16754,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- route-policy:create
|
||||
- route-policy:attach
|
||||
- notification-channel:attach
|
||||
- ADMIN
|
||||
- tokenizer:
|
||||
- route-policy:create
|
||||
- route-policy:attach
|
||||
- notification-channel:attach
|
||||
- ADMIN
|
||||
summary: Create route policy
|
||||
tags:
|
||||
- routepolicies
|
||||
@@ -16804,9 +16801,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- route-policy:delete
|
||||
- ADMIN
|
||||
- tokenizer:
|
||||
- route-policy:delete
|
||||
- ADMIN
|
||||
summary: Delete route policy
|
||||
tags:
|
||||
- routepolicies
|
||||
@@ -16862,9 +16859,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- route-policy:read
|
||||
- VIEWER
|
||||
- tokenizer:
|
||||
- route-policy:read
|
||||
- VIEWER
|
||||
summary: Get route policy by ID
|
||||
tags:
|
||||
- routepolicies
|
||||
@@ -16931,17 +16928,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- route-policy:update
|
||||
- route-policy:attach
|
||||
- route-policy:detach
|
||||
- notification-channel:attach
|
||||
- notification-channel:detach
|
||||
- ADMIN
|
||||
- tokenizer:
|
||||
- route-policy:update
|
||||
- route-policy:attach
|
||||
- route-policy:detach
|
||||
- notification-channel:attach
|
||||
- notification-channel:detach
|
||||
- ADMIN
|
||||
summary: Update route policy
|
||||
tags:
|
||||
- routepolicies
|
||||
|
||||
@@ -173,10 +173,9 @@ Each spec follows these principles:
|
||||
1. **Directory per feature**: `tests/e2e/tests/<feature>/*.spec.ts`. Cross-resource junction concerns (e.g. cascade-delete) go in their own file, not packed into one giant spec.
|
||||
2. **Test titles use `TC-NN`**: `test('TC-01 alerts page — tabs render', ...)`. Preserves ordering at a glance and maps to external coverage tracking.
|
||||
3. **UI-first**: drive flows through the UI. Playwright traces capture every BE request/response the UI triggers, so asserting on UI outcomes implicitly validates BE contracts. Reach for direct `page.request.*` only when the test's *purpose* is asserting a response contract (use `page.waitForResponse` on a UI click) or when a specific UI step is structurally flaky (e.g. Ant DatePicker calendar-cell indices) — and even then try UI first.
|
||||
4. **Self-contained state**: each spec seeds its own data and cleans up at suite teardown. The pytest harness creates a fresh stack with **zero** dashboards / alerts / etc. — never assume pre-existing data. Patterns, in order of preference:
|
||||
- **Driver `dispose`** — the driver tracks what it seeded and deletes it after the test, so the spec has no cleanup code. See `dashboards.seed(...)` in `tests/e2e/drivers/dashboards.ts`.
|
||||
- **Per-test seed + cleanup in `try / finally`** — small specs without a driver, where each test owns its data.
|
||||
- **Suite-level seed + `afterAll` teardown** — larger specs without a driver. One `test.afterAll(...)` deletes everything the suite seeded. See `tests/e2e/tests/llm-o11y/llm-pricing.spec.ts`. `test.beforeAll` / `test.afterAll` cannot use `authedPage` directly (it's test-scoped); use `newAdminContext(browser)` from `helpers/auth.ts` instead — it performs one fresh login per suite hook.
|
||||
4. **Self-contained state**: each spec seeds its own data and cleans up at suite teardown. The pytest harness creates a fresh stack with **zero** dashboards / alerts / etc. — never assume pre-existing data. Two patterns work:
|
||||
- **Per-test seed + cleanup in `try / finally`** — small specs where each test owns its data.
|
||||
- **Suite-level seed + `afterAll` teardown** — preferred for larger specs. Each `createDashboard(...)` call adds the resulting ID to a module-level `Set<string>`, and one `test.afterAll(...)` deletes everything in the set. See `tests/e2e/tests/dashboards/list.spec.ts` for the full pattern. `test.beforeAll` / `test.afterAll` cannot use `authedPage` directly (it's test-scoped); use `newAdminContext(browser)` from `helpers/auth.ts` instead — it performs one fresh login per suite hook.
|
||||
5. **Seed via API when the UI flow is multi-step or brittle.** The frontend stores its JWT in `localStorage` under `AUTH_TOKEN`; `page.request.*` inherits the auth fixture's storage state. A typical pattern:
|
||||
```ts
|
||||
const token = await page.evaluate(
|
||||
|
||||
@@ -1,140 +0,0 @@
|
||||
import type { ErrorEvent, StackFrame } from '@sentry/react';
|
||||
|
||||
import {
|
||||
hasNoAppFrames,
|
||||
isExternalIntegrationError,
|
||||
SENTRY_IGNORE_ERRORS,
|
||||
} from '../sentryFilters';
|
||||
|
||||
const APP_BUNDLE = 'https://example.us.signoz.cloud/assets/index-B3QqK3ie.js';
|
||||
|
||||
function eventWithFrames(...filenames: string[]): ErrorEvent {
|
||||
return {
|
||||
type: undefined,
|
||||
exception: {
|
||||
values: [
|
||||
{
|
||||
type: 'TypeError',
|
||||
value: 'Failed to fetch',
|
||||
stacktrace: {
|
||||
frames: filenames.map((filename) => ({ filename, lineno: 1, colno: 1 })),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('isExternalIntegrationError', () => {
|
||||
it.each([
|
||||
[
|
||||
'PostHog recorder',
|
||||
'https://us-assets.i.posthog.com/static/posthog-recorder.js?v=1.298.0',
|
||||
],
|
||||
[
|
||||
'Pylon widget',
|
||||
'https://widget.usepylon.com/widget/00000000-0000-0000-0000-000000000000',
|
||||
],
|
||||
['Appcues', 'https://fast.appcues.com/123456.js'],
|
||||
])('drops an error with a %s frame', (_, url) => {
|
||||
expect(isExternalIntegrationError(eventWithFrames(APP_BUNDLE, url))).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it('drops it when the top frame is our bundle', () => {
|
||||
expect(
|
||||
isExternalIntegrationError(
|
||||
eventWithFrames(
|
||||
'https://us-assets.i.posthog.com/static/posthog-recorder.js?v=1.298.0',
|
||||
'<anonymous>',
|
||||
APP_BUNDLE,
|
||||
),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps an error from our bundle only', () => {
|
||||
expect(
|
||||
isExternalIntegrationError(eventWithFrames(APP_BUNDLE, '<anonymous>')),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps an error from a host that only contains an integration name', () => {
|
||||
expect(
|
||||
isExternalIntegrationError(
|
||||
eventWithFrames(
|
||||
'https://posthog.example.com/app.js',
|
||||
'https://notusepylon.com/widget.js',
|
||||
),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps an error without a stack trace', () => {
|
||||
expect(isExternalIntegrationError({ type: undefined })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('hasNoAppFrames', () => {
|
||||
const PAGE_URL = 'https://example.us.signoz.cloud/dashboard/01a081e1';
|
||||
|
||||
function eventWithStackFrames(frames: StackFrame[]): ErrorEvent {
|
||||
return {
|
||||
type: undefined,
|
||||
exception: {
|
||||
values: [{ type: 'SyntaxError', stacktrace: { frames } }],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
it('drops a script appended to the page', () => {
|
||||
expect(
|
||||
hasNoAppFrames(
|
||||
eventWithStackFrames([
|
||||
{ filename: PAGE_URL, lineno: 1, colno: 30, function: 'global code' },
|
||||
{ filename: '[native code]', function: 'eval' },
|
||||
{ filename: '[native code]', function: 'append' },
|
||||
]),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('drops a browser extension error', () => {
|
||||
expect(
|
||||
hasNoAppFrames(
|
||||
eventWithStackFrames([
|
||||
{ filename: 'chrome-extension://abc/content.js', lineno: 4, colno: 12 },
|
||||
]),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps an error with a frame from our bundle', () => {
|
||||
expect(hasNoAppFrames(eventWithFrames(PAGE_URL, APP_BUNDLE))).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps an error without a stack trace', () => {
|
||||
expect(hasNoAppFrames({ type: undefined })).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps an error whose frames have no position', () => {
|
||||
expect(
|
||||
hasNoAppFrames(
|
||||
eventWithStackFrames([{ filename: '[native code]', function: 'eval' }]),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('SENTRY_IGNORE_ERRORS', () => {
|
||||
it('ignores the bundled PostHog recorder load failure', () => {
|
||||
expect(
|
||||
SENTRY_IGNORE_ERRORS.some((pattern) =>
|
||||
pattern.test(
|
||||
'Error: Called on script loaded before session recording is available',
|
||||
),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -22,7 +22,6 @@ import { ChatSupportState, useChatSupport } from 'hooks/useChatSupport';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
|
||||
import { StatusCodes } from 'http-status-codes';
|
||||
import { IS_PROD } from 'lib/env';
|
||||
import history from 'lib/history';
|
||||
import ErrorBoundaryFallback from 'pages/ErrorBoundaryFallback/ErrorBoundaryFallback';
|
||||
import posthog from 'posthog-js';
|
||||
@@ -38,11 +37,6 @@ import defaultRoutes, {
|
||||
LIST_LICENSES,
|
||||
SUPPORT_ROUTE,
|
||||
} from './routes';
|
||||
import {
|
||||
hasNoAppFrames,
|
||||
isExternalIntegrationError,
|
||||
SENTRY_IGNORE_ERRORS,
|
||||
} from './sentryFilters';
|
||||
|
||||
const appRouter = (children: ReactNode): ReactNode => (
|
||||
<Router history={history}>
|
||||
@@ -316,7 +310,16 @@ function App(): JSX.Element {
|
||||
tunnel: window.signozBootData.settings.sentry.tunnel,
|
||||
environment: process.env.ENVIRONMENT,
|
||||
release: process.env.VERSION,
|
||||
ignoreErrors: SENTRY_IGNORE_ERRORS,
|
||||
// A tab that outlived a deploy requests hashed assets the new build no longer
|
||||
// has. `lazyRetry` recovers by reloading once, so this class is not worth
|
||||
// reporting. The stylesheet message is Vite's own; the module ones are the
|
||||
// same failure worded differently by Chromium, Firefox and Safari.
|
||||
ignoreErrors: [
|
||||
/Unable to preload CSS for/,
|
||||
/Failed to fetch dynamically imported module/,
|
||||
/error loading dynamically imported module/,
|
||||
/Importing a module script failed/,
|
||||
],
|
||||
integrations: [
|
||||
// Kept for the `transaction` tag used in routing, even though
|
||||
// tracing is disabled. Ref: https://github.com/SigNoz/platform-pod/issues/2393#issuecomment-4603658055
|
||||
@@ -351,15 +354,6 @@ function App(): JSX.Element {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isExternalIntegrationError(event)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Dev serves source from /src/, so every frame would look foreign there.
|
||||
if (IS_PROD && hasNoAppFrames(event)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const sessionReplayUrl = posthog.get_session_replay_url?.({
|
||||
withTimestamp: true,
|
||||
});
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
import type { ErrorEvent } from '@sentry/react';
|
||||
|
||||
export const SENTRY_IGNORE_ERRORS = [
|
||||
// A tab that outlived a deploy requests hashed assets the new build no longer
|
||||
// has. `lazyRetry` recovers by reloading once, so this class is not worth
|
||||
// reporting. The stylesheet message is Vite's own; the module ones are the
|
||||
// same failure worded differently by Chromium, Firefox and Safari.
|
||||
/Unable to preload CSS for/,
|
||||
/Failed to fetch dynamically imported module/,
|
||||
/error loading dynamically imported module/,
|
||||
/Importing a module script failed/,
|
||||
// Thrown by the bundled posthog-js when its recorder script fails to load, so
|
||||
// its frames point at our own bundle and the URL check below misses it.
|
||||
/Called on script loaded before session recording is available/,
|
||||
];
|
||||
|
||||
const APP_ASSETS_PATH = '/assets/';
|
||||
|
||||
// Frames without a position are `[native code]`, which says nothing about the
|
||||
// script that threw.
|
||||
export function hasNoAppFrames(event: ErrorEvent): boolean {
|
||||
const frames = (event.exception?.values ?? [])
|
||||
.flatMap((exception) => exception.stacktrace?.frames ?? [])
|
||||
.filter(
|
||||
(frame) => frame.filename && (frame.lineno != null || frame.colno != null),
|
||||
);
|
||||
|
||||
return (
|
||||
frames.length > 0 &&
|
||||
!frames.some((frame) => frame.filename?.includes(APP_ASSETS_PATH))
|
||||
);
|
||||
}
|
||||
|
||||
// PostHog's lazy recorder, the Pylon widget and Appcues.
|
||||
const EXTERNAL_SCRIPT_URLS = [
|
||||
/^https?:\/\/[^/]+\.posthog\.com\//,
|
||||
/^https?:\/\/(?:[^/]+\.)?usepylon\.com\//,
|
||||
/^https?:\/\/(?:[^/]+\.)?appcues\.(?:com|net)\//,
|
||||
];
|
||||
|
||||
// Checks every frame, not only the top one: a failed fetch from the recorder
|
||||
// tops out in Sentry's own fetch wrapper, which is bundled with the app.
|
||||
export function isExternalIntegrationError(event: ErrorEvent): boolean {
|
||||
return (event.exception?.values ?? []).some((exception) =>
|
||||
(exception.stacktrace?.frames ?? []).some((frame) =>
|
||||
EXTERNAL_SCRIPT_URLS.some((url) => url.test(frame.filename ?? '')),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -3579,6 +3579,7 @@ export enum CoretypesKindDTO {
|
||||
'logs-field' = 'logs-field',
|
||||
'traces-field' = 'traces-field',
|
||||
'metrics-field' = 'metrics-field',
|
||||
'llm-pricing-rule' = 'llm-pricing-rule',
|
||||
}
|
||||
export enum CoretypesTypeDTO {
|
||||
user = 'user',
|
||||
|
||||
@@ -129,7 +129,6 @@ const MetricsAggregateSection = memo(function MetricsAggregateSection({
|
||||
onChange={handleChangeOperator}
|
||||
operators={operators}
|
||||
className="metrics-operators-select"
|
||||
data-testid="metrics-time-aggregation"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -193,10 +192,7 @@ const MetricsAggregateSection = memo(function MetricsAggregateSection({
|
||||
AGGREGATE ACROSS TIME SERIES
|
||||
</div>
|
||||
</Tooltip>
|
||||
<div
|
||||
className="metrics-aggregation-section-content-item-value"
|
||||
data-testid="metrics-space-aggregation"
|
||||
>
|
||||
<div className="metrics-aggregation-section-content-item-value">
|
||||
<SpaceAggregationOptions
|
||||
panelType={panelType}
|
||||
key={`${panelType}${queryAggregation.spaceAggregation}${queryAggregation.timeAggregation}`}
|
||||
@@ -233,10 +229,7 @@ const MetricsAggregateSection = memo(function MetricsAggregateSection({
|
||||
<div className="metrics-space-aggregation-section">
|
||||
<div className="metrics-aggregation-section-content">
|
||||
<div className="metrics-aggregation-section-content-item">
|
||||
<div
|
||||
className="metrics-aggregation-section-content-item-value"
|
||||
data-testid="metrics-space-aggregation"
|
||||
>
|
||||
<div className="metrics-aggregation-section-content-item-value">
|
||||
<SpaceAggregationOptions
|
||||
panelType={panelType}
|
||||
key={`${panelType}${queryAggregation.spaceAggregation}${queryAggregation.timeAggregation}`}
|
||||
|
||||
@@ -332,7 +332,6 @@ function HavingFilter({
|
||||
value={input}
|
||||
onChange={handleChange}
|
||||
theme={isDarkMode ? copilot : githubLight}
|
||||
data-testid="having-editor"
|
||||
className="having-filter-select-editor"
|
||||
width="100%"
|
||||
extensions={[
|
||||
|
||||
@@ -615,7 +615,6 @@ function QueryAggregationSelect({
|
||||
setInput(value);
|
||||
onChange?.(value);
|
||||
}}
|
||||
data-testid="query-aggregation-editor"
|
||||
className={`query-aggregation-select-editor ${
|
||||
validationError ? 'error' : ''
|
||||
}`}
|
||||
|
||||
@@ -1607,7 +1607,6 @@ function QuerySearch({
|
||||
onChange={handleChange}
|
||||
onUpdate={handleUpdate}
|
||||
onCreateEditor={handleEditorCreate}
|
||||
data-testid="query-where-clause-editor"
|
||||
className={cx('query-where-clause-editor', {
|
||||
isValid: validation.isValid === true,
|
||||
hasErrors: validation.errors.length > 0,
|
||||
@@ -1681,7 +1680,6 @@ function QuerySearch({
|
||||
className={cx('query-status-container', {
|
||||
hasErrors: validation.errors.length > 0,
|
||||
})}
|
||||
data-testid="query-validation-status"
|
||||
>
|
||||
<Popover
|
||||
placement="bottomRight"
|
||||
|
||||
@@ -183,7 +183,6 @@ export const QueryV2 = forwardRef(function QueryV2(
|
||||
<div
|
||||
className={cx('query-v2', { 'where-clause-view': showOnlyWhereClause })}
|
||||
ref={ref}
|
||||
data-testid={`query-${query.queryName}`}
|
||||
>
|
||||
<div className="qb-content-section">
|
||||
{(!showOnlyWhereClause || showTraceOperator) && (
|
||||
@@ -247,7 +246,6 @@ export const QueryV2 = forwardRef(function QueryV2(
|
||||
{isMultiQueryAllowed && (
|
||||
<Dropdown
|
||||
items={queryActionItems}
|
||||
testId="query-actions"
|
||||
nativeButton={false}
|
||||
align="end"
|
||||
side="bottom"
|
||||
|
||||
@@ -61,10 +61,7 @@ export default function TraceOperator({
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx('qb-trace-operator', !isRawQuery && 'non-list-view')}
|
||||
data-testid="trace-operator"
|
||||
>
|
||||
<div className={cx('qb-trace-operator', !isRawQuery && 'non-list-view')}>
|
||||
<div className="qb-trace-operator-container">
|
||||
<div
|
||||
className={cx(
|
||||
|
||||
@@ -378,7 +378,6 @@ function TraceOperatorEditor({
|
||||
theme={isDarkMode ? copilot : githubLight}
|
||||
onChange={handleChange}
|
||||
onUpdate={handleUpdate}
|
||||
data-testid="trace-operator-editor"
|
||||
className={cx('query-where-clause-editor', {
|
||||
isValid: validation.isValid === true,
|
||||
hasErrors: validation.errors.length > 0,
|
||||
|
||||
@@ -147,28 +147,6 @@ describe('getAutoContexts', () => {
|
||||
metadata: { page: 'alert_list' },
|
||||
},
|
||||
]);
|
||||
|
||||
expect(
|
||||
getAutoContexts(ROUTES.LIST_ALL_ALERT, '?tab=RoutingPolicies'),
|
||||
).toStrictEqual([
|
||||
{
|
||||
source: 'auto',
|
||||
type: 'alert',
|
||||
resourceId: null,
|
||||
metadata: { page: 'alert_list' },
|
||||
},
|
||||
]);
|
||||
|
||||
expect(
|
||||
getAutoContexts(ROUTES.LIST_ALL_ALERT, '?tab=PlannedDowntime'),
|
||||
).toStrictEqual([
|
||||
{
|
||||
source: 'auto',
|
||||
type: 'alert',
|
||||
resourceId: null,
|
||||
metadata: { page: 'alert_list' },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns dashboard detail context on dashboard page', () => {
|
||||
|
||||
@@ -58,12 +58,6 @@ describe('resolvePageType', () => {
|
||||
expect(resolvePageType(ROUTES.LIST_ALL_ALERT, '?tab=Configuration')).toBe(
|
||||
PageTypeDTO.alert_list,
|
||||
);
|
||||
expect(resolvePageType(ROUTES.LIST_ALL_ALERT, '?tab=RoutingPolicies')).toBe(
|
||||
PageTypeDTO.alert_list,
|
||||
);
|
||||
expect(resolvePageType(ROUTES.LIST_ALL_ALERT, '?tab=PlannedDowntime')).toBe(
|
||||
PageTypeDTO.alert_list,
|
||||
);
|
||||
});
|
||||
|
||||
it('returns log_detail when logs explorer has activeLogId', () => {
|
||||
|
||||
@@ -30,19 +30,6 @@ jest.mock('@signozhq/ui/sonner', () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
// jsdom has no layout, and Floating UI's getComputedStyle walk over every
|
||||
// popover ancestor costs ~1 s per open here, enough to time out under load.
|
||||
jest.mock('@floating-ui/dom', () => ({
|
||||
...jest.requireActual('@floating-ui/dom'),
|
||||
autoUpdate: (): (() => void) => (): void => {},
|
||||
computePosition: (
|
||||
_reference: unknown,
|
||||
_floating: unknown,
|
||||
{ placement = 'bottom', strategy = 'absolute' } = {},
|
||||
): Promise<unknown> =>
|
||||
Promise.resolve({ x: 0, y: 0, placement, strategy, middlewareData: {} }),
|
||||
}));
|
||||
|
||||
type AccountSettingsDrawerProps = ComponentProps<typeof AccountSettingsDrawer>;
|
||||
|
||||
const onClose = jest.fn() as jest.MockedFunction<
|
||||
@@ -103,7 +90,7 @@ describe('GCP AccountSettingsDrawer', () => {
|
||||
});
|
||||
|
||||
it('keeps save disabled until the project IDs actually change', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderDrawer();
|
||||
|
||||
expect(screen.getByTestId('gcp-update-account-btn')).toHaveAttribute(
|
||||
@@ -122,7 +109,7 @@ describe('GCP AccountSettingsDrawer', () => {
|
||||
});
|
||||
|
||||
it('sends the updated project IDs while preserving the immutable deployment fields', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderDrawer();
|
||||
|
||||
await addProjectIds(user, 'gcp-edit-project-ids-select', ['project-c']);
|
||||
@@ -165,7 +152,7 @@ describe('GCP AccountSettingsDrawer', () => {
|
||||
});
|
||||
|
||||
it('blocks the update and shows a validation error when every project ID is removed', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderDrawer();
|
||||
|
||||
// Strip every tag via its remove icon; the list shrinks as we go.
|
||||
@@ -201,7 +188,7 @@ describe('GCP AccountSettingsDrawer', () => {
|
||||
),
|
||||
);
|
||||
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderDrawer();
|
||||
|
||||
await addProjectIds(user, 'gcp-edit-project-ids-select', ['project-c']);
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
import { Pill } from '@signozhq/ui/pill';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import cx from 'classnames';
|
||||
|
||||
import type { DowntimeAlertOption } from './types';
|
||||
|
||||
interface AlertRuleTagsProps {
|
||||
selectedTags: DowntimeAlertOption[];
|
||||
closable: boolean;
|
||||
handleClose?: (removedTag: DowntimeAlertOption['value']) => void;
|
||||
classname?: string;
|
||||
}
|
||||
export function AlertRuleTags(props: AlertRuleTagsProps): JSX.Element {
|
||||
const { closable, selectedTags, handleClose, classname } = props;
|
||||
return (
|
||||
<div
|
||||
style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 8 }}
|
||||
className={cx('alert-rule-tags', classname)}
|
||||
>
|
||||
{selectedTags?.map((tag: DowntimeAlertOption, index: number) => {
|
||||
if (closable) {
|
||||
return (
|
||||
<Pill.Closeable
|
||||
key={tag.value}
|
||||
maxWidth={200}
|
||||
onClose={(): void => handleClose?.(tag.value)}
|
||||
>
|
||||
{tag.label}
|
||||
</Pill.Closeable>
|
||||
);
|
||||
}
|
||||
|
||||
const isLongTag = (tag?.label as string)?.length > 20;
|
||||
const tagElem = (
|
||||
<Badge
|
||||
textTransform="none"
|
||||
key={tag.value}
|
||||
color={index % 2 ? 'highlight-danger' : 'primary'}
|
||||
variant="outlined"
|
||||
>
|
||||
{isLongTag
|
||||
? `${(tag?.label as string | null)?.slice(0, 20)}...`
|
||||
: tag?.label}
|
||||
</Badge>
|
||||
);
|
||||
return (
|
||||
<Tooltip title={isLongTag ? tag?.label : undefined} key={tag?.value}>
|
||||
{tagElem}
|
||||
</Tooltip>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,176 +0,0 @@
|
||||
.container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.headerBand {
|
||||
--control-height: 2rem;
|
||||
--input-height: var(--control-height);
|
||||
--input-wrapper-height: var(--control-height);
|
||||
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-6);
|
||||
flex-shrink: 0;
|
||||
padding: 0 var(--spacing-8) var(--spacing-6) var(--spacing-8);
|
||||
}
|
||||
|
||||
.commandHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-4);
|
||||
}
|
||||
|
||||
.headingBlock {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.title {
|
||||
margin: 0;
|
||||
color: var(--l1-foreground);
|
||||
font-size: var(--font-size-lg);
|
||||
font-weight: var(--font-weight-medium);
|
||||
line-height: 28px;
|
||||
letter-spacing: -0.09px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.countPill {
|
||||
padding: 2px 9px;
|
||||
border-radius: 999px;
|
||||
background: var(--l2-background);
|
||||
border: 1px solid var(--l2-border);
|
||||
color: var(--l2-foreground);
|
||||
font-size: var(--font-size-xs);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.grow {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.filtersRow {
|
||||
position: relative;
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-4);
|
||||
}
|
||||
|
||||
.searchInput {
|
||||
flex: 1 1 0;
|
||||
min-width: 220px;
|
||||
}
|
||||
|
||||
.searchIcon {
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.actionsHeader {
|
||||
display: block;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.tableContainer {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
--tanstack-table-row-hover-bg: var(--l2-background-hover);
|
||||
--tanstack-table-row-active-bg: var(--l2-background-active);
|
||||
--tanstack-table-row-height: 42px;
|
||||
|
||||
--tanstack-cell-padding-top-override: 5px;
|
||||
--tanstack-cell-padding-bottom-override: 5px;
|
||||
--tanstack-cell-padding-left-override: 16px;
|
||||
--tanstack-cell-padding-right-override: 16px;
|
||||
|
||||
--tanstack-table-row-odd-bg: color-mix(
|
||||
in srgb,
|
||||
var(--l1-foreground) 2%,
|
||||
transparent
|
||||
);
|
||||
--tanstack-table-row-even-bg: color-mix(
|
||||
in srgb,
|
||||
var(--l1-foreground) 1%,
|
||||
transparent
|
||||
);
|
||||
}
|
||||
|
||||
.paginationContainer {
|
||||
padding-right: var(--spacing-12);
|
||||
height: 62px;
|
||||
}
|
||||
|
||||
.expression {
|
||||
font-family: var(--font-mono, monospace);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.badges {
|
||||
display: flex;
|
||||
gap: var(--spacing-2);
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.timeText {
|
||||
display: inline-block;
|
||||
white-space: nowrap;
|
||||
font-size: var(--tanstack-plain-cell-font-size, 14px);
|
||||
line-height: var(--tanstack-plain-cell-line-height, 18px);
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.emptyState {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--spacing-3);
|
||||
padding: 48px 24px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.emptyIcon {
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.emptyTitle {
|
||||
color: var(--l1-foreground);
|
||||
font-size: 16px;
|
||||
font-weight: 500;
|
||||
line-height: 24px;
|
||||
}
|
||||
|
||||
.emptySubtitle {
|
||||
color: var(--l2-foreground);
|
||||
font-size: 14px;
|
||||
line-height: 20px;
|
||||
max-width: 420px;
|
||||
}
|
||||
|
||||
.docsLink {
|
||||
color: var(--l2-foreground);
|
||||
font-size: 13px;
|
||||
text-decoration: none;
|
||||
|
||||
&:hover {
|
||||
color: var(--l1-foreground);
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
@@ -109,6 +109,191 @@
|
||||
}
|
||||
}
|
||||
|
||||
.planned-downtime-container {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
|
||||
.planned-downtime-content {
|
||||
width: calc(100% - 30px);
|
||||
max-width: 736px;
|
||||
|
||||
.title {
|
||||
color: var(--l1-foreground);
|
||||
font-size: var(--font-size-lg);
|
||||
font-style: normal;
|
||||
font-weight: var(--font-weight-normal);
|
||||
line-height: 28px;
|
||||
letter-spacing: -0.09px;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
color: var(---bg-vanilla-400);
|
||||
font-size: var(--font-size-sm);
|
||||
font-style: normal;
|
||||
font-weight: var(--font-weight-normal);
|
||||
line-height: 20px;
|
||||
letter-spacing: -0.07px;
|
||||
}
|
||||
|
||||
.ant-input-affix-wrapper {
|
||||
margin-top: 16px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.schedule-created-at {
|
||||
border: 1px solid var(--l1-border);
|
||||
background-color: var(--l2-background);
|
||||
border-top: 0px;
|
||||
width: 100%;
|
||||
padding: 8px 16px;
|
||||
gap: 6px;
|
||||
height: 40px;
|
||||
border-bottom-left-radius: 6px;
|
||||
border-bottom-right-radius: 6px;
|
||||
|
||||
display: flex;
|
||||
align-items: center;
|
||||
.ant-typography {
|
||||
color: var(--l2-foreground);
|
||||
font-variant-numeric: lining-nums tabular-nums stacked-fractions
|
||||
slashed-zero;
|
||||
font-feature-settings:
|
||||
'dlig' on,
|
||||
'salt' on,
|
||||
'cpsp' on,
|
||||
'case' on;
|
||||
font-family: Inter;
|
||||
font-size: 14px;
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
line-height: 18px;
|
||||
letter-spacing: -0.07px;
|
||||
}
|
||||
}
|
||||
|
||||
.ant-collapse-header {
|
||||
height: 56px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.header-content {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
|
||||
.ant-typography {
|
||||
color: var(--l2-foreground);
|
||||
font-variant-numeric: lining-nums tabular-nums stacked-fractions
|
||||
slashed-zero;
|
||||
font-feature-settings:
|
||||
'dlig' on,
|
||||
'salt' on,
|
||||
'cpsp' on,
|
||||
'case' on;
|
||||
font-family: Inter;
|
||||
font-size: 14px;
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
line-height: 18px;
|
||||
letter-spacing: -0.07px;
|
||||
}
|
||||
|
||||
.action-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 20px;
|
||||
cursor: pointer;
|
||||
|
||||
.hidden {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.new-downtime-menu {
|
||||
.create-downtime-menu-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
}
|
||||
|
||||
.planned-downtime-table {
|
||||
.ant-table {
|
||||
background: none !important;
|
||||
}
|
||||
.ant-table-cell {
|
||||
padding: 0 !important;
|
||||
border: 0 !important;
|
||||
width: 736px;
|
||||
}
|
||||
|
||||
.ant-table-tbody {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
|
||||
.collapse-list {
|
||||
border: 1px solid var(--l1-border);
|
||||
background-color: var(--l2-background);
|
||||
border-top-left-radius: 6px;
|
||||
border-top-right-radius: 6px;
|
||||
|
||||
.render-item-collapse-list {
|
||||
margin-bottom: 13px;
|
||||
display: grid;
|
||||
grid-template-columns: 128px 1fr;
|
||||
}
|
||||
|
||||
.alert-rule-collapse-list {
|
||||
width: 540px;
|
||||
max-height: 100px;
|
||||
overflow: auto;
|
||||
}
|
||||
.ant-collapse-content-active {
|
||||
border-top: 0;
|
||||
}
|
||||
|
||||
.ant-collapse-item {
|
||||
border: none;
|
||||
}
|
||||
.ant-collapse-content-box {
|
||||
padding: 8px 20px 12px 38px;
|
||||
|
||||
.render-item-value {
|
||||
.ant-typography {
|
||||
color: var(--l1-foreground);
|
||||
font-family: Inter;
|
||||
font-size: 14px;
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
line-height: 18px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.ant-typography {
|
||||
color: var(--l2-foreground);
|
||||
font-family: Inter;
|
||||
font-size: 14px;
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
line-height: 20px; /* 142.857% */
|
||||
letter-spacing: -0.07px;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.delete-schedule-modal {
|
||||
width: calc(100% - 30px) !important; /* Adjust the 20px as needed */
|
||||
max-width: 384px;
|
||||
|
||||
@@ -1,51 +1,36 @@
|
||||
import React, {
|
||||
ChangeEvent,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
} from 'react';
|
||||
import React, { ChangeEvent, useEffect, useState } from 'react';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import { Plus, Search } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Input } from '@signozhq/ui/input';
|
||||
import { Button, Flex, Form, Tooltip } from 'antd';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { Form } from 'antd';
|
||||
import {
|
||||
useDeleteDowntimeScheduleByID,
|
||||
useListDowntimeSchedules,
|
||||
} from 'api/generated/services/downtimeschedules';
|
||||
import { useListRules } from 'api/generated/services/rules';
|
||||
import type { AlertmanagertypesPlannedMaintenanceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { ColumnSelector } from 'components/TanStackTableView';
|
||||
import TextToolTip from 'components/TextToolTip';
|
||||
import dayjs from 'dayjs';
|
||||
import useDebouncedFn from 'hooks/useDebouncedFunction';
|
||||
import { useNotifications } from 'hooks/useNotifications';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import { useAppContext } from 'providers/App/App';
|
||||
import { useErrorModal } from 'providers/ErrorModalProvider';
|
||||
import { useTimezone } from 'providers/Timezone';
|
||||
import { USER_ROLES } from 'types/roles';
|
||||
|
||||
import 'dayjs/locale/en';
|
||||
|
||||
import styles from './PlannedDowntime.module.scss';
|
||||
import { PlannedDowntimeDeleteModal } from './PlannedDowntimeDeleteModal';
|
||||
import { PlannedDowntimeForm } from './PlannedDowntimeForm';
|
||||
import PlannedDowntimeList from './PlannedDowntimeList';
|
||||
import { PlannedDowntimeList } from './PlannedDowntimeList';
|
||||
import {
|
||||
defaultInitialValues,
|
||||
deleteDowntimeHandler,
|
||||
} from './PlannedDowntimeutils';
|
||||
import { getPlannedDowntimeColumns } from './table.config';
|
||||
import { DowntimeSchedulesTableData } from './types';
|
||||
import usePlannedDowntimeTable from './usePlannedDowntimeTable';
|
||||
|
||||
import './PlannedDowntime.styles.scss';
|
||||
|
||||
const COLUMNS_STORAGE_KEY = 'planned-downtime-columns';
|
||||
|
||||
dayjs.locale('en');
|
||||
|
||||
export function PlannedDowntime(): JSX.Element {
|
||||
@@ -84,7 +69,7 @@ export function PlannedDowntime(): JSX.Element {
|
||||
}
|
||||
}, [form, isOpen]);
|
||||
|
||||
const [searchValue, setSearchValue] = React.useState<string>(
|
||||
const [searchValue, setSearchValue] = React.useState<string | number>(
|
||||
urlQuery.get('search') || '',
|
||||
);
|
||||
const [deleteData, setDeleteData] = useState<{ id: string; name: string }>();
|
||||
@@ -101,62 +86,16 @@ export function PlannedDowntime(): JSX.Element {
|
||||
history.replace(url);
|
||||
}, 300);
|
||||
|
||||
const {
|
||||
containerRef,
|
||||
calculatedPageSize,
|
||||
filteredDowntimes,
|
||||
pagedDowntimes,
|
||||
setPage,
|
||||
setLimit,
|
||||
} = usePlannedDowntimeTable(
|
||||
downtimeSchedules.data?.data || [],
|
||||
alertOptions || [],
|
||||
searchValue,
|
||||
);
|
||||
|
||||
const handleSearch = (e: ChangeEvent<HTMLInputElement>): void => {
|
||||
setSearchValue(e.target.value);
|
||||
updateUrlWithSearch(e.target.value);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const clearSearch = (): void => {
|
||||
setSearchValue('');
|
||||
updateUrlWithSearch('');
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const canEdit = user?.role !== USER_ROLES.VIEWER;
|
||||
const { formatTimezoneAdjustedTimestamp } = useTimezone();
|
||||
const columns = React.useMemo(
|
||||
() => getPlannedDowntimeColumns(formatTimezoneAdjustedTimestamp),
|
||||
[formatTimezoneAdjustedTimestamp],
|
||||
);
|
||||
|
||||
const handleCreate = useCallback((): void => {
|
||||
setInitialValues(defaultInitialValues);
|
||||
setIsOpen(true);
|
||||
setEditMode(false);
|
||||
form.resetFields();
|
||||
}, [form]);
|
||||
|
||||
const handleEdit = useCallback(
|
||||
(downtime: DowntimeSchedulesTableData): void => {
|
||||
setInitialValues({ ...downtime });
|
||||
setIsOpen(true);
|
||||
setEditMode(true);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handleDelete = useCallback(
|
||||
(downtime: DowntimeSchedulesTableData): void => {
|
||||
setDeleteData({ id: downtime.id, name: downtime.name });
|
||||
setIsDeleteModalOpen(true);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// Delete Downtime Schedule
|
||||
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
|
||||
const { notifications } = useNotifications();
|
||||
@@ -186,107 +125,78 @@ export function PlannedDowntime(): JSX.Element {
|
||||
});
|
||||
};
|
||||
|
||||
const isFetching = useMemo(
|
||||
() => downtimeSchedules.isLoading || downtimeSchedules.isFetching,
|
||||
[downtimeSchedules.isLoading, downtimeSchedules.isFetching],
|
||||
);
|
||||
const totalDowntimes = useMemo(
|
||||
() => downtimeSchedules.data?.data?.length ?? 0,
|
||||
[downtimeSchedules.data?.data?.length],
|
||||
);
|
||||
const isEmpty = useMemo(
|
||||
() => !isFetching && !searchValue && totalDowntimes === 0,
|
||||
[isFetching, searchValue, totalDowntimes],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<header className={styles.headerBand}>
|
||||
<div className={styles.commandHeader}>
|
||||
<div className={styles.headingBlock}>
|
||||
<Typography.Title className={styles.title}>
|
||||
Planned Downtime
|
||||
</Typography.Title>
|
||||
<span className={styles.countPill}>{totalDowntimes}</span>
|
||||
</div>
|
||||
<div className={styles.grow} />
|
||||
{!isEmpty && (
|
||||
<ColumnSelector
|
||||
columns={columns}
|
||||
storageKey={COLUMNS_STORAGE_KEY}
|
||||
testId="planned-downtime-columns"
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
variant="solid"
|
||||
color="primary"
|
||||
size="sm"
|
||||
prefix={<Plus size={14} />}
|
||||
onClick={handleCreate}
|
||||
disabled={!canEdit}
|
||||
disabledTooltip="You need edit permissions to create a planned downtime"
|
||||
testId="planned-downtime-create"
|
||||
>
|
||||
New downtime
|
||||
</Button>
|
||||
<TextToolTip
|
||||
text="More details on how to schedule planned downtime"
|
||||
url="https://signoz.io/docs/alerts-management/planned-maintenance/"
|
||||
urlText="Learn More"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.filtersRow}>
|
||||
<div className="planned-downtime-container">
|
||||
<div className="planned-downtime-content">
|
||||
<Typography.Title className="title">Planned Downtime</Typography.Title>
|
||||
<Typography.Text className="subtitle">
|
||||
Create and manage planned downtimes.
|
||||
</Typography.Text>
|
||||
<Flex className="toolbar">
|
||||
<Input
|
||||
containerClassName={styles.searchInput}
|
||||
placeholder="Search by name"
|
||||
placeholder="Search for a planned downtime..."
|
||||
prefix={<Search size={12} color={Color.BG_VANILLA_400} />}
|
||||
value={searchValue}
|
||||
onChange={handleSearch}
|
||||
suffix={<Search size={14} className={styles.searchIcon} />}
|
||||
testId="planned-downtime-search"
|
||||
/>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div ref={containerRef} className={styles.tableContainer}>
|
||||
<Tooltip
|
||||
title={
|
||||
user?.role === USER_ROLES.VIEWER
|
||||
? 'You need edit permissions to create a planned downtime'
|
||||
: ''
|
||||
}
|
||||
>
|
||||
<Button
|
||||
type="primary"
|
||||
onClick={(): void => {
|
||||
setInitialValues(defaultInitialValues);
|
||||
setIsOpen(true);
|
||||
setEditMode(false);
|
||||
form.resetFields();
|
||||
}}
|
||||
disabled={user?.role === USER_ROLES.VIEWER}
|
||||
>
|
||||
<Flex align="center" gap={4}>
|
||||
<Plus size={16} />
|
||||
New downtime
|
||||
</Flex>
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</Flex>
|
||||
<br />
|
||||
<PlannedDowntimeList
|
||||
columns={columns}
|
||||
downtimes={filteredDowntimes}
|
||||
pagedDowntimes={pagedDowntimes}
|
||||
calculatedPageSize={calculatedPageSize}
|
||||
onLimitChange={setLimit}
|
||||
isFetching={isFetching}
|
||||
isError={downtimeSchedules.isError}
|
||||
refetch={refetchAllSchedules}
|
||||
canEdit={canEdit}
|
||||
onEdit={handleEdit}
|
||||
onDelete={handleDelete}
|
||||
onCreate={handleCreate}
|
||||
hasSearchTerm={searchValue.length > 0}
|
||||
onClearSearch={clearSearch}
|
||||
downtimeSchedules={downtimeSchedules}
|
||||
alertOptions={alertOptions || []}
|
||||
setInitialValues={setInitialValues}
|
||||
setModalOpen={setIsOpen}
|
||||
handleDeleteDowntime={(id, name): void => {
|
||||
setDeleteData({ id, name });
|
||||
setIsDeleteModalOpen(true);
|
||||
}}
|
||||
setEditMode={setEditMode}
|
||||
searchValue={searchValue}
|
||||
/>
|
||||
{isOpen && (
|
||||
<PlannedDowntimeForm
|
||||
alertOptions={alertOptions || []}
|
||||
initialValues={initialValues}
|
||||
isError={isError}
|
||||
isLoading={isLoading}
|
||||
isOpen={isOpen}
|
||||
setIsOpen={setIsOpen}
|
||||
refetchAllSchedules={refetchAllSchedules}
|
||||
isEditMode={isEditMode}
|
||||
form={form}
|
||||
/>
|
||||
)}
|
||||
<PlannedDowntimeDeleteModal
|
||||
isDeleteLoading={isDeleteLoading}
|
||||
isDeleteModalOpen={isDeleteModalOpen}
|
||||
onDeleteHandler={onDeleteHandler}
|
||||
setIsDeleteModalOpen={setIsDeleteModalOpen}
|
||||
downtimeSchedule={deleteData?.name || ''}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{isOpen && (
|
||||
<PlannedDowntimeForm
|
||||
alertOptions={alertOptions || []}
|
||||
initialValues={initialValues}
|
||||
isError={isError}
|
||||
isLoading={isLoading}
|
||||
isOpen={isOpen}
|
||||
setIsOpen={setIsOpen}
|
||||
refetchAllSchedules={refetchAllSchedules}
|
||||
isEditMode={isEditMode}
|
||||
form={form}
|
||||
/>
|
||||
)}
|
||||
<PlannedDowntimeDeleteModal
|
||||
isDeleteLoading={isDeleteLoading}
|
||||
isDeleteModalOpen={isDeleteModalOpen}
|
||||
onDeleteHandler={onDeleteHandler}
|
||||
setIsDeleteModalOpen={setIsDeleteModalOpen}
|
||||
downtimeSchedule={deleteData?.name || ''}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
import { useMemo } from 'react';
|
||||
import { Ellipsis, PenLine, Trash2 } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Dropdown, type DropdownItemType } from '@signozhq/ui/dropdown';
|
||||
|
||||
import styles from './PlannedDowntime.module.scss';
|
||||
import { DowntimeSchedulesTableData } from './types';
|
||||
|
||||
interface PlannedDowntimeActionsMenuProps {
|
||||
downtime: DowntimeSchedulesTableData;
|
||||
onEdit: (downtime: DowntimeSchedulesTableData) => void;
|
||||
onDelete: (downtime: DowntimeSchedulesTableData) => void;
|
||||
}
|
||||
|
||||
function PlannedDowntimeActionsMenu({
|
||||
downtime,
|
||||
onEdit,
|
||||
onDelete,
|
||||
}: PlannedDowntimeActionsMenuProps): JSX.Element {
|
||||
const menuItems = useMemo<DropdownItemType[]>(
|
||||
() => [
|
||||
{
|
||||
type: 'item',
|
||||
value: 'edit',
|
||||
label: 'Edit',
|
||||
prefix: <PenLine size={14} />,
|
||||
onClick: (): void => onEdit(downtime),
|
||||
},
|
||||
{ type: 'separator', value: 'before-delete' },
|
||||
{
|
||||
type: 'item',
|
||||
value: 'delete',
|
||||
label: 'Delete',
|
||||
prefix: <Trash2 size={14} />,
|
||||
danger: true,
|
||||
onClick: (): void => onDelete(downtime),
|
||||
},
|
||||
],
|
||||
[downtime, onEdit, onDelete],
|
||||
);
|
||||
|
||||
return (
|
||||
// the row itself opens the downtime, so the actions keep their clicks
|
||||
// eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
|
||||
<div
|
||||
className={styles.actions}
|
||||
onClick={(event): void => event.stopPropagation()}
|
||||
>
|
||||
<Dropdown items={menuItems} nativeButton align="end" side="bottom">
|
||||
<Button
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
icon
|
||||
testId={`downtime-actions-${downtime.id}`}
|
||||
aria-label={`Actions for ${downtime.name}`}
|
||||
>
|
||||
<Ellipsis size={16} />
|
||||
</Button>
|
||||
</Dropdown>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default PlannedDowntimeActionsMenu;
|
||||
@@ -1,53 +0,0 @@
|
||||
import { CalendarClock, Plus } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
|
||||
import styles from './PlannedDowntime.module.scss';
|
||||
|
||||
const DOCS_URL =
|
||||
'https://signoz.io/docs/alerts-management/planned-maintenance/';
|
||||
|
||||
interface PlannedDowntimeEmptyStateProps {
|
||||
canCreate: boolean;
|
||||
onCreate: () => void;
|
||||
}
|
||||
|
||||
function PlannedDowntimeEmptyState({
|
||||
canCreate,
|
||||
onCreate,
|
||||
}: PlannedDowntimeEmptyStateProps): JSX.Element {
|
||||
return (
|
||||
<div className={styles.emptyState} data-testid="planned-downtime-empty-state">
|
||||
<CalendarClock className={styles.emptyIcon} size={16} />
|
||||
<Typography.Text className={styles.emptyTitle}>
|
||||
No planned downtime yet
|
||||
</Typography.Text>
|
||||
<Typography.Text className={styles.emptySubtitle}>
|
||||
A planned downtime silences alert rules for a window you schedule, once or
|
||||
on repeat, so maintenance does not page anyone.
|
||||
</Typography.Text>
|
||||
{canCreate && (
|
||||
<Button
|
||||
variant="solid"
|
||||
color="primary"
|
||||
size="md"
|
||||
prefix={<Plus size={14} />}
|
||||
onClick={onCreate}
|
||||
testId="planned-downtime-empty-create"
|
||||
>
|
||||
New downtime
|
||||
</Button>
|
||||
)}
|
||||
<a
|
||||
className={styles.docsLink}
|
||||
href={DOCS_URL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Read the planned downtime guide
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default PlannedDowntimeEmptyState;
|
||||
@@ -43,7 +43,7 @@ import { ALL_TIME_ZONES } from 'utils/timeZoneUtil';
|
||||
|
||||
import 'dayjs/locale/en';
|
||||
|
||||
import { AlertRuleTags } from './AlertRuleTags';
|
||||
import { AlertRuleTags } from './PlannedDowntimeList';
|
||||
import {
|
||||
getAlertOptionsFromIds,
|
||||
getDurationInfo,
|
||||
|
||||
@@ -1,109 +1,379 @@
|
||||
import { useMemo } from 'react';
|
||||
import ErrorEmptyState from 'components/Alerts/ErrorEmptyState';
|
||||
import NoResultsEmptyState from 'components/Alerts/NoResultsEmptyState';
|
||||
import TanStackTable, { TableColumnDef } from 'components/TanStackTableView';
|
||||
import React, { ReactNode, useEffect } from 'react';
|
||||
import { UseQueryResult } from 'react-query';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Collapse, Flex, Space, Table, TableProps, Tooltip } from 'antd';
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
import { Pill } from '@signozhq/ui/pill';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import type { DefaultOptionType } from 'antd/es/select';
|
||||
import type {
|
||||
ListDowntimeSchedules200,
|
||||
RenderErrorResponseDTO,
|
||||
AlertmanagertypesPlannedMaintenanceDTO,
|
||||
AlertmanagertypesScheduleDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import type { ErrorType } from 'api/generatedAPIInstance';
|
||||
import cx from 'classnames';
|
||||
import dayjs from 'dayjs';
|
||||
import { useNotifications } from 'hooks/useNotifications';
|
||||
import { defaultTo } from 'lodash-es';
|
||||
import { CalendarClock, PenLine, Trash2 } from '@signozhq/icons';
|
||||
import { useAppContext } from 'providers/App/App';
|
||||
import { USER_ROLES } from 'types/roles';
|
||||
|
||||
import styles from './PlannedDowntime.module.scss';
|
||||
import PlannedDowntimeActionsMenu from './PlannedDowntimeActionsMenu';
|
||||
import PlannedDowntimeEmptyState from './PlannedDowntimeEmptyState';
|
||||
import { DowntimeSchedulesTableData, PlannedDowntimeListProps } from './types';
|
||||
import { PLANNED_DOWNTIME_QUERY_PARAMS } from './usePlannedDowntimeTable';
|
||||
import { showErrorNotification } from 'utils/error';
|
||||
import {
|
||||
formatDateTime,
|
||||
getAlertOptionsFromIds,
|
||||
getDuration,
|
||||
recurrenceInfo,
|
||||
} from './PlannedDowntimeutils';
|
||||
|
||||
function PlannedDowntimeList({
|
||||
columns,
|
||||
downtimes,
|
||||
pagedDowntimes,
|
||||
calculatedPageSize,
|
||||
onLimitChange,
|
||||
isFetching,
|
||||
isError,
|
||||
refetch,
|
||||
canEdit,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onCreate,
|
||||
hasSearchTerm,
|
||||
onClearSearch,
|
||||
}: PlannedDowntimeListProps): JSX.Element {
|
||||
const columnsWithActions =
|
||||
useMemo((): TableColumnDef<DowntimeSchedulesTableData>[] => {
|
||||
if (!canEdit) {
|
||||
return columns;
|
||||
}
|
||||
import './PlannedDowntime.styles.scss';
|
||||
|
||||
return [
|
||||
...columns,
|
||||
{
|
||||
id: 'actions',
|
||||
header: (): JSX.Element => (
|
||||
<span className={styles.actionsHeader}>Actions</span>
|
||||
),
|
||||
accessorKey: 'id',
|
||||
width: { fixed: '96px', ignoreLastColumnFill: true },
|
||||
enableSort: false,
|
||||
enableResize: false,
|
||||
enableRemove: false,
|
||||
enableMove: false,
|
||||
pin: 'right',
|
||||
cell: ({ row }): JSX.Element => (
|
||||
<PlannedDowntimeActionsMenu
|
||||
downtime={row}
|
||||
onEdit={onEdit}
|
||||
onDelete={onDelete}
|
||||
/>
|
||||
),
|
||||
},
|
||||
];
|
||||
}, [canEdit, columns, onEdit, onDelete]);
|
||||
|
||||
const isEmpty = !isFetching && downtimes.length === 0;
|
||||
|
||||
if (isError) {
|
||||
return (
|
||||
<ErrorEmptyState
|
||||
title="Failed to load planned downtime"
|
||||
onRefresh={refetch}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (isEmpty && hasSearchTerm) {
|
||||
return (
|
||||
<NoResultsEmptyState
|
||||
title="No matching planned downtime"
|
||||
subtitle="No planned downtime matches your search. Try adjusting your search criteria."
|
||||
onClear={onClearSearch}
|
||||
clearButtonText="Clear Search"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (isEmpty) {
|
||||
return <PlannedDowntimeEmptyState canCreate={canEdit} onCreate={onCreate} />;
|
||||
}
|
||||
const { Panel } = Collapse;
|
||||
|
||||
interface AlertRuleTagsProps {
|
||||
selectedTags: DefaultOptionType | DefaultOptionType[];
|
||||
closable: boolean;
|
||||
handleClose?: (removedTag: DefaultOptionType['value']) => void;
|
||||
classname?: string;
|
||||
}
|
||||
export function AlertRuleTags(props: AlertRuleTagsProps): JSX.Element {
|
||||
const { closable, selectedTags, handleClose, classname } = props;
|
||||
return (
|
||||
<TanStackTable<DowntimeSchedulesTableData>
|
||||
data={pagedDowntimes}
|
||||
columns={columnsWithActions}
|
||||
isLoading={isFetching}
|
||||
getRowKey={(row): string => row.id}
|
||||
getItemKey={(row): string => row.id}
|
||||
getRowTestId={(row): string => `downtime-row-${row.id}`}
|
||||
columnStorageKey="planned-downtime-columns"
|
||||
enableQueryParams={PLANNED_DOWNTIME_QUERY_PARAMS}
|
||||
onRowClick={canEdit ? onEdit : undefined}
|
||||
pagination={{
|
||||
total: downtimes.length,
|
||||
calculatedPageSize,
|
||||
onLimitChange,
|
||||
showTotalCount: true,
|
||||
}}
|
||||
paginationClassname={styles.paginationContainer}
|
||||
enableAlternatingRowColors
|
||||
plainTextCellLineClamp={1}
|
||||
/>
|
||||
<Space
|
||||
wrap
|
||||
style={{ marginBottom: 8 }}
|
||||
className={cx('alert-rule-tags', classname)}
|
||||
>
|
||||
{selectedTags?.map((tag: DefaultOptionType, index: number) => {
|
||||
if (closable) {
|
||||
return (
|
||||
<Pill.Closeable
|
||||
key={tag.value}
|
||||
maxWidth={200}
|
||||
onClose={(): void => handleClose?.(tag.value)}
|
||||
>
|
||||
{tag.label}
|
||||
</Pill.Closeable>
|
||||
);
|
||||
}
|
||||
|
||||
const isLongTag = (tag?.label as string)?.length > 20;
|
||||
const tagElem = (
|
||||
<Badge
|
||||
textTransform="none"
|
||||
key={tag.value}
|
||||
color={index % 2 ? 'highlight-danger' : 'primary'}
|
||||
variant="outlined"
|
||||
>
|
||||
{isLongTag
|
||||
? `${(tag?.label as string | null)?.slice(0, 20)}...`
|
||||
: tag?.label}
|
||||
</Badge>
|
||||
);
|
||||
return (
|
||||
<Tooltip title={isLongTag ? tag?.label : undefined} key={tag?.value}>
|
||||
{tagElem}
|
||||
</Tooltip>
|
||||
);
|
||||
})}
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
|
||||
export default PlannedDowntimeList;
|
||||
function HeaderComponent({
|
||||
name,
|
||||
duration,
|
||||
handleEdit,
|
||||
handleDelete,
|
||||
}: {
|
||||
name: string;
|
||||
duration: string;
|
||||
handleEdit: () => void;
|
||||
handleDelete: () => void;
|
||||
}): JSX.Element {
|
||||
const { user } = useAppContext();
|
||||
const isCrudEnabled = user?.role !== USER_ROLES.VIEWER;
|
||||
return (
|
||||
<Flex className="header-content" justify="space-between">
|
||||
<Flex gap={8}>
|
||||
<Typography>{name}</Typography>
|
||||
<Badge textTransform="none" variant="solid" color="secondary">
|
||||
{duration}
|
||||
</Badge>
|
||||
</Flex>
|
||||
|
||||
{isCrudEnabled && (
|
||||
<div className="action-btn">
|
||||
<PenLine
|
||||
size={14}
|
||||
onClick={(e): void => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
handleEdit();
|
||||
}}
|
||||
/>
|
||||
<Trash2
|
||||
size={14}
|
||||
color={Color.BG_CHERRY_500}
|
||||
onClick={(e): void => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
handleDelete();
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</Flex>
|
||||
);
|
||||
}
|
||||
|
||||
export function CollapseListContent({
|
||||
created_at,
|
||||
created_by_name,
|
||||
created_by_email,
|
||||
schedule,
|
||||
updated_at,
|
||||
updated_by_name,
|
||||
alertOptions,
|
||||
}: {
|
||||
created_at?: string;
|
||||
created_by_name?: string;
|
||||
created_by_email?: string;
|
||||
schedule?: AlertmanagertypesScheduleDTO;
|
||||
updated_at?: string;
|
||||
updated_by_name?: string;
|
||||
alertOptions?: DefaultOptionType[];
|
||||
}): JSX.Element {
|
||||
const renderItems = (title: string, value: ReactNode): JSX.Element => (
|
||||
<div className="render-item-collapse-list">
|
||||
<Typography>{title}</Typography>
|
||||
<div className="render-item-value">{value}</div>
|
||||
</div>
|
||||
);
|
||||
const startTime = formatDateTime(schedule?.startTime, schedule?.timezone);
|
||||
const endTime = formatDateTime(schedule?.endTime, schedule?.timezone);
|
||||
|
||||
return (
|
||||
<Flex vertical>
|
||||
{renderItems(
|
||||
'Created by',
|
||||
created_by_name ? (
|
||||
<Flex gap={8}>
|
||||
<Typography>{created_by_name}</Typography>
|
||||
{created_by_email && (
|
||||
<Badge textTransform="none" variant="solid" color="secondary">
|
||||
{created_by_email}
|
||||
</Badge>
|
||||
)}
|
||||
</Flex>
|
||||
) : (
|
||||
'-'
|
||||
),
|
||||
)}
|
||||
{renderItems(
|
||||
'Created on',
|
||||
created_at ? (
|
||||
<Typography>{`${formatDateTime(created_at)}`}</Typography>
|
||||
) : (
|
||||
'-'
|
||||
),
|
||||
)}
|
||||
{updated_at &&
|
||||
renderItems(
|
||||
'Updated on',
|
||||
<Typography>{`${formatDateTime(updated_at)}`}</Typography>,
|
||||
)}
|
||||
{updated_by_name &&
|
||||
renderItems('Updated by', <Typography>{updated_by_name}</Typography>)}
|
||||
|
||||
{renderItems(
|
||||
'Timeframe',
|
||||
schedule?.startTime ? (
|
||||
<Typography>{`${startTime} ⎯ ${endTime}`}</Typography>
|
||||
) : (
|
||||
'-'
|
||||
),
|
||||
)}
|
||||
{renderItems(
|
||||
'Timezone',
|
||||
<Typography>{schedule?.timezone || '-'}</Typography>,
|
||||
)}
|
||||
{renderItems('Repeats', <Typography>{recurrenceInfo(schedule)}</Typography>)}
|
||||
{renderItems(
|
||||
'Alerts silenced',
|
||||
alertOptions?.length ? (
|
||||
<AlertRuleTags
|
||||
closable={false}
|
||||
classname="alert-rule-collapse-list"
|
||||
selectedTags={alertOptions}
|
||||
/>
|
||||
) : (
|
||||
<Badge variant="solid" color="secondary">
|
||||
All alert rules
|
||||
</Badge>
|
||||
),
|
||||
)}
|
||||
</Flex>
|
||||
);
|
||||
}
|
||||
|
||||
export function CustomCollapseList(
|
||||
props: DowntimeSchedulesTableData & {
|
||||
setInitialValues: React.Dispatch<
|
||||
React.SetStateAction<Partial<AlertmanagertypesPlannedMaintenanceDTO>>
|
||||
>;
|
||||
setModalOpen: React.Dispatch<React.SetStateAction<boolean>>;
|
||||
handleDeleteDowntime: (id: string, name: string) => void;
|
||||
setEditMode: React.Dispatch<React.SetStateAction<boolean>>;
|
||||
},
|
||||
): JSX.Element {
|
||||
const {
|
||||
createdAt,
|
||||
createdBy,
|
||||
schedule,
|
||||
updatedAt,
|
||||
updatedBy,
|
||||
name,
|
||||
id,
|
||||
alertOptions,
|
||||
setInitialValues,
|
||||
setModalOpen,
|
||||
handleDeleteDowntime,
|
||||
setEditMode,
|
||||
} = props;
|
||||
|
||||
const scheduleTime = schedule?.startTime
|
||||
? dayjs(schedule.startTime).tz(schedule.timezone)
|
||||
: createdAt || '';
|
||||
const formattedDateAndTime = `Start time ⎯ ${formatDateTime(scheduleTime)} ${schedule?.timezone}`;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Collapse accordion className="collapse-list">
|
||||
<Panel
|
||||
header={
|
||||
<HeaderComponent
|
||||
duration={
|
||||
schedule?.recurrence?.duration
|
||||
? schedule.recurrence.duration
|
||||
: getDuration(schedule?.startTime || '', schedule?.endTime || '')
|
||||
}
|
||||
name={defaultTo(name, '')}
|
||||
handleEdit={() => {
|
||||
setInitialValues({ ...props });
|
||||
setModalOpen(true);
|
||||
setEditMode(true);
|
||||
}}
|
||||
handleDelete={() => handleDeleteDowntime(id ?? '', name || '')}
|
||||
/>
|
||||
}
|
||||
key={id ?? ''}
|
||||
>
|
||||
<CollapseListContent
|
||||
created_at={createdAt ? dayjs(createdAt).toISOString() : ''}
|
||||
created_by_name={defaultTo(createdBy, '')}
|
||||
schedule={schedule}
|
||||
updated_at={updatedAt ? dayjs(updatedAt).toISOString() : ''}
|
||||
updated_by_name={defaultTo(updatedBy, '')}
|
||||
alertOptions={alertOptions}
|
||||
/>
|
||||
</Panel>
|
||||
</Collapse>
|
||||
<div className="schedule-created-at">
|
||||
<CalendarClock size={14} />
|
||||
<Typography.Text>{formattedDateAndTime}</Typography.Text>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export type DowntimeSchedulesTableData =
|
||||
AlertmanagertypesPlannedMaintenanceDTO & {
|
||||
alertOptions: DefaultOptionType[];
|
||||
};
|
||||
|
||||
export function PlannedDowntimeList({
|
||||
downtimeSchedules,
|
||||
alertOptions,
|
||||
setInitialValues,
|
||||
setModalOpen,
|
||||
handleDeleteDowntime,
|
||||
setEditMode,
|
||||
searchValue,
|
||||
}: {
|
||||
downtimeSchedules: UseQueryResult<
|
||||
ListDowntimeSchedules200,
|
||||
ErrorType<RenderErrorResponseDTO>
|
||||
>;
|
||||
alertOptions: DefaultOptionType[];
|
||||
setInitialValues: React.Dispatch<
|
||||
React.SetStateAction<Partial<AlertmanagertypesPlannedMaintenanceDTO>>
|
||||
>;
|
||||
setModalOpen: React.Dispatch<React.SetStateAction<boolean>>;
|
||||
handleDeleteDowntime: (id: string, name: string) => void;
|
||||
setEditMode: React.Dispatch<React.SetStateAction<boolean>>;
|
||||
searchValue: string | number;
|
||||
}): JSX.Element {
|
||||
const columns: TableProps<DowntimeSchedulesTableData>['columns'] = [
|
||||
{
|
||||
title: 'Downtime',
|
||||
key: 'downtime',
|
||||
render: (data: DowntimeSchedulesTableData): JSX.Element =>
|
||||
CustomCollapseList({
|
||||
...data,
|
||||
setInitialValues,
|
||||
setModalOpen,
|
||||
handleDeleteDowntime,
|
||||
setEditMode,
|
||||
}),
|
||||
},
|
||||
];
|
||||
const { notifications } = useNotifications();
|
||||
|
||||
const tableData = [...(downtimeSchedules.data?.data || [])]
|
||||
.sort((a, b): number => {
|
||||
if (a?.updatedAt && b?.updatedAt) {
|
||||
return dayjs(b.updatedAt).diff(dayjs(a.updatedAt));
|
||||
}
|
||||
return 0;
|
||||
})
|
||||
.filter(
|
||||
(data) =>
|
||||
data.name.includes(searchValue.toLocaleString()) ||
|
||||
data.id === searchValue.toLocaleString(),
|
||||
)
|
||||
.map((data) => {
|
||||
const specificAlertOptions = getAlertOptionsFromIds(
|
||||
data.alertIds || [],
|
||||
alertOptions,
|
||||
);
|
||||
|
||||
return { ...data, alertOptions: specificAlertOptions };
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (downtimeSchedules.isError) {
|
||||
showErrorNotification(notifications, downtimeSchedules.error);
|
||||
}
|
||||
}, [downtimeSchedules.error, downtimeSchedules.isError, notifications]);
|
||||
|
||||
const paginationConfig = {
|
||||
pageSize: 5,
|
||||
showSizeChanger: false,
|
||||
hideOnSinglePage: true,
|
||||
};
|
||||
return (
|
||||
<Table<DowntimeSchedulesTableData>
|
||||
columns={columns}
|
||||
className="planned-downtime-table"
|
||||
bordered={false}
|
||||
dataSource={tableData || []}
|
||||
loading={downtimeSchedules.isLoading || downtimeSchedules.isFetching}
|
||||
showHeader={false}
|
||||
pagination={paginationConfig}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { UseMutateAsyncFunction } from 'react-query';
|
||||
import type { NotificationInstance } from 'antd/es/notification/interface';
|
||||
import type { DefaultOptionType } from 'antd/es/select';
|
||||
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
|
||||
import type {
|
||||
DeleteDowntimeScheduleByIDPathParameters,
|
||||
@@ -12,8 +13,6 @@ import { AxiosError } from 'axios';
|
||||
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
|
||||
import dayjs, { Dayjs } from 'dayjs';
|
||||
import { isEmpty } from 'lodash-es';
|
||||
|
||||
import type { DowntimeAlertOption } from './types';
|
||||
import APIError from 'types/api/error';
|
||||
|
||||
type DateTimeString = string | null | undefined;
|
||||
@@ -57,8 +56,8 @@ export const formatDateTime = (
|
||||
|
||||
export const getAlertOptionsFromIds = (
|
||||
alertIds: string[],
|
||||
alertOptions: DowntimeAlertOption[],
|
||||
): DowntimeAlertOption[] =>
|
||||
alertOptions: DefaultOptionType[],
|
||||
): DefaultOptionType[] =>
|
||||
alertOptions.filter(
|
||||
(alert) =>
|
||||
alert !== undefined &&
|
||||
@@ -222,48 +221,3 @@ export const recurrenceOptionWithSubmenu: Option[] = [
|
||||
export const isScheduleRecurring = (
|
||||
schedule?: AlertmanagertypesPlannedMaintenanceDTO['schedule'] | null,
|
||||
): boolean => (schedule ? !isEmpty(schedule?.recurrence) : false);
|
||||
|
||||
const REPEAT_TYPE_LABEL: Record<string, string> = {
|
||||
daily: 'Daily',
|
||||
weekly: 'Weekly',
|
||||
monthly: 'Monthly',
|
||||
};
|
||||
|
||||
export const formatRepeats = (
|
||||
schedule: AlertmanagertypesScheduleDTO,
|
||||
): string => {
|
||||
const recurrence = schedule.recurrence;
|
||||
if (!recurrence) {
|
||||
return 'Does not repeat';
|
||||
}
|
||||
|
||||
const label =
|
||||
REPEAT_TYPE_LABEL[recurrence.repeatType] ?? recurrence.repeatType;
|
||||
const days = recurrence.repeatOn?.length
|
||||
? ` on ${recurrence.repeatOn
|
||||
.map((day) => day.charAt(0).toUpperCase() + day.slice(1, 3))
|
||||
.join(', ')}`
|
||||
: '';
|
||||
const duration = recurrence.duration ? ` · ${recurrence.duration}` : '';
|
||||
return `${label}${days}${duration}`;
|
||||
};
|
||||
|
||||
export const formatWindow = (
|
||||
schedule: AlertmanagertypesScheduleDTO,
|
||||
): string => {
|
||||
if (!schedule.startTime) {
|
||||
return '-';
|
||||
}
|
||||
const start = formatDateTime(schedule.startTime, schedule.timezone);
|
||||
const timezone = schedule.timezone ? ` (${schedule.timezone})` : '';
|
||||
if (!schedule.endTime) {
|
||||
return `From ${start}${timezone}`;
|
||||
}
|
||||
return `${start} ⎯ ${formatDateTime(schedule.endTime, schedule.timezone)}${timezone}`;
|
||||
};
|
||||
|
||||
export const formatScheduleDuration = (
|
||||
schedule: AlertmanagertypesScheduleDTO,
|
||||
): string =>
|
||||
schedule.recurrence?.duration ||
|
||||
getDuration(schedule.startTime, schedule.endTime);
|
||||
|
||||
@@ -2,7 +2,7 @@ import { screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { render } from 'tests/test-utils';
|
||||
|
||||
import { AlertRuleTags } from '../AlertRuleTags';
|
||||
import { AlertRuleTags } from '../PlannedDowntimeList';
|
||||
|
||||
const RULES = [
|
||||
{ label: 'Postgres connections near limit', value: 'rule-5' },
|
||||
|
||||
@@ -1,34 +1,21 @@
|
||||
import { UseQueryResult } from 'react-query';
|
||||
import { VirtuosoMockContext } from 'react-virtuoso';
|
||||
import { fireEvent, screen } from '@testing-library/react';
|
||||
import type {
|
||||
ListDowntimeSchedules200,
|
||||
RenderErrorResponseDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
AlertmanagertypesRepeatOnDTO,
|
||||
AlertmanagertypesRepeatTypeDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import type { ErrorType } from 'api/generatedAPIInstance';
|
||||
import { mockLocation } from 'container/RoutingPolicies/__tests__/testUtils';
|
||||
import { render, userEvent } from 'tests/test-utils';
|
||||
import {
|
||||
mockLocation,
|
||||
mockQueryParams,
|
||||
} from 'container/RoutingPolicies/__tests__/testUtils';
|
||||
import { render } from 'tests/test-utils';
|
||||
import { USER_ROLES } from 'types/roles';
|
||||
|
||||
import { PlannedDowntime } from '../PlannedDowntime';
|
||||
import { buildSchedule, createMockDowntime } from './testUtils';
|
||||
|
||||
const SEARCH_TEST_ID = 'planned-downtime-search';
|
||||
const CREATE_TEST_ID = 'planned-downtime-create';
|
||||
|
||||
function renderPage(role: string = USER_ROLES.ADMIN): void {
|
||||
render(
|
||||
<VirtuosoMockContext.Provider value={{ viewportHeight: 800, itemHeight: 46 }}>
|
||||
<PlannedDowntime />
|
||||
</VirtuosoMockContext.Provider>,
|
||||
{},
|
||||
{ role },
|
||||
);
|
||||
}
|
||||
const SEARCH_PLACEHOLDER = 'Search for a planned downtime...';
|
||||
|
||||
const MOCK_DOWNTIME_1_NAME = 'Mock Downtime 1';
|
||||
const MOCK_DOWNTIME_2_NAME = 'Mock Downtime 2';
|
||||
@@ -40,19 +27,11 @@ const MOCK_DATE_3 = '2024-01-03';
|
||||
const MOCK_DOWNTIME_1 = createMockDowntime({
|
||||
id: '1',
|
||||
name: MOCK_DOWNTIME_1_NAME,
|
||||
description: 'Database maintenance',
|
||||
createdAt: MOCK_DATE_1,
|
||||
createdBy: 'creator@signoz.io',
|
||||
updatedAt: MOCK_DATE_1,
|
||||
updatedBy: 'editor@signoz.io',
|
||||
schedule: buildSchedule({
|
||||
startTime: MOCK_DATE_1,
|
||||
timezone: 'Asia/Kolkata',
|
||||
recurrence: {
|
||||
duration: '2h',
|
||||
repeatType: AlertmanagertypesRepeatTypeDTO.weekly,
|
||||
repeatOn: [AlertmanagertypesRepeatOnDTO.monday],
|
||||
},
|
||||
timezone: 'UTC',
|
||||
}),
|
||||
alertIds: [],
|
||||
});
|
||||
@@ -147,152 +126,113 @@ jest.mock('api/generated/services/rules', () => ({
|
||||
describe('PlannedDowntime Component', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockUrlQuery = new URLSearchParams();
|
||||
mockUrlQuery = mockQueryParams({});
|
||||
mockLocation('/alerts');
|
||||
});
|
||||
|
||||
it('renders the header, search and create action', () => {
|
||||
renderPage();
|
||||
it('renders the PlannedDowntime component properly', () => {
|
||||
render(<PlannedDowntime />, {}, { role: 'ADMIN' });
|
||||
|
||||
// Check if title is rendered
|
||||
expect(screen.getByText('Planned Downtime')).toBeInTheDocument();
|
||||
expect(screen.getByTestId(SEARCH_TEST_ID)).toBeInTheDocument();
|
||||
expect(screen.getByTestId(CREATE_TEST_ID)).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'false',
|
||||
);
|
||||
|
||||
// Check if subtitle is rendered
|
||||
expect(
|
||||
screen.getByText('Create and manage planned downtimes.'),
|
||||
).toBeInTheDocument();
|
||||
|
||||
// Check if search input is rendered
|
||||
expect(screen.getByPlaceholderText(SEARCH_PLACEHOLDER)).toBeInTheDocument();
|
||||
|
||||
// Check if "New downtime" button is enabled for ADMIN
|
||||
const newDowntimeButton = screen.getByRole('button', {
|
||||
name: /new downtime/i,
|
||||
});
|
||||
expect(newDowntimeButton).toBeInTheDocument();
|
||||
expect(newDowntimeButton).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('disables the "New downtime" button for users with VIEWER role', () => {
|
||||
renderPage(USER_ROLES.VIEWER);
|
||||
render(<PlannedDowntime />, {}, { role: USER_ROLES.VIEWER });
|
||||
|
||||
expect(screen.getByTestId(CREATE_TEST_ID)).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
// Check if "New downtime" button is disabled for VIEWER
|
||||
const newDowntimeButton = screen.getByRole('button', {
|
||||
name: /new downtime/i,
|
||||
});
|
||||
expect(newDowntimeButton).toBeInTheDocument();
|
||||
expect(newDowntimeButton).toBeDisabled();
|
||||
|
||||
expect(newDowntimeButton).toHaveAttribute('disabled');
|
||||
});
|
||||
|
||||
it('should load with search term from URL query params', () => {
|
||||
const searchTerm = 'existing search';
|
||||
mockUrlQuery = new URLSearchParams({ search: searchTerm });
|
||||
mockUrlQuery = mockQueryParams({ search: searchTerm });
|
||||
|
||||
renderPage();
|
||||
render(<PlannedDowntime />, {}, { role: USER_ROLES.ADMIN });
|
||||
|
||||
const searchInput = screen.getByTestId(SEARCH_TEST_ID) as HTMLInputElement;
|
||||
const searchInput = screen.getByPlaceholderText(
|
||||
SEARCH_PLACEHOLDER,
|
||||
) as HTMLInputElement;
|
||||
expect(searchInput.value).toBe(searchTerm);
|
||||
});
|
||||
|
||||
it('should initialize with empty search when no search param is in URL', () => {
|
||||
renderPage();
|
||||
mockUrlQuery = mockQueryParams({});
|
||||
|
||||
const searchInput = screen.getByTestId(SEARCH_TEST_ID) as HTMLInputElement;
|
||||
render(<PlannedDowntime />, {}, { role: USER_ROLES.ADMIN });
|
||||
|
||||
const searchInput = screen.getByPlaceholderText(
|
||||
SEARCH_PLACEHOLDER,
|
||||
) as HTMLInputElement;
|
||||
expect(searchInput.value).toBe('');
|
||||
});
|
||||
|
||||
it('should display all downtime schedules when no search term is entered', async () => {
|
||||
renderPage();
|
||||
render(<PlannedDowntime />, {}, { role: USER_ROLES.ADMIN });
|
||||
|
||||
await expect(
|
||||
screen.findByText(MOCK_DOWNTIME_1_NAME),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.getByText(MOCK_DOWNTIME_1_NAME)).toBeInTheDocument();
|
||||
expect(screen.getByText(MOCK_DOWNTIME_2_NAME)).toBeInTheDocument();
|
||||
expect(screen.getByText(MOCK_DOWNTIME_3_NAME)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the key schedule details and hides secondary columns by default', async () => {
|
||||
renderPage();
|
||||
|
||||
await screen.findByText(MOCK_DOWNTIME_1_NAME);
|
||||
expect(screen.getByText(/\(Asia\/Kolkata\)$/)).toBeInTheDocument();
|
||||
expect(screen.getByText('Weekly on Mon · 2h')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Asia/Kolkata')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('2h')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Database maintenance')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('creator@signoz.io')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('editor@signoz.io')).not.toBeInTheDocument();
|
||||
expect(screen.getAllByText('All alert rules')).toHaveLength(3);
|
||||
expect(screen.getAllByText('Active')).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('lets every data column be resized', async () => {
|
||||
renderPage();
|
||||
|
||||
await screen.findByText(MOCK_DOWNTIME_1_NAME);
|
||||
const resizable = Array.from(document.querySelectorAll('th'))
|
||||
.filter((th) => th.querySelector('[title="Drag to resize column"]'))
|
||||
.map((th) => th.textContent?.trim());
|
||||
expect(resizable).toStrictEqual([
|
||||
'Downtime',
|
||||
'Status',
|
||||
'Schedule',
|
||||
'Repeats',
|
||||
'Alerts Silenced',
|
||||
]);
|
||||
});
|
||||
|
||||
it('should filter downtime schedules by name when searching', async () => {
|
||||
renderPage();
|
||||
render(<PlannedDowntime />, {}, { role: USER_ROLES.ADMIN });
|
||||
|
||||
await expect(
|
||||
screen.findByText(MOCK_DOWNTIME_1_NAME),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.getByText(MOCK_DOWNTIME_1_NAME)).toBeInTheDocument();
|
||||
|
||||
fireEvent.change(screen.getByTestId(SEARCH_TEST_ID), {
|
||||
target: { value: MOCK_DOWNTIME_1_NAME },
|
||||
});
|
||||
const searchInput = screen.getByPlaceholderText(SEARCH_PLACEHOLDER);
|
||||
|
||||
await expect(
|
||||
screen.findByText(MOCK_DOWNTIME_1_NAME),
|
||||
).resolves.toBeInTheDocument();
|
||||
fireEvent.change(searchInput, { target: { value: MOCK_DOWNTIME_1_NAME } });
|
||||
|
||||
expect(screen.getByText(MOCK_DOWNTIME_1_NAME)).toBeInTheDocument();
|
||||
expect(screen.queryByText(MOCK_DOWNTIME_2_NAME)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(MOCK_DOWNTIME_3_NAME)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should filter downtime schedules with partial name match', async () => {
|
||||
renderPage();
|
||||
render(<PlannedDowntime />, {}, { role: USER_ROLES.ADMIN });
|
||||
|
||||
await expect(
|
||||
screen.findByText(MOCK_DOWNTIME_1_NAME),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.getByText(MOCK_DOWNTIME_1_NAME)).toBeInTheDocument();
|
||||
|
||||
fireEvent.change(screen.getByTestId(SEARCH_TEST_ID), {
|
||||
target: { value: '2' },
|
||||
});
|
||||
const searchInput = screen.getByPlaceholderText(SEARCH_PLACEHOLDER);
|
||||
|
||||
await expect(
|
||||
screen.findByText(MOCK_DOWNTIME_2_NAME),
|
||||
).resolves.toBeInTheDocument();
|
||||
fireEvent.change(searchInput, { target: { value: '2' } });
|
||||
|
||||
expect(screen.getByText(MOCK_DOWNTIME_2_NAME)).toBeInTheDocument();
|
||||
expect(screen.queryByText(MOCK_DOWNTIME_1_NAME)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(MOCK_DOWNTIME_3_NAME)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show no results when search term matches nothing', async () => {
|
||||
renderPage();
|
||||
render(<PlannedDowntime />, {}, { role: USER_ROLES.ADMIN });
|
||||
|
||||
fireEvent.change(screen.getByTestId(SEARCH_TEST_ID), {
|
||||
target: { value: 'NonExistentDowntime' },
|
||||
});
|
||||
const searchInput = screen.getByPlaceholderText(SEARCH_PLACEHOLDER);
|
||||
|
||||
fireEvent.change(searchInput, { target: { value: 'NonExistentDowntime' } });
|
||||
|
||||
await expect(
|
||||
screen.findByTestId('no-results-empty-state'),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.queryByText(MOCK_DOWNTIME_1_NAME)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens the delete confirmation from the row actions', async () => {
|
||||
renderPage();
|
||||
|
||||
await userEvent.click(await screen.findByTestId('downtime-actions-1'));
|
||||
await userEvent.click(await screen.findByText('Delete'));
|
||||
|
||||
await expect(
|
||||
screen.findByRole('button', { name: 'Delete Schedule' }),
|
||||
).resolves.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides row actions for viewers', async () => {
|
||||
renderPage(USER_ROLES.VIEWER);
|
||||
|
||||
await screen.findByText(MOCK_DOWNTIME_1_NAME);
|
||||
expect(screen.queryByTestId('downtime-actions-1')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(MOCK_DOWNTIME_2_NAME)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(MOCK_DOWNTIME_3_NAME)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,236 +0,0 @@
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
import { AlertmanagertypesMaintenanceStatusDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import type { TableColumnDef } from 'components/TanStackTableView';
|
||||
import TanStackTable from 'components/TanStackTableView';
|
||||
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
|
||||
import { toRelativeTime } from 'pages/AlertList/NotificationChannels/utils/relativeTime';
|
||||
|
||||
import styles from './PlannedDowntime.module.scss';
|
||||
import {
|
||||
formatRepeats,
|
||||
formatScheduleDuration,
|
||||
formatWindow,
|
||||
} from './PlannedDowntimeutils';
|
||||
import { DowntimeSchedulesTableData } from './types';
|
||||
|
||||
const STATUS_BADGE: Record<
|
||||
AlertmanagertypesMaintenanceStatusDTO,
|
||||
{ label: string; color: 'success' | 'info' | 'secondary' }
|
||||
> = {
|
||||
[AlertmanagertypesMaintenanceStatusDTO.active]: {
|
||||
label: 'Active',
|
||||
color: 'success',
|
||||
},
|
||||
[AlertmanagertypesMaintenanceStatusDTO.upcoming]: {
|
||||
label: 'Upcoming',
|
||||
color: 'info',
|
||||
},
|
||||
[AlertmanagertypesMaintenanceStatusDTO.expired]: {
|
||||
label: 'Expired',
|
||||
color: 'secondary',
|
||||
},
|
||||
};
|
||||
|
||||
export function getPlannedDowntimeColumns(
|
||||
formatTimezoneAdjustedTimestamp: (date: string, format: string) => string,
|
||||
): TableColumnDef<DowntimeSchedulesTableData>[] {
|
||||
const textCell = (value: string | undefined): JSX.Element => (
|
||||
<TanStackTable.Text title={value || undefined}>
|
||||
{value || '-'}
|
||||
</TanStackTable.Text>
|
||||
);
|
||||
|
||||
const timestampCell = (
|
||||
row: DowntimeSchedulesTableData,
|
||||
value: string | undefined,
|
||||
): JSX.Element => {
|
||||
if (!value) {
|
||||
return <TanStackTable.Text>-</TanStackTable.Text>;
|
||||
}
|
||||
|
||||
return (
|
||||
<TanStackTable.HoverTooltip
|
||||
rowId={row.id}
|
||||
title={formatTimezoneAdjustedTimestamp(
|
||||
value,
|
||||
DATE_TIME_FORMATS.DASH_DATETIME,
|
||||
)}
|
||||
>
|
||||
<span className={styles.timeText}>{toRelativeTime(value)}</span>
|
||||
</TanStackTable.HoverTooltip>
|
||||
);
|
||||
};
|
||||
|
||||
return [
|
||||
{
|
||||
id: 'name',
|
||||
header: 'Downtime',
|
||||
accessorKey: 'name',
|
||||
width: { default: '100%', min: '200px' },
|
||||
enableSort: true,
|
||||
enableResize: true,
|
||||
enableRemove: false,
|
||||
enableMove: false,
|
||||
cell: ({ row }): JSX.Element => (
|
||||
<TanStackTable.Text
|
||||
title={row.name}
|
||||
data-testid={`downtime-row-${row.id}-name`}
|
||||
>
|
||||
{row.name}
|
||||
</TanStackTable.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'status',
|
||||
header: 'Status',
|
||||
accessorKey: 'status',
|
||||
width: { default: '110px', min: '100px' },
|
||||
enableSort: true,
|
||||
enableResize: true,
|
||||
enableMove: false,
|
||||
cell: ({ row }): JSX.Element => {
|
||||
const status = STATUS_BADGE[row.status];
|
||||
return status ? (
|
||||
<Badge textTransform="none" variant="outlined" color={status.color}>
|
||||
{status.label}
|
||||
</Badge>
|
||||
) : (
|
||||
textCell(row.status)
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'window',
|
||||
header: 'Schedule',
|
||||
accessorFn: (row) => row.schedule?.startTime,
|
||||
width: { default: '340px', min: '220px' },
|
||||
enableSort: true,
|
||||
enableResize: true,
|
||||
enableMove: false,
|
||||
cell: ({ row }): JSX.Element => textCell(formatWindow(row.schedule)),
|
||||
},
|
||||
{
|
||||
id: 'timezone',
|
||||
header: 'Timezone',
|
||||
accessorFn: (row) => row.schedule?.timezone,
|
||||
width: { default: '130px', min: '110px' },
|
||||
defaultVisibility: false,
|
||||
enableSort: false,
|
||||
enableResize: true,
|
||||
enableMove: false,
|
||||
cell: ({ row }): JSX.Element => textCell(row.schedule?.timezone),
|
||||
},
|
||||
{
|
||||
id: 'repeats',
|
||||
header: 'Repeats',
|
||||
accessorFn: (row) => row.schedule?.recurrence?.repeatType,
|
||||
width: { default: '180px', min: '120px' },
|
||||
enableSort: false,
|
||||
enableResize: true,
|
||||
enableMove: false,
|
||||
cell: ({ row }): JSX.Element => textCell(formatRepeats(row.schedule)),
|
||||
},
|
||||
{
|
||||
id: 'duration',
|
||||
header: 'Duration',
|
||||
accessorFn: (row) => row.schedule?.recurrence?.duration,
|
||||
width: { default: '110px', min: '90px' },
|
||||
defaultVisibility: false,
|
||||
enableSort: false,
|
||||
enableResize: true,
|
||||
enableMove: false,
|
||||
cell: ({ row }): JSX.Element =>
|
||||
textCell(formatScheduleDuration(row.schedule)),
|
||||
},
|
||||
{
|
||||
id: 'alertsSilenced',
|
||||
header: 'Alerts Silenced',
|
||||
accessorKey: 'alertIds',
|
||||
width: { default: '200px', min: '140px' },
|
||||
enableSort: false,
|
||||
enableResize: true,
|
||||
enableMove: false,
|
||||
cell: ({ row }): JSX.Element =>
|
||||
row.alertOptions.length ? (
|
||||
<div
|
||||
className={styles.badges}
|
||||
title={row.alertOptions
|
||||
.flatMap((alert) =>
|
||||
typeof alert.label === 'string' ? [alert.label] : [],
|
||||
)
|
||||
.join(', ')}
|
||||
>
|
||||
{row.alertOptions.map((alert) => (
|
||||
<Badge
|
||||
key={alert.value}
|
||||
textTransform="none"
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
>
|
||||
{alert.label}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<Badge textTransform="none" variant="solid" color="secondary">
|
||||
All alert rules
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'description',
|
||||
header: 'Description',
|
||||
accessorKey: 'description',
|
||||
width: { default: '200px', min: '120px' },
|
||||
defaultVisibility: false,
|
||||
enableSort: false,
|
||||
enableResize: true,
|
||||
enableMove: false,
|
||||
cell: ({ row }): JSX.Element => textCell(row.description),
|
||||
},
|
||||
{
|
||||
id: 'createdBy',
|
||||
header: 'Created By',
|
||||
accessorKey: 'createdBy',
|
||||
width: { default: '180px', min: '120px' },
|
||||
defaultVisibility: false,
|
||||
enableSort: false,
|
||||
enableResize: true,
|
||||
enableMove: false,
|
||||
cell: ({ row }): JSX.Element => textCell(row.createdBy),
|
||||
},
|
||||
{
|
||||
id: 'createdAt',
|
||||
header: 'Created At',
|
||||
accessorKey: 'createdAt',
|
||||
width: { default: '150px', min: '120px' },
|
||||
defaultVisibility: false,
|
||||
enableSort: true,
|
||||
enableResize: true,
|
||||
enableMove: false,
|
||||
cell: ({ row }): JSX.Element => timestampCell(row, row.createdAt),
|
||||
},
|
||||
{
|
||||
id: 'updatedBy',
|
||||
header: 'Updated By',
|
||||
accessorKey: 'updatedBy',
|
||||
width: { default: '180px', min: '120px' },
|
||||
defaultVisibility: false,
|
||||
enableSort: false,
|
||||
enableResize: true,
|
||||
enableMove: false,
|
||||
cell: ({ row }): JSX.Element => textCell(row.updatedBy),
|
||||
},
|
||||
{
|
||||
id: 'updatedAt',
|
||||
header: 'Updated At',
|
||||
accessorKey: 'updatedAt',
|
||||
width: { default: '150px', min: '120px' },
|
||||
defaultVisibility: false,
|
||||
enableSort: true,
|
||||
enableResize: true,
|
||||
enableMove: false,
|
||||
cell: ({ row }): JSX.Element => timestampCell(row, row.updatedAt),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import type { AlertmanagertypesPlannedMaintenanceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import type { TableColumnDef } from 'components/TanStackTableView';
|
||||
import type { SelectOption } from 'types/common/select';
|
||||
|
||||
export type DowntimeAlertOption = Omit<
|
||||
SelectOption<string | number | null, ReactNode>,
|
||||
'value'
|
||||
> & {
|
||||
value?: string | number | null;
|
||||
};
|
||||
|
||||
export type DowntimeSchedulesTableData =
|
||||
AlertmanagertypesPlannedMaintenanceDTO & {
|
||||
alertOptions: DowntimeAlertOption[];
|
||||
};
|
||||
|
||||
export interface PlannedDowntimeListProps {
|
||||
columns: TableColumnDef<DowntimeSchedulesTableData>[];
|
||||
downtimes: DowntimeSchedulesTableData[];
|
||||
pagedDowntimes: DowntimeSchedulesTableData[];
|
||||
calculatedPageSize: number | null;
|
||||
onLimitChange: (limit: number) => void;
|
||||
isFetching: boolean;
|
||||
isError: boolean;
|
||||
refetch: () => void;
|
||||
canEdit: boolean;
|
||||
onEdit: (downtime: DowntimeSchedulesTableData) => void;
|
||||
onDelete: (downtime: DowntimeSchedulesTableData) => void;
|
||||
onCreate: () => void;
|
||||
hasSearchTerm: boolean;
|
||||
onClearSearch: () => void;
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
import { RefObject, useMemo } from 'react';
|
||||
import type { AlertmanagertypesPlannedMaintenanceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { sortByColumn } from 'components/Alerts/utils';
|
||||
import type { SortState } from 'components/TanStackTableView/types';
|
||||
import { useCalculatedPageSize } from 'components/TanStackTableView/useCalculatedPageSize';
|
||||
import { useTableParams } from 'components/TanStackTableView/useTableParams';
|
||||
|
||||
import { getAlertOptionsFromIds } from './PlannedDowntimeutils';
|
||||
import { DowntimeAlertOption, DowntimeSchedulesTableData } from './types';
|
||||
|
||||
export const PLANNED_DOWNTIME_QUERY_PARAMS = {
|
||||
orderBy: 'orderBy',
|
||||
page: 'page',
|
||||
limit: 'limit',
|
||||
} as const;
|
||||
|
||||
const DEFAULT_PAGE = 1;
|
||||
const DEFAULT_LIMIT = 10;
|
||||
const DEFAULT_SORT: SortState = { columnName: 'updatedAt', order: 'desc' };
|
||||
|
||||
const toTime = (value: string | undefined): number =>
|
||||
value ? new Date(value).getTime() : 0;
|
||||
|
||||
function getSortValue(
|
||||
downtime: DowntimeSchedulesTableData,
|
||||
columnName: string,
|
||||
): string | number {
|
||||
switch (columnName) {
|
||||
case 'name':
|
||||
return downtime.name.toLowerCase();
|
||||
case 'status':
|
||||
return downtime.status;
|
||||
case 'window':
|
||||
return toTime(downtime.schedule?.startTime);
|
||||
case 'createdAt':
|
||||
return toTime(downtime.createdAt);
|
||||
case 'updatedAt':
|
||||
return toTime(downtime.updatedAt);
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
interface UsePlannedDowntimeTableReturn {
|
||||
containerRef: RefObject<HTMLDivElement>;
|
||||
calculatedPageSize: number | null;
|
||||
filteredDowntimes: DowntimeSchedulesTableData[];
|
||||
pagedDowntimes: DowntimeSchedulesTableData[];
|
||||
setPage: (page: number) => void;
|
||||
setLimit: (limit: number) => void;
|
||||
}
|
||||
|
||||
function usePlannedDowntimeTable(
|
||||
downtimes: AlertmanagertypesPlannedMaintenanceDTO[],
|
||||
alertOptions: DowntimeAlertOption[],
|
||||
searchValue: string,
|
||||
): UsePlannedDowntimeTableReturn {
|
||||
const { containerRef, calculatedPageSize } = useCalculatedPageSize({
|
||||
rowHeight: 46,
|
||||
});
|
||||
|
||||
const { orderBy, page, limit, setLimit, setPage } = useTableParams(
|
||||
PLANNED_DOWNTIME_QUERY_PARAMS,
|
||||
{
|
||||
page: DEFAULT_PAGE,
|
||||
limit: DEFAULT_LIMIT,
|
||||
storageKey: 'planned-downtime',
|
||||
calculatedPageSize,
|
||||
cleanupOnUnmount: true,
|
||||
},
|
||||
);
|
||||
|
||||
const filteredDowntimes = useMemo(() => {
|
||||
const search = searchValue.toLowerCase();
|
||||
return downtimes
|
||||
.filter(
|
||||
(downtime) =>
|
||||
downtime.name.toLowerCase().includes(search) ||
|
||||
downtime.id === searchValue,
|
||||
)
|
||||
.map((downtime) => ({
|
||||
...downtime,
|
||||
alertOptions: getAlertOptionsFromIds(downtime.alertIds || [], alertOptions),
|
||||
}));
|
||||
}, [downtimes, alertOptions, searchValue]);
|
||||
|
||||
const pagedDowntimes = useMemo(() => {
|
||||
const sorted = sortByColumn(
|
||||
filteredDowntimes,
|
||||
orderBy,
|
||||
getSortValue,
|
||||
DEFAULT_SORT,
|
||||
);
|
||||
const start = (page - 1) * limit;
|
||||
return sorted.slice(start, start + limit);
|
||||
}, [filteredDowntimes, orderBy, page, limit]);
|
||||
|
||||
return {
|
||||
containerRef,
|
||||
calculatedPageSize,
|
||||
filteredDowntimes,
|
||||
pagedDowntimes,
|
||||
setPage,
|
||||
setLimit,
|
||||
};
|
||||
}
|
||||
|
||||
export default usePlannedDowntimeTable;
|
||||
@@ -112,7 +112,7 @@ export function Formula({
|
||||
);
|
||||
|
||||
return (
|
||||
<Row gutter={[0, 15]} data-testid={`formula-${formula.queryName}`}>
|
||||
<Row gutter={[0, 15]}>
|
||||
<QBEntityOptions
|
||||
isCollapsed={isCollapse}
|
||||
showFunctions={false}
|
||||
@@ -130,7 +130,6 @@ export function Formula({
|
||||
<Input.TextArea
|
||||
name="expression"
|
||||
className="formula-expression"
|
||||
data-testid="formula-expression"
|
||||
onChange={handleChange}
|
||||
size="middle"
|
||||
value={formula.expression}
|
||||
@@ -142,7 +141,6 @@ export function Formula({
|
||||
<Input
|
||||
name="legend"
|
||||
className="formula-legend"
|
||||
data-testid="formula-legend"
|
||||
onChange={handleChange}
|
||||
size="middle"
|
||||
value={formula.legend}
|
||||
|
||||
@@ -98,7 +98,6 @@ export default function QBEntityOptions({
|
||||
value="search"
|
||||
className="periscope-btn collapse"
|
||||
onClick={onCollapseEntity}
|
||||
data-testid="qb-entity-collapse"
|
||||
>
|
||||
{isCollapsed ? <ChevronRight size={16} /> : <ChevronDown size={16} />}
|
||||
</Button>
|
||||
@@ -109,7 +108,6 @@ export default function QBEntityOptions({
|
||||
className="periscope-btn visibility-toggle"
|
||||
onClick={onToggleVisibility}
|
||||
disabled={isRawQuery && !showTraceOperator}
|
||||
data-testid="qb-entity-visibility"
|
||||
>
|
||||
{entityData.disabled ? <EyeOff size={16} /> : <Eye size={16} />}
|
||||
</Button>
|
||||
@@ -117,11 +115,7 @@ export default function QBEntityOptions({
|
||||
|
||||
{entityType === 'query' && showCloneOption && (
|
||||
<Tooltip title={`Clone Query ${entityData.queryName}`}>
|
||||
<Button
|
||||
className={cx('periscope-btn')}
|
||||
onClick={handleCloneEntity}
|
||||
data-testid="qb-entity-clone"
|
||||
>
|
||||
<Button className={cx('periscope-btn')} onClick={handleCloneEntity}>
|
||||
<Copy size={14} />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
@@ -137,7 +131,6 @@ export default function QBEntityOptions({
|
||||
: '',
|
||||
isLogsExplorerPage && lastUsedQuery === index ? 'sync-btn' : '',
|
||||
)}
|
||||
data-testid="qb-entity-name"
|
||||
>
|
||||
{entityData.queryName}
|
||||
</Button>
|
||||
@@ -192,11 +185,7 @@ export default function QBEntityOptions({
|
||||
</div>
|
||||
|
||||
{showDeleteButton && !isRawQuery && (
|
||||
<Button
|
||||
className="periscope-btn ghost"
|
||||
onClick={onDelete}
|
||||
data-testid="qb-entity-delete"
|
||||
>
|
||||
<Button className="periscope-btn ghost" onClick={onDelete}>
|
||||
<Trash2 size={14} />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
@@ -1,176 +0,0 @@
|
||||
.container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.headerBand {
|
||||
--control-height: 2rem;
|
||||
--input-height: var(--control-height);
|
||||
--input-wrapper-height: var(--control-height);
|
||||
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-6);
|
||||
flex-shrink: 0;
|
||||
padding: 0 var(--spacing-8) var(--spacing-6) var(--spacing-8);
|
||||
}
|
||||
|
||||
.commandHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-4);
|
||||
}
|
||||
|
||||
.headingBlock {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.title {
|
||||
margin: 0;
|
||||
color: var(--l1-foreground);
|
||||
font-size: var(--font-size-lg);
|
||||
font-weight: var(--font-weight-medium);
|
||||
line-height: 28px;
|
||||
letter-spacing: -0.09px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.countPill {
|
||||
padding: 2px 9px;
|
||||
border-radius: 999px;
|
||||
background: var(--l2-background);
|
||||
border: 1px solid var(--l2-border);
|
||||
color: var(--l2-foreground);
|
||||
font-size: var(--font-size-xs);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.grow {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.filtersRow {
|
||||
position: relative;
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-4);
|
||||
}
|
||||
|
||||
.searchInput {
|
||||
flex: 1 1 0;
|
||||
min-width: 220px;
|
||||
}
|
||||
|
||||
.searchIcon {
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.actionsHeader {
|
||||
display: block;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.tableContainer {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
--tanstack-table-row-hover-bg: var(--l2-background-hover);
|
||||
--tanstack-table-row-active-bg: var(--l2-background-active);
|
||||
--tanstack-table-row-height: 42px;
|
||||
|
||||
--tanstack-cell-padding-top-override: 5px;
|
||||
--tanstack-cell-padding-bottom-override: 5px;
|
||||
--tanstack-cell-padding-left-override: 16px;
|
||||
--tanstack-cell-padding-right-override: 16px;
|
||||
|
||||
--tanstack-table-row-odd-bg: color-mix(
|
||||
in srgb,
|
||||
var(--l1-foreground) 2%,
|
||||
transparent
|
||||
);
|
||||
--tanstack-table-row-even-bg: color-mix(
|
||||
in srgb,
|
||||
var(--l1-foreground) 1%,
|
||||
transparent
|
||||
);
|
||||
}
|
||||
|
||||
.paginationContainer {
|
||||
padding-right: var(--spacing-12);
|
||||
height: 62px;
|
||||
}
|
||||
|
||||
.expression {
|
||||
font-family: var(--font-mono, monospace);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.badges {
|
||||
display: flex;
|
||||
gap: var(--spacing-2);
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.timeText {
|
||||
display: inline-block;
|
||||
white-space: nowrap;
|
||||
font-size: var(--tanstack-plain-cell-font-size, 14px);
|
||||
line-height: var(--tanstack-plain-cell-line-height, 18px);
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.emptyState {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--spacing-3);
|
||||
padding: 48px 24px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.emptyIcon {
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.emptyTitle {
|
||||
color: var(--l1-foreground);
|
||||
font-size: 16px;
|
||||
font-weight: 500;
|
||||
line-height: 24px;
|
||||
}
|
||||
|
||||
.emptySubtitle {
|
||||
color: var(--l2-foreground);
|
||||
font-size: 14px;
|
||||
line-height: 20px;
|
||||
max-width: 420px;
|
||||
}
|
||||
|
||||
.docsLink {
|
||||
color: var(--l2-foreground);
|
||||
font-size: 13px;
|
||||
text-decoration: none;
|
||||
|
||||
&:hover {
|
||||
color: var(--l1-foreground);
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
@@ -1,30 +1,21 @@
|
||||
import { ChangeEvent, useCallback, useMemo } from 'react';
|
||||
import { ChangeEvent, useMemo } from 'react';
|
||||
import { Plus, Search } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Input } from '@signozhq/ui/input';
|
||||
import { Button, Flex, Tooltip } from 'antd';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { ColumnSelector } from 'components/TanStackTableView';
|
||||
import TextToolTip from 'components/TextToolTip';
|
||||
import { useAppContext } from 'providers/App/App';
|
||||
import { useTimezone } from 'providers/Timezone';
|
||||
import { USER_ROLES } from 'types/roles';
|
||||
|
||||
import DeleteRoutingPolicy from './DeleteRoutingPolicy';
|
||||
import styles from './RoutingPolicies.module.scss';
|
||||
import RoutingPolicyDetails from './RoutingPolicyDetails';
|
||||
import RoutingPolicyList from './RoutingPolicyList';
|
||||
import { getRoutingPolicyColumns } from './table.config';
|
||||
import { RoutingPolicy } from './types';
|
||||
import useRoutingPolicies from './useRoutingPolicies';
|
||||
import useRoutingPoliciesTable from './useRoutingPoliciesTable';
|
||||
|
||||
import './styles.scss';
|
||||
|
||||
const COLUMNS_STORAGE_KEY = 'routing-policies-columns';
|
||||
|
||||
function RoutingPolicies(): JSX.Element {
|
||||
const { user } = useAppContext();
|
||||
const { formatTimezoneAdjustedTimestamp } = useTimezone();
|
||||
const {
|
||||
// Routing Policies
|
||||
selectedRoutingPolicy,
|
||||
@@ -55,136 +46,79 @@ function RoutingPolicies(): JSX.Element {
|
||||
isPolicyDetailsModalActionLoading,
|
||||
} = useRoutingPolicies();
|
||||
|
||||
const { containerRef, calculatedPageSize, pagedPolicies, setPage, setLimit } =
|
||||
useRoutingPoliciesTable(routingPoliciesData);
|
||||
const disableCreateButton = user?.role === USER_ROLES.VIEWER;
|
||||
|
||||
const canEdit = user?.role !== USER_ROLES.VIEWER;
|
||||
|
||||
const columns = useMemo(
|
||||
() => getRoutingPolicyColumns(formatTimezoneAdjustedTimestamp),
|
||||
[formatTimezoneAdjustedTimestamp],
|
||||
);
|
||||
const tooltipTitle = useMemo(() => {
|
||||
if (user?.role === USER_ROLES.VIEWER) {
|
||||
return 'You need edit permissions to create a routing policy';
|
||||
}
|
||||
return '';
|
||||
}, [user?.role]);
|
||||
|
||||
const handleSearch = (e: ChangeEvent<HTMLInputElement>): void => {
|
||||
setSearchTerm(e.target.value || '');
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const handleClearSearch = useCallback((): void => {
|
||||
setSearchTerm('');
|
||||
setPage(1);
|
||||
}, [setSearchTerm, setPage]);
|
||||
|
||||
const handleCreate = useCallback(
|
||||
(): void => handlePolicyDetailsModalOpen('create', null),
|
||||
[handlePolicyDetailsModalOpen],
|
||||
);
|
||||
|
||||
const handleEdit = useCallback(
|
||||
(routingPolicy: RoutingPolicy): void =>
|
||||
handlePolicyDetailsModalOpen('edit', routingPolicy),
|
||||
[handlePolicyDetailsModalOpen],
|
||||
);
|
||||
|
||||
const isFetching = useMemo(
|
||||
() => isLoadingRoutingPolicies || isFetchingRoutingPolicies,
|
||||
[isLoadingRoutingPolicies, isFetchingRoutingPolicies],
|
||||
);
|
||||
const hasSearchTerm = useMemo(() => searchTerm.length > 0, [searchTerm]);
|
||||
const isEmpty = useMemo(
|
||||
() => !isFetching && !hasSearchTerm && routingPoliciesData.length === 0,
|
||||
[isFetching, hasSearchTerm, routingPoliciesData.length],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<header className={styles.headerBand}>
|
||||
<div className={styles.commandHeader}>
|
||||
<div className={styles.headingBlock}>
|
||||
<Typography.Title className={styles.title}>
|
||||
Routing Policies
|
||||
</Typography.Title>
|
||||
<span className={styles.countPill}>{routingPoliciesData.length}</span>
|
||||
</div>
|
||||
<div className={styles.grow} />
|
||||
{!isEmpty && (
|
||||
<ColumnSelector
|
||||
columns={columns}
|
||||
storageKey={COLUMNS_STORAGE_KEY}
|
||||
testId="routing-policies-columns"
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
variant="solid"
|
||||
color="primary"
|
||||
size="sm"
|
||||
prefix={<Plus size={14} />}
|
||||
onClick={handleCreate}
|
||||
disabled={!canEdit}
|
||||
disabledTooltip="You need edit permissions to create a routing policy"
|
||||
testId="routing-policies-create"
|
||||
>
|
||||
New routing policy
|
||||
</Button>
|
||||
<TextToolTip
|
||||
text="More details on how to configure routing policies"
|
||||
url="https://signoz.io/docs/alerts-management/routing-policy"
|
||||
urlText="Learn More"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.filtersRow}>
|
||||
<div className="routing-policies-container">
|
||||
<div className="routing-policies-content">
|
||||
<Typography.Title className="title">Routing Policies</Typography.Title>
|
||||
<Typography.Text className="subtitle">
|
||||
Create and manage routing policies.
|
||||
</Typography.Text>
|
||||
<Flex className="toolbar">
|
||||
<Input
|
||||
containerClassName={styles.searchInput}
|
||||
placeholder="Search by name or description"
|
||||
placeholder="Search for a routing policy..."
|
||||
prefix={<Search size={12} color={Color.BG_VANILLA_400} />}
|
||||
value={searchTerm}
|
||||
onChange={handleSearch}
|
||||
suffix={<Search size={14} className={styles.searchIcon} />}
|
||||
testId="routing-policies-search"
|
||||
/>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div ref={containerRef} className={styles.tableContainer}>
|
||||
<Tooltip title={tooltipTitle}>
|
||||
<Button
|
||||
type="primary"
|
||||
onClick={(): void => handlePolicyDetailsModalOpen('create', null)}
|
||||
disabled={disableCreateButton}
|
||||
>
|
||||
<Flex gap={4} align="center">
|
||||
<Plus size={16} />
|
||||
New routing policy
|
||||
</Flex>
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</Flex>
|
||||
<br />
|
||||
<RoutingPolicyList
|
||||
columns={columns}
|
||||
routingPolicies={routingPoliciesData}
|
||||
pagedPolicies={pagedPolicies}
|
||||
calculatedPageSize={calculatedPageSize}
|
||||
onLimitChange={setLimit}
|
||||
isFetching={isFetching}
|
||||
isError={isErrorRoutingPolicies}
|
||||
refetch={refetchRoutingPolicies}
|
||||
canEdit={canEdit}
|
||||
onEdit={handleEdit}
|
||||
onDelete={handleDeleteModalOpen}
|
||||
onCreate={handleCreate}
|
||||
hasSearchTerm={hasSearchTerm}
|
||||
onClearSearch={handleClearSearch}
|
||||
refetchRoutingPolicies={refetchRoutingPolicies}
|
||||
isRoutingPoliciesFetching={isFetchingRoutingPolicies}
|
||||
isRoutingPoliciesLoading={isLoadingRoutingPolicies}
|
||||
isRoutingPoliciesError={isErrorRoutingPolicies}
|
||||
handlePolicyDetailsModalOpen={handlePolicyDetailsModalOpen}
|
||||
handleDeleteModalOpen={handleDeleteModalOpen}
|
||||
hasSearchTerm={(searchTerm?.length ?? 0) > 0}
|
||||
/>
|
||||
{policyDetailsModalState.isOpen && (
|
||||
<RoutingPolicyDetails
|
||||
routingPolicy={selectedRoutingPolicy}
|
||||
closeModal={handlePolicyDetailsModalClose}
|
||||
mode={policyDetailsModalState.mode}
|
||||
channels={channels}
|
||||
isErrorChannels={isErrorChannels}
|
||||
isLoadingChannels={isLoadingChannels}
|
||||
handlePolicyDetailsModalAction={handlePolicyDetailsModalAction}
|
||||
isPolicyDetailsModalActionLoading={isPolicyDetailsModalActionLoading}
|
||||
refreshChannels={refreshChannels}
|
||||
/>
|
||||
)}
|
||||
{isDeleteModalOpen && (
|
||||
<DeleteRoutingPolicy
|
||||
isDeletingRoutingPolicy={isDeletingRoutingPolicy}
|
||||
handleDelete={handleDeleteRoutingPolicy}
|
||||
handleClose={handleDeleteModalClose}
|
||||
routingPolicy={selectedRoutingPolicy}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{policyDetailsModalState.isOpen && (
|
||||
<RoutingPolicyDetails
|
||||
routingPolicy={selectedRoutingPolicy}
|
||||
closeModal={handlePolicyDetailsModalClose}
|
||||
mode={policyDetailsModalState.mode}
|
||||
channels={channels}
|
||||
isErrorChannels={isErrorChannels}
|
||||
isLoadingChannels={isLoadingChannels}
|
||||
handlePolicyDetailsModalAction={handlePolicyDetailsModalAction}
|
||||
isPolicyDetailsModalActionLoading={isPolicyDetailsModalActionLoading}
|
||||
refreshChannels={refreshChannels}
|
||||
/>
|
||||
)}
|
||||
{isDeleteModalOpen && (
|
||||
<DeleteRoutingPolicy
|
||||
isDeletingRoutingPolicy={isDeletingRoutingPolicy}
|
||||
handleDelete={handleDeleteRoutingPolicy}
|
||||
handleClose={handleDeleteModalClose}
|
||||
routingPolicy={selectedRoutingPolicy}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
import { Plus, Route } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
|
||||
import styles from './RoutingPolicies.module.scss';
|
||||
|
||||
const DOCS_URL = 'https://signoz.io/docs/alerts-management/routing-policy';
|
||||
|
||||
interface RoutingPoliciesEmptyStateProps {
|
||||
canCreate: boolean;
|
||||
onCreate: () => void;
|
||||
}
|
||||
|
||||
function RoutingPoliciesEmptyState({
|
||||
canCreate,
|
||||
onCreate,
|
||||
}: RoutingPoliciesEmptyStateProps): JSX.Element {
|
||||
return (
|
||||
<div className={styles.emptyState} data-testid="routing-policies-empty-state">
|
||||
<Route className={styles.emptyIcon} size={16} />
|
||||
<Typography.Text className={styles.emptyTitle}>
|
||||
No routing policies yet
|
||||
</Typography.Text>
|
||||
<Typography.Text className={styles.emptySubtitle}>
|
||||
A routing policy sends alerts matching an expression to the channels you
|
||||
pick, without editing each alert rule.
|
||||
</Typography.Text>
|
||||
{canCreate && (
|
||||
<Button
|
||||
variant="solid"
|
||||
color="primary"
|
||||
size="md"
|
||||
prefix={<Plus size={14} />}
|
||||
onClick={onCreate}
|
||||
testId="routing-policies-empty-create"
|
||||
>
|
||||
New routing policy
|
||||
</Button>
|
||||
)}
|
||||
<a
|
||||
className={styles.docsLink}
|
||||
href={DOCS_URL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Read the routing policy guide
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default RoutingPoliciesEmptyState;
|
||||
@@ -1,65 +0,0 @@
|
||||
import { useMemo } from 'react';
|
||||
import { Ellipsis, PenLine, Trash2 } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Dropdown, type DropdownItemType } from '@signozhq/ui/dropdown';
|
||||
|
||||
import styles from './RoutingPolicies.module.scss';
|
||||
import { RoutingPolicy } from './types';
|
||||
|
||||
interface RoutingPolicyActionsMenuProps {
|
||||
routingPolicy: RoutingPolicy;
|
||||
onEdit: (routingPolicy: RoutingPolicy) => void;
|
||||
onDelete: (routingPolicy: RoutingPolicy) => void;
|
||||
}
|
||||
|
||||
function RoutingPolicyActionsMenu({
|
||||
routingPolicy,
|
||||
onEdit,
|
||||
onDelete,
|
||||
}: RoutingPolicyActionsMenuProps): JSX.Element {
|
||||
const menuItems = useMemo<DropdownItemType[]>(
|
||||
() => [
|
||||
{
|
||||
type: 'item',
|
||||
value: 'edit',
|
||||
label: 'Edit',
|
||||
prefix: <PenLine size={14} />,
|
||||
onClick: (): void => onEdit(routingPolicy),
|
||||
},
|
||||
{ type: 'separator', value: 'before-delete' },
|
||||
{
|
||||
type: 'item',
|
||||
value: 'delete',
|
||||
label: 'Delete',
|
||||
prefix: <Trash2 size={14} />,
|
||||
danger: true,
|
||||
onClick: (): void => onDelete(routingPolicy),
|
||||
},
|
||||
],
|
||||
[routingPolicy, onEdit, onDelete],
|
||||
);
|
||||
|
||||
return (
|
||||
// the row itself opens the policy, so the actions keep their clicks
|
||||
// eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
|
||||
<div
|
||||
className={styles.actions}
|
||||
onClick={(event): void => event.stopPropagation()}
|
||||
>
|
||||
<Dropdown items={menuItems} nativeButton align="end" side="bottom">
|
||||
<Button
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
icon
|
||||
testId={`routing-policy-actions-${routingPolicy.id}`}
|
||||
aria-label={`Actions for ${routingPolicy.name}`}
|
||||
>
|
||||
<Ellipsis size={16} />
|
||||
</Button>
|
||||
</Dropdown>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default RoutingPolicyActionsMenu;
|
||||
@@ -1,106 +1,98 @@
|
||||
import { useMemo } from 'react';
|
||||
import ErrorEmptyState from 'components/Alerts/ErrorEmptyState';
|
||||
import NoResultsEmptyState from 'components/Alerts/NoResultsEmptyState';
|
||||
import TanStackTable, { TableColumnDef } from 'components/TanStackTableView';
|
||||
import { Button, Table, TableProps } from 'antd';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { RotateCw } from '@signozhq/icons';
|
||||
|
||||
import RoutingPoliciesEmptyState from './RoutingPoliciesEmptyState';
|
||||
import RoutingPolicyActionsMenu from './RoutingPolicyActionsMenu';
|
||||
import styles from './RoutingPolicies.module.scss';
|
||||
import awwSnapUrl from '@/assets/Icons/awwSnap.svg';
|
||||
import emptyStateUrl from '@/assets/Icons/emptyState.svg';
|
||||
|
||||
import RoutingPolicyListItem from './RoutingPolicyListItem';
|
||||
import { RoutingPolicy, RoutingPolicyListProps } from './types';
|
||||
import { ROUTING_POLICIES_QUERY_PARAMS } from './useRoutingPoliciesTable';
|
||||
|
||||
function RoutingPolicyList({
|
||||
columns,
|
||||
routingPolicies,
|
||||
pagedPolicies,
|
||||
calculatedPageSize,
|
||||
onLimitChange,
|
||||
isFetching,
|
||||
isError,
|
||||
refetch,
|
||||
canEdit,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onCreate,
|
||||
refetchRoutingPolicies,
|
||||
isRoutingPoliciesFetching,
|
||||
isRoutingPoliciesLoading,
|
||||
isRoutingPoliciesError,
|
||||
handlePolicyDetailsModalOpen,
|
||||
handleDeleteModalOpen,
|
||||
hasSearchTerm,
|
||||
onClearSearch,
|
||||
}: RoutingPolicyListProps): JSX.Element {
|
||||
const columnsWithActions = useMemo((): TableColumnDef<RoutingPolicy>[] => {
|
||||
if (!canEdit) {
|
||||
return columns;
|
||||
}
|
||||
const columns: TableProps<RoutingPolicy>['columns'] = [
|
||||
{
|
||||
title: 'Routing Policy',
|
||||
key: 'routingPolicy',
|
||||
render: (data: RoutingPolicy): JSX.Element => (
|
||||
<RoutingPolicyListItem
|
||||
routingPolicy={data}
|
||||
handlePolicyDetailsModalOpen={handlePolicyDetailsModalOpen}
|
||||
handleDeleteModalOpen={handleDeleteModalOpen}
|
||||
/>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return [
|
||||
...columns,
|
||||
{
|
||||
id: 'actions',
|
||||
header: (): JSX.Element => (
|
||||
<span className={styles.actionsHeader}>Actions</span>
|
||||
),
|
||||
accessorKey: 'id',
|
||||
width: { fixed: '96px', ignoreLastColumnFill: true },
|
||||
enableSort: false,
|
||||
enableResize: false,
|
||||
enableRemove: false,
|
||||
enableMove: false,
|
||||
pin: 'right',
|
||||
cell: ({ row }): JSX.Element => (
|
||||
<RoutingPolicyActionsMenu
|
||||
routingPolicy={row}
|
||||
onEdit={onEdit}
|
||||
onDelete={onDelete}
|
||||
const showLoading = isRoutingPoliciesLoading || isRoutingPoliciesFetching;
|
||||
const showError = !showLoading && isRoutingPoliciesError;
|
||||
|
||||
const localeEmptyState = useMemo(
|
||||
() => (
|
||||
<div className="no-routing-policies-message-container">
|
||||
{showError ? (
|
||||
<img src={awwSnapUrl} alt="aww-snap" className="error-state-svg" />
|
||||
) : (
|
||||
<img
|
||||
src={emptyStateUrl}
|
||||
alt="thinking-emoji"
|
||||
className="empty-state-svg"
|
||||
/>
|
||||
),
|
||||
},
|
||||
];
|
||||
}, [canEdit, columns, onEdit, onDelete]);
|
||||
|
||||
const isEmpty = !isFetching && routingPolicies.length === 0;
|
||||
|
||||
if (isError) {
|
||||
return (
|
||||
<ErrorEmptyState
|
||||
title="Failed to load routing policies"
|
||||
onRefresh={refetch}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (isEmpty && hasSearchTerm) {
|
||||
return (
|
||||
<NoResultsEmptyState
|
||||
title="No matching routing policies"
|
||||
subtitle="No routing policies match your search. Try adjusting your search criteria."
|
||||
onClear={onClearSearch}
|
||||
clearButtonText="Clear Search"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (isEmpty) {
|
||||
return <RoutingPoliciesEmptyState canCreate={canEdit} onCreate={onCreate} />;
|
||||
}
|
||||
)}
|
||||
{showError ? (
|
||||
<div className="error-state">
|
||||
<Typography.Text>
|
||||
Something went wrong while fetching routing policies.
|
||||
</Typography.Text>
|
||||
<Button icon={<RotateCw size={14} />} onClick={refetchRoutingPolicies}>
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
) : hasSearchTerm ? (
|
||||
<Typography.Text>No matching routing policies found.</Typography.Text>
|
||||
) : (
|
||||
<Typography.Text>
|
||||
No routing policies yet,{' '}
|
||||
<a
|
||||
href="https://signoz.io/docs/alerts-management/routing-policy"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Learn more here
|
||||
</a>
|
||||
</Typography.Text>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
[showError, hasSearchTerm, refetchRoutingPolicies],
|
||||
);
|
||||
|
||||
return (
|
||||
<TanStackTable<RoutingPolicy>
|
||||
data={pagedPolicies}
|
||||
columns={columnsWithActions}
|
||||
isLoading={isFetching}
|
||||
getRowKey={(row): string => row.id}
|
||||
getItemKey={(row): string => row.id}
|
||||
getRowTestId={(row): string => `routing-policy-row-${row.id}`}
|
||||
columnStorageKey="routing-policies-columns"
|
||||
enableQueryParams={ROUTING_POLICIES_QUERY_PARAMS}
|
||||
onRowClick={canEdit ? onEdit : undefined}
|
||||
<Table<RoutingPolicy>
|
||||
columns={columns}
|
||||
className="routing-policies-table"
|
||||
bordered={false}
|
||||
dataSource={routingPolicies}
|
||||
loading={showLoading}
|
||||
showHeader={false}
|
||||
rowKey="id"
|
||||
pagination={{
|
||||
total: routingPolicies.length,
|
||||
calculatedPageSize,
|
||||
onLimitChange,
|
||||
showTotalCount: true,
|
||||
pageSize: 5,
|
||||
showSizeChanger: false,
|
||||
hideOnSinglePage: true,
|
||||
}}
|
||||
locale={{
|
||||
emptyText: showLoading ? null : localeEmptyState,
|
||||
}}
|
||||
paginationClassname={styles.paginationContainer}
|
||||
enableAlternatingRowColors
|
||||
plainTextCellLineClamp={1}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
162
frontend/src/container/RoutingPolicies/RoutingPolicyListItem.tsx
Normal file
162
frontend/src/container/RoutingPolicies/RoutingPolicyListItem.tsx
Normal file
@@ -0,0 +1,162 @@
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Button, Collapse, Flex } from 'antd';
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
|
||||
import { PenLine, Trash2 } from '@signozhq/icons';
|
||||
import { useAppContext } from 'providers/App/App';
|
||||
import { useTimezone } from 'providers/Timezone';
|
||||
import { USER_ROLES } from 'types/roles';
|
||||
|
||||
import {
|
||||
PolicyListItemContentProps,
|
||||
PolicyListItemHeaderProps,
|
||||
RoutingPolicyListItemProps,
|
||||
} from './types';
|
||||
|
||||
function PolicyListItemHeader({
|
||||
name,
|
||||
handleEdit,
|
||||
handleDelete,
|
||||
}: PolicyListItemHeaderProps): JSX.Element {
|
||||
const { user } = useAppContext();
|
||||
|
||||
const isEditEnabled = user?.role !== USER_ROLES.VIEWER;
|
||||
|
||||
return (
|
||||
<Flex
|
||||
className="policy-list-item-header"
|
||||
justify="space-between"
|
||||
align="center"
|
||||
>
|
||||
<Typography.Text className="policy-list-item-header-title" truncate={1}>
|
||||
{name}
|
||||
</Typography.Text>
|
||||
{isEditEnabled && (
|
||||
<div className="action-btn">
|
||||
<Button
|
||||
onClick={(e): void => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
handleEdit();
|
||||
}}
|
||||
type="text"
|
||||
shape="circle"
|
||||
icon={<PenLine size={14} data-testid="edit-routing-policy" />}
|
||||
/>
|
||||
<Button
|
||||
onClick={(e): void => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
handleDelete();
|
||||
}}
|
||||
type="text"
|
||||
shape="circle"
|
||||
icon={
|
||||
<Trash2
|
||||
size={14}
|
||||
color={Color.BG_CHERRY_500}
|
||||
data-testid="delete-routing-policy"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</Flex>
|
||||
);
|
||||
}
|
||||
|
||||
function PolicyListItemContent({
|
||||
routingPolicy,
|
||||
}: PolicyListItemContentProps): JSX.Element {
|
||||
const { formatTimezoneAdjustedTimestamp } = useTimezone();
|
||||
|
||||
return (
|
||||
<div className="policy-list-item-content">
|
||||
<div className="policy-list-item-content-row">
|
||||
<Typography>Created by</Typography>
|
||||
<Typography>{routingPolicy.createdBy}</Typography>
|
||||
</div>
|
||||
<div className="policy-list-item-content-row">
|
||||
<Typography>Created on</Typography>
|
||||
<Typography>
|
||||
{routingPolicy.createdAt
|
||||
? formatTimezoneAdjustedTimestamp(
|
||||
routingPolicy.createdAt,
|
||||
DATE_TIME_FORMATS.MONTH_DATETIME,
|
||||
)
|
||||
: '-'}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="policy-list-item-content-row">
|
||||
<Typography>Updated by</Typography>
|
||||
<Typography>{routingPolicy.updatedBy || '-'}</Typography>
|
||||
</div>
|
||||
<div className="policy-list-item-content-row">
|
||||
<Typography>Updated on</Typography>
|
||||
<Typography>
|
||||
{routingPolicy.updatedAt
|
||||
? formatTimezoneAdjustedTimestamp(
|
||||
routingPolicy.updatedAt,
|
||||
DATE_TIME_FORMATS.MONTH_DATETIME,
|
||||
)
|
||||
: '-'}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="policy-list-item-content-row">
|
||||
<Typography>Expression</Typography>
|
||||
<Typography.Text truncate={1}>
|
||||
{routingPolicy.expression || '-'}
|
||||
</Typography.Text>
|
||||
</div>
|
||||
<div className="policy-list-item-content-row">
|
||||
<Typography>Description</Typography>
|
||||
<Typography.Text truncate={1}>
|
||||
{routingPolicy.description || '-'}
|
||||
</Typography.Text>
|
||||
</div>
|
||||
<div className="policy-list-item-content-row">
|
||||
<Typography>Channels</Typography>
|
||||
<div>
|
||||
{routingPolicy.channels.map((channel) => (
|
||||
<Badge
|
||||
textTransform="none"
|
||||
variant="solid"
|
||||
key={channel}
|
||||
color="secondary"
|
||||
>
|
||||
{channel}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RoutingPolicyListItem({
|
||||
routingPolicy,
|
||||
handlePolicyDetailsModalOpen,
|
||||
handleDeleteModalOpen,
|
||||
}: RoutingPolicyListItemProps): JSX.Element {
|
||||
return (
|
||||
<Collapse accordion className="policy-list-item">
|
||||
<Collapse.Panel
|
||||
header={
|
||||
<PolicyListItemHeader
|
||||
name={routingPolicy.name}
|
||||
handleEdit={(): void =>
|
||||
handlePolicyDetailsModalOpen('edit', routingPolicy)
|
||||
}
|
||||
handleDelete={(): void => handleDeleteModalOpen(routingPolicy)}
|
||||
/>
|
||||
}
|
||||
key={routingPolicy.id}
|
||||
>
|
||||
<PolicyListItemContent routingPolicy={routingPolicy} />
|
||||
</Collapse.Panel>
|
||||
</Collapse>
|
||||
);
|
||||
}
|
||||
|
||||
export default RoutingPolicyListItem;
|
||||
@@ -1,5 +1,5 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import * as appHooks from 'providers/App/App';
|
||||
import { fireEvent, render, screen } from 'tests/test-utils';
|
||||
|
||||
import RoutingPolicies from '../RoutingPolicies';
|
||||
import * as routingPoliciesHooks from '../useRoutingPolicies';
|
||||
@@ -7,14 +7,34 @@ import {
|
||||
getAppContextMockState,
|
||||
getUseRoutingPoliciesMockData,
|
||||
MOCK_ROUTING_POLICY_1,
|
||||
mockLocation,
|
||||
mockQueryParams,
|
||||
} from './testUtils';
|
||||
|
||||
const ROUTING_POLICY_DETAILS_TEST_ID = 'routing-policy-details';
|
||||
const SEARCH_TEST_ID = 'routing-policies-search';
|
||||
const CREATE_TEST_ID = 'routing-policies-create';
|
||||
const SEARCH_PLACEHOLDER = 'Search for a routing policy...';
|
||||
|
||||
jest.spyOn(appHooks, 'useAppContext').mockReturnValue(getAppContextMockState());
|
||||
|
||||
jest.mock('hooks/useUrlQuery', () => ({
|
||||
__esModule: true,
|
||||
default: (): URLSearchParams => mockQueryParams({}),
|
||||
}));
|
||||
|
||||
const mockHistoryReplace = jest.fn();
|
||||
jest.mock('react-router-dom', () => ({
|
||||
...jest.requireActual('react-router-dom'),
|
||||
useHistory: (): any => ({
|
||||
replace: mockHistoryReplace,
|
||||
}),
|
||||
useLocation: (): any => ({
|
||||
pathname: '/alerts',
|
||||
search: '',
|
||||
hash: '',
|
||||
state: null,
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock('../RoutingPolicyList', () => ({
|
||||
__esModule: true,
|
||||
default: jest.fn(() => (
|
||||
@@ -46,13 +66,20 @@ jest.spyOn(routingPoliciesHooks, 'default').mockReturnValue(
|
||||
describe('RoutingPolicies', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockQueryParams({});
|
||||
mockLocation('/alerts');
|
||||
});
|
||||
|
||||
it('should render components properly', () => {
|
||||
render(<RoutingPolicies />);
|
||||
expect(screen.getByText('Routing Policies')).toBeInTheDocument();
|
||||
expect(screen.getByTestId(SEARCH_TEST_ID)).toBeInTheDocument();
|
||||
expect(screen.getByTestId(CREATE_TEST_ID)).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText('Create and manage routing policies.'),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText(SEARCH_PLACEHOLDER)).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole('button', { name: /New routing policy/ }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByTestId('routing-policy-list')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId(ROUTING_POLICY_DETAILS_TEST_ID),
|
||||
@@ -62,10 +89,9 @@ describe('RoutingPolicies', () => {
|
||||
|
||||
it('should enable the "New routing policy" button for users with ADMIN role', () => {
|
||||
render(<RoutingPolicies />);
|
||||
expect(screen.getByTestId(CREATE_TEST_ID)).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'false',
|
||||
);
|
||||
expect(
|
||||
screen.getByRole('button', { name: /New routing policy/ }),
|
||||
).toBeEnabled();
|
||||
});
|
||||
|
||||
it('should disable the "New routing policy" button for users with VIEWER role', () => {
|
||||
@@ -73,15 +99,14 @@ describe('RoutingPolicies', () => {
|
||||
.spyOn(appHooks, 'useAppContext')
|
||||
.mockReturnValueOnce(getAppContextMockState({ role: 'VIEWER' }));
|
||||
render(<RoutingPolicies />);
|
||||
expect(screen.getByTestId(CREATE_TEST_ID)).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
expect(
|
||||
screen.getByRole('button', { name: /New routing policy/ }),
|
||||
).toBeDisabled();
|
||||
});
|
||||
|
||||
it('filters routing policies by search term', () => {
|
||||
render(<RoutingPolicies />);
|
||||
const searchInput = screen.getByTestId(SEARCH_TEST_ID);
|
||||
const searchInput = screen.getByPlaceholderText(SEARCH_PLACEHOLDER);
|
||||
fireEvent.change(searchInput, {
|
||||
target: { value: MOCK_ROUTING_POLICY_1.name },
|
||||
});
|
||||
@@ -91,7 +116,10 @@ describe('RoutingPolicies', () => {
|
||||
|
||||
it('clicking on the "New routing policy" button opens the policy details modal', () => {
|
||||
render(<RoutingPolicies />);
|
||||
fireEvent.click(screen.getByTestId(CREATE_TEST_ID));
|
||||
const newRoutingPolicyButton = screen.getByRole('button', {
|
||||
name: /New routing policy/,
|
||||
});
|
||||
fireEvent.click(newRoutingPolicyButton);
|
||||
expect(mockHandlePolicyDetailsModalOpen).toHaveBeenCalledWith('create', null);
|
||||
});
|
||||
|
||||
@@ -120,8 +148,9 @@ describe('RoutingPolicies', () => {
|
||||
expect(screen.getByTestId('delete-routing-policy')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show the current search term', () => {
|
||||
it('should load with search term from URL query params', () => {
|
||||
const searchTerm = 'existing search';
|
||||
mockQueryParams({ search: searchTerm });
|
||||
jest.spyOn(routingPoliciesHooks, 'default').mockReturnValue(
|
||||
getUseRoutingPoliciesMockData({
|
||||
searchTerm,
|
||||
@@ -130,11 +159,14 @@ describe('RoutingPolicies', () => {
|
||||
|
||||
render(<RoutingPolicies />);
|
||||
|
||||
const searchInput = screen.getByTestId(SEARCH_TEST_ID) as HTMLInputElement;
|
||||
const searchInput = screen.getByPlaceholderText(
|
||||
SEARCH_PLACEHOLDER,
|
||||
) as HTMLInputElement;
|
||||
expect(searchInput.value).toBe(searchTerm);
|
||||
});
|
||||
|
||||
it('should show an empty search when there is no search term', () => {
|
||||
it('should initialize with empty search when no search param is in URL', () => {
|
||||
mockQueryParams({});
|
||||
jest.spyOn(routingPoliciesHooks, 'default').mockReturnValue(
|
||||
getUseRoutingPoliciesMockData({
|
||||
searchTerm: '',
|
||||
@@ -143,7 +175,9 @@ describe('RoutingPolicies', () => {
|
||||
|
||||
render(<RoutingPolicies />);
|
||||
|
||||
const searchInput = screen.getByTestId(SEARCH_TEST_ID) as HTMLInputElement;
|
||||
const searchInput = screen.getByPlaceholderText(
|
||||
SEARCH_PLACEHOLDER,
|
||||
) as HTMLInputElement;
|
||||
expect(searchInput.value).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,159 +1,126 @@
|
||||
import { VirtuosoMockContext } from 'react-virtuoso';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
|
||||
import RoutingPolicyList from '../RoutingPolicyList';
|
||||
import { getRoutingPolicyColumns } from '../table.config';
|
||||
import { RoutingPolicyListProps } from '../types';
|
||||
import { MOCK_ROUTING_POLICY_1, MOCK_ROUTING_POLICY_2 } from './testUtils';
|
||||
import RoutingPoliciesList from '../RoutingPolicyList';
|
||||
import { RoutingPolicyListItemProps } from '../types';
|
||||
import { getUseRoutingPoliciesMockData } from './testUtils';
|
||||
|
||||
const POLICIES = [MOCK_ROUTING_POLICY_1, MOCK_ROUTING_POLICY_2];
|
||||
const useRoutingPolicesMockData = getUseRoutingPoliciesMockData();
|
||||
const mockHandlePolicyDetailsModalOpen = jest.fn();
|
||||
const mockHandleDeleteModalOpen = jest.fn();
|
||||
const mockRefetchRoutingPolicies = jest.fn();
|
||||
|
||||
function renderList(
|
||||
overrides: Partial<RoutingPolicyListProps> = {},
|
||||
): RoutingPolicyListProps {
|
||||
const props: RoutingPolicyListProps = {
|
||||
columns: getRoutingPolicyColumns((date) => date),
|
||||
routingPolicies: POLICIES,
|
||||
pagedPolicies: POLICIES,
|
||||
calculatedPageSize: null,
|
||||
onLimitChange: jest.fn(),
|
||||
isFetching: false,
|
||||
isError: false,
|
||||
refetch: jest.fn(),
|
||||
canEdit: true,
|
||||
onEdit: jest.fn(),
|
||||
onDelete: jest.fn(),
|
||||
onCreate: jest.fn(),
|
||||
hasSearchTerm: false,
|
||||
onClearSearch: jest.fn(),
|
||||
...overrides,
|
||||
};
|
||||
render(
|
||||
<VirtuosoMockContext.Provider value={{ viewportHeight: 800, itemHeight: 46 }}>
|
||||
<RoutingPolicyList {...props} />
|
||||
</VirtuosoMockContext.Provider>,
|
||||
);
|
||||
return props;
|
||||
}
|
||||
jest.mock('../RoutingPolicyListItem', () => ({
|
||||
__esModule: true,
|
||||
default: jest.fn(({ routingPolicy }: RoutingPolicyListItemProps) => (
|
||||
<div data-testid="routing-policy-list-item">{routingPolicy.name}</div>
|
||||
)),
|
||||
}));
|
||||
|
||||
describe('RoutingPolicyList', () => {
|
||||
it('renders the key policy fields and hides audit columns by default', async () => {
|
||||
renderList();
|
||||
const ROUTING_POLICY_LIST_ITEM_TEST_ID = 'routing-policy-list-item';
|
||||
|
||||
await expect(
|
||||
screen.findByTestId(`routing-policy-row-${MOCK_ROUTING_POLICY_1.id}-name`),
|
||||
).resolves.toHaveTextContent(MOCK_ROUTING_POLICY_1.name);
|
||||
describe('RoutingPoliciesList', () => {
|
||||
it('renders base layout with routing policies', () => {
|
||||
render(
|
||||
<RoutingPoliciesList
|
||||
routingPolicies={useRoutingPolicesMockData.routingPoliciesData}
|
||||
isRoutingPoliciesLoading={
|
||||
useRoutingPolicesMockData.isLoadingRoutingPolicies
|
||||
}
|
||||
isRoutingPoliciesError={useRoutingPolicesMockData.isErrorRoutingPolicies}
|
||||
handlePolicyDetailsModalOpen={mockHandlePolicyDetailsModalOpen}
|
||||
handleDeleteModalOpen={mockHandleDeleteModalOpen}
|
||||
hasSearchTerm={false}
|
||||
refetchRoutingPolicies={mockRefetchRoutingPolicies}
|
||||
isRoutingPoliciesFetching={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
const routingPolicyItems = screen.getAllByTestId(
|
||||
ROUTING_POLICY_LIST_ITEM_TEST_ID,
|
||||
);
|
||||
expect(routingPolicyItems).toHaveLength(2);
|
||||
expect(routingPolicyItems[0]).toHaveTextContent(
|
||||
useRoutingPolicesMockData.routingPoliciesData[0].name,
|
||||
);
|
||||
expect(routingPolicyItems[1]).toHaveTextContent(
|
||||
useRoutingPolicesMockData.routingPoliciesData[1].name,
|
||||
);
|
||||
});
|
||||
|
||||
it('renders loading state', () => {
|
||||
render(
|
||||
<RoutingPoliciesList
|
||||
routingPolicies={useRoutingPolicesMockData.routingPoliciesData}
|
||||
isRoutingPoliciesLoading
|
||||
isRoutingPoliciesError={false}
|
||||
handlePolicyDetailsModalOpen={mockHandlePolicyDetailsModalOpen}
|
||||
handleDeleteModalOpen={mockHandleDeleteModalOpen}
|
||||
hasSearchTerm={false}
|
||||
refetchRoutingPolicies={mockRefetchRoutingPolicies}
|
||||
isRoutingPoliciesFetching={false}
|
||||
/>,
|
||||
);
|
||||
// Check for loading spinner by class name
|
||||
expect(document.querySelector('.ant-spin-spinning')).toBeInTheDocument();
|
||||
// Check that the table is in loading state (blurred)
|
||||
expect(document.querySelector('.ant-spin-blur')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders loading state when data is being fetched', () => {
|
||||
render(
|
||||
<RoutingPoliciesList
|
||||
routingPolicies={useRoutingPolicesMockData.routingPoliciesData}
|
||||
isRoutingPoliciesLoading={false}
|
||||
isRoutingPoliciesError={false}
|
||||
handlePolicyDetailsModalOpen={mockHandlePolicyDetailsModalOpen}
|
||||
handleDeleteModalOpen={mockHandleDeleteModalOpen}
|
||||
hasSearchTerm={false}
|
||||
refetchRoutingPolicies={mockRefetchRoutingPolicies}
|
||||
isRoutingPoliciesFetching
|
||||
/>,
|
||||
);
|
||||
// Check for loading spinner by class name
|
||||
expect(document.querySelector('.ant-spin-spinning')).toBeInTheDocument();
|
||||
// Check that the table is in loading state (blurred)
|
||||
expect(document.querySelector('.ant-spin-blur')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders error state', () => {
|
||||
render(
|
||||
<RoutingPoliciesList
|
||||
routingPolicies={[]}
|
||||
isRoutingPoliciesLoading={false}
|
||||
isRoutingPoliciesError
|
||||
handlePolicyDetailsModalOpen={mockHandlePolicyDetailsModalOpen}
|
||||
handleDeleteModalOpen={mockHandleDeleteModalOpen}
|
||||
hasSearchTerm={false}
|
||||
refetchRoutingPolicies={mockRefetchRoutingPolicies}
|
||||
isRoutingPoliciesFetching={false}
|
||||
/>,
|
||||
);
|
||||
expect(
|
||||
screen.getByTestId(`routing-policy-row-${MOCK_ROUTING_POLICY_2.id}-name`),
|
||||
).toHaveTextContent(MOCK_ROUTING_POLICY_2.name);
|
||||
|
||||
expect(
|
||||
screen.getByText(MOCK_ROUTING_POLICY_1.expression),
|
||||
screen.getByText('Something went wrong while fetching routing policies.'),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByText(MOCK_ROUTING_POLICY_1.description as string),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText(MOCK_ROUTING_POLICY_1.channels?.[0] || ''),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByText(MOCK_ROUTING_POLICY_1.createdBy as string),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByText(MOCK_ROUTING_POLICY_2.updatedBy as string),
|
||||
).not.toBeInTheDocument();
|
||||
|
||||
const retryButton = screen.getByRole('button', { name: 'Retry' });
|
||||
expect(retryButton).toBeInTheDocument();
|
||||
fireEvent.click(retryButton);
|
||||
expect(mockRefetchRoutingPolicies).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('lets every data column be resized', async () => {
|
||||
renderList();
|
||||
|
||||
await screen.findByText(MOCK_ROUTING_POLICY_1.name);
|
||||
const resizable = Array.from(document.querySelectorAll('th'))
|
||||
.filter((th) => th.querySelector('[title="Drag to resize column"]'))
|
||||
.map((th) => th.textContent?.trim());
|
||||
expect(resizable).toStrictEqual(['Routing Policy', 'Expression', 'Channels']);
|
||||
});
|
||||
|
||||
it('opens the policy on row click', async () => {
|
||||
const { onEdit } = renderList();
|
||||
|
||||
await userEvent.click(
|
||||
await screen.findByTestId(
|
||||
`routing-policy-row-${MOCK_ROUTING_POLICY_1.id}-name`,
|
||||
),
|
||||
it('renders empty state', () => {
|
||||
render(
|
||||
<RoutingPoliciesList
|
||||
routingPolicies={[]}
|
||||
isRoutingPoliciesLoading={false}
|
||||
isRoutingPoliciesError={false}
|
||||
handlePolicyDetailsModalOpen={mockHandlePolicyDetailsModalOpen}
|
||||
handleDeleteModalOpen={mockHandleDeleteModalOpen}
|
||||
hasSearchTerm={false}
|
||||
refetchRoutingPolicies={mockRefetchRoutingPolicies}
|
||||
isRoutingPoliciesFetching={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(onEdit).toHaveBeenCalledWith(
|
||||
MOCK_ROUTING_POLICY_1,
|
||||
MOCK_ROUTING_POLICY_1.id,
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
it('edits and deletes from the actions menu', async () => {
|
||||
const { onEdit, onDelete } = renderList();
|
||||
const actions = `routing-policy-actions-${MOCK_ROUTING_POLICY_1.id}`;
|
||||
|
||||
await userEvent.click(await screen.findByTestId(actions));
|
||||
await userEvent.click(await screen.findByText('Edit'));
|
||||
expect(onEdit).toHaveBeenCalledWith(MOCK_ROUTING_POLICY_1);
|
||||
|
||||
await userEvent.click(screen.getByTestId(actions));
|
||||
await userEvent.click(await screen.findByText('Delete'));
|
||||
expect(onDelete).toHaveBeenCalledWith(MOCK_ROUTING_POLICY_1);
|
||||
});
|
||||
|
||||
it('hides actions and row click for viewers', async () => {
|
||||
const { onEdit } = renderList({ canEdit: false });
|
||||
|
||||
await userEvent.click(
|
||||
await screen.findByTestId(
|
||||
`routing-policy-row-${MOCK_ROUTING_POLICY_1.id}-name`,
|
||||
),
|
||||
);
|
||||
|
||||
expect(
|
||||
screen.queryByTestId(`routing-policy-actions-${MOCK_ROUTING_POLICY_1.id}`),
|
||||
).not.toBeInTheDocument();
|
||||
expect(onEdit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('renders the error state with a refresh', async () => {
|
||||
const { refetch } = renderList({ isError: true, routingPolicies: [] });
|
||||
|
||||
expect(screen.getByTestId('error-title')).toHaveTextContent(
|
||||
'Failed to load routing policies',
|
||||
);
|
||||
await userEvent.click(screen.getByTestId('error-refresh-button'));
|
||||
expect(refetch).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('renders the no-results state when a search matches nothing', async () => {
|
||||
const { onClearSearch } = renderList({
|
||||
routingPolicies: [],
|
||||
pagedPolicies: [],
|
||||
hasSearchTerm: true,
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByTestId('no-results-clear-button'));
|
||||
expect(onClearSearch).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('renders the empty state with a create action', async () => {
|
||||
const { onCreate } = renderList({ routingPolicies: [], pagedPolicies: [] });
|
||||
|
||||
expect(
|
||||
screen.getByTestId('routing-policies-empty-state'),
|
||||
).toBeInTheDocument();
|
||||
await userEvent.click(screen.getByTestId('routing-policies-empty-create'));
|
||||
expect(onCreate).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('hides the empty-state create action for viewers', () => {
|
||||
renderList({ routingPolicies: [], pagedPolicies: [], canEdit: false });
|
||||
|
||||
expect(
|
||||
screen.queryByTestId('routing-policies-empty-create'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.getByText('No routing policies yet,')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import * as appHooks from 'providers/App/App';
|
||||
import { ROLES, USER_ROLES } from 'types/roles';
|
||||
|
||||
import RoutingPolicyListItem from '../RoutingPolicyListItem';
|
||||
import { getAppContextMockState, MOCK_ROUTING_POLICY_1 } from './testUtils';
|
||||
|
||||
const mockFormatTimezoneAdjustedTimestamp = jest.fn();
|
||||
jest.mock('providers/Timezone', () => ({
|
||||
useTimezone: (): any => ({
|
||||
formatTimezoneAdjustedTimestamp: mockFormatTimezoneAdjustedTimestamp,
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.spyOn(appHooks, 'useAppContext').mockReturnValue(getAppContextMockState());
|
||||
|
||||
const mockRoutingPolicy = MOCK_ROUTING_POLICY_1;
|
||||
const mockHandlePolicyDetailsModalOpen = jest.fn();
|
||||
const mockHandleDeleteModalOpen = jest.fn();
|
||||
|
||||
const EDIT_ROUTING_POLICY_TEST_ID = 'edit-routing-policy';
|
||||
const DELETE_ROUTING_POLICY_TEST_ID = 'delete-routing-policy';
|
||||
|
||||
describe('RoutingPolicyListItem', () => {
|
||||
it('should render properly in collapsed state', () => {
|
||||
render(
|
||||
<RoutingPolicyListItem
|
||||
routingPolicy={mockRoutingPolicy}
|
||||
handlePolicyDetailsModalOpen={mockHandlePolicyDetailsModalOpen}
|
||||
handleDeleteModalOpen={mockHandleDeleteModalOpen}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByText(mockRoutingPolicy.name)).toBeInTheDocument();
|
||||
expect(screen.getByTestId(EDIT_ROUTING_POLICY_TEST_ID)).toBeInTheDocument();
|
||||
expect(screen.getByTestId(DELETE_ROUTING_POLICY_TEST_ID)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render properly in expanded state', () => {
|
||||
render(
|
||||
<RoutingPolicyListItem
|
||||
routingPolicy={mockRoutingPolicy}
|
||||
handlePolicyDetailsModalOpen={mockHandlePolicyDetailsModalOpen}
|
||||
handleDeleteModalOpen={mockHandleDeleteModalOpen}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByText(mockRoutingPolicy.name)).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByText(mockRoutingPolicy.name));
|
||||
|
||||
expect(screen.getByText(mockRoutingPolicy.expression)).toBeInTheDocument();
|
||||
expect(screen.getByText(mockRoutingPolicy.channels[0])).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText(mockRoutingPolicy.createdBy || 'user1@signoz.io'),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText(mockRoutingPolicy.description || 'description 1'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should call handlePolicyDetailsModalOpen when edit button is clicked', () => {
|
||||
render(
|
||||
<RoutingPolicyListItem
|
||||
routingPolicy={mockRoutingPolicy}
|
||||
handlePolicyDetailsModalOpen={mockHandlePolicyDetailsModalOpen}
|
||||
handleDeleteModalOpen={mockHandleDeleteModalOpen}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId(EDIT_ROUTING_POLICY_TEST_ID));
|
||||
expect(mockHandlePolicyDetailsModalOpen).toHaveBeenCalledWith(
|
||||
'edit',
|
||||
mockRoutingPolicy,
|
||||
);
|
||||
});
|
||||
|
||||
it('should call handleDeleteModalOpen when delete button is clicked', () => {
|
||||
render(
|
||||
<RoutingPolicyListItem
|
||||
routingPolicy={mockRoutingPolicy}
|
||||
handlePolicyDetailsModalOpen={mockHandlePolicyDetailsModalOpen}
|
||||
handleDeleteModalOpen={mockHandleDeleteModalOpen}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByTestId(DELETE_ROUTING_POLICY_TEST_ID));
|
||||
expect(mockHandleDeleteModalOpen).toHaveBeenCalledWith(mockRoutingPolicy);
|
||||
});
|
||||
|
||||
it('edit and delete buttons should not be rendered for viewer role', () => {
|
||||
jest
|
||||
.spyOn(appHooks, 'useAppContext')
|
||||
.mockReturnValue(
|
||||
getAppContextMockState({ role: USER_ROLES.VIEWER as ROLES }),
|
||||
);
|
||||
render(
|
||||
<RoutingPolicyListItem
|
||||
routingPolicy={mockRoutingPolicy}
|
||||
handlePolicyDetailsModalOpen={mockHandlePolicyDetailsModalOpen}
|
||||
handleDeleteModalOpen={mockHandleDeleteModalOpen}
|
||||
/>,
|
||||
);
|
||||
expect(
|
||||
screen.queryByTestId(EDIT_ROUTING_POLICY_TEST_ID),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId(DELETE_ROUTING_POLICY_TEST_ID),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('in details panel, show "-" for undefined values', () => {
|
||||
render(
|
||||
<RoutingPolicyListItem
|
||||
routingPolicy={mockRoutingPolicy}
|
||||
handlePolicyDetailsModalOpen={mockHandlePolicyDetailsModalOpen}
|
||||
handleDeleteModalOpen={mockHandleDeleteModalOpen}
|
||||
/>,
|
||||
);
|
||||
|
||||
// Expand the details panel
|
||||
fireEvent.click(screen.getByText(mockRoutingPolicy.name));
|
||||
|
||||
const updatedByRow = screen.getByText('Updated by').parentElement;
|
||||
expect(updatedByRow).toHaveTextContent('-');
|
||||
|
||||
const updatedOnRow = screen.getByText('Updated on').parentElement;
|
||||
expect(updatedOnRow).toHaveTextContent('-');
|
||||
});
|
||||
});
|
||||
@@ -11,7 +11,7 @@ export const MOCK_ROUTING_POLICY_1: RoutingPolicy = {
|
||||
description: 'description 1',
|
||||
channels: ['Channel 1'],
|
||||
createdAt: '2021-01-04',
|
||||
updatedAt: '2021-01-04',
|
||||
updatedAt: undefined,
|
||||
createdBy: 'user1@signoz.io',
|
||||
updatedBy: undefined,
|
||||
};
|
||||
@@ -149,7 +149,7 @@ export function convertRoutingPolicyToApiResponse(
|
||||
id: routingPolicy.id,
|
||||
name: routingPolicy.name,
|
||||
expression: routingPolicy.expression,
|
||||
channels: routingPolicy.channels ?? [],
|
||||
channels: routingPolicy.channels,
|
||||
description: routingPolicy.description || '',
|
||||
createdAt: routingPolicy.createdAt || '',
|
||||
updatedAt: routingPolicy.updatedAt || '',
|
||||
|
||||
@@ -1,3 +1,173 @@
|
||||
.routing-policies-container {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
margin-top: 8px;
|
||||
|
||||
.routing-policies-content {
|
||||
width: calc(100% - 30px);
|
||||
max-width: 736px;
|
||||
|
||||
.title {
|
||||
color: var(--l1-foreground);
|
||||
font-size: var(--font-size-lg);
|
||||
font-style: normal;
|
||||
font-weight: var(--font-weight-normal);
|
||||
line-height: 28px;
|
||||
letter-spacing: -0.09px;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
color: var(--l2-foreground);
|
||||
font-size: var(--font-size-sm);
|
||||
font-style: normal;
|
||||
font-weight: var(--font-weight-normal);
|
||||
line-height: 20px;
|
||||
letter-spacing: -0.07px;
|
||||
}
|
||||
|
||||
.ant-input-affix-wrapper {
|
||||
margin-top: 16px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.routing-policies-table {
|
||||
.no-routing-policies-message-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
min-height: 200px;
|
||||
|
||||
.error-state {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 16px;
|
||||
|
||||
.ant-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
|
||||
.empty-state-svg {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
}
|
||||
|
||||
.ant-typography {
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.routing-policies-table {
|
||||
.ant-table {
|
||||
background: none !important;
|
||||
}
|
||||
.ant-table-cell {
|
||||
padding: 0 !important;
|
||||
border: 0 !important;
|
||||
width: 736px;
|
||||
}
|
||||
|
||||
.ant-table-tbody {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
|
||||
.policy-list-item {
|
||||
border: 1px solid var(--l1-border);
|
||||
background-color: var(--l2-background);
|
||||
border-radius: 6px;
|
||||
|
||||
.ant-collapse-header {
|
||||
height: 56px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.policy-list-item-header {
|
||||
.ant-typography {
|
||||
color: var(--l2-foreground);
|
||||
font-family: Inter;
|
||||
font-size: 14px;
|
||||
font-weight: 400;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
.policy-list-item-header-title {
|
||||
min-width: 0;
|
||||
display: block;
|
||||
flex: 0 1 500px;
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.action-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
cursor: pointer;
|
||||
|
||||
.ant-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.policy-list-item-content {
|
||||
.policy-list-item-content-row {
|
||||
display: grid;
|
||||
grid-template-columns: 128px 1fr;
|
||||
margin-bottom: 13px;
|
||||
|
||||
.ant-typography:first-child {
|
||||
color: var(--l2-foreground);
|
||||
font-family: Inter;
|
||||
font-size: 13px;
|
||||
font-weight: 400;
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
.ant-typography:last-child,
|
||||
div .ant-typography {
|
||||
color: var(--l1-foreground);
|
||||
font-family: Inter;
|
||||
font-size: 13px;
|
||||
font-weight: 400;
|
||||
line-height: 18px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.ant-collapse-content-box {
|
||||
padding: 12px 20px 12px 38px;
|
||||
}
|
||||
|
||||
.ant-collapse-content-active {
|
||||
border-top: none;
|
||||
}
|
||||
|
||||
.ant-collapse-item {
|
||||
border: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.create-policy-modal {
|
||||
.ant-modal-content {
|
||||
padding: 16px;
|
||||
|
||||
@@ -1,144 +0,0 @@
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
import type { TableColumnDef } from 'components/TanStackTableView';
|
||||
import TanStackTable from 'components/TanStackTableView';
|
||||
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
|
||||
import { toRelativeTime } from 'pages/AlertList/NotificationChannels/utils/relativeTime';
|
||||
|
||||
import styles from './RoutingPolicies.module.scss';
|
||||
import { RoutingPolicy } from './types';
|
||||
|
||||
export function getRoutingPolicyColumns(
|
||||
formatTimezoneAdjustedTimestamp: (date: string, format: string) => string,
|
||||
): TableColumnDef<RoutingPolicy>[] {
|
||||
const textCell = (value: string | null | undefined): JSX.Element => (
|
||||
<TanStackTable.Text title={value ?? undefined}>
|
||||
{value || '-'}
|
||||
</TanStackTable.Text>
|
||||
);
|
||||
|
||||
const timestampCell = (
|
||||
row: RoutingPolicy,
|
||||
value: string | null | undefined,
|
||||
): JSX.Element => {
|
||||
if (!value) {
|
||||
return <TanStackTable.Text>-</TanStackTable.Text>;
|
||||
}
|
||||
|
||||
return (
|
||||
<TanStackTable.HoverTooltip
|
||||
rowId={row.id}
|
||||
title={formatTimezoneAdjustedTimestamp(
|
||||
value,
|
||||
DATE_TIME_FORMATS.DASH_DATETIME,
|
||||
)}
|
||||
>
|
||||
<span className={styles.timeText}>{toRelativeTime(value)}</span>
|
||||
</TanStackTable.HoverTooltip>
|
||||
);
|
||||
};
|
||||
|
||||
return [
|
||||
{
|
||||
id: 'name',
|
||||
header: 'Routing Policy',
|
||||
accessorKey: 'name',
|
||||
width: { default: '100%', min: '220px' },
|
||||
enableSort: true,
|
||||
enableResize: true,
|
||||
enableRemove: false,
|
||||
enableMove: false,
|
||||
cell: ({ row }): JSX.Element => (
|
||||
<TanStackTable.Text
|
||||
title={row.name}
|
||||
data-testid={`routing-policy-row-${row.id}-name`}
|
||||
>
|
||||
{row.name}
|
||||
</TanStackTable.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'expression',
|
||||
header: 'Expression',
|
||||
accessorKey: 'expression',
|
||||
width: { default: '260px', min: '160px' },
|
||||
enableSort: false,
|
||||
enableResize: true,
|
||||
enableMove: false,
|
||||
cell: ({ row }): JSX.Element => (
|
||||
<TanStackTable.Text className={styles.expression} title={row.expression}>
|
||||
{row.expression}
|
||||
</TanStackTable.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'channels',
|
||||
header: 'Channels',
|
||||
accessorKey: 'channels',
|
||||
width: { default: '220px', min: '140px' },
|
||||
enableSort: false,
|
||||
enableResize: true,
|
||||
enableMove: false,
|
||||
cell: ({ row }): JSX.Element =>
|
||||
row.channels?.length ? (
|
||||
<div className={styles.badges} title={row.channels.join(', ')}>
|
||||
{row.channels.map((channel) => (
|
||||
<Badge
|
||||
key={channel}
|
||||
textTransform="none"
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
>
|
||||
{channel}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<TanStackTable.Text>-</TanStackTable.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'createdBy',
|
||||
header: 'Created By',
|
||||
accessorKey: 'createdBy',
|
||||
width: { default: '180px', min: '120px' },
|
||||
defaultVisibility: false,
|
||||
enableSort: false,
|
||||
enableResize: true,
|
||||
enableMove: false,
|
||||
cell: ({ row }): JSX.Element => textCell(row.createdBy),
|
||||
},
|
||||
{
|
||||
id: 'createdAt',
|
||||
header: 'Created At',
|
||||
accessorKey: 'createdAt',
|
||||
width: { default: '150px', min: '120px' },
|
||||
defaultVisibility: false,
|
||||
enableSort: true,
|
||||
enableResize: true,
|
||||
enableMove: false,
|
||||
cell: ({ row }): JSX.Element => timestampCell(row, row.createdAt),
|
||||
},
|
||||
{
|
||||
id: 'updatedBy',
|
||||
header: 'Updated By',
|
||||
accessorKey: 'updatedBy',
|
||||
width: { default: '180px', min: '120px' },
|
||||
defaultVisibility: false,
|
||||
enableSort: false,
|
||||
enableResize: true,
|
||||
enableMove: false,
|
||||
cell: ({ row }): JSX.Element => textCell(row.updatedBy),
|
||||
},
|
||||
{
|
||||
id: 'updatedAt',
|
||||
header: 'Updated At',
|
||||
accessorKey: 'updatedAt',
|
||||
width: { default: '150px', min: '120px' },
|
||||
defaultVisibility: false,
|
||||
enableSort: true,
|
||||
enableResize: true,
|
||||
enableMove: false,
|
||||
cell: ({ row }): JSX.Element => timestampCell(row, row.updatedAt),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -1,8 +1,16 @@
|
||||
import type { AlertmanagertypesGettableRoutePolicyDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import type { TableColumnDef } from 'components/TanStackTableView';
|
||||
import type { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
|
||||
import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
|
||||
|
||||
export type RoutingPolicy = AlertmanagertypesGettableRoutePolicyDTO;
|
||||
export interface RoutingPolicy {
|
||||
id: string;
|
||||
name: string;
|
||||
expression: string;
|
||||
channels: string[];
|
||||
description: string | undefined;
|
||||
createdAt: string | undefined;
|
||||
updatedAt: string | undefined;
|
||||
createdBy: string | undefined;
|
||||
updatedBy: string | undefined;
|
||||
}
|
||||
|
||||
type HandlePolicyDetailsModalOpen = (
|
||||
mode: PolicyDetailsModalMode,
|
||||
@@ -24,20 +32,30 @@ type HandleDeleteModalOpen = (routingPolicy: RoutingPolicy) => void;
|
||||
export type PolicyDetailsModalMode = 'create' | 'edit' | null;
|
||||
|
||||
export interface RoutingPolicyListProps {
|
||||
columns: TableColumnDef<RoutingPolicy>[];
|
||||
routingPolicies: RoutingPolicy[];
|
||||
pagedPolicies: RoutingPolicy[];
|
||||
calculatedPageSize: number | null;
|
||||
onLimitChange: (limit: number) => void;
|
||||
isFetching: boolean;
|
||||
isError: boolean;
|
||||
refetch: () => void;
|
||||
canEdit: boolean;
|
||||
onEdit: (routingPolicy: RoutingPolicy) => void;
|
||||
onDelete: HandleDeleteModalOpen;
|
||||
onCreate: () => void;
|
||||
refetchRoutingPolicies: () => void;
|
||||
isRoutingPoliciesLoading: boolean;
|
||||
isRoutingPoliciesFetching: boolean;
|
||||
isRoutingPoliciesError: boolean;
|
||||
handlePolicyDetailsModalOpen: HandlePolicyDetailsModalOpen;
|
||||
handleDeleteModalOpen: HandleDeleteModalOpen;
|
||||
hasSearchTerm: boolean;
|
||||
onClearSearch: () => void;
|
||||
}
|
||||
|
||||
export interface RoutingPolicyListItemProps {
|
||||
routingPolicy: RoutingPolicy;
|
||||
handlePolicyDetailsModalOpen: HandlePolicyDetailsModalOpen;
|
||||
handleDeleteModalOpen: HandleDeleteModalOpen;
|
||||
}
|
||||
|
||||
export interface PolicyListItemHeaderProps {
|
||||
name: string;
|
||||
handleEdit: () => void;
|
||||
handleDelete: () => void;
|
||||
}
|
||||
|
||||
export interface PolicyListItemContentProps {
|
||||
routingPolicy: RoutingPolicy;
|
||||
}
|
||||
|
||||
export interface RoutingPolicyDetailsProps {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useQueryClient } from 'react-query';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import { toast } from '@signozhq/ui/sonner';
|
||||
@@ -88,22 +88,22 @@ function useRoutingPolicies(): UseRoutingPoliciesReturn {
|
||||
} = useChannelOptions();
|
||||
|
||||
const refreshChannels = (): void => {
|
||||
void refetchChannels();
|
||||
refetchChannels();
|
||||
};
|
||||
|
||||
// Handlers
|
||||
const handlePolicyDetailsModalOpen = useCallback(
|
||||
(mode: PolicyDetailsModalMode, routingPolicy: RoutingPolicy | null): void => {
|
||||
if (routingPolicy) {
|
||||
setSelectedRoutingPolicy(routingPolicy);
|
||||
}
|
||||
setPolicyDetailsModalState({
|
||||
isOpen: true,
|
||||
mode,
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
const handlePolicyDetailsModalOpen = (
|
||||
mode: PolicyDetailsModalMode,
|
||||
routingPolicy: RoutingPolicy | null,
|
||||
): void => {
|
||||
if (routingPolicy) {
|
||||
setSelectedRoutingPolicy(routingPolicy);
|
||||
}
|
||||
setPolicyDetailsModalState({
|
||||
isOpen: true,
|
||||
mode,
|
||||
});
|
||||
};
|
||||
|
||||
const handlePolicyDetailsModalClose = (): void => {
|
||||
setSelectedRoutingPolicy(null);
|
||||
@@ -113,13 +113,10 @@ function useRoutingPolicies(): UseRoutingPoliciesReturn {
|
||||
});
|
||||
};
|
||||
|
||||
const handleDeleteModalOpen = useCallback(
|
||||
(routingPolicy: RoutingPolicy): void => {
|
||||
setSelectedRoutingPolicy(routingPolicy);
|
||||
setIsDeleteModalOpen(true);
|
||||
},
|
||||
[],
|
||||
);
|
||||
const handleDeleteModalOpen = (routingPolicy: RoutingPolicy): void => {
|
||||
setSelectedRoutingPolicy(routingPolicy);
|
||||
setIsDeleteModalOpen(true);
|
||||
};
|
||||
|
||||
const handleDeleteModalClose = (): void => {
|
||||
setSelectedRoutingPolicy(null);
|
||||
@@ -157,7 +154,7 @@ function useRoutingPolicies(): UseRoutingPoliciesReturn {
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast.success('Routing policy created successfully');
|
||||
void queryClient.invalidateQueries(REACT_QUERY_KEY.GET_ROUTING_POLICIES);
|
||||
queryClient.invalidateQueries(REACT_QUERY_KEY.GET_ROUTING_POLICIES);
|
||||
handlePolicyDetailsModalClose();
|
||||
},
|
||||
onError: (error) => {
|
||||
@@ -179,7 +176,7 @@ function useRoutingPolicies(): UseRoutingPoliciesReturn {
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast.success('Routing policy updated successfully');
|
||||
void queryClient.invalidateQueries(REACT_QUERY_KEY.GET_ROUTING_POLICIES);
|
||||
queryClient.invalidateQueries(REACT_QUERY_KEY.GET_ROUTING_POLICIES);
|
||||
handlePolicyDetailsModalClose();
|
||||
},
|
||||
onError: () => {
|
||||
@@ -212,7 +209,7 @@ function useRoutingPolicies(): UseRoutingPoliciesReturn {
|
||||
deleteRoutingPolicy(selectedRoutingPolicy.id, {
|
||||
onSuccess: () => {
|
||||
toast.success('Routing policy deleted successfully');
|
||||
void queryClient.invalidateQueries(REACT_QUERY_KEY.GET_ROUTING_POLICIES);
|
||||
queryClient.invalidateQueries(REACT_QUERY_KEY.GET_ROUTING_POLICIES);
|
||||
handleDeleteModalClose();
|
||||
},
|
||||
onError: () => {
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
import { RefObject, useMemo } from 'react';
|
||||
import { sortByColumn } from 'components/Alerts/utils';
|
||||
import { useCalculatedPageSize } from 'components/TanStackTableView/useCalculatedPageSize';
|
||||
import { useTableParams } from 'components/TanStackTableView/useTableParams';
|
||||
|
||||
import { RoutingPolicy } from './types';
|
||||
|
||||
export const ROUTING_POLICIES_QUERY_PARAMS = {
|
||||
orderBy: 'orderBy',
|
||||
page: 'page',
|
||||
limit: 'limit',
|
||||
} as const;
|
||||
|
||||
const DEFAULT_PAGE = 1;
|
||||
const DEFAULT_LIMIT = 10;
|
||||
|
||||
function getSortValue(
|
||||
policy: RoutingPolicy,
|
||||
columnName: string,
|
||||
): string | number {
|
||||
switch (columnName) {
|
||||
case 'name':
|
||||
return policy.name.toLowerCase();
|
||||
case 'createdAt':
|
||||
return policy.createdAt ? new Date(policy.createdAt).getTime() : 0;
|
||||
case 'updatedAt':
|
||||
return policy.updatedAt ? new Date(policy.updatedAt).getTime() : 0;
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
interface UseRoutingPoliciesTableReturn {
|
||||
containerRef: RefObject<HTMLDivElement>;
|
||||
calculatedPageSize: number | null;
|
||||
pagedPolicies: RoutingPolicy[];
|
||||
setPage: (page: number) => void;
|
||||
setLimit: (limit: number) => void;
|
||||
}
|
||||
|
||||
function useRoutingPoliciesTable(
|
||||
routingPolicies: RoutingPolicy[],
|
||||
): UseRoutingPoliciesTableReturn {
|
||||
const { containerRef, calculatedPageSize } = useCalculatedPageSize({
|
||||
rowHeight: 46,
|
||||
});
|
||||
|
||||
const { orderBy, page, limit, setLimit, setPage } = useTableParams(
|
||||
ROUTING_POLICIES_QUERY_PARAMS,
|
||||
{
|
||||
page: DEFAULT_PAGE,
|
||||
limit: DEFAULT_LIMIT,
|
||||
storageKey: 'routing-policies',
|
||||
calculatedPageSize,
|
||||
cleanupOnUnmount: true,
|
||||
},
|
||||
);
|
||||
|
||||
const pagedPolicies = useMemo(() => {
|
||||
const sorted = sortByColumn(routingPolicies, orderBy, getSortValue);
|
||||
const start = (page - 1) * limit;
|
||||
return sorted.slice(start, start + limit);
|
||||
}, [routingPolicies, orderBy, page, limit]);
|
||||
|
||||
return {
|
||||
containerRef,
|
||||
calculatedPageSize,
|
||||
pagedPolicies,
|
||||
setPage,
|
||||
setLimit,
|
||||
};
|
||||
}
|
||||
|
||||
export default useRoutingPoliciesTable;
|
||||
@@ -21,15 +21,7 @@ export default {
|
||||
{
|
||||
kind: 'notification-channel',
|
||||
type: 'metaresource',
|
||||
allowedVerbs: [
|
||||
'attach',
|
||||
'create',
|
||||
'delete',
|
||||
'detach',
|
||||
'list',
|
||||
'read',
|
||||
'update',
|
||||
],
|
||||
allowedVerbs: ['create', 'delete', 'list', 'read', 'update'],
|
||||
},
|
||||
{
|
||||
kind: 'quick-filter',
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
.alerts-container {
|
||||
// Hands the page height down to the active tab so its content can bound itself
|
||||
// instead of guessing with 100vh. Child combinators only, nested Tabs
|
||||
// (e.g. the alert history timeline) must not be caught.
|
||||
// (Configuration) must not be caught.
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
|
||||
@@ -55,6 +55,14 @@
|
||||
}
|
||||
}
|
||||
|
||||
.configuration-tabs {
|
||||
.ant-tabs-nav {
|
||||
.ant-tabs-nav-wrap {
|
||||
padding: 0 8px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.alert-rules-container {
|
||||
margin-top: 10px;
|
||||
flex: 1;
|
||||
@@ -62,82 +70,4 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.alert-configuration-container {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: stretch;
|
||||
|
||||
.alert-configuration-sidebar {
|
||||
width: 240px;
|
||||
flex-shrink: 0;
|
||||
border-right: 1px solid var(--l1-border);
|
||||
background: var(--l1-background);
|
||||
padding: 12px 8px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
overflow-y: auto;
|
||||
|
||||
.sidebar-nav-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
height: 32px;
|
||||
padding: 0 8px;
|
||||
margin: 0;
|
||||
border: none;
|
||||
border-radius: var(--radius-2, 4px);
|
||||
background: transparent;
|
||||
color: var(--l2-foreground);
|
||||
font-family: inherit;
|
||||
font-size: 13px;
|
||||
font-weight: var(--font-weight-normal, 400);
|
||||
line-height: 18px;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
background 0.12s ease,
|
||||
color 0.12s ease;
|
||||
|
||||
&:hover {
|
||||
background: var(--l1-background-hover);
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
|
||||
&.active {
|
||||
background: var(--l1-background-hover);
|
||||
color: var(--l1-foreground);
|
||||
font-weight: var(--font-weight-medium, 500);
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--primary-background);
|
||||
outline-offset: -1px;
|
||||
}
|
||||
|
||||
.sidebar-nav-item-label {
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
color: inherit;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.alert-configuration-content {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
|
||||
> .alert-rules-container {
|
||||
margin-top: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
|
||||
import { rest } from 'msw';
|
||||
import { screen, userEvent, within } from 'storybook/test';
|
||||
import { userEvent, within } from 'storybook/test';
|
||||
|
||||
import { choiceControl, countControl } from '@/storybook/controls/controls';
|
||||
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
@@ -111,14 +111,20 @@ export const clickFirstRowAction = async (
|
||||
canvasElement: HTMLElement,
|
||||
action: 'edit' | 'delete',
|
||||
): Promise<void> => {
|
||||
await userEvent.click(
|
||||
await within(canvasElement).findByRole(
|
||||
'button',
|
||||
{ name: `Actions for ${FIRST_DOWNTIME_NAME}` },
|
||||
const icon = (
|
||||
await within(canvasElement).findByText(
|
||||
FIRST_DOWNTIME_NAME,
|
||||
undefined,
|
||||
untilLoaded,
|
||||
),
|
||||
);
|
||||
await userEvent.click(
|
||||
await screen.findByText(action === 'edit' ? 'Edit' : 'Delete'),
|
||||
);
|
||||
)
|
||||
)
|
||||
.closest('.header-content')
|
||||
// The row action holds edit then delete, neither of them labelled.
|
||||
?.querySelectorAll('.action-btn svg')[action === 'edit' ? 0 : 1];
|
||||
|
||||
if (!icon) {
|
||||
throw new Error(`Downtime ${action} action did not render`);
|
||||
}
|
||||
|
||||
await userEvent.click(icon);
|
||||
};
|
||||
|
||||
@@ -21,7 +21,7 @@ const pageStory = storyMocks(plannedDowntimeMocks, { layout: 'app' });
|
||||
* Windows that silence rules on a schedule, one off or recurring, with the rules
|
||||
* each window covers.
|
||||
*
|
||||
* Route: `/alerts?tab=Configuration&subTab=planned-downtime`.
|
||||
* Route: `/alerts?tab=Configuration&subTab=PlannedDowntime`.
|
||||
*/
|
||||
const meta = {
|
||||
title: 'Pages/Alerts/Planned Downtime',
|
||||
@@ -47,22 +47,22 @@ export const NoDowntimes: Story = {
|
||||
};
|
||||
|
||||
/**
|
||||
* A viewer: the edit and delete actions on a row are gone and New downtime is
|
||||
* disabled.
|
||||
* A viewer: the edit and delete actions on a row and the New downtime button
|
||||
* are gone.
|
||||
*/
|
||||
export const Viewer: Story = {
|
||||
args: { access: 'viewer' },
|
||||
};
|
||||
|
||||
/** A downtime opened from its row: the form prefilled with its window and rules. */
|
||||
export const OpenFromRow: Story = {
|
||||
/** A downtime opened up: who scheduled it, the window, and what it silences. */
|
||||
export const Expanded: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
const canvas = within(canvasElement);
|
||||
|
||||
await userEvent.click(
|
||||
await canvas.findByText(FIRST_DOWNTIME_NAME, undefined, untilLoaded),
|
||||
);
|
||||
await screen.findByText(/edit planned downtime/i);
|
||||
await canvas.findByText(/alerts silenced/i);
|
||||
},
|
||||
};
|
||||
|
||||
@@ -97,9 +97,7 @@ export const EditDowntime: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await clickFirstRowAction(canvasElement, 'edit');
|
||||
await screen.findByText(/edit planned downtime/i);
|
||||
await within(await screen.findByRole('dialog')).findByText(
|
||||
/^Postgres connections/,
|
||||
);
|
||||
await screen.findByText(/^Postgres connections/);
|
||||
},
|
||||
};
|
||||
|
||||
@@ -120,13 +118,13 @@ export const SearchNoResults: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
const canvas = within(canvasElement);
|
||||
const search = await canvas.findByPlaceholderText(
|
||||
'Search by name',
|
||||
'Search for a planned downtime...',
|
||||
undefined,
|
||||
untilLoaded,
|
||||
);
|
||||
|
||||
await userEvent.type(search, 'no matching downtime');
|
||||
await canvas.findByText('No matching planned downtime');
|
||||
await canvas.findByRole('table');
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ import { choiceControl, countControl } from '@/storybook/controls/controls';
|
||||
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
|
||||
import {
|
||||
FIRST_POLICY_NAME,
|
||||
ROUTING_POLICY_MAX,
|
||||
routingPoliciesResponse,
|
||||
} from './__story_mockdata__/routingPolicies';
|
||||
@@ -143,8 +142,7 @@ export const fillNewPolicy = async (): Promise<void> => {
|
||||
'severity = "critical"',
|
||||
);
|
||||
await userEvent.click(await screen.findByRole('combobox'));
|
||||
const options = await screen.findAllByTitle('ops-slack');
|
||||
await userEvent.click(options[options.length - 1]);
|
||||
await userEvent.click(await screen.findByTitle('ops-slack'));
|
||||
await userEvent.keyboard('{Escape}');
|
||||
await userEvent.click(
|
||||
await screen.findByRole('button', { name: 'Save Routing Policy' }),
|
||||
@@ -155,11 +153,13 @@ export const openEditPolicy = async (
|
||||
canvasElement: HTMLElement,
|
||||
): Promise<void> => {
|
||||
await userEvent.click(
|
||||
await within(canvasElement).findByText(
|
||||
FIRST_POLICY_NAME,
|
||||
undefined,
|
||||
untilLoaded,
|
||||
),
|
||||
(
|
||||
await within(canvasElement).findAllByTestId(
|
||||
'edit-routing-policy',
|
||||
undefined,
|
||||
untilLoaded,
|
||||
)
|
||||
)[0],
|
||||
);
|
||||
await userEvent.click(
|
||||
await screen.findByRole('button', { name: 'Save Routing Policy' }),
|
||||
|
||||
@@ -22,7 +22,7 @@ const pageStory = storyMocks(routingPoliciesMocks, { layout: 'app' });
|
||||
* Policies that route a firing alert to channels by expression, in the order they
|
||||
* are evaluated.
|
||||
*
|
||||
* Route: `/alerts?tab=Configuration&subTab=routing-policies`.
|
||||
* Route: `/alerts?tab=Configuration&subTab=RoutingPolicies`.
|
||||
*/
|
||||
const meta = {
|
||||
title: 'Pages/Alerts/Routing Policies',
|
||||
@@ -47,20 +47,20 @@ export const NoPolicies: Story = {
|
||||
args: { policies: 0 },
|
||||
};
|
||||
|
||||
/** A viewer: the row actions are gone and New routing policy is disabled. */
|
||||
/** A viewer: the row actions and the New routing policy button are gone. */
|
||||
export const Viewer: Story = {
|
||||
args: { access: 'viewer' },
|
||||
};
|
||||
|
||||
/** A policy opened from its row: the form prefilled with its expression and channels. */
|
||||
export const EditPolicy: Story = {
|
||||
/** A policy opened up: the expression it matches on and where it sends. */
|
||||
export const Expanded: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
const canvas = within(canvasElement);
|
||||
|
||||
await userEvent.click(
|
||||
await canvas.findByText(FIRST_POLICY_NAME, undefined, untilLoaded),
|
||||
);
|
||||
await screen.findByText(/edit routing policy/i);
|
||||
await canvas.findByText(/expression/i);
|
||||
},
|
||||
};
|
||||
|
||||
@@ -83,13 +83,15 @@ export const DeletePolicyConfirm: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
const canvas = within(canvasElement);
|
||||
|
||||
const [firstRowActions] = await canvas.findAllByRole(
|
||||
'button',
|
||||
{ name: /^Actions for / },
|
||||
untilLoaded,
|
||||
await userEvent.click(
|
||||
(
|
||||
await canvas.findAllByTestId(
|
||||
'delete-routing-policy',
|
||||
undefined,
|
||||
untilLoaded,
|
||||
)
|
||||
)[0],
|
||||
);
|
||||
await userEvent.click(firstRowActions);
|
||||
await userEvent.click(await screen.findByText('Delete'));
|
||||
// The modal titles itself and its confirm button the same.
|
||||
await screen.findByRole('button', { name: 'Delete Routing Policy' });
|
||||
},
|
||||
@@ -100,13 +102,13 @@ export const SearchNoResults: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
const canvas = within(canvasElement);
|
||||
const search = await canvas.findByPlaceholderText(
|
||||
'Search by name or description',
|
||||
'Search for a routing policy...',
|
||||
undefined,
|
||||
untilLoaded,
|
||||
);
|
||||
|
||||
await userEvent.type(search, 'no matching policy');
|
||||
await canvas.findByText('No matching routing policies');
|
||||
await canvas.findByText('No matching routing policies found.');
|
||||
},
|
||||
};
|
||||
|
||||
@@ -138,10 +140,6 @@ export const FormValidationError: Story = {
|
||||
},
|
||||
};
|
||||
|
||||
const expectToast = async (text: RegExp): Promise<void> => {
|
||||
await waitFor(() => expect(screen.getByText(text)).toBeVisible());
|
||||
};
|
||||
|
||||
const confirmDelete = async (canvasElement: HTMLElement): Promise<void> => {
|
||||
await DeletePolicyConfirm.play?.({ canvasElement } as never);
|
||||
await userEvent.click(
|
||||
@@ -154,11 +152,13 @@ export const CreatePolicyToast: Story = {
|
||||
play: async ({ canvasElement, args }): Promise<void> => {
|
||||
await NewPolicy.play?.({ canvasElement } as never);
|
||||
await fillNewPolicy();
|
||||
await expectToast(
|
||||
args.createState === 'success'
|
||||
? /routing policy created successfully/i
|
||||
: /Policy name already exists/i,
|
||||
);
|
||||
if (args.createState === 'success') {
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByText(/routing policy created successfully/i),
|
||||
).toBeVisible(),
|
||||
);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
@@ -173,11 +173,13 @@ export const CreatePolicyErrorToast: Story = {
|
||||
export const UpdatePolicyToast: Story = {
|
||||
play: async ({ canvasElement, args }): Promise<void> => {
|
||||
await openEditPolicy(canvasElement);
|
||||
await expectToast(
|
||||
args.updateState === 'success'
|
||||
? /routing policy updated successfully/i
|
||||
: /failed to update routing policy/i,
|
||||
);
|
||||
if (args.updateState === 'success') {
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByText(/routing policy updated successfully/i),
|
||||
).toBeVisible(),
|
||||
);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
@@ -192,11 +194,13 @@ export const UpdatePolicyErrorToast: Story = {
|
||||
export const DeletePolicyToast: Story = {
|
||||
play: async ({ canvasElement, args }): Promise<void> => {
|
||||
await confirmDelete(canvasElement);
|
||||
await expectToast(
|
||||
args.deleteState === 'success'
|
||||
? /routing policy deleted successfully/i
|
||||
: /failed to delete routing policy/i,
|
||||
);
|
||||
if (args.deleteState === 'success') {
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByText(/routing policy deleted successfully/i),
|
||||
).toBeVisible(),
|
||||
);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -8,10 +8,8 @@ const LIST_ALERT_RULES_TEXT = 'List Alert Rules Component';
|
||||
const TRIGGERED_ALERTS_TEXT = 'Triggered Alerts';
|
||||
const ALERT_RULES_TEXT = 'Alert Rules';
|
||||
const CONFIGURATION_TEXT = 'Configuration';
|
||||
const NOTIFICATION_CHANNELS_TEXT = 'Notification Channels';
|
||||
const PLANNED_DOWNTIME_TEXT = 'Planned Downtime';
|
||||
const ROUTING_POLICIES_TEXT = 'Routing Policies';
|
||||
const CHANNELS_SUB_TAB = 'channels';
|
||||
const PLANNED_DOWNTIME_SUB_TAB = 'planned-downtime';
|
||||
const ROUTING_POLICIES_SUB_TAB = 'routing-policies';
|
||||
|
||||
@@ -47,12 +45,6 @@ jest.mock('pages/AlertDetails', () => ({
|
||||
return <div>Alert Details Component</div>;
|
||||
},
|
||||
}));
|
||||
jest.mock('../NotificationChannels/NotificationChannels', () => ({
|
||||
__esModule: true,
|
||||
default: function MockNotificationChannels(): JSX.Element {
|
||||
return <div>Notification Channels Component</div>;
|
||||
},
|
||||
}));
|
||||
jest.mock('container/PlannedDowntime/PlannedDowntime', () => ({
|
||||
PlannedDowntime: function MockPlannedDowntime(): JSX.Element {
|
||||
return <div>Planned Downtime Component</div>;
|
||||
@@ -145,6 +137,15 @@ describe('AlertList', () => {
|
||||
expect(screen.getByText(LIST_ALERT_RULES_TEXT)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render Configuration tab with default Planned Downtime sub-tab when tab query param is Configuration', () => {
|
||||
mockQueryParams({ tab: 'Configuration' });
|
||||
mockLocation(ALERTS_PATH);
|
||||
|
||||
render(<AlertList />);
|
||||
|
||||
expect(screen.getByText(PLANNED_DOWNTIME_TEXT)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should navigate to TriggeredAlerts tab when clicked', () => {
|
||||
mockQueryParams({ tab: 'AlertRules' });
|
||||
mockLocation(ALERTS_PATH);
|
||||
@@ -166,109 +167,74 @@ describe('AlertList', () => {
|
||||
|
||||
expect(mockSafeNavigate).toHaveBeenCalledWith('/alerts?tab=AlertRules');
|
||||
});
|
||||
|
||||
it('should navigate to Configuration tab with default channels subTab when clicked', () => {
|
||||
mockQueryParams({ tab: 'AlertRules' });
|
||||
mockLocation(ALERTS_PATH);
|
||||
|
||||
render(<AlertList />);
|
||||
|
||||
clickTab(CONFIGURATION_TEXT);
|
||||
|
||||
expect(mockSafeNavigate).toHaveBeenCalledWith(
|
||||
`/alerts?tab=Configuration&subTab=${CHANNELS_SUB_TAB}`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Configuration Tab with Secondary Sidebar', () => {
|
||||
it('should render Configuration tab with secondary sidebar containing channels, routing policies, and planned downtime', () => {
|
||||
mockQueryParams({ tab: 'Configuration' });
|
||||
mockLocation(ALERTS_PATH);
|
||||
describe('Configuration Tab', () => {
|
||||
describe('Rendering', () => {
|
||||
it('should render Configuration tab with default Planned Downtime sub-tab', () => {
|
||||
mockQueryParams({ tab: CONFIGURATION_TEXT });
|
||||
mockLocation(ALERTS_PATH);
|
||||
|
||||
render(<AlertList />);
|
||||
render(<AlertList />);
|
||||
|
||||
expect(
|
||||
screen.getByTestId('alert-configuration-sidebar'),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText(NOTIFICATION_CHANNELS_TEXT)).toBeInTheDocument();
|
||||
expect(screen.getByText(ROUTING_POLICIES_TEXT)).toBeInTheDocument();
|
||||
expect(screen.getByText(PLANNED_DOWNTIME_TEXT)).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText('Notification Channels Component'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render Routing Policies when subTab is routing-policies', () => {
|
||||
mockQueryParams({
|
||||
tab: 'Configuration',
|
||||
subTab: ROUTING_POLICIES_SUB_TAB,
|
||||
expect(screen.getByText(PLANNED_DOWNTIME_TEXT)).toBeInTheDocument();
|
||||
expect(screen.getByText(ROUTING_POLICIES_TEXT)).toBeInTheDocument();
|
||||
expect(screen.getByText('Planned Downtime Component')).toBeInTheDocument();
|
||||
});
|
||||
mockLocation(ALERTS_PATH);
|
||||
|
||||
render(<AlertList />);
|
||||
it('should render Routing Policies sub-tab when subTab query param is routing-policies', () => {
|
||||
mockQueryParams({
|
||||
tab: CONFIGURATION_TEXT,
|
||||
subTab: ROUTING_POLICIES_SUB_TAB,
|
||||
});
|
||||
mockLocation(ALERTS_PATH);
|
||||
|
||||
expect(screen.getByText('Routing Policies Component')).toBeInTheDocument();
|
||||
});
|
||||
render(<AlertList />);
|
||||
|
||||
it('should render Planned Downtime when subTab is planned-downtime', () => {
|
||||
mockQueryParams({
|
||||
tab: 'Configuration',
|
||||
subTab: PLANNED_DOWNTIME_SUB_TAB,
|
||||
expect(screen.getByText('Routing Policies Component')).toBeInTheDocument();
|
||||
});
|
||||
mockLocation(ALERTS_PATH);
|
||||
|
||||
render(<AlertList />);
|
||||
|
||||
expect(screen.getByText('Planned Downtime Component')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should navigate to Routing Policies subtab when clicked in secondary sidebar', () => {
|
||||
mockQueryParams({ tab: 'Configuration', subTab: CHANNELS_SUB_TAB });
|
||||
mockLocation(ALERTS_PATH);
|
||||
describe('Navigation', () => {
|
||||
it('should navigate to Configuration tab with default subTab when clicked', () => {
|
||||
mockQueryParams({ tab: 'AlertRules' });
|
||||
mockLocation(ALERTS_PATH);
|
||||
|
||||
render(<AlertList />);
|
||||
render(<AlertList />);
|
||||
|
||||
fireEvent.click(
|
||||
screen.getByTestId('configuration-sidebar-routing-policies'),
|
||||
);
|
||||
clickTab(CONFIGURATION_TEXT);
|
||||
|
||||
expect(mockSafeNavigate).toHaveBeenCalledWith(
|
||||
`/alerts?tab=Configuration&subTab=${ROUTING_POLICIES_SUB_TAB}`,
|
||||
);
|
||||
});
|
||||
expect(mockSafeNavigate).toHaveBeenCalledWith(
|
||||
`/alerts?tab=Configuration&subTab=${PLANNED_DOWNTIME_SUB_TAB}`,
|
||||
);
|
||||
});
|
||||
|
||||
it('should navigate to Planned Downtime subtab when clicked in secondary sidebar', () => {
|
||||
mockQueryParams({ tab: 'Configuration', subTab: CHANNELS_SUB_TAB });
|
||||
mockLocation(ALERTS_PATH);
|
||||
it('should preserve existing subTab when navigating to Configuration tab', () => {
|
||||
mockQueryParams({ tab: 'AlertRules', subTab: ROUTING_POLICIES_SUB_TAB });
|
||||
mockLocation(ALERTS_PATH);
|
||||
|
||||
render(<AlertList />);
|
||||
render(<AlertList />);
|
||||
|
||||
fireEvent.click(
|
||||
screen.getByTestId('configuration-sidebar-planned-downtime'),
|
||||
);
|
||||
clickTab(CONFIGURATION_TEXT);
|
||||
|
||||
expect(mockSafeNavigate).toHaveBeenCalledWith(
|
||||
`/alerts?tab=Configuration&subTab=${PLANNED_DOWNTIME_SUB_TAB}`,
|
||||
);
|
||||
});
|
||||
expect(mockSafeNavigate).toHaveBeenCalledWith(
|
||||
`/alerts?tab=Configuration&subTab=${ROUTING_POLICIES_SUB_TAB}`,
|
||||
);
|
||||
});
|
||||
|
||||
it('should support legacy RoutingPolicies query param as Configuration tab', () => {
|
||||
mockQueryParams({ tab: 'RoutingPolicies' });
|
||||
mockLocation(ALERTS_PATH);
|
||||
it('should clear subTab when navigating away from Configuration tab', () => {
|
||||
mockQueryParams({
|
||||
tab: CONFIGURATION_TEXT,
|
||||
subTab: PLANNED_DOWNTIME_SUB_TAB,
|
||||
});
|
||||
mockLocation(ALERTS_PATH);
|
||||
|
||||
render(<AlertList />);
|
||||
render(<AlertList />);
|
||||
|
||||
expect(screen.getByText('Routing Policies Component')).toBeInTheDocument();
|
||||
});
|
||||
clickTab(ALERT_RULES_TEXT);
|
||||
|
||||
it('should support legacy PlannedDowntime query param as Configuration tab', () => {
|
||||
mockQueryParams({ tab: 'PlannedDowntime' });
|
||||
mockLocation(ALERTS_PATH);
|
||||
|
||||
render(<AlertList />);
|
||||
|
||||
expect(screen.getByText('Planned Downtime Component')).toBeInTheDocument();
|
||||
expect(mockSafeNavigate).toHaveBeenCalledWith('/alerts?tab=AlertRules');
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,8 +10,7 @@ import RoutingPolicies from 'container/RoutingPolicies';
|
||||
import TriggeredAlerts from 'container/TriggeredAlerts';
|
||||
import { useSafeNavigate } from 'hooks/useSafeNavigate';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import { GalleryVerticalEnd, Pyramid } from '@signozhq/icons';
|
||||
import cx from 'classnames';
|
||||
import { Cable, GalleryVerticalEnd, Pyramid } from '@signozhq/icons';
|
||||
import AlertDetails from 'pages/AlertDetails';
|
||||
import ChannelsEdit from 'pages/ChannelsEdit';
|
||||
import ChannelsNew from 'pages/ChannelsNew';
|
||||
@@ -22,30 +21,6 @@ import { AlertListSubTabs, AlertListTabs } from './types';
|
||||
|
||||
import './AlertList.styles.scss';
|
||||
|
||||
interface ConfigurationSidebarItem {
|
||||
key: AlertListSubTabs;
|
||||
label: string;
|
||||
itemKey: string;
|
||||
}
|
||||
|
||||
const CONFIGURATION_SIDEBAR_ITEMS: ConfigurationSidebarItem[] = [
|
||||
{
|
||||
key: AlertListSubTabs.CHANNELS,
|
||||
label: 'Notification Channels',
|
||||
itemKey: 'configuration-sidebar-channels',
|
||||
},
|
||||
{
|
||||
key: AlertListSubTabs.ROUTING_POLICIES,
|
||||
label: 'Routing Policies',
|
||||
itemKey: 'configuration-sidebar-routing-policies',
|
||||
},
|
||||
{
|
||||
key: AlertListSubTabs.PLANNED_DOWNTIME,
|
||||
label: 'Planned Downtime',
|
||||
itemKey: 'configuration-sidebar-planned-downtime',
|
||||
},
|
||||
];
|
||||
|
||||
function AllAlertList(): JSX.Element {
|
||||
const urlQuery = useUrlQuery();
|
||||
const location = useLocation();
|
||||
@@ -59,126 +34,39 @@ function AllAlertList(): JSX.Element {
|
||||
const isChannelsEdit = location.pathname.startsWith('/alerts/channels/edit/');
|
||||
const isChannelDetails = isChannelsNew || isChannelsEdit;
|
||||
|
||||
const getActiveTab = useCallback((): string => {
|
||||
if (isAlertHistory || isAlertOverview) {
|
||||
return AlertListTabs.ALERT_RULES;
|
||||
}
|
||||
if (isChannelDetails) {
|
||||
return AlertListTabs.CONFIGURATION;
|
||||
}
|
||||
if (
|
||||
tab === AlertListTabs.CHANNELS ||
|
||||
tab === AlertListTabs.ROUTING_POLICIES ||
|
||||
tab === AlertListTabs.PLANNED_DOWNTIME
|
||||
) {
|
||||
return AlertListTabs.CONFIGURATION;
|
||||
}
|
||||
return tab || AlertListTabs.ALERT_RULES;
|
||||
}, [isAlertHistory, isAlertOverview, isChannelDetails, tab]);
|
||||
|
||||
const getActiveSubTab = useCallback((): AlertListSubTabs => {
|
||||
if (isChannelDetails) {
|
||||
return AlertListSubTabs.CHANNELS;
|
||||
}
|
||||
if (tab === AlertListTabs.CHANNELS) {
|
||||
return AlertListSubTabs.CHANNELS;
|
||||
}
|
||||
if (tab === AlertListTabs.ROUTING_POLICIES) {
|
||||
return AlertListSubTabs.ROUTING_POLICIES;
|
||||
}
|
||||
if (tab === AlertListTabs.PLANNED_DOWNTIME) {
|
||||
return AlertListSubTabs.PLANNED_DOWNTIME;
|
||||
}
|
||||
if (
|
||||
subTab === AlertListSubTabs.CHANNELS ||
|
||||
subTab === AlertListSubTabs.ROUTING_POLICIES ||
|
||||
subTab === AlertListSubTabs.PLANNED_DOWNTIME
|
||||
) {
|
||||
return subTab;
|
||||
}
|
||||
return AlertListSubTabs.CHANNELS;
|
||||
}, [isChannelDetails, tab, subTab]);
|
||||
|
||||
const handleTopTabChange = useCallback(
|
||||
(newTab: string): void => {
|
||||
const handleConfigurationTabChange = useCallback(
|
||||
(subTab: string): void => {
|
||||
const queryParams = new URLSearchParams();
|
||||
queryParams.set('tab', newTab);
|
||||
|
||||
if (newTab === AlertListTabs.CONFIGURATION) {
|
||||
const currentSubTab = getActiveSubTab();
|
||||
queryParams.set('subTab', currentSubTab);
|
||||
}
|
||||
|
||||
safeNavigate(`/alerts?${queryParams.toString()}`);
|
||||
},
|
||||
[getActiveSubTab, safeNavigate],
|
||||
);
|
||||
|
||||
const handleSubTabChange = useCallback(
|
||||
(newSubTab: AlertListSubTabs): void => {
|
||||
const queryParams = new URLSearchParams();
|
||||
queryParams.set('tab', AlertListTabs.CONFIGURATION);
|
||||
queryParams.set('subTab', newSubTab);
|
||||
queryParams.set('subTab', subTab);
|
||||
safeNavigate(`/alerts?${queryParams.toString()}`);
|
||||
},
|
||||
[safeNavigate],
|
||||
);
|
||||
|
||||
const activeSubTab = getActiveSubTab();
|
||||
|
||||
const configurationTab = useMemo(
|
||||
() => (
|
||||
<div className="alert-configuration-container">
|
||||
<div
|
||||
className="alert-configuration-sidebar"
|
||||
data-testid="alert-configuration-sidebar"
|
||||
>
|
||||
{CONFIGURATION_SIDEBAR_ITEMS.map((item) => (
|
||||
<button
|
||||
key={item.key}
|
||||
type="button"
|
||||
className={cx('sidebar-nav-item', {
|
||||
active: activeSubTab === item.key,
|
||||
})}
|
||||
onClick={(): void => handleSubTabChange(item.key)}
|
||||
data-testid={item.itemKey}
|
||||
>
|
||||
<span className="sidebar-nav-item-label">{item.label}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div
|
||||
className="alert-configuration-content"
|
||||
data-testid="alert-configuration-content"
|
||||
>
|
||||
{activeSubTab === AlertListSubTabs.CHANNELS && (
|
||||
<div className="alert-rules-container">
|
||||
{isChannelsNew && <ChannelsNew />}
|
||||
{isChannelsEdit && <ChannelsEdit />}
|
||||
{!isChannelDetails && <NotificationChannels />}
|
||||
</div>
|
||||
)}
|
||||
{activeSubTab === AlertListSubTabs.ROUTING_POLICIES && (
|
||||
<div className="alert-rules-container">
|
||||
<RoutingPolicies />
|
||||
</div>
|
||||
)}
|
||||
{activeSubTab === AlertListSubTabs.PLANNED_DOWNTIME && (
|
||||
<div className="alert-rules-container">
|
||||
<PlannedDowntime />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
[
|
||||
activeSubTab,
|
||||
handleSubTabChange,
|
||||
isChannelsNew,
|
||||
isChannelsEdit,
|
||||
isChannelDetails,
|
||||
],
|
||||
);
|
||||
const configurationTab = useMemo(() => {
|
||||
const tabs = [
|
||||
{
|
||||
label: 'Planned Downtime',
|
||||
key: AlertListSubTabs.PLANNED_DOWNTIME,
|
||||
children: <PlannedDowntime />,
|
||||
},
|
||||
{
|
||||
label: 'Routing Policies',
|
||||
key: AlertListSubTabs.ROUTING_POLICIES,
|
||||
children: <RoutingPolicies />,
|
||||
},
|
||||
];
|
||||
return (
|
||||
<Tabs
|
||||
className="configuration-tabs"
|
||||
activeKey={subTab || AlertListSubTabs.PLANNED_DOWNTIME}
|
||||
items={tabs}
|
||||
onChange={handleConfigurationTabChange}
|
||||
/>
|
||||
);
|
||||
}, [subTab, handleConfigurationTabChange]);
|
||||
|
||||
const items: TabsProps['items'] = [
|
||||
{
|
||||
@@ -205,6 +93,22 @@ function AllAlertList(): JSX.Element {
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
label: (
|
||||
<div className="periscope-tab top-level-tab">
|
||||
<Cable size={14} />
|
||||
Notification Channels
|
||||
</div>
|
||||
),
|
||||
key: AlertListTabs.CHANNELS,
|
||||
children: (
|
||||
<div className="alert-rules-container">
|
||||
{isChannelsNew && <ChannelsNew />}
|
||||
{isChannelsEdit && <ChannelsEdit />}
|
||||
{!isChannelDetails && <NotificationChannels />}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
label: (
|
||||
<div className="periscope-tab top-level-tab">
|
||||
@@ -217,12 +121,37 @@ function AllAlertList(): JSX.Element {
|
||||
},
|
||||
];
|
||||
|
||||
const getActiveKey = (): string => {
|
||||
if (isAlertHistory || isAlertOverview) {
|
||||
return AlertListTabs.ALERT_RULES;
|
||||
}
|
||||
if (isChannelDetails) {
|
||||
return AlertListTabs.CHANNELS;
|
||||
}
|
||||
return tab || AlertListTabs.ALERT_RULES;
|
||||
};
|
||||
|
||||
return (
|
||||
<Tabs
|
||||
destroyInactiveTabPane
|
||||
items={items}
|
||||
activeKey={getActiveTab()}
|
||||
onChange={handleTopTabChange}
|
||||
activeKey={getActiveKey()}
|
||||
onChange={(tab): void => {
|
||||
const queryParams = new URLSearchParams();
|
||||
|
||||
queryParams.set('tab', tab);
|
||||
|
||||
// If navigating to Configuration tab, set default subTab
|
||||
if (tab === AlertListTabs.CONFIGURATION) {
|
||||
const currentSubTab = subTab || AlertListSubTabs.PLANNED_DOWNTIME;
|
||||
queryParams.set('subTab', currentSubTab);
|
||||
} else {
|
||||
// Clear subTab when navigating out of Configuration tab
|
||||
queryParams.delete('subTab');
|
||||
}
|
||||
|
||||
safeNavigate(`/alerts?${queryParams.toString()}`);
|
||||
}}
|
||||
className={`alerts-container ${
|
||||
isAlertHistory || isAlertOverview || isChannelDetails
|
||||
? 'alert-details-tabs'
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
export enum AlertListSubTabs {
|
||||
CHANNELS = 'channels',
|
||||
ROUTING_POLICIES = 'routing-policies',
|
||||
PLANNED_DOWNTIME = 'planned-downtime',
|
||||
ROUTING_POLICIES = 'routing-policies',
|
||||
}
|
||||
|
||||
export enum AlertListTabs {
|
||||
@@ -9,6 +8,4 @@ export enum AlertListTabs {
|
||||
ALERT_RULES = 'AlertRules',
|
||||
CONFIGURATION = 'Configuration',
|
||||
CHANNELS = 'Channels',
|
||||
ROUTING_POLICIES = 'RoutingPolicies',
|
||||
PLANNED_DOWNTIME = 'PlannedDowntime',
|
||||
}
|
||||
|
||||
@@ -166,10 +166,7 @@ function PanelEditorQueryBuilder({
|
||||
return modes.map((queryType) => ({
|
||||
key: queryType,
|
||||
label: (
|
||||
<div
|
||||
className={styles.queryTypeTab}
|
||||
data-testid={`query-type-tab-${queryType}`}
|
||||
>
|
||||
<div className={styles.queryTypeTab}>
|
||||
{queryTypeComponents[queryType].icon}
|
||||
<Typography>{queryTypeComponents[queryType].label}</Typography>
|
||||
</div>
|
||||
|
||||
@@ -74,7 +74,8 @@
|
||||
"meter-metrics",
|
||||
"logs-field",
|
||||
"traces-field",
|
||||
"metrics-field"
|
||||
"metrics-field",
|
||||
"llm-pricing-rule"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
|
||||
@@ -34,9 +34,6 @@ type Alertmanager interface {
|
||||
// ListChannels lists all channels for the organization.
|
||||
ListChannels(context.Context, string) ([]*alertmanagertypes.Channel, error)
|
||||
|
||||
// GetChannelIDsByNames resolves display names to channel ids and rejects unknown names.
|
||||
GetChannelIDsByNames(context.Context, string, []string) ([]string, error)
|
||||
|
||||
// ListAllChannels lists all channels for all organizations. It is used by the legacy alertmanager only.
|
||||
ListAllChannels(context.Context) ([]*alertmanagertypes.Channel, error)
|
||||
|
||||
|
||||
@@ -1023,80 +1023,6 @@ func (_c *MockAlertmanager_GetChannelByID_Call) RunAndReturn(run func(context1 c
|
||||
return _c
|
||||
}
|
||||
|
||||
// GetChannelIDsByNames provides a mock function for the type MockAlertmanager
|
||||
func (_mock *MockAlertmanager) GetChannelIDsByNames(context1 context.Context, s string, strings []string) ([]string, error) {
|
||||
ret := _mock.Called(context1, s, strings)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for GetChannelIDsByNames")
|
||||
}
|
||||
|
||||
var r0 []string
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string, []string) ([]string, error)); ok {
|
||||
return returnFunc(context1, s, strings)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string, []string) []string); ok {
|
||||
r0 = returnFunc(context1, s, strings)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]string)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, string, []string) error); ok {
|
||||
r1 = returnFunc(context1, s, strings)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockAlertmanager_GetChannelIDsByNames_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetChannelIDsByNames'
|
||||
type MockAlertmanager_GetChannelIDsByNames_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// GetChannelIDsByNames is a helper method to define mock.On call
|
||||
// - context1 context.Context
|
||||
// - s string
|
||||
// - strings []string
|
||||
func (_e *MockAlertmanager_Expecter) GetChannelIDsByNames(context1 any, s any, strings any) *MockAlertmanager_GetChannelIDsByNames_Call {
|
||||
return &MockAlertmanager_GetChannelIDsByNames_Call{Call: _e.mock.On("GetChannelIDsByNames", context1, s, strings)}
|
||||
}
|
||||
|
||||
func (_c *MockAlertmanager_GetChannelIDsByNames_Call) Run(run func(context1 context.Context, s string, strings []string)) *MockAlertmanager_GetChannelIDsByNames_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
var arg2 []string
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].([]string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAlertmanager_GetChannelIDsByNames_Call) Return(strings1 []string, err error) *MockAlertmanager_GetChannelIDsByNames_Call {
|
||||
_c.Call.Return(strings1, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAlertmanager_GetChannelIDsByNames_Call) RunAndReturn(run func(context1 context.Context, s string, strings []string) ([]string, error)) *MockAlertmanager_GetChannelIDsByNames_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// GetConfig provides a mock function for the type MockAlertmanager
|
||||
func (_mock *MockAlertmanager) GetConfig(context1 context.Context, s string) (*alertmanagertypes.Config, error) {
|
||||
ret := _mock.Called(context1, s)
|
||||
|
||||
@@ -147,19 +147,6 @@ func (provider *provider) ListChannels(ctx context.Context, orgID string) ([]*al
|
||||
return channels, err
|
||||
}
|
||||
|
||||
func (provider *provider) GetChannelIDsByNames(ctx context.Context, orgID string, names []string) ([]string, error) {
|
||||
if len(names) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
channels, _, err := provider.configStore.ListChannels(ctx, orgID, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return alertmanagertypes.MapChannelNamesToIDs(channels, names)
|
||||
}
|
||||
|
||||
func (provider *provider) ListNotificationChannels(ctx context.Context, orgID string, params *alertmanagertypes.ListChannelsParams) (*alertmanagertypes.ListableNotificationChannel, error) {
|
||||
channels, total, err := provider.configStore.ListChannels(ctx, orgID, params)
|
||||
if err != nil {
|
||||
@@ -541,10 +528,6 @@ func (provider *provider) CreateRoutePolicy(ctx context.Context, routeRequest *a
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if _, err := provider.GetChannelIDsByNames(ctx, orgID.String(), routeRequest.Channels); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
route := alertmanagertypes.RoutePolicy{
|
||||
Expression: routeRequest.Expression,
|
||||
ExpressionKind: routeRequest.ExpressionKind,
|
||||
@@ -737,10 +720,6 @@ func (provider *provider) UpdateRoutePolicyByID(ctx context.Context, routeID str
|
||||
return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid route: %v", err)
|
||||
}
|
||||
|
||||
if _, err := provider.GetChannelIDsByNames(ctx, orgID.String(), route.Channels); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
existingRoute, err := provider.notificationManager.GetRoutePolicyByID(ctx, claims.OrgID, routeID)
|
||||
if err != nil {
|
||||
return nil, errors.NewInvalidInputf(errors.CodeNotFound, "route not found: %v", err)
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/http/handler"
|
||||
"github.com/SigNoz/signoz/pkg/ruler"
|
||||
"github.com/SigNoz/signoz/pkg/types"
|
||||
"github.com/SigNoz/signoz/pkg/types/alertmanagertypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/authtypes"
|
||||
@@ -331,167 +330,88 @@ func (provider *provider) addAlertmanagerRoutes(router *mux.Router) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/route_policies", handler.New(
|
||||
provider.authzMiddleware.CheckResources(provider.alertmanagerHandler.GetAllRoutePolicies, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "GetAllRoutePolicies",
|
||||
Tags: []string{"routepolicies"},
|
||||
Summary: "List route policies",
|
||||
Description: "This endpoint lists all route policies for the organization",
|
||||
Response: make([]*alertmanagertypes.GettableRoutePolicy, 0),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceRoutePolicy.Scope(coretypes.VerbList)}),
|
||||
},
|
||||
handler.WithResourceDefs(handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceRoutePolicy,
|
||||
Verb: coretypes.VerbList,
|
||||
Category: coretypes.ActionCategoryDataAccess,
|
||||
Selector: coretypes.WildcardSelector,
|
||||
}),
|
||||
)).Methods(http.MethodGet).GetError(); err != nil {
|
||||
if err := router.Handle("/api/v1/route_policies", handler.New(provider.authzMiddleware.ViewAccess(provider.alertmanagerHandler.GetAllRoutePolicies), handler.OpenAPIDef{
|
||||
ID: "GetAllRoutePolicies",
|
||||
Tags: []string{"routepolicies"},
|
||||
Summary: "List route policies",
|
||||
Description: "This endpoint lists all route policies for the organization",
|
||||
Request: nil,
|
||||
RequestContentType: "",
|
||||
Response: make([]*alertmanagertypes.GettableRoutePolicy, 0),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
|
||||
})).Methods(http.MethodGet).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/route_policies/{id}", handler.New(
|
||||
provider.authzMiddleware.CheckResources(provider.alertmanagerHandler.GetRoutePolicyByID, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "GetRoutePolicyByID",
|
||||
Tags: []string{"routepolicies"},
|
||||
Summary: "Get route policy by ID",
|
||||
Description: "This endpoint returns a route policy by ID",
|
||||
Response: new(alertmanagertypes.GettableRoutePolicy),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusNotFound},
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceRoutePolicy.Scope(coretypes.VerbRead)}),
|
||||
},
|
||||
handler.WithResourceDefs(handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceRoutePolicy,
|
||||
Verb: coretypes.VerbRead,
|
||||
Category: coretypes.ActionCategoryDataAccess,
|
||||
ID: coretypes.PathParam("id"),
|
||||
Selector: coretypes.IDSelector,
|
||||
}),
|
||||
)).Methods(http.MethodGet).GetError(); err != nil {
|
||||
if err := router.Handle("/api/v1/route_policies/{id}", handler.New(provider.authzMiddleware.ViewAccess(provider.alertmanagerHandler.GetRoutePolicyByID), handler.OpenAPIDef{
|
||||
ID: "GetRoutePolicyByID",
|
||||
Tags: []string{"routepolicies"},
|
||||
Summary: "Get route policy by ID",
|
||||
Description: "This endpoint returns a route policy by ID",
|
||||
Request: nil,
|
||||
RequestContentType: "",
|
||||
Response: new(alertmanagertypes.GettableRoutePolicy),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusNotFound},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
|
||||
})).Methods(http.MethodGet).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/route_policies", handler.New(
|
||||
provider.authzMiddleware.CheckResources(provider.alertmanagerHandler.CreateRoutePolicy, authtypes.SigNozAdminRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "CreateRoutePolicy",
|
||||
Tags: []string{"routepolicies"},
|
||||
Summary: "Create route policy",
|
||||
Description: "This endpoint creates a route policy",
|
||||
Request: new(alertmanagertypes.PostableRoutePolicy),
|
||||
RequestContentType: "application/json",
|
||||
Response: new(alertmanagertypes.GettableRoutePolicy),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusCreated,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest},
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{
|
||||
coretypes.ResourceMetaResourceRoutePolicy.Scope(coretypes.VerbCreate),
|
||||
coretypes.ResourceMetaResourceRoutePolicy.Scope(coretypes.VerbAttach),
|
||||
coretypes.ResourceMetaResourceNotificationChannel.Scope(coretypes.VerbAttach),
|
||||
}),
|
||||
},
|
||||
handler.WithResourceDefs(
|
||||
handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceRoutePolicy,
|
||||
Verb: coretypes.VerbCreate,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
ID: coretypes.ResponseJSONPath("data.id"),
|
||||
Selector: coretypes.WildcardSelector,
|
||||
},
|
||||
handler.AttachDetachSiblingResourceDef{
|
||||
Verb: coretypes.VerbAttach,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
SourceResource: coretypes.ResourceMetaResourceRoutePolicy,
|
||||
SourceIDs: coretypes.OneID(coretypes.ResponseJSONPath("data.id")),
|
||||
SourceSelector: coretypes.WildcardSelector,
|
||||
TargetResource: coretypes.ResourceMetaResourceNotificationChannel,
|
||||
TargetIDs: ruler.NewCreateRoutePolicyChannelAttachExtractor(provider.alertmanagerService),
|
||||
TargetSelector: coretypes.IDSelector,
|
||||
},
|
||||
),
|
||||
)).Methods(http.MethodPost).GetError(); err != nil {
|
||||
if err := router.Handle("/api/v1/route_policies", handler.New(provider.authzMiddleware.AdminAccess(provider.alertmanagerHandler.CreateRoutePolicy), handler.OpenAPIDef{
|
||||
ID: "CreateRoutePolicy",
|
||||
Tags: []string{"routepolicies"},
|
||||
Summary: "Create route policy",
|
||||
Description: "This endpoint creates a route policy",
|
||||
Request: new(alertmanagertypes.PostableRoutePolicy),
|
||||
RequestContentType: "application/json",
|
||||
Response: new(alertmanagertypes.GettableRoutePolicy),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusCreated,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
|
||||
})).Methods(http.MethodPost).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/route_policies/{id}", handler.New(
|
||||
provider.authzMiddleware.CheckResources(provider.alertmanagerHandler.UpdateRoutePolicy, authtypes.SigNozAdminRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "UpdateRoutePolicy",
|
||||
Tags: []string{"routepolicies"},
|
||||
Summary: "Update route policy",
|
||||
Description: "This endpoint updates a route policy by ID",
|
||||
Request: new(alertmanagertypes.PostableRoutePolicy),
|
||||
RequestContentType: "application/json",
|
||||
Response: new(alertmanagertypes.GettableRoutePolicy),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{
|
||||
coretypes.ResourceMetaResourceRoutePolicy.Scope(coretypes.VerbUpdate),
|
||||
coretypes.ResourceMetaResourceRoutePolicy.Scope(coretypes.VerbAttach),
|
||||
coretypes.ResourceMetaResourceRoutePolicy.Scope(coretypes.VerbDetach),
|
||||
coretypes.ResourceMetaResourceNotificationChannel.Scope(coretypes.VerbAttach),
|
||||
coretypes.ResourceMetaResourceNotificationChannel.Scope(coretypes.VerbDetach),
|
||||
}),
|
||||
},
|
||||
handler.WithResourceDefs(
|
||||
handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceRoutePolicy,
|
||||
Verb: coretypes.VerbUpdate,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
ID: coretypes.PathParam("id"),
|
||||
Selector: coretypes.IDSelector,
|
||||
},
|
||||
handler.AttachDetachSiblingResourceDef{
|
||||
Verb: coretypes.VerbAttach,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
SourceResource: coretypes.ResourceMetaResourceRoutePolicy,
|
||||
SourceIDs: coretypes.OneID(coretypes.PathParam("id")),
|
||||
SourceSelector: coretypes.IDSelector,
|
||||
TargetResource: coretypes.ResourceMetaResourceNotificationChannel,
|
||||
TargetIDs: ruler.NewUpdateRoutePolicyChannelAttachExtractor(provider.alertmanagerService),
|
||||
TargetSelector: coretypes.IDSelector,
|
||||
},
|
||||
handler.AttachDetachSiblingResourceDef{
|
||||
Verb: coretypes.VerbDetach,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
SourceResource: coretypes.ResourceMetaResourceRoutePolicy,
|
||||
SourceIDs: coretypes.OneID(coretypes.PathParam("id")),
|
||||
SourceSelector: coretypes.IDSelector,
|
||||
TargetResource: coretypes.ResourceMetaResourceNotificationChannel,
|
||||
TargetIDs: ruler.NewUpdateRoutePolicyChannelDetachExtractor(provider.alertmanagerService),
|
||||
TargetSelector: coretypes.IDSelector,
|
||||
},
|
||||
),
|
||||
)).Methods(http.MethodPut).GetError(); err != nil {
|
||||
if err := router.Handle("/api/v1/route_policies/{id}", handler.New(provider.authzMiddleware.AdminAccess(provider.alertmanagerHandler.UpdateRoutePolicy), handler.OpenAPIDef{
|
||||
ID: "UpdateRoutePolicy",
|
||||
Tags: []string{"routepolicies"},
|
||||
Summary: "Update route policy",
|
||||
Description: "This endpoint updates a route policy by ID",
|
||||
Request: new(alertmanagertypes.PostableRoutePolicy),
|
||||
RequestContentType: "application/json",
|
||||
Response: new(alertmanagertypes.GettableRoutePolicy),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
|
||||
})).Methods(http.MethodPut).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/route_policies/{id}", handler.New(
|
||||
provider.authzMiddleware.CheckResources(provider.alertmanagerHandler.DeleteRoutePolicyByID, authtypes.SigNozAdminRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "DeleteRoutePolicyByID",
|
||||
Tags: []string{"routepolicies"},
|
||||
Summary: "Delete route policy",
|
||||
Description: "This endpoint deletes a route policy by ID",
|
||||
SuccessStatusCode: http.StatusNoContent,
|
||||
ErrorStatusCodes: []int{http.StatusNotFound},
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceRoutePolicy.Scope(coretypes.VerbDelete)}),
|
||||
},
|
||||
handler.WithResourceDefs(handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceRoutePolicy,
|
||||
Verb: coretypes.VerbDelete,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
ID: coretypes.PathParam("id"),
|
||||
Selector: coretypes.IDSelector,
|
||||
}),
|
||||
)).Methods(http.MethodDelete).GetError(); err != nil {
|
||||
if err := router.Handle("/api/v1/route_policies/{id}", handler.New(provider.authzMiddleware.AdminAccess(provider.alertmanagerHandler.DeleteRoutePolicyByID), handler.OpenAPIDef{
|
||||
ID: "DeleteRoutePolicyByID",
|
||||
Tags: []string{"routepolicies"},
|
||||
Summary: "Delete route policy",
|
||||
Description: "This endpoint deletes a route policy by ID",
|
||||
Request: nil,
|
||||
RequestContentType: "",
|
||||
Response: nil,
|
||||
ResponseContentType: "",
|
||||
SuccessStatusCode: http.StatusNoContent,
|
||||
ErrorStatusCodes: []int{http.StatusNotFound},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
|
||||
})).Methods(http.MethodDelete).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -4,14 +4,15 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/http/handler"
|
||||
"github.com/SigNoz/signoz/pkg/types"
|
||||
"github.com/SigNoz/signoz/pkg/types/authtypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/coretypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/llmpricingruletypes"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
func (provider *provider) addLLMPricingRuleRoutes(router *mux.Router) error {
|
||||
if err := router.Handle("/api/v1/llm_pricing_rules", handler.New(
|
||||
provider.authzMiddleware.ViewAccess(provider.llmPricingRuleHandler.List),
|
||||
provider.authzMiddleware.CheckResources(provider.llmPricingRuleHandler.List, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "ListLLMPricingRules",
|
||||
Tags: []string{"llmpricingrules"},
|
||||
@@ -25,14 +26,20 @@ func (provider *provider) addLLMPricingRuleRoutes(router *mux.Router) error {
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceLLMPricingRule.Scope(coretypes.VerbList)}),
|
||||
},
|
||||
handler.WithResourceDefs(handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceLLMPricingRule,
|
||||
Verb: coretypes.VerbList,
|
||||
Category: coretypes.ActionCategoryDataAccess,
|
||||
Selector: coretypes.WildcardSelector,
|
||||
}),
|
||||
)).Methods(http.MethodGet).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/llm_pricing_rules", handler.New(
|
||||
provider.authzMiddleware.AdminAccess(provider.llmPricingRuleHandler.CreateOrUpdate),
|
||||
provider.authzMiddleware.CheckResources(provider.llmPricingRuleHandler.CreateOrUpdate, authtypes.SigNozAdminRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "CreateOrUpdateLLMPricingRules",
|
||||
Tags: []string{"llmpricingrules"},
|
||||
@@ -43,14 +50,20 @@ func (provider *provider) addLLMPricingRuleRoutes(router *mux.Router) error {
|
||||
SuccessStatusCode: http.StatusNoContent,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceLLMPricingRule.Scope(coretypes.VerbUpdate)}),
|
||||
},
|
||||
handler.WithResourceDefs(handler.TelemetryResourceDef{
|
||||
Verb: coretypes.VerbUpdate,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
Selector: llmpricingruletypes.RuleSelector,
|
||||
Resources: llmpricingruletypes.UpdatableRulesResources,
|
||||
}),
|
||||
)).Methods(http.MethodPut).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/llm_pricing_rules/unmapped_models", handler.New(
|
||||
provider.authzMiddleware.ViewAccess(provider.llmPricingRuleHandler.ListUnmappedModels),
|
||||
provider.authzMiddleware.CheckResources(provider.llmPricingRuleHandler.ListUnmappedModels, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "ListUnmappedLLMModels",
|
||||
Tags: []string{"llmpricingrules"},
|
||||
@@ -63,14 +76,20 @@ func (provider *provider) addLLMPricingRuleRoutes(router *mux.Router) error {
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceLLMPricingRule.Scope(coretypes.VerbList)}),
|
||||
},
|
||||
handler.WithResourceDefs(handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceLLMPricingRule,
|
||||
Verb: coretypes.VerbList,
|
||||
Category: coretypes.ActionCategoryDataAccess,
|
||||
Selector: coretypes.WildcardSelector,
|
||||
}),
|
||||
)).Methods(http.MethodGet).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/llm_pricing_rules/{id}", handler.New(
|
||||
provider.authzMiddleware.ViewAccess(provider.llmPricingRuleHandler.Get),
|
||||
provider.authzMiddleware.CheckResources(provider.llmPricingRuleHandler.Get, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "GetLLMPricingRule",
|
||||
Tags: []string{"llmpricingrules"},
|
||||
@@ -83,14 +102,21 @@ func (provider *provider) addLLMPricingRuleRoutes(router *mux.Router) error {
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusNotFound},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceLLMPricingRule.Scope(coretypes.VerbRead)}),
|
||||
},
|
||||
handler.WithResourceDefs(handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceLLMPricingRule,
|
||||
Verb: coretypes.VerbRead,
|
||||
Category: coretypes.ActionCategoryDataAccess,
|
||||
ID: coretypes.PathParam("id"),
|
||||
Selector: coretypes.IDSelector,
|
||||
}),
|
||||
)).Methods(http.MethodGet).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/llm_pricing_rules/{id}", handler.New(
|
||||
provider.authzMiddleware.AdminAccess(provider.llmPricingRuleHandler.Delete),
|
||||
provider.authzMiddleware.CheckResources(provider.llmPricingRuleHandler.Delete, authtypes.SigNozAdminRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "DeleteLLMPricingRule",
|
||||
Tags: []string{"llmpricingrules"},
|
||||
@@ -103,8 +129,15 @@ func (provider *provider) addLLMPricingRuleRoutes(router *mux.Router) error {
|
||||
SuccessStatusCode: http.StatusNoContent,
|
||||
ErrorStatusCodes: []int{http.StatusNotFound},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceLLMPricingRule.Scope(coretypes.VerbDelete)}),
|
||||
},
|
||||
handler.WithResourceDefs(handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceLLMPricingRule,
|
||||
Verb: coretypes.VerbDelete,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
ID: coretypes.PathParam("id"),
|
||||
Selector: coretypes.IDSelector,
|
||||
}),
|
||||
)).Methods(http.MethodDelete).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -91,7 +91,6 @@ type provider struct {
|
||||
ruleStateHistoryHandler rulestatehistory.Handler
|
||||
spanMapperHandler spanmapper.Handler
|
||||
alertmanagerHandler alertmanager.Handler
|
||||
alertmanagerService alertmanager.Alertmanager
|
||||
prometheusHandler prometheus.Handler
|
||||
traceDetailHandler tracedetail.Handler
|
||||
rulerHandler ruler.Handler
|
||||
@@ -137,7 +136,6 @@ func NewFactory(
|
||||
ruleStateHistoryHandler rulestatehistory.Handler,
|
||||
spanMapperHandler spanmapper.Handler,
|
||||
alertmanagerHandler alertmanager.Handler,
|
||||
alertmanagerService alertmanager.Alertmanager,
|
||||
prometheusHandler prometheus.Handler,
|
||||
llmPricingRuleHandler llmpricingrule.Handler,
|
||||
traceDetailHandler tracedetail.Handler,
|
||||
@@ -191,7 +189,6 @@ func NewFactory(
|
||||
ruleStateHistoryHandler,
|
||||
spanMapperHandler,
|
||||
alertmanagerHandler,
|
||||
alertmanagerService,
|
||||
prometheusHandler,
|
||||
llmPricingRuleHandler,
|
||||
traceDetailHandler,
|
||||
@@ -247,7 +244,6 @@ func newProvider(
|
||||
ruleStateHistoryHandler rulestatehistory.Handler,
|
||||
spanMapperHandler spanmapper.Handler,
|
||||
alertmanagerHandler alertmanager.Handler,
|
||||
alertmanagerService alertmanager.Alertmanager,
|
||||
prometheusHandler prometheus.Handler,
|
||||
llmPricingRuleHandler llmpricingrule.Handler,
|
||||
traceDetailHandler tracedetail.Handler,
|
||||
@@ -303,7 +299,6 @@ func newProvider(
|
||||
ruleStateHistoryHandler: ruleStateHistoryHandler,
|
||||
spanMapperHandler: spanMapperHandler,
|
||||
alertmanagerHandler: alertmanagerHandler,
|
||||
alertmanagerService: alertmanagerService,
|
||||
prometheusHandler: prometheusHandler,
|
||||
traceDetailHandler: traceDetailHandler,
|
||||
rulerHandler: rulerHandler,
|
||||
|
||||
@@ -140,9 +140,7 @@ func (handler *handler) QueryRawStream(rw http.ResponseWriter, req *http.Request
|
||||
}
|
||||
// create the v5 request param
|
||||
queryRangeRequest := qbtypes.QueryRangeRequest{
|
||||
// Coerce the window to epoch milliseconds up front (End may be 0 for the
|
||||
// open-ended stream, which ToMilliSecs leaves untouched).
|
||||
Start: qbtypes.ToMilliSecs(start),
|
||||
Start: start,
|
||||
RequestType: qbtypes.RequestTypeRawStream,
|
||||
CompositeQuery: qbtypes.CompositeQuery{
|
||||
Queries: []qbtypes.QueryEnvelope{
|
||||
|
||||
@@ -11,12 +11,6 @@ func makeBuckets(start, end uint64) []tsRange {
|
||||
startNS := querybuilder.ToNanoSecs(start)
|
||||
endNS := querybuilder.ToNanoSecs(end)
|
||||
|
||||
// A cursor that reaches the window boundary can leave end <= start; the
|
||||
// subtractions below are unsigned and would wrap.
|
||||
if endNS <= startNS {
|
||||
return nil
|
||||
}
|
||||
|
||||
if endNS-startNS <= uint64(hourNanos) {
|
||||
return []tsRange{{fromNS: startNS, toNS: endNS}}
|
||||
}
|
||||
@@ -26,9 +20,9 @@ func makeBuckets(start, end uint64) []tsRange {
|
||||
curEnd := endNS
|
||||
|
||||
for {
|
||||
curStart := startNS
|
||||
if curEnd-startNS > bucket {
|
||||
curStart = curEnd - bucket
|
||||
curStart := curEnd - bucket
|
||||
if curStart < startNS {
|
||||
curStart = startNS
|
||||
}
|
||||
out = append(out, tsRange{fromNS: curStart, toNS: curEnd})
|
||||
|
||||
|
||||
@@ -111,10 +111,11 @@ func New(
|
||||
|
||||
func (q *querier) QueryRange(ctx context.Context, orgID valuer.UUID, req *qbtypes.QueryRangeRequest) (*qbtypes.QueryRangeResponse, error) {
|
||||
|
||||
// Callers that build the request in-process never pass through
|
||||
// UnmarshalJSON, so normalise here too.
|
||||
req.Start = qbtypes.ToMilliSecs(req.Start)
|
||||
req.End = qbtypes.ToMilliSecs(req.End)
|
||||
// Coerce the window to epoch milliseconds up front so every downstream
|
||||
// consumer (TimeRange, narrowWindowByTraceID, step interval, etc.) can
|
||||
// safely assume ms regardless of the resolution the caller sent.
|
||||
req.Start = querybuilder.ToMilliSecs(req.Start)
|
||||
req.End = querybuilder.ToMilliSecs(req.End)
|
||||
|
||||
event := &qbtypes.QBEvent{
|
||||
Version: "v5",
|
||||
@@ -533,8 +534,10 @@ func familyTemporality(temporalities map[string]metrictypes.Temporality, names [
|
||||
|
||||
func (q *querier) QueryRawStream(ctx context.Context, orgID valuer.UUID, req *qbtypes.QueryRangeRequest, client *qbtypes.RawStream) {
|
||||
|
||||
req.Start = qbtypes.ToMilliSecs(req.Start)
|
||||
req.End = qbtypes.ToMilliSecs(req.End)
|
||||
// Coerce the window to epoch milliseconds up front (End may be 0 for the
|
||||
// open-ended stream, which ToMilliSecs leaves untouched).
|
||||
req.Start = querybuilder.ToMilliSecs(req.Start)
|
||||
req.End = querybuilder.ToMilliSecs(req.End)
|
||||
|
||||
event := &qbtypes.QBEvent{
|
||||
Version: "v5",
|
||||
|
||||
@@ -33,6 +33,28 @@ func ToNanoSecs(epoch uint64) uint64 {
|
||||
return temp * uint64(math.Pow(10, float64(19-count)))
|
||||
}
|
||||
|
||||
// ToMilliSecs takes an epoch whose resolution is inferred from its magnitude
|
||||
// (s/ms/µs/ns) and returns it in milliseconds. A millisecond epoch for the
|
||||
// current era has 13 digits (e.g. ~1.7e12 in 2026), so the value is scaled so
|
||||
// its digit-width matches: smaller values (seconds) are scaled up, larger ones
|
||||
// (micro/nanoseconds) are scaled down. Zero is returned unchanged.
|
||||
func ToMilliSecs(epoch uint64) uint64 {
|
||||
if epoch == 0 {
|
||||
return 0
|
||||
}
|
||||
temp := epoch
|
||||
count := 0
|
||||
for epoch != 0 {
|
||||
epoch /= 10
|
||||
count++
|
||||
}
|
||||
const msDigits = 13
|
||||
if count < msDigits {
|
||||
return temp * uint64(math.Pow(10, float64(msDigits-count)))
|
||||
}
|
||||
return temp / uint64(math.Pow(10, float64(count-msDigits)))
|
||||
}
|
||||
|
||||
// TODO(srikanthccv): should these be rounded to nearest multiple of 60 instead of 5 if step > 60?
|
||||
// That would make graph look nice but "nice" but should be less important than the usefulness.
|
||||
func RecommendedStepInterval(start, end uint64) uint64 {
|
||||
|
||||
@@ -60,3 +60,51 @@ func TestToNanoSecs(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToMilliSecs(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
epoch uint64
|
||||
expected uint64
|
||||
}{
|
||||
{
|
||||
name: "10-digit Unix timestamp (seconds) - 2023-01-01 00:00:00 UTC",
|
||||
epoch: 1672531200, // seconds
|
||||
expected: 1672531200000, // * 10^3
|
||||
},
|
||||
{
|
||||
name: "13-digit Unix timestamp (milliseconds) - already ms",
|
||||
epoch: 1672531200000,
|
||||
expected: 1672531200000, // unchanged
|
||||
},
|
||||
{
|
||||
name: "16-digit Unix timestamp (microseconds)",
|
||||
epoch: 1672531200000000, // microseconds
|
||||
expected: 1672531200000, // / 10^3
|
||||
},
|
||||
{
|
||||
name: "19-digit Unix timestamp (nanoseconds)",
|
||||
epoch: 1672531200000000000, // nanoseconds
|
||||
expected: 1672531200000, // / 10^6
|
||||
},
|
||||
{
|
||||
name: "Unix epoch start - zero is unchanged",
|
||||
epoch: 0,
|
||||
expected: 0,
|
||||
},
|
||||
{
|
||||
name: "Recent timestamp in seconds - 2024-05-25 12:00:00 UTC",
|
||||
epoch: 1716638400,
|
||||
expected: 1716638400000,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result := ToMilliSecs(tt.epoch)
|
||||
if result != tt.expected {
|
||||
t.Errorf("ToMilliSecs(%d) = %d, want %d", tt.epoch, result, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,127 +0,0 @@
|
||||
package ruler
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/alertmanager"
|
||||
"github.com/SigNoz/signoz/pkg/types/authtypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/coretypes"
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
const (
|
||||
attachedSide diffSide = iota
|
||||
detachedSide
|
||||
)
|
||||
|
||||
type diffSide int
|
||||
|
||||
func NewCreateRoutePolicyChannelAttachExtractor(alertmanagerService alertmanager.Alertmanager) coretypes.ResourceIDsExtractor {
|
||||
return coretypes.ResourceIDsExtractor{Phase: coretypes.PhaseRequest, Fn: func(ec coretypes.ExtractorContext) ([]string, error) {
|
||||
if ec.Request == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
ctx := ec.Request.Context()
|
||||
orgID, err := orgIDFromContext(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
names, err := coretypes.BodyJSONArray("channels").Fn(ec)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return alertmanagerService.GetChannelIDsByNames(ctx, orgID.StringValue(), names)
|
||||
}}
|
||||
}
|
||||
|
||||
func NewUpdateRoutePolicyChannelAttachExtractor(alertmanagerService alertmanager.Alertmanager) coretypes.ResourceIDsExtractor {
|
||||
return newRoutePolicyDiffExtractor(alertmanagerService, attachedSide)
|
||||
}
|
||||
|
||||
func NewUpdateRoutePolicyChannelDetachExtractor(alertmanagerService alertmanager.Alertmanager) coretypes.ResourceIDsExtractor {
|
||||
return newRoutePolicyDiffExtractor(alertmanagerService, detachedSide)
|
||||
}
|
||||
|
||||
func newRoutePolicyDiffExtractor(alertmanagerService alertmanager.Alertmanager, side diffSide) coretypes.ResourceIDsExtractor {
|
||||
return coretypes.ResourceIDsExtractor{Phase: coretypes.PhaseRequest, Fn: func(ec coretypes.ExtractorContext) ([]string, error) {
|
||||
if ec.Request == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
ctx := ec.Request.Context()
|
||||
orgID, err := orgIDFromContext(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
stored, err := alertmanagerService.GetRoutePolicyByID(ctx, mux.Vars(ec.Request)["id"])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
incoming, err := coretypes.BodyJSONArray("channels").Fn(ec)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
attached, detached := diffLinks(stored.Channels, incoming)
|
||||
if side == detachedSide {
|
||||
return alertmanagerService.GetChannelIDsByNames(ctx, orgID.StringValue(), detached)
|
||||
}
|
||||
|
||||
return alertmanagerService.GetChannelIDsByNames(ctx, orgID.StringValue(), attached)
|
||||
}}
|
||||
}
|
||||
|
||||
func orgIDFromContext(ctx context.Context) (valuer.UUID, error) {
|
||||
claims, err := authtypes.ClaimsFromContext(ctx)
|
||||
if err != nil {
|
||||
return valuer.UUID{}, err
|
||||
}
|
||||
|
||||
return valuer.NewUUID(claims.OrgID)
|
||||
}
|
||||
|
||||
func diffLinks(stored, incoming []string) (attached, detached []string) {
|
||||
storedSet := make(map[string]struct{}, len(stored))
|
||||
for _, id := range stored {
|
||||
storedSet[id] = struct{}{}
|
||||
}
|
||||
|
||||
incomingSet := make(map[string]struct{}, len(incoming))
|
||||
for _, id := range incoming {
|
||||
incomingSet[id] = struct{}{}
|
||||
}
|
||||
|
||||
seen := make(map[string]struct{}, len(incoming))
|
||||
attached = make([]string, 0, len(incoming))
|
||||
for _, id := range incoming {
|
||||
if _, ok := storedSet[id]; ok {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
attached = append(attached, id)
|
||||
}
|
||||
|
||||
clear(seen)
|
||||
detached = make([]string, 0, len(stored))
|
||||
for _, id := range stored {
|
||||
if _, ok := incomingSet[id]; ok {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
detached = append(detached, id)
|
||||
}
|
||||
|
||||
return attached, detached
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
package ruler
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestDiffLinks(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
stored []string
|
||||
incoming []string
|
||||
wantAttached []string
|
||||
wantDetached []string
|
||||
}{
|
||||
{
|
||||
name: "BothEmpty_NothingChanges",
|
||||
wantAttached: []string{},
|
||||
wantDetached: []string{},
|
||||
},
|
||||
{
|
||||
name: "NoStored_EverythingAttaches",
|
||||
incoming: []string{"slack", "pager"},
|
||||
wantAttached: []string{"slack", "pager"},
|
||||
wantDetached: []string{},
|
||||
},
|
||||
{
|
||||
name: "NoIncoming_EverythingDetaches",
|
||||
stored: []string{"slack", "pager"},
|
||||
wantAttached: []string{},
|
||||
wantDetached: []string{"slack", "pager"},
|
||||
},
|
||||
{
|
||||
name: "Unchanged_NothingChanges",
|
||||
stored: []string{"slack", "pager"},
|
||||
incoming: []string{"pager", "slack"},
|
||||
wantAttached: []string{},
|
||||
wantDetached: []string{},
|
||||
},
|
||||
{
|
||||
name: "OneAddedOneRemoved_BothSidesReported",
|
||||
stored: []string{"slack", "pager"},
|
||||
incoming: []string{"slack", "email"},
|
||||
wantAttached: []string{"email"},
|
||||
wantDetached: []string{"pager"},
|
||||
},
|
||||
{
|
||||
name: "DuplicateIncoming_CollapsedOnce",
|
||||
incoming: []string{"slack", "slack"},
|
||||
wantAttached: []string{"slack"},
|
||||
wantDetached: []string{},
|
||||
},
|
||||
{
|
||||
name: "DuplicateStored_CollapsedOnce",
|
||||
stored: []string{"pager", "pager"},
|
||||
wantAttached: []string{},
|
||||
wantDetached: []string{"pager"},
|
||||
},
|
||||
{
|
||||
name: "IncomingOrderPreserved",
|
||||
stored: []string{"keep"},
|
||||
incoming: []string{"zebra", "keep", "apple"},
|
||||
wantAttached: []string{"zebra", "apple"},
|
||||
wantDetached: []string{},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
attached, detached := diffLinks(testCase.stored, testCase.incoming)
|
||||
|
||||
assert.Equal(t, testCase.wantAttached, attached)
|
||||
assert.Equal(t, testCase.wantDetached, detached)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -100,7 +100,6 @@ func NewOpenAPI(ctx context.Context, instrumentation instrumentation.Instrumenta
|
||||
struct{ rulestatehistory.Handler }{},
|
||||
struct{ spanmapper.Handler }{},
|
||||
struct{ alertmanager.Handler }{},
|
||||
struct{ alertmanager.Alertmanager }{},
|
||||
struct{ prometheus.Handler }{},
|
||||
struct{ llmpricingrule.Handler }{},
|
||||
struct{ tracedetail.Handler }{},
|
||||
|
||||
@@ -266,7 +266,7 @@ func NewSQLMigrationProviderFactories(
|
||||
sqlmigration.NewAddMetricsFieldTuplesFactory(sqlstore),
|
||||
sqlmigration.NewAddGCPConnectionMethodFactory(),
|
||||
sqlmigration.NewDeleteOrphanSARolesFactory(),
|
||||
sqlmigration.NewAddRoutePolicyTuplesFactory(sqlstore),
|
||||
sqlmigration.NewAddLLMPricingRuleTuplesFactory(sqlstore),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -331,7 +331,7 @@ func NewQuerierProviderFactories(telemetryStore telemetrystore.TelemetryStore, p
|
||||
)
|
||||
}
|
||||
|
||||
func NewAPIServerProviderFactories(orgGetter organization.Getter, authz authz.AuthZ, modules Modules, handlers Handlers, globalConfig global.Config, gatewayService gateway.Gateway, identNResolver identn.IdentNResolver, sharder sharder.Sharder, auditor auditor.Auditor, web web.Web, alertmanagerService alertmanager.Alertmanager) factory.NamedMap[factory.ProviderFactory[apiserver.APIServer, apiserver.Config]] {
|
||||
func NewAPIServerProviderFactories(orgGetter organization.Getter, authz authz.AuthZ, modules Modules, handlers Handlers, globalConfig global.Config, gatewayService gateway.Gateway, identNResolver identn.IdentNResolver, sharder sharder.Sharder, auditor auditor.Auditor, web web.Web) factory.NamedMap[factory.ProviderFactory[apiserver.APIServer, apiserver.Config]] {
|
||||
return factory.MustNewNamedMap(
|
||||
signozapiserver.NewFactory(
|
||||
orgGetter,
|
||||
@@ -368,7 +368,6 @@ func NewAPIServerProviderFactories(orgGetter organization.Getter, authz authz.Au
|
||||
handlers.RuleStateHistory,
|
||||
handlers.SpanMapperHandler,
|
||||
handlers.AlertmanagerHandler,
|
||||
alertmanagerService,
|
||||
handlers.PrometheusHandler,
|
||||
handlers.LLMPricingRuleHandler,
|
||||
handlers.TraceDetail,
|
||||
|
||||
@@ -106,7 +106,6 @@ func TestNewProviderFactories(t *testing.T) {
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -622,7 +622,7 @@ func New(
|
||||
ctx,
|
||||
providerSettings,
|
||||
config.APIServer,
|
||||
NewAPIServerProviderFactories(orgGetter, authz, modules, handlers, config.Global, gateway, identNResolver, sharder, auditor, web, alertmanager),
|
||||
NewAPIServerProviderFactories(orgGetter, authz, modules, handlers, config.Global, gateway, identNResolver, sharder, auditor, web),
|
||||
"signoz",
|
||||
)
|
||||
if err != nil {
|
||||
|
||||
@@ -16,21 +16,21 @@ import (
|
||||
"github.com/uptrace/bun/migrate"
|
||||
)
|
||||
|
||||
type addRoutePolicyTuples struct {
|
||||
type addLLMPricingRuleTuples struct {
|
||||
sqlstore sqlstore.SQLStore
|
||||
}
|
||||
|
||||
func NewAddRoutePolicyTuplesFactory(sqlstore sqlstore.SQLStore) factory.ProviderFactory[SQLMigration, Config] {
|
||||
return factory.NewProviderFactory(factory.MustNewName("add_route_policy_tuples"), func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {
|
||||
return &addRoutePolicyTuples{sqlstore: sqlstore}, nil
|
||||
func NewAddLLMPricingRuleTuplesFactory(sqlstore sqlstore.SQLStore) factory.ProviderFactory[SQLMigration, Config] {
|
||||
return factory.NewProviderFactory(factory.MustNewName("add_llm_pricing_rule_tuples"), func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {
|
||||
return &addLLMPricingRuleTuples{sqlstore: sqlstore}, nil
|
||||
})
|
||||
}
|
||||
|
||||
func (migration *addRoutePolicyTuples) Register(migrations *migrate.Migrations) error {
|
||||
func (migration *addLLMPricingRuleTuples) Register(migrations *migrate.Migrations) error {
|
||||
return migrations.Register(migration.Up, migration.Down)
|
||||
}
|
||||
|
||||
func (migration *addRoutePolicyTuples) Up(ctx context.Context, db *bun.DB) error {
|
||||
func (migration *addLLMPricingRuleTuples) Up(ctx context.Context, db *bun.DB) error {
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -54,26 +54,15 @@ func (migration *addRoutePolicyTuples) Up(ctx context.Context, db *bun.DB) error
|
||||
|
||||
isPG := migration.sqlstore.BunDB().Dialect().Name() == dialect.PG
|
||||
|
||||
crudVerbs := []string{"create", "read", "update", "delete", "list"}
|
||||
readVerbs := []string{"read", "list"}
|
||||
linkVerbs := []string{"attach", "detach"}
|
||||
|
||||
tuples := make([]migrationTuple, 0, 15)
|
||||
for _, verb := range crudVerbs {
|
||||
tuples = append(tuples, migrationTuple{authtypes.SigNozAdminRoleName, "metaresource", "route-policy", verb})
|
||||
}
|
||||
for _, verb := range readVerbs {
|
||||
tuples = append(tuples,
|
||||
migrationTuple{authtypes.SigNozEditorRoleName, "metaresource", "route-policy", verb},
|
||||
migrationTuple{authtypes.SigNozViewerRoleName, "metaresource", "route-policy", verb},
|
||||
)
|
||||
}
|
||||
for _, verb := range linkVerbs {
|
||||
tuples = append(tuples,
|
||||
migrationTuple{authtypes.SigNozAdminRoleName, "metaresource", "route-policy", verb},
|
||||
migrationTuple{authtypes.SigNozAdminRoleName, "metaresource", "notification-channel", verb},
|
||||
migrationTuple{authtypes.SigNozEditorRoleName, "metaresource", "notification-channel", verb},
|
||||
)
|
||||
tuples := []migrationTuple{
|
||||
{authtypes.SigNozAdminRoleName, "metaresource", "llm-pricing-rule", "read"},
|
||||
{authtypes.SigNozAdminRoleName, "metaresource", "llm-pricing-rule", "update"},
|
||||
{authtypes.SigNozAdminRoleName, "metaresource", "llm-pricing-rule", "delete"},
|
||||
{authtypes.SigNozAdminRoleName, "metaresource", "llm-pricing-rule", "list"},
|
||||
{authtypes.SigNozEditorRoleName, "metaresource", "llm-pricing-rule", "read"},
|
||||
{authtypes.SigNozEditorRoleName, "metaresource", "llm-pricing-rule", "list"},
|
||||
{authtypes.SigNozViewerRoleName, "metaresource", "llm-pricing-rule", "read"},
|
||||
{authtypes.SigNozViewerRoleName, "metaresource", "llm-pricing-rule", "list"},
|
||||
}
|
||||
|
||||
for _, orgID := range orgIDs {
|
||||
@@ -168,6 +157,6 @@ func (migration *addRoutePolicyTuples) Up(ctx context.Context, db *bun.DB) error
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (migration *addRoutePolicyTuples) Down(context.Context, *bun.DB) error {
|
||||
func (migration *addLLMPricingRuleTuples) Down(context.Context, *bun.DB) error {
|
||||
return nil
|
||||
}
|
||||
@@ -150,24 +150,6 @@ func NewConfigFromChannels(globalConfig GlobalConfig, routeConfig RouteConfig, c
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func MapChannelNamesToIDs(channels Channels, names []string) ([]string, error) {
|
||||
idByName := make(map[string]string, len(channels))
|
||||
for _, channel := range channels {
|
||||
idByName[channel.DisplayName] = channel.ID.StringValue()
|
||||
}
|
||||
|
||||
ids := make([]string, 0, len(names))
|
||||
for _, name := range names {
|
||||
id, ok := idByName[name]
|
||||
if !ok {
|
||||
return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "notification channel %q does not exist", name)
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
func NewStatsFromChannels(channels Channels) map[string]any {
|
||||
stats := make(map[string]any)
|
||||
for _, channel := range channels {
|
||||
|
||||
@@ -6,12 +6,9 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/types"
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
"github.com/prometheus/alertmanager/config"
|
||||
"github.com/prometheus/common/model"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestNewConfigFromChannels(t *testing.T) {
|
||||
@@ -299,36 +296,3 @@ func TestNewChannelFromReceiverGoogleChat(t *testing.T) {
|
||||
channel.Data,
|
||||
)
|
||||
}
|
||||
|
||||
func TestMapChannelNamesToIDs(t *testing.T) {
|
||||
slackID := valuer.GenerateUUID()
|
||||
pagerID := valuer.GenerateUUID()
|
||||
channels := Channels{
|
||||
{Identifiable: types.Identifiable{ID: slackID}, DisplayName: "slack"},
|
||||
{Identifiable: types.Identifiable{ID: pagerID}, DisplayName: "pager"},
|
||||
}
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
names []string
|
||||
want []string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "AllKnown_IDsInRequestOrder", names: []string{"pager", "slack"}, want: []string{pagerID.StringValue(), slackID.StringValue()}},
|
||||
{name: "UnknownName_Errors", names: []string{"slack", "missing"}, wantErr: true},
|
||||
{name: "NoNames_Empty", names: nil, want: []string{}},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
got, err := MapChannelNamesToIDs(channels, testCase.names)
|
||||
if testCase.wantErr {
|
||||
require.Error(t, err)
|
||||
return
|
||||
}
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testCase.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,6 +80,7 @@ func (name Kind) Enum() []any {
|
||||
KindLogsField,
|
||||
KindTracesField,
|
||||
KindMetricsField,
|
||||
KindLLMPricingRule,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ var Kinds = []Kind{
|
||||
KindLogsField,
|
||||
KindTracesField,
|
||||
KindMetricsField,
|
||||
KindLLMPricingRule,
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -82,4 +83,5 @@ var (
|
||||
KindLogsField = MustNewKind("logs-field")
|
||||
KindTracesField = MustNewKind("traces-field")
|
||||
KindMetricsField = MustNewKind("metrics-field")
|
||||
KindLLMPricingRule = MustNewKind("llm-pricing-rule")
|
||||
)
|
||||
|
||||
@@ -172,16 +172,12 @@ var ManagedRoleToTransactions = map[string][]Transaction{
|
||||
{Verb: VerbDelete, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindNotificationChannel}, WildCardSelectorString)},
|
||||
{Verb: VerbCreate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindNotificationChannel}, WildCardSelectorString)},
|
||||
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindNotificationChannel}, WildCardSelectorString)},
|
||||
{Verb: VerbAttach, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindNotificationChannel}, WildCardSelectorString)},
|
||||
{Verb: VerbDetach, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindNotificationChannel}, WildCardSelectorString)},
|
||||
// route-policy — admin writes, viewer reads
|
||||
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindRoutePolicy}, WildCardSelectorString)},
|
||||
{Verb: VerbUpdate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindRoutePolicy}, WildCardSelectorString)},
|
||||
{Verb: VerbDelete, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindRoutePolicy}, WildCardSelectorString)},
|
||||
{Verb: VerbCreate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindRoutePolicy}, WildCardSelectorString)},
|
||||
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindRoutePolicy}, WildCardSelectorString)},
|
||||
{Verb: VerbAttach, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindRoutePolicy}, WildCardSelectorString)},
|
||||
{Verb: VerbDetach, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindRoutePolicy}, WildCardSelectorString)},
|
||||
// apdex-setting — admin updates, viewer reads
|
||||
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindApdexSetting}, WildCardSelectorString)},
|
||||
{Verb: VerbUpdate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindApdexSetting}, WildCardSelectorString)},
|
||||
@@ -222,6 +218,11 @@ var ManagedRoleToTransactions = map[string][]Transaction{
|
||||
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindMetricsField}, WildCardSelectorString)},
|
||||
{Verb: VerbUpdate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindMetricsField}, WildCardSelectorString)},
|
||||
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindMetricsField}, WildCardSelectorString)},
|
||||
// llm-pricing-rule — admin writes, viewer reads
|
||||
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindLLMPricingRule}, WildCardSelectorString)},
|
||||
{Verb: VerbUpdate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindLLMPricingRule}, WildCardSelectorString)},
|
||||
{Verb: VerbDelete, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindLLMPricingRule}, WildCardSelectorString)},
|
||||
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindLLMPricingRule}, WildCardSelectorString)},
|
||||
},
|
||||
SigNozEditorRoleName: {
|
||||
// cloud-integration — editor can read accounts
|
||||
@@ -286,8 +287,6 @@ var ManagedRoleToTransactions = map[string][]Transaction{
|
||||
// notification-channel — read only (admin writes)
|
||||
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindNotificationChannel}, WildCardSelectorString)},
|
||||
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindNotificationChannel}, WildCardSelectorString)},
|
||||
{Verb: VerbAttach, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindNotificationChannel}, WildCardSelectorString)},
|
||||
{Verb: VerbDetach, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindNotificationChannel}, WildCardSelectorString)},
|
||||
// route-policy — read only (admin writes)
|
||||
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindRoutePolicy}, WildCardSelectorString)},
|
||||
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindRoutePolicy}, WildCardSelectorString)},
|
||||
@@ -323,6 +322,9 @@ var ManagedRoleToTransactions = map[string][]Transaction{
|
||||
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindMetricsField}, WildCardSelectorString)},
|
||||
{Verb: VerbUpdate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindMetricsField}, WildCardSelectorString)},
|
||||
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindMetricsField}, WildCardSelectorString)},
|
||||
// llm-pricing-rule — read only (admin writes)
|
||||
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindLLMPricingRule}, WildCardSelectorString)},
|
||||
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindLLMPricingRule}, WildCardSelectorString)},
|
||||
},
|
||||
SigNozViewerRoleName: {
|
||||
// cloud-integration — viewer can read accounts
|
||||
@@ -387,6 +389,9 @@ var ManagedRoleToTransactions = map[string][]Transaction{
|
||||
// metrics-field — viewer reads
|
||||
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindMetricsField}, WildCardSelectorString)},
|
||||
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindMetricsField}, WildCardSelectorString)},
|
||||
// llm-pricing-rule — read only
|
||||
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindLLMPricingRule}, WildCardSelectorString)},
|
||||
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindLLMPricingRule}, WildCardSelectorString)},
|
||||
},
|
||||
SigNozAnonymousRoleName: {
|
||||
// public-dashboard — anonymous read
|
||||
|
||||
@@ -40,6 +40,7 @@ var Resources = []Resource{
|
||||
ResourceMetaResourceLogsField,
|
||||
ResourceMetaResourceTracesField,
|
||||
ResourceMetaResourceMetricsField,
|
||||
ResourceMetaResourceLLMPricingRule,
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -48,7 +49,7 @@ var (
|
||||
ResourceRole = NewResourceRole()
|
||||
ResourceServiceAccount = NewResourceServiceAccount()
|
||||
ResourceUser = NewResourceUser()
|
||||
ResourceMetaResourceNotificationChannel = NewResourceMetaResource(KindNotificationChannel)
|
||||
ResourceMetaResourceNotificationChannel = NewResourceMetaResource(KindNotificationChannel, VerbCreate, VerbList, VerbRead, VerbUpdate, VerbDelete)
|
||||
ResourceMetaResourceRoutePolicy = NewResourceMetaResource(KindRoutePolicy)
|
||||
ResourceMetaResourceApdexSetting = NewResourceMetaResource(KindApdexSetting)
|
||||
ResourceMetaResourceAuthDomain = NewResourceMetaResource(KindAuthDomain)
|
||||
@@ -82,4 +83,5 @@ var (
|
||||
ResourceMetaResourceLogsField = NewResourceMetaResource(KindLogsField)
|
||||
ResourceMetaResourceTracesField = NewResourceMetaResource(KindTracesField)
|
||||
ResourceMetaResourceMetricsField = NewResourceMetaResource(KindMetricsField, VerbList, VerbRead, VerbUpdate)
|
||||
ResourceMetaResourceLLMPricingRule = NewResourceMetaResource(KindLLMPricingRule, VerbList, VerbRead, VerbUpdate, VerbDelete)
|
||||
)
|
||||
|
||||
65
pkg/types/llmpricingruletypes/resource.go
Normal file
65
pkg/types/llmpricingruletypes/resource.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package llmpricingruletypes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"slices"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/types/coretypes"
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
)
|
||||
|
||||
// UpdatableRulesResources resolves the pricing rules an upsert body writes to.
|
||||
//
|
||||
// A rule with isOverride and an id is an edit, checked by that id. Everything
|
||||
// else resolves to the wildcard: isOverride without an id is a create, sourceId
|
||||
// without isOverride is a sync row, and an empty list has nothing to check.
|
||||
func UpdatableRulesResources(ec coretypes.ExtractorContext) ([]coretypes.ResourceWithID, error) {
|
||||
// encoding/json with the handler's tags, so duplicate or case-variant id
|
||||
// keys resolve to the id that is actually written.
|
||||
var body struct {
|
||||
Rules []*struct {
|
||||
// Normalised through valuer so an uppercase id still matches the
|
||||
// lowercase selector regex of the metaresource type.
|
||||
ID *valuer.UUID `json:"id"`
|
||||
IsOverride *bool `json:"isOverride"`
|
||||
} `json:"rules"`
|
||||
}
|
||||
if err := json.Unmarshal(ec.RequestBody, &body); err != nil {
|
||||
return nil, errors.Wrapf(err, errors.TypeInvalidInput, ErrCodePricingRuleInvalidInput, "invalid pricing rules body")
|
||||
}
|
||||
|
||||
ids := make([]string, 0, len(body.Rules))
|
||||
wildcard := len(body.Rules) == 0
|
||||
for _, rule := range body.Rules {
|
||||
if rule == nil || rule.ID == nil || rule.IsOverride == nil {
|
||||
wildcard = true
|
||||
continue
|
||||
}
|
||||
|
||||
if !slices.Contains(ids, rule.ID.StringValue()) {
|
||||
ids = append(ids, rule.ID.StringValue())
|
||||
}
|
||||
}
|
||||
if wildcard {
|
||||
ids = append(ids, coretypes.WildCardSelectorString)
|
||||
}
|
||||
|
||||
resources := make([]coretypes.ResourceWithID, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
resources = append(resources, coretypes.ResourceWithID{Resource: coretypes.ResourceMetaResourceLLMPricingRule, ID: id})
|
||||
}
|
||||
|
||||
return resources, nil
|
||||
}
|
||||
|
||||
// RuleSelector exists because IDSelector would turn the wildcard entry into
|
||||
// the wildcard twice; an id still resolves to the id plus the wildcard.
|
||||
func RuleSelector(ctx context.Context, resource coretypes.Resource, id string, orgID valuer.UUID) ([]coretypes.Selector, error) {
|
||||
if id == coretypes.WildCardSelectorString {
|
||||
return coretypes.WildcardSelector(ctx, resource, id, orgID)
|
||||
}
|
||||
|
||||
return coretypes.IDSelector(ctx, resource, id, orgID)
|
||||
}
|
||||
116
pkg/types/llmpricingruletypes/resource_test.go
Normal file
116
pkg/types/llmpricingruletypes/resource_test.go
Normal file
@@ -0,0 +1,116 @@
|
||||
package llmpricingruletypes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/types/coretypes"
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
)
|
||||
|
||||
func TestUpdatableRulesResources(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
body string
|
||||
want []string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "EmptyRules_Wildcard",
|
||||
body: `{"rules":[]}`,
|
||||
want: []string{"*"},
|
||||
},
|
||||
{
|
||||
name: "Edit_ID",
|
||||
body: `{"rules":[{"id":"0b6d1a4e-5c1f-4d2a-9e3b-1f2a3b4c5d6e","isOverride":true}]}`,
|
||||
want: []string{"0b6d1a4e-5c1f-4d2a-9e3b-1f2a3b4c5d6e"},
|
||||
},
|
||||
{
|
||||
name: "Create_Wildcard",
|
||||
body: `{"rules":[{"modelName":"gpt","isOverride":true}]}`,
|
||||
want: []string{"*"},
|
||||
},
|
||||
{
|
||||
name: "SyncRow_Wildcard",
|
||||
body: `{"rules":[{"sourceId":"4e9a0b12-3c4d-4e5f-8a6b-7c8d9e0f1a2b"}]}`,
|
||||
want: []string{"*"},
|
||||
},
|
||||
{
|
||||
name: "Mixed_DedupedIDsThenWildcardOnce",
|
||||
body: `{"rules":[{"id":"6abc2d34-5e6f-4a7b-8c8d-9e0f1a2b3c4d","isOverride":true},{"modelName":"new","isOverride":true},{"id":"6abc2d34-5e6f-4a7b-8c8d-9e0f1a2b3c4d","isOverride":false},{"sourceId":"7bcd3e45-6f7a-4b8c-9d9e-0f1a2b3c4d5e"}]}`,
|
||||
want: []string{"6abc2d34-5e6f-4a7b-8c8d-9e0f1a2b3c4d", "*"},
|
||||
},
|
||||
{
|
||||
name: "UppercaseID_Lowercased",
|
||||
body: `{"rules":[{"id":"8CDE4F56-7A8B-4C9D-8E0F-1A2B3C4D5E6F","isOverride":true}]}`,
|
||||
want: []string{"8cde4f56-7a8b-4c9d-8e0f-1a2b3c4d5e6f"},
|
||||
},
|
||||
{
|
||||
name: "DuplicateIDKey_LastWins",
|
||||
body: `{"rules":[{"id":"0b6d1a4e-5c1f-4d2a-9e3b-1f2a3b4c5d6e","id":"6abc2d34-5e6f-4a7b-8c8d-9e0f1a2b3c4d","isOverride":true}]}`,
|
||||
want: []string{"6abc2d34-5e6f-4a7b-8c8d-9e0f1a2b3c4d"},
|
||||
},
|
||||
{
|
||||
name: "CaseVariantIDKey_LastWins",
|
||||
body: `{"rules":[{"id":"0b6d1a4e-5c1f-4d2a-9e3b-1f2a3b4c5d6e","ID":"6abc2d34-5e6f-4a7b-8c8d-9e0f1a2b3c4d","isOverride":true}]}`,
|
||||
want: []string{"6abc2d34-5e6f-4a7b-8c8d-9e0f1a2b3c4d"},
|
||||
},
|
||||
{
|
||||
name: "InvalidID_Rejected",
|
||||
body: `{"rules":[{"id":"not-a-uuid","isOverride":true}]}`,
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
resources, err := UpdatableRulesResources(coretypes.ExtractorContext{RequestBody: []byte(testCase.body)})
|
||||
if testCase.wantErr {
|
||||
require.Error(t, err)
|
||||
return
|
||||
}
|
||||
|
||||
require.NoError(t, err)
|
||||
got := make([]string, 0, len(resources))
|
||||
for _, resource := range resources {
|
||||
got = append(got, resource.ID)
|
||||
}
|
||||
assert.Equal(t, testCase.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuleSelector(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
id string
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "Wildcard_WildcardOnly",
|
||||
id: "*",
|
||||
want: []string{"*"},
|
||||
},
|
||||
{
|
||||
name: "ID_IDThenWildcard",
|
||||
id: "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
|
||||
want: []string{"a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "*"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
selectors, err := RuleSelector(context.Background(), coretypes.ResourceMetaResourceLLMPricingRule, testCase.id, valuer.GenerateUUID())
|
||||
require.NoError(t, err)
|
||||
|
||||
got := make([]string, 0, len(selectors))
|
||||
for _, selector := range selectors {
|
||||
got = append(got, selector.String())
|
||||
}
|
||||
assert.Equal(t, testCase.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -664,12 +664,6 @@ func (r *QueryRangeRequest) UnmarshalJSON(data []byte) error {
|
||||
// Copy the decoded values back to the original struct
|
||||
*r = QueryRangeRequest(temp)
|
||||
|
||||
// Coerce the window to epoch milliseconds up front so every downstream
|
||||
// consumer (TimeRange, narrowWindowByTraceID, step interval, etc.) can
|
||||
// safely assume ms regardless of the resolution the caller sent.
|
||||
r.Start = ToMilliSecs(r.Start)
|
||||
r.End = ToMilliSecs(r.End)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
package querybuildertypesv5
|
||||
|
||||
import "math"
|
||||
|
||||
// ToMilliSecs takes an epoch whose resolution is inferred from its magnitude
|
||||
// (s/ms/µs/ns) and returns it in milliseconds. A millisecond epoch for the
|
||||
// current era has 13 digits (e.g. ~1.7e12 in 2026), so the value is scaled so
|
||||
// its digit-width matches: smaller values (seconds) are scaled up, larger ones
|
||||
// (micro/nanoseconds) are scaled down. Zero is returned unchanged.
|
||||
func ToMilliSecs(epoch uint64) uint64 {
|
||||
if epoch == 0 {
|
||||
return 0
|
||||
}
|
||||
temp := epoch
|
||||
count := 0
|
||||
for epoch != 0 {
|
||||
epoch /= 10
|
||||
count++
|
||||
}
|
||||
const msDigits = 13
|
||||
if count < msDigits {
|
||||
return temp * uint64(math.Pow(10, float64(msDigits-count)))
|
||||
}
|
||||
return temp / uint64(math.Pow(10, float64(count-msDigits)))
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package querybuildertypesv5
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestToMilliSecs(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
epoch uint64
|
||||
expected uint64
|
||||
}{
|
||||
{
|
||||
name: "SecondsEpoch_TenDigits_ScaledUp",
|
||||
epoch: 1672531200, // seconds, 2023-01-01 00:00:00 UTC
|
||||
expected: 1672531200000, // * 10^3
|
||||
},
|
||||
{
|
||||
name: "MilliSecondsEpoch_ThirteenDigits_Unchanged",
|
||||
epoch: 1672531200000,
|
||||
expected: 1672531200000, // unchanged
|
||||
},
|
||||
{
|
||||
name: "MicroSecondsEpoch_SixteenDigits_ScaledDown",
|
||||
epoch: 1672531200000000, // microseconds
|
||||
expected: 1672531200000, // / 10^3
|
||||
},
|
||||
{
|
||||
name: "NanoSecondsEpoch_NineteenDigits_ScaledDown",
|
||||
epoch: 1672531200000000000, // nanoseconds
|
||||
expected: 1672531200000, // / 10^6
|
||||
},
|
||||
{
|
||||
name: "Zero_Unchanged",
|
||||
epoch: 0,
|
||||
expected: 0,
|
||||
},
|
||||
{
|
||||
name: "SecondsEpoch_RecentTimestamp_ScaledUp",
|
||||
epoch: 1716638400, // 2024-05-25 12:00:00 UTC
|
||||
expected: 1716638400000,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
assert.Equal(t, testCase.expected, ToMilliSecs(testCase.epoch))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -5,16 +5,12 @@ import (
|
||||
"math"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/types/metrictypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
|
||||
)
|
||||
|
||||
// maxEndTimeAhead tolerates client clock skew; anything further ahead is a malformed timestamp.
|
||||
const maxEndTimeAhead = 24 * time.Hour
|
||||
|
||||
// getQueryIdentifier returns a friendly identifier for a query based on its type and name/content.
|
||||
func getQueryIdentifier(envelope QueryEnvelope, index int) string {
|
||||
name := envelope.GetQueryName()
|
||||
@@ -578,8 +574,12 @@ func (q *QueryBuilderQuery[T]) validateOrderByForAggregation() error {
|
||||
|
||||
// Validate validates the entire query range request.
|
||||
func (r *QueryRangeRequest) Validate(opts ...ValidationOption) error {
|
||||
if err := r.validateTimeRange(); err != nil {
|
||||
return err
|
||||
// Validate time range
|
||||
if r.RequestType != RequestTypeRawStream && r.Start >= r.End {
|
||||
return errors.NewInvalidInputf(
|
||||
errors.CodeInvalidInput,
|
||||
"start time must be before end time",
|
||||
)
|
||||
}
|
||||
|
||||
// Validate request type
|
||||
@@ -631,8 +631,8 @@ func (r *QueryRangeRequest) Validate(opts ...ValidationOption) error {
|
||||
// this so per-query errors can be attributed individually via QueryEnvelope.Validate
|
||||
// instead of failing fast like Validate does.
|
||||
func (r *QueryRangeRequest) ValidateRequestScope() ([]ValidationOption, error) {
|
||||
if err := r.validateTimeRange(); err != nil {
|
||||
return nil, err
|
||||
if r.RequestType != RequestTypeRawStream && r.Start >= r.End {
|
||||
return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "start time must be before end time")
|
||||
}
|
||||
|
||||
var opts []ValidationOption
|
||||
@@ -699,22 +699,6 @@ func (e QueryEnvelope) Validate(opts ...ValidationOption) error {
|
||||
return validateQueryEnvelope(e, opts...)
|
||||
}
|
||||
|
||||
func (r *QueryRangeRequest) validateTimeRange() error {
|
||||
if r.RequestType == RequestTypeRawStream {
|
||||
return nil
|
||||
}
|
||||
if r.Start == 0 {
|
||||
return errors.NewInvalidInputf(errors.CodeInvalidInput, "start time is required")
|
||||
}
|
||||
if r.Start >= r.End {
|
||||
return errors.NewInvalidInputf(errors.CodeInvalidInput, "start time must be before end time")
|
||||
}
|
||||
if r.End > uint64(time.Now().Add(maxEndTimeAhead).UnixMilli()) {
|
||||
return errors.NewInvalidInputf(errors.CodeInvalidInput, "end time %s is too far in the future", time.UnixMilli(int64(r.End)).UTC().Format(time.RFC3339))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateAllQueriesNotDisabled validates that at least one query in the composite query is enabled.
|
||||
func (r *QueryRangeRequest) validateAllQueriesNotDisabled() error {
|
||||
for _, envelope := range r.CompositeQuery.Queries {
|
||||
|
||||
@@ -65,7 +65,7 @@ export const ThresholdMatchType = {
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* `AlertListTabs` (`frontend/src/pages/AlertList/types.ts`). The values are
|
||||
* `AlertListTabs` (`frontend/src/pages/AlertList/types.ts:7-9`). The values are
|
||||
* space-less — the tab *labels* read "Triggered Alerts" but the `tab` URL param
|
||||
* is `TriggeredAlerts`, and asserting the label form silently fails.
|
||||
*/
|
||||
@@ -73,9 +73,6 @@ export const AlertListTab = {
|
||||
TRIGGERED_ALERTS: 'TriggeredAlerts',
|
||||
ALERT_RULES: 'AlertRules',
|
||||
CONFIGURATION: 'Configuration',
|
||||
CHANNELS: 'Channels',
|
||||
ROUTING_POLICIES: 'RoutingPolicies',
|
||||
PLANNED_DOWNTIME: 'PlannedDowntime',
|
||||
} as const;
|
||||
|
||||
/**
|
||||
|
||||
@@ -381,7 +381,6 @@ test.describe('Alert create — v2 builder', () => {
|
||||
const url = new URL(page.url());
|
||||
expect(url.pathname).toBe('/alerts');
|
||||
expect(url.searchParams.get('tab')).toBe('Configuration');
|
||||
expect(url.searchParams.get('subTab')).toBe('routing-policies');
|
||||
});
|
||||
|
||||
test('CV2-16 the group-by select is disabled until the query groups by something', async ({
|
||||
|
||||
@@ -2,7 +2,7 @@ import { expect, test } from '../../fixtures/alerts/alert-rules';
|
||||
import { ALERTS_LIST_PATH } from '../../helpers/alerts/constants';
|
||||
import { watchConsole } from '../../helpers/common';
|
||||
|
||||
// TC-* — the Alerts page shell: the top-level tabs, how they map to
|
||||
// TC-* — the Alerts page shell: the four top-level tabs, how they map to
|
||||
// `?tab=`, and a navigation smoke check per tab. Tab *internals* (channel CRUD,
|
||||
// planned downtime, routing policies) are deliberately out of scope — each
|
||||
// deserves its own spec file.
|
||||
@@ -10,11 +10,12 @@ import { watchConsole } from '../../helpers/common';
|
||||
const TAB_NAMES = {
|
||||
triggered: /triggered alerts/i,
|
||||
rules: /alert rules/i,
|
||||
channels: /notification channels/i,
|
||||
configuration: /configuration/i,
|
||||
};
|
||||
|
||||
test.describe('Alerts page shell', () => {
|
||||
test('TC-01 all top-level tabs render', async ({ authedPage: page }) => {
|
||||
test('TC-01 all four top-level tabs render', async ({ authedPage: page }) => {
|
||||
await page.goto(ALERTS_LIST_PATH);
|
||||
|
||||
for (const name of Object.values(TAB_NAMES)) {
|
||||
@@ -42,53 +43,43 @@ test.describe('Alerts page shell', () => {
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test('TC-03 tab switch writes ?tab=', async ({ authedPage: page }) => {
|
||||
test('TC-03 tab switch writes ?tab= and clears subTab', async ({
|
||||
authedPage: page,
|
||||
}) => {
|
||||
await page.goto(ALERTS_LIST_PATH);
|
||||
|
||||
await page.getByRole('tab', { name: TAB_NAMES.triggered }).click();
|
||||
await expect(page).toHaveURL(/[?&]tab=TriggeredAlerts/);
|
||||
|
||||
await page.getByRole('tab', { name: TAB_NAMES.channels }).click();
|
||||
await expect(page).toHaveURL(/[?&]tab=Channels/);
|
||||
|
||||
// Entering Configuration adds the default subTab...
|
||||
await page.getByRole('tab', { name: TAB_NAMES.configuration }).click();
|
||||
await expect(page).toHaveURL(/[?&]tab=Configuration/);
|
||||
await expect(page).toHaveURL(/[?&]subTab=channels/);
|
||||
await expect(page).toHaveURL(/[?&]subTab=planned-downtime/);
|
||||
|
||||
// ...and leaving it drops subTab entirely (onChange rebuilds the search
|
||||
// from scratch rather than mutating the existing params).
|
||||
await page.getByRole('tab', { name: TAB_NAMES.rules }).click();
|
||||
await expect(page).toHaveURL(/[?&]tab=AlertRules/);
|
||||
await expect(page).not.toHaveURL(/subTab=/);
|
||||
});
|
||||
|
||||
test('TC-04 Configuration sub-tab deep-links and sidebar navigation', async ({
|
||||
authedPage: page,
|
||||
}) => {
|
||||
test('TC-04 Configuration deep-link', async ({ authedPage: page }) => {
|
||||
// Deep-linking without subTab: the inner Tabs falls back to
|
||||
// planned-downtime for its activeKey without writing it to the URL, so
|
||||
// assert the rendered tab, not the param.
|
||||
await page.goto(`${ALERTS_LIST_PATH}?tab=Configuration`);
|
||||
await expect(
|
||||
page.getByRole('tab', { name: /planned downtime/i }),
|
||||
).toHaveAttribute('aria-selected', 'true');
|
||||
|
||||
await page.goto(
|
||||
`${ALERTS_LIST_PATH}?tab=Configuration&subTab=routing-policies`,
|
||||
);
|
||||
await expect(
|
||||
page.getByRole('tab', { name: TAB_NAMES.configuration }),
|
||||
).toHaveAttribute('aria-selected', 'true');
|
||||
await expect(page.getByTestId('alert-configuration-sidebar')).toBeVisible();
|
||||
await expect(
|
||||
page.getByTestId('configuration-sidebar-routing-policies'),
|
||||
).toBeVisible();
|
||||
|
||||
await page.goto(
|
||||
`${ALERTS_LIST_PATH}?tab=Configuration&subTab=planned-downtime`,
|
||||
);
|
||||
await expect(
|
||||
page.getByRole('tab', { name: TAB_NAMES.configuration }),
|
||||
).toHaveAttribute('aria-selected', 'true');
|
||||
await expect(
|
||||
page.getByTestId('configuration-sidebar-planned-downtime'),
|
||||
).toBeVisible();
|
||||
|
||||
// Backwards-compatible legacy deep links
|
||||
await page.goto(`${ALERTS_LIST_PATH}?tab=RoutingPolicies`);
|
||||
await expect(
|
||||
page.getByRole('tab', { name: TAB_NAMES.configuration }),
|
||||
).toHaveAttribute('aria-selected', 'true');
|
||||
|
||||
await page.goto(`${ALERTS_LIST_PATH}?tab=PlannedDowntime`);
|
||||
await expect(
|
||||
page.getByRole('tab', { name: TAB_NAMES.configuration }),
|
||||
page.getByRole('tab', { name: /routing policies/i }),
|
||||
).toHaveAttribute('aria-selected', 'true');
|
||||
});
|
||||
|
||||
@@ -111,16 +102,13 @@ test.describe('Alerts page shell', () => {
|
||||
expect(watch.failedResponses).toEqual([]);
|
||||
});
|
||||
|
||||
test('TC-06 Notification Channels smoke under Configuration', async ({
|
||||
test('TC-06 Notification Channels tab smoke', async ({
|
||||
authedPage: page,
|
||||
alertChannel,
|
||||
}) => {
|
||||
// The worker's channel gives this tab a row to render.
|
||||
await page.goto(`${ALERTS_LIST_PATH}?tab=Configuration&subTab=channels`);
|
||||
await page.goto(`${ALERTS_LIST_PATH}?tab=Channels`);
|
||||
|
||||
await expect(
|
||||
page.getByTestId('configuration-sidebar-channels'),
|
||||
).toBeVisible();
|
||||
await expect(page.getByText(alertChannel.name)).toBeVisible();
|
||||
await expect(
|
||||
page.getByRole('button', { name: /new channel/i }),
|
||||
@@ -128,17 +116,16 @@ test.describe('Alerts page shell', () => {
|
||||
});
|
||||
|
||||
test('TC-07 tab state survives reload', async ({ authedPage: page }) => {
|
||||
await page.goto(`${ALERTS_LIST_PATH}?tab=Configuration&subTab=channels`);
|
||||
await page.goto(`${ALERTS_LIST_PATH}?tab=Channels`);
|
||||
await expect(
|
||||
page.getByRole('tab', { name: TAB_NAMES.configuration }),
|
||||
page.getByRole('tab', { name: TAB_NAMES.channels }),
|
||||
).toHaveAttribute('aria-selected', 'true');
|
||||
|
||||
await page.reload();
|
||||
|
||||
await expect(page).toHaveURL(/[?&]tab=Configuration/);
|
||||
await expect(page).toHaveURL(/[?&]subTab=channels/);
|
||||
await expect(page).toHaveURL(/[?&]tab=Channels/);
|
||||
await expect(
|
||||
page.getByRole('tab', { name: TAB_NAMES.configuration }),
|
||||
page.getByRole('tab', { name: TAB_NAMES.channels }),
|
||||
).toHaveAttribute('aria-selected', 'true');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -256,9 +256,7 @@
|
||||
"read",
|
||||
"update",
|
||||
"delete",
|
||||
"list",
|
||||
"attach",
|
||||
"detach"
|
||||
"list"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -269,9 +267,7 @@
|
||||
"read",
|
||||
"update",
|
||||
"delete",
|
||||
"list",
|
||||
"attach",
|
||||
"detach"
|
||||
"list"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -301,6 +297,16 @@
|
||||
"list"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "metaresource",
|
||||
"kind": "llm-pricing-rule",
|
||||
"verbs": [
|
||||
"read",
|
||||
"update",
|
||||
"delete",
|
||||
"list"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "metaresource",
|
||||
"kind": "ttl-setting",
|
||||
@@ -496,9 +502,7 @@
|
||||
"kind": "notification-channel",
|
||||
"verbs": [
|
||||
"read",
|
||||
"list",
|
||||
"attach",
|
||||
"detach"
|
||||
"list"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -534,6 +538,14 @@
|
||||
"list"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "metaresource",
|
||||
"kind": "llm-pricing-rule",
|
||||
"verbs": [
|
||||
"read",
|
||||
"list"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "metaresource",
|
||||
"kind": "ttl-setting",
|
||||
@@ -713,6 +725,14 @@
|
||||
"list"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "metaresource",
|
||||
"kind": "llm-pricing-rule",
|
||||
"verbs": [
|
||||
"read",
|
||||
"list"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "metaresource",
|
||||
"kind": "ttl-setting",
|
||||
|
||||
267
tests/integration/tests/llmpricingrules/02_authz.py
Normal file
267
tests/integration/tests/llmpricingrules/02_authz.py
Normal file
@@ -0,0 +1,267 @@
|
||||
from collections.abc import Callable
|
||||
from http import HTTPStatus
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
from wiremock.resources.mappings import Mapping
|
||||
|
||||
from fixtures import types
|
||||
from fixtures.auth import (
|
||||
USER_ADMIN_EMAIL,
|
||||
USER_ADMIN_PASSWORD,
|
||||
add_license,
|
||||
change_user_role,
|
||||
create_active_user,
|
||||
)
|
||||
from fixtures.llmpricingrules import (
|
||||
LLM_PRICING_RULES_URL,
|
||||
delete_all_llm_pricing_rules,
|
||||
list_llm_pricing_rules,
|
||||
upsert_llm_pricing_rules,
|
||||
)
|
||||
from fixtures.role import find_role_by_name, transaction_group
|
||||
|
||||
user_password = "password123Z$"
|
||||
editor_email = "llm-pricing-editor@integration.test"
|
||||
viewer_email = "llm-pricing-viewer@integration.test"
|
||||
updater_role = "llm-pricing-updater"
|
||||
updater_email = "llm-pricing-updater@integration.test"
|
||||
scoped_role = "llm-pricing-scoped"
|
||||
scoped_email = "llm-pricing-scoped@integration.test"
|
||||
|
||||
PROBE_RULE = {
|
||||
"modelName": "authz-probe",
|
||||
"provider": "OpenAI",
|
||||
"modelPattern": ["authz-probe*"],
|
||||
"unit": "per_million_tokens",
|
||||
"pricing": {"input": 1, "output": 2},
|
||||
"isOverride": True,
|
||||
"enabled": True,
|
||||
}
|
||||
|
||||
OTHER_RULE = {
|
||||
"modelName": "authz-probe-other",
|
||||
"provider": "Anthropic",
|
||||
"modelPattern": ["authz-probe-other*"],
|
||||
"unit": "per_million_tokens",
|
||||
"pricing": {"input": 3, "output": 4},
|
||||
"isOverride": True,
|
||||
"enabled": True,
|
||||
}
|
||||
|
||||
|
||||
def test_setup(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: types.Operation, # pylint: disable=unused-argument
|
||||
make_http_mocks: Callable[[types.TestContainerDocker, list[Mapping]], None],
|
||||
get_token: Callable[[str, str], str],
|
||||
create_role: Callable[..., str],
|
||||
) -> None:
|
||||
add_license(signoz, make_http_mocks, get_token)
|
||||
|
||||
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
delete_all_llm_pricing_rules(signoz, admin_token)
|
||||
assert upsert_llm_pricing_rules(signoz, admin_token, [PROBE_RULE, OTHER_RULE]).status_code == HTTPStatus.NO_CONTENT
|
||||
probe_id = next(r["id"] for r in list_llm_pricing_rules(signoz, admin_token) if r["modelName"] == PROBE_RULE["modelName"])
|
||||
|
||||
create_active_user(signoz, admin_token, email=editor_email, role="signoz-editor", password=user_password)
|
||||
create_active_user(signoz, admin_token, email=viewer_email, role="signoz-viewer", password=user_password)
|
||||
|
||||
create_role(admin_token, updater_role, [transaction_group("update", "metaresource", "llm-pricing-rule", ["*"])])
|
||||
updater = create_active_user(signoz, admin_token, email=updater_email, role="signoz-viewer", password=user_password)
|
||||
change_user_role(signoz, admin_token, updater, "signoz-viewer", updater_role)
|
||||
|
||||
create_role(
|
||||
admin_token,
|
||||
scoped_role,
|
||||
[
|
||||
transaction_group("read", "metaresource", "llm-pricing-rule", [probe_id]),
|
||||
transaction_group("update", "metaresource", "llm-pricing-rule", [probe_id]),
|
||||
transaction_group("delete", "metaresource", "llm-pricing-rule", [probe_id]),
|
||||
],
|
||||
)
|
||||
scoped = create_active_user(signoz, admin_token, email=scoped_email, role="signoz-viewer", password=user_password)
|
||||
change_user_role(signoz, admin_token, scoped, "signoz-viewer", scoped_role)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"path",
|
||||
[LLM_PRICING_RULES_URL, f"{LLM_PRICING_RULES_URL}/unmapped_models"],
|
||||
ids=["list", "unmapped_models"],
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
("email", "expected"),
|
||||
[
|
||||
(USER_ADMIN_EMAIL, HTTPStatus.OK),
|
||||
(editor_email, HTTPStatus.OK),
|
||||
(viewer_email, HTTPStatus.OK),
|
||||
(updater_email, HTTPStatus.FORBIDDEN),
|
||||
(scoped_email, HTTPStatus.FORBIDDEN),
|
||||
],
|
||||
ids=["admin", "editor", "viewer", "updater", "scoped"],
|
||||
)
|
||||
def test_reads_need_list_grant(
|
||||
signoz: types.SigNoz,
|
||||
get_token: Callable[[str, str], str],
|
||||
path: str,
|
||||
email: str,
|
||||
expected: HTTPStatus,
|
||||
) -> None:
|
||||
token = get_token(email, USER_ADMIN_PASSWORD if email == USER_ADMIN_EMAIL else user_password)
|
||||
|
||||
response = requests.get(
|
||||
signoz.self.host_configs["8080"].get(path),
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=10,
|
||||
)
|
||||
assert response.status_code == expected, response.text
|
||||
if expected == HTTPStatus.FORBIDDEN:
|
||||
assert "llm-pricing-rule:list" in response.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("email", "model_name", "expected"),
|
||||
[
|
||||
(USER_ADMIN_EMAIL, PROBE_RULE["modelName"], HTTPStatus.OK),
|
||||
(editor_email, PROBE_RULE["modelName"], HTTPStatus.OK),
|
||||
(viewer_email, PROBE_RULE["modelName"], HTTPStatus.OK),
|
||||
(updater_email, PROBE_RULE["modelName"], HTTPStatus.FORBIDDEN),
|
||||
(scoped_email, PROBE_RULE["modelName"], HTTPStatus.OK),
|
||||
(scoped_email, OTHER_RULE["modelName"], HTTPStatus.FORBIDDEN),
|
||||
],
|
||||
ids=["admin", "editor", "viewer", "updater", "scoped_granted", "scoped_other"],
|
||||
)
|
||||
def test_get_needs_read_grant(
|
||||
signoz: types.SigNoz,
|
||||
get_token: Callable[[str, str], str],
|
||||
email: str,
|
||||
model_name: str,
|
||||
expected: HTTPStatus,
|
||||
) -> None:
|
||||
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
rule_id = next(r["id"] for r in list_llm_pricing_rules(signoz, admin_token) if r["modelName"] == model_name)
|
||||
token = get_token(email, USER_ADMIN_PASSWORD if email == USER_ADMIN_EMAIL else user_password)
|
||||
|
||||
response = requests.get(
|
||||
signoz.self.host_configs["8080"].get(f"{LLM_PRICING_RULES_URL}/{rule_id}"),
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=10,
|
||||
)
|
||||
assert response.status_code == expected, response.text
|
||||
if expected == HTTPStatus.FORBIDDEN:
|
||||
assert "llm-pricing-rule:read" in response.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("email", "expected"),
|
||||
[
|
||||
(editor_email, HTTPStatus.FORBIDDEN),
|
||||
(viewer_email, HTTPStatus.FORBIDDEN),
|
||||
(scoped_email, HTTPStatus.NO_CONTENT),
|
||||
(updater_email, HTTPStatus.NO_CONTENT),
|
||||
(USER_ADMIN_EMAIL, HTTPStatus.NO_CONTENT),
|
||||
],
|
||||
ids=["editor", "viewer", "scoped", "updater", "admin"],
|
||||
)
|
||||
def test_upsert_needs_update_grant(
|
||||
signoz: types.SigNoz,
|
||||
get_token: Callable[[str, str], str],
|
||||
email: str,
|
||||
expected: HTTPStatus,
|
||||
) -> None:
|
||||
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
rule_id = next(r["id"] for r in list_llm_pricing_rules(signoz, admin_token) if r["modelName"] == PROBE_RULE["modelName"])
|
||||
token = get_token(email, USER_ADMIN_PASSWORD if email == USER_ADMIN_EMAIL else user_password)
|
||||
|
||||
response = upsert_llm_pricing_rules(signoz, token, [{**PROBE_RULE, "id": rule_id}])
|
||||
assert response.status_code == expected, response.text
|
||||
if expected == HTTPStatus.FORBIDDEN:
|
||||
assert "llm-pricing-rule:update" in response.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"shape",
|
||||
["other_rule", "create", "sync_row", "own_and_other"],
|
||||
ids=["other_rule", "create", "sync_row", "own_and_other"],
|
||||
)
|
||||
def test_upsert_scoped_to_granted_rule(
|
||||
signoz: types.SigNoz,
|
||||
get_token: Callable[[str, str], str],
|
||||
shape: str,
|
||||
) -> None:
|
||||
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
rules = {r["modelName"]: r for r in list_llm_pricing_rules(signoz, admin_token)}
|
||||
own = {**PROBE_RULE, "id": rules[PROBE_RULE["modelName"]]["id"]}
|
||||
other = {**OTHER_RULE, "id": rules[OTHER_RULE["modelName"]]["id"]}
|
||||
sync_row = {**{k: v for k, v in PROBE_RULE.items() if k != "isOverride"}, "sourceId": "11111111-1111-4111-8111-111111111199"}
|
||||
bodies = {"other_rule": [other], "create": [PROBE_RULE], "sync_row": [sync_row], "own_and_other": [own, other]}
|
||||
|
||||
response = upsert_llm_pricing_rules(signoz, get_token(scoped_email, user_password), bodies[shape])
|
||||
assert response.status_code == HTTPStatus.FORBIDDEN, response.text
|
||||
assert "llm-pricing-rule:update" in response.text
|
||||
|
||||
|
||||
def test_revoke_update_grant(
|
||||
signoz: types.SigNoz,
|
||||
get_token: Callable[[str, str], str],
|
||||
) -> None:
|
||||
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
rule_id = next(r["id"] for r in list_llm_pricing_rules(signoz, admin_token) if r["modelName"] == PROBE_RULE["modelName"])
|
||||
|
||||
response = requests.put(
|
||||
signoz.self.host_configs["8080"].get(f"/api/v1/roles/{find_role_by_name(signoz, admin_token, scoped_role)}"),
|
||||
json={
|
||||
"description": "",
|
||||
"transactionGroups": [
|
||||
transaction_group("read", "metaresource", "llm-pricing-rule", [rule_id]),
|
||||
transaction_group("delete", "metaresource", "llm-pricing-rule", [rule_id]),
|
||||
],
|
||||
},
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=10,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
|
||||
|
||||
response = upsert_llm_pricing_rules(signoz, get_token(scoped_email, user_password), [{**PROBE_RULE, "id": rule_id}])
|
||||
assert response.status_code == HTTPStatus.FORBIDDEN, response.text
|
||||
assert "llm-pricing-rule:update" in response.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("email", "model_name", "expected"),
|
||||
[
|
||||
(editor_email, PROBE_RULE["modelName"], HTTPStatus.FORBIDDEN),
|
||||
(viewer_email, PROBE_RULE["modelName"], HTTPStatus.FORBIDDEN),
|
||||
(updater_email, PROBE_RULE["modelName"], HTTPStatus.FORBIDDEN),
|
||||
(scoped_email, OTHER_RULE["modelName"], HTTPStatus.FORBIDDEN),
|
||||
(scoped_email, PROBE_RULE["modelName"], HTTPStatus.NO_CONTENT),
|
||||
(USER_ADMIN_EMAIL, OTHER_RULE["modelName"], HTTPStatus.NO_CONTENT),
|
||||
],
|
||||
ids=["editor", "viewer", "updater", "scoped_other", "scoped_granted", "admin"],
|
||||
)
|
||||
def test_delete_needs_delete_grant(
|
||||
signoz: types.SigNoz,
|
||||
get_token: Callable[[str, str], str],
|
||||
email: str,
|
||||
model_name: str,
|
||||
expected: HTTPStatus,
|
||||
) -> None:
|
||||
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
rule_id = next(r["id"] for r in list_llm_pricing_rules(signoz, admin_token) if r["modelName"] == model_name)
|
||||
token = get_token(email, USER_ADMIN_PASSWORD if email == USER_ADMIN_EMAIL else user_password)
|
||||
|
||||
response = requests.delete(
|
||||
signoz.self.host_configs["8080"].get(f"{LLM_PRICING_RULES_URL}/{rule_id}"),
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=10,
|
||||
)
|
||||
assert response.status_code == expected, response.text
|
||||
if expected == HTTPStatus.FORBIDDEN:
|
||||
assert "llm-pricing-rule:delete" in response.text
|
||||
|
||||
|
||||
def test_cleanup(
|
||||
signoz: types.SigNoz,
|
||||
get_token: Callable[[str, str], str],
|
||||
) -> None:
|
||||
delete_all_llm_pricing_rules(signoz, get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD))
|
||||
@@ -1,165 +0,0 @@
|
||||
from collections.abc import Callable
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from http import HTTPStatus
|
||||
|
||||
import pytest
|
||||
|
||||
from fixtures import types
|
||||
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
|
||||
from fixtures.logs import Logs
|
||||
from fixtures.metrics import Metrics
|
||||
from fixtures.querier import (
|
||||
Aggregation,
|
||||
BuilderQuery,
|
||||
MetricAggregation,
|
||||
get_all_warnings,
|
||||
get_error_message,
|
||||
get_series_values,
|
||||
make_query_request,
|
||||
)
|
||||
from fixtures.traces import TraceIdGenerator, Traces
|
||||
|
||||
TWO_YEARS = timedelta(days=730)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"start_ms,end_ms,message",
|
||||
[
|
||||
pytest.param(0, 1_700_000_000_000, "start time is required", id="zero_start"),
|
||||
pytest.param(1_700_000_000_000, 1_700_000_000_000, "start time must be before end time", id="start_equals_end"),
|
||||
# 2592000000 is 30 days in ms; read as an epoch in seconds it is year 2052.
|
||||
pytest.param(1_700_000_000_000, 2_592_000_000, "end time 2052-02-20T00:00:00Z is too far in the future", id="end_in_2052"),
|
||||
],
|
||||
)
|
||||
def test_time_range_rejected(
|
||||
start_ms: int,
|
||||
end_ms: int,
|
||||
message: str,
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
) -> None:
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
response = make_query_request(
|
||||
signoz,
|
||||
token,
|
||||
start_ms=start_ms,
|
||||
end_ms=end_ms,
|
||||
queries=[BuilderQuery(signal="logs", aggregations=[Aggregation(expression="count()")], step_interval=60).to_dict()],
|
||||
)
|
||||
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
assert get_error_message(response.json()) == message
|
||||
|
||||
|
||||
def test_two_year_logs_timeseries_step_clamped(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_logs: Callable[[list[Logs]], None],
|
||||
) -> None:
|
||||
# A 1s step over 2 years is clamped to 42045s (at most ~1500 points); end is aligned to it so the bucket count is stable.
|
||||
step_seconds = 42045
|
||||
end = datetime.fromtimestamp(int(datetime.now(tz=UTC).timestamp()) // step_seconds * step_seconds, tz=UTC)
|
||||
insert_logs([Logs(timestamp=end - timedelta(minutes=1), resources={"service.name": "time-range-logs"}, body="two year span")])
|
||||
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
response = make_query_request(
|
||||
signoz,
|
||||
token,
|
||||
start_ms=int((end - TWO_YEARS).timestamp() * 1000),
|
||||
end_ms=int(end.timestamp() * 1000),
|
||||
queries=[
|
||||
BuilderQuery(
|
||||
signal="logs",
|
||||
filter_expression="service.name = 'time-range-logs'",
|
||||
aggregations=[Aggregation(expression="count()")],
|
||||
step_interval=1,
|
||||
).to_dict()
|
||||
],
|
||||
format_options={"formatTableResultForUI": False, "fillGaps": True},
|
||||
)
|
||||
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json()["data"]["meta"]["stepIntervals"] == {"A": step_seconds}
|
||||
assert get_all_warnings(response.json()) == [
|
||||
{"message": f"Query A is requesting aggregation interval 1 seconds, which is smaller than the minimum allowed interval of {step_seconds} seconds for selected time range. Using the minimum instead"},
|
||||
]
|
||||
values = get_series_values(response.json(), "A")
|
||||
assert len(values) == 1502
|
||||
assert sum(v["value"] for v in values) == 1
|
||||
|
||||
|
||||
def test_two_year_traces_timeseries_step_clamped(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
) -> None:
|
||||
# Same clamp as logs: 42045s; end is aligned to it so the bucket count is stable.
|
||||
step_seconds = 42045
|
||||
end = datetime.fromtimestamp(int(datetime.now(tz=UTC).timestamp()) // step_seconds * step_seconds, tz=UTC)
|
||||
insert_traces([Traces(timestamp=end - timedelta(minutes=1), trace_id=TraceIdGenerator.trace_id(), span_id=TraceIdGenerator.span_id(), resources={"service.name": "time-range-traces"})])
|
||||
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
response = make_query_request(
|
||||
signoz,
|
||||
token,
|
||||
start_ms=int((end - TWO_YEARS).timestamp() * 1000),
|
||||
end_ms=int(end.timestamp() * 1000),
|
||||
queries=[
|
||||
BuilderQuery(
|
||||
signal="traces",
|
||||
filter_expression="service.name = 'time-range-traces'",
|
||||
aggregations=[Aggregation(expression="count()")],
|
||||
step_interval=1,
|
||||
).to_dict()
|
||||
],
|
||||
format_options={"formatTableResultForUI": False, "fillGaps": True},
|
||||
)
|
||||
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json()["data"]["meta"]["stepIntervals"] == {"A": step_seconds}
|
||||
assert get_all_warnings(response.json()) == [
|
||||
{"message": f"Query A is requesting aggregation interval 1 seconds, which is smaller than the minimum allowed interval of {step_seconds} seconds for selected time range. Using the minimum instead"},
|
||||
]
|
||||
values = get_series_values(response.json(), "A")
|
||||
assert len(values) == 1502
|
||||
assert sum(v["value"] for v in values) == 1
|
||||
|
||||
|
||||
def test_two_year_metrics_timeseries_step_clamped(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_metrics: Callable[[list[Metrics]], None],
|
||||
) -> None:
|
||||
# A 1s step over 2 years is clamped to 210600s (~300 points); end is aligned to it so the bucket count is stable.
|
||||
step_seconds = 210600
|
||||
metric_name = "time_range_two_year_gauge"
|
||||
end = datetime.fromtimestamp(int(datetime.now(tz=UTC).timestamp()) // step_seconds * step_seconds, tz=UTC)
|
||||
insert_metrics([Metrics(metric_name=metric_name, labels={"service": "time-range-metrics"}, timestamp=end - timedelta(minutes=1), value=1.0, temporality="Unspecified", type_="Gauge", is_monotonic=False)])
|
||||
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
response = make_query_request(
|
||||
signoz,
|
||||
token,
|
||||
start_ms=int((end - TWO_YEARS).timestamp() * 1000),
|
||||
end_ms=int(end.timestamp() * 1000),
|
||||
queries=[
|
||||
BuilderQuery(
|
||||
signal="metrics",
|
||||
aggregations=[MetricAggregation(metric_name=metric_name, time_aggregation="latest", space_aggregation="sum", temporality="unspecified")],
|
||||
step_interval=1,
|
||||
).to_dict()
|
||||
],
|
||||
format_options={"formatTableResultForUI": False, "fillGaps": True},
|
||||
)
|
||||
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json()["data"]["meta"]["stepIntervals"] == {"A": step_seconds}
|
||||
assert get_all_warnings(response.json()) == [
|
||||
{"message": f"Query A is requesting aggregation interval 1 seconds, which is smaller than the minimum allowed interval of {step_seconds} seconds for selected time range. Using the minimum instead"},
|
||||
]
|
||||
assert len(get_series_values(response.json(), "A")) == 301
|
||||
@@ -1,418 +0,0 @@
|
||||
from collections.abc import Callable
|
||||
from http import HTTPStatus
|
||||
|
||||
import requests
|
||||
from wiremock.resources.mappings import Mapping
|
||||
|
||||
from fixtures.auth import (
|
||||
USER_ADMIN_EMAIL,
|
||||
USER_ADMIN_PASSWORD,
|
||||
add_license,
|
||||
change_user_role,
|
||||
create_active_user,
|
||||
)
|
||||
from fixtures.role import find_role_by_name, transaction_group
|
||||
from fixtures.types import Operation, SigNoz, TestContainerDocker
|
||||
|
||||
ROUTE_POLICIES_URL = "/api/v1/route_policies"
|
||||
|
||||
_EDITOR_EMAIL = "editor+alertauthz@integration.test"
|
||||
_EDITOR_PASSWORD = "password123Z$"
|
||||
_VIEWER_EMAIL = "viewer+alertauthz@integration.test"
|
||||
_VIEWER_PASSWORD = "password123Z$"
|
||||
_ACTOR_EMAIL = "customrole+alertauthz@integration.test"
|
||||
_ACTOR_PASSWORD = "password123Z$"
|
||||
_ACTOR_ROLE_NAME = "alert-authz-actor"
|
||||
|
||||
_ROUTE_POLICY_NAME = "alert-authz-route-policy"
|
||||
_ACTOR_ROUTE_POLICY_NAME = "alert-authz-actor-route-policy"
|
||||
|
||||
SEED_CHANNEL = {"name": "alert-authz-channel", "email_configs": [{"to": "alert-authz@integration.test"}]}
|
||||
SEED_CHANNEL_ALT = {"name": "alert-authz-channel-alt", "email_configs": [{"to": "alert-authz-alt@integration.test"}]}
|
||||
|
||||
ROUTE_POLICY_TEMPLATE = {"expression": 'threshold.name == "critical"', "channels": [SEED_CHANNEL["name"]], "description": "authz coverage policy"}
|
||||
|
||||
_ACTOR_BASE_TRANSACTION_GROUPS = [
|
||||
transaction_group("create", "metaresource", "route-policy", ["*"]),
|
||||
transaction_group("read", "metaresource", "route-policy", ["*"]),
|
||||
transaction_group("list", "metaresource", "route-policy", ["*"]),
|
||||
transaction_group("update", "metaresource", "route-policy", ["*"]),
|
||||
transaction_group("delete", "metaresource", "route-policy", ["*"]),
|
||||
transaction_group("attach", "metaresource", "route-policy", ["*"]),
|
||||
transaction_group("detach", "metaresource", "route-policy", ["*"]),
|
||||
]
|
||||
|
||||
|
||||
def test_setup_users_and_channels(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
response = requests.get(
|
||||
signoz.self.host_configs["8080"].get("/api/v2/users"),
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
existing_emails = {user["email"] for user in response.json()["data"]}
|
||||
|
||||
for email, role, password, name in (
|
||||
(_EDITOR_EMAIL, "signoz-editor", _EDITOR_PASSWORD, "alert authz editor"),
|
||||
(_VIEWER_EMAIL, "signoz-viewer", _VIEWER_PASSWORD, "alert authz viewer"),
|
||||
):
|
||||
if email not in existing_emails:
|
||||
create_active_user(signoz, admin_token, email=email, role=role, password=password, name=name)
|
||||
|
||||
response = requests.get(
|
||||
signoz.self.host_configs["8080"].get("/api/v1/channels"),
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
existing_channel_names = [channel["name"] for channel in response.json()["data"] or []]
|
||||
for channel in (SEED_CHANNEL, SEED_CHANNEL_ALT):
|
||||
if channel["name"] not in existing_channel_names:
|
||||
response = requests.post(
|
||||
signoz.self.host_configs["8080"].get("/api/v1/channels"),
|
||||
json=channel,
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.CREATED, response.text
|
||||
|
||||
response = requests.get(
|
||||
signoz.self.host_configs["8080"].get(ROUTE_POLICIES_URL),
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
for policy in response.json()["data"] or []:
|
||||
if policy["name"] in (_ROUTE_POLICY_NAME, _ACTOR_ROUTE_POLICY_NAME):
|
||||
response = requests.delete(
|
||||
signoz.self.host_configs["8080"].get(f"{ROUTE_POLICIES_URL}/{policy['id']}"),
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
|
||||
|
||||
response = requests.post(
|
||||
signoz.self.host_configs["8080"].get(ROUTE_POLICIES_URL),
|
||||
json={**ROUTE_POLICY_TEMPLATE, "name": _ROUTE_POLICY_NAME},
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.CREATED, response.text
|
||||
|
||||
|
||||
def test_viewer_and_editor_allowed_on_route_policy_reads(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
for email, password in ((_VIEWER_EMAIL, _VIEWER_PASSWORD), (_EDITOR_EMAIL, _EDITOR_PASSWORD)):
|
||||
token = get_token(email, password)
|
||||
|
||||
response = requests.get(
|
||||
signoz.self.host_configs["8080"].get(ROUTE_POLICIES_URL),
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, f"{email}: {response.text}"
|
||||
policy_id = {policy["name"]: policy["id"] for policy in response.json()["data"]}[_ROUTE_POLICY_NAME]
|
||||
|
||||
response = requests.get(
|
||||
signoz.self.host_configs["8080"].get(f"{ROUTE_POLICIES_URL}/{policy_id}"),
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, f"{email}: {response.text}"
|
||||
|
||||
|
||||
def test_viewer_and_editor_forbidden_on_route_policy_writes(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
response = requests.get(
|
||||
signoz.self.host_configs["8080"].get(ROUTE_POLICIES_URL),
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
policy_id = {policy["name"]: policy["id"] for policy in response.json()["data"]}[_ROUTE_POLICY_NAME]
|
||||
|
||||
for email, password in ((_VIEWER_EMAIL, _VIEWER_PASSWORD), (_EDITOR_EMAIL, _EDITOR_PASSWORD)):
|
||||
token = get_token(email, password)
|
||||
for method, path in (
|
||||
("post", ROUTE_POLICIES_URL),
|
||||
("put", f"{ROUTE_POLICIES_URL}/{policy_id}"),
|
||||
("delete", f"{ROUTE_POLICIES_URL}/{policy_id}"),
|
||||
):
|
||||
response = getattr(requests, method)(
|
||||
signoz.self.host_configs["8080"].get(path),
|
||||
json={**ROUTE_POLICY_TEMPLATE, "name": _ROUTE_POLICY_NAME},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.FORBIDDEN, f"{email} {method.upper()} {path}: expected 403, got {response.status_code}: {response.text}"
|
||||
|
||||
|
||||
def test_admin_allowed_on_route_policy_writes(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
response = requests.get(
|
||||
signoz.self.host_configs["8080"].get(ROUTE_POLICIES_URL),
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
policy_id = {policy["name"]: policy["id"] for policy in response.json()["data"]}[_ROUTE_POLICY_NAME]
|
||||
|
||||
response = requests.put(
|
||||
signoz.self.host_configs["8080"].get(f"{ROUTE_POLICIES_URL}/{policy_id}"),
|
||||
json={**ROUTE_POLICY_TEMPLATE, "name": _ROUTE_POLICY_NAME, "channels": [SEED_CHANNEL_ALT["name"]]},
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
assert response.json()["data"]["channels"] == [SEED_CHANNEL_ALT["name"]]
|
||||
|
||||
response = requests.delete(
|
||||
signoz.self.host_configs["8080"].get(f"{ROUTE_POLICIES_URL}/{policy_id}"),
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
|
||||
|
||||
|
||||
def test_route_policy_naming_unknown_channel_rejected(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
response = requests.post(
|
||||
signoz.self.host_configs["8080"].get(ROUTE_POLICIES_URL),
|
||||
json={**ROUTE_POLICY_TEMPLATE, "name": _ROUTE_POLICY_NAME, "channels": ["alert-authz-channel-missing"]},
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
|
||||
|
||||
|
||||
def test_apply_license(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
make_http_mocks: Callable[[TestContainerDocker, list[Mapping]], None],
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
add_license(signoz, make_http_mocks, get_token)
|
||||
|
||||
|
||||
def test_route_policy_managed_role_tuples_enforced_with_license(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
editor_token = get_token(_EDITOR_EMAIL, _EDITOR_PASSWORD)
|
||||
|
||||
response = requests.post(
|
||||
signoz.self.host_configs["8080"].get(ROUTE_POLICIES_URL),
|
||||
json={**ROUTE_POLICY_TEMPLATE, "name": _ROUTE_POLICY_NAME},
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.CREATED, f"admin create must pass on the migrated route-policy and channel attach tuples: {response.text}"
|
||||
policy_id = response.json()["data"]["id"]
|
||||
|
||||
response = requests.get(
|
||||
signoz.self.host_configs["8080"].get(f"{ROUTE_POLICIES_URL}/{policy_id}"),
|
||||
headers={"Authorization": f"Bearer {editor_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, f"editor read must pass on the migrated route-policy read tuple: {response.text}"
|
||||
|
||||
response = requests.put(
|
||||
signoz.self.host_configs["8080"].get(f"{ROUTE_POLICIES_URL}/{policy_id}"),
|
||||
json={**ROUTE_POLICY_TEMPLATE, "name": _ROUTE_POLICY_NAME, "channels": [SEED_CHANNEL_ALT["name"]]},
|
||||
headers={"Authorization": f"Bearer {editor_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.FORBIDDEN, f"editor update must be forbidden, the migration grants editors no route-policy update tuple: {response.text}"
|
||||
|
||||
response = requests.delete(
|
||||
signoz.self.host_configs["8080"].get(f"{ROUTE_POLICIES_URL}/{policy_id}"),
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, f"admin delete must pass on the migrated route-policy delete tuple: {response.text}"
|
||||
|
||||
|
||||
def test_setup_channel_scoped_actor(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
create_role: Callable[..., str],
|
||||
):
|
||||
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
response = requests.get(
|
||||
signoz.self.host_configs["8080"].get("/api/v1/roles"),
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
existing_role_ids = {role["name"]: role["id"] for role in response.json()["data"]}
|
||||
|
||||
if _ACTOR_ROLE_NAME in existing_role_ids:
|
||||
response = requests.put(
|
||||
signoz.self.host_configs["8080"].get(f"/api/v1/roles/{existing_role_ids[_ACTOR_ROLE_NAME]}"),
|
||||
json={"description": "", "transactionGroups": _ACTOR_BASE_TRANSACTION_GROUPS},
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
|
||||
else:
|
||||
create_role(admin_token, _ACTOR_ROLE_NAME, _ACTOR_BASE_TRANSACTION_GROUPS)
|
||||
|
||||
response = requests.get(
|
||||
signoz.self.host_configs["8080"].get("/api/v2/users"),
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
if _ACTOR_EMAIL not in {user["email"] for user in response.json()["data"]}:
|
||||
user_id = create_active_user(signoz, admin_token, email=_ACTOR_EMAIL, role="signoz-viewer", password=_ACTOR_PASSWORD, name="alert authz actor")
|
||||
change_user_role(signoz, admin_token, user_id, "signoz-viewer", _ACTOR_ROLE_NAME)
|
||||
|
||||
|
||||
def test_route_policy_naming_channel_forbidden_without_channel_attach(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
token = get_token(_ACTOR_EMAIL, _ACTOR_PASSWORD)
|
||||
|
||||
response = requests.post(
|
||||
signoz.self.host_configs["8080"].get(ROUTE_POLICIES_URL),
|
||||
json={**ROUTE_POLICY_TEMPLATE, "name": _ACTOR_ROUTE_POLICY_NAME},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.FORBIDDEN, response.text
|
||||
|
||||
|
||||
def test_route_policy_channel_changes_follow_channel_attach_and_detach(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
role_id = find_role_by_name(signoz, admin_token, _ACTOR_ROLE_NAME)
|
||||
|
||||
response = requests.put(
|
||||
signoz.self.host_configs["8080"].get(f"/api/v1/roles/{role_id}"),
|
||||
json={"description": "", "transactionGroups": _ACTOR_BASE_TRANSACTION_GROUPS + [transaction_group("attach", "metaresource", "notification-channel", ["*"])]},
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
|
||||
|
||||
token = get_token(_ACTOR_EMAIL, _ACTOR_PASSWORD)
|
||||
response = requests.post(
|
||||
signoz.self.host_configs["8080"].get(ROUTE_POLICIES_URL),
|
||||
json={**ROUTE_POLICY_TEMPLATE, "name": _ACTOR_ROUTE_POLICY_NAME},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.CREATED, response.text
|
||||
policy_id = response.json()["data"]["id"]
|
||||
|
||||
response = requests.put(
|
||||
signoz.self.host_configs["8080"].get(f"{ROUTE_POLICIES_URL}/{policy_id}"),
|
||||
json={**ROUTE_POLICY_TEMPLATE, "name": _ACTOR_ROUTE_POLICY_NAME, "channels": [SEED_CHANNEL["name"], SEED_CHANNEL_ALT["name"]]},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
|
||||
response = requests.put(
|
||||
signoz.self.host_configs["8080"].get(f"{ROUTE_POLICIES_URL}/{policy_id}"),
|
||||
json={**ROUTE_POLICY_TEMPLATE, "name": _ACTOR_ROUTE_POLICY_NAME, "channels": [SEED_CHANNEL_ALT["name"]]},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.FORBIDDEN, response.text
|
||||
|
||||
response = requests.put(
|
||||
signoz.self.host_configs["8080"].get(f"/api/v1/roles/{role_id}"),
|
||||
json={
|
||||
"description": "",
|
||||
"transactionGroups": _ACTOR_BASE_TRANSACTION_GROUPS + [transaction_group("attach", "metaresource", "notification-channel", ["*"]), transaction_group("detach", "metaresource", "notification-channel", ["*"])],
|
||||
},
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
|
||||
|
||||
response = requests.put(
|
||||
signoz.self.host_configs["8080"].get(f"{ROUTE_POLICIES_URL}/{policy_id}"),
|
||||
json={**ROUTE_POLICY_TEMPLATE, "name": _ACTOR_ROUTE_POLICY_NAME, "channels": [SEED_CHANNEL_ALT["name"]]},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
assert response.json()["data"]["channels"] == [SEED_CHANNEL_ALT["name"]]
|
||||
|
||||
response = requests.delete(
|
||||
signoz.self.host_configs["8080"].get(f"{ROUTE_POLICIES_URL}/{policy_id}"),
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
|
||||
|
||||
|
||||
def test_alert_authz_cleanup(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
response = requests.get(
|
||||
signoz.self.host_configs["8080"].get(ROUTE_POLICIES_URL),
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
for policy in response.json()["data"] or []:
|
||||
if policy["name"] in (_ROUTE_POLICY_NAME, _ACTOR_ROUTE_POLICY_NAME):
|
||||
response = requests.delete(
|
||||
signoz.self.host_configs["8080"].get(f"{ROUTE_POLICIES_URL}/{policy['id']}"),
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
|
||||
|
||||
response = requests.get(
|
||||
signoz.self.host_configs["8080"].get("/api/v1/channels"),
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
for channel in response.json()["data"] or []:
|
||||
if channel["name"] in (SEED_CHANNEL["name"], SEED_CHANNEL_ALT["name"]):
|
||||
response = requests.delete(
|
||||
signoz.self.host_configs["8080"].get(f"/api/v1/channels/{channel['id']}"),
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, f"delete channel: {response.text}"
|
||||
Reference in New Issue
Block a user