mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-13 20:01:05 +00:00
Compare commits
11 Commits
feat/input
...
tvats-remo
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
be7df2f8f7 | ||
|
|
445e3cb088 | ||
|
|
0fbd56058f | ||
|
|
0f598c49ad | ||
|
|
b780551de6 | ||
|
|
8bc4c5f79c | ||
|
|
198230f064 | ||
|
|
0791306e52 | ||
|
|
792de1376d | ||
|
|
20e6d44289 | ||
|
|
9fef8eea69 |
@@ -11,7 +11,7 @@ Page stories are written with the `signoz-page-story` skill ([`.claude/skills/si
|
||||
- **New page, new story. New state, new control or variant.** The skill decides which: a control on a response, a variant worth linking to, or a `play` story for a state only a click reaches.
|
||||
- **A shared component is covered through its pages.** A change under `components/` or `container/` with no story of its own updates the stories of the pages that render it.
|
||||
- **Plays live with the mocks.** A `play` is a named function exported from `stories/__story_mockdata__/<page>.play.ts`, which is collapsed for review like the rest of the AI-owned mocks. The story file only names it: `play: openEditDrawer`. A story file that still holds play bodies moves them there the first time you edit it.
|
||||
- **A play passes for every control value.** Branch each check on the args it depends on (panel kind, data state, row count, hidden header). A value the page supports must never fail the play.
|
||||
- **A play passes for every control value.** Branch each check on the args it depends on (panel kind, data state, access, check state and revoked permissions, license, held-open tooltips, a count at 0, a view or tab that drops the target, a write state). A value the page supports must never fail the play. The `signoz-page-story` skill's **Plays** section lists the cases plays have missed.
|
||||
- **Mocks answer every request a reachable state makes.** Selecting a row, opening a view or switching a tab that fetches more hits a handler, never the 501 catch-all.
|
||||
- **Already covered, say so.** When the existing story and its controls already reach the changed state, no story edit is needed; state that in the PR description.
|
||||
- **Opt out only when there is no visual diff.** Skip stories only when the change renders nothing differently: types, api clients, hooks with no UI branch, tests. Deleting a page deletes its stories.
|
||||
|
||||
@@ -106,6 +106,27 @@ await expect(toggle.getAttribute('aria-checked')).toBe(before);
|
||||
|
||||
**Delete a story once its difference disappears.** Say a story checks that a button reads "View" rather than "Edit" when a permission is missing. If the label later becomes the same either way, that story passes no matter which permissions are held, including all of them, and it is testing nothing. When a behaviour stops depending on a permission, delete the story or rewrite it to lock in the new behaviour, and say which one you did in the PR.
|
||||
|
||||
## Plays
|
||||
|
||||
CI runs each play once, with its story's own args. Anyone can flip a control in the panel, and nothing runs the play against that value, so a play that breaks on it goes unnoticed. Write each play so it cannot.
|
||||
|
||||
Before writing the clicks, list what has to be on screen for the play's target to exist, and return early when the args take it away. These are the cases plays have missed:
|
||||
|
||||
- The controls every story has. `State` on loading or error renders no rows and no filter suggestions. `Access`, `Permissions` and `Revoked` remove rows, row actions and gated buttons, and the `editor` and `viewer` presets grant telemetry reads only, so a page gated on its own resource shows them nothing. `Check state` on loading disables every gated control, and on error an `AuthZButton` stays enabled while an `AuthZGuardContent` set to fail closed hides what it wraps. `License` and `Banner` decide the plan, so a cloud-only form is gone on the others. `Hold tooltips open` shows a label a second time, inside its tooltip.
|
||||
- A count at 0. The page can swap its whole list for an empty state, and the header, filters and column picker go with it.
|
||||
- A view, filter or invalid query that leaves no rows, even when the count is above 0.
|
||||
- A tab without the widget. A filter box that one tab has is not on the next.
|
||||
- A second list beside the main one, such as saved views. At 0, loading or failed, its actions are gone.
|
||||
- Text that depends on an arg. A disabled rule offers Enable, not Disable. A write that fails raises a different toast from one that lands, and one left loading raises none. Pick the expected text from the args.
|
||||
- Rows that move. A view, a sort or pinning changes which row is locked, pinned or legacy, so find the row by what it is, not by its index.
|
||||
|
||||
Make those checks with the page's own code instead of restating a condition. Build the rows with the builder the handler uses and the view's own filter, and check a permission with the page's own check through `accessFor(...).allows(...)`, or the role against the constant the page gates on, such as `componentPermission.action`. Export the checks from the mocks module, next to the handlers, so a handler change moves them too. The alert rules page has `listedRules`, `hasRowMenu`, `showsNoRulesPage` and `listsSavedViews`; the dashboards list has `listedDashboards`, `canList`, `canCreate` and `canUpdate`.
|
||||
|
||||
Two habits cover the rest:
|
||||
|
||||
- Use `findAllBy*` and take the first whenever the text can appear twice, such as in a tooltip or a popover title.
|
||||
- Wrap `toBeVisible` in `waitFor` for anything that fades in. A tooltip or toast found the moment it mounts is not visible yet.
|
||||
|
||||
## Rules
|
||||
|
||||
- **Default is the loaded page.** `export const Default: Story = {}` with no args, every widget carrying data. Empty, loading and failed are variants or control values, never the default.
|
||||
@@ -116,7 +137,7 @@ await expect(toggle.getAttribute('aria-checked')).toBe(before);
|
||||
- **Endpoints the page owns go through `response.json`**, so the Data control covers loaded, loading and failed in one declaration. Endpoints the page cannot render without (ingestion detection, preferences, feature payloads) take a plain resolver so the shell survives the loading and error states.
|
||||
- **Query-param state starts from `route`** (`/logs?tab=explorer`). In-page param navigation works inside a story; a different pathname is blocked and reported by the overlay. A control for a param is worth it only when the param is a page mode someone would want to flip.
|
||||
- **File layout**: every story file for a page lives under `src/pages/<Page>/stories/`: `<Page>.stories.tsx`, `<Page>.stories.mocks.tsx`, payload builders in `stories/__story_mockdata__/<page>.ts`, play functions in `stories/__story_mockdata__/<page>.play.ts`. Nothing page-specific in `src/storybook/controls/`. A page that is a tab strip over several routes gets one story file per tab, in its own folder under the module page (`LogsModulePage/Pipelines/stories/Pipelines.stories.tsx`), each with its own mocks and `__story_mockdata__/`; the builders more than one tab needs stay in the module page's own `stories/__story_mockdata__/` (`AlertList/stories/__story_mockdata__/alerts.ts`), which a tab reaches as `../../stories/__story_mockdata__/alerts`. Every one of them renders the module page, so the tab strip is there, and the `route` its mocks return decides which tab is open. A page's permission stories go one level further down, in `stories/authz/<Page>.authz.stories.tsx`, on the page's own mocks: see **Permission stories**.
|
||||
- **A state only a click reaches is a story with a `play` function**, not a control: a drawer, a modal, an edit mode the page holds in component state. Drive it with `userEvent` and the queries from `storybook/test`, take the first of a repeated row action, and wait on the state's own text. The page fetches before it renders a row, so the finder needs a timeout past the 1s default. The play is a named function exported from `__story_mockdata__/<page>.play.ts` and the story file only names it (`play: openEditDrawer`), so the reviewer reads states, not clicks; a story file that still holds play bodies moves them there the first time you edit it. It branches every check on the args it depends on: a control value the page supports never fails it. A state the app drops again on its own, such as one keyed on an array identity that a refetch replaces, does not get a story: it would not survive being looked at. A _sequence_ of such states, a wizard's steps or a questionnaire's pages, is still a control: declare the steps in the mocks module and walk them from a `play` on the meta that destructures `mount`, which is what makes Storybook replay it on an arg change. See [references/controls.md](references/controls.md).
|
||||
- **A state only a click reaches is a story with a `play` function**, not a control: a drawer, a modal, an edit mode the page holds in component state. Drive it with `userEvent` and the queries from `storybook/test`, take the first of a repeated row action, and wait on the state's own text. The page fetches before it renders a row, so the finder needs a timeout past the 1s default. The play is a named function exported from `__story_mockdata__/<page>.play.ts` and the story file only names it (`play: openEditDrawer`), so the reviewer reads states, not clicks; a story file that still holds play bodies moves them there the first time you edit it. It branches every check on the args it depends on: a control value the page supports never fails it. See **Plays**. A state the app drops again on its own, such as one keyed on an array identity that a refetch replaces, does not get a story: it would not survive being looked at. A _sequence_ of such states, a wizard's steps or a questionnaire's pages, is still a control: declare the steps in the mocks module and walk them from a `play` on the meta that destructures `mount`, which is what makes Storybook replay it on an arg change. See [references/controls.md](references/controls.md).
|
||||
- **The mocks are AI-owned and say so.** `<Page>.stories.mocks.tsx` and every file under a `__story_mockdata__/` open with this banner, above the imports:
|
||||
|
||||
```ts
|
||||
@@ -143,7 +164,7 @@ await expect(toggle.getAttribute('aria-checked')).toBe(before);
|
||||
- [ ] a page tagged `authz` has its `Authz` folder: one story per permission it reads, each reached by `revoked`, none of them a role preset, and each one checked by the `disabled` state of what the permission gates
|
||||
- [ ] the mocks module and every `__story_mockdata__` file carry the AI-owned banner
|
||||
- [ ] every control flipped once, its effect seen on screen
|
||||
- [ ] every play passes with each control value its story exposes, and the story file holds no play body
|
||||
- [ ] every play passes with each control value its story exposes, checked against the cases in **Plays**, and the story file holds no play body
|
||||
- [ ] every request a reachable state makes (a selected row, an opened view, a switched tab) has a handler
|
||||
- [ ] console clean: no `[storybook] no msw handler`, no 501, no msw unhandled request, no React warning
|
||||
- [ ] no navigation overlay on mount
|
||||
|
||||
@@ -67,7 +67,7 @@ services:
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
telemetrystore-migrator:
|
||||
image: signoz/signoz-otel-collector:v0.144.6
|
||||
image: signoz/signoz-otel-collector:v0.144.15
|
||||
container_name: telemetrystore-migrator
|
||||
environment:
|
||||
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_DSN=tcp://clickhouse:9000
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
services:
|
||||
signoz-otel-collector:
|
||||
image: signoz/signoz-otel-collector:v0.142.0
|
||||
image: signoz/signoz-otel-collector:v0.144.15
|
||||
container_name: signoz-otel-collector-dev
|
||||
entrypoint:
|
||||
- /bin/sh
|
||||
|
||||
50
.github/workflows/build-staging.yaml
vendored
50
.github/workflows/build-staging.yaml
vendored
@@ -18,25 +18,25 @@ env:
|
||||
jobs:
|
||||
prepare:
|
||||
runs-on: ubuntu-latest
|
||||
if: ${{ contains(github.event.label.name, 'staging:') || github.event.ref == 'refs/heads/main' }}
|
||||
if: ${{ github.event_name == 'push' || startsWith(github.event.label.name, 'staging:') }}
|
||||
outputs:
|
||||
version: ${{ steps.build-info.outputs.version }}
|
||||
hash: ${{ steps.build-info.outputs.hash }}
|
||||
time: ${{ steps.build-info.outputs.time }}
|
||||
branch: ${{ steps.build-info.outputs.branch }}
|
||||
deployment: ${{ steps.build-info.outputs.deployment }}
|
||||
path: ${{ steps.build-info.outputs.path }}
|
||||
steps:
|
||||
- name: self-checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- id: token
|
||||
name: github-token-gen
|
||||
uses: actions/create-github-app-token@v1
|
||||
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0
|
||||
with:
|
||||
app-id: ${{ secrets.PRIMUS_APP_ID }}
|
||||
private-key: ${{ secrets.PRIMUS_PRIVATE_KEY }}
|
||||
owner: ${{ github.repository_owner }}
|
||||
- name: primus-checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
repository: signoz/primus
|
||||
ref: main
|
||||
@@ -44,22 +44,29 @@ jobs:
|
||||
token: ${{ steps.token.outputs.token }}
|
||||
- name: build-info
|
||||
id: build-info
|
||||
env:
|
||||
LABEL: ${{ github.event.label.name }}
|
||||
run: |
|
||||
echo "version=$($MAKE info-version)" >> $GITHUB_OUTPUT
|
||||
echo "hash=$($MAKE info-commit-short)" >> $GITHUB_OUTPUT
|
||||
echo "time=$($MAKE info-timestamp)" >> $GITHUB_OUTPUT
|
||||
echo "branch=$($MAKE info-branch)" >> $GITHUB_OUTPUT
|
||||
|
||||
staging_label="${{ github.event.label.name }}"
|
||||
if [[ "${staging_label}" == "staging:"* ]]; then
|
||||
deployment=${staging_label#"staging:"}
|
||||
elif [[ "${{ github.event.ref }}" == "refs/heads/main" ]]; then
|
||||
deployment="staging"
|
||||
# merges to main release the base every overlay inherits, a staging:<deployment> label releases that overlay
|
||||
if [[ "${GITHUB_EVENT_NAME}" == push ]]; then
|
||||
path="overlays/staging/*/signoz/base"
|
||||
else
|
||||
echo "error: not able to determine deployment - please verify the PR label or the branch"
|
||||
# the deployment is spliced into the release path glob and the JSON payload
|
||||
deployment="${LABEL#staging:}"
|
||||
if [[ ! "${deployment}" =~ ^[a-z0-9]([a-z0-9-]*[a-z0-9])?$ ]]; then
|
||||
echo "::error::label ${LABEL} must be staging:<deployment>, where the deployment is lowercase letters, digits and dashes"
|
||||
exit 1
|
||||
fi
|
||||
path="overlays/staging/*/signoz/overlays/${deployment}"
|
||||
fi
|
||||
echo "deployment=${deployment}" >> $GITHUB_OUTPUT
|
||||
|
||||
{
|
||||
echo "version=$($MAKE info-version)"
|
||||
echo "hash=$($MAKE info-commit-short)"
|
||||
echo "time=$($MAKE info-timestamp)"
|
||||
echo "branch=$($MAKE info-branch)"
|
||||
echo "path=${path}"
|
||||
} >> "${GITHUB_OUTPUT}"
|
||||
- name: create-dotenv
|
||||
run: |
|
||||
mkdir -p frontend
|
||||
@@ -71,7 +78,7 @@ jobs:
|
||||
echo 'VITE_ENVIRONMENT="staging"' >> frontend/.env
|
||||
echo 'VITE_VERSION="${{ steps.build-info.outputs.version }}"' >> frontend/.env
|
||||
- name: cache-dotenv
|
||||
uses: actions/cache@v4
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: frontend/.env
|
||||
key: staging-dotenv-${{ github.sha }}
|
||||
@@ -115,7 +122,6 @@ jobs:
|
||||
DOCKER_MANIFEST: true
|
||||
DOCKER_PROVIDERS: gcp
|
||||
staging:
|
||||
if: ${{ contains(github.event.label.name, 'staging:') || github.event.ref == 'refs/heads/main' }}
|
||||
uses: signoz/primus.workflows/.github/workflows/github-trigger.yaml@main
|
||||
secrets: inherit
|
||||
needs: [prepare, go-build]
|
||||
@@ -123,6 +129,6 @@ jobs:
|
||||
PRIMUS_REF: main
|
||||
GITHUB_ENVIRONMENT: staging
|
||||
GITHUB_SILENT: true
|
||||
GITHUB_REPOSITORY_NAME: charts-saas-v3-staging
|
||||
GITHUB_EVENT_NAME: releaser
|
||||
GITHUB_EVENT_PAYLOAD: '{"deployment": "${{ needs.prepare.outputs.deployment }}", "signoz_version": "${{ needs.prepare.outputs.version }}"}'
|
||||
GITHUB_REPOSITORY_NAME: signoz.staging.cl.gcp.deployments
|
||||
GITHUB_EVENT_NAME: release
|
||||
GITHUB_EVENT_PAYLOAD: '{"path": "${{ needs.prepare.outputs.path }}", "image": "us-central1-docker.pkg.dev/signoz-registry/signoz/signoz", "tag": "${{ needs.prepare.outputs.version }}"}'
|
||||
|
||||
2
.github/workflows/e2eci.yaml
vendored
2
.github/workflows/e2eci.yaml
vendored
@@ -88,7 +88,7 @@ jobs:
|
||||
postgres:15 \
|
||||
clickhouse/clickhouse-server:25.12.5 \
|
||||
clickhouse/clickhouse-keeper:25.12.5 \
|
||||
signoz/signoz-schema-migrator:v0.144.9 \
|
||||
signoz/signoz-schema-migrator:v0.144.15 \
|
||||
wiremock/wiremock:2.35.1-1 \
|
||||
| xargs -P 0 -n 1 docker pull -q
|
||||
- name: python
|
||||
|
||||
2
.github/workflows/integrationci.yaml
vendored
2
.github/workflows/integrationci.yaml
vendored
@@ -84,7 +84,7 @@ jobs:
|
||||
clickhouse-version:
|
||||
- 25.12.5
|
||||
schema-migrator-version:
|
||||
- v0.144.6
|
||||
- v0.144.15
|
||||
postgres-version:
|
||||
- 15
|
||||
if: |
|
||||
|
||||
@@ -25613,7 +25613,6 @@ paths:
|
||||
low (z-score {{$value}}).
|
||||
summary: Span ingestion anomaly
|
||||
condition:
|
||||
algorithm: standard
|
||||
compositeQuery:
|
||||
panelType: graph
|
||||
queries:
|
||||
@@ -26280,9 +26279,23 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- EDITOR
|
||||
- rule:create
|
||||
- rule:attach
|
||||
- notification-channel:attach
|
||||
- logs:read
|
||||
- traces:read
|
||||
- metrics:read
|
||||
- audit-logs:read
|
||||
- meter-metrics:read
|
||||
- tokenizer:
|
||||
- EDITOR
|
||||
- rule:create
|
||||
- rule:attach
|
||||
- notification-channel:attach
|
||||
- logs:read
|
||||
- traces:read
|
||||
- metrics:read
|
||||
- audit-logs:read
|
||||
- meter-metrics:read
|
||||
summary: Create alert rule
|
||||
tags:
|
||||
- rules
|
||||
@@ -26327,9 +26340,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- EDITOR
|
||||
- rule:delete
|
||||
- tokenizer:
|
||||
- EDITOR
|
||||
- rule:delete
|
||||
summary: Delete alert rule
|
||||
tags:
|
||||
- rules
|
||||
@@ -26385,9 +26398,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- rule:read
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
- rule:read
|
||||
summary: Get alert rule by ID
|
||||
tags:
|
||||
- rules
|
||||
@@ -26569,7 +26582,6 @@ paths:
|
||||
low (z-score {{$value}}).
|
||||
summary: Span ingestion anomaly
|
||||
condition:
|
||||
algorithm: standard
|
||||
compositeQuery:
|
||||
panelType: graph
|
||||
queries:
|
||||
@@ -27242,9 +27254,27 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- EDITOR
|
||||
- rule:update
|
||||
- rule:attach
|
||||
- rule:detach
|
||||
- notification-channel:attach
|
||||
- notification-channel:detach
|
||||
- logs:read
|
||||
- traces:read
|
||||
- metrics:read
|
||||
- audit-logs:read
|
||||
- meter-metrics:read
|
||||
- tokenizer:
|
||||
- EDITOR
|
||||
- rule:update
|
||||
- rule:attach
|
||||
- rule:detach
|
||||
- notification-channel:attach
|
||||
- notification-channel:detach
|
||||
- logs:read
|
||||
- traces:read
|
||||
- metrics:read
|
||||
- audit-logs:read
|
||||
- meter-metrics:read
|
||||
summary: Patch alert rule
|
||||
tags:
|
||||
- rules
|
||||
@@ -27426,7 +27456,6 @@ paths:
|
||||
low (z-score {{$value}}).
|
||||
summary: Span ingestion anomaly
|
||||
condition:
|
||||
algorithm: standard
|
||||
compositeQuery:
|
||||
panelType: graph
|
||||
queries:
|
||||
@@ -28087,9 +28116,27 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- EDITOR
|
||||
- rule:update
|
||||
- rule:attach
|
||||
- rule:detach
|
||||
- notification-channel:attach
|
||||
- notification-channel:detach
|
||||
- logs:read
|
||||
- traces:read
|
||||
- metrics:read
|
||||
- audit-logs:read
|
||||
- meter-metrics:read
|
||||
- tokenizer:
|
||||
- EDITOR
|
||||
- rule:update
|
||||
- rule:attach
|
||||
- rule:detach
|
||||
- notification-channel:attach
|
||||
- notification-channel:detach
|
||||
- logs:read
|
||||
- traces:read
|
||||
- metrics:read
|
||||
- audit-logs:read
|
||||
- meter-metrics:read
|
||||
summary: Update alert rule
|
||||
tags:
|
||||
- rules
|
||||
@@ -28156,9 +28203,25 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- EDITOR
|
||||
- rule:read
|
||||
- rule:create
|
||||
- rule:attach
|
||||
- notification-channel:attach
|
||||
- logs:read
|
||||
- traces:read
|
||||
- metrics:read
|
||||
- audit-logs:read
|
||||
- meter-metrics:read
|
||||
- tokenizer:
|
||||
- EDITOR
|
||||
- rule:read
|
||||
- rule:create
|
||||
- rule:attach
|
||||
- notification-channel:attach
|
||||
- logs:read
|
||||
- traces:read
|
||||
- metrics:read
|
||||
- audit-logs:read
|
||||
- meter-metrics:read
|
||||
summary: Clone alert rule
|
||||
tags:
|
||||
- rules
|
||||
@@ -29045,7 +29108,6 @@ paths:
|
||||
low (z-score {{$value}}).
|
||||
summary: Span ingestion anomaly
|
||||
condition:
|
||||
algorithm: standard
|
||||
compositeQuery:
|
||||
panelType: graph
|
||||
queries:
|
||||
@@ -29712,9 +29774,23 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- EDITOR
|
||||
- rule:create
|
||||
- rule:attach
|
||||
- notification-channel:attach
|
||||
- logs:read
|
||||
- traces:read
|
||||
- metrics:read
|
||||
- audit-logs:read
|
||||
- meter-metrics:read
|
||||
- tokenizer:
|
||||
- EDITOR
|
||||
- rule:create
|
||||
- rule:attach
|
||||
- notification-channel:attach
|
||||
- logs:read
|
||||
- traces:read
|
||||
- metrics:read
|
||||
- audit-logs:read
|
||||
- meter-metrics:read
|
||||
summary: Test alert rule
|
||||
tags:
|
||||
- rules
|
||||
@@ -31809,9 +31885,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- rule:list
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
- rule:list
|
||||
summary: List alert rules (v3)
|
||||
tags:
|
||||
- rules
|
||||
|
||||
@@ -256,7 +256,7 @@ Tests can be configured using pytest options:
|
||||
- `--sqlite-mode` — SQLite journal mode: `delete` or `wal` (default: `delete`). Only relevant when `--sqlstore-provider=sqlite`.
|
||||
- `--postgres-version` — PostgreSQL version (default: `15`)
|
||||
- `--clickhouse-version` — ClickHouse version, also used for ClickHouse Keeper (default: `25.12.5`)
|
||||
- `--schema-migrator-version` — SigNoz schema migrator version (default: `v0.144.9`)
|
||||
- `--schema-migrator-version` — SigNoz schema migrator version (default: `v0.144.15`)
|
||||
- `--with-web` — Build the frontend into the SigNoz image (required for e2e)
|
||||
|
||||
Example:
|
||||
|
||||
@@ -56,7 +56,6 @@ func NewServer(config signoz.Config, signoz *signoz.SigNoz) (*Server, error) {
|
||||
signoz.SQLStore,
|
||||
integrationsController.GetPipelinesForInstalledIntegrations,
|
||||
reader,
|
||||
signoz.Flagger,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -11,6 +11,8 @@ import axios, { AxiosError, AxiosRequestConfig } from 'axios';
|
||||
// generated API Instance
|
||||
const generatedAPIAxiosInstance = axios.create({
|
||||
baseURL: ENVIRONMENT.baseURL,
|
||||
// The backend binds repeated keys (`states=a&states=b`); axios' default sends `states[]=`.
|
||||
paramsSerializer: { indexes: null },
|
||||
});
|
||||
|
||||
let generatedAPIQueryKeyHeaderContext: Record<string, unknown> | undefined;
|
||||
|
||||
@@ -630,7 +630,6 @@ describe('Footer utils', () => {
|
||||
expect(props.ruleType).toBe('anomaly_rule');
|
||||
expect(props.alertType).toBe(AlertTypes.METRICS_BASED_ALERT);
|
||||
expect(props.schemaVersion).toBe('v2alpha1');
|
||||
expect(props.condition.algorithm).toBe('standard');
|
||||
expect(props.condition.seasonality).toBe('daily');
|
||||
expect(props.condition.thresholds?.spec[0]).toMatchObject({
|
||||
target: 3,
|
||||
|
||||
@@ -324,7 +324,6 @@ export function buildCreateAnomalyAlertRulePayload(
|
||||
condition: {
|
||||
...payload.condition,
|
||||
thresholds: { kind: 'basic', spec: thresholds },
|
||||
algorithm: thresholdState.algorithm,
|
||||
seasonality: thresholdState.seasonality,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -323,7 +323,6 @@ describe('CreateAlert utils', () => {
|
||||
ruleType: 'anomaly_rule',
|
||||
condition: {
|
||||
...defaultPostableAlertRuleV2.condition,
|
||||
algorithm: 'standard',
|
||||
seasonality: 'weekly',
|
||||
thresholds: {
|
||||
kind: 'basic',
|
||||
@@ -349,7 +348,6 @@ describe('CreateAlert utils', () => {
|
||||
expect(getThresholdStateFromAlertDef(anomalyDef)).toMatchObject({
|
||||
operator: AlertThresholdOperator.IS_BELOW,
|
||||
thresholds: [{ thresholdValue: 3 }],
|
||||
algorithm: 'standard',
|
||||
seasonality: 'weekly',
|
||||
});
|
||||
});
|
||||
|
||||
@@ -274,8 +274,6 @@ export function getThresholdStateFromAlertDef(
|
||||
matchType:
|
||||
alertDef.condition.thresholds?.spec[0].matchType ||
|
||||
AlertThresholdMatchType.AT_LEAST_ONCE,
|
||||
algorithm:
|
||||
alertDef.condition.algorithm || INITIAL_ALERT_THRESHOLD_STATE.algorithm,
|
||||
seasonality:
|
||||
alertDef.condition.seasonality || INITIAL_ALERT_THRESHOLD_STATE.seasonality,
|
||||
};
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useListRulesV3 } from 'api/generated/services/rules';
|
||||
import {
|
||||
type ListRulesV3200,
|
||||
type ListRulesV3Params,
|
||||
RuletypesAlertStateDTO,
|
||||
type RuletypesListableRuleDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { GeneratedAPIInstance } from 'api/generatedAPIInstance';
|
||||
|
||||
const HOME_ALERT_RULES_LIMIT = 5;
|
||||
|
||||
@@ -23,18 +21,7 @@ interface HomeAlertRules {
|
||||
|
||||
export function useHomeAlertRules(): HomeAlertRules {
|
||||
const firing = useListRulesV3(FIRING_RULES_PARAMS, {
|
||||
query: {
|
||||
cacheTime: 0,
|
||||
// The backend binds repeated `states=` keys; axios' default sends `states[]=`.
|
||||
queryFn: ({ signal }) =>
|
||||
GeneratedAPIInstance<ListRulesV3200>({
|
||||
url: '/api/v3/rules',
|
||||
method: 'GET',
|
||||
params: FIRING_RULES_PARAMS,
|
||||
paramsSerializer: { indexes: null },
|
||||
signal,
|
||||
}),
|
||||
},
|
||||
query: { cacheTime: 0 },
|
||||
});
|
||||
const firingRules = firing.data?.data.rules;
|
||||
const latest = useListRulesV3(
|
||||
|
||||
@@ -104,5 +104,5 @@ describe('AI observability Explorer', () => {
|
||||
...defaultOptionsQuery,
|
||||
selectColumns: [],
|
||||
});
|
||||
});
|
||||
}, 15_000);
|
||||
});
|
||||
|
||||
@@ -31,6 +31,8 @@ jest.mock('@floating-ui/dom', () => ({
|
||||
Promise.resolve({ x: 0, y: 0, placement, strategy, middlewareData: {} }),
|
||||
}));
|
||||
|
||||
jest.setTimeout(15_000);
|
||||
|
||||
const VIEW_1_ORDER_BY = JSON.stringify({ columnName: 'name', order: 'asc' });
|
||||
const VIEW_1_QUERY = "severity = 'critical'";
|
||||
|
||||
|
||||
@@ -3,13 +3,11 @@ import logEvent from 'api/common/logEvent';
|
||||
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
|
||||
import { useListRulesV3 } from 'api/generated/services/rules';
|
||||
import type {
|
||||
ListRulesV3200,
|
||||
ListRulesV3Params,
|
||||
RenderErrorResponseDTO,
|
||||
RuletypesLabelPairDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import type { AxiosError } from 'axios';
|
||||
import { GeneratedAPIInstance } from 'api/generatedAPIInstance';
|
||||
import { isUndefined } from 'lodash-es';
|
||||
|
||||
import type { AlertRule } from './types';
|
||||
@@ -35,18 +33,7 @@ export function useAlertRulesData(
|
||||
const hasLoggedEvent = useRef(false);
|
||||
|
||||
const rulesResponse = useListRulesV3(params, {
|
||||
query: {
|
||||
keepPreviousData: true,
|
||||
// The backend binds repeated `states=` keys; axios' default sends `states[]=`.
|
||||
queryFn: ({ signal }) =>
|
||||
GeneratedAPIInstance<ListRulesV3200>({
|
||||
url: '/api/v3/rules',
|
||||
method: 'GET',
|
||||
params,
|
||||
paramsSerializer: { indexes: null },
|
||||
signal,
|
||||
}),
|
||||
},
|
||||
query: { keepPreviousData: true },
|
||||
});
|
||||
|
||||
const rules = useMemo(
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { QueryParams } from 'constants/query';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { back, getCurrentLocation } from 'lib/router/navigation';
|
||||
import { act, AllTheProviders, renderHook, waitFor } from 'tests/test-utils';
|
||||
|
||||
// jest.config.ts maps `hooks/useSafeNavigate` to a mock; the `.ts` path loads the real hook.
|
||||
const { useSafeNavigate } = jest.requireActual<
|
||||
typeof import('hooks/useSafeNavigate')
|
||||
>('hooks/useSafeNavigate.ts');
|
||||
|
||||
describe('useSafeNavigate', () => {
|
||||
it('adds a history entry for replace: false even when the target adds params', async () => {
|
||||
const initialSearch = `?${QueryParams.relativeTime}=15m`;
|
||||
const { result } = renderHook(() => useSafeNavigate(), {
|
||||
wrapper: ({ children }): JSX.Element => (
|
||||
<AllTheProviders initialRoute={`${ROUTES.LOGS_EXPLORER}${initialSearch}`}>
|
||||
{children}
|
||||
</AllTheProviders>
|
||||
),
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.safeNavigate(
|
||||
`${ROUTES.LOGS_EXPLORER}?${QueryParams.startTime}=1000`,
|
||||
{ replace: false },
|
||||
);
|
||||
});
|
||||
act(() => back());
|
||||
|
||||
await waitFor(() => expect(getCurrentLocation().search).toBe(initialSearch));
|
||||
});
|
||||
});
|
||||
@@ -140,7 +140,7 @@ export const useSafeNavigate = (
|
||||
|
||||
const navigationOptions = {
|
||||
...options,
|
||||
replace: isDefaultParamsNavigation || options?.replace,
|
||||
replace: options?.replace ?? isDefaultParamsNavigation,
|
||||
};
|
||||
|
||||
if (typeof to === 'string') {
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
*/
|
||||
|
||||
import { rest, type ResponseComposition, type RestContext } from 'msw';
|
||||
import type { RuletypesListableRuleDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { screen, userEvent, within } from 'storybook/test';
|
||||
|
||||
import {
|
||||
@@ -12,7 +13,10 @@ import {
|
||||
toggleControl,
|
||||
} from '@/storybook/controls/controls';
|
||||
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import { accessFor } from '@/storybook/access/access';
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
import { useAlertRuleViewsStore } from 'container/ListAlertRules/useAlertRuleViewsStore';
|
||||
import { componentPermission } from 'utils/permission';
|
||||
import { DEFAULT_RULE_LIST_FILTER } from 'container/ListAlertRules/utils';
|
||||
import {
|
||||
DEFAULT_RULE_VIEW,
|
||||
@@ -281,3 +285,37 @@ export const runRowAction = async (
|
||||
await userEvent.click(actions);
|
||||
await userEvent.click(await screen.findByRole('menuitem', { name }));
|
||||
};
|
||||
|
||||
export type AlertRulesArgs = PageStoryArgs<typeof alertRulesMocks>;
|
||||
|
||||
export const listedRules = (
|
||||
args: AlertRulesArgs,
|
||||
): RuletypesListableRuleDTO[] => {
|
||||
const params = new URL(listRoute(args.view), 'http://localhost').searchParams;
|
||||
if (
|
||||
args.dataState !== 'loaded' ||
|
||||
(args.invalidQuery !== 'off' && params.get('query'))
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return alertRulesPage(
|
||||
args.rules,
|
||||
{ severity: args.ruleSeverity, state: args.ruleState },
|
||||
params,
|
||||
).data.rules;
|
||||
};
|
||||
|
||||
export const hasRowMenu = (args: AlertRulesArgs): boolean =>
|
||||
listedRules(args).length > 0 &&
|
||||
componentPermission.action.includes(
|
||||
accessFor(args.access, args.permissions, args.revoked).legacyRole,
|
||||
);
|
||||
|
||||
export const showsNoRulesPage = (args: AlertRulesArgs): boolean =>
|
||||
args.view === DEFAULT_RULE_VIEW &&
|
||||
args.dataState === 'loaded' &&
|
||||
args.rules === 0;
|
||||
|
||||
export const listsSavedViews = (args: AlertRulesArgs): boolean =>
|
||||
args.ruleViews > 0 && args.ruleViewsState === 'success';
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
|
||||
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
|
||||
import { alertRulesMocks } from './AlertRules.stories.mocks';
|
||||
import {
|
||||
alertRulesMocks,
|
||||
type AlertRulesArgs,
|
||||
} from './AlertRules.stories.mocks';
|
||||
import {
|
||||
cloneAlert,
|
||||
copyLabel,
|
||||
@@ -22,8 +24,6 @@ import {
|
||||
import AlertList from '../../index';
|
||||
import { RULE_MAX } from '../../stories/__story_mockdata__/alerts';
|
||||
|
||||
type AlertRulesArgs = PageStoryArgs<typeof alertRulesMocks>;
|
||||
|
||||
const pageStory = storyMocks(alertRulesMocks, { layout: 'app' });
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,20 +3,22 @@
|
||||
* Do not hand-edit: regenerate instead.
|
||||
*/
|
||||
|
||||
import { DEFAULT_RULE_VIEW } from 'container/ListAlertRules/list.config';
|
||||
import { expect, screen, userEvent, within } from 'storybook/test';
|
||||
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
import { RuletypesAlertStateDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
|
||||
|
||||
import {
|
||||
alertRulesMocks,
|
||||
type AlertRulesArgs,
|
||||
hasRowMenu,
|
||||
listedRules,
|
||||
listsSavedViews,
|
||||
runRowAction,
|
||||
showsNoRulesPage,
|
||||
untilLoaded,
|
||||
} from '../AlertRules.stories.mocks';
|
||||
|
||||
interface PlayContext {
|
||||
canvasElement: HTMLElement;
|
||||
args: PageStoryArgs<typeof alertRulesMocks>;
|
||||
args: AlertRulesArgs;
|
||||
}
|
||||
|
||||
// A row's rename and delete only take the pointer while the row is hovered,
|
||||
@@ -25,10 +27,15 @@ const hoverActions = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
|
||||
export const openQuerySuggestions = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (listedRules(args).length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const canvas = within(canvasElement);
|
||||
// The labels come with the rule list, so the box is opened once rows are in.
|
||||
await canvas.findAllByTestId('alert-actions', undefined, untilLoaded);
|
||||
await canvas.findAllByTestId(/^alert-row-.+-name$/, undefined, untilLoaded);
|
||||
const search = canvas.getByTestId('alert-rules-list-search');
|
||||
await userEvent.click(search.querySelector('.cm-content') ?? search);
|
||||
await screen.findByText('labels.team');
|
||||
@@ -49,7 +56,12 @@ export const openSaveViewPopover = async ({
|
||||
|
||||
export const openRenameViewPopover = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!listsSavedViews(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await hoverActions.click(
|
||||
await within(canvasElement).findByTestId(
|
||||
'alert-rules-view-rename-view-1',
|
||||
@@ -57,12 +69,17 @@ export const openRenameViewPopover = async ({
|
||||
untilLoaded,
|
||||
),
|
||||
);
|
||||
await screen.findByText('Rename view');
|
||||
await screen.findAllByText('Rename view');
|
||||
};
|
||||
|
||||
export const openDeleteViewConfirm = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!listsSavedViews(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await hoverActions.click(
|
||||
await within(canvasElement).findByTestId(
|
||||
'alert-rules-view-delete-view-1',
|
||||
@@ -75,7 +92,12 @@ export const openDeleteViewConfirm = async ({
|
||||
|
||||
export const openRowActions = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!hasRowMenu(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [actions] = await within(canvasElement).findAllByTestId(
|
||||
'alert-actions',
|
||||
undefined,
|
||||
@@ -88,7 +110,12 @@ export const openRowActions = async ({
|
||||
|
||||
export const openDisabledRuleActions = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!hasRowMenu(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [actions] = await within(canvasElement).findAllByTestId(
|
||||
'alert-actions',
|
||||
undefined,
|
||||
@@ -96,12 +123,21 @@ export const openDisabledRuleActions = async ({
|
||||
);
|
||||
|
||||
await userEvent.click(actions);
|
||||
await screen.findByText(/^enable$/i);
|
||||
await screen.findByText(
|
||||
listedRules(args)[0].state === RuletypesAlertStateDTO.disabled
|
||||
? /^enable$/i
|
||||
: /^disable$/i,
|
||||
);
|
||||
};
|
||||
|
||||
export const openColumnPicker = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (showsNoRulesPage(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await userEvent.click(
|
||||
await within(canvasElement).findByTestId(
|
||||
'alert-columns-button',
|
||||
@@ -116,11 +152,7 @@ export const openStatesFilter = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (
|
||||
args.rules === 0 &&
|
||||
args.view === DEFAULT_RULE_VIEW &&
|
||||
args.dataState === 'loaded'
|
||||
) {
|
||||
if (showsNoRulesPage(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -144,6 +176,10 @@ export const toggleAlert = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!hasRowMenu(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await runRowAction(canvasElement, /^(enable|disable)$/i);
|
||||
if (args.toggleState === 'success') {
|
||||
await expect(
|
||||
@@ -156,6 +192,10 @@ export const cloneAlert = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!hasRowMenu(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await runRowAction(canvasElement, /^clone$/i);
|
||||
if (args.cloneState === 'success') {
|
||||
await expect(
|
||||
@@ -168,6 +208,10 @@ export const deleteAlert = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!hasRowMenu(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await runRowAction(canvasElement, /^delete$/i);
|
||||
if (args.deleteState === 'success') {
|
||||
await expect(
|
||||
@@ -176,7 +220,11 @@ export const deleteAlert = async ({
|
||||
}
|
||||
};
|
||||
|
||||
export const copyLabel = async (): Promise<void> => {
|
||||
export const copyLabel = async ({ args }: PlayContext): Promise<void> => {
|
||||
if (!args.tooltipsOpen || listedRules(args).length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [copy] = await screen.findAllByRole(
|
||||
'button',
|
||||
{ name: 'Copy to clipboard' },
|
||||
@@ -184,5 +232,7 @@ export const copyLabel = async (): Promise<void> => {
|
||||
);
|
||||
|
||||
await userEvent.click(copy);
|
||||
await expect(await screen.findByText(/copied! use in search/i)).toBeVisible();
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText(/copied! use in search/i)).toBeVisible(),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -16,6 +16,12 @@ import {
|
||||
type GetDashboardV2200,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import ROUTES from 'constants/routes';
|
||||
import {
|
||||
buildDashboardDeletePermission,
|
||||
buildDashboardReadPermission,
|
||||
buildDashboardUpdatePermission,
|
||||
DashboardCreatePermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/dashboard.permissions';
|
||||
import {
|
||||
expect,
|
||||
mocked,
|
||||
@@ -24,7 +30,9 @@ import {
|
||||
waitFor,
|
||||
within,
|
||||
} from 'storybook/test';
|
||||
import { LicensePlatform } from 'types/api/licensesV3/getActive';
|
||||
|
||||
import { grantsAll } from '@/storybook/access/access';
|
||||
import {
|
||||
choiceControl,
|
||||
countControl,
|
||||
@@ -32,6 +40,8 @@ import {
|
||||
toggleControl,
|
||||
} from '@/storybook/controls/controls';
|
||||
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import { appShellMocks } from '@/storybook/globals/appShellMocks';
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
|
||||
import {
|
||||
orgUsersResponse,
|
||||
@@ -67,6 +77,8 @@ import {
|
||||
type DashboardViewId,
|
||||
findBuiltinView,
|
||||
} from '../list.config';
|
||||
import { LIST_CHECKS } from '../constants/permissions';
|
||||
import type { DashboardListItem } from '../utils/helpers';
|
||||
|
||||
const LIST = 'Dashboards · list';
|
||||
const VIEWS = 'Dashboards · views';
|
||||
@@ -528,6 +540,81 @@ export const dashboardsListMocks = defineStoryMocks({
|
||||
},
|
||||
});
|
||||
|
||||
export type DashboardsListArgs = PageStoryArgs<typeof dashboardsListMocks>;
|
||||
|
||||
const PAGE_SIZE = 20;
|
||||
|
||||
export const canList = (args: DashboardsListArgs): boolean =>
|
||||
grantsAll(args, ...LIST_CHECKS);
|
||||
|
||||
/** `AuthZButton` leaves New dashboard enabled when the check itself fails. */
|
||||
export const canCreate = (args: DashboardsListArgs): boolean =>
|
||||
args.authzState === 'error' || grantsAll(args, DashboardCreatePermission);
|
||||
|
||||
export const canUpdate = (
|
||||
args: DashboardsListArgs,
|
||||
row: DashboardListItem,
|
||||
): boolean =>
|
||||
grantsAll(
|
||||
args,
|
||||
buildDashboardReadPermission(row.id),
|
||||
buildDashboardUpdatePermission(row.id),
|
||||
);
|
||||
|
||||
export const canDuplicate = (
|
||||
args: DashboardsListArgs,
|
||||
row: DashboardListItem,
|
||||
): boolean =>
|
||||
grantsAll(
|
||||
args,
|
||||
buildDashboardReadPermission(row.id),
|
||||
DashboardCreatePermission,
|
||||
);
|
||||
|
||||
export const canDelete = (
|
||||
args: DashboardsListArgs,
|
||||
row: DashboardListItem,
|
||||
): boolean =>
|
||||
!row.locked && grantsAll(args, buildDashboardDeletePermission(row.id));
|
||||
|
||||
export const listedDashboards = (
|
||||
args: DashboardsListArgs,
|
||||
): DashboardListItem[] => {
|
||||
if (args.dataState !== 'loaded' || args.invalidQuery || !canList(args)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const view = findBuiltinView(args.view);
|
||||
const rows = dashboardsListResponse({
|
||||
count: args.dashboards,
|
||||
offset: 0,
|
||||
limit: view?.clientFilter ? args.dashboards : PAGE_SIZE,
|
||||
markers: args.markers,
|
||||
query:
|
||||
new URL(listRoute(args.view), 'http://localhost').searchParams.get(
|
||||
'query',
|
||||
) ?? '',
|
||||
}).data.dashboards;
|
||||
|
||||
return view?.clientFilter
|
||||
? view.clientFilter(rows, {
|
||||
userEmail: STORY_USER_EMAIL,
|
||||
recent: recentDashboardIds(RECENT_COUNT),
|
||||
})
|
||||
: rows;
|
||||
};
|
||||
|
||||
export const showsWorkspaceEmpty = (args: DashboardsListArgs): boolean =>
|
||||
args.view === DEFAULT_DASHBOARD_VIEW &&
|
||||
args.dataState === 'loaded' &&
|
||||
!args.invalidQuery &&
|
||||
canList(args) &&
|
||||
args.dashboards === 0;
|
||||
|
||||
export const isCloudTenant = (args: DashboardsListArgs): boolean =>
|
||||
appShellMocks.config?.(appShellMocks.read(args)).appContext?.activeLicense
|
||||
?.platform === LicensePlatform.CLOUD;
|
||||
|
||||
/** Opens the actions menu of the row at `index`. */
|
||||
export const openRowActions = async (
|
||||
canvasElement: HTMLElement,
|
||||
@@ -541,7 +628,7 @@ export const openRowActions = async (
|
||||
);
|
||||
|
||||
await userEvent.click(triggers[index]);
|
||||
await screen.findByText('Rename');
|
||||
await screen.findByTestId('dashboard-action-delete');
|
||||
};
|
||||
|
||||
/** Picks a row action, retrying while its permission check still disables it. */
|
||||
@@ -574,10 +661,11 @@ export const TOAST_TIMEOUT = 10000;
|
||||
|
||||
export const openLegacyDialog = async (
|
||||
canvasElement: HTMLElement,
|
||||
index: number,
|
||||
): Promise<void> => {
|
||||
await userEvent.click(
|
||||
await within(canvasElement).findByTestId(
|
||||
'dashboard-title-4',
|
||||
`dashboard-title-${index}`,
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
),
|
||||
@@ -587,8 +675,9 @@ export const openLegacyDialog = async (
|
||||
|
||||
export const retryMigration = async (
|
||||
canvasElement: HTMLElement,
|
||||
index: number,
|
||||
): Promise<void> => {
|
||||
await openLegacyDialog(canvasElement);
|
||||
await openLegacyDialog(canvasElement, index);
|
||||
const retry = await screen.findByTestId('legacy-dashboard-retry-migration');
|
||||
|
||||
await waitFor(
|
||||
|
||||
@@ -1,47 +1,41 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
|
||||
import {
|
||||
dashboardsListMocks,
|
||||
type DashboardsListArgs,
|
||||
longQueryRoute,
|
||||
overflowingRows,
|
||||
} from './DashboardsListPage.stories.mocks';
|
||||
import {
|
||||
copyLegacyDashboardId,
|
||||
createDashboardFails,
|
||||
createDashboard,
|
||||
deleteDashboard,
|
||||
deleteViewFails,
|
||||
deleteView,
|
||||
duplicateDashboard,
|
||||
importCreateFails,
|
||||
importDashboard,
|
||||
importInvalidImage,
|
||||
importInvalidJson,
|
||||
lockDashboard,
|
||||
migrateDashboard,
|
||||
migrationFails,
|
||||
openCreatedByFilter,
|
||||
openEditTagsDialog,
|
||||
openFirstRowActions,
|
||||
openRenameDialog,
|
||||
openSaveViewPopover,
|
||||
openTemplateTab,
|
||||
pinFails,
|
||||
pinPastLimit,
|
||||
pinDashboard,
|
||||
renameDashboard,
|
||||
renameViewFails,
|
||||
saveViewFails,
|
||||
renameView,
|
||||
saveView,
|
||||
submitTemplateRequest,
|
||||
templateRequestFails,
|
||||
templateRequestRejected,
|
||||
unlockDashboard,
|
||||
unpinFails,
|
||||
unpinDashboard,
|
||||
updateTags,
|
||||
} from './__story_mockdata__/dashboardsList.play';
|
||||
|
||||
import DashboardsListPage from '../DashboardsListPage';
|
||||
|
||||
type DashboardsListArgs = PageStoryArgs<typeof dashboardsListMocks>;
|
||||
|
||||
const pageStory = storyMocks(dashboardsListMocks, { layout: 'app' });
|
||||
|
||||
/**
|
||||
@@ -182,21 +176,21 @@ export const DashboardDeletedToast: Story = {
|
||||
/** Pinning past the limit: the backend refuses with a 409. */
|
||||
export const PinLimitToast: Story = {
|
||||
args: { pinWrite: 'limit' },
|
||||
play: pinPastLimit,
|
||||
play: pinDashboard,
|
||||
parameters: { allowConsoleErrors: true },
|
||||
};
|
||||
|
||||
/** A pin the backend failed to write. */
|
||||
export const PinFailedToast: Story = {
|
||||
args: { pinWrite: 'error' },
|
||||
play: pinFails,
|
||||
play: pinDashboard,
|
||||
parameters: { allowConsoleErrors: true },
|
||||
};
|
||||
|
||||
/** An unpin the backend failed to write, from the first (pinned) row. */
|
||||
export const UnpinFailedToast: Story = {
|
||||
args: { pinWrite: 'error' },
|
||||
play: unpinFails,
|
||||
play: unpinDashboard,
|
||||
parameters: { allowConsoleErrors: true },
|
||||
};
|
||||
|
||||
@@ -213,14 +207,14 @@ export const DashboardMigratedToast: Story = {
|
||||
/** Retry migration of the legacy dashboard refused by the backend. */
|
||||
export const DashboardMigrationFailedToast: Story = {
|
||||
args: { migrationWrite: 'error' },
|
||||
play: migrationFails,
|
||||
play: migrateDashboard,
|
||||
parameters: { allowConsoleErrors: true },
|
||||
};
|
||||
|
||||
/** The Blank tab's create failing: the toast raised beside the error modal. */
|
||||
export const CreateDashboardFailedToast: Story = {
|
||||
args: { createWrite: 'error' },
|
||||
play: createDashboardFails,
|
||||
play: createDashboard,
|
||||
parameters: { allowConsoleErrors: true },
|
||||
};
|
||||
|
||||
@@ -232,7 +226,7 @@ export const ImportJsonInvalidImageToast: Story = {
|
||||
/** A valid dashboard file the create endpoint refuses. */
|
||||
export const ImportJsonCreateFailedToast: Story = {
|
||||
args: { createWrite: 'error' },
|
||||
play: importCreateFails,
|
||||
play: importDashboard,
|
||||
parameters: { allowConsoleErrors: true },
|
||||
};
|
||||
|
||||
@@ -244,33 +238,33 @@ export const TemplateRequestSubmittedToast: Story = {
|
||||
/** A template request the analytics endpoint answered with a failure. */
|
||||
export const TemplateRequestFailedToast: Story = {
|
||||
args: { templateRequest: 'error' },
|
||||
play: templateRequestFails,
|
||||
play: submitTemplateRequest,
|
||||
};
|
||||
|
||||
/** A template request that threw before an answer came back. */
|
||||
export const TemplateRequestRejectedToast: Story = {
|
||||
args: { templateRequest: 'rejected' },
|
||||
play: templateRequestRejected,
|
||||
play: submitTemplateRequest,
|
||||
};
|
||||
|
||||
/** Saving the current filters as a view, refused by the backend. */
|
||||
export const SaveViewFailedToast: Story = {
|
||||
args: { viewWrite: 'error' },
|
||||
play: saveViewFails,
|
||||
play: saveView,
|
||||
parameters: { allowConsoleErrors: true },
|
||||
};
|
||||
|
||||
/** Renaming a saved view, refused by the backend. */
|
||||
export const RenameViewFailedToast: Story = {
|
||||
args: { viewWrite: 'error' },
|
||||
play: renameViewFails,
|
||||
play: renameView,
|
||||
parameters: { allowConsoleErrors: true },
|
||||
};
|
||||
|
||||
/** Deleting a saved view, refused by the backend. */
|
||||
export const DeleteViewFailedToast: Story = {
|
||||
args: { viewWrite: 'error' },
|
||||
play: deleteViewFails,
|
||||
play: deleteView,
|
||||
parameters: { allowConsoleErrors: true },
|
||||
};
|
||||
|
||||
|
||||
@@ -5,30 +5,68 @@
|
||||
|
||||
import { expect, screen, userEvent, within } from 'storybook/test';
|
||||
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
|
||||
import {
|
||||
canCreate,
|
||||
canDelete,
|
||||
canDuplicate,
|
||||
canList,
|
||||
canUpdate,
|
||||
clickRowAction,
|
||||
dashboardsListMocks,
|
||||
type DashboardsListArgs,
|
||||
isCloudTenant,
|
||||
listedDashboards,
|
||||
openLegacyDialog,
|
||||
openRowActions,
|
||||
pickRowAction,
|
||||
requestTemplate,
|
||||
retryMigration,
|
||||
showsWorkspaceEmpty,
|
||||
TOAST_TIMEOUT,
|
||||
uploadDashboardJson,
|
||||
} from '../DashboardsListPage.stories.mocks';
|
||||
import type { TemplateRequest } from './dashboardsList';
|
||||
|
||||
interface PlayContext {
|
||||
canvasElement: HTMLElement;
|
||||
args: PageStoryArgs<typeof dashboardsListMocks>;
|
||||
args: DashboardsListArgs;
|
||||
}
|
||||
|
||||
const IMPORTED_SPEC = { layouts: [], panels: {}, variables: [] };
|
||||
|
||||
const TEMPLATE_REQUEST_TOASTS = {
|
||||
success: 'Dashboard request submitted',
|
||||
error: 'Event rejected',
|
||||
rejected: 'Something went wrong',
|
||||
} satisfies Record<TemplateRequest, string>;
|
||||
|
||||
const openNewDashboard = async (canvasElement: HTMLElement): Promise<void> => {
|
||||
await userEvent.click(
|
||||
await within(canvasElement).findByTestId(
|
||||
'new-dashboard-cta',
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const canEditRow = (args: DashboardsListArgs, index: number): boolean => {
|
||||
const row = listedDashboards(args)[index];
|
||||
|
||||
return !!row && !row.legacy && !row.locked && canUpdate(args, row);
|
||||
};
|
||||
|
||||
export const openCreatedByFilter = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (
|
||||
!canList(args) ||
|
||||
args.dataState !== 'loaded' ||
|
||||
showsWorkspaceEmpty(args)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const filter = await within(canvasElement).findByTestId(
|
||||
'dashboards-filter-created-by',
|
||||
{},
|
||||
@@ -37,18 +75,18 @@ export const openCreatedByFilter = async ({
|
||||
|
||||
await userEvent.click(filter.querySelector('.ant-select-selector') ?? filter);
|
||||
await userEvent.click(await screen.findByText('Ada (ada@signoz.io)'));
|
||||
await screen.findByRole('checkbox', { checked: true });
|
||||
await screen.findAllByRole('checkbox', { checked: true });
|
||||
};
|
||||
|
||||
export const openTemplateTab = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
const canvas = within(canvasElement);
|
||||
|
||||
await userEvent.click(
|
||||
await canvas.findByTestId('new-dashboard-cta', {}, { timeout: 10000 }),
|
||||
);
|
||||
if (!canCreate(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await openNewDashboard(canvasElement);
|
||||
await expect(
|
||||
await screen.findByRole('dialog', {}, { timeout: 10000 }),
|
||||
).toHaveTextContent('New dashboard');
|
||||
@@ -58,12 +96,13 @@ export const openTemplateTab = async ({
|
||||
|
||||
export const importInvalidJson = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
const canvas = within(canvasElement);
|
||||
if (!canCreate(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await userEvent.click(
|
||||
await canvas.findByTestId('new-dashboard-cta', {}, { timeout: 10000 }),
|
||||
);
|
||||
await openNewDashboard(canvasElement);
|
||||
await userEvent.click(await screen.findByText('Import JSON'));
|
||||
await userEvent.click(await screen.findByTestId('import-json-submit'));
|
||||
await screen.findByText(/error loading json/i);
|
||||
@@ -73,13 +112,23 @@ export const importInvalidJson = async ({
|
||||
|
||||
export const openFirstRowActions = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (listedDashboards(args).length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
await openRowActions(canvasElement, 0);
|
||||
};
|
||||
|
||||
export const openRenameDialog = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!canEditRow(args, 1)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await openRowActions(canvasElement, 1);
|
||||
await pickRowAction('Rename');
|
||||
await screen.findByRole('dialog', { name: 'Rename dashboard' });
|
||||
@@ -87,7 +136,12 @@ export const openRenameDialog = async ({
|
||||
|
||||
export const openEditTagsDialog = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!canEditRow(args, 1)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await openRowActions(canvasElement, 1);
|
||||
await pickRowAction(/^(Edit|Add) Tags$/);
|
||||
await screen.findByRole('dialog', { name: /^(Edit|Add) tags$/ });
|
||||
@@ -95,7 +149,12 @@ export const openEditTagsDialog = async ({
|
||||
|
||||
export const openSaveViewPopover = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!canList(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await userEvent.click(
|
||||
await within(canvasElement).findByRole(
|
||||
'button',
|
||||
@@ -110,6 +169,10 @@ export const renameDashboard = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!canEditRow(args, 1)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await openRowActions(canvasElement, 1);
|
||||
await pickRowAction('Rename');
|
||||
const input = await screen.findByTestId('rename-dashboard-input');
|
||||
@@ -126,6 +189,10 @@ export const updateTags = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!canEditRow(args, 1)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await openRowActions(canvasElement, 1);
|
||||
await pickRowAction(/^(Edit|Add) Tags$/);
|
||||
const input = await screen.findByPlaceholderText('key:value (press Enter)');
|
||||
@@ -141,11 +208,37 @@ export const duplicateDashboard = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
const row = listedDashboards(args)[1];
|
||||
if (!row || row.legacy || !canDuplicate(args, row)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await openRowActions(canvasElement, 1);
|
||||
await clickRowAction('dashboard-action-duplicate');
|
||||
if (args.rowWrite === 'success') {
|
||||
await screen.findByText(
|
||||
'Duplicated "API latency and errors"',
|
||||
`Duplicated "${row.name}"`,
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleLockAt = async (
|
||||
canvasElement: HTMLElement,
|
||||
args: DashboardsListArgs,
|
||||
index: number,
|
||||
): Promise<void> => {
|
||||
const row = listedDashboards(args)[index];
|
||||
if (!row || row.legacy || !canUpdate(args, row)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await openRowActions(canvasElement, index);
|
||||
await clickRowAction('dashboard-action-lock');
|
||||
if (args.rowWrite === 'success') {
|
||||
await screen.findByText(
|
||||
row.locked ? 'Dashboard unlocked' : 'Dashboard locked',
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
);
|
||||
@@ -155,29 +248,22 @@ export const duplicateDashboard = async ({
|
||||
export const lockDashboard = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
await openRowActions(canvasElement, 1);
|
||||
await clickRowAction('dashboard-action-lock');
|
||||
if (args.rowWrite === 'success') {
|
||||
await screen.findByText('Dashboard locked', {}, { timeout: TOAST_TIMEOUT });
|
||||
}
|
||||
};
|
||||
}: PlayContext): Promise<void> => toggleLockAt(canvasElement, args, 1);
|
||||
|
||||
export const unlockDashboard = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
await openRowActions(canvasElement, 0);
|
||||
await clickRowAction('dashboard-action-lock');
|
||||
if (args.rowWrite === 'success') {
|
||||
await screen.findByText('Dashboard unlocked', {}, { timeout: TOAST_TIMEOUT });
|
||||
}
|
||||
};
|
||||
}: PlayContext): Promise<void> => toggleLockAt(canvasElement, args, 0);
|
||||
|
||||
export const deleteDashboard = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
const row = listedDashboards(args)[1];
|
||||
if (!row || !canDelete(args, row)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await openRowActions(canvasElement, 1);
|
||||
await clickRowAction('dashboard-action-delete');
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
@@ -194,61 +280,73 @@ export const deleteDashboard = async ({
|
||||
}
|
||||
};
|
||||
|
||||
export const pinPastLimit = async ({
|
||||
export const pinDashboard = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
const index = listedDashboards(args).findIndex((row) => !row.pinned);
|
||||
if (index < 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
await userEvent.click(
|
||||
await within(canvasElement).findByTestId(
|
||||
'dashboard-pin-3',
|
||||
`dashboard-pin-${index}`,
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
),
|
||||
);
|
||||
await screen.findByText(
|
||||
/You can pin up to 10 dashboards/,
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
);
|
||||
if (args.pinWrite === 'limit') {
|
||||
await screen.findByText(
|
||||
/You can pin up to 10 dashboards/,
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
);
|
||||
}
|
||||
if (args.pinWrite === 'error') {
|
||||
await screen.findByText(
|
||||
'Failed to pin dashboard.',
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export const pinFails = async ({
|
||||
export const unpinDashboard = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
await userEvent.click(
|
||||
await within(canvasElement).findByTestId(
|
||||
'dashboard-pin-3',
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
),
|
||||
);
|
||||
await screen.findByText(
|
||||
'Failed to pin dashboard.',
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
);
|
||||
};
|
||||
const index = listedDashboards(args).findIndex((row) => row.pinned);
|
||||
if (index < 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
export const unpinFails = async ({
|
||||
canvasElement,
|
||||
}: PlayContext): Promise<void> => {
|
||||
await userEvent.click(
|
||||
await within(canvasElement).findByTestId(
|
||||
'dashboard-pin-0',
|
||||
`dashboard-pin-${index}`,
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
),
|
||||
);
|
||||
await screen.findByText(
|
||||
'Failed to unpin dashboard.',
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
);
|
||||
if (args.pinWrite === 'error') {
|
||||
await screen.findByText(
|
||||
'Failed to unpin dashboard.',
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export const copyLegacyDashboardId = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
await openLegacyDialog(canvasElement);
|
||||
const index = listedDashboards(args).findIndex((row) => row.legacy);
|
||||
if (index < 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
await openLegacyDialog(canvasElement, index);
|
||||
await userEvent.click(await screen.findByTestId('legacy-dashboard-copy-id'));
|
||||
await screen.findByText('Dashboard ID copied', {}, { timeout: TOAST_TIMEOUT });
|
||||
};
|
||||
@@ -257,7 +355,13 @@ export const migrateDashboard = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
await retryMigration(canvasElement);
|
||||
const rows = listedDashboards(args);
|
||||
const index = rows.findIndex((row) => row.legacy);
|
||||
if (index < 0 || !canUpdate(args, rows[index])) {
|
||||
return;
|
||||
}
|
||||
|
||||
await retryMigration(canvasElement, index);
|
||||
if (args.migrationWrite === 'success') {
|
||||
await screen.findByText(
|
||||
'Dashboard migrated to the new experience',
|
||||
@@ -265,47 +369,43 @@ export const migrateDashboard = async ({
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export const migrationFails = async ({
|
||||
canvasElement,
|
||||
}: PlayContext): Promise<void> => {
|
||||
await retryMigration(canvasElement);
|
||||
await screen.findByText(
|
||||
'Something went wrong',
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
);
|
||||
};
|
||||
|
||||
export const createDashboardFails = async ({
|
||||
canvasElement,
|
||||
}: PlayContext): Promise<void> => {
|
||||
await userEvent.click(
|
||||
await within(canvasElement).findByTestId(
|
||||
'new-dashboard-cta',
|
||||
if (args.migrationWrite === 'error') {
|
||||
await screen.findByText(
|
||||
'Something went wrong',
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
),
|
||||
);
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export const createDashboard = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!canCreate(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await openNewDashboard(canvasElement);
|
||||
await userEvent.click(await screen.findByTestId('create-dashboard-submit'));
|
||||
await screen.findAllByText(
|
||||
/Something went wrong/,
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
);
|
||||
if (args.createWrite === 'error') {
|
||||
await screen.findAllByText(
|
||||
/Something went wrong/,
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export const importInvalidImage = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
await userEvent.click(
|
||||
await within(canvasElement).findByTestId(
|
||||
'new-dashboard-cta',
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
),
|
||||
);
|
||||
if (!canCreate(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await openNewDashboard(canvasElement);
|
||||
await uploadDashboardJson({
|
||||
schemaVersion: 'v6',
|
||||
image: 'https://example.com/logo.png',
|
||||
@@ -318,59 +418,52 @@ export const importInvalidImage = async ({
|
||||
);
|
||||
};
|
||||
|
||||
export const importCreateFails = async ({
|
||||
export const importDashboard = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
await userEvent.click(
|
||||
await within(canvasElement).findByTestId(
|
||||
'new-dashboard-cta',
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
),
|
||||
);
|
||||
if (!canCreate(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await openNewDashboard(canvasElement);
|
||||
await uploadDashboardJson({
|
||||
schemaVersion: 'v6',
|
||||
spec: { display: { name: 'Imported' }, ...IMPORTED_SPEC },
|
||||
});
|
||||
await screen.findAllByText(
|
||||
/Something went wrong/,
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
);
|
||||
if (args.createWrite === 'error') {
|
||||
await screen.findAllByText(
|
||||
/Something went wrong/,
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export const submitTemplateRequest = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!canCreate(args) || !isCloudTenant(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await requestTemplate(canvasElement);
|
||||
await screen.findByText(
|
||||
'Dashboard request submitted',
|
||||
TEMPLATE_REQUEST_TOASTS[args.templateRequest],
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
);
|
||||
};
|
||||
|
||||
export const templateRequestFails = async ({
|
||||
export const saveView = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
await requestTemplate(canvasElement);
|
||||
await screen.findByText('Event rejected', {}, { timeout: TOAST_TIMEOUT });
|
||||
};
|
||||
if (!canList(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
export const templateRequestRejected = async ({
|
||||
canvasElement,
|
||||
}: PlayContext): Promise<void> => {
|
||||
await requestTemplate(canvasElement);
|
||||
await screen.findByText(
|
||||
'Something went wrong',
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
);
|
||||
};
|
||||
|
||||
export const saveViewFails = async ({
|
||||
canvasElement,
|
||||
}: PlayContext): Promise<void> => {
|
||||
await userEvent.click(
|
||||
await within(canvasElement).findByRole(
|
||||
'button',
|
||||
@@ -380,16 +473,26 @@ export const saveViewFails = async ({
|
||||
);
|
||||
await userEvent.type(await screen.findByTestId('save-view-name'), 'On-call');
|
||||
await userEvent.click(await screen.findByTestId('save-view-confirm'));
|
||||
await screen.findByText(
|
||||
'Failed to save view.',
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
);
|
||||
if (args.viewWrite === 'error') {
|
||||
await screen.findByText(
|
||||
'Failed to save view.',
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export const renameViewFails = async ({
|
||||
const listsSavedViews = (args: DashboardsListArgs): boolean =>
|
||||
canList(args) && args.dataState === 'loaded' && args.savedViews > 0;
|
||||
|
||||
export const renameView = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!listsSavedViews(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [rename] = await within(canvasElement).findAllByRole(
|
||||
'button',
|
||||
{ name: 'Rename view' },
|
||||
@@ -403,16 +506,23 @@ export const renameViewFails = async ({
|
||||
await userEvent.clear(input);
|
||||
await userEvent.type(input, 'Renamed view');
|
||||
await userEvent.click(await screen.findByTestId('rename-view-confirm'));
|
||||
await screen.findByText(
|
||||
'Failed to update view.',
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
);
|
||||
if (args.viewWrite === 'error') {
|
||||
await screen.findByText(
|
||||
'Failed to update view.',
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteViewFails = async ({
|
||||
export const deleteView = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!listsSavedViews(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [remove] = await within(canvasElement).findAllByRole(
|
||||
'button',
|
||||
{ name: 'Delete view' },
|
||||
@@ -425,9 +535,11 @@ export const deleteViewFails = async ({
|
||||
await userEvent.click(
|
||||
await within(dialog).findByRole('button', { name: 'Delete' }),
|
||||
);
|
||||
await screen.findByText(
|
||||
'Failed to delete view.',
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
);
|
||||
if (args.viewWrite === 'error') {
|
||||
await screen.findByText(
|
||||
'Failed to delete view.',
|
||||
{},
|
||||
{ timeout: TOAST_TIMEOUT },
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -9,6 +9,8 @@ import {
|
||||
InfraMonitoringEntity,
|
||||
} from 'container/InfraMonitoringK8sV2/constants';
|
||||
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
|
||||
import { infraStoryMocks } from './InfrastructureMonitoring.stories.mocks';
|
||||
import { infraListResponse } from './__story_mockdata__/infraMonitoring';
|
||||
|
||||
@@ -56,6 +58,7 @@ export const podLongNodeName = rest.post(
|
||||
* what puts `?category=` on the route the story starts on.
|
||||
*/
|
||||
export const podsMocks = infraStoryMocks(InfraMonitoringEntity.PODS);
|
||||
export type PodsArgs = PageStoryArgs<typeof podsMocks>;
|
||||
export const nodesMocks = infraStoryMocks(InfraMonitoringEntity.NODES);
|
||||
export const namespacesMocks = infraStoryMocks(
|
||||
InfraMonitoringEntity.NAMESPACES,
|
||||
|
||||
@@ -1,21 +1,24 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import {
|
||||
findSuggestion,
|
||||
openKeySuggestions,
|
||||
typeFilter,
|
||||
} from 'components/QueryBuilderV2/QueryV2/QuerySearch/stories/__story_mockdata__/querySearch.play';
|
||||
import { screen, userEvent, within } from 'storybook/test';
|
||||
import { VIEWS } from 'container/InfraMonitoringK8sV2/constants';
|
||||
|
||||
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
|
||||
import { podLongNodeName, podsMocks } from './Kubernetes.stories.mocks';
|
||||
import {
|
||||
podLongNodeName,
|
||||
podsMocks,
|
||||
type PodsArgs,
|
||||
} from './Kubernetes.stories.mocks';
|
||||
import {
|
||||
copyPodMetadata,
|
||||
copyPodName,
|
||||
openDrawerLogsTab,
|
||||
openTableOptions,
|
||||
suggestFilterKeys,
|
||||
suggestFilterValues,
|
||||
} from './__story_mockdata__/pods.play';
|
||||
|
||||
import InfrastructureMonitoringPage from '../InfrastructureMonitoringPage';
|
||||
|
||||
type PodsArgs = PageStoryArgs<typeof podsMocks>;
|
||||
|
||||
const pageStory = storyMocks(podsMocks, { layout: 'app' });
|
||||
|
||||
/**
|
||||
@@ -57,38 +60,19 @@ export const PodDetailsEventsJsonBody: StoryObj<PodsArgs> = {
|
||||
/** The selected pod's details drawer, switched to its logs tab. */
|
||||
export const DetailsDrawerLogsTab: StoryObj<PodsArgs> = {
|
||||
args: { drawer: true },
|
||||
play: async () => {
|
||||
const drawer = within(
|
||||
await screen.findByRole('dialog', {}, { timeout: 10000 }),
|
||||
);
|
||||
|
||||
await userEvent.click(
|
||||
await drawer.findByText('Logs', {}, { timeout: 10000 }),
|
||||
);
|
||||
await drawer.findAllByText(/handled request in/, {}, { timeout: 10000 });
|
||||
},
|
||||
play: openDrawerLogsTab,
|
||||
};
|
||||
|
||||
/** The copy button beside the pod name in the drawer, which toasts the copy. */
|
||||
export const PodNameCopiedToast: StoryObj<PodsArgs> = {
|
||||
args: { drawer: true },
|
||||
play: async () => {
|
||||
await userEvent.click(
|
||||
await screen.findByTestId('copy-id-button', {}, { timeout: 10000 }),
|
||||
);
|
||||
await screen.findByText('Pod name copied to clipboard');
|
||||
},
|
||||
play: copyPodName,
|
||||
};
|
||||
|
||||
/** A metadata value's copy button in the drawer, which toasts the label it copied. */
|
||||
export const PodMetadataCopiedToast: StoryObj<PodsArgs> = {
|
||||
args: { drawer: true },
|
||||
play: async () => {
|
||||
await userEvent.click(
|
||||
await screen.findByTestId('copy-metadata-namespace', {}, { timeout: 10000 }),
|
||||
);
|
||||
await screen.findByText('NAMESPACE copied to clipboard');
|
||||
},
|
||||
play: copyPodMetadata,
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -122,19 +106,7 @@ export const TooltipsInDetailsDrawer: StoryObj<PodsArgs> = {
|
||||
*/
|
||||
export const TooltipsInOptionsPanel: StoryObj<PodsArgs> = {
|
||||
args: { tooltipsOpen: true },
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
|
||||
await userEvent.click(
|
||||
await canvas.findByTestId(
|
||||
'k8s-table-options-button',
|
||||
{},
|
||||
{ timeout: 10000 },
|
||||
),
|
||||
);
|
||||
|
||||
await screen.findByText('Columns');
|
||||
},
|
||||
play: openTableOptions,
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -147,16 +119,11 @@ const heldViewport = { sbshot: { viewport: { height: 1200 } } };
|
||||
/** The pod filter focused: the Kubernetes keys pods can be narrowed by. */
|
||||
export const FilterKeySuggestions: StoryObj<PodsArgs> = {
|
||||
parameters: heldViewport,
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await openKeySuggestions(canvasElement, 'k8s.node.name');
|
||||
},
|
||||
play: suggestFilterKeys,
|
||||
};
|
||||
|
||||
/** The pod filter on a namespace: the namespaces the pods run in. */
|
||||
export const FilterValueSuggestions: StoryObj<PodsArgs> = {
|
||||
parameters: heldViewport,
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await typeFilter(canvasElement, 'k8s.namespace.name = ');
|
||||
await findSuggestion(canvasElement, 'kube-system');
|
||||
},
|
||||
play: suggestFilterValues,
|
||||
};
|
||||
|
||||
97
frontend/src/pages/InfrastructureMonitoring/stories/__story_mockdata__/pods.play.ts
generated
Normal file
97
frontend/src/pages/InfrastructureMonitoring/stories/__story_mockdata__/pods.play.ts
generated
Normal file
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
|
||||
* Do not hand-edit: regenerate instead.
|
||||
*/
|
||||
|
||||
import {
|
||||
findSuggestion,
|
||||
openKeySuggestions,
|
||||
typeFilter,
|
||||
} from 'components/QueryBuilderV2/QueryV2/QuerySearch/stories/__story_mockdata__/querySearch.play';
|
||||
import { screen, userEvent, within } from 'storybook/test';
|
||||
|
||||
import type { PodsArgs } from '../Kubernetes.stories.mocks';
|
||||
|
||||
interface PlayContext {
|
||||
canvasElement: HTMLElement;
|
||||
args: PodsArgs;
|
||||
}
|
||||
|
||||
export const openDrawerLogsTab = async ({
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!args.drawer || args.dataState !== 'loaded' || args.telemetryRows === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const drawer = within(
|
||||
await screen.findByRole('dialog', {}, { timeout: 10000 }),
|
||||
);
|
||||
|
||||
await userEvent.click(await drawer.findByText('Logs', {}, { timeout: 10000 }));
|
||||
await drawer.findAllByText(/handled request in/, {}, { timeout: 10000 });
|
||||
};
|
||||
|
||||
export const copyPodName = async ({ args }: PlayContext): Promise<void> => {
|
||||
if (!args.drawer) {
|
||||
return;
|
||||
}
|
||||
|
||||
await userEvent.click(
|
||||
await screen.findByTestId('copy-id-button', {}, { timeout: 10000 }),
|
||||
);
|
||||
await screen.findByText('Pod name copied to clipboard');
|
||||
};
|
||||
|
||||
export const copyPodMetadata = async ({ args }: PlayContext): Promise<void> => {
|
||||
if (!args.drawer || args.dataState !== 'loaded') {
|
||||
return;
|
||||
}
|
||||
|
||||
await userEvent.click(
|
||||
await screen.findByTestId('copy-metadata-namespace', {}, { timeout: 10000 }),
|
||||
);
|
||||
await screen.findByText('NAMESPACE copied to clipboard');
|
||||
};
|
||||
|
||||
export const openTableOptions = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
// The drawer covers the list, so its options are out of reach.
|
||||
if (args.drawer) {
|
||||
return;
|
||||
}
|
||||
|
||||
await userEvent.click(
|
||||
await within(canvasElement).findByTestId(
|
||||
'k8s-table-options-button',
|
||||
{},
|
||||
{ timeout: 10000 },
|
||||
),
|
||||
);
|
||||
await screen.findByText('Columns');
|
||||
};
|
||||
|
||||
export const suggestFilterKeys = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (args.dataState !== 'loaded') {
|
||||
return;
|
||||
}
|
||||
|
||||
await openKeySuggestions(canvasElement, 'k8s.node.name');
|
||||
};
|
||||
|
||||
export const suggestFilterValues = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (args.dataState !== 'loaded') {
|
||||
return;
|
||||
}
|
||||
|
||||
await typeFilter(canvasElement, 'k8s.namespace.name = ');
|
||||
await findSuggestion(canvasElement, 'kube-system');
|
||||
};
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
toggleControl,
|
||||
} from '@/storybook/controls/controls';
|
||||
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
import {
|
||||
RESPONSE_STATES,
|
||||
type ResponseState,
|
||||
@@ -312,3 +313,5 @@ export const logsMocks = defineStoryMocks({
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
export type LogsArgs = PageStoryArgs<typeof logsMocks>;
|
||||
|
||||
@@ -1,23 +1,35 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import {
|
||||
blurFilter,
|
||||
openKeySuggestions,
|
||||
showFilterErrors,
|
||||
typeFilter,
|
||||
typeFilterWithCaretBack,
|
||||
findSuggestion,
|
||||
} from 'components/QueryBuilderV2/QueryV2/QuerySearch/stories/__story_mockdata__/querySearch.play';
|
||||
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
|
||||
|
||||
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
|
||||
import { logsMocks } from './LogsModulePage.stories.mocks';
|
||||
import { type LogsArgs, logsMocks } from './LogsModulePage.stories.mocks';
|
||||
import {
|
||||
completeFilter,
|
||||
copyLog,
|
||||
copyLogDetailsLink,
|
||||
copyLogLinkFromRow,
|
||||
dirtyQuickFiltersSettings,
|
||||
openLogContext,
|
||||
openLogDetails,
|
||||
openLogDetailsMenu,
|
||||
openQuickFiltersSettings,
|
||||
showFilterSyntaxError,
|
||||
stepToNextLog,
|
||||
suggestConjunctions,
|
||||
suggestFilterKeys,
|
||||
suggestFilterValues,
|
||||
suggestInListValues,
|
||||
suggestInNestedGroup,
|
||||
suggestNegatedOperators,
|
||||
suggestNoValues,
|
||||
suggestNumberOperators,
|
||||
suggestOperators,
|
||||
suggestPartialKey,
|
||||
suggestRecentSearches,
|
||||
} from './__story_mockdata__/logs.play';
|
||||
|
||||
import LogsModulePage from '../LogsModulePage';
|
||||
|
||||
type LogsArgs = PageStoryArgs<typeof logsMocks>;
|
||||
|
||||
const pageStory = storyMocks(logsMocks, { layout: 'app' });
|
||||
|
||||
/**
|
||||
@@ -38,42 +50,6 @@ export default meta;
|
||||
|
||||
type Story = StoryObj<LogsArgs>;
|
||||
|
||||
/** The page fetches before it renders a row, which outlasts the 1s default. */
|
||||
const untilLoaded = { timeout: 15_000 };
|
||||
|
||||
const openQuickFiltersSettings = async (): Promise<void> => {
|
||||
// The settings control renders disabled while its permission check is in
|
||||
// flight and is swapped for the enabled one once the check answers, so it is
|
||||
// looked up again on every attempt; a click on the disabled one is dropped in
|
||||
// silence.
|
||||
const control = await waitFor(() => {
|
||||
const settings = screen.getByTestId('settings-icon-container');
|
||||
|
||||
expect(settings).not.toHaveAttribute('aria-disabled', 'true');
|
||||
|
||||
return settings;
|
||||
}, untilLoaded);
|
||||
|
||||
await userEvent.click(control);
|
||||
await screen.findByText('Edit quick filters');
|
||||
};
|
||||
|
||||
/** Opening a log is what the drawer is for, and the first row will do. */
|
||||
const openFirstLog = async (canvasElement: HTMLElement): Promise<void> => {
|
||||
const [row] = await within(canvasElement).findAllByTestId(
|
||||
/^logs-table-row-/,
|
||||
undefined,
|
||||
untilLoaded,
|
||||
);
|
||||
|
||||
// The list hangs its click handler off the cells rather than the row, so a
|
||||
// click on the row itself opens nothing.
|
||||
const [, timestamp] = within(row).getAllByRole('cell');
|
||||
|
||||
await userEvent.click(timestamp);
|
||||
await screen.findByTestId('log-detail-drawer', undefined, untilLoaded);
|
||||
};
|
||||
|
||||
/**
|
||||
* The explorer on its list view: quick filters down the left, the frequency
|
||||
* chart over a page of log lines across every severity, and the saved views
|
||||
@@ -148,30 +124,17 @@ export const JsonBodyFieldsRaw: Story = {
|
||||
|
||||
/** One log opened up: its own fields, then the resource that sent it. */
|
||||
export const LogDetails: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await openFirstLog(canvasElement);
|
||||
},
|
||||
play: openLogDetails,
|
||||
};
|
||||
|
||||
/** The logs either side of the one that was opened, on the same filters. */
|
||||
export const LogDetailsContext: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await openFirstLog(canvasElement);
|
||||
await userEvent.click(
|
||||
await screen.findByText('Context', undefined, untilLoaded),
|
||||
);
|
||||
// The tab queries the logs either side before it can render them.
|
||||
await screen.findAllByText(/cache lookup for cart/, undefined, untilLoaded);
|
||||
},
|
||||
play: openLogContext,
|
||||
};
|
||||
|
||||
/** The log detail drawer with its header actions menu open. */
|
||||
export const LogDetailsMenuOpen: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await openFirstLog(canvasElement);
|
||||
await userEvent.click(await screen.findByTestId('log-details-header-menu'));
|
||||
await screen.findByText('Copy link to log');
|
||||
},
|
||||
play: openLogDetailsMenu,
|
||||
};
|
||||
|
||||
/** A response warning shown beside the query actions. */
|
||||
@@ -196,17 +159,6 @@ export const QuickFiltersSettings: Story = {
|
||||
play: openQuickFiltersSettings,
|
||||
};
|
||||
|
||||
const dirtyQuickFiltersSettings = async (): Promise<void> => {
|
||||
await openQuickFiltersSettings();
|
||||
// One Remove per added filter; the first row's is the one clicked.
|
||||
const [removeFilter] = await screen.findAllByRole('button', {
|
||||
name: 'Remove',
|
||||
});
|
||||
|
||||
await userEvent.click(removeFilter);
|
||||
await screen.findByRole('button', { name: 'Save changes' });
|
||||
};
|
||||
|
||||
/** Settings with an unsaved filter removal and the fixed action footer. */
|
||||
export const QuickFiltersSettingsDirty: Story = {
|
||||
play: dirtyQuickFiltersSettings,
|
||||
@@ -232,76 +184,48 @@ export const QuickFiltersSettingsWithBanner: Story = {
|
||||
*/
|
||||
export const Tooltips: Story = {
|
||||
args: { tooltipsOpen: true },
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await openFirstLog(canvasElement);
|
||||
await userEvent.click(
|
||||
await screen.findByTestId('log-details-header-next', undefined, untilLoaded),
|
||||
);
|
||||
},
|
||||
play: stepToNextLog,
|
||||
};
|
||||
|
||||
/** The filter focused before anything is typed: every key the logs carry. */
|
||||
export const FilterKeySuggestions: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await openKeySuggestions(canvasElement, 'severity_text');
|
||||
},
|
||||
play: suggestFilterKeys,
|
||||
};
|
||||
|
||||
/** A partial key, with the keys that still match and the typed part marked. */
|
||||
export const FilterPartialKey: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await typeFilter(canvasElement, 'serv');
|
||||
await findSuggestion(canvasElement, 'service.name');
|
||||
},
|
||||
play: suggestPartialKey,
|
||||
};
|
||||
|
||||
/** A string key followed by a space: the operators a string compares with. */
|
||||
export const FilterOperatorSuggestions: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await typeFilter(canvasElement, 'service.name ');
|
||||
await findSuggestion(canvasElement, 'CONTAINS');
|
||||
},
|
||||
play: suggestOperators,
|
||||
};
|
||||
|
||||
/** A number key puts the range comparisons first. */
|
||||
export const FilterNumberOperatorSuggestions: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await typeFilter(canvasElement, 'http.status_code ');
|
||||
await findSuggestion(canvasElement, 'BETWEEN');
|
||||
},
|
||||
play: suggestNumberOperators,
|
||||
};
|
||||
|
||||
/** `NOT` after a key narrows the list to the operators it can negate. */
|
||||
export const FilterNegatedOperatorSuggestions: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await typeFilter(canvasElement, 'service.name NOT ');
|
||||
await findSuggestion(canvasElement, 'IN');
|
||||
},
|
||||
play: suggestNegatedOperators,
|
||||
};
|
||||
|
||||
/** A key and an operator: the values the key holds, fetched for it. */
|
||||
export const FilterValueSuggestions: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await typeFilter(canvasElement, 'service.name = ');
|
||||
await findSuggestion(canvasElement, 'checkout');
|
||||
},
|
||||
play: suggestFilterValues,
|
||||
};
|
||||
|
||||
/** Values still being fetched for the key. */
|
||||
export const FilterValuesLoading: Story = {
|
||||
args: { filterValues: 'loading' },
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await typeFilter(canvasElement, 'service.name = ');
|
||||
await findSuggestion(canvasElement, 'Loading suggestions');
|
||||
},
|
||||
play: suggestFilterValues,
|
||||
};
|
||||
|
||||
/** A key the backend holds no values for, such as the free-text body. */
|
||||
export const FilterNoValueSuggestions: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await typeFilter(canvasElement, 'body = ');
|
||||
await findSuggestion(canvasElement, 'No suggestions available');
|
||||
},
|
||||
play: suggestNoValues,
|
||||
};
|
||||
|
||||
/** The values request failed. */
|
||||
@@ -309,120 +233,55 @@ export const FilterValuesError: Story = {
|
||||
args: { filterValues: 'error' },
|
||||
// The values request deliberately fails.
|
||||
parameters: { allowConsoleErrors: true },
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await typeFilter(canvasElement, 'service.name = ');
|
||||
await findSuggestion(canvasElement, 'Error loading suggestions');
|
||||
},
|
||||
play: suggestFilterValues,
|
||||
};
|
||||
|
||||
/** Inside an `IN` list, after the first value: the rest of the values. */
|
||||
export const FilterInList: Story = {
|
||||
// The editor logs a TypeError while the list is open, which it survives.
|
||||
parameters: { allowConsoleErrors: true },
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await typeFilterWithCaretBack(
|
||||
canvasElement,
|
||||
"service.name IN ['auth', ]",
|
||||
1,
|
||||
'checkout',
|
||||
);
|
||||
},
|
||||
play: suggestInListValues,
|
||||
};
|
||||
|
||||
/** A complete condition: the conjunctions that start the next one. */
|
||||
export const FilterConjunctionSuggestions: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await typeFilter(canvasElement, "service.name = 'checkout' ");
|
||||
await findSuggestion(canvasElement, 'OR');
|
||||
},
|
||||
play: suggestConjunctions,
|
||||
};
|
||||
|
||||
/** Inside an opened group: keys, another group and `NOT`. */
|
||||
export const FilterNestedGroup: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await typeFilterWithCaretBack(canvasElement, '()', 1, 'NOT');
|
||||
},
|
||||
play: suggestInNestedGroup,
|
||||
};
|
||||
|
||||
/** A long valid expression mixing operators, left for the next run. */
|
||||
export const FilterComplete: Story = {
|
||||
// The editor logs a TypeError while the `IN` list is typed, which it survives.
|
||||
parameters: { allowConsoleErrors: true },
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await typeFilter(
|
||||
canvasElement,
|
||||
"service.name IN ['checkout', 'payments'] AND severity_text = 'ERROR' AND http.status_code >= 500 AND body CONTAINS 'timeout'",
|
||||
);
|
||||
await blurFilter(canvasElement);
|
||||
},
|
||||
play: completeFilter,
|
||||
};
|
||||
|
||||
/** An incomplete expression after focus left: the marker and its errors. */
|
||||
export const FilterSyntaxError: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await showFilterErrors(canvasElement, 'service.name = ');
|
||||
},
|
||||
play: showFilterSyntaxError,
|
||||
};
|
||||
|
||||
/** Filters run before, offered above the key suggestions. */
|
||||
export const FilterRecentSearches: Story = {
|
||||
args: { recentFilters: 3 },
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await openKeySuggestions(
|
||||
canvasElement,
|
||||
"k8s.namespace.name = 'observability'",
|
||||
);
|
||||
},
|
||||
play: suggestRecentSearches,
|
||||
};
|
||||
|
||||
/** Row actions render on hover, so the first row is hovered before the copy link is pressed. */
|
||||
export const LogLinkCopiedToast: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
const [row] = await within(canvasElement).findAllByTestId(
|
||||
/^logs-table-row-/,
|
||||
undefined,
|
||||
untilLoaded,
|
||||
);
|
||||
const [, timestamp] = within(row).getAllByRole('cell');
|
||||
|
||||
await userEvent.hover(timestamp);
|
||||
await userEvent.click(
|
||||
await waitFor(() => {
|
||||
const button = canvasElement.querySelector<HTMLElement>('.copy-log-btn');
|
||||
|
||||
if (!button) {
|
||||
throw new Error('Row actions did not render');
|
||||
}
|
||||
|
||||
return button;
|
||||
}, untilLoaded),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText('Copied to clipboard')).toBeVisible(),
|
||||
);
|
||||
},
|
||||
play: copyLogLinkFromRow,
|
||||
};
|
||||
|
||||
/** "Copy log" in the log detail drawer's actions menu. */
|
||||
export const LogCopiedToast: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await openFirstLog(canvasElement);
|
||||
await userEvent.click(await screen.findByTestId('log-details-header-menu'));
|
||||
await userEvent.click(await screen.findByText('Copy log'));
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText('Copied to clipboard')).toBeVisible(),
|
||||
);
|
||||
},
|
||||
play: copyLog,
|
||||
};
|
||||
|
||||
/** "Copy link to log" in the log detail drawer's actions menu. */
|
||||
export const LogDetailsLinkCopiedToast: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await openFirstLog(canvasElement);
|
||||
await userEvent.click(await screen.findByTestId('log-details-header-menu'));
|
||||
await userEvent.click(await screen.findByText('Copy link to log'));
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText('Copied to clipboard')).toBeVisible(),
|
||||
);
|
||||
},
|
||||
play: copyLogDetailsLink,
|
||||
};
|
||||
|
||||
319
frontend/src/pages/LogsModulePage/stories/__story_mockdata__/logs.play.ts
generated
Normal file
319
frontend/src/pages/LogsModulePage/stories/__story_mockdata__/logs.play.ts
generated
Normal file
@@ -0,0 +1,319 @@
|
||||
/**
|
||||
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
|
||||
* Do not hand-edit: regenerate instead.
|
||||
*/
|
||||
|
||||
import {
|
||||
blurFilter,
|
||||
findSuggestion,
|
||||
openKeySuggestions,
|
||||
showFilterErrors,
|
||||
typeFilter,
|
||||
typeFilterWithCaretBack,
|
||||
} from 'components/QueryBuilderV2/QueryV2/QuerySearch/stories/__story_mockdata__/querySearch.play';
|
||||
import { QuickFilterManagePermissions } from 'lib/authz/hooks/useAuthZ/permissions/quick-filter.permissions';
|
||||
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
|
||||
|
||||
import { grantsAll } from '@/storybook/access/access';
|
||||
|
||||
import type { LogsArgs } from '../LogsModulePage.stories.mocks';
|
||||
|
||||
interface PlayContext {
|
||||
canvasElement: HTMLElement;
|
||||
args: LogsArgs;
|
||||
}
|
||||
|
||||
/** The page fetches before it renders a row, which outlasts the 1s default. */
|
||||
const untilLoaded = { timeout: 15_000 };
|
||||
|
||||
const VALUE_SUGGESTIONS = {
|
||||
loaded: 'checkout',
|
||||
loading: 'Loading suggestions',
|
||||
error: 'Error loading suggestions',
|
||||
} satisfies Record<LogsArgs['filterValues'], string>;
|
||||
|
||||
/** The rows a play opens exist only in the list view's table format. */
|
||||
const listsLogRows = (args: LogsArgs, count = 1): boolean =>
|
||||
args.view === 'list' &&
|
||||
args.format === 'table' &&
|
||||
args.dataState === 'loaded' &&
|
||||
args.logs >= count;
|
||||
|
||||
/** The settings control stays enabled when the check itself fails. */
|
||||
const canManageQuickFilters = (args: LogsArgs): boolean =>
|
||||
args.filtersPanel &&
|
||||
(args.authzState === 'error' ||
|
||||
grantsAll(args, ...QuickFilterManagePermissions));
|
||||
|
||||
/** Runs `drive` once the filter has its keys, which come with the page's data. */
|
||||
const onFilter =
|
||||
(drive: (canvasElement: HTMLElement, args: LogsArgs) => Promise<void>) =>
|
||||
async ({ canvasElement, args }: PlayContext): Promise<void> => {
|
||||
if (args.dataState === 'loaded') {
|
||||
await drive(canvasElement, args);
|
||||
}
|
||||
};
|
||||
|
||||
/** Opening a log is what the drawer is for, and the first row will do. */
|
||||
const openFirstLog = async (canvasElement: HTMLElement): Promise<void> => {
|
||||
const [row] = await within(canvasElement).findAllByTestId(
|
||||
/^logs-table-row-/,
|
||||
undefined,
|
||||
untilLoaded,
|
||||
);
|
||||
|
||||
// The list hangs its click handler off the cells rather than the row, so a
|
||||
// click on the row itself opens nothing.
|
||||
const [, timestamp] = within(row).getAllByRole('cell');
|
||||
|
||||
await userEvent.click(timestamp);
|
||||
await screen.findByTestId('log-detail-drawer', undefined, untilLoaded);
|
||||
};
|
||||
|
||||
const openLogMenuItem = async (
|
||||
canvasElement: HTMLElement,
|
||||
item: string,
|
||||
): Promise<void> => {
|
||||
await openFirstLog(canvasElement);
|
||||
await userEvent.click(await screen.findByTestId('log-details-header-menu'));
|
||||
await userEvent.click(await screen.findByText(item));
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText('Copied to clipboard')).toBeVisible(),
|
||||
);
|
||||
};
|
||||
|
||||
export const openLogDetails = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!listsLogRows(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await openFirstLog(canvasElement);
|
||||
};
|
||||
|
||||
export const openLogContext = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!listsLogRows(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await openFirstLog(canvasElement);
|
||||
await userEvent.click(
|
||||
await screen.findByText('Context', undefined, untilLoaded),
|
||||
);
|
||||
// The tab queries the logs either side before it can render them.
|
||||
await screen.findAllByText(/cache lookup for cart/, undefined, untilLoaded);
|
||||
};
|
||||
|
||||
export const openLogDetailsMenu = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!listsLogRows(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await openFirstLog(canvasElement);
|
||||
await userEvent.click(await screen.findByTestId('log-details-header-menu'));
|
||||
await screen.findByText('Copy link to log');
|
||||
};
|
||||
|
||||
export const openQuickFiltersSettings = async ({
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!canManageQuickFilters(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// The settings control renders disabled while its permission check is in
|
||||
// flight and is swapped for the enabled one once the check answers, so it is
|
||||
// looked up again on every attempt; a click on the disabled one is dropped in
|
||||
// silence.
|
||||
const control = await waitFor(async () => {
|
||||
const settings = screen.getByTestId('settings-icon-container');
|
||||
|
||||
await expect(settings).not.toHaveAttribute('aria-disabled', 'true');
|
||||
|
||||
return settings;
|
||||
}, untilLoaded);
|
||||
|
||||
await userEvent.click(control);
|
||||
await screen.findByText('Edit quick filters');
|
||||
};
|
||||
|
||||
export const dirtyQuickFiltersSettings = async (
|
||||
context: PlayContext,
|
||||
): Promise<void> => {
|
||||
const { args } = context;
|
||||
if (
|
||||
!canManageQuickFilters(args) ||
|
||||
args.dataState !== 'loaded' ||
|
||||
args.quickFilters === 0
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
await openQuickFiltersSettings(context);
|
||||
// One Remove per added filter; the first row's is the one clicked.
|
||||
const [removeFilter] = await screen.findAllByRole('button', {
|
||||
name: 'Remove',
|
||||
});
|
||||
|
||||
await userEvent.click(removeFilter);
|
||||
await screen.findByRole('button', { name: 'Save changes' });
|
||||
};
|
||||
|
||||
export const stepToNextLog = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!listsLogRows(args, 2)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await openFirstLog(canvasElement);
|
||||
await userEvent.click(
|
||||
await screen.findByTestId('log-details-header-next', undefined, untilLoaded),
|
||||
);
|
||||
};
|
||||
|
||||
export const suggestFilterKeys = onFilter((canvasElement) =>
|
||||
openKeySuggestions(canvasElement, 'severity_text'),
|
||||
);
|
||||
|
||||
export const suggestPartialKey = onFilter(async (canvasElement) => {
|
||||
await typeFilter(canvasElement, 'serv');
|
||||
await findSuggestion(canvasElement, 'service.name');
|
||||
});
|
||||
|
||||
export const suggestOperators = onFilter(async (canvasElement) => {
|
||||
await typeFilter(canvasElement, 'service.name ');
|
||||
await findSuggestion(canvasElement, 'CONTAINS');
|
||||
});
|
||||
|
||||
export const suggestNumberOperators = onFilter(async (canvasElement) => {
|
||||
await typeFilter(canvasElement, 'http.status_code ');
|
||||
await findSuggestion(canvasElement, 'BETWEEN');
|
||||
});
|
||||
|
||||
export const suggestNegatedOperators = onFilter(async (canvasElement) => {
|
||||
await typeFilter(canvasElement, 'service.name NOT ');
|
||||
await findSuggestion(canvasElement, 'IN');
|
||||
});
|
||||
|
||||
export const suggestFilterValues = onFilter(async (canvasElement, args) => {
|
||||
await typeFilter(canvasElement, 'service.name = ');
|
||||
await findSuggestion(canvasElement, VALUE_SUGGESTIONS[args.filterValues]);
|
||||
});
|
||||
|
||||
export const suggestNoValues = onFilter(async (canvasElement, args) => {
|
||||
if (args.filterValues !== 'loaded') {
|
||||
return;
|
||||
}
|
||||
|
||||
await typeFilter(canvasElement, 'body = ');
|
||||
await findSuggestion(canvasElement, 'No suggestions available');
|
||||
});
|
||||
|
||||
export const suggestInListValues = onFilter(async (canvasElement, args) => {
|
||||
if (args.filterValues !== 'loaded') {
|
||||
return;
|
||||
}
|
||||
|
||||
await typeFilterWithCaretBack(
|
||||
canvasElement,
|
||||
"service.name IN ['auth', ]",
|
||||
1,
|
||||
'checkout',
|
||||
);
|
||||
});
|
||||
|
||||
export const suggestConjunctions = onFilter(async (canvasElement) => {
|
||||
await typeFilter(canvasElement, "service.name = 'checkout' ");
|
||||
await findSuggestion(canvasElement, 'OR');
|
||||
});
|
||||
|
||||
export const suggestInNestedGroup = onFilter((canvasElement) =>
|
||||
typeFilterWithCaretBack(canvasElement, '()', 1, 'NOT'),
|
||||
);
|
||||
|
||||
export const completeFilter = onFilter(async (canvasElement) => {
|
||||
await typeFilter(
|
||||
canvasElement,
|
||||
"service.name IN ['checkout', 'payments'] AND severity_text = 'ERROR' AND http.status_code >= 500 AND body CONTAINS 'timeout'",
|
||||
);
|
||||
await blurFilter(canvasElement);
|
||||
});
|
||||
|
||||
export const showFilterSyntaxError = onFilter((canvasElement) =>
|
||||
showFilterErrors(canvasElement, 'service.name = '),
|
||||
);
|
||||
|
||||
export const suggestRecentSearches = onFilter(async (canvasElement, args) => {
|
||||
if (args.recentFilters === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
await openKeySuggestions(
|
||||
canvasElement,
|
||||
"k8s.namespace.name = 'observability'",
|
||||
);
|
||||
});
|
||||
|
||||
export const copyLogLinkFromRow = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!listsLogRows(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [row] = await within(canvasElement).findAllByTestId(
|
||||
/^logs-table-row-/,
|
||||
undefined,
|
||||
untilLoaded,
|
||||
);
|
||||
const [, timestamp] = within(row).getAllByRole('cell');
|
||||
|
||||
await userEvent.hover(timestamp);
|
||||
await userEvent.click(
|
||||
await waitFor(() => {
|
||||
const button = canvasElement.querySelector<HTMLElement>('.copy-log-btn');
|
||||
|
||||
if (!button) {
|
||||
throw new Error('Row actions did not render');
|
||||
}
|
||||
|
||||
return button;
|
||||
}, untilLoaded),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText('Copied to clipboard')).toBeVisible(),
|
||||
);
|
||||
};
|
||||
|
||||
export const copyLog = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!listsLogRows(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await openLogMenuItem(canvasElement, 'Copy log');
|
||||
};
|
||||
|
||||
export const copyLogDetailsLink = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!listsLogRows(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await openLogMenuItem(canvasElement, 'Copy link to log');
|
||||
};
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
toggleControl,
|
||||
} from '@/storybook/controls/controls';
|
||||
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
import { dashboardsForUserResponse } from '@/storybook/msw/__story_mockdata__/dashboards';
|
||||
import {
|
||||
fieldKeysResponse,
|
||||
@@ -553,6 +554,8 @@ export const metricsMocks = defineStoryMocks({
|
||||
},
|
||||
});
|
||||
|
||||
export type MetricsArgs = PageStoryArgs<typeof metricsMocks>;
|
||||
|
||||
export const saveUnit = async (
|
||||
canvasElement: HTMLElement,
|
||||
expected: string | false,
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import {
|
||||
findSuggestion,
|
||||
openKeySuggestions,
|
||||
typeFilter,
|
||||
} from 'components/QueryBuilderV2/QueryV2/QuerySearch/stories/__story_mockdata__/querySearch.play';
|
||||
import { screen, userEvent } from 'storybook/test';
|
||||
|
||||
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
|
||||
import { metricsMocks, saveUnit } from './MetricsExplorerPage.stories.mocks';
|
||||
import {
|
||||
type MetricsArgs,
|
||||
metricsMocks,
|
||||
} from './MetricsExplorerPage.stories.mocks';
|
||||
import {
|
||||
openDashboardsMenu,
|
||||
saveMetricUnit,
|
||||
suggestFilterKeys,
|
||||
suggestFilterValues,
|
||||
} from './__story_mockdata__/metricsExplorer.play';
|
||||
import MetricsExplorerPage from '../MetricsExplorerPage';
|
||||
|
||||
type MetricsArgs = PageStoryArgs<typeof metricsMocks>;
|
||||
|
||||
const pageStory = storyMocks(metricsMocks, { layout: 'app' });
|
||||
|
||||
/**
|
||||
@@ -103,31 +103,17 @@ export const Tooltips: Story = {
|
||||
*/
|
||||
export const MetricDetailsDashboardsMenu: Story = {
|
||||
args: { drawer: 'details' },
|
||||
play: async (): Promise<void> => {
|
||||
await userEvent.click(
|
||||
await screen.findByTestId(
|
||||
'metric-dashboards-popover',
|
||||
{},
|
||||
{ timeout: 10000 },
|
||||
),
|
||||
);
|
||||
await screen.findByRole('menu');
|
||||
},
|
||||
play: openDashboardsMenu,
|
||||
};
|
||||
|
||||
/** The summary's metric search focused: the attributes metrics can be found by. */
|
||||
export const FilterKeySuggestions: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await openKeySuggestions(canvasElement, 'k8s.cluster.name');
|
||||
},
|
||||
play: suggestFilterKeys,
|
||||
};
|
||||
|
||||
/** The metric search on an attribute and an operator: the values it holds. */
|
||||
export const FilterValueSuggestions: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await typeFilter(canvasElement, 'service.name = ');
|
||||
await findSuggestion(canvasElement, 'checkout');
|
||||
},
|
||||
play: suggestFilterValues,
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -136,14 +122,7 @@ export const FilterValueSuggestions: Story = {
|
||||
*/
|
||||
export const UnitSavedToast: Story = {
|
||||
args: { tab: 'explorer', metricUnit: 'unset' },
|
||||
play: async ({ canvasElement, args }): Promise<void> => {
|
||||
await saveUnit(
|
||||
canvasElement,
|
||||
args.unitSave === 'success'
|
||||
? 'Unit saved successfully'
|
||||
: 'Failed to save unit',
|
||||
);
|
||||
},
|
||||
play: saveMetricUnit,
|
||||
};
|
||||
|
||||
/** The same save with the metadata write failing. */
|
||||
@@ -151,7 +130,5 @@ export const UnitSaveErrorToast: Story = {
|
||||
args: { tab: 'explorer', metricUnit: 'unset', unitSave: 'error' },
|
||||
// The deliberate 500 is the state under test.
|
||||
parameters: { allowConsoleErrors: true },
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await saveUnit(canvasElement, 'Failed to save unit');
|
||||
},
|
||||
play: saveMetricUnit,
|
||||
};
|
||||
|
||||
90
frontend/src/pages/MetricsExplorer/stories/__story_mockdata__/metricsExplorer.play.ts
generated
Normal file
90
frontend/src/pages/MetricsExplorer/stories/__story_mockdata__/metricsExplorer.play.ts
generated
Normal file
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
|
||||
* Do not hand-edit: regenerate instead.
|
||||
*/
|
||||
|
||||
import {
|
||||
findSuggestion,
|
||||
openKeySuggestions,
|
||||
typeFilter,
|
||||
} from 'components/QueryBuilderV2/QueryV2/QuerySearch/stories/__story_mockdata__/querySearch.play';
|
||||
import { screen, userEvent } from 'storybook/test';
|
||||
|
||||
import {
|
||||
type MetricsArgs,
|
||||
saveUnit,
|
||||
} from '../MetricsExplorerPage.stories.mocks';
|
||||
|
||||
interface PlayContext {
|
||||
canvasElement: HTMLElement;
|
||||
args: MetricsArgs;
|
||||
}
|
||||
|
||||
const showsMetricSearch = (args: MetricsArgs): boolean =>
|
||||
args.dataState === 'loaded' && args.tab !== 'volume-control';
|
||||
|
||||
export const openDashboardsMenu = async ({
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (
|
||||
args.tab !== 'summary' ||
|
||||
args.drawer !== 'details' ||
|
||||
args.dataState !== 'loaded' ||
|
||||
args.relatedAssets === 0
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
await userEvent.click(
|
||||
await screen.findByTestId(
|
||||
'metric-dashboards-popover',
|
||||
{},
|
||||
{ timeout: 10000 },
|
||||
),
|
||||
);
|
||||
await screen.findByRole('menu');
|
||||
};
|
||||
|
||||
export const suggestFilterKeys = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!showsMetricSearch(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await openKeySuggestions(canvasElement, 'k8s.cluster.name');
|
||||
};
|
||||
|
||||
export const suggestFilterValues = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!showsMetricSearch(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await typeFilter(canvasElement, 'service.name = ');
|
||||
await findSuggestion(canvasElement, 'checkout');
|
||||
};
|
||||
|
||||
export const saveMetricUnit = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (
|
||||
args.tab !== 'explorer' ||
|
||||
args.dataState !== 'loaded' ||
|
||||
args.metricUnit !== 'unset' ||
|
||||
args.explorerMetrics !== 1
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
await saveUnit(
|
||||
canvasElement,
|
||||
args.unitSave === 'success'
|
||||
? 'Unit saved successfully'
|
||||
: 'Failed to save unit',
|
||||
);
|
||||
};
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
toggleControl,
|
||||
} from '@/storybook/controls/controls';
|
||||
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
import { fieldValuesResponse } from '@/storybook/msw/__story_mockdata__/fields';
|
||||
import {
|
||||
queryRangeV5RawResponse,
|
||||
@@ -354,3 +355,5 @@ export const tracesMocks = defineStoryMocks({
|
||||
],
|
||||
config: (values) => ({ route: tracesRoute(values) }),
|
||||
});
|
||||
|
||||
export type TracesArgs = PageStoryArgs<typeof tracesMocks>;
|
||||
|
||||
@@ -1,21 +1,22 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import {
|
||||
findSuggestion,
|
||||
openKeySuggestions,
|
||||
showFilterErrors,
|
||||
typeFilter,
|
||||
} from 'components/QueryBuilderV2/QueryV2/QuerySearch/stories/__story_mockdata__/querySearch.play';
|
||||
import { ExplorerViews } from 'pages/LogsExplorer/utils';
|
||||
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
|
||||
|
||||
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
|
||||
import { tracesMocks } from './TracesModulePage.stories.mocks';
|
||||
import { type TracesArgs, tracesMocks } from './TracesModulePage.stories.mocks';
|
||||
import {
|
||||
dirtyQuickFiltersSettings,
|
||||
loadNextListPage,
|
||||
openQuickFiltersSettings,
|
||||
showRootSpansNextPage,
|
||||
suggestBooleanValues,
|
||||
suggestFilterKeys,
|
||||
suggestFilterValues,
|
||||
suggestResourceKeys,
|
||||
showFilterSyntaxError,
|
||||
} from './__story_mockdata__/traces.play';
|
||||
import TracesModulePage from '../TracesModulePage';
|
||||
|
||||
type TracesArgs = PageStoryArgs<typeof tracesMocks>;
|
||||
|
||||
const pageStory = storyMocks(tracesMocks, { layout: 'app' });
|
||||
|
||||
/**
|
||||
@@ -34,28 +35,8 @@ const meta = {
|
||||
|
||||
export default meta;
|
||||
|
||||
/** The page fetches before it renders its filters, which outlasts the 1s default. */
|
||||
const untilLoaded = { timeout: 15_000 };
|
||||
|
||||
type Story = StoryObj<TracesArgs>;
|
||||
|
||||
const openQuickFiltersSettings = async (): Promise<void> => {
|
||||
// The settings control renders disabled while its permission check is in
|
||||
// flight and is swapped for the enabled one once the check answers, so it is
|
||||
// looked up again on every attempt; a click on the disabled one is dropped in
|
||||
// silence.
|
||||
const control = await waitFor(() => {
|
||||
const settings = screen.getByTestId('settings-icon-container');
|
||||
|
||||
expect(settings).not.toHaveAttribute('aria-disabled', 'true');
|
||||
|
||||
return settings;
|
||||
}, untilLoaded);
|
||||
|
||||
await userEvent.click(control);
|
||||
await screen.findByText('Edit quick filters');
|
||||
};
|
||||
|
||||
/**
|
||||
* The Explorer tab on a full window of spans: the org's quick filters down the
|
||||
* left, the query builder and the view switcher above, and the span list with
|
||||
@@ -77,35 +58,13 @@ export const RootSpans: Story = {
|
||||
*/
|
||||
export const RootSpansNextPage: Story = {
|
||||
args: { view: ExplorerViews.TRACE, spans: 50 },
|
||||
play: async (): Promise<void> => {
|
||||
await userEvent.click(
|
||||
await screen.findByRole('button', { name: 'Go to next page' }, untilLoaded),
|
||||
);
|
||||
const pager = screen.getByLabelText('pagination');
|
||||
|
||||
await expect(
|
||||
await within(pager).findByText('3', undefined, untilLoaded),
|
||||
).toBeVisible();
|
||||
},
|
||||
play: showRootSpansNextPage,
|
||||
};
|
||||
|
||||
/** The span list scrolled to its end, with the next 100 spans loaded under the first. */
|
||||
export const ListNextPage: Story = {
|
||||
args: { spans: 150 },
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
// Scrolls again on every attempt, since each loaded page moves the end.
|
||||
await waitFor(async (): Promise<void> => {
|
||||
const scroller = canvasElement.querySelector<HTMLElement>(
|
||||
'[data-virtuoso-scroller]',
|
||||
);
|
||||
|
||||
await expect(scroller).not.toBeNull();
|
||||
(scroller as HTMLElement).scrollTop = (scroller as HTMLElement).scrollHeight;
|
||||
await expect(
|
||||
canvasElement.querySelector('tr[data-index="120"]'),
|
||||
).not.toBeNull();
|
||||
}, untilLoaded);
|
||||
},
|
||||
play: loadNextListPage,
|
||||
};
|
||||
|
||||
/** The charted view of the same trace query. */
|
||||
@@ -154,17 +113,6 @@ export const QuickFiltersSettings: Story = {
|
||||
play: openQuickFiltersSettings,
|
||||
};
|
||||
|
||||
const dirtyQuickFiltersSettings = async (): Promise<void> => {
|
||||
await openQuickFiltersSettings();
|
||||
// One Remove per added filter; the first row's is the one clicked.
|
||||
const [removeFilter] = await screen.findAllByRole('button', {
|
||||
name: 'Remove',
|
||||
});
|
||||
|
||||
await userEvent.click(removeFilter);
|
||||
await screen.findByRole('button', { name: 'Save changes' });
|
||||
};
|
||||
|
||||
/** Settings with an unsaved filter removal and the fixed action footer. */
|
||||
export const QuickFiltersSettingsDirty: Story = {
|
||||
play: dirtyQuickFiltersSettings,
|
||||
@@ -183,38 +131,25 @@ export const QuickFiltersSettingsWithBanner: Story = {
|
||||
|
||||
/** The filter focused before anything is typed: span and resource keys together. */
|
||||
export const FilterKeySuggestions: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await openKeySuggestions(canvasElement, 'status_code_string');
|
||||
},
|
||||
play: suggestFilterKeys,
|
||||
};
|
||||
|
||||
/** A context prefix: only the keys that live on the resource. */
|
||||
export const FilterResourceKeys: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await typeFilter(canvasElement, 'resource.');
|
||||
await findSuggestion(canvasElement, 'resource.service.name');
|
||||
},
|
||||
play: suggestResourceKeys,
|
||||
};
|
||||
|
||||
/** A key and an operator: the services the spans came from. */
|
||||
export const FilterValueSuggestions: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await typeFilter(canvasElement, 'service.name = ');
|
||||
await findSuggestion(canvasElement, 'checkout');
|
||||
},
|
||||
play: suggestFilterValues,
|
||||
};
|
||||
|
||||
/** A boolean key offers its two values. */
|
||||
export const FilterBooleanValues: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await typeFilter(canvasElement, 'has_error = ');
|
||||
await findSuggestion(canvasElement, 'false');
|
||||
},
|
||||
play: suggestBooleanValues,
|
||||
};
|
||||
|
||||
/** A dangling conjunction after focus left: the marker and its errors. */
|
||||
export const FilterSyntaxError: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await showFilterErrors(canvasElement, 'has_error = true AND');
|
||||
},
|
||||
play: showFilterSyntaxError,
|
||||
};
|
||||
|
||||
191
frontend/src/pages/TracesModulePage/stories/__story_mockdata__/traces.play.ts
generated
Normal file
191
frontend/src/pages/TracesModulePage/stories/__story_mockdata__/traces.play.ts
generated
Normal file
@@ -0,0 +1,191 @@
|
||||
/**
|
||||
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
|
||||
* Do not hand-edit: regenerate instead.
|
||||
*/
|
||||
|
||||
import {
|
||||
findSuggestion,
|
||||
openKeySuggestions,
|
||||
showFilterErrors,
|
||||
typeFilter,
|
||||
} from 'components/QueryBuilderV2/QueryV2/QuerySearch/stories/__story_mockdata__/querySearch.play';
|
||||
import { QuickFilterManagePermissions } from 'lib/authz/hooks/useAuthZ/permissions/quick-filter.permissions';
|
||||
import { ExplorerViews } from 'pages/LogsExplorer/utils';
|
||||
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
|
||||
|
||||
import { grantsAll } from '@/storybook/access/access';
|
||||
|
||||
import type { TracesArgs } from '../TracesModulePage.stories.mocks';
|
||||
|
||||
interface PlayContext {
|
||||
canvasElement: HTMLElement;
|
||||
args: TracesArgs;
|
||||
}
|
||||
|
||||
/** The page fetches before it renders its filters, which outlasts the 1s default. */
|
||||
const untilLoaded = { timeout: 15_000 };
|
||||
|
||||
const LIST_PAGE_SIZE = 100;
|
||||
|
||||
const TRACE_PAGE_SIZE = 20;
|
||||
|
||||
const showsFilter = (args: TracesArgs): boolean =>
|
||||
args.dataState === 'loaded' && args.tab !== 'funnels';
|
||||
|
||||
const showsView = (args: TracesArgs, view: ExplorerViews): boolean =>
|
||||
args.tab === 'explorer' && args.view === view && args.dataState === 'loaded';
|
||||
|
||||
/** The settings control stays enabled when the check itself fails. */
|
||||
const canManageQuickFilters = (args: TracesArgs): boolean =>
|
||||
args.tab === 'explorer' &&
|
||||
(args.authzState === 'error' ||
|
||||
grantsAll(args, ...QuickFilterManagePermissions));
|
||||
|
||||
export const showRootSpansNextPage = async ({
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
// The pager offers page 3 once page 2 comes back full.
|
||||
if (
|
||||
!showsView(args, ExplorerViews.TRACE) ||
|
||||
args.spans < 2 * TRACE_PAGE_SIZE
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
await userEvent.click(
|
||||
await screen.findByRole('button', { name: 'Go to next page' }, untilLoaded),
|
||||
);
|
||||
const pager = screen.getByLabelText('pagination');
|
||||
|
||||
await expect(
|
||||
await within(pager).findByText('3', undefined, untilLoaded),
|
||||
).toBeVisible();
|
||||
};
|
||||
|
||||
export const loadNextListPage = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!showsView(args, ExplorerViews.LIST) || args.spans <= LIST_PAGE_SIZE) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Scrolls again on every attempt, since each loaded page moves the end.
|
||||
await waitFor(async (): Promise<void> => {
|
||||
const scroller = canvasElement.querySelector<HTMLElement>(
|
||||
'[data-virtuoso-scroller]',
|
||||
);
|
||||
|
||||
await expect(scroller).not.toBeNull();
|
||||
(scroller as HTMLElement).scrollTop = (scroller as HTMLElement).scrollHeight;
|
||||
const indexes = Array.from(
|
||||
canvasElement.querySelectorAll<HTMLElement>('tr[data-index]'),
|
||||
(row) => Number(row.dataset.index),
|
||||
);
|
||||
|
||||
await expect(Math.max(...indexes)).toBeGreaterThanOrEqual(LIST_PAGE_SIZE);
|
||||
}, untilLoaded);
|
||||
};
|
||||
|
||||
export const openQuickFiltersSettings = async ({
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!canManageQuickFilters(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// The settings control renders disabled while its permission check is in
|
||||
// flight and is swapped for the enabled one once the check answers, so it is
|
||||
// looked up again on every attempt; a click on the disabled one is dropped in
|
||||
// silence.
|
||||
const control = await waitFor(async () => {
|
||||
const settings = screen.getByTestId('settings-icon-container');
|
||||
|
||||
await expect(settings).not.toHaveAttribute('aria-disabled', 'true');
|
||||
|
||||
return settings;
|
||||
}, untilLoaded);
|
||||
|
||||
await userEvent.click(control);
|
||||
await screen.findByText('Edit quick filters');
|
||||
};
|
||||
|
||||
export const dirtyQuickFiltersSettings = async (
|
||||
context: PlayContext,
|
||||
): Promise<void> => {
|
||||
const { args } = context;
|
||||
if (
|
||||
!canManageQuickFilters(args) ||
|
||||
args.dataState !== 'loaded' ||
|
||||
args.quickFilters === 0
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
await openQuickFiltersSettings(context);
|
||||
// One Remove per added filter; the first row's is the one clicked.
|
||||
const [removeFilter] = await screen.findAllByRole('button', {
|
||||
name: 'Remove',
|
||||
});
|
||||
|
||||
await userEvent.click(removeFilter);
|
||||
await screen.findByRole('button', { name: 'Save changes' });
|
||||
};
|
||||
|
||||
export const suggestFilterKeys = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!showsFilter(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await openKeySuggestions(canvasElement, 'status_code_string');
|
||||
};
|
||||
|
||||
export const suggestResourceKeys = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!showsFilter(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await typeFilter(canvasElement, 'resource.');
|
||||
await findSuggestion(canvasElement, 'resource.service.name');
|
||||
};
|
||||
|
||||
export const suggestFilterValues = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!showsFilter(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await typeFilter(canvasElement, 'service.name = ');
|
||||
await findSuggestion(canvasElement, 'checkout');
|
||||
};
|
||||
|
||||
export const suggestBooleanValues = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!showsFilter(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await typeFilter(canvasElement, 'has_error = ');
|
||||
await findSuggestion(canvasElement, 'false');
|
||||
};
|
||||
|
||||
export const showFilterSyntaxError = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!showsFilter(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await showFilterErrors(canvasElement, 'has_error = true AND');
|
||||
};
|
||||
@@ -6,12 +6,16 @@ import {
|
||||
IsViewerPermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/legacy';
|
||||
import permissionsType from 'lib/authz/hooks/useAuthZ/permissions.type';
|
||||
import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';
|
||||
import {
|
||||
formatPermission,
|
||||
gettableTransactionToPermission,
|
||||
permissionToTransactionDto,
|
||||
} from 'lib/authz/hooks/useAuthZ/utils';
|
||||
import { ROLES, USER_ROLES } from 'types/roles';
|
||||
|
||||
import type { ResponseState } from '../runtime/responseState';
|
||||
|
||||
/**
|
||||
* `relation:kind` for every verb the backend allows on a resource, from the
|
||||
* generated permission catalogue, so a resource added there shows up here
|
||||
@@ -159,3 +163,23 @@ export const accessFor = (
|
||||
legacyRole: deriveLegacyRole(permissions),
|
||||
};
|
||||
};
|
||||
|
||||
export interface AccessArgs {
|
||||
access: AccessPreset;
|
||||
permissions: readonly string[];
|
||||
revoked: readonly string[];
|
||||
authzState: ResponseState;
|
||||
}
|
||||
|
||||
/** Whether `authz/check`, answered from a story's access controls, passes every one of `checks`. */
|
||||
export const grantsAll = (
|
||||
args: AccessArgs,
|
||||
...checks: BrandedPermission[]
|
||||
): boolean => {
|
||||
const grant = accessFor(args.access, args.permissions, args.revoked);
|
||||
|
||||
return (
|
||||
args.authzState === 'loaded' &&
|
||||
checks.every((check) => grant.allows(permissionToTransactionDto(check)))
|
||||
);
|
||||
};
|
||||
|
||||
@@ -36,7 +36,6 @@ export interface PostableAlertRuleV2 {
|
||||
absentFor?: number;
|
||||
requireMinPoints?: boolean;
|
||||
requiredNumPoints?: number;
|
||||
algorithm?: string;
|
||||
seasonality?: string;
|
||||
};
|
||||
evaluation?: {
|
||||
|
||||
@@ -4,8 +4,8 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/http/handler"
|
||||
"github.com/SigNoz/signoz/pkg/querybuilder"
|
||||
"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"
|
||||
"github.com/SigNoz/signoz/pkg/types/coretypes"
|
||||
@@ -14,124 +14,343 @@ import (
|
||||
)
|
||||
|
||||
func (provider *provider) addRulerRoutes(router *mux.Router) error {
|
||||
if err := router.Handle("/api/v3/rules", handler.New(provider.authzMiddleware.ViewAccess(provider.rulerHandler.ListRulesV3), handler.OpenAPIDef{
|
||||
ID: "ListRulesV3",
|
||||
Tags: []string{"rules"},
|
||||
Summary: "List alert rules (v3)",
|
||||
Description: "Returns a page of alert rules with their current evaluation state, trimmed to the fields the list page renders. Supports a filter DSL (`query`), a repeated `states` filter applied after the state overlay, sort (`updated_at`/`created_at`/`name`/`state`/`severity`), order (`asc`/`desc`), and offset-based pagination (`limit`/`offset`). In the filter DSL, a non-reserved key is matched as a rule label directly (`team = infra`); a key that collides with a reserved keyword matches either interpretation (negative operators exclude both), and `labels.<key>` targets only the label. The response also carries the org's label pairs and the reserved filter keys for building filter suggestions.",
|
||||
RequestQuery: new(ruletypes.ListRulesParams),
|
||||
Response: new(ruletypes.ListableRules),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest},
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
|
||||
})).Methods(http.MethodGet).GetError(); err != nil {
|
||||
if err := router.Handle("/api/v3/rules", handler.New(
|
||||
provider.authzMiddleware.CheckResources(provider.rulerHandler.ListRulesV3, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "ListRulesV3",
|
||||
Tags: []string{"rules"},
|
||||
Summary: "List alert rules (v3)",
|
||||
Description: "Returns a page of alert rules with their current evaluation state, trimmed to the fields the list page renders. Supports a filter DSL (`query`), a repeated `states` filter applied after the state overlay, sort (`updated_at`/`created_at`/`name`/`state`/`severity`), order (`asc`/`desc`), and offset-based pagination (`limit`/`offset`). In the filter DSL, a non-reserved key is matched as a rule label directly (`team = infra`); a key that collides with a reserved keyword matches either interpretation (negative operators exclude both), and `labels.<key>` targets only the label. The response also carries the org's label pairs and the reserved filter keys for building filter suggestions.",
|
||||
RequestQuery: new(ruletypes.ListRulesParams),
|
||||
Response: new(ruletypes.ListableRules),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest},
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceRule.Scope(coretypes.VerbList)}),
|
||||
},
|
||||
handler.WithResourceDefs(handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceRule,
|
||||
Verb: coretypes.VerbList,
|
||||
Category: coretypes.ActionCategoryDataAccess,
|
||||
Selector: coretypes.WildcardSelector,
|
||||
}),
|
||||
)).Methods(http.MethodGet).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v2/rules/{id}", handler.New(provider.authzMiddleware.ViewAccess(provider.rulerHandler.GetRuleByID), handler.OpenAPIDef{
|
||||
ID: "GetRuleByID",
|
||||
Tags: []string{"rules"},
|
||||
Summary: "Get alert rule by ID",
|
||||
Description: "This endpoint returns an alert rule by ID",
|
||||
Response: new(ruletypes.Rule),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusNotFound},
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
|
||||
})).Methods(http.MethodGet).GetError(); err != nil {
|
||||
if err := router.Handle("/api/v2/rules/{id}", handler.New(
|
||||
provider.authzMiddleware.CheckResources(provider.rulerHandler.GetRuleByID, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "GetRuleByID",
|
||||
Tags: []string{"rules"},
|
||||
Summary: "Get alert rule by ID",
|
||||
Description: "This endpoint returns an alert rule by ID",
|
||||
Response: new(ruletypes.Rule),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusNotFound},
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceRule.Scope(coretypes.VerbRead)}),
|
||||
},
|
||||
handler.WithResourceDefs(handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceRule,
|
||||
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/v2/rules", handler.New(provider.authzMiddleware.EditAccess(provider.rulerHandler.CreateRule), handler.OpenAPIDef{
|
||||
ID: "CreateRule",
|
||||
Tags: []string{"rules"},
|
||||
Summary: "Create alert rule",
|
||||
Description: "This endpoint creates a new alert rule",
|
||||
Request: new(ruletypes.PostableRule),
|
||||
RequestContentType: "application/json",
|
||||
RequestExamples: postableRuleExamples(),
|
||||
Response: new(ruletypes.Rule),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusCreated,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest},
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleEditor),
|
||||
})).Methods(http.MethodPost).GetError(); err != nil {
|
||||
if err := router.Handle("/api/v2/rules", handler.New(
|
||||
provider.authzMiddleware.CheckResources(provider.rulerHandler.CreateRule, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "CreateRule",
|
||||
Tags: []string{"rules"},
|
||||
Summary: "Create alert rule",
|
||||
Description: "This endpoint creates a new alert rule",
|
||||
Request: new(ruletypes.PostableRule),
|
||||
RequestContentType: "application/json",
|
||||
RequestExamples: postableRuleExamples(),
|
||||
Response: new(ruletypes.Rule),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusCreated,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest},
|
||||
SecuritySchemes: newScopedSecuritySchemes(append([]string{
|
||||
coretypes.ResourceMetaResourceRule.Scope(coretypes.VerbCreate),
|
||||
coretypes.ResourceMetaResourceRule.Scope(coretypes.VerbAttach),
|
||||
coretypes.ResourceMetaResourceNotificationChannel.Scope(coretypes.VerbAttach),
|
||||
}, telemetryReadScopes()...)),
|
||||
},
|
||||
handler.WithResourceDefs(
|
||||
handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceRule,
|
||||
Verb: coretypes.VerbCreate,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
ID: coretypes.ResponseJSONPath("data.id"),
|
||||
Selector: coretypes.WildcardSelector,
|
||||
},
|
||||
handler.AttachDetachSiblingResourceDef{
|
||||
Verb: coretypes.VerbAttach,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
SourceResource: coretypes.ResourceMetaResourceRule,
|
||||
SourceIDs: coretypes.OneID(coretypes.ResponseJSONPath("data.id")),
|
||||
SourceSelector: coretypes.WildcardSelector,
|
||||
TargetResource: coretypes.ResourceMetaResourceNotificationChannel,
|
||||
TargetIDs: ruler.NewCreateRuleChannelAttachExtractor(provider.alertmanagerService),
|
||||
TargetSelector: coretypes.IDSelector,
|
||||
},
|
||||
handler.TelemetryResourceDef{
|
||||
Verb: coretypes.VerbRead,
|
||||
Category: coretypes.ActionCategoryDataAccess,
|
||||
Selector: querybuilder.TelemetrySelector,
|
||||
Resources: ruler.NewRuleBodyTelemetryResources(),
|
||||
},
|
||||
),
|
||||
)).Methods(http.MethodPost).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v2/rules/{id}/clone", handler.New(provider.authzMiddleware.EditAccess(provider.rulerHandler.CloneRuleByID), handler.OpenAPIDef{
|
||||
ID: "CloneRuleByID",
|
||||
Tags: []string{"rules"},
|
||||
Summary: "Clone alert rule",
|
||||
Description: "This endpoint creates a new alert rule from the stored definition of an existing one. The clone keeps every modeled field of the source, including its enabled/disabled state, and gets the source's name suffixed with \" - Copy\" (or a bumped \" - Copy (n)\" counter when the source is itself a copy). The clone is owned by the caller.",
|
||||
Response: new(ruletypes.Rule),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusCreated,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleEditor),
|
||||
})).Methods(http.MethodPost).GetError(); err != nil {
|
||||
if err := router.Handle("/api/v2/rules/{id}/clone", handler.New(
|
||||
provider.authzMiddleware.CheckResources(provider.rulerHandler.CloneRuleByID, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "CloneRuleByID",
|
||||
Tags: []string{"rules"},
|
||||
Summary: "Clone alert rule",
|
||||
Description: "This endpoint creates a new alert rule from the stored definition of an existing one. The clone keeps every modeled field of the source, including its enabled/disabled state, and gets the source's name suffixed with \" - Copy\" (or a bumped \" - Copy (n)\" counter when the source is itself a copy). The clone is owned by the caller.",
|
||||
Response: new(ruletypes.Rule),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusCreated,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
|
||||
SecuritySchemes: newScopedSecuritySchemes(append([]string{
|
||||
coretypes.ResourceMetaResourceRule.Scope(coretypes.VerbRead),
|
||||
coretypes.ResourceMetaResourceRule.Scope(coretypes.VerbCreate),
|
||||
coretypes.ResourceMetaResourceRule.Scope(coretypes.VerbAttach),
|
||||
coretypes.ResourceMetaResourceNotificationChannel.Scope(coretypes.VerbAttach),
|
||||
}, telemetryReadScopes()...)),
|
||||
},
|
||||
handler.WithResourceDefs(
|
||||
handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceRule,
|
||||
Verb: coretypes.VerbRead,
|
||||
Category: coretypes.ActionCategoryDataAccess,
|
||||
ID: coretypes.PathParam("id"),
|
||||
Selector: coretypes.IDSelector,
|
||||
},
|
||||
handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceRule,
|
||||
Verb: coretypes.VerbCreate,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
ID: coretypes.ResponseJSONPath("data.id"),
|
||||
Selector: coretypes.WildcardSelector,
|
||||
},
|
||||
handler.AttachDetachSiblingResourceDef{
|
||||
Verb: coretypes.VerbAttach,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
SourceResource: coretypes.ResourceMetaResourceRule,
|
||||
SourceIDs: coretypes.OneID(coretypes.ResponseJSONPath("data.id")),
|
||||
SourceSelector: coretypes.WildcardSelector,
|
||||
TargetResource: coretypes.ResourceMetaResourceNotificationChannel,
|
||||
TargetIDs: ruler.NewCloneRuleChannelAttachExtractor(provider.alertmanagerService, provider.rulerService),
|
||||
TargetSelector: coretypes.IDSelector,
|
||||
},
|
||||
handler.TelemetryResourceDef{
|
||||
Verb: coretypes.VerbRead,
|
||||
Category: coretypes.ActionCategoryDataAccess,
|
||||
Selector: querybuilder.TelemetrySelector,
|
||||
Resources: ruler.NewRuleQueryTelemetryResources(provider.rulerService),
|
||||
},
|
||||
),
|
||||
)).Methods(http.MethodPost).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := router.Handle("/api/v2/rules/{id}", handler.New(
|
||||
provider.authzMiddleware.CheckResources(provider.rulerHandler.UpdateRuleByID, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "UpdateRuleByID",
|
||||
Tags: []string{"rules"},
|
||||
Summary: "Update alert rule",
|
||||
Description: "This endpoint updates an alert rule by ID",
|
||||
Request: new(ruletypes.PostableRule),
|
||||
RequestContentType: "application/json",
|
||||
RequestExamples: postableRuleExamples(),
|
||||
SuccessStatusCode: http.StatusNoContent,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
|
||||
SecuritySchemes: newScopedSecuritySchemes(append([]string{
|
||||
coretypes.ResourceMetaResourceRule.Scope(coretypes.VerbUpdate),
|
||||
coretypes.ResourceMetaResourceRule.Scope(coretypes.VerbAttach),
|
||||
coretypes.ResourceMetaResourceRule.Scope(coretypes.VerbDetach),
|
||||
coretypes.ResourceMetaResourceNotificationChannel.Scope(coretypes.VerbAttach),
|
||||
coretypes.ResourceMetaResourceNotificationChannel.Scope(coretypes.VerbDetach),
|
||||
}, telemetryReadScopes()...)),
|
||||
},
|
||||
handler.WithResourceDefs(
|
||||
handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceRule,
|
||||
Verb: coretypes.VerbUpdate,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
ID: coretypes.PathParam("id"),
|
||||
Selector: coretypes.IDSelector,
|
||||
},
|
||||
handler.AttachDetachSiblingResourceDef{
|
||||
Verb: coretypes.VerbAttach,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
SourceResource: coretypes.ResourceMetaResourceRule,
|
||||
SourceIDs: coretypes.OneID(coretypes.PathParam("id")),
|
||||
SourceSelector: coretypes.IDSelector,
|
||||
TargetResource: coretypes.ResourceMetaResourceNotificationChannel,
|
||||
TargetIDs: ruler.NewReplaceRuleChannelAttachExtractor(provider.alertmanagerService, provider.rulerService),
|
||||
TargetSelector: coretypes.IDSelector,
|
||||
},
|
||||
handler.AttachDetachSiblingResourceDef{
|
||||
Verb: coretypes.VerbDetach,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
SourceResource: coretypes.ResourceMetaResourceRule,
|
||||
SourceIDs: coretypes.OneID(coretypes.PathParam("id")),
|
||||
SourceSelector: coretypes.IDSelector,
|
||||
TargetResource: coretypes.ResourceMetaResourceNotificationChannel,
|
||||
TargetIDs: ruler.NewReplaceRuleChannelDetachExtractor(provider.alertmanagerService, provider.rulerService),
|
||||
TargetSelector: coretypes.IDSelector,
|
||||
},
|
||||
handler.TelemetryResourceDef{
|
||||
Verb: coretypes.VerbRead,
|
||||
Category: coretypes.ActionCategoryDataAccess,
|
||||
Selector: querybuilder.TelemetrySelector,
|
||||
Resources: ruler.NewRuleBodyTelemetryResources(),
|
||||
},
|
||||
),
|
||||
)).Methods(http.MethodPut).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v2/rules/{id}", handler.New(provider.authzMiddleware.EditAccess(provider.rulerHandler.UpdateRuleByID), handler.OpenAPIDef{
|
||||
ID: "UpdateRuleByID",
|
||||
Tags: []string{"rules"},
|
||||
Summary: "Update alert rule",
|
||||
Description: "This endpoint updates an alert rule by ID",
|
||||
Request: new(ruletypes.PostableRule),
|
||||
RequestContentType: "application/json",
|
||||
RequestExamples: postableRuleExamples(),
|
||||
SuccessStatusCode: http.StatusNoContent,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleEditor),
|
||||
})).Methods(http.MethodPut).GetError(); err != nil {
|
||||
if err := router.Handle("/api/v2/rules/{id}", handler.New(
|
||||
provider.authzMiddleware.CheckResources(provider.rulerHandler.DeleteRuleByID, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "DeleteRuleByID",
|
||||
Tags: []string{"rules"},
|
||||
Summary: "Delete alert rule",
|
||||
Description: "This endpoint deletes an alert rule by ID",
|
||||
SuccessStatusCode: http.StatusNoContent,
|
||||
ErrorStatusCodes: []int{http.StatusNotFound},
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceRule.Scope(coretypes.VerbDelete)}),
|
||||
},
|
||||
handler.WithResourceDefs(handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceRule,
|
||||
Verb: coretypes.VerbDelete,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
ID: coretypes.PathParam("id"),
|
||||
Selector: coretypes.IDSelector,
|
||||
}),
|
||||
)).Methods(http.MethodDelete).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v2/rules/{id}", handler.New(provider.authzMiddleware.EditAccess(provider.rulerHandler.DeleteRuleByID), handler.OpenAPIDef{
|
||||
ID: "DeleteRuleByID",
|
||||
Tags: []string{"rules"},
|
||||
Summary: "Delete alert rule",
|
||||
Description: "This endpoint deletes an alert rule by ID",
|
||||
SuccessStatusCode: http.StatusNoContent,
|
||||
ErrorStatusCodes: []int{http.StatusNotFound},
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleEditor),
|
||||
})).Methods(http.MethodDelete).GetError(); err != nil {
|
||||
if err := router.Handle("/api/v2/rules/{id}", handler.New(
|
||||
provider.authzMiddleware.CheckResources(provider.rulerHandler.PatchRuleByID, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "PatchRuleByID",
|
||||
Tags: []string{"rules"},
|
||||
Summary: "Patch alert rule",
|
||||
Description: "This endpoint applies a partial update to an alert rule by ID",
|
||||
Request: new(ruletypes.PostableRule),
|
||||
RequestContentType: "application/json",
|
||||
RequestExamples: postableRuleExamples(),
|
||||
Response: new(ruletypes.Rule),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
|
||||
SecuritySchemes: newScopedSecuritySchemes(append([]string{
|
||||
coretypes.ResourceMetaResourceRule.Scope(coretypes.VerbUpdate),
|
||||
coretypes.ResourceMetaResourceRule.Scope(coretypes.VerbAttach),
|
||||
coretypes.ResourceMetaResourceRule.Scope(coretypes.VerbDetach),
|
||||
coretypes.ResourceMetaResourceNotificationChannel.Scope(coretypes.VerbAttach),
|
||||
coretypes.ResourceMetaResourceNotificationChannel.Scope(coretypes.VerbDetach),
|
||||
}, telemetryReadScopes()...)),
|
||||
},
|
||||
handler.WithResourceDefs(
|
||||
handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceRule,
|
||||
Verb: coretypes.VerbUpdate,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
ID: coretypes.PathParam("id"),
|
||||
Selector: coretypes.IDSelector,
|
||||
},
|
||||
handler.AttachDetachSiblingResourceDef{
|
||||
Verb: coretypes.VerbAttach,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
SourceResource: coretypes.ResourceMetaResourceRule,
|
||||
SourceIDs: coretypes.OneID(coretypes.PathParam("id")),
|
||||
SourceSelector: coretypes.IDSelector,
|
||||
TargetResource: coretypes.ResourceMetaResourceNotificationChannel,
|
||||
TargetIDs: ruler.NewPatchRuleChannelAttachExtractor(provider.alertmanagerService, provider.rulerService),
|
||||
TargetSelector: coretypes.IDSelector,
|
||||
},
|
||||
handler.AttachDetachSiblingResourceDef{
|
||||
Verb: coretypes.VerbDetach,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
SourceResource: coretypes.ResourceMetaResourceRule,
|
||||
SourceIDs: coretypes.OneID(coretypes.PathParam("id")),
|
||||
SourceSelector: coretypes.IDSelector,
|
||||
TargetResource: coretypes.ResourceMetaResourceNotificationChannel,
|
||||
TargetIDs: ruler.NewPatchRuleChannelDetachExtractor(provider.alertmanagerService, provider.rulerService),
|
||||
TargetSelector: coretypes.IDSelector,
|
||||
},
|
||||
handler.TelemetryResourceDef{
|
||||
Verb: coretypes.VerbRead,
|
||||
Category: coretypes.ActionCategoryDataAccess,
|
||||
Selector: querybuilder.TelemetrySelector,
|
||||
Resources: ruler.NewOptionalRuleBodyTelemetryResources(),
|
||||
Optional: true,
|
||||
},
|
||||
),
|
||||
)).Methods(http.MethodPatch).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v2/rules/{id}", handler.New(provider.authzMiddleware.EditAccess(provider.rulerHandler.PatchRuleByID), handler.OpenAPIDef{
|
||||
ID: "PatchRuleByID",
|
||||
Tags: []string{"rules"},
|
||||
Summary: "Patch alert rule",
|
||||
Description: "This endpoint applies a partial update to an alert rule by ID",
|
||||
Request: new(ruletypes.PostableRule),
|
||||
RequestContentType: "application/json",
|
||||
RequestExamples: postableRuleExamples(),
|
||||
Response: new(ruletypes.Rule),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleEditor),
|
||||
})).Methods(http.MethodPatch).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v2/rules/test", handler.New(provider.authzMiddleware.EditAccess(provider.rulerHandler.TestRule), handler.OpenAPIDef{
|
||||
ID: "TestRule",
|
||||
Tags: []string{"rules"},
|
||||
Summary: "Test alert rule",
|
||||
Description: "This endpoint fires a test notification for the given rule definition",
|
||||
Request: new(ruletypes.PostableRule),
|
||||
RequestContentType: "application/json",
|
||||
RequestExamples: postableRuleExamples(),
|
||||
Response: new(ruletypes.GettableTestRule),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest},
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleEditor),
|
||||
})).Methods(http.MethodPost).GetError(); err != nil {
|
||||
if err := router.Handle("/api/v2/rules/test", handler.New(
|
||||
provider.authzMiddleware.CheckResources(provider.rulerHandler.TestRule, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "TestRule",
|
||||
Tags: []string{"rules"},
|
||||
Summary: "Test alert rule",
|
||||
Description: "This endpoint fires a test notification for the given rule definition",
|
||||
Request: new(ruletypes.PostableRule),
|
||||
RequestContentType: "application/json",
|
||||
RequestExamples: postableRuleExamples(),
|
||||
Response: new(ruletypes.GettableTestRule),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest},
|
||||
SecuritySchemes: newScopedSecuritySchemes(append([]string{
|
||||
coretypes.ResourceMetaResourceRule.Scope(coretypes.VerbCreate),
|
||||
coretypes.ResourceMetaResourceRule.Scope(coretypes.VerbAttach),
|
||||
coretypes.ResourceMetaResourceNotificationChannel.Scope(coretypes.VerbAttach),
|
||||
}, telemetryReadScopes()...)),
|
||||
},
|
||||
handler.WithResourceDefs(
|
||||
handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceRule,
|
||||
Verb: coretypes.VerbCreate,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
Selector: coretypes.WildcardSelector,
|
||||
},
|
||||
handler.AttachDetachSiblingResourceDef{
|
||||
Verb: coretypes.VerbAttach,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
SourceResource: coretypes.ResourceMetaResourceRule,
|
||||
SourceSelector: coretypes.WildcardSelector,
|
||||
TargetResource: coretypes.ResourceMetaResourceNotificationChannel,
|
||||
TargetIDs: ruler.NewCreateRuleChannelAttachExtractor(provider.alertmanagerService),
|
||||
TargetSelector: coretypes.IDSelector,
|
||||
},
|
||||
handler.TelemetryResourceDef{
|
||||
Verb: coretypes.VerbRead,
|
||||
Category: coretypes.ActionCategoryDataAccess,
|
||||
Selector: querybuilder.TelemetrySelector,
|
||||
Resources: ruler.NewRuleBodyTelemetryResources(),
|
||||
},
|
||||
),
|
||||
)).Methods(http.MethodPost).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -251,7 +251,6 @@ func postableRuleExamples() []handler.OpenAPIExample {
|
||||
},
|
||||
},
|
||||
},
|
||||
"algorithm": "standard",
|
||||
"seasonality": "daily",
|
||||
"selectedQueryName": "A",
|
||||
"requireMinPoints": true,
|
||||
|
||||
@@ -5,28 +5,23 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/types/ruletypes"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestPostableRuleExamplesValidate verifies every example payload returned by
|
||||
// postableRuleExamples() round-trips through PostableRule.UnmarshalJSON and
|
||||
// postableRuleExamples() round-trips through PostableRule.DecodeStrict and
|
||||
// passes Validate(). If an example drifts from the runtime contract this
|
||||
// breaks loudly so the spec doesn't ship invalid payloads to users.
|
||||
func TestPostableRuleExamplesValidate(t *testing.T) {
|
||||
for _, example := range postableRuleExamples() {
|
||||
t.Run(example.Name, func(t *testing.T) {
|
||||
raw, err := json.Marshal(example.Value)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal example: %v", err)
|
||||
}
|
||||
require.NoError(t, err)
|
||||
|
||||
var rule ruletypes.PostableRule
|
||||
if err := json.Unmarshal(raw, &rule); err != nil {
|
||||
t.Fatalf("unmarshal: %v\npayload: %s", err, raw)
|
||||
}
|
||||
|
||||
if err := rule.Validate(); err != nil {
|
||||
t.Fatalf("Validate: %v\npayload: %s", err, raw)
|
||||
}
|
||||
require.NoError(t, rule.DecodeStrict(string(raw)), "payload: %s", raw)
|
||||
assert.NoError(t, rule.Validate(), "payload: %s", raw)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,7 +68,13 @@ func (provider *provider) addUserRoutes(router *mux.Router) error {
|
||||
ErrorStatusCodes: []int{},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: []handler.OpenAPISecurityScheme{{Name: authtypes.IdentNProviderTokenizer.StringValue()}},
|
||||
})).Methods(http.MethodGet).GetError(); err != nil {
|
||||
}, handler.WithResourceDefs(handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceUser,
|
||||
Verb: coretypes.VerbRead,
|
||||
Category: coretypes.ActionCategoryAccessControl,
|
||||
ID: provider.userIDExtractor(),
|
||||
Selector: coretypes.IDSelector,
|
||||
}))).Methods(http.MethodGet).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -128,7 +134,13 @@ func (provider *provider) addUserRoutes(router *mux.Router) error {
|
||||
ErrorStatusCodes: []int{},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: []handler.OpenAPISecurityScheme{{Name: authtypes.IdentNProviderTokenizer.StringValue()}},
|
||||
})).Methods(http.MethodPut).GetError(); err != nil {
|
||||
}, handler.WithResourceDefs(handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceUser,
|
||||
Verb: coretypes.VerbUpdate,
|
||||
Category: coretypes.ActionCategoryAccessControl,
|
||||
ID: provider.userIDExtractor(),
|
||||
Selector: coretypes.IDSelector,
|
||||
}))).Methods(http.MethodPut).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -294,7 +306,12 @@ func (provider *provider) addUserRoutes(router *mux.Router) error {
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: []handler.OpenAPISecurityScheme{},
|
||||
})).Methods(http.MethodPost).GetError(); err != nil {
|
||||
}, handler.WithResourceDefs(handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceFactorPassword,
|
||||
Verb: coretypes.VerbRead,
|
||||
Category: coretypes.ActionCategoryAccessControl,
|
||||
Selector: coretypes.WildcardSelector,
|
||||
}))).Methods(http.MethodPost).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -311,7 +328,12 @@ func (provider *provider) addUserRoutes(router *mux.Router) error {
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: []handler.OpenAPISecurityScheme{{Name: authtypes.IdentNProviderTokenizer.StringValue()}},
|
||||
})).Methods(http.MethodPut).GetError(); err != nil {
|
||||
}, handler.WithResourceDefs(handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceFactorPassword,
|
||||
Verb: coretypes.VerbUpdate,
|
||||
Category: coretypes.ActionCategoryAccessControl,
|
||||
Selector: coretypes.WildcardSelector,
|
||||
}))).Methods(http.MethodPut).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -328,7 +350,12 @@ func (provider *provider) addUserRoutes(router *mux.Router) error {
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusUnprocessableEntity},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: []handler.OpenAPISecurityScheme{},
|
||||
})).Methods(http.MethodPost).GetError(); err != nil {
|
||||
}, handler.WithResourceDefs(handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceFactorPassword,
|
||||
Verb: coretypes.VerbCreate,
|
||||
Category: coretypes.ActionCategoryAccessControl,
|
||||
Selector: coretypes.WildcardSelector,
|
||||
}))).Methods(http.MethodPost).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -345,7 +372,12 @@ func (provider *provider) addUserRoutes(router *mux.Router) error {
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: []handler.OpenAPISecurityScheme{},
|
||||
})).Methods(http.MethodPost).GetError(); err != nil {
|
||||
}, handler.WithResourceDefs(handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceFactorPassword,
|
||||
Verb: coretypes.VerbUpdate,
|
||||
Category: coretypes.ActionCategoryAccessControl,
|
||||
Selector: coretypes.WildcardSelector,
|
||||
}))).Methods(http.MethodPost).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -493,6 +525,21 @@ func (provider *provider) addUserRoutes(router *mux.Router) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (provider *provider) userIDExtractor() coretypes.ResourceIDExtractor {
|
||||
return coretypes.NewResourceIDExtractor(coretypes.PhaseRequest, func(ec coretypes.ExtractorContext) (string, error) {
|
||||
if ec.Request == nil {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
claims, err := authtypes.ClaimsFromContext(ec.Request.Context())
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return claims.UserID, nil
|
||||
})
|
||||
}
|
||||
|
||||
func (provider *provider) userRoleUserIDExtractor() coretypes.ResourceIDExtractor {
|
||||
return coretypes.NewResourceIDExtractor(coretypes.PhaseRequest, func(ec coretypes.ExtractorContext) (string, error) {
|
||||
if ec.Request == nil {
|
||||
|
||||
@@ -109,6 +109,8 @@ type TelemetryResourceDef struct {
|
||||
Category coretypes.ActionCategory
|
||||
Selector coretypes.SelectorFunc
|
||||
Resources coretypes.ResourceExtractor
|
||||
// Optional skips the check instead of failing when the request carries no telemetry resources.
|
||||
Optional bool
|
||||
}
|
||||
|
||||
func (def TelemetryResourceDef) resolveRequest(ec coretypes.ExtractorContext) []coretypes.ResolvedResource {
|
||||
@@ -116,6 +118,9 @@ func (def TelemetryResourceDef) resolveRequest(ec coretypes.ExtractorContext) []
|
||||
if err != nil {
|
||||
return []coretypes.ResolvedResource{coretypes.NewResolvedResourceWithError(def.Verb, def.Category, err)}
|
||||
}
|
||||
if len(refs) == 0 && def.Optional {
|
||||
return nil
|
||||
}
|
||||
if len(refs) == 0 {
|
||||
return []coretypes.ResolvedResource{coretypes.NewResolvedResourceWithError(
|
||||
def.Verb,
|
||||
|
||||
@@ -69,3 +69,43 @@ func TestAttachDetachSiblingResourceDefKeepsEmptySingleID(t *testing.T) {
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, []string{""}, withTarget.TargetIDs())
|
||||
}
|
||||
|
||||
func TestTelemetryResourceDefWithoutResources(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
optional bool
|
||||
wantLen int
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "Required_Errors",
|
||||
optional: false,
|
||||
wantLen: 1,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "Optional_ResolvesNothing",
|
||||
optional: true,
|
||||
wantLen: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
def := TelemetryResourceDef{
|
||||
Verb: coretypes.VerbRead,
|
||||
Category: coretypes.ActionCategoryDataAccess,
|
||||
Selector: coretypes.WildcardSelector,
|
||||
Resources: func(coretypes.ExtractorContext) ([]coretypes.ResourceWithID, error) { return nil, nil },
|
||||
Optional: testCase.optional,
|
||||
}
|
||||
|
||||
resolved := ResolveRequest([]ResourceDef{def}, coretypes.ExtractorContext{})
|
||||
|
||||
require.Len(t, resolved, testCase.wantLen)
|
||||
if testCase.wantErr {
|
||||
assert.Error(t, resolved[0].Err())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2688,19 +2688,7 @@ func (aH *APIHandler) PreviewLogsPipelinesHandler(w http.ResponseWriter, r *http
|
||||
return
|
||||
}
|
||||
|
||||
claims, errv2 := authtypes.ClaimsFromContext(r.Context())
|
||||
if errv2 != nil {
|
||||
render.Error(w, errv2)
|
||||
return
|
||||
}
|
||||
|
||||
orgID, errv2 := valuer.NewUUID(claims.OrgID)
|
||||
if errv2 != nil {
|
||||
render.Error(w, errv2)
|
||||
return
|
||||
}
|
||||
|
||||
resultLogs, err := aH.LogsParsingPipelineController.PreviewLogsPipelines(r.Context(), orgID, &req)
|
||||
resultLogs, err := aH.LogsParsingPipelineController.PreviewLogsPipelines(r.Context(), &req)
|
||||
if err != nil {
|
||||
render.Error(w, err)
|
||||
return
|
||||
|
||||
@@ -165,22 +165,6 @@ func isNormalizerProcessor(name string) bool {
|
||||
return name == normalizerProcessor || strings.HasPrefix(name, normalizerProcessorPrefix)
|
||||
}
|
||||
|
||||
// collectorNormalizesFirst reports whether the logs pipeline of the collector config runs
|
||||
// signozlogsnormalizer ahead of user pipelines, judged by the first one as in buildCollectorPipelineProcessorsList.
|
||||
// Malformed configs report false; generateCollectorConfigWithPipelines surfaces their errors.
|
||||
func collectorNormalizesFirst(collectorConf map[string]interface{}) bool {
|
||||
p, err := getOtelPipelineFromConfig(collectorConf)
|
||||
if err != nil || p.Pipelines.Logs == nil {
|
||||
return false
|
||||
}
|
||||
normalizerIdx := slices.IndexFunc(p.Pipelines.Logs.Processors, isNormalizerProcessor)
|
||||
if normalizerIdx < 0 {
|
||||
return false
|
||||
}
|
||||
processorConfigs, _ := collectorConf["processors"].(map[string]interface{})
|
||||
return opampPosition(processorConfigs, p.Pipelines.Logs.Processors[normalizerIdx]) == normalizerBeforeUserPipelines
|
||||
}
|
||||
|
||||
func opampPosition(processorConfigs map[string]interface{}, name string) string {
|
||||
config, _ := processorConfigs[name].(map[string]interface{})
|
||||
opamp, _ := config["opamp"].(map[string]interface{})
|
||||
|
||||
@@ -5,12 +5,10 @@ import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/flagger/flaggertest"
|
||||
"github.com/SigNoz/signoz/pkg/query-service/constants"
|
||||
"github.com/SigNoz/signoz/pkg/query-service/model"
|
||||
v3 "github.com/SigNoz/signoz/pkg/query-service/model/v3"
|
||||
"github.com/SigNoz/signoz/pkg/types/pipelinetypes"
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
. "github.com/smartystreets/goconvey/convey"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -501,61 +499,3 @@ func TestPipeCharInAliasDoesntBreakCollectorConfig(t *testing.T) {
|
||||
}, result[0].Attributes_string,
|
||||
)
|
||||
}
|
||||
|
||||
func TestRecommendAgentConfigWithNormalizerProcessorAndJSONBody(t *testing.T) {
|
||||
userPipeline := makeTestAddAttributePipeline()
|
||||
controller := &LogParsingPipelineController{
|
||||
fl: flaggertest.WithUseJSONBody(t, true),
|
||||
GetIntegrationPipelines: func(context.Context, string) ([]pipelinetypes.GettablePipeline, error) {
|
||||
return []pipelinetypes.GettablePipeline{userPipeline}, nil
|
||||
},
|
||||
}
|
||||
normalizeOperator := CollectorConfProcessorName(getNormalizePipeline())
|
||||
user := CollectorConfProcessorName(userPipeline)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
processors string
|
||||
logs string
|
||||
expected []any
|
||||
}{
|
||||
{
|
||||
name: "NoNormalizer_OperatorPrepended",
|
||||
logs: "[memory_limiter, batch]",
|
||||
expected: []any{"memory_limiter", normalizeOperator, user, "batch"},
|
||||
},
|
||||
{
|
||||
name: "NormalizerDefault_OperatorKept",
|
||||
logs: "[memory_limiter, signozlogsnormalizer, batch]",
|
||||
expected: []any{"memory_limiter", normalizeOperator, user, "signozlogsnormalizer", "batch"},
|
||||
},
|
||||
{
|
||||
name: "NormalizerBefore_OperatorDropped",
|
||||
processors: "signozlogsnormalizer:\n opamp:\n position: before\n",
|
||||
logs: "[memory_limiter, signozlogsnormalizer, batch]",
|
||||
expected: []any{"memory_limiter", "signozlogsnormalizer", user, "batch"},
|
||||
},
|
||||
{
|
||||
name: "NormalizerAfter_OperatorKept",
|
||||
processors: "signozlogsnormalizer:\n opamp:\n position: after\n",
|
||||
logs: "[memory_limiter, signozlogsnormalizer, batch]",
|
||||
expected: []any{"memory_limiter", normalizeOperator, user, "signozlogsnormalizer", "batch"},
|
||||
},
|
||||
}
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
conf := fmt.Sprintf(
|
||||
"processors:\n memory_limiter: {}\n batch: {}\n %s\nservice:\n pipelines:\n logs:\n receivers: [otlp]\n processors: %s\n exporters: [clickhouselogsexporter]\n",
|
||||
testCase.processors, testCase.logs,
|
||||
)
|
||||
|
||||
recommended, _, err := controller.RecommendAgentConfig(valuer.GenerateUUID(), []byte(conf), nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
var recommendedConf map[string]any
|
||||
require.NoError(t, yaml.Unmarshal(recommended, &recommendedConf))
|
||||
logs := recommendedConf["service"].(map[string]any)["pipelines"].(map[string]any)["logs"].(map[string]any)
|
||||
assert.Equal(t, testCase.expected, logs["processors"])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/flagger"
|
||||
"github.com/SigNoz/signoz/pkg/query-service/agentConf"
|
||||
"github.com/SigNoz/signoz/pkg/query-service/constants"
|
||||
"github.com/SigNoz/signoz/pkg/query-service/interfaces"
|
||||
@@ -20,7 +19,6 @@ import (
|
||||
"github.com/SigNoz/signoz/pkg/query-service/utils"
|
||||
"github.com/SigNoz/signoz/pkg/sqlstore"
|
||||
"github.com/SigNoz/signoz/pkg/types"
|
||||
"github.com/SigNoz/signoz/pkg/types/featuretypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/opamptypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/pipelinetypes"
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
@@ -39,21 +37,18 @@ type LogParsingPipelineController struct {
|
||||
GetIntegrationPipelines func(context.Context, string) ([]pipelinetypes.GettablePipeline, error)
|
||||
// TODO(Piyush): remove with qbv5 migration
|
||||
reader interfaces.Reader
|
||||
fl flagger.Flagger
|
||||
}
|
||||
|
||||
func NewLogParsingPipelinesController(
|
||||
sqlStore sqlstore.SQLStore,
|
||||
getIntegrationPipelines func(context.Context, string) ([]pipelinetypes.GettablePipeline, error),
|
||||
reader interfaces.Reader,
|
||||
fl flagger.Flagger,
|
||||
) (*LogParsingPipelineController, error) {
|
||||
repo := NewRepo(sqlStore)
|
||||
return &LogParsingPipelineController{
|
||||
Repo: repo,
|
||||
GetIntegrationPipelines: getIntegrationPipelines,
|
||||
reader: reader,
|
||||
fl: fl,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -220,44 +215,6 @@ func (ic *LogParsingPipelineController) ValidatePipelines(ctx context.Context,
|
||||
return err
|
||||
}
|
||||
|
||||
// withNormalizePipeline places normalize ahead of user pipelines when queries run on body_v2
|
||||
// (use_json_body), so operators see the body the explorer shows. Absent when the flag is off
|
||||
// or collectorNormalizesFirst.
|
||||
func (ic *LogParsingPipelineController) withNormalizePipeline(ctx context.Context, orgID valuer.UUID, pipelines []pipelinetypes.GettablePipeline, collectorNormalizesFirst bool) []pipelinetypes.GettablePipeline {
|
||||
if collectorNormalizesFirst || !ic.fl.BooleanOrEmpty(ctx, flagger.FeatureUseJSONBody, featuretypes.NewFlaggerEvaluationContext(orgID)) {
|
||||
return pipelines
|
||||
}
|
||||
return append([]pipelinetypes.GettablePipeline{getNormalizePipeline()}, pipelines...)
|
||||
}
|
||||
|
||||
func getNormalizePipeline() pipelinetypes.GettablePipeline {
|
||||
return pipelinetypes.GettablePipeline{
|
||||
StoreablePipeline: pipelinetypes.StoreablePipeline{
|
||||
Name: "Default Pipeline - PreProcessing Body",
|
||||
Alias: "NormalizeBodyDefault",
|
||||
Enabled: true,
|
||||
},
|
||||
Filter: &v3.FilterSet{
|
||||
Items: []v3.FilterItem{
|
||||
{
|
||||
Key: v3.AttributeKey{
|
||||
Key: "body",
|
||||
},
|
||||
Operator: v3.FilterOperatorExists,
|
||||
},
|
||||
},
|
||||
},
|
||||
Config: []pipelinetypes.PipelineOperator{
|
||||
{
|
||||
ID: uuid.NewString(),
|
||||
Type: "normalize",
|
||||
Enabled: true,
|
||||
If: "body != nil",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Returns effective list of pipelines including user created
|
||||
// pipelines and pipelines for installed integrations
|
||||
func (ic *LogParsingPipelineController) getEffectivePipelinesByVersion(
|
||||
@@ -352,7 +309,6 @@ type PipelinesPreviewResponse struct {
|
||||
|
||||
func (ic *LogParsingPipelineController) PreviewLogsPipelines(
|
||||
ctx context.Context,
|
||||
orgID valuer.UUID,
|
||||
request *PipelinesPreviewRequest,
|
||||
) (*PipelinesPreviewResponse, error) {
|
||||
pipelines, err := ic.enrichPipelinesFilters(ctx, request.Pipelines)
|
||||
@@ -360,11 +316,6 @@ func (ic *LogParsingPipelineController) PreviewLogsPipelines(
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// The collector gets the same pipeline prepended over opamp; see RecommendAgentConfig.
|
||||
if ic.fl.BooleanOrEmpty(ctx, flagger.FeatureUseJSONBody, featuretypes.NewFlaggerEvaluationContext(orgID)) {
|
||||
pipelines = append([]pipelinetypes.GettablePipeline{getNormalizePipeline()}, pipelines...)
|
||||
}
|
||||
|
||||
result, collectorLogs, err := SimulatePipelinesProcessing(ctx, pipelines, request.Logs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -383,16 +334,13 @@ func (pc *LogParsingPipelineController) AgentFeatureType() agentConf.AgentFeatur
|
||||
|
||||
// Implements agentConf.AgentFeature interface.
|
||||
// RecommendAgentConfig generates the collector config to be sent to agents.
|
||||
// The normalize pipeline (when use_json_body is on) is placed
|
||||
// here, after rawPipelineData is serialized. So it is only present in the config sent to
|
||||
// the collector and never persisted to the database as part of the user's pipeline list.
|
||||
//
|
||||
// NOTE: The configId sent to agents is derived from the pipeline version number
|
||||
// (e.g. "LogPipelines:5"), not the YAML content. If server-side logic changes
|
||||
// the generated YAML without bumping the version (e.g. toggling the use_json_body
|
||||
// flag or updating operator IfExpressions), agents that already
|
||||
// applied that version will not re-apply the new config. In such cases, users must save a
|
||||
// new pipeline version via the API to force agents to pick up the change.
|
||||
// the generated YAML without bumping the version (e.g. updating operator IfExpressions),
|
||||
// agents that already applied that version will not re-apply the new config. In such
|
||||
// cases, users must save a new pipeline version via the API to force agents to pick up
|
||||
// the change.
|
||||
func (pc *LogParsingPipelineController) RecommendAgentConfig(
|
||||
orgId valuer.UUID,
|
||||
currentConfYaml []byte,
|
||||
@@ -418,15 +366,7 @@ func (pc *LogParsingPipelineController) RecommendAgentConfig(
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
collectorConf, err := unmarshalCollectorConfig(currentConfYaml)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
// normalize is only for sending to the collector, never persisted
|
||||
enrichedPipelines = pc.withNormalizePipeline(ctx, orgId, enrichedPipelines, collectorNormalizesFirst(collectorConf))
|
||||
|
||||
updatedConf, err := generateCollectorConfigWithPipelines(collectorConf, enrichedPipelines)
|
||||
updatedConf, err := GenerateCollectorConfigWithPipelines(currentConfYaml, enrichedPipelines)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
@@ -6,11 +6,9 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/flagger/flaggertest"
|
||||
"github.com/SigNoz/signoz/pkg/query-service/model"
|
||||
v3 "github.com/SigNoz/signoz/pkg/query-service/model/v3"
|
||||
"github.com/SigNoz/signoz/pkg/types/pipelinetypes"
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
"github.com/google/uuid"
|
||||
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/entry"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -119,42 +117,11 @@ func TestPipelinePreview(t *testing.T) {
|
||||
|
||||
}
|
||||
|
||||
func TestPipelinePreviewNormalizesBodyWithJSONBodyEnabled(t *testing.T) {
|
||||
controller := &LogParsingPipelineController{fl: flaggertest.WithUseJSONBody(t, true)}
|
||||
func TestPipelinePreviewKeepsBodyAsIs(t *testing.T) {
|
||||
controller := &LogParsingPipelineController{}
|
||||
|
||||
result, err := controller.PreviewLogsPipelines(
|
||||
context.Background(),
|
||||
valuer.GenerateUUID(),
|
||||
&PipelinesPreviewRequest{
|
||||
Pipelines: []pipelinetypes.GettablePipeline{makeTestAddAttributePipeline()},
|
||||
Logs: []model.SignozLog{
|
||||
makeTestSignozLog("test log body", map[string]interface{}{"method": "GET"}),
|
||||
makeTestSignozLog(
|
||||
`{"level":"error","msg":"json log body"}`,
|
||||
map[string]interface{}{"method": "GET"},
|
||||
),
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, result.OutputLogs, 2)
|
||||
|
||||
assert.Equal(t, `{"message":"test log body"}`, result.OutputLogs[0].Body)
|
||||
assert.Equal(
|
||||
t,
|
||||
`{"level":"error","message":"json log body"}`,
|
||||
result.OutputLogs[1].Body,
|
||||
)
|
||||
assert.Equal(t, "val", result.OutputLogs[0].Attributes_string["test"])
|
||||
}
|
||||
|
||||
func TestPipelinePreviewKeepsBodyAsIsWithJSONBodyDisabled(t *testing.T) {
|
||||
controller := &LogParsingPipelineController{fl: flaggertest.WithUseJSONBody(t, false)}
|
||||
|
||||
result, err := controller.PreviewLogsPipelines(
|
||||
context.Background(),
|
||||
valuer.GenerateUUID(),
|
||||
&PipelinesPreviewRequest{
|
||||
Pipelines: []pipelinetypes.GettablePipeline{makeTestAddAttributePipeline()},
|
||||
Logs: []model.SignozLog{
|
||||
|
||||
@@ -46,7 +46,6 @@ func NewServer(config signoz.Config, signoz *signoz.SigNoz) (*Server, error) {
|
||||
signoz.SQLStore,
|
||||
integrationsController.GetPipelinesForInstalledIntegrations,
|
||||
reader,
|
||||
signoz.Flagger,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -1054,31 +1054,24 @@ func (m *Manager) PatchRule(ctx context.Context, ruleStr string, id valuer.UUID)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
storedRule := ruletypes.PostableRule{}
|
||||
if err := json.Unmarshal([]byte(storedJSON.Data), &storedRule); err != nil {
|
||||
m.logger.ErrorContext(ctx, "failed to unmarshal rule from db", slog.String("rule.id", id.StringValue()), errors.Attr(err))
|
||||
return nil, err
|
||||
}
|
||||
// a rule stored before selectedQueryName was required resolves it the way evaluation does
|
||||
storedRule.RuleCondition.SelectedQuery = storedRule.RuleCondition.SelectedQueryName()
|
||||
|
||||
if err := storedRule.DecodeStrict(ruleStr); err != nil {
|
||||
storedRule, err := ruletypes.NewPatchedPostableRule([]byte(storedJSON.Data), []byte(ruleStr))
|
||||
if err != nil {
|
||||
m.logger.ErrorContext(ctx, "failed to unmarshal patched rule with given id", slog.String("rule.id", id.StringValue()), errors.Attr(err))
|
||||
return nil, err
|
||||
}
|
||||
if err := storedRule.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := m.validateChannels(ctx, claims.OrgID, &storedRule); err != nil {
|
||||
if err := m.validateChannels(ctx, claims.OrgID, storedRule); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// deploy or un-deploy task according to patched (new) rule state
|
||||
if err := m.syncRuleStateWithTask(ctx, orgID, taskName, &storedRule); err != nil {
|
||||
if err := m.syncRuleStateWithTask(ctx, orgID, taskName, storedRule); err != nil {
|
||||
m.logger.ErrorContext(ctx, "failed to sync stored rule state with the task", slog.String("task.name", taskName), errors.Attr(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
newStoredJson, err := json.Marshal(&storedRule)
|
||||
newStoredJson, err := json.Marshal(storedRule)
|
||||
if err != nil {
|
||||
m.logger.ErrorContext(ctx, "failed to marshal new stored rule with given id", slog.String("rule.id", id.StringValue()), errors.Attr(err))
|
||||
return nil, err
|
||||
@@ -1091,7 +1084,7 @@ func (m *Manager) PatchRule(ctx context.Context, ruleStr string, id valuer.UUID)
|
||||
|
||||
err = m.ruleStore.EditRule(ctx, storedJSON, func(ctx context.Context) error { return nil })
|
||||
if err != nil {
|
||||
if err := m.syncRuleStateWithTask(ctx, orgID, taskName, &storedRule); err != nil {
|
||||
if err := m.syncRuleStateWithTask(ctx, orgID, taskName, storedRule); err != nil {
|
||||
m.logger.ErrorContext(ctx, "failed to restore rule after patch failure", "task_name", taskName, errors.Attr(err))
|
||||
}
|
||||
return nil, err
|
||||
@@ -1100,7 +1093,7 @@ func (m *Manager) PatchRule(ctx context.Context, ruleStr string, id valuer.UUID)
|
||||
// prepare http response
|
||||
response := ruletypes.GettableRule{
|
||||
Id: id.StringValue(),
|
||||
PostableRule: storedRule,
|
||||
PostableRule: *storedRule,
|
||||
}
|
||||
|
||||
// fetch state of rule from memory
|
||||
|
||||
@@ -5,12 +5,15 @@ import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/alertmanager"
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/querybuilder"
|
||||
"github.com/SigNoz/signoz/pkg/types/alertmanagertypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/authtypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/coretypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/ruletypes"
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -20,6 +23,8 @@ const (
|
||||
|
||||
type diffSide int
|
||||
|
||||
type incomingChannelsFunc func(stored *ruletypes.GettableRule, body []byte) ([]string, error)
|
||||
|
||||
var DowntimeRuleIDsExtractor = coretypes.ResourceIDsExtractor{Phase: coretypes.PhaseRequest, Fn: func(ec coretypes.ExtractorContext) ([]string, error) {
|
||||
ids, err := coretypes.BodyJSONArray("alertIds").Fn(ec)
|
||||
if err != nil {
|
||||
@@ -81,6 +86,126 @@ func newDowntimeDiffExtractor(rulerService Ruler, side diffSide) coretypes.Resou
|
||||
}}
|
||||
}
|
||||
|
||||
func NewCreateRuleChannelAttachExtractor(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 := parseRuleChannels(ec.RequestBody)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return resolveKnownChannelIDs(ctx, alertmanagerService, orgID, names)
|
||||
}}
|
||||
}
|
||||
|
||||
func NewCloneRuleChannelAttachExtractor(alertmanagerService alertmanager.Alertmanager, rulerService Ruler) 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 := fetchStoredRule(ec, rulerService)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return resolveKnownChannelIDs(ctx, alertmanagerService, orgID, stored.Channels())
|
||||
}}
|
||||
}
|
||||
|
||||
func NewReplaceRuleChannelAttachExtractor(alertmanagerService alertmanager.Alertmanager, rulerService Ruler) coretypes.ResourceIDsExtractor {
|
||||
return newRuleChannelDiffExtractor(alertmanagerService, rulerService, parseReplacedRuleChannels, attachedSide)
|
||||
}
|
||||
|
||||
func NewReplaceRuleChannelDetachExtractor(alertmanagerService alertmanager.Alertmanager, rulerService Ruler) coretypes.ResourceIDsExtractor {
|
||||
return newRuleChannelDiffExtractor(alertmanagerService, rulerService, parseReplacedRuleChannels, detachedSide)
|
||||
}
|
||||
|
||||
func NewPatchRuleChannelAttachExtractor(alertmanagerService alertmanager.Alertmanager, rulerService Ruler) coretypes.ResourceIDsExtractor {
|
||||
return newRuleChannelDiffExtractor(alertmanagerService, rulerService, parsePatchedRuleChannels, attachedSide)
|
||||
}
|
||||
|
||||
func NewPatchRuleChannelDetachExtractor(alertmanagerService alertmanager.Alertmanager, rulerService Ruler) coretypes.ResourceIDsExtractor {
|
||||
return newRuleChannelDiffExtractor(alertmanagerService, rulerService, parsePatchedRuleChannels, detachedSide)
|
||||
}
|
||||
|
||||
func newRuleChannelDiffExtractor(alertmanagerService alertmanager.Alertmanager, rulerService Ruler, incoming incomingChannelsFunc, 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 := fetchStoredRule(ec, rulerService)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
incomingNames, err := incoming(stored, ec.RequestBody)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
attached, detached := diffLinks(stored.Channels(), incomingNames)
|
||||
if side == detachedSide {
|
||||
return resolveKnownChannelIDs(ctx, alertmanagerService, orgID, detached)
|
||||
}
|
||||
|
||||
return resolveKnownChannelIDs(ctx, alertmanagerService, orgID, attached)
|
||||
}}
|
||||
}
|
||||
|
||||
func parseReplacedRuleChannels(_ *ruletypes.GettableRule, body []byte) ([]string, error) {
|
||||
return parseRuleChannels(body)
|
||||
}
|
||||
|
||||
func parsePatchedRuleChannels(stored *ruletypes.GettableRule, body []byte) ([]string, error) {
|
||||
patched, err := applyRulePatch(stored, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return patched.Channels(), nil
|
||||
}
|
||||
|
||||
func applyRulePatch(stored *ruletypes.GettableRule, body []byte) (*ruletypes.PostableRule, error) {
|
||||
encoded, err := json.Marshal(stored.PostableRule)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return ruletypes.NewPatchedPostableRule(encoded, body)
|
||||
}
|
||||
|
||||
func parseRuleChannels(body []byte) ([]string, error) {
|
||||
rule := new(ruletypes.PostableRule)
|
||||
if err := rule.DecodeStrict(string(body)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return rule.Channels(), nil
|
||||
}
|
||||
|
||||
func diffDowntimeRuleLinks(stored, incoming []string) (attached, detached []string) {
|
||||
return diffLinks(defaultToWildcardIfEmpty(stored), incoming)
|
||||
}
|
||||
@@ -153,6 +278,20 @@ func newRoutePolicyDiffExtractor(alertmanagerService alertmanager.Alertmanager,
|
||||
}}
|
||||
}
|
||||
|
||||
// resolveKnownChannelIDs skips unknown names, the handler rejects them with a clearer error.
|
||||
func resolveKnownChannelIDs(ctx context.Context, alertmanagerService alertmanager.Alertmanager, orgID valuer.UUID, names []string) ([]string, error) {
|
||||
if len(names) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
channels, err := alertmanagerService.ListChannels(ctx, orgID.StringValue())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return alertmanagertypes.MapKnownChannelNamesToIDs(channels, names), nil
|
||||
}
|
||||
|
||||
func orgIDFromContext(ctx context.Context) (valuer.UUID, error) {
|
||||
claims, err := authtypes.ClaimsFromContext(ctx)
|
||||
if err != nil {
|
||||
@@ -184,17 +323,47 @@ func NewRuleQueryFieldResources(rulerService Ruler) coretypes.ResourceExtractor
|
||||
}
|
||||
}
|
||||
|
||||
func fetchStoredCompositeQuery(ec coretypes.ExtractorContext, rulerService Ruler) ([]byte, error) {
|
||||
if ec.Request == nil {
|
||||
return nil, nil
|
||||
}
|
||||
func NewRuleBodyTelemetryResources() coretypes.ResourceExtractor {
|
||||
return func(ec coretypes.ExtractorContext) ([]coretypes.ResourceWithID, error) {
|
||||
compositeQuery := gjson.GetBytes(ec.RequestBody, "condition.compositeQuery")
|
||||
if !compositeQuery.Exists() {
|
||||
return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "condition.compositeQuery is required")
|
||||
}
|
||||
|
||||
body, err := json.Marshal(map[string]json.RawMessage{"compositeQuery": json.RawMessage(compositeQuery.Raw)})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return querybuilder.QueryRangeResources(coretypes.ExtractorContext{Request: ec.Request, RequestBody: body})
|
||||
}
|
||||
}
|
||||
|
||||
func NewOptionalRuleBodyTelemetryResources() coretypes.ResourceExtractor {
|
||||
return func(ec coretypes.ExtractorContext) ([]coretypes.ResourceWithID, error) {
|
||||
if !gjson.GetBytes(ec.RequestBody, "condition.compositeQuery").Exists() {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return NewRuleBodyTelemetryResources()(ec)
|
||||
}
|
||||
}
|
||||
|
||||
func fetchStoredRule(ec coretypes.ExtractorContext, rulerService Ruler) (*ruletypes.GettableRule, error) {
|
||||
ruleID, err := valuer.NewUUID(mux.Vars(ec.Request)["id"])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
stored, err := rulerService.GetRule(ec.Request.Context(), ruleID)
|
||||
return rulerService.GetRule(ec.Request.Context(), ruleID)
|
||||
}
|
||||
|
||||
func fetchStoredCompositeQuery(ec coretypes.ExtractorContext, rulerService Ruler) ([]byte, error) {
|
||||
if ec.Request == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
stored, err := fetchStoredRule(ec, rulerService)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
package ruler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagertest"
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/types"
|
||||
"github.com/SigNoz/signoz/pkg/types/alertmanagertypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/alertmanagertypes/alertmanagertypestest"
|
||||
"github.com/SigNoz/signoz/pkg/types/authtypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/coretypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/ruletypes"
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -314,3 +320,309 @@ func TestMapFieldResources(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func v2RuleJSON(channels string) string {
|
||||
return `{
|
||||
"alert": "TestAlert",
|
||||
"version": "v5",
|
||||
"schemaVersion": "v2alpha1",
|
||||
"ruleType": "threshold_rule",
|
||||
"condition": {
|
||||
"compositeQuery": {
|
||||
"queryType": "builder",
|
||||
"queries": [{
|
||||
"type": "builder_query",
|
||||
"spec": {
|
||||
"name": "A",
|
||||
"signal": "metrics",
|
||||
"aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}],
|
||||
"stepInterval": "5m"
|
||||
}
|
||||
}]
|
||||
},
|
||||
"thresholds": {
|
||||
"kind": "basic",
|
||||
"spec": [{"name": "critical", "target": 90.0, "matchType": "1", "op": "1", "channels": ` + channels + `}]
|
||||
}
|
||||
},
|
||||
"evaluation": {
|
||||
"kind": "rolling",
|
||||
"spec": {"evalWindow": "5m", "frequency": "1m"}
|
||||
},
|
||||
"notificationSettings": {
|
||||
"renotify": {"enabled": true, "interval": "4h", "alertStates": ["firing"]}
|
||||
}
|
||||
}`
|
||||
}
|
||||
|
||||
func TestParseRuleChannels(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
body string
|
||||
wantChannels []string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "V2ThresholdChannels_ReadDirectly",
|
||||
body: v2RuleJSON(`["email"]`),
|
||||
wantChannels: []string{"email"},
|
||||
},
|
||||
{
|
||||
name: "V2EmptyChannels_Empty",
|
||||
body: v2RuleJSON(`[]`),
|
||||
wantChannels: nil,
|
||||
},
|
||||
{
|
||||
name: "NotJSON_InvalidInput",
|
||||
body: "not json",
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "TruncatedJSON_InvalidInput",
|
||||
body: `{"alert": `,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "UnknownField_InvalidInput",
|
||||
body: `{"preferredChannels": ["pager"]}`,
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
channels, err := parseRuleChannels([]byte(testCase.body))
|
||||
|
||||
if testCase.wantErr {
|
||||
require.Error(t, err)
|
||||
assert.True(t, errors.Ast(err, errors.TypeInvalidInput), err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testCase.wantChannels, channels)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIncomingRuleChannels(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
incoming incomingChannelsFunc
|
||||
stored string
|
||||
body string
|
||||
wantChannels []string
|
||||
wantStoredAfter []string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "Replaced_IgnoresStored",
|
||||
incoming: parseReplacedRuleChannels,
|
||||
stored: v2RuleJSON(`["slack"]`),
|
||||
body: v2RuleJSON(`["pager"]`),
|
||||
wantChannels: []string{"pager"},
|
||||
wantStoredAfter: []string{"slack"},
|
||||
},
|
||||
{
|
||||
name: "Patched_OmitsCondition_StoredChannelsSurvive",
|
||||
incoming: parsePatchedRuleChannels,
|
||||
stored: v2RuleJSON(`["slack"]`),
|
||||
body: `{"disabled": true}`,
|
||||
wantChannels: []string{"slack"},
|
||||
wantStoredAfter: []string{"slack"},
|
||||
},
|
||||
{
|
||||
name: "Patched_SetsChannels_StoredChannelsReplaced",
|
||||
incoming: parsePatchedRuleChannels,
|
||||
stored: v2RuleJSON(`["slack"]`),
|
||||
body: v2RuleJSON(`["pager"]`),
|
||||
wantChannels: []string{"pager"},
|
||||
wantStoredAfter: []string{"slack"},
|
||||
},
|
||||
{
|
||||
name: "Patched_EmptiesChannels_NoChannelsLeft",
|
||||
incoming: parsePatchedRuleChannels,
|
||||
stored: v2RuleJSON(`["slack"]`),
|
||||
body: v2RuleJSON(`[]`),
|
||||
wantChannels: nil,
|
||||
wantStoredAfter: []string{"slack"},
|
||||
},
|
||||
{
|
||||
name: "Patched_UnknownField_Errors",
|
||||
incoming: parsePatchedRuleChannels,
|
||||
stored: v2RuleJSON(`["slack"]`),
|
||||
body: `{"preferredChannels": ["pager"]}`,
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
stored := new(ruletypes.GettableRule)
|
||||
require.NoError(t, json.Unmarshal([]byte(testCase.stored), &stored.PostableRule))
|
||||
|
||||
channels, err := testCase.incoming(stored, []byte(testCase.body))
|
||||
|
||||
if testCase.wantErr {
|
||||
require.Error(t, err)
|
||||
return
|
||||
}
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testCase.wantChannels, channels)
|
||||
assert.Equal(t, testCase.wantStoredAfter, stored.Channels())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuleBodyTelemetryResources(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
body string
|
||||
wantKind coretypes.Kind
|
||||
wantID string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "V5Body_NoFilter_MetricsWildcard",
|
||||
body: v2RuleJSON(`[]`),
|
||||
wantKind: coretypes.KindMetrics,
|
||||
wantID: "builder_query/*",
|
||||
},
|
||||
{
|
||||
name: "MissingCondition_Errors",
|
||||
body: `{"alert": "TestAlert", "version": "v5"}`,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "NotJSON_Errors",
|
||||
body: "not json",
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
refs, err := NewRuleBodyTelemetryResources()(coretypes.ExtractorContext{RequestBody: []byte(testCase.body)})
|
||||
|
||||
if testCase.wantErr {
|
||||
assert.Error(t, err)
|
||||
return
|
||||
}
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, refs, 1)
|
||||
assert.Equal(t, testCase.wantKind, refs[0].Resource.Kind())
|
||||
assert.Equal(t, testCase.wantID, refs[0].ID)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyRulePatch(t *testing.T) {
|
||||
logsQuery := `{"condition": {"compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "logs", "stepInterval": "5m"}}]}}}`
|
||||
testCases := []struct {
|
||||
name string
|
||||
body string
|
||||
wantSignal string
|
||||
wantChannels []string
|
||||
}{
|
||||
{
|
||||
name: "BodyWithoutCondition_KeepsStoredQueryAndChannels",
|
||||
body: `{"disabled": true}`,
|
||||
wantSignal: "metrics",
|
||||
wantChannels: []string{"slack"},
|
||||
},
|
||||
{
|
||||
name: "BodyWithNewQuery_ReplacesSignalKeepsThresholds",
|
||||
body: logsQuery,
|
||||
wantSignal: "logs",
|
||||
wantChannels: []string{"slack"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
stored := new(ruletypes.GettableRule)
|
||||
require.NoError(t, json.Unmarshal([]byte(v2RuleJSON(`["slack"]`)), &stored.PostableRule))
|
||||
|
||||
patched, err := applyRulePatch(stored, []byte(testCase.body))
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, patched.RuleCondition)
|
||||
require.NotNil(t, patched.RuleCondition.CompositeQuery)
|
||||
encoded, err := json.Marshal(patched.RuleCondition.CompositeQuery)
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, string(encoded), `"signal":"`+testCase.wantSignal+`"`)
|
||||
assert.Equal(t, testCase.wantChannels, patched.Channels())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOptionalRuleBodyTelemetryResources(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
body string
|
||||
wantRefs int
|
||||
}{
|
||||
{
|
||||
name: "BodyWithoutCondition_NoResources",
|
||||
body: `{"disabled": true}`,
|
||||
wantRefs: 0,
|
||||
},
|
||||
{
|
||||
name: "BodyWithQuery_MetricsResource",
|
||||
body: v2RuleJSON(`[]`),
|
||||
wantRefs: 1,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
refs, err := NewOptionalRuleBodyTelemetryResources()(coretypes.ExtractorContext{RequestBody: []byte(testCase.body)})
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, refs, testCase.wantRefs)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveKnownChannelIDs(t *testing.T) {
|
||||
channels := []*alertmanagertypes.Channel{
|
||||
{Identifiable: types.Identifiable{ID: valuer.GenerateUUID()}, Name: "slack", DisplayName: "slack"},
|
||||
}
|
||||
testCases := []struct {
|
||||
name string
|
||||
names []string
|
||||
wantIDs []string
|
||||
}{
|
||||
{
|
||||
name: "KnownName_Resolved",
|
||||
names: []string{"slack"},
|
||||
wantIDs: []string{channels[0].ID.StringValue()},
|
||||
},
|
||||
{
|
||||
name: "UnknownName_Skipped",
|
||||
names: []string{"slack", "gone"},
|
||||
wantIDs: []string{channels[0].ID.StringValue()},
|
||||
},
|
||||
{
|
||||
name: "NoNames_NoLookup",
|
||||
names: nil,
|
||||
wantIDs: nil,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
alertmanagerService := alertmanagertest.NewMockAlertmanager(t)
|
||||
if len(testCase.names) > 0 {
|
||||
alertmanagerService.EXPECT().ListChannels(mock.Anything, mock.Anything).Return(channels, nil)
|
||||
}
|
||||
|
||||
ids, err := resolveKnownChannelIDs(context.Background(), alertmanagerService, valuer.GenerateUUID(), testCase.names)
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testCase.wantIDs, ids)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,6 +168,23 @@ func MapChannelNamesToIDs(channels Channels, names []string) ([]string, error) {
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// MapKnownChannelNamesToIDs skips names with no matching channel instead of failing.
|
||||
func MapKnownChannelNamesToIDs(channels Channels, names []string) []string {
|
||||
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 {
|
||||
if id, ok := idByName[name]; ok {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
|
||||
return ids
|
||||
}
|
||||
|
||||
func NewStatsFromChannels(channels Channels) map[string]any {
|
||||
stats := make(map[string]any)
|
||||
for _, channel := range channels {
|
||||
|
||||
@@ -332,3 +332,28 @@ func TestMapChannelNamesToIDs(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapKnownChannelNamesToIDs(t *testing.T) {
|
||||
slackID := valuer.GenerateUUID()
|
||||
pagerID := valuer.GenerateUUID()
|
||||
channels := Channels{
|
||||
{Identifiable: types.Identifiable{ID: slackID}, DisplayName: "slack-alerts"},
|
||||
{Identifiable: types.Identifiable{ID: pagerID}, DisplayName: "pager-oncall"},
|
||||
}
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
names []string
|
||||
want []string
|
||||
}{
|
||||
{name: "AllKnown_IDsInRequestOrder", names: []string{"pager-oncall", "slack-alerts"}, want: []string{pagerID.StringValue(), slackID.StringValue()}},
|
||||
{name: "UnknownName_Skipped", names: []string{"slack-alerts", "deleted-channel"}, want: []string{slackID.StringValue()}},
|
||||
{name: "NoNames_Empty", names: nil, want: []string{}},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
assert.Equal(t, testCase.want, MapKnownChannelNamesToIDs(channels, testCase.names))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -250,6 +250,21 @@ func (r *PostableRule) UnmarshalJSON(bytes []byte) error {
|
||||
return r.validate()
|
||||
}
|
||||
|
||||
func NewPatchedPostableRule(stored []byte, patch []byte) (*PostableRule, error) {
|
||||
patched := new(PostableRule)
|
||||
if err := json.Unmarshal(stored, patched); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// a rule stored before selectedQueryName was required resolves it the way evaluation does
|
||||
patched.RuleCondition.SelectedQuery = patched.RuleCondition.SelectedQueryName()
|
||||
|
||||
if err := patched.DecodeStrict(string(patch)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return patched, nil
|
||||
}
|
||||
|
||||
func (r *PostableRule) DecodeStrict(ruleStr string) error {
|
||||
err := json.Unmarshal([]byte(ruleStr), r)
|
||||
if err == nil {
|
||||
|
||||
@@ -116,6 +116,6 @@ def pytest_addoption(parser: pytest.Parser):
|
||||
parser.addoption(
|
||||
"--schema-migrator-version",
|
||||
action="store",
|
||||
default="v0.144.9", # todo(nikhil): change to 0.144.10
|
||||
default="v0.144.15",
|
||||
help="schema migrator version",
|
||||
)
|
||||
|
||||
2
tests/fixtures/logs.py
vendored
2
tests/fixtures/logs.py
vendored
@@ -174,7 +174,7 @@ class Logs(ABC):
|
||||
self.body_v2 = body_v2
|
||||
else:
|
||||
# Try to parse body as JSON; if successful use it directly,
|
||||
# otherwise wrap as {"message": body} matching the normalize operator behavior.
|
||||
# otherwise wrap as {"message": body} matching signozlogsnormalizer.
|
||||
try:
|
||||
json.loads(body)
|
||||
self.body_v2 = body
|
||||
|
||||
34
tests/fixtures/querier.py
vendored
34
tests/fixtures/querier.py
vendored
@@ -1018,20 +1018,38 @@ def assert_distribution_sums_heatmap(
|
||||
# we already create the evolution for resource during schema migration
|
||||
# since we have to create test data around it, we need to get the evolution time
|
||||
def get_resource_evolution_time(signoz: types.SigNoz, signal: str) -> datetime:
|
||||
return get_column_evolution_time(signoz, signal, "resource", "resource")
|
||||
|
||||
|
||||
# the migrator also seeds the traces attributes JSON rollout at install
|
||||
def get_attribute_evolution_time(signoz: types.SigNoz, signal: str) -> datetime:
|
||||
return get_column_evolution_time(signoz, signal, "attributes", "attribute")
|
||||
|
||||
|
||||
def get_attribute_backend_now(signoz: types.SigNoz, attribute_backend: str) -> datetime:
|
||||
"""The "now" a test anchors its spans and query window to. "map" sits before the traces
|
||||
attributes JSON rollout, where the querier reads only the legacy maps, the same SQL as with
|
||||
use_trace_attributes_json off; "json" is the wall clock, after the rollout."""
|
||||
if attribute_backend == "map":
|
||||
return get_attribute_evolution_time(signoz, "traces") - timedelta(hours=1)
|
||||
return datetime.now(tz=UTC)
|
||||
|
||||
|
||||
def get_column_evolution_time(signoz: types.SigNoz, signal: str, column_name: str, field_context: str) -> datetime:
|
||||
result = signoz.telemetrystore.conn.query(
|
||||
"""
|
||||
SELECT release_time
|
||||
SELECT min(release_time)
|
||||
FROM signoz_metadata.distributed_column_evolution_metadata
|
||||
WHERE signal = %(signal)s
|
||||
AND field_context = 'resource'
|
||||
AND field_context = %(field_context)s
|
||||
AND field_name = '__all__'
|
||||
AND column_name = 'resource'
|
||||
LIMIT 1
|
||||
AND column_name = %(column_name)s
|
||||
HAVING count() > 0
|
||||
""",
|
||||
parameters={"signal": signal},
|
||||
parameters={"signal": signal, "column_name": column_name, "field_context": field_context},
|
||||
).result_rows
|
||||
|
||||
assert result, f"Expected {signal} resource evolution metadata to exist"
|
||||
assert result, f"Expected {signal} {column_name} evolution metadata to exist"
|
||||
|
||||
release_time_ns = int(result[0][0])
|
||||
return datetime.fromtimestamp(release_time_ns / 1e9, tz=UTC)
|
||||
@@ -1132,7 +1150,7 @@ def generate_logs_with_corrupt_metadata() -> list[Logs]:
|
||||
]
|
||||
|
||||
|
||||
def generate_traces_with_corrupt_metadata() -> list[Traces]:
|
||||
def generate_traces_with_corrupt_metadata(now: datetime | None = None) -> list[Traces]:
|
||||
"""
|
||||
Specifically, entries with 'id', 'timestamp', 'trace_id' and 'duration_nano' fields in metadata
|
||||
"""
|
||||
@@ -1143,7 +1161,7 @@ def generate_traces_with_corrupt_metadata() -> list[Traces]:
|
||||
topic_service_trace_id = TraceIdGenerator.trace_id()
|
||||
topic_service_span_id = TraceIdGenerator.span_id()
|
||||
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
now = (now or datetime.now(tz=UTC)).replace(second=0, microsecond=0)
|
||||
|
||||
return [
|
||||
Traces(
|
||||
|
||||
2
tests/fixtures/signoz.py
vendored
2
tests/fixtures/signoz.py
vendored
@@ -92,7 +92,7 @@ def create_signoz(
|
||||
"SIGNOZ_ALERTMANAGER_SIGNOZ_ROUTE_GROUP__WAIT": "1s",
|
||||
"SIGNOZ_ALERTMANAGER_SIGNOZ_ROUTE_GROUP__INTERVAL": "5s",
|
||||
"SIGNOZ_CLOUDINTEGRATION_AGENT_VERSION": "v0.0.8",
|
||||
# tests reseed the attributes rollout row between cases
|
||||
# no schema metadata caching in tests
|
||||
"SIGNOZ_QUERIER_SCHEMAMETADATASTORE_CACHE__TTL": "1ns",
|
||||
}
|
||||
| sqlstore.env
|
||||
|
||||
54
tests/fixtures/traces.py
vendored
54
tests/fixtures/traces.py
vendored
@@ -986,60 +986,6 @@ def insert_traces(
|
||||
)
|
||||
|
||||
|
||||
def insert_attribute_evolution_to_clickhouse(conn, signal: str, release_time: datetime.datetime) -> None:
|
||||
"""Seed the `attributes` JSON column-evolution row for a signal at release_time. Unlike the
|
||||
resource row (seeded by the migrator at install), the attribute JSON rollout is install-specific
|
||||
and not migrator-seeded, so tests insert it to gate map-vs-JSON resolution across a window."""
|
||||
# insert_deduplicate=0: successive tests seed a byte-identical row (release_time is
|
||||
# minute-aligned), and ReplicatedMergeTree would drop the re-insert as a duplicate even
|
||||
# after the prior test's teardown deleted it, leaving the querier to fall back to the Map.
|
||||
conn.command(
|
||||
"""
|
||||
INSERT INTO signoz_metadata.distributed_column_evolution_metadata
|
||||
(signal, column_name, column_type, field_context, field_name, version, release_time)
|
||||
SETTINGS insert_deduplicate = 0
|
||||
VALUES (%(signal)s, 'attributes', 'JSON()', 'attribute', '__all__', 1, %(release_time_ns)s)
|
||||
""",
|
||||
parameters={"signal": signal, "release_time_ns": int(release_time.timestamp() * 1e9)},
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(name="seed_attribute_evolution", scope="function")
|
||||
def seed_attribute_evolution(
|
||||
clickhouse: types.TestContainerClickhouse,
|
||||
) -> Generator[Callable[[str, datetime.datetime], None], Any]:
|
||||
def _seed(signal: str, release_time: datetime.datetime) -> None:
|
||||
insert_attribute_evolution_to_clickhouse(clickhouse.conn, signal, release_time)
|
||||
|
||||
yield _seed
|
||||
|
||||
cluster = clickhouse.env["SIGNOZ_TELEMETRYSTORE_CLICKHOUSE_CLUSTER"]
|
||||
clickhouse.conn.query(f"ALTER TABLE signoz_metadata.column_evolution_metadata ON CLUSTER '{cluster}' DELETE WHERE column_name = 'attributes' AND field_context = 'attribute' AND field_name = '__all__' SETTINGS mutations_sync = 1")
|
||||
|
||||
|
||||
# A rollout far before any test's query window, so seeding it makes the querier read span
|
||||
# attributes entirely from the native JSON column rather than straddling into the legacy Map.
|
||||
ATTRIBUTE_JSON_ROLLOUT_TIME = datetime.datetime(2020, 1, 1, tzinfo=datetime.UTC)
|
||||
|
||||
|
||||
@pytest.fixture(name="use_attribute_backend")
|
||||
def use_attribute_backend(
|
||||
seed_attribute_evolution: Callable[[str, datetime.datetime], None],
|
||||
) -> Callable[[str], None]:
|
||||
"""Applies the physical attribute layout a test runs under. "map" leaves the querier on the
|
||||
legacy attributes_{string,number,bool} maps; "json" seeds the column-evolution row so it reads
|
||||
the native `attributes` JSON column instead. Pair with
|
||||
@pytest.mark.parametrize("attribute_backend", ["map", "json"]) and call it once in the body;
|
||||
insert_traces dual-writes both layouts, so a test that passes under both has strict Map/JSON
|
||||
parity."""
|
||||
|
||||
def _apply(backend: str) -> None:
|
||||
if backend == "json":
|
||||
seed_attribute_evolution("traces", ATTRIBUTE_JSON_ROLLOUT_TIME)
|
||||
|
||||
return _apply
|
||||
|
||||
|
||||
@pytest.fixture(name="insert_top_level_operations", scope="function")
|
||||
def insert_top_level_operations(
|
||||
clickhouse: types.TestContainerClickhouse,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from collections.abc import Callable
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from datetime import timedelta
|
||||
from http import HTTPStatus
|
||||
from typing import Any
|
||||
|
||||
@@ -20,6 +20,7 @@ from fixtures.querier import (
|
||||
build_order_by,
|
||||
build_traces_scalar_query,
|
||||
get_all_series,
|
||||
get_attribute_backend_now,
|
||||
get_scalar_table_data,
|
||||
index_series_by_label,
|
||||
make_query_request,
|
||||
@@ -70,7 +71,6 @@ def test_traces_aggregate_order_by_count(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
use_attribute_backend: Callable[[str], None],
|
||||
attribute_backend: str,
|
||||
order_by: dict[str, str],
|
||||
aggregation_alias: str,
|
||||
@@ -86,9 +86,9 @@ def test_traces_aggregate_order_by_count(
|
||||
fieldContext. Only the combinations that double-specify the context are a bad
|
||||
request; the rest resolve and return the span count.
|
||||
"""
|
||||
use_attribute_backend(attribute_backend)
|
||||
now = get_attribute_backend_now(signoz, attribute_backend)
|
||||
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
now = now.replace(second=0, microsecond=0)
|
||||
trace_id = TraceIdGenerator.trace_id()
|
||||
spans = [
|
||||
Traces(
|
||||
@@ -109,9 +109,11 @@ def test_traces_aggregate_order_by_count(
|
||||
response = make_query_request(
|
||||
signoz,
|
||||
token,
|
||||
start_ms=int((datetime.now(tz=UTC) - timedelta(minutes=5)).timestamp() * 1000),
|
||||
end_ms=int(datetime.now(tz=UTC).timestamp() * 1000),
|
||||
start_ms=int((now - timedelta(minutes=5)).timestamp() * 1000),
|
||||
end_ms=int(now.timestamp() * 1000),
|
||||
request_type=RequestType.TIME_SERIES,
|
||||
# cases share the query, and a "map" window is old enough to be served from the cache
|
||||
no_cache=True,
|
||||
queries=[
|
||||
BuilderQuery(
|
||||
signal="traces",
|
||||
@@ -145,7 +147,6 @@ def test_traces_aggregate_functions(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
use_attribute_backend: Callable[[str], None],
|
||||
attribute_backend: str,
|
||||
noise: str,
|
||||
) -> None:
|
||||
@@ -163,10 +164,10 @@ def test_traces_aggregate_functions(
|
||||
the corrupt variant the same-named colliding attributes must not change any of
|
||||
these.
|
||||
"""
|
||||
use_attribute_backend(attribute_backend)
|
||||
now = get_attribute_backend_now(signoz, attribute_backend)
|
||||
|
||||
extra_attrs, extra_resources = trace_noise(noise)
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
now = now.replace(second=0, microsecond=0)
|
||||
# A scalar rate divides by the whole query window, so both sides agree on it.
|
||||
# Traces derives this separately from logs (telemetrytraces/statement_builder.go).
|
||||
lookback_minutes = 5
|
||||
@@ -253,7 +254,6 @@ def test_traces_aggregate_calculated_range_countif(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
use_attribute_backend: Callable[[str], None],
|
||||
attribute_backend: str,
|
||||
) -> None:
|
||||
"""
|
||||
@@ -264,9 +264,9 @@ def test_traces_aggregate_calculated_range_countif(
|
||||
countIf(response_status_code >= 400 AND response_status_code < 500) counts the
|
||||
single 4XX span (404).
|
||||
"""
|
||||
use_attribute_backend(attribute_backend)
|
||||
now = get_attribute_backend_now(signoz, attribute_backend)
|
||||
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
now = now.replace(second=0, microsecond=0)
|
||||
spans = [
|
||||
Traces(
|
||||
timestamp=now - timedelta(seconds=i + 1),
|
||||
@@ -307,7 +307,6 @@ def test_traces_aggregate_having(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
use_attribute_backend: Callable[[str], None],
|
||||
attribute_backend: str,
|
||||
noise: str,
|
||||
) -> None:
|
||||
@@ -319,10 +318,10 @@ def test_traces_aggregate_having(
|
||||
A grouped scalar query with `having count() > 2` returns only the groups
|
||||
whose count qualifies (svc-a), derived from the inserted spans.
|
||||
"""
|
||||
use_attribute_backend(attribute_backend)
|
||||
now = get_attribute_backend_now(signoz, attribute_backend)
|
||||
|
||||
extra_attrs, extra_resources = trace_noise(noise)
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
now = now.replace(second=0, microsecond=0)
|
||||
counts = {"svc-a": 3, "svc-b": 1}
|
||||
spans = [
|
||||
Traces(
|
||||
@@ -379,7 +378,6 @@ def test_traces_aggregate_time_series_limit(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
use_attribute_backend: Callable[[str], None],
|
||||
attribute_backend: str,
|
||||
noise: str,
|
||||
limit: int,
|
||||
@@ -395,10 +393,10 @@ def test_traces_aggregate_time_series_limit(
|
||||
summing to that service's span count. Under the corrupt variant the grouping
|
||||
(resource.service.name) and count are unaffected by the colliding attributes.
|
||||
"""
|
||||
use_attribute_backend(attribute_backend)
|
||||
now = get_attribute_backend_now(signoz, attribute_backend)
|
||||
|
||||
extra_attrs, extra_resources = trace_noise(noise)
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
now = now.replace(second=0, microsecond=0)
|
||||
counts = {"svc-a": 5, "svc-b": 3, "svc-c": 7, "svc-d": 1}
|
||||
spans = [
|
||||
Traces(
|
||||
@@ -463,7 +461,6 @@ def test_traces_aggregate_unknown_key(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
use_attribute_backend: Callable[[str], None],
|
||||
attribute_backend: str,
|
||||
expression: str,
|
||||
expected_value: Any,
|
||||
@@ -476,9 +473,9 @@ def test_traces_aggregate_unknown_key(
|
||||
Aggregating a bare unknown key synthesizes a null column: count() of it is 0
|
||||
(no non-null values) and sum()/avg() are null — the query never errors.
|
||||
"""
|
||||
use_attribute_backend(attribute_backend)
|
||||
now = get_attribute_backend_now(signoz, attribute_backend)
|
||||
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
now = now.replace(second=0, microsecond=0)
|
||||
spans = [
|
||||
Traces(
|
||||
timestamp=now - timedelta(seconds=i + 1),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from collections.abc import Callable
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from datetime import timedelta
|
||||
from http import HTTPStatus
|
||||
from typing import Any
|
||||
|
||||
@@ -16,6 +16,7 @@ from fixtures.querier import (
|
||||
find_named_result,
|
||||
format_timestamp,
|
||||
generate_traces_with_corrupt_metadata,
|
||||
get_attribute_backend_now,
|
||||
get_rows,
|
||||
make_query_request,
|
||||
)
|
||||
@@ -237,11 +238,10 @@ def test_trace_operator(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
use_attribute_backend: Callable[[str], None],
|
||||
attribute_backend: str,
|
||||
case: dict,
|
||||
) -> None:
|
||||
use_attribute_backend(attribute_backend)
|
||||
now = get_attribute_backend_now(signoz, attribute_backend)
|
||||
|
||||
t1_trace_id = TraceIdGenerator.trace_id()
|
||||
t1_checkout_span_id = TraceIdGenerator.span_id() # POST /checkout — structural root of T1
|
||||
@@ -251,7 +251,7 @@ def test_trace_operator(
|
||||
t2_root_span_id = TraceIdGenerator.span_id()
|
||||
t2_child_span_id = TraceIdGenerator.span_id()
|
||||
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
now = now.replace(second=0, microsecond=0)
|
||||
|
||||
insert_traces(
|
||||
[
|
||||
@@ -580,7 +580,6 @@ def test_trace_operator_with_adjusted_keys(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
use_attribute_backend: Callable[[str], None],
|
||||
attribute_backend: str,
|
||||
payload_factory: Callable[[list[Traces]], list[dict[str, Any]]],
|
||||
request_type: str,
|
||||
@@ -592,9 +591,9 @@ def test_trace_operator_with_adjusted_keys(
|
||||
queries, otherwise deprecated keys and context-prefixed aliases don't
|
||||
resolve.
|
||||
"""
|
||||
use_attribute_backend(attribute_backend)
|
||||
now = get_attribute_backend_now(signoz, attribute_backend)
|
||||
|
||||
traces = generate_traces_with_corrupt_metadata()
|
||||
traces = generate_traces_with_corrupt_metadata(now)
|
||||
insert_traces(traces)
|
||||
payload = payload_factory(traces)
|
||||
|
||||
@@ -603,8 +602,8 @@ def test_trace_operator_with_adjusted_keys(
|
||||
response = make_query_request(
|
||||
signoz,
|
||||
token,
|
||||
start_ms=int((datetime.now(tz=UTC) - timedelta(minutes=5)).timestamp() * 1000),
|
||||
end_ms=int(datetime.now(tz=UTC).timestamp() * 1000),
|
||||
start_ms=int((now - timedelta(minutes=5)).timestamp() * 1000),
|
||||
end_ms=int(now.timestamp() * 1000),
|
||||
request_type=request_type,
|
||||
queries=payload,
|
||||
)
|
||||
@@ -642,7 +641,6 @@ def test_trace_operator_select_fields(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
use_attribute_backend: Callable[[str], None],
|
||||
attribute_backend: str,
|
||||
select_fields: list[dict[str, Any]],
|
||||
expansion: str,
|
||||
@@ -667,9 +665,9 @@ def test_trace_operator_select_fields(
|
||||
- pkg/telemetrytraces/trace_operator_cte_builder.go::buildListQuery for
|
||||
the per-row SELECT.
|
||||
"""
|
||||
use_attribute_backend(attribute_backend)
|
||||
now = get_attribute_backend_now(signoz, attribute_backend)
|
||||
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
now = now.replace(second=0, microsecond=0)
|
||||
|
||||
trace_id = TraceIdGenerator.trace_id()
|
||||
parent_span_id = TraceIdGenerator.span_id()
|
||||
@@ -754,8 +752,8 @@ def test_trace_operator_select_fields(
|
||||
response = make_query_request(
|
||||
signoz,
|
||||
token,
|
||||
start_ms=int((datetime.now(tz=UTC) - timedelta(minutes=5)).timestamp() * 1000),
|
||||
end_ms=int(datetime.now(tz=UTC).timestamp() * 1000),
|
||||
start_ms=int((now - timedelta(minutes=5)).timestamp() * 1000),
|
||||
end_ms=int(now.timestamp() * 1000),
|
||||
request_type=RequestType.RAW,
|
||||
queries=queries,
|
||||
)
|
||||
@@ -792,7 +790,6 @@ def test_trace_operator_scalar_limit(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
use_attribute_backend: Callable[[str], None],
|
||||
attribute_backend: str,
|
||||
) -> None:
|
||||
"""
|
||||
@@ -803,9 +800,9 @@ def test_trace_operator_scalar_limit(
|
||||
1. A scalar trace operator grouped by service.name with limit=2 returns
|
||||
only the top two groups by count.
|
||||
"""
|
||||
use_attribute_backend(attribute_backend)
|
||||
now = get_attribute_backend_now(signoz, attribute_backend)
|
||||
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
now = now.replace(second=0, microsecond=0)
|
||||
span_counts = {"limit-a": 4, "limit-b": 3, "limit-c": 2, "limit-d": 1}
|
||||
|
||||
insert_traces(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from collections.abc import Callable
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from datetime import timedelta
|
||||
from http import HTTPStatus
|
||||
|
||||
import pytest
|
||||
@@ -12,6 +12,7 @@ from fixtures.querier import (
|
||||
build_group_by_field,
|
||||
build_raw_query,
|
||||
build_traces_scalar_query,
|
||||
get_attribute_backend_now,
|
||||
get_rows,
|
||||
get_scalar_table_data,
|
||||
make_query_request,
|
||||
@@ -28,14 +29,12 @@ def test_traces_filter_unknown_key_synthesizes(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
use_attribute_backend: Callable[[str], None],
|
||||
attribute_backend: str,
|
||||
) -> None:
|
||||
"""An unknown attribute key runs against synthesized columns and returns 200 with a
|
||||
"not found" warning so typos still surface."""
|
||||
use_attribute_backend(attribute_backend)
|
||||
now = get_attribute_backend_now(signoz, attribute_backend)
|
||||
|
||||
now = datetime.now(tz=UTC)
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
response = make_query_request(
|
||||
signoz,
|
||||
@@ -63,15 +62,13 @@ def test_traces_filter_unknown_resource_key_filters(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
use_attribute_backend: Callable[[str], None],
|
||||
attribute_backend: str,
|
||||
) -> None:
|
||||
"""A resource-qualified unknown key must FILTER (0 rows), not be dropped: the
|
||||
resource-fingerprint sub-query skips keys absent from metadata, so the synthesized
|
||||
condition stays in the main query. A regression here returns every span."""
|
||||
use_attribute_backend(attribute_backend)
|
||||
now = get_attribute_backend_now(signoz, attribute_backend)
|
||||
|
||||
now = datetime.now(tz=UTC)
|
||||
insert_traces(
|
||||
[
|
||||
Traces(
|
||||
@@ -117,14 +114,12 @@ def test_traces_group_by_unknown_key_null_bucket(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
use_attribute_backend: Callable[[str], None],
|
||||
attribute_backend: str,
|
||||
) -> None:
|
||||
"""Grouping by an unknown key runs against synthesized columns: every span lands in
|
||||
the NULL bucket instead of the query failing."""
|
||||
use_attribute_backend(attribute_backend)
|
||||
now = get_attribute_backend_now(signoz, attribute_backend)
|
||||
|
||||
now = datetime.now(tz=UTC)
|
||||
insert_traces(
|
||||
[
|
||||
Traces(
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
from collections.abc import Callable
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from datetime import timedelta
|
||||
from http import HTTPStatus
|
||||
|
||||
import pytest
|
||||
|
||||
from fixtures import types
|
||||
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
|
||||
from fixtures.querier import BuilderQuery, OrderBy, RequestType, TelemetryFieldKey, get_rows, make_query_request
|
||||
from fixtures.querier import BuilderQuery, OrderBy, RequestType, TelemetryFieldKey, get_attribute_backend_now, get_rows, make_query_request
|
||||
from fixtures.traces import TraceIdGenerator, Traces, TracesKind, TracesStatusCode
|
||||
|
||||
# Filter-operator coverage for traces, modelled on the shapes that dominate real
|
||||
@@ -70,7 +70,6 @@ def test_traces_filter_operators(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
use_attribute_backend: Callable[[str], None],
|
||||
attribute_backend: str,
|
||||
expression: str,
|
||||
expected_names: set[str],
|
||||
@@ -83,9 +82,9 @@ def test_traces_filter_operators(
|
||||
Tests:
|
||||
Each production-shaped filter operator selects exactly the expected spans.
|
||||
"""
|
||||
use_attribute_backend(attribute_backend)
|
||||
now = get_attribute_backend_now(signoz, attribute_backend)
|
||||
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
now = now.replace(second=0, microsecond=0)
|
||||
# (name, service, deployment.environment, http.request.method, http.response.status_code, latency_ms, has_error_type)
|
||||
specs = [
|
||||
("checkout-handler", "checkout", "prod", "GET", "200", 100, False),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from collections.abc import Callable
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from datetime import timedelta
|
||||
from http import HTTPStatus
|
||||
|
||||
import numpy as np
|
||||
@@ -12,6 +12,7 @@ from fixtures.querier import (
|
||||
build_group_by_field,
|
||||
build_order_by,
|
||||
build_traces_scalar_query,
|
||||
get_attribute_backend_now,
|
||||
get_scalar_table_data,
|
||||
make_scalar_query_request,
|
||||
)
|
||||
@@ -33,7 +34,6 @@ def test_traces_aggregate_percentiles(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
use_attribute_backend: Callable[[str], None],
|
||||
attribute_backend: str,
|
||||
noise: str,
|
||||
) -> None:
|
||||
@@ -49,10 +49,10 @@ def test_traces_aggregate_percentiles(
|
||||
intrinsic column rather than error with ClickHouse NO_COMMON_TYPE (386) — the
|
||||
regression behind the span_percentile 500.
|
||||
"""
|
||||
use_attribute_backend(attribute_backend)
|
||||
now = get_attribute_backend_now(signoz, attribute_backend)
|
||||
|
||||
extra_attrs, extra_resources = trace_noise(noise)
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
now = now.replace(second=0, microsecond=0)
|
||||
durations_s = [1, 2, 3, 4, 5]
|
||||
spans = [
|
||||
Traces(
|
||||
@@ -101,7 +101,6 @@ def test_traces_aggregate_group_by_non_resource(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
use_attribute_backend: Callable[[str], None],
|
||||
attribute_backend: str,
|
||||
noise: str,
|
||||
group_key: str,
|
||||
@@ -116,10 +115,10 @@ def test_traces_aggregate_group_by_non_resource(
|
||||
not just a resource key — buckets by the real value; under the corrupt variant a
|
||||
same-named colliding attribute must not divert the grouping.
|
||||
"""
|
||||
use_attribute_backend(attribute_backend)
|
||||
now = get_attribute_backend_now(signoz, attribute_backend)
|
||||
|
||||
extra_attrs, extra_resources = trace_noise(noise)
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
now = now.replace(second=0, microsecond=0)
|
||||
specs = [("op-a", "/a"), ("op-a", "/a"), ("op-b", "/b")]
|
||||
spans = [
|
||||
Traces(
|
||||
@@ -157,7 +156,6 @@ def test_traces_aggregate_multi_group_by(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
use_attribute_backend: Callable[[str], None],
|
||||
attribute_backend: str,
|
||||
noise: str,
|
||||
) -> None:
|
||||
@@ -170,10 +168,10 @@ def test_traces_aggregate_multi_group_by(
|
||||
Grouping by two keys (a resource key and an intrinsic column) returns one row per
|
||||
present pair with the correct per-pair count.
|
||||
"""
|
||||
use_attribute_backend(attribute_backend)
|
||||
now = get_attribute_backend_now(signoz, attribute_backend)
|
||||
|
||||
extra_attrs, extra_resources = trace_noise(noise)
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
now = now.replace(second=0, microsecond=0)
|
||||
pair_counts = {("svc-1", "op-a"): 2, ("svc-1", "op-b"): 1, ("svc-2", "op-a"): 1}
|
||||
spans = [
|
||||
Traces(
|
||||
@@ -224,7 +222,6 @@ def test_traces_aggregate_having_breadth(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
use_attribute_backend: Callable[[str], None],
|
||||
attribute_backend: str,
|
||||
noise: str,
|
||||
having_expression: str,
|
||||
@@ -239,10 +236,10 @@ def test_traces_aggregate_having_breadth(
|
||||
each keep only the qualifying groups — extending the count()-only HAVING in
|
||||
02_aggregation.py.
|
||||
"""
|
||||
use_attribute_backend(attribute_backend)
|
||||
now = get_attribute_backend_now(signoz, attribute_backend)
|
||||
|
||||
extra_attrs, extra_resources = trace_noise(noise)
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
now = now.replace(second=0, microsecond=0)
|
||||
specs = [("svc-a", 1), ("svc-a", 1), ("svc-a", 1), ("svc-b", 5)]
|
||||
spans = [
|
||||
Traces(
|
||||
@@ -288,7 +285,6 @@ def test_traces_duration_nano_qol_filter_with_collision(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
use_attribute_backend: Callable[[str], None],
|
||||
attribute_backend: str,
|
||||
duration_filter: str,
|
||||
) -> None:
|
||||
@@ -303,9 +299,9 @@ def test_traces_duration_nano_qol_filter_with_collision(
|
||||
ClickHouse NO_COMMON_TYPE (386). The string attribute is cast; the intrinsic column
|
||||
stays a bare comparison.
|
||||
"""
|
||||
use_attribute_backend(attribute_backend)
|
||||
now = get_attribute_backend_now(signoz, attribute_backend)
|
||||
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
now = now.replace(second=0, microsecond=0)
|
||||
durations_s = [1, 2, 3, 4, 5]
|
||||
spans = [
|
||||
Traces(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from collections.abc import Callable
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from datetime import timedelta
|
||||
from http import HTTPStatus
|
||||
|
||||
from fixtures import types
|
||||
@@ -14,6 +14,7 @@ from fixtures.querier import (
|
||||
build_group_by_field,
|
||||
build_traces_scalar_query,
|
||||
get_all_warnings,
|
||||
get_attribute_evolution_time,
|
||||
get_preview_sql,
|
||||
get_rows,
|
||||
index_series_by_label,
|
||||
@@ -28,7 +29,6 @@ def test_traces_attributes_json_evolution(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
seed_attribute_evolution: Callable[[str, datetime], None],
|
||||
) -> None:
|
||||
"""`http.route` is a dotted key, so the `attributes` JSON column nests it under the path
|
||||
http.route while the legacy attributes_string map keys it verbatim. Spans before the attribute
|
||||
@@ -37,8 +37,7 @@ def test_traces_attributes_json_evolution(
|
||||
map+JSON multiIf (straddling), and must return identical rows across the boundary."""
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
evolution_time = datetime.now(tz=UTC).replace(second=0, microsecond=0) - timedelta(minutes=30)
|
||||
seed_attribute_evolution("traces", evolution_time)
|
||||
evolution_time = get_attribute_evolution_time(signoz, "traces").replace(second=0, microsecond=0)
|
||||
|
||||
before_2 = evolution_time - timedelta(minutes=10)
|
||||
before_1 = evolution_time - timedelta(minutes=5)
|
||||
@@ -162,15 +161,13 @@ def test_traces_attributes_json_typed_filters(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
seed_attribute_evolution: Callable[[str, datetime], None],
|
||||
) -> None:
|
||||
"""In the JSON-only window each dotted attribute reads through the nested path with its native
|
||||
cast: string (::String), Int64 (toFloat64(...::Nullable(Float64))), Bool (::Nullable(Bool)),
|
||||
and existence via the raw path. Filters must select the same rows the Map path would."""
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
evolution_time = datetime.now(tz=UTC).replace(second=0, microsecond=0) - timedelta(minutes=30)
|
||||
seed_attribute_evolution("traces", evolution_time)
|
||||
evolution_time = get_attribute_evolution_time(signoz, "traces").replace(second=0, microsecond=0)
|
||||
|
||||
hit = evolution_time + timedelta(minutes=5)
|
||||
miss = evolution_time + timedelta(minutes=6)
|
||||
@@ -230,7 +227,6 @@ def test_traces_attributes_json_collision_and_map_parity(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
seed_attribute_evolution: Callable[[str, datetime], None],
|
||||
) -> None:
|
||||
"""A name stored under two types (`app.status` as 200 and 'teapot') is one JSON path with
|
||||
per-row types. The Map-era behavior must hold on it: group-by reads each row as its stored
|
||||
@@ -239,8 +235,7 @@ def test_traces_attributes_json_collision_and_map_parity(
|
||||
across every stored type."""
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
evolution_time = datetime.now(tz=UTC).replace(second=0, microsecond=0) - timedelta(minutes=30)
|
||||
seed_attribute_evolution("traces", evolution_time)
|
||||
evolution_time = get_attribute_evolution_time(signoz, "traces").replace(second=0, microsecond=0)
|
||||
|
||||
hit = evolution_time + timedelta(minutes=5)
|
||||
insert_traces(
|
||||
@@ -343,14 +338,12 @@ def test_traces_attributes_json_number_reads(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
seed_attribute_evolution: Callable[[str, datetime], None],
|
||||
) -> None:
|
||||
"""A JSON number reads like the attributes_number map: a numeric string as its number, an
|
||||
integer above 2^53 rounded, and a non-numeric string as no number."""
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
evolution_time = datetime.now(tz=UTC).replace(second=0, microsecond=0) - timedelta(minutes=30)
|
||||
seed_attribute_evolution("traces", evolution_time)
|
||||
evolution_time = get_attribute_evolution_time(signoz, "traces").replace(second=0, microsecond=0)
|
||||
|
||||
hit = evolution_time + timedelta(minutes=5)
|
||||
insert_traces(
|
||||
@@ -400,14 +393,12 @@ def test_traces_attributes_json_list_view(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
seed_attribute_evolution: Callable[[str, datetime], None],
|
||||
) -> None:
|
||||
"""One straddling list query surfaces each row's attributes bag from its own home
|
||||
(legacy maps / dual-written / JSON-only), flattened to dotted keys with native types."""
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
evolution_time = datetime.now(tz=UTC).replace(second=0, microsecond=0) - timedelta(minutes=30)
|
||||
seed_attribute_evolution("traces", evolution_time)
|
||||
evolution_time = get_attribute_evolution_time(signoz, "traces").replace(second=0, microsecond=0)
|
||||
|
||||
service = "list-homes-service"
|
||||
spans = [
|
||||
@@ -477,14 +468,12 @@ def test_traces_attributes_json_unreported_key(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
seed_attribute_evolution: Callable[[str, datetime], None],
|
||||
) -> None:
|
||||
"""An attribute metadata does not report follows the rollout like a reported one: the legacy
|
||||
map before it, the attributes JSON column after it."""
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
evolution_time = datetime.now(tz=UTC).replace(second=0, microsecond=0) - timedelta(minutes=30)
|
||||
seed_attribute_evolution("traces", evolution_time)
|
||||
evolution_time = get_attribute_evolution_time(signoz, "traces").replace(second=0, microsecond=0)
|
||||
|
||||
before = evolution_time - timedelta(minutes=5)
|
||||
after = evolution_time + timedelta(minutes=5)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from collections.abc import Callable
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from datetime import timedelta
|
||||
from http import HTTPStatus
|
||||
|
||||
from fixtures import types
|
||||
@@ -9,6 +9,7 @@ from fixtures.querier import (
|
||||
OrderBy,
|
||||
RequestType,
|
||||
TelemetryFieldKey,
|
||||
get_attribute_evolution_time,
|
||||
get_rows,
|
||||
make_query_request,
|
||||
)
|
||||
@@ -20,15 +21,13 @@ def test_traces_scalar_and_object_key_both_survive(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
seed_attribute_evolution: Callable[[str, datetime], None],
|
||||
) -> None:
|
||||
"""A span attribute stored as both a scalar and an object prefix (db.function and
|
||||
db.function.arg) keeps both dotted keys through the native JSON read. json_only writes only the
|
||||
JSON column, so no legacy attribute map backfills the keys."""
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
evolution_time = datetime.now(tz=UTC).replace(second=0, microsecond=0) - timedelta(minutes=30)
|
||||
seed_attribute_evolution("traces", evolution_time)
|
||||
evolution_time = get_attribute_evolution_time(signoz, "traces").replace(second=0, microsecond=0)
|
||||
|
||||
service = "scalar-object-service"
|
||||
span_time = evolution_time + timedelta(minutes=5)
|
||||
|
||||
@@ -8,7 +8,7 @@ import requests
|
||||
from fixtures import types
|
||||
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
|
||||
from fixtures.querier import RequestType, build_aggregation, build_traces_scalar_query, get_preview_statements, make_preview_query_request
|
||||
from fixtures.traces import ATTRIBUTE_JSON_ROLLOUT_TIME, Traces
|
||||
from fixtures.traces import Traces
|
||||
|
||||
PROMOTED_PATHS = "/api/v1/promoted_paths"
|
||||
|
||||
@@ -18,10 +18,8 @@ def test_traces_filters_use_skip_indexes(
|
||||
create_user_admin: types.Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
seed_attribute_evolution: Callable[[str, datetime], None],
|
||||
request: pytest.FixtureRequest,
|
||||
) -> None:
|
||||
seed_attribute_evolution("traces", ATTRIBUTE_JSON_ROLLOUT_TIME)
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
resp = requests.post(
|
||||
|
||||
@@ -35,6 +35,9 @@ _DOWNTIME_NAME = "alert-authz-downtime"
|
||||
_ACTOR_DOWNTIME_NAME = "alert-authz-actor-downtime"
|
||||
_ROUTE_POLICY_NAME = "alert-authz-route-policy"
|
||||
_ACTOR_ROUTE_POLICY_NAME = "alert-authz-actor-route-policy"
|
||||
_EDITOR_RULE = "alert authz editor rule"
|
||||
_ACTOR_RULE = "alert authz actor rule"
|
||||
_ACTOR_SWAP_RULE = "alert authz actor swap rule"
|
||||
|
||||
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"}]}
|
||||
@@ -95,6 +98,24 @@ _ACTOR_BASE_TRANSACTION_GROUPS = [
|
||||
transaction_group("attach", "metaresource", "rule", ["*"]),
|
||||
]
|
||||
|
||||
_ACTOR_RULE_TRANSACTION_GROUPS = _ACTOR_BASE_TRANSACTION_GROUPS + [
|
||||
transaction_group("create", "metaresource", "rule", ["*"]),
|
||||
transaction_group("read", "metaresource", "rule", ["*"]),
|
||||
transaction_group("list", "metaresource", "rule", ["*"]),
|
||||
transaction_group("update", "metaresource", "rule", ["*"]),
|
||||
transaction_group("delete", "metaresource", "rule", ["*"]),
|
||||
transaction_group("detach", "metaresource", "rule", ["*"]),
|
||||
]
|
||||
|
||||
LOGS_RULE_CONDITION = {
|
||||
**RULE_CONDITION,
|
||||
"compositeQuery": {
|
||||
"queryType": "builder",
|
||||
"panelType": "graph",
|
||||
"queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "logs", "aggregations": [{"expression": "count()"}]}}],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_setup_users_and_channels(
|
||||
signoz: SigNoz,
|
||||
@@ -441,6 +462,148 @@ def test_viewer_allowed_on_rule_views(
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
|
||||
|
||||
|
||||
def test_viewer_allowed_on_rule_reads(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
token = get_token(_VIEWER_EMAIL, _VIEWER_PASSWORD)
|
||||
|
||||
response = requests.get(
|
||||
signoz.self.host_configs["8080"].get(f"{V3_RULES_URL}?limit=200"),
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
target_id = {rule["alert"]: rule["id"] for rule in response.json()["data"]["rules"]}[_TARGET_RULE]
|
||||
|
||||
response = requests.get(
|
||||
signoz.self.host_configs["8080"].get(f"{V2_RULES_URL}/{target_id}"),
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, f"GET rule {target_id}: expected 200, got {response.status_code}: {response.text}"
|
||||
|
||||
|
||||
def test_viewer_forbidden_on_rule_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)
|
||||
token = get_token(_VIEWER_EMAIL, _VIEWER_PASSWORD)
|
||||
|
||||
response = requests.get(
|
||||
signoz.self.host_configs["8080"].get(f"{V3_RULES_URL}?limit=200"),
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
target_id = {rule["alert"]: rule["id"] for rule in response.json()["data"]["rules"]}[_TARGET_RULE]
|
||||
|
||||
body = {**RULE_TEMPLATE, "alert": _TARGET_RULE}
|
||||
for method, path, payload in (
|
||||
("post", V2_RULES_URL, body),
|
||||
("put", f"{V2_RULES_URL}/{target_id}", body),
|
||||
("patch", f"{V2_RULES_URL}/{target_id}", {"description": "viewer patch"}),
|
||||
("delete", f"{V2_RULES_URL}/{target_id}", None),
|
||||
("post", f"{V2_RULES_URL}/{target_id}/clone", None),
|
||||
("post", f"{V2_RULES_URL}/test", body),
|
||||
):
|
||||
response = getattr(requests, method)(
|
||||
signoz.self.host_configs["8080"].get(path),
|
||||
json=payload,
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.FORBIDDEN, f"{method.upper()} {path}: expected 403, got {response.status_code}: {response.text}"
|
||||
|
||||
|
||||
def test_editor_allowed_on_rule_lifecycle(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
token = get_token(_EDITOR_EMAIL, _EDITOR_PASSWORD)
|
||||
|
||||
response = requests.post(
|
||||
signoz.self.host_configs["8080"].get(V2_RULES_URL),
|
||||
json={**RULE_TEMPLATE, "alert": _EDITOR_RULE},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.CREATED, response.text
|
||||
rule_id = response.json()["data"]["id"]
|
||||
|
||||
swapped_condition = {
|
||||
**RULE_CONDITION,
|
||||
"thresholds": {
|
||||
"kind": "basic",
|
||||
"spec": [{"name": "critical", "target": 90, "matchType": "at_least_once", "op": "above", "channels": [SEED_CHANNEL_ALT["name"]]}],
|
||||
},
|
||||
}
|
||||
response = requests.put(
|
||||
signoz.self.host_configs["8080"].get(f"{V2_RULES_URL}/{rule_id}"),
|
||||
json={**RULE_TEMPLATE, "alert": _EDITOR_RULE, "condition": swapped_condition},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
|
||||
|
||||
response = requests.patch(
|
||||
signoz.self.host_configs["8080"].get(f"{V2_RULES_URL}/{rule_id}"),
|
||||
json={"description": "patched without touching channels"},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
assert response.json()["data"]["condition"]["thresholds"]["spec"][0]["channels"] == [SEED_CHANNEL_ALT["name"]], response.text
|
||||
|
||||
response = requests.post(
|
||||
signoz.self.host_configs["8080"].get(f"{V2_RULES_URL}/{rule_id}/clone"),
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.CREATED, response.text
|
||||
clone_id = response.json()["data"]["id"]
|
||||
|
||||
response = requests.post(
|
||||
signoz.self.host_configs["8080"].get(f"{V2_RULES_URL}/test"),
|
||||
json={**RULE_TEMPLATE, "alert": _EDITOR_RULE},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
|
||||
for created_id in (rule_id, clone_id):
|
||||
response = requests.delete(
|
||||
signoz.self.host_configs["8080"].get(f"{V2_RULES_URL}/{created_id}"),
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
|
||||
|
||||
|
||||
def test_rule_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)
|
||||
|
||||
condition = {
|
||||
**RULE_CONDITION,
|
||||
"thresholds": {"kind": "basic", "spec": [{"name": "critical", "target": 90, "matchType": "at_least_once", "op": "above", "channels": ["alert-authz-missing-channel"]}]},
|
||||
}
|
||||
response = requests.post(
|
||||
signoz.self.host_configs["8080"].get(V2_RULES_URL),
|
||||
json={**RULE_TEMPLATE, "alert": _EDITOR_RULE, "condition": condition},
|
||||
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
|
||||
@@ -898,6 +1061,277 @@ def test_downtime_widening_to_all_rules_forbidden_without_wildcard_attach(
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
|
||||
|
||||
|
||||
def test_setup_rule_scoped_actor(
|
||||
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.put(
|
||||
signoz.self.host_configs["8080"].get(f"/api/v1/roles/{find_role_by_name(signoz, admin_token, _ACTOR_ROLE_NAME)}"),
|
||||
json={
|
||||
"description": "",
|
||||
"transactionGroups": _ACTOR_RULE_TRANSACTION_GROUPS + [transaction_group("read", "telemetryresource", "metrics", ["builder_query/*"])],
|
||||
},
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
|
||||
|
||||
|
||||
def test_rule_without_channels_allowed_without_channel_attach(
|
||||
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)
|
||||
token = get_token(_ACTOR_EMAIL, _ACTOR_PASSWORD)
|
||||
|
||||
condition = {
|
||||
**RULE_CONDITION,
|
||||
"thresholds": {"kind": "basic", "spec": [{"name": "critical", "target": 90, "matchType": "at_least_once", "op": "above", "channels": []}]},
|
||||
}
|
||||
response = requests.post(
|
||||
signoz.self.host_configs["8080"].get(V2_RULES_URL),
|
||||
json={
|
||||
**RULE_TEMPLATE,
|
||||
"alert": _ACTOR_RULE,
|
||||
"condition": condition,
|
||||
"notificationSettings": {**RULE_TEMPLATE["notificationSettings"], "usePolicy": True},
|
||||
},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.CREATED, response.text
|
||||
|
||||
response = requests.delete(
|
||||
signoz.self.host_configs["8080"].get(f"{V2_RULES_URL}/{response.json()['data']['id']}"),
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
|
||||
|
||||
|
||||
def test_rule_naming_channel_forbidden_without_channel_attach(
|
||||
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)
|
||||
token = get_token(_ACTOR_EMAIL, _ACTOR_PASSWORD)
|
||||
|
||||
response = requests.post(
|
||||
signoz.self.host_configs["8080"].get(V2_RULES_URL),
|
||||
json={**RULE_TEMPLATE, "alert": _ACTOR_RULE},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.FORBIDDEN, response.text
|
||||
|
||||
response = requests.get(
|
||||
signoz.self.host_configs["8080"].get(f"{V3_RULES_URL}?limit=200"),
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
target_id = {rule["alert"]: rule["id"] for rule in response.json()["data"]["rules"]}[_TARGET_RULE]
|
||||
|
||||
response = requests.post(
|
||||
signoz.self.host_configs["8080"].get(f"{V2_RULES_URL}/{target_id}/clone"),
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.FORBIDDEN, response.text
|
||||
|
||||
|
||||
def test_rule_naming_channel_allowed_once_channel_attach_granted(
|
||||
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.put(
|
||||
signoz.self.host_configs["8080"].get(f"/api/v1/roles/{find_role_by_name(signoz, admin_token, _ACTOR_ROLE_NAME)}"),
|
||||
json={
|
||||
"description": "",
|
||||
"transactionGroups": _ACTOR_RULE_TRANSACTION_GROUPS
|
||||
+ [
|
||||
transaction_group("read", "telemetryresource", "metrics", ["builder_query/*"]),
|
||||
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(V2_RULES_URL),
|
||||
json={**RULE_TEMPLATE, "alert": _ACTOR_RULE},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.CREATED, response.text
|
||||
rule_id = response.json()["data"]["id"]
|
||||
|
||||
response = requests.post(
|
||||
signoz.self.host_configs["8080"].get(f"{V2_RULES_URL}/{rule_id}/clone"),
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.CREATED, response.text
|
||||
clone_id = response.json()["data"]["id"]
|
||||
|
||||
for created_id in (rule_id, clone_id):
|
||||
response = requests.delete(
|
||||
signoz.self.host_configs["8080"].get(f"{V2_RULES_URL}/{created_id}"),
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
|
||||
|
||||
|
||||
def test_channel_swap_forbidden_without_channel_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)
|
||||
token = get_token(_ACTOR_EMAIL, _ACTOR_PASSWORD)
|
||||
|
||||
response = requests.post(
|
||||
signoz.self.host_configs["8080"].get(V2_RULES_URL),
|
||||
json={**RULE_TEMPLATE, "alert": _ACTOR_SWAP_RULE},
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.CREATED, response.text
|
||||
rule_id = response.json()["data"]["id"]
|
||||
|
||||
swapped_condition = {
|
||||
**RULE_CONDITION,
|
||||
"thresholds": {
|
||||
"kind": "basic",
|
||||
"spec": [{"name": "critical", "target": 90, "matchType": "at_least_once", "op": "above", "channels": [SEED_CHANNEL_ALT["name"]]}],
|
||||
},
|
||||
}
|
||||
response = requests.put(
|
||||
signoz.self.host_configs["8080"].get(f"{V2_RULES_URL}/{rule_id}"),
|
||||
json={**RULE_TEMPLATE, "alert": _ACTOR_SWAP_RULE, "condition": swapped_condition},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.FORBIDDEN, response.text
|
||||
|
||||
response = requests.patch(
|
||||
signoz.self.host_configs["8080"].get(f"{V2_RULES_URL}/{rule_id}"),
|
||||
json={"description": "patched without touching channels"},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
|
||||
response = requests.delete(
|
||||
signoz.self.host_configs["8080"].get(f"{V2_RULES_URL}/{rule_id}"),
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
|
||||
|
||||
|
||||
def test_rule_mutations_need_telemetry_read_on_query(
|
||||
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)
|
||||
token = get_token(_ACTOR_EMAIL, _ACTOR_PASSWORD)
|
||||
|
||||
condition = {
|
||||
**RULE_CONDITION,
|
||||
"thresholds": {"kind": "basic", "spec": [{"name": "critical", "target": 90, "matchType": "at_least_once", "op": "above", "channels": []}]},
|
||||
}
|
||||
body = {
|
||||
**RULE_TEMPLATE,
|
||||
"alert": _ACTOR_RULE,
|
||||
"condition": condition,
|
||||
"notificationSettings": {**RULE_TEMPLATE["notificationSettings"], "usePolicy": True},
|
||||
}
|
||||
response = requests.post(
|
||||
signoz.self.host_configs["8080"].get(V2_RULES_URL),
|
||||
json=body,
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.CREATED, response.text
|
||||
rule_id = response.json()["data"]["id"]
|
||||
|
||||
logs_body = {**body, "alertType": "LOGS_BASED_ALERT", "condition": {**LOGS_RULE_CONDITION, "thresholds": condition["thresholds"]}}
|
||||
for method, path, payload in (
|
||||
("post", V2_RULES_URL, logs_body),
|
||||
("put", f"{V2_RULES_URL}/{rule_id}", logs_body),
|
||||
("patch", f"{V2_RULES_URL}/{rule_id}", {"condition": logs_body["condition"]}),
|
||||
("post", f"{V2_RULES_URL}/test", logs_body),
|
||||
):
|
||||
response = getattr(requests, method)(
|
||||
signoz.self.host_configs["8080"].get(path),
|
||||
json=payload,
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.FORBIDDEN, f"{method.upper()} {path}: expected 403, got {response.status_code}: {response.text}"
|
||||
|
||||
response = requests.post(
|
||||
signoz.self.host_configs["8080"].get(f"{V2_RULES_URL}/test"),
|
||||
json=body,
|
||||
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"/api/v1/roles/{find_role_by_name(signoz, admin_token, _ACTOR_ROLE_NAME)}"),
|
||||
json={"description": "", "transactionGroups": _ACTOR_RULE_TRANSACTION_GROUPS},
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
|
||||
|
||||
token = get_token(_ACTOR_EMAIL, _ACTOR_PASSWORD)
|
||||
for method, path, payload in (
|
||||
("post", V2_RULES_URL, body),
|
||||
("put", f"{V2_RULES_URL}/{rule_id}", body),
|
||||
("patch", f"{V2_RULES_URL}/{rule_id}", {"condition": body["condition"]}),
|
||||
("post", f"{V2_RULES_URL}/{rule_id}/clone", None),
|
||||
("post", f"{V2_RULES_URL}/test", body),
|
||||
):
|
||||
response = getattr(requests, method)(
|
||||
signoz.self.host_configs["8080"].get(path),
|
||||
json=payload,
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.FORBIDDEN, f"{method.upper()} {path}: expected 403, got {response.status_code}: {response.text}"
|
||||
|
||||
response = requests.patch(
|
||||
signoz.self.host_configs["8080"].get(f"{V2_RULES_URL}/{rule_id}"),
|
||||
json={"description": "patch without the query needs no telemetry read"},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
|
||||
response = requests.delete(
|
||||
signoz.self.host_configs["8080"].get(f"{V2_RULES_URL}/{rule_id}"),
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
|
||||
|
||||
|
||||
def test_history_labels_need_telemetry_and_field_grants(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
|
||||
@@ -422,8 +422,8 @@ def test_update_rejects_malformed_id(
|
||||
"status": "error",
|
||||
"error": {
|
||||
"type": "invalid-input",
|
||||
"code": "invalid_input",
|
||||
"message": "id is not a valid uuid",
|
||||
"code": "invalid_selector",
|
||||
"message": "invalid selector for type metaresource: not-a-uuid",
|
||||
"errors": [],
|
||||
"suggestions": [],
|
||||
},
|
||||
|
||||
@@ -7,6 +7,7 @@ import requests
|
||||
|
||||
from fixtures import types
|
||||
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
|
||||
from fixtures.querier import get_attribute_backend_now, get_attribute_evolution_time
|
||||
from fixtures.querierai import root_span
|
||||
from fixtures.traces import TraceIdGenerator, Traces, TracesKind, TracesStatusCode
|
||||
|
||||
@@ -27,15 +28,13 @@ def test_summary_ai_trace(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
use_attribute_backend: Callable[[str], None],
|
||||
attribute_backend: str,
|
||||
) -> None:
|
||||
"""The summary carries the waterfall's trace-level fields and, for a trace with gen_ai
|
||||
spans, token totals over every LLM span and the cost summed over the spans that carry it.
|
||||
Spans are written to one layout only, so a read from the wrong column sums to zero."""
|
||||
use_attribute_backend(attribute_backend)
|
||||
now = get_attribute_backend_now(signoz, attribute_backend).replace(second=0, microsecond=0)
|
||||
write_mode = "json_only" if attribute_backend == "json" else "legacy_only"
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
service = f"td-summary-{attribute_backend}"
|
||||
resources = {"service.name": service}
|
||||
trace_id = TraceIdGenerator.trace_id()
|
||||
@@ -129,14 +128,11 @@ def test_summary_ai_trace_across_json_rollout(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
seed_attribute_evolution: Callable[[str, datetime], None],
|
||||
) -> None:
|
||||
"""A trace that straddles the attribute JSON rollout has LLM spans written only to the legacy
|
||||
maps before it and to the JSON column after it. The summary window covers both, so the gen_ai
|
||||
reads must fall back across columns and sum every span."""
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
rollout = now - timedelta(minutes=30)
|
||||
seed_attribute_evolution("traces", rollout)
|
||||
rollout = get_attribute_evolution_time(signoz, "traces").replace(second=0, microsecond=0)
|
||||
|
||||
service = "td-summary-rollout"
|
||||
resources = {"service.name": service}
|
||||
|
||||
@@ -8,7 +8,8 @@ import requests
|
||||
|
||||
from fixtures import types
|
||||
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
|
||||
from fixtures.traces import ATTRIBUTE_JSON_ROLLOUT_TIME, TraceIdGenerator, Traces, TracesKind
|
||||
from fixtures.querier import get_attribute_evolution_time
|
||||
from fixtures.traces import TraceIdGenerator, Traces, TracesKind
|
||||
|
||||
|
||||
def test_thread_returns_gen_ai_spans_in_order(
|
||||
@@ -16,9 +17,7 @@ def test_thread_returns_gen_ai_spans_in_order(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
seed_attribute_evolution: Callable[[str, datetime], None],
|
||||
) -> None:
|
||||
seed_attribute_evolution("traces", ATTRIBUTE_JSON_ROLLOUT_TIME)
|
||||
now = datetime.now(tz=UTC).replace(microsecond=0)
|
||||
trace_id = TraceIdGenerator.trace_id()
|
||||
root_id, first_llm_id, tool_id, agent_id, second_llm_id, legacy_llm_id, third_llm_id, flattened_llm_id, responses_llm_id, langchain_llm_id, openrouter_llm_id, vercel_llm_id, anthropic_llm_id, gemini_llm_id = (TraceIdGenerator.span_id() for _ in range(14))
|
||||
@@ -30,7 +29,7 @@ def test_thread_returns_gen_ai_spans_in_order(
|
||||
|
||||
insert_traces(
|
||||
[
|
||||
Traces(timestamp=now - timedelta(seconds=10), duration=timedelta(seconds=9), trace_id=trace_id, span_id=root_id, name="POST /chat", kind=TracesKind.SPAN_KIND_SERVER, resources=resources, attribute_write_mode="json_only"),
|
||||
Traces(timestamp=now - timedelta(seconds=10), duration=timedelta(seconds=9), trace_id=trace_id, span_id=root_id, name="POST /chat", kind=TracesKind.SPAN_KIND_SERVER, resources=resources),
|
||||
Traces(
|
||||
timestamp=now - timedelta(seconds=8),
|
||||
trace_id=trace_id,
|
||||
@@ -39,7 +38,6 @@ def test_thread_returns_gen_ai_spans_in_order(
|
||||
name="chat gpt-4o",
|
||||
resources=resources,
|
||||
attributes={"gen_ai.request.model": "gpt-4o", "gen_ai.system_instructions": first_instructions, "gen_ai.input.messages": first_input, "gen_ai.output.messages": first_output, "gen_ai.response.finish_reasons": json.dumps(["tool_calls"])},
|
||||
attribute_write_mode="json_only",
|
||||
),
|
||||
Traces(
|
||||
timestamp=now - timedelta(seconds=6),
|
||||
@@ -49,10 +47,9 @@ def test_thread_returns_gen_ai_spans_in_order(
|
||||
name="execute_tool get_weather",
|
||||
resources=resources,
|
||||
attributes={"gen_ai.tool.name": "get_weather", "gen_ai.tool.call.id": "call_1", "gen_ai.tool.call.arguments": json.dumps({"city": "Bangalore"}), "gen_ai.tool.call.result": "sunny"},
|
||||
attribute_write_mode="json_only",
|
||||
),
|
||||
Traces(timestamp=now - timedelta(seconds=5), trace_id=trace_id, span_id=agent_id, parent_span_id=root_id, name="invoke_agent planner", resources=resources, attributes={"gen_ai.agent.name": "planner"}, attribute_write_mode="json_only"),
|
||||
Traces(timestamp=now - timedelta(seconds=4), trace_id=trace_id, span_id=second_llm_id, parent_span_id=root_id, name="chat gpt-4o", resources=resources, attributes={"gen_ai.request.model": "gpt-4o", "gen_ai.input.messages": second_input}, attribute_write_mode="json_only"),
|
||||
Traces(timestamp=now - timedelta(seconds=5), trace_id=trace_id, span_id=agent_id, parent_span_id=root_id, name="invoke_agent planner", resources=resources, attributes={"gen_ai.agent.name": "planner"}),
|
||||
Traces(timestamp=now - timedelta(seconds=4), trace_id=trace_id, span_id=second_llm_id, parent_span_id=root_id, name="chat gpt-4o", resources=resources, attributes={"gen_ai.request.model": "gpt-4o", "gen_ai.input.messages": second_input}),
|
||||
Traces(
|
||||
timestamp=now - timedelta(seconds=3),
|
||||
trace_id=trace_id,
|
||||
@@ -61,9 +58,8 @@ def test_thread_returns_gen_ai_spans_in_order(
|
||||
name="openai.chat",
|
||||
resources=resources,
|
||||
attributes={"gen_ai.request.model": "gpt-4o", "gen_ai.prompt.0.role": "user", "gen_ai.prompt.0.content": "and tomorrow?", "gen_ai.completion.0.role": "assistant", "gen_ai.completion.0.content": "Also sunny.", "gen_ai.completion.0.finish_reason": "stop"},
|
||||
attribute_write_mode="json_only",
|
||||
),
|
||||
Traces(timestamp=now - timedelta(seconds=2), trace_id=trace_id, span_id=third_llm_id, parent_span_id=root_id, name="chat gpt-4o", resources=resources, attributes={"gen_ai.request.model": "gpt-4o", "gen_ai.output.messages": "It is sunny in Bangalore."}, attribute_write_mode="json_only"),
|
||||
Traces(timestamp=now - timedelta(seconds=2), trace_id=trace_id, span_id=third_llm_id, parent_span_id=root_id, name="chat gpt-4o", resources=resources, attributes={"gen_ai.request.model": "gpt-4o", "gen_ai.output.messages": "It is sunny in Bangalore."}),
|
||||
Traces(
|
||||
timestamp=now - timedelta(seconds=1),
|
||||
trace_id=trace_id,
|
||||
@@ -79,7 +75,6 @@ def test_thread_returns_gen_ai_spans_in_order(
|
||||
"llm.output_messages.0.message.content": "You're welcome.",
|
||||
"llm.finish_reason": "stop",
|
||||
},
|
||||
attribute_write_mode="json_only",
|
||||
),
|
||||
Traces(
|
||||
timestamp=now,
|
||||
@@ -93,7 +88,6 @@ def test_thread_returns_gen_ai_spans_in_order(
|
||||
"gen_ai.input.messages": json.dumps({"model": "gpt-4o", "instructions": "Be brief.", "input": [{"role": "user", "content": "bye"}]}),
|
||||
"gen_ai.output.messages": json.dumps({"object": "response", "status": "completed", "output": [{"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "Bye!"}]}]}),
|
||||
},
|
||||
attribute_write_mode="json_only",
|
||||
),
|
||||
Traces(
|
||||
timestamp=now + timedelta(seconds=1),
|
||||
@@ -109,7 +103,6 @@ def test_thread_returns_gen_ai_spans_in_order(
|
||||
{"generations": [[{"text": "See you!", "generation_info": {"finish_reason": "stop"}, "type": "ChatGeneration", "message": {"lc": 1, "type": "constructor", "id": ["langchain", "schema", "messages", "AIMessage"], "kwargs": {"content": "See you!", "type": "ai"}}}]]}
|
||||
),
|
||||
},
|
||||
attribute_write_mode="json_only",
|
||||
),
|
||||
Traces(
|
||||
timestamp=now + timedelta(seconds=2),
|
||||
@@ -123,7 +116,6 @@ def test_thread_returns_gen_ai_spans_in_order(
|
||||
"gen_ai.input.messages": json.dumps({"messages": [{"role": "user", "content": "one word"}]}),
|
||||
"gen_ai.output.messages": json.dumps({"completion": "Yes.", "reasoning": None, "rawRequest": {"model": "openai/gpt-4o-mini"}}),
|
||||
},
|
||||
attribute_write_mode="json_only",
|
||||
),
|
||||
Traces(
|
||||
timestamp=now + timedelta(seconds=3),
|
||||
@@ -139,7 +131,6 @@ def test_thread_returns_gen_ai_spans_in_order(
|
||||
"gen_ai.input.messages": json.dumps([{"role": "user", "content": [{"type": "text", "text": "last one"}]}]),
|
||||
"gen_ai.output.messages": "Done.",
|
||||
},
|
||||
attribute_write_mode="json_only",
|
||||
),
|
||||
Traces(
|
||||
timestamp=now + timedelta(seconds=4),
|
||||
@@ -153,7 +144,6 @@ def test_thread_returns_gen_ai_spans_in_order(
|
||||
"gen_ai.input.messages": json.dumps({"system": "Be terse.", "messages": [{"role": "user", "content": "ping"}]}),
|
||||
"gen_ai.output.messages": json.dumps({"type": "message", "role": "assistant", "content": [{"type": "text", "text": "pong"}], "stop_reason": "end_turn"}),
|
||||
},
|
||||
attribute_write_mode="json_only",
|
||||
),
|
||||
Traces(
|
||||
timestamp=now + timedelta(seconds=5),
|
||||
@@ -167,7 +157,6 @@ def test_thread_returns_gen_ai_spans_in_order(
|
||||
"gen_ai.input.messages": json.dumps({"contents": [{"role": "user", "parts": [{"text": "ping"}]}]}),
|
||||
"gen_ai.output.messages": json.dumps({"candidates": [{"content": {"role": "model", "parts": [{"text": "pong"}]}, "finishReason": "STOP"}]}),
|
||||
},
|
||||
attribute_write_mode="json_only",
|
||||
),
|
||||
]
|
||||
)
|
||||
@@ -231,9 +220,7 @@ def test_thread_paginates_with_cursors(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
seed_attribute_evolution: Callable[[str, datetime], None],
|
||||
) -> None:
|
||||
seed_attribute_evolution("traces", ATTRIBUTE_JSON_ROLLOUT_TIME)
|
||||
now = datetime.now(tz=UTC).replace(microsecond=0)
|
||||
trace_id = TraceIdGenerator.trace_id()
|
||||
span_ids = [TraceIdGenerator.span_id() for _ in range(3)]
|
||||
@@ -241,7 +228,7 @@ def test_thread_paginates_with_cursors(
|
||||
timestamps = [now - timedelta(seconds=6), now - timedelta(seconds=3), now - timedelta(seconds=3)]
|
||||
insert_traces(
|
||||
[
|
||||
Traces(timestamp=timestamp, trace_id=trace_id, span_id=span_id, name="chat gpt-4o", resources={"service.name": "tracedetail-thread-pages"}, attributes={"gen_ai.request.model": "gpt-4o", "gen_ai.input.messages": json.dumps([{"role": "user", "content": span_id}])}, attribute_write_mode="json_only")
|
||||
Traces(timestamp=timestamp, trace_id=trace_id, span_id=span_id, name="chat gpt-4o", resources={"service.name": "tracedetail-thread-pages"}, attributes={"gen_ai.request.model": "gpt-4o", "gen_ai.input.messages": json.dumps([{"role": "user", "content": span_id}])})
|
||||
for span_id, timestamp in zip(span_ids, timestamps, strict=True)
|
||||
]
|
||||
)
|
||||
@@ -286,9 +273,7 @@ def test_thread_paginates_across_buckets(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
seed_attribute_evolution: Callable[[str, datetime], None],
|
||||
) -> None:
|
||||
seed_attribute_evolution("traces", ATTRIBUTE_JSON_ROLLOUT_TIME)
|
||||
now = datetime.now(tz=UTC).replace(microsecond=0)
|
||||
bucket = now.replace(minute=0 if now.minute < 30 else 30, second=0)
|
||||
trace_id = TraceIdGenerator.trace_id()
|
||||
@@ -303,7 +288,7 @@ def test_thread_paginates_across_buckets(
|
||||
span_ids = [TraceIdGenerator.span_id() for _ in timestamps]
|
||||
insert_traces(
|
||||
[
|
||||
Traces(timestamp=timestamp, trace_id=trace_id, span_id=span_id, name="chat gpt-4o", resources={"service.name": "tracedetail-thread-buckets"}, attributes={"gen_ai.request.model": "gpt-4o", "gen_ai.input.messages": json.dumps([{"role": "user", "content": span_id}])}, attribute_write_mode="json_only")
|
||||
Traces(timestamp=timestamp, trace_id=trace_id, span_id=span_id, name="chat gpt-4o", resources={"service.name": "tracedetail-thread-buckets"}, attributes={"gen_ai.request.model": "gpt-4o", "gen_ai.input.messages": json.dumps([{"role": "user", "content": span_id}])})
|
||||
for span_id, timestamp in zip(span_ids, timestamps, strict=True)
|
||||
]
|
||||
)
|
||||
@@ -340,9 +325,7 @@ def test_thread_opens_around_span(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
seed_attribute_evolution: Callable[[str, datetime], None],
|
||||
) -> None:
|
||||
seed_attribute_evolution("traces", ATTRIBUTE_JSON_ROLLOUT_TIME)
|
||||
now = datetime.now(tz=UTC).replace(microsecond=0)
|
||||
trace_id = TraceIdGenerator.trace_id()
|
||||
resources = {"service.name": "tracedetail-thread-anchor"}
|
||||
@@ -352,7 +335,7 @@ def test_thread_opens_around_span(
|
||||
# http span, not a thread row, sits between the third and fourth llm spans
|
||||
insert_traces(
|
||||
[
|
||||
Traces(timestamp=now - timedelta(seconds=20), duration=timedelta(seconds=19), trace_id=trace_id, span_id=root_id, name="POST /chat", kind=TracesKind.SPAN_KIND_SERVER, resources=resources, attribute_write_mode="json_only"),
|
||||
Traces(timestamp=now - timedelta(seconds=20), duration=timedelta(seconds=19), trace_id=trace_id, span_id=root_id, name="POST /chat", kind=TracesKind.SPAN_KIND_SERVER, resources=resources),
|
||||
*(
|
||||
Traces(
|
||||
timestamp=now - timedelta(seconds=18 - 3 * i),
|
||||
@@ -362,11 +345,10 @@ def test_thread_opens_around_span(
|
||||
name="chat gpt-4o",
|
||||
resources=resources,
|
||||
attributes={"gen_ai.request.model": "gpt-4o", "gen_ai.input.messages": json.dumps([{"role": "user", "content": span_id}])},
|
||||
attribute_write_mode="json_only",
|
||||
)
|
||||
for i, span_id in enumerate(llm_ids)
|
||||
),
|
||||
Traces(timestamp=now - timedelta(seconds=11), trace_id=trace_id, span_id=http_id, parent_span_id=root_id, name="GET /weather", resources=resources, attributes={"http.request.method": "GET"}, attribute_write_mode="json_only"),
|
||||
Traces(timestamp=now - timedelta(seconds=11), trace_id=trace_id, span_id=http_id, parent_span_id=root_id, name="GET /weather", resources=resources, attributes={"http.request.method": "GET"}),
|
||||
]
|
||||
)
|
||||
|
||||
@@ -420,11 +402,8 @@ def test_thread_reads_spans_across_json_rollout(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
seed_attribute_evolution: Callable[[str, datetime], None],
|
||||
) -> None:
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
rollout = now - timedelta(minutes=30)
|
||||
seed_attribute_evolution("traces", rollout)
|
||||
rollout = get_attribute_evolution_time(signoz, "traces").replace(second=0, microsecond=0)
|
||||
resources = {"service.name": "tracedetail-thread-rollout"}
|
||||
|
||||
# trace entirely before the rollout: messages live only in the legacy maps
|
||||
@@ -472,16 +451,14 @@ def test_thread_without_gen_ai_spans_is_empty(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
seed_attribute_evolution: Callable[[str, datetime], None],
|
||||
) -> None:
|
||||
seed_attribute_evolution("traces", ATTRIBUTE_JSON_ROLLOUT_TIME)
|
||||
trace_id = TraceIdGenerator.trace_id()
|
||||
resources = {"service.name": "tracedetail-thread-empty"}
|
||||
# messages without a gate key, as a failed call or an unmapped SDK writes them, are not a row either
|
||||
insert_traces(
|
||||
[
|
||||
Traces(timestamp=datetime.now(tz=UTC) - timedelta(seconds=5), trace_id=trace_id, span_id=TraceIdGenerator.span_id(), name="GET /health", resources=resources, attribute_write_mode="json_only"),
|
||||
Traces(timestamp=datetime.now(tz=UTC) - timedelta(seconds=4), trace_id=trace_id, span_id=TraceIdGenerator.span_id(), name="chat", resources=resources, attributes={"gen_ai.input.messages": json.dumps([{"role": "user", "content": "hi"}])}, attribute_write_mode="json_only"),
|
||||
Traces(timestamp=datetime.now(tz=UTC) - timedelta(seconds=5), trace_id=trace_id, span_id=TraceIdGenerator.span_id(), name="GET /health", resources=resources),
|
||||
Traces(timestamp=datetime.now(tz=UTC) - timedelta(seconds=4), trace_id=trace_id, span_id=TraceIdGenerator.span_id(), name="chat", resources=resources, attributes={"gen_ai.input.messages": json.dumps([{"role": "user", "content": "hi"}])}),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import requests
|
||||
|
||||
from fixtures import types
|
||||
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
|
||||
from fixtures.traces import ATTRIBUTE_JSON_ROLLOUT_TIME, TraceIdGenerator, Traces, TracesKind
|
||||
from fixtures.traces import TraceIdGenerator, Traces, TracesKind
|
||||
|
||||
|
||||
def test_waterfall_formats_messages_on_gen_ai_spans(
|
||||
@@ -15,9 +15,7 @@ def test_waterfall_formats_messages_on_gen_ai_spans(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
seed_attribute_evolution: Callable[[str, datetime], None],
|
||||
) -> None:
|
||||
seed_attribute_evolution("traces", ATTRIBUTE_JSON_ROLLOUT_TIME)
|
||||
now = datetime.now(tz=UTC).replace(microsecond=0)
|
||||
trace_id = TraceIdGenerator.trace_id()
|
||||
root_id, llm_id, tool_id, output_only_id = (TraceIdGenerator.span_id() for _ in range(4))
|
||||
|
||||
@@ -6,7 +6,7 @@ import requests
|
||||
|
||||
from fixtures import types
|
||||
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
|
||||
from fixtures.traces import ATTRIBUTE_JSON_ROLLOUT_TIME, TraceIdGenerator, Traces, TracesKind
|
||||
from fixtures.traces import TraceIdGenerator, Traces, TracesKind
|
||||
|
||||
|
||||
def test_waterfall_and_flamegraph_read_each_attribute_home(
|
||||
@@ -14,9 +14,7 @@ def test_waterfall_and_flamegraph_read_each_attribute_home(
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
seed_attribute_evolution: Callable[[str, datetime], None],
|
||||
) -> None:
|
||||
seed_attribute_evolution("traces", ATTRIBUTE_JSON_ROLLOUT_TIME)
|
||||
now = datetime.now(tz=UTC).replace(microsecond=0)
|
||||
trace_id = TraceIdGenerator.trace_id()
|
||||
legacy_id, json_id, dual_id = (TraceIdGenerator.span_id() for _ in range(3))
|
||||
|
||||
Reference in New Issue
Block a user