Compare commits

..

15 Commits

Author SHA1 Message Date
Tushar Vats
ca7daf8ea9 fix(querier): skip offset rows without decoding them (#13564)
Some checks are pending
cacheci / tests (push) Waiting to run
Release Drafter / update_release_draft (push) Waiting to run
build-staging / prepare (push) Waiting to run
build-staging / js-build (push) Blocked by required conditions
build-staging / go-build (push) Blocked by required conditions
build-staging / staging (push) Blocked by required conditions
#### Description

- Raw lists sorted by timestamp (logs: `timestamp, id`) fetch `offset +
limit` rows per chunk and drop the first `offset` in Go. Every dropped
row was first decoded into a `RawRow` (body + attribute maps), so deep
pages loaded every skipped row into memory and could OOM signoz-0.
- `readAsRawSkipping` now steps past the skipped rows with `rows.Next()`
without `Scan`, so they are never decoded. Memory stays at about one
page plus one ClickHouse block.
- `executeWindowList` passes the remaining offset to each chunk and
counts the skipped rows against `need` and `offsetLeft`.

#### Issues closed by this PR

Fixes: SigNoz/events-pod#270
Part of: SigNoz/events-pod#269

#### Additional Information

- Skipped rows still cross the wire. Pushing `OFFSET` into ClickHouse is
point 1 of the issue.
- `TestReadAsRawSkipping` uses `clickhouse-go-mock` rows (v0.15.1,
bumped in SigNoz/signoz#13580), whose `Next()` advances like the real
driver. Each skipped row is marked with `RowError`, so the test fails if
a skipped row is ever scanned.
- New integration tests `test_traces_list_offset_across_chunks` and
`test_logs_list_offset_across_chunks` page a 4h list with offsets
landing in, and crossing into, each of its three time chunks.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 19:20:30 +00:00
Swapnil Nakade
d038407475 feat(session): add resource defs to session routes (#13563)
<!--A few plain bullets saying what changed and why, for a reviewer
skimming it - not a wall of text, not a restatement of the diff, not
generated boilerplate.-->
#### Description
- add resource defs to session routes
- why? - so that auditor can pick up these routes for auditing
- session routes are pre-auth so audit events will be dropped at the
zero org id condition
- rotate and delete session (when session is active) routes are audited

<!--Reference issues using `Closes #issue-number` to enable automatic
closure on merge. -->
#### Issues closed by this PR
contributes to https://github.com/SigNoz/keystone-pod/issues/10
2026-11-13 17:16:26 +00:00
Tushar Vats
da3719ec7e chore(deps): bump clickhouse-go-mock to v0.15.1 (#13580)
#### Description

- Bumps `github.com/SigNoz/clickhouse-go-mock` v0.14.0 → v0.15.1. Its
`Rows.Next()` now advances like the real driver (skipping a row with
`Next()` and no `Scan()` works), and the new `Rows.RowError` fails
`Scan` of a chosen row (SigNoz/clickhouse-go-mock#14).
- v0.15.1 requires clickhouse-go v2.47.0, so this also raises
**production** clickhouse-go 2.44.0 → 2.47.0 and ch-go 0.71.0 → 0.73.0,
with transitive bumps (zap 1.28.0, otelhttp 0.69.0, gopsutil 4.26.5,
lz4, orb, brotli, purego, go-version, go-sysconf, numcpus, plan9stats).
- Kept apart from SigNoz/signoz#13564 so the driver upgrade can be
reverted on its own.

#### Issues closed by this PR

Part of: SigNoz/events-pod#270

#### Additional Information

- clickhouse-go 2.45–2.47: positional binding now skips `?` inside
string literals, quoted identifiers and comments (`--`, `/* */`, `#`)
(ClickHouse/clickhouse-go#1879, #1888). Our builders emit no SQL
comments and no `?` inside quotes, and values inlined by
`pkg/clickhousesql` that contain `?` were previously bound as
placeholders; now they stay literal. `\?` handling is unchanged. Other
fixes: JSON column serialization version (#1850), DateTime/DateTime64
time zones (#1882), connection eviction on wrapped net errors (#1869).
- ch-go 0.73.0 drops the obsolete nested-exception flag
(ClickHouse/ch-go#1159, marked breaking): `proto.Exception.Nested` is
gone. We only use ch-go's error-code constants, and clickhouse-go's own
`Exception` is unchanged between 2.44.0 and 2.47.0.
- Tested: `go build ./...`, `go test ./...` (all pass), `go vet ./...`
(same 38 findings as `main`, none new). Integration suites
`querierlogs`, `queriertraces` and `querier_json_body` against a server
built with these versions: 624 pass (5 first hit ClickHouse memory
limits in the shared local test container while inserting fixtures, and
passed on rerun).
- Follow-up: #13564 switches `TestReadAsRawSkipping` to `cmock` +
`RowError` and drops its mockery driver mocks once this merges.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-11-13 17:13:24 +00:00
Gaurav Tewari
99745b7dba fix(ai-assistant): open explorer chips on the answer's time range (#13363)
#### Description
- Noz's explorer chips carried the query but not its time window, so the
Explorer opened on the current picker value (e.g. Last 6 hours) instead
of the window the answer was computed for.
- Chips now apply the action's `start`/`end` as an absolute range:
off-page via `startTime`/`endTime` on the Explorer URL; on an
already-open Explorer by also setting the global time and dropping the
stale `relativeTime`.
- Without a valid range nothing changes: query and filters hand over,
time stays as is.

#### Issues closed by this PR
Closes SigNoz/nerve-pod#174

#### Screenshots / Screen Recordings
Prev -


https://github.com/user-attachments/assets/9d54125f-ed32-486e-acc2-2d1c59963fa5

 


Now -




https://github.com/user-attachments/assets/1ce75dc0-d62a-430c-b458-ca1036459955




#### Additional Information
- Stacked on #13557, which carries the `redirectWithQueryBuilderData`
change this relies on.
- The Explorers' global time is Redux-only, so `useDispatch` goes behind
the existing `no-restricted-imports` escape hatch.
- Time params are not written with nuqs: the Explorers' time is Redux +
react-router URL writes, and a second nuqs writer adds a history entry
or leaves react-router with a stale `relativeTime` (see
`utils/timeUrlParams.ts`). Once the Explorers move to
`store/globalTime`, the chip can call `setSelectedTime` and drop its URL
handling.

---------

Co-authored-by: Gaurav Tewari <tewarig@users.noreply.github.com>
2026-11-13 17:10:07 +00:00
Swapnil Nakade
fb60ae1594 refactor: using signoz otel collector image for ch migration (#13517)
<!--A few plain bullets saying what changed and why, for a reviewer
skimming it - not a wall of text, not a restatement of the diff, not
generated boilerplate.-->
#### Description
- using signoz otel collector image for ch migration
- adding auditquerier in test suite in ci
- added v0.144.16-rc.1 temporarily
2026-11-13 16:53:14 +00:00
Gaurav Tewari
d099467285 feat(query-builder): drop null params and forward navigate options on redirect (#13557)
#### Description
- `redirectWithQueryBuilderData` deletes a search param passed as `null`
instead of writing `"null"`, so one navigation can swap params (e.g.
`relativeTime` for `startTime`/`endTime`).
- Its trailing `newTab` flag becomes `navigateOptions: { newTab, replace
}`, passed straight to `safeNavigate`.

#### Issues closed by this PR

#### Screenshots / Screen Recordings

#### Additional Information
- Split out of #13363. Stacked on #13556 only to keep #13363's diff
clean; it doesn't depend on it.
- The `source: null` reset in `CreateAlertV2/QuerySection` now removes
`source` instead of writing `source=null`; its readers only compare
against `DASHBOARDS`, so behavior is the same.

Co-authored-by: Gaurav Tewari <tewarig@users.noreply.github.com>
2026-11-13 15:51:53 +00:00
Swapnil Nakade
445e3cb088 feat(user): add resource defs to self-service user routes (#13574)
<!--A few plain bullets saying what changed and why, for a reviewer
skimming it - not a wall of text, not a restatement of the diff, not
generated boilerplate.-->
#### Description
- add resource defs to the self-service user routes: get and update my
user, change my password, forgot password, reset password, verify reset
token
- why? so that the auditor can pick up these routes for auditing
- update my user and change my password are audited today
- forgot and reset password are pre-auth, so their audit events are
dropped at the zero org id check until the principal is resolvable
- routes stay open access, no API or OpenAPI spec change

<!--Reference issues using `Closes #issue-number` to enable automatic
closure on merge. -->
#### Issues closed by this PR
contributes to https://github.com/SigNoz/keystone-pod/issues/10
2026-11-13 14:58:58 +00:00
Nikhil Mantri
0fbd56058f fix(authz): keep rule validation errors behind the rule FGA check (#13576)
#### Description

- Fixes `ruler/08_rule_validation.py` failing on main after #13253,
since the rule authz check runs before the handler's validation.
- Malformed rule JSON returned 500 from the channel extractor, it now
decodes strictly like the handler and returns 400.
- Channel attach checks skip names that don't exist, so the handler's
`validateChannels` returns its clearer error (e.g. channel referenced by
name instead of display name). Existing channels still need attach.
- A malformed rule id now gets the generic `invalid_selector` 400 like
every other FGA route, test updated.
2026-11-13 14:54:47 +00:00
Nikhil Soni
0f598c49ad test(traces): anchor attribute evolution tests to the migrator's rollout (#13551)
#### Description
- Schema migrator `v0.144.13+` (migration 1002) seeds the traces
`attributes` JSON rollout at install, as it already does for resources.
Tests that wrote their own rollout rows broke on it: `[map]` cases read
JSON, and the seed teardown deleted the migrator's row
(`test_summary_ai_trace[map]` failing on #13517).
- Bumps the schema migrator to `v0.144.15` (CI, tests, devenv). Tests no
longer write `column_evolution_metadata`; rollout-straddle tests anchor
to the migrator's time via `get_attribute_evolution_time`, mirroring
`get_resource_evolution_time`.
- Map/JSON dual run kept: `[map]` anchors spans and query window an hour
before the rollout, where the querier reads only the legacy maps, the
same SQL as with `use_trace_attributes_json` off. `queriertraces` raises
the flux interval so those past windows aren't served from each other's
cached buckets.

#### Additional Information
- Unblocks #13517, which switches migrations to the otel-collector
image.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: swapnil-signoz <swapnil@signoz.io>
2026-11-13 13:04:16 +00:00
Gaurav Tewari
b780551de6 fix(navigation): keep an explicit replace: false in safeNavigate (#13556)
#### Description
- `safeNavigate` replaced the history entry whenever the target added a
param the current URL lacked, even when the caller passed `replace:
false`. An explicit `replace` now wins; without one, behavior is
unchanged.
- No caller passes `replace: false` today, so nothing changes until one
opts in.

#### Issues closed by this PR

#### Screenshots / Screen Recordings

#### Additional Information
- Split out of #13363, whose Noz chips need a history entry Back can
return to when they add `startTime`/`endTime` on an open Explorer.

Co-authored-by: Gaurav Tewari <tewarig@users.noreply.github.com>
2026-11-13 11:32:14 +00:00
Nikhil Mantri
8bc4c5f79c feat(authz): rule FGA (#13253)
Some checks failed
build-staging / prepare (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
build-staging / staging (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
cacheci / tests (push) Has been cancelled
#### Description

- Move `/api/v2/rules*`, `/api/v3/rules` and `/api/v2/rules/test` from
role gates to `CheckResources` on rule verbs.
- Create, update, patch, clone and test also check attach and detach on
the notification channels the rule names, diffed against the stored
rule. Unknown channel names are rejected with 400.
- Create, update, patch, clone and test also check read on the telemetry
the rule's query touches, so a rule cannot be used to read signals the
caller cannot query directly. Managed roles already hold these reads,
only custom roles are affected.
- PATCH checks telemetry read only when the body carries
`condition.compositeQuery`, so disabling or renaming a rule needs no
read on its stored query. This adds an opt-in `Optional` flag on
`TelemetryResourceDef` for that one route, every other telemetry def
keeps failing closed.
- Detach of a channel name that no longer exists is skipped instead of
rejected, so a rule whose channel was removed can still be updated.
Attach stays strict.
- Integration tests cover viewer, editor and a custom role on every
gate. No migration, rule tuples come from #13251 and channel links from
#13249.

#### Issues closed by this PR

Closes SigNoz/pulse-pod#286
Closes SigNoz/pulse-pod#355

#### Additional Information

Fifth of five stacked PRs splitting #12927. Stacked on #13252.
2026-11-13 09:15:38 +00:00
Naman Verma
198230f064 fix: remove algorithm from all rule examples and request builders (#13567)
#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/732
2026-11-13 09:11:00 +00:00
Aswin K.M.
0791306e52 feat(build-staging): release staging through the deployments repo on merges and labels (#13571)
#### Description

- Merges to `main` now build and release the staging base
(`overlays/staging/*/signoz/base`), which every staging overlay
inherits.
- `staging:<deployment>` labels on PRs still release only that
deployment's overlay.
- Releases go to `signoz.staging.cl.gcp.deployments` with a `{path,
image, tag}` payload instead of `{deployment, signoz_version, source}`.
- The deployment label is checked against
`^[a-z0-9]([a-z0-9-]*[a-z0-9])?$` before it goes into the path glob and
the JSON payload.
- `checkout`, `create-github-app-token` and `cache` are pinned to
release SHAs.
2026-11-13 09:04:43 +00:00
Ashwin Bhatkal
792de1376d test(storybook): make plays pass on every control value (#13538)
#### Description

- The plays on the alert rules page, the dashboards list and the
metrics, traces, logs and pods explorers now check the args they depend
on: whether rows are listed, which permissions are held, whether the
data loaded, which tab, view or format is open, and how a write answers.
Run once against every control value, 167 of 969 alert rules runs, 336
of 1,372 dashboards list runs and 212 of about 2,200 explorer runs
failed on `main`. All of them pass now.
- The explorer pages' plays moved out of their story files into play
files, as the skill asks. Plays that had become the same play under a
different control value are now one.
- `grantsAll` in `src/storybook/access/access.ts` answers a permission
check from a story's access controls, the same way the `authz/check`
mock does.
- The `signoz-page-story` skill gets a **Plays** section listing the
cases these plays missed and how to guard them with the page's own code,
and `.claude/rules/storybook.md` points at it. CI runs each play only
with its story's own args, so these rules are what keeps a new play from
missing the same cases.
- No screen renders differently: only plays, their mock helpers and the
skill changed.

#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/727
2026-11-13 06:05:06 +00:00
Ashwin Bhatkal
20e6d44289 fix(api): send array query params as repeated keys (#13457)
Some checks failed
build-staging / staging (push) Has been cancelled
build-staging / prepare (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
#### Description

- The generated API client now sends array query params as repeated keys
(`states=firing&states=pending`) instead of axios' default `states[]=`.
The backend binds only repeated keys, so a `states` filter sent through
a generated hook was ignored and every rule came back.
- The alert list page and the home page alerts card drop their own
requests that worked around this.
- `states` on `GET /api/v3/rules` is the only array query param in the
generated and AI assistant clients today, so no other request changes.

#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/719
2026-11-12 16:50:41 +00:00
168 changed files with 5768 additions and 4149 deletions

View File

@@ -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.

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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 }}"}'

View File

@@ -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-otel-collector:v0.144.16-rc.1 \
wiremock/wiremock:2.35.1-1 \
| xargs -P 0 -n 1 docker pull -q
- name: python

View File

@@ -40,6 +40,7 @@ jobs:
suite:
- alertmanager
- alertmanagerrotation
- auditquerier
- basepath
- callbackauthn
- cloudintegrations
@@ -83,8 +84,8 @@ jobs:
- wal
clickhouse-version:
- 25.12.5
schema-migrator-version:
- v0.144.6
signoz-otel-collector-version:
- v0.144.16-rc.1
postgres-version:
- 15
if: |
@@ -155,4 +156,4 @@ jobs:
--sqlite-mode ${{matrix.sqlite-mode}} \
--postgres-version ${{matrix.postgres-version}} \
--clickhouse-version ${{matrix.clickhouse-version}} \
--schema-migrator-version ${{matrix.schema-migrator-version}}
--signoz-otel-collector-version ${{matrix.signoz-otel-collector-version}}

View File

@@ -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

View File

@@ -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`)
- `--signoz-otel-collector-version`: SigNoz OTel collector version, used to run the ClickHouse migrations (default: `v0.144.16-rc.1`)
- `--with-web` — Build the frontend into the SigNoz image (required for e2e)
Example:

View File

@@ -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;

View File

@@ -1,4 +1,6 @@
import { useEffect, useState } from 'react';
import { useCallback, useEffect, useState } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useDispatch } from 'react-redux';
import { convertFiltersToExpression } from 'components/QueryBuilderV2/utils';
import { matchRoute } from 'lib/router/matchRoute';
import { navigate } from 'lib/router/navigation';
@@ -26,6 +28,7 @@ import {
} from 'api/ai-assistant/chat';
import ROUTES from 'constants/routes';
import { QueryParams } from 'constants/query';
import { UpdateTimeInterval } from 'store/actions';
import { buildExplorerNavigationUrl } from 'utils/buildExplorerNavigationUrl';
import { openInNewTab } from 'utils/navigation';
import {
@@ -53,6 +56,7 @@ import {
getPanelTypeForRequestType,
requestTypeFromActionQuery,
} from './utils/getPanelTypeForRequestType';
import { getTimeRangeFromActionQuery } from './utils/getTimeRangeFromActionQuery';
import { isOnResourcePage } from './utils/isOnResourcePage';
import { openSavedViewByKey } from './utils/openSavedView';
import {
@@ -279,6 +283,7 @@ interface ApplyFilterDeps {
typeof useQueryBuilder
>['redirectWithQueryBuilderData'];
handleSetQueryData: ReturnType<typeof useQueryBuilder>['handleSetQueryData'];
setCustomTimeRange: (start: number, end: number) => void;
}
/**
@@ -344,18 +349,35 @@ function applyFilter(action: MessageActionDTO, deps: ApplyFilterDeps): void {
requestTypeFromActionQuery(action.query),
action.signal,
);
const timeRange = getTimeRangeFromActionQuery(action.query);
const normalized = withDerivedFilterExpressions(urlQuery as unknown as Query);
// eslint-disable-next-line no-console
console.log('[apply_filter] normalized', normalized);
if (signalMatchesPathname(action.signal, deps.pathname)) {
// eslint-disable-next-line no-console
console.log('[apply_filter] on-page → handleSetQueryData + redirect');
if (timeRange) {
deps.setCustomTimeRange(timeRange.start, timeRange.end);
}
normalized.builder.queryData.forEach((q, i) => {
deps.handleSetQueryData(i, q);
});
deps.redirectWithQueryBuilderData(normalized, {
[QueryParams.panelTypes]: panelType,
});
deps.redirectWithQueryBuilderData(
normalized,
{
[QueryParams.panelTypes]: panelType,
...(timeRange && {
[QueryParams.startTime]: timeRange.start,
[QueryParams.endTime]: timeRange.end,
// relativeTime outranks startTime/endTime in the time picker, so drop it.
[QueryParams.relativeTime]: null,
}),
},
undefined,
undefined,
// New params like startTime would otherwise make safeNavigate replace the entry.
{ replace: false },
);
return;
}
const base = explorerRouteForSignal(action.signal);
@@ -368,6 +390,10 @@ function applyFilter(action: MessageActionDTO, deps: ApplyFilterDeps): void {
console.log('[apply_filter] off-page → navigate', base);
const url = buildExplorerNavigationUrl(base, normalized, {
[QueryParams.panelTypes]: panelType,
...(timeRange && {
[QueryParams.startTime]: timeRange.start,
[QueryParams.endTime]: timeRange.end,
}),
});
navigate(url);
}
@@ -402,6 +428,13 @@ export default function ActionsSection({
const sendMessage = useAIAssistantStore((s) => s.sendMessage);
const { threadId, page, mode } = useAIAssistantAnalyticsContext();
const { redirectWithQueryBuilderData, handleSetQueryData } = useQueryBuilder();
const dispatch = useDispatch();
const setCustomTimeRange = useCallback(
(start: number, end: number): void => {
dispatch(UpdateTimeInterval('custom', [start, end]));
},
[dispatch],
);
// Per-chip click state, keyed by chip key (see `key` below). Persists
// loading/success/error so the chip reflects the rollback outcome until
@@ -433,9 +466,16 @@ export default function ActionsSection({
pathname,
redirectWithQueryBuilderData,
handleSetQueryData,
setCustomTimeRange,
});
});
}, [actions, pathname, redirectWithQueryBuilderData, handleSetQueryData]);
}, [
actions,
pathname,
redirectWithQueryBuilderData,
handleSetQueryData,
setCustomTimeRange,
]);
if (actions.length === 0) {
return null;
@@ -568,6 +608,7 @@ export default function ActionsSection({
pathname,
redirectWithQueryBuilderData,
handleSetQueryData,
setCustomTimeRange,
});
break;
}

View File

@@ -9,6 +9,7 @@ import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';
import ROUTES from 'constants/routes';
import { getCurrentLocation } from 'lib/router/navigation';
import { UpdateTimeInterval } from 'store/actions';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import { QueryBuilderContextType } from 'types/common/queryBuilder';
@@ -24,7 +25,17 @@ jest.mock('api/common/logEvent', () => ({
default: jest.fn(),
}));
jest.mock('store/actions', () => {
const actual =
jest.requireActual<typeof import('store/actions')>('store/actions');
return { ...actual, UpdateTimeInterval: jest.fn(actual.UpdateTimeInterval) };
});
const mockUndo = undoExecution as jest.MockedFunction<typeof undoExecution>;
const mockUpdateTimeInterval = jest.mocked(UpdateTimeInterval);
const START_MS = Date.UTC(2026, 6, 26, 10, 34);
const END_MS = Date.UTC(2026, 6, 26, 10, 49);
const UNDO_ACTION = {
kind: MessageActionKindDTO.undo,
@@ -38,13 +49,18 @@ function renderUndoChip(): HTMLElement {
}
// Labels differ per test: auto-applied filters are deduped module-wide by label.
function countByServiceAction(label: string): MessageActionDTO {
function countByServiceAction(
label: string,
{ start, end }: { start?: number; end?: number } = {},
): MessageActionDTO {
return {
kind: MessageActionKindDTO.apply_filter,
label,
signal: ApplyFilterSignalDTO.logs,
query: {
requestType: Querybuildertypesv5RequestTypeDTO.scalar,
start,
end,
compositeQuery: {
queries: [
{
@@ -62,10 +78,8 @@ function countByServiceAction(label: string): MessageActionDTO {
};
}
function currentPanelTypesParam(): string | null {
return new URLSearchParams(getCurrentLocation().search).get(
QueryParams.panelTypes,
);
function currentParam(param: string): string | null {
return new URLSearchParams(getCurrentLocation().search).get(param);
}
describe('ActionsSection rollback chip', () => {
@@ -139,7 +153,34 @@ describe('ActionsSection apply_filter', () => {
await waitFor(() =>
expect(getCurrentLocation().pathname).toBe(ROUTES.LOGS_EXPLORER),
);
expect(currentPanelTypesParam()).toBe(JSON.stringify(PANEL_TYPES.TABLE));
expect(currentParam(QueryParams.panelTypes)).toBe(
JSON.stringify(PANEL_TYPES.TABLE),
);
});
it('opens the explorer on the time range that produced the answer', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<ActionsSection
actions={[
countByServiceAction('Open with time', {
start: START_MS,
end: END_MS,
}),
]}
messageId="message-with-time"
/>,
undefined,
{ initialRoute: ROUTES.HOME },
);
await user.click(screen.getByTestId('ai-action-chip-apply_filter'));
await waitFor(() =>
expect(getCurrentLocation().pathname).toBe(ROUTES.LOGS_EXPLORER),
);
expect(currentParam(QueryParams.startTime)).toBe(String(START_MS));
expect(currentParam(QueryParams.endTime)).toBe(String(END_MS));
});
it('switches the open explorer to the Table view when applied on it', async () => {
@@ -167,6 +208,54 @@ describe('ActionsSection apply_filter', () => {
expect(redirectWithQueryBuilderData).toHaveBeenCalledWith(
expect.objectContaining({ builder: expect.anything() }),
{ [QueryParams.panelTypes]: PANEL_TYPES.TABLE },
undefined,
undefined,
{ replace: false },
);
});
it('switches the open explorer to the answer time range', async () => {
const redirectWithQueryBuilderData = jest.fn() as jest.MockedFunction<
QueryBuilderContextType['redirectWithQueryBuilderData']
>;
const handleSetQueryData = jest.fn() as jest.MockedFunction<
QueryBuilderContextType['handleSetQueryData']
>;
render(
<ActionsSection
actions={[
countByServiceAction('Apply with time', {
start: START_MS,
end: END_MS,
}),
]}
messageId="message-on-page-with-time"
/>,
undefined,
{
initialRoute: ROUTES.LOGS_EXPLORER,
queryBuilderOverrides: { redirectWithQueryBuilderData, handleSetQueryData },
},
);
await waitFor(() =>
expect(redirectWithQueryBuilderData).toHaveBeenCalledTimes(1),
);
expect(redirectWithQueryBuilderData).toHaveBeenCalledWith(
expect.objectContaining({ builder: expect.anything() }),
{
[QueryParams.panelTypes]: PANEL_TYPES.TABLE,
[QueryParams.startTime]: START_MS,
[QueryParams.endTime]: END_MS,
[QueryParams.relativeTime]: null,
},
undefined,
undefined,
{ replace: false },
);
expect(mockUpdateTimeInterval).toHaveBeenCalledWith('custom', [
START_MS,
END_MS,
]);
});
});

View File

@@ -0,0 +1,25 @@
import type { MessageActionDTOQuery } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { normalizeTimeToMs } from 'utils/timeUtils';
export interface ActionTimeRange {
start: number;
end: number;
}
function toTimestampMs(value: unknown): number | null {
if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
return null;
}
return normalizeTimeToMs(Math.trunc(value));
}
export function getTimeRangeFromActionQuery(
query: MessageActionDTOQuery | undefined,
): ActionTimeRange | null {
const start = toTimestampMs(query?.start);
const end = toTimestampMs(query?.end);
if (start === null || end === null || end <= start) {
return null;
}
return { start, end };
}

View File

@@ -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,

View File

@@ -324,7 +324,6 @@ export function buildCreateAnomalyAlertRulePayload(
condition: {
...payload.condition,
thresholds: { kind: 'basic', spec: thresholds },
algorithm: thresholdState.algorithm,
seasonality: thresholdState.seasonality,
},
};

View File

@@ -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',
});
});

View File

@@ -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,
};

View File

@@ -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(

View File

@@ -104,5 +104,5 @@ describe('AI observability Explorer', () => {
...defaultOptionsQuery,
selectColumns: [],
});
});
}, 15_000);
});

View File

@@ -3,4 +3,24 @@
flex-direction: column;
gap: var(--spacing-8);
padding: var(--spacing-0) var(--spacing-0);
//TODO: remove this once we have a proper dashboard page.
// The embedded V2 DashboardContainer renders its own page header (dashboard
// title + share/feedback chrome) removed it for now
:global([class*='dashboardPageHeader']),
:global([class*='dashboardInfoWithActions']) {
display: none;
}
// Embedded read-only: the add-variable and panel-action triggers are dead here.
:global([class*='addSlot']),
:global([data-testid^='panel-actions-']) {
display: none;
}
}
.errorState {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--spacing-2);
padding: var(--spacing-8);
}

View File

@@ -1,24 +1,47 @@
import { useEffect } from 'react';
import { Typography } from '@signozhq/ui/typography';
import logEvent from 'api/common/logEvent';
import SystemDashboard from 'container/SystemDashboard/SystemDashboard';
import { createSystemDashboardHost } from 'container/SystemDashboard/systemDashboardHost';
import { CHARTS_ONLY } from 'pages/DashboardPage/DashboardContainer/controls/presets';
import Spinner from 'components/Spinner';
import DashboardContainer from 'pages/DashboardPage/DashboardContainer';
import { useSystemDashboard } from './hooks/useSystemDashboard';
import styles from './Overview.module.scss';
const AI_OVERVIEW = createSystemDashboardHost(
'ai-o11y-overview',
'llm-observability-overview',
);
function Overview(): JSX.Element {
const { dashboard, isLoading, isError, error, refetch } = useSystemDashboard();
useEffect(() => {
void logEvent('AI Observability Overview: Page visited', {});
}, []);
const renderContent = (): JSX.Element => {
if (isLoading) {
return <Spinner tip="Loading dashboard..." />;
}
if (isError || !dashboard) {
return (
<div className={styles.errorState}>
<Typography.Title>Failed to load dashboard</Typography.Title>
<Typography.Text>
{error?.response?.data?.error?.message ?? error?.message}
</Typography.Text>
</div>
);
}
return (
<DashboardContainer
dashboard={dashboard}
refetch={refetch}
canEditDashboardOverride={false}
/>
);
};
return (
<div className={styles.overview} data-testid="llm-observability-overview">
<SystemDashboard host={AI_OVERVIEW} controls={CHARTS_ONLY} />
{renderContent()}
</div>
);
}

View File

@@ -0,0 +1,56 @@
import { useCallback, useMemo } from 'react';
import { useQueryClient } from 'react-query';
import {
getGetDashboardV2QueryKey,
useGetSystemDashboard,
} from 'api/generated/services/dashboard';
import type { GetSystemDashboardQueryError } from 'api/generated/services/dashboard';
import type {
DashboardtypesGettableDashboardV2DTO,
GetDashboardV2200,
} from 'api/generated/services/sigNoz.schemas';
const SYSTEM_DASHBOARD_NAME = 'ai-o11y-overview';
const DASHBOARD_ID = 'llm-observability-overview';
export interface UseSystemDashboardResult {
dashboard: DashboardtypesGettableDashboardV2DTO | undefined;
isLoading: boolean;
isError: boolean;
error: GetSystemDashboardQueryError | null;
refetch: () => void;
}
export function useSystemDashboard(): UseSystemDashboardResult {
const queryClient = useQueryClient();
const { data, isLoading, isError, error, refetch } = useGetSystemDashboard(
{ name: SYSTEM_DASHBOARD_NAME },
{ query: { staleTime: Infinity, refetchOnMount: false } },
);
const dashboard = useMemo(
() =>
data
? ({
...data.data,
id: DASHBOARD_ID,
} as DashboardtypesGettableDashboardV2DTO)
: undefined,
[data],
);
if (dashboard) {
queryClient.setQueryData<GetDashboardV2200>(
getGetDashboardV2QueryKey({ id: DASHBOARD_ID }),
{ data: dashboard, status: 'success' },
);
}
const refetchDashboard = useCallback((): void => {
void refetch();
}, [refetch]);
return { dashboard, isLoading, isError, error, refetch: refetchDashboard };
}

View File

@@ -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(

View File

@@ -2,14 +2,77 @@
display: flex;
flex-direction: column;
.meter-explorer-notices {
.meter-explorer-date-time {
display: flex;
min-height: 30px;
justify-content: end;
border-bottom: 1px solid var(--l1-border);
padding: 10px 16px;
}
.meter-explorer-graphs {
display: flex;
flex-direction: column;
gap: 12px;
padding: 16px 20px 0;
padding: 20px;
gap: 36px;
&:empty {
display: none;
.info {
display: flex;
flex-direction: column;
gap: 12px;
}
.meter-column-graph {
.row-card {
background-color: var(--l2-background);
padding-left: 10px;
height: 32px;
display: flex;
justify-content: center;
align-items: center;
.section-title {
color: var(--l2-foreground);
font-family: Inter;
font-size: 14px;
font-style: normal;
font-weight: 500;
line-height: 20px;
letter-spacing: -0.07px;
}
}
.graph-description {
padding: 10px;
display: flex;
justify-content: center;
align-items: center;
}
.meter-page-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
align-items: flex-start;
gap: 10px;
.meter-graph {
height: 400px;
padding: 10px;
width: 100%;
box-sizing: border-box;
}
}
}
.total {
.meter-column-graph {
.meter-page-grid {
grid-template-columns: repeat(3, 1fr);
.meter-graph {
height: 200px;
}
}
}
}
}
}

View File

@@ -1,30 +1,121 @@
import { useCallback } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
import { useDispatch, useSelector } from 'react-redux';
import { useAppLocation } from 'lib/router/useAppLocation';
import { navigate } from 'lib/router/navigation';
import { Alert } from 'antd';
import { Typography } from '@signozhq/ui/typography';
import getLocalStorageApi from 'api/browser/localstorage/get';
import setLocalStorageApi from 'api/browser/localstorage/set';
import { LOCALSTORAGE } from 'constants/localStorage';
import SystemDashboard from 'container/SystemDashboard/SystemDashboard';
import { createSystemDashboardHost } from 'container/SystemDashboard/systemDashboardHost';
import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';
import GridCard from 'container/WidgetCard/Card';
import { Card, CardContainer } from 'container/WidgetCard/styles';
import DateTimeSelectionV2 from 'container/TopNav/DateTimeSelectionV2';
import dayjs from 'dayjs';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import {
CHARTS_ONLY,
withControls,
} from 'pages/DashboardPage/DashboardContainer/controls/presets';
import useUrlQuery from 'hooks/useUrlQuery';
import { UpdateTimeInterval } from 'store/actions';
import { AppState } from 'store/reducers';
import { Widgets } from 'types/api/widgets/widget';
import { GlobalReducer } from 'types/reducer/globalTime';
import { v4 as uuid } from 'uuid';
import {
getLogCountWidgetData,
getLogSizeWidgetData,
getMetricCountWidgetData,
getSpanCountWidgetData,
getSpanSizeWidgetData,
getTotalLogSizeWidgetData,
getTotalMetricDatapointCountWidgetData,
getTotalTraceSizeWidgetData,
} from './graphs';
import './BreakDown.styles.scss';
const COST_METER = createSystemDashboardHost(
'cost-meter-breakdown',
'cost-meter-breakdown',
);
type MetricSection = {
id: string;
title: string;
graphs: Widgets[];
};
const CONTROLS = withControls(CHARTS_ONLY, {
toolbar: { autoRefresh: false },
});
const sections: MetricSection[] = [
{
id: uuid(),
title: 'Total',
graphs: [
getTotalLogSizeWidgetData(),
getTotalTraceSizeWidgetData(),
getTotalMetricDatapointCountWidgetData(),
],
},
{
id: uuid(),
title: 'Logs',
graphs: [getLogCountWidgetData(), getLogSizeWidgetData()],
},
{
id: uuid(),
title: 'Traces',
graphs: [getSpanCountWidgetData(), getSpanSizeWidgetData()],
},
{
id: uuid(),
title: 'Metrics',
graphs: [getMetricCountWidgetData()],
},
];
function Section(section: MetricSection): JSX.Element {
const isDarkMode = useIsDarkMode();
const { title, graphs } = section;
const { pathname } = useAppLocation();
const dispatch = useDispatch();
const urlQuery = useUrlQuery();
const onDragSelect = useCallback(
(start: number, end: number) => {
const startTimestamp = Math.trunc(start);
const endTimestamp = Math.trunc(end);
urlQuery.set(QueryParams.startTime, startTimestamp.toString());
urlQuery.set(QueryParams.endTime, endTimestamp.toString());
const generatedUrl = `${pathname}?${urlQuery.toString()}`;
navigate(generatedUrl);
if (startTimestamp !== endTimestamp) {
dispatch(UpdateTimeInterval('custom', [startTimestamp, endTimestamp]));
}
},
[dispatch, pathname, urlQuery],
);
return (
<div
className="meter-column-graph"
data-testid={`meter-breakdown-section-${title.toLowerCase()}`}
>
<CardContainer className="row-card" isDarkMode={isDarkMode}>
<Typography.Text className="section-title">{title}</Typography.Text>
</CardContainer>
<div className="meter-page-grid">
{graphs.map((widget) => (
<Card
key={widget?.id}
isDarkMode={isDarkMode}
$panelType={PANEL_TYPES.BAR}
className="meter-graph"
>
<GridCard widget={widget} onDragSelect={onDragSelect} version="v5" />
</Card>
))}
</div>
</div>
);
}
function BreakDown(): JSX.Element {
const { isCloudUser } = useGetTenantLicense();
@@ -42,7 +133,10 @@ function BreakDown(): JSX.Element {
return (
<div className="meter-explorer-breakdown">
<section className="meter-explorer-notices">
<section className="meter-explorer-date-time">
<DateTimeSelectionV2 showAutoRefresh={false} />
</section>
<section className="meter-explorer-graphs">
{showInfo && (
<Alert
type="info"
@@ -85,8 +179,28 @@ function BreakDown(): JSX.Element {
}
/>
)}
<section className="total">
<Section
id={sections[0].id}
title={sections[0].title}
graphs={sections[0].graphs}
/>
</section>
{sections.map((section, idx) => {
if (idx === 0) {
return;
}
return (
<Section
key={section.id}
id={section.id}
title={section.title}
graphs={section.graphs}
/>
);
})}
</section>
<SystemDashboard host={COST_METER} controls={CONTROLS} />
</div>
);
}

View File

@@ -1,49 +0,0 @@
import type { DashboardControlsInput } from 'pages/DashboardPage/DashboardContainer/controls/types';
import { resolveControls } from 'pages/DashboardPage/DashboardContainer/controls/dashboardControls';
import { render, screen } from 'tests/test-utils';
import type { SystemDashboardHost } from 'container/SystemDashboard/systemDashboardHost';
import BreakDown from '../BreakDown';
jest.mock('container/SystemDashboard/SystemDashboard', () => ({
__esModule: true,
default: ({
host,
controls,
}: {
host: SystemDashboardHost;
controls: DashboardControlsInput;
}): JSX.Element => (
<div
data-testid="system-dashboard"
data-name={host.name}
data-controls={JSON.stringify(controls)}
/>
),
}));
describe('Cost meter breakdown', () => {
it('mounts the cost meter system dashboard as charts only, without auto-refresh', () => {
render(<BreakDown />);
const dashboard = screen.getByTestId('system-dashboard');
expect(dashboard).toHaveAttribute('data-name', 'cost-meter-breakdown');
const controls = resolveControls(
JSON.parse(dashboard.getAttribute('data-controls') ?? ''),
true,
);
expect(controls.header.breadcrumbs).toBe(false);
expect(controls.panelActions.createAlert).toBe(false);
expect(controls.panelActions.drilldown).toBe(false);
expect(controls.panelActions.zoom).toBe(true);
expect(controls.toolbar.autoRefresh).toBe(false);
expect(controls.toolbar.timeRange).toBe(true);
});
it('keeps the UTC billing notice above the dashboard', () => {
render(<BreakDown />);
expect(screen.getByText(/Billing is calculated in UTC/)).toBeInTheDocument();
});
});

View File

@@ -0,0 +1,374 @@
import { PANEL_TYPES } from 'constants/queryBuilder';
import { GetWidgetQueryBuilderProps } from 'container/MetricsApplication/types';
import { Widgets } from 'types/api/widgets/widget';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import {
IBuilderFormula,
IBuilderQuery,
} from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
import { v4 as uuid } from 'uuid';
interface GetWidgetQueryProps {
title: string;
description: string;
queryData: IBuilderQuery[];
queryFormulas?: IBuilderFormula[];
panelTypes?: PANEL_TYPES;
yAxisUnit?: string;
columnUnits?: Record<string, string>;
}
interface GetWidgetQueryPropsReturn extends GetWidgetQueryBuilderProps {
description?: string;
nullZeroValues: string;
columnUnits?: Record<string, string>;
}
export const getWidgetQueryBuilder = ({
query,
title = '',
panelTypes,
yAxisUnit = '',
fillSpans = false,
id,
nullZeroValues,
description,
}: GetWidgetQueryPropsReturn): Widgets => ({
description: description || '',
id: id || uuid(),
nullZeroValues: nullZeroValues || '',
opacity: '1',
panelTypes,
query,
timePreferance: 'GLOBAL_TIME',
title,
yAxisUnit,
softMax: null,
softMin: null,
selectedLogFields: [],
selectedTracesFields: [],
fillSpans,
});
export function getWidgetQuery(
props: GetWidgetQueryProps,
): GetWidgetQueryPropsReturn {
const { title, description, panelTypes, yAxisUnit, columnUnits } = props;
return {
title,
yAxisUnit: yAxisUnit || 'none',
panelTypes: panelTypes || PANEL_TYPES.TIME_SERIES,
fillSpans: false,
description,
nullZeroValues: 'zero',
columnUnits,
query: {
queryType: EQueryType.QUERY_BUILDER,
promql: [],
builder: {
queryData: props.queryData,
queryFormulas: (props.queryFormulas as IBuilderFormula[]) || [],
queryTraceOperator: [],
},
clickhouse_sql: [],
id: uuid(),
},
};
}
export const getTotalLogSizeWidgetData = (): Widgets =>
getWidgetQueryBuilder(
getWidgetQuery({
queryData: [
{
aggregateAttribute: {
dataType: DataTypes.Float64,
key: 'signoz.meter.log.size',
id: 'signoz.meter.log.size--float64--Sum--true',
type: 'Sum',
},
aggregateOperator: 'increase',
dataSource: DataSource.METRICS,
source: 'meter',
disabled: false,
expression: 'A',
filters: { items: [], op: 'AND' },
functions: [],
groupBy: [],
having: [],
legend: 'count',
limit: null,
orderBy: [],
queryName: 'A',
reduceTo: ReduceOperators.SUM,
spaceAggregation: 'sum',
stepInterval: null,
timeAggregation: 'increase',
},
],
title: 'Total size of log records ingested',
description: '',
panelTypes: PANEL_TYPES.VALUE,
yAxisUnit: 'bytes',
}),
);
export const getTotalTraceSizeWidgetData = (): Widgets =>
getWidgetQueryBuilder(
getWidgetQuery({
queryData: [
{
aggregateAttribute: {
dataType: DataTypes.Float64,
key: 'signoz.meter.span.size',
id: 'signoz.meter.span.size--float64--Sum--true',
type: 'Sum',
},
aggregateOperator: 'increase',
dataSource: DataSource.METRICS,
source: 'meter',
disabled: false,
expression: 'A',
filters: { items: [], op: 'AND' },
functions: [],
groupBy: [],
having: [],
legend: 'count',
limit: null,
orderBy: [],
queryName: 'A',
reduceTo: ReduceOperators.SUM,
spaceAggregation: 'sum',
stepInterval: null,
timeAggregation: 'increase',
},
],
title: 'Total size of spans ingested',
description: '',
panelTypes: PANEL_TYPES.VALUE,
yAxisUnit: 'bytes',
}),
);
export const getTotalMetricDatapointCountWidgetData = (): Widgets =>
getWidgetQueryBuilder(
getWidgetQuery({
queryData: [
{
aggregateAttribute: {
dataType: DataTypes.Float64,
key: 'signoz.meter.metric.datapoint.count',
id: 'signoz.meter.metric.datapoint.count--float64--Sum--true',
type: 'Sum',
},
aggregateOperator: 'increase',
dataSource: DataSource.METRICS,
source: 'meter',
disabled: false,
expression: 'A',
filters: { items: [], op: 'AND' },
functions: [],
groupBy: [],
having: [],
legend: 'count',
limit: null,
orderBy: [],
queryName: 'A',
reduceTo: ReduceOperators.SUM,
spaceAggregation: 'sum',
stepInterval: null,
timeAggregation: 'increase',
},
],
title: 'Total metric datapoints ingested',
description: '',
panelTypes: PANEL_TYPES.VALUE,
yAxisUnit: 'short',
}),
);
export const getLogCountWidgetData = (): Widgets =>
getWidgetQueryBuilder(
getWidgetQuery({
queryData: [
{
aggregateAttribute: {
dataType: DataTypes.Float64,
key: 'signoz.meter.log.count',
id: 'signoz.meter.log.count--float64--Sum--true',
type: 'Sum',
},
aggregateOperator: 'increase',
dataSource: DataSource.METRICS,
source: 'meter',
disabled: false,
expression: 'A',
filters: { items: [], op: 'AND' },
functions: [],
groupBy: [],
having: [],
legend: 'count',
limit: null,
orderBy: [],
queryName: 'A',
reduceTo: ReduceOperators.AVG,
spaceAggregation: 'sum',
stepInterval: null,
timeAggregation: 'increase',
},
],
title: 'Count of log records ingested',
description: '',
panelTypes: PANEL_TYPES.BAR,
yAxisUnit: 'short',
}),
);
export const getLogSizeWidgetData = (): Widgets =>
getWidgetQueryBuilder(
getWidgetQuery({
queryData: [
{
aggregateAttribute: {
dataType: DataTypes.Float64,
key: 'signoz.meter.log.size',
id: 'signoz.meter.log.size--float64--Sum--true',
type: 'Sum',
},
aggregateOperator: 'increase',
dataSource: DataSource.METRICS,
source: 'meter',
disabled: false,
expression: 'A',
filters: { items: [], op: 'AND' },
functions: [],
groupBy: [],
having: [],
legend: 'size',
limit: null,
orderBy: [],
queryName: 'A',
reduceTo: ReduceOperators.AVG,
spaceAggregation: 'sum',
stepInterval: null,
timeAggregation: 'increase',
},
],
title: 'Size of log records ingested',
description: '',
panelTypes: PANEL_TYPES.BAR,
yAxisUnit: 'bytes',
}),
);
export const getSpanCountWidgetData = (): Widgets =>
getWidgetQueryBuilder(
getWidgetQuery({
queryData: [
{
aggregateAttribute: {
dataType: DataTypes.Float64,
key: 'signoz.meter.span.count',
id: 'signoz.meter.span.count--float64--Sum--true',
type: 'Sum',
},
aggregateOperator: 'increase',
dataSource: DataSource.METRICS,
source: 'meter',
disabled: false,
expression: 'A',
filters: { items: [], op: 'AND' },
functions: [],
groupBy: [],
having: [],
legend: 'count',
limit: null,
orderBy: [],
queryName: 'A',
reduceTo: ReduceOperators.AVG,
spaceAggregation: 'sum',
stepInterval: null,
timeAggregation: 'increase',
},
],
title: 'Count of spans ingested',
description: '',
panelTypes: PANEL_TYPES.BAR,
yAxisUnit: 'short',
}),
);
export const getSpanSizeWidgetData = (): Widgets =>
getWidgetQueryBuilder(
getWidgetQuery({
queryData: [
{
aggregateAttribute: {
dataType: DataTypes.Float64,
key: 'signoz.meter.span.size',
id: 'signoz.meter.span.size--float64--Sum--true',
type: 'Sum',
},
aggregateOperator: 'increase',
dataSource: DataSource.METRICS,
source: 'meter',
disabled: false,
expression: 'A',
filters: { items: [], op: 'AND' },
functions: [],
groupBy: [],
having: [],
legend: 'size',
limit: null,
orderBy: [],
queryName: 'A',
reduceTo: ReduceOperators.AVG,
spaceAggregation: 'sum',
stepInterval: null,
timeAggregation: 'increase',
},
],
title: 'Size of spans ingested',
description: '',
panelTypes: PANEL_TYPES.BAR,
yAxisUnit: 'bytes',
}),
);
export const getMetricCountWidgetData = (): Widgets =>
getWidgetQueryBuilder(
getWidgetQuery({
queryData: [
{
aggregateAttribute: {
dataType: DataTypes.Float64,
key: 'signoz.meter.metric.datapoint.count',
id: 'signoz.meter.metric.datapoint.count--float64--Sum--true',
type: 'Sum',
},
aggregateOperator: 'increase',
dataSource: DataSource.METRICS,
source: 'meter',
disabled: false,
expression: 'A',
filters: { items: [], op: 'AND' },
functions: [],
groupBy: [],
having: [],
legend: 'count',
limit: null,
orderBy: [],
queryName: 'A',
reduceTo: ReduceOperators.AVG,
spaceAggregation: 'sum',
stepInterval: null,
timeAggregation: 'increase',
},
],
title: 'Count of metric datapoints ingested',
description: '',
panelTypes: PANEL_TYPES.BAR,
yAxisUnit: 'short',
}),
);

View File

@@ -1,7 +0,0 @@
.errorState {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--spacing-2);
padding: var(--spacing-8);
}

View File

@@ -1,49 +0,0 @@
import { Typography } from '@signozhq/ui/typography';
import Spinner from 'components/Spinner';
import DashboardContainer from 'pages/DashboardPage/DashboardContainer';
import type { DashboardControlsInput } from 'pages/DashboardPage/DashboardContainer/controls/types';
import type { SystemDashboardHost } from './systemDashboardHost';
import { useSystemDashboard } from './useSystemDashboard';
import styles from './SystemDashboard.module.scss';
interface SystemDashboardProps {
host: SystemDashboardHost;
controls?: DashboardControlsInput;
}
/** A shipped, read-only system dashboard, embedded in a feature page. */
function SystemDashboard({
host,
controls,
}: SystemDashboardProps): JSX.Element {
const { dashboard, isLoading, isError, error, refetch } =
useSystemDashboard(host);
if (isLoading) {
return <Spinner tip="Loading dashboard..." />;
}
if (isError || !dashboard) {
return (
<div className={styles.errorState} data-testid="system-dashboard-error">
<Typography.Title>Failed to load dashboard</Typography.Title>
<Typography.Text>
{error?.response?.data?.error?.message ?? error?.message}
</Typography.Text>
</div>
);
}
return (
<DashboardContainer
dashboard={dashboard}
refetch={refetch}
source={host.source}
readOnly
controls={controls}
/>
);
}
export default SystemDashboard;

View File

@@ -1,84 +0,0 @@
import {
DashboardtypesSourceDTO,
type GetSystemDashboard200,
} from 'api/generated/services/sigNoz.schemas';
import { rest, server } from 'mocks-server/server';
import { render, screen } from 'tests/test-utils';
import SystemDashboard from '../SystemDashboard';
import { createSystemDashboardHost } from '../systemDashboardHost';
const HOST = createSystemDashboardHost('test-overview', 'test-overview-id');
const ENDPOINT = '*/api/v2/dashboards/system/test-overview';
jest.mock('pages/DashboardPage/DashboardContainer', () => ({
__esModule: true,
default: ({
dashboard,
readOnly,
}: {
dashboard: { id: string; spec: { display: { name: string } } };
readOnly: boolean;
}): JSX.Element => (
<div
data-testid="dashboard-container"
data-dashboard-id={dashboard.id}
data-read-only={String(readOnly)}
>
{dashboard.spec.display.name}
</div>
),
}));
const response: GetSystemDashboard200 = {
status: 'success',
data: {
orgId: 'org',
locked: true,
name: 'signoz---test-overview',
schemaVersion: 'v6',
source: DashboardtypesSourceDTO.system,
tags: [],
spec: {
display: { name: 'Test overview' },
variables: [],
panels: {},
layouts: [],
},
},
};
describe('SystemDashboard', () => {
afterEach(() => server.resetHandlers());
it('mounts the named system dashboard read-only under the host id', async () => {
server.use(rest.get(ENDPOINT, (_req, res, ctx) => res(ctx.json(response))));
render(<SystemDashboard host={HOST} />);
const container = await screen.findByTestId('dashboard-container');
expect(container).toHaveTextContent('Test overview');
expect(container).toHaveAttribute('data-dashboard-id', 'test-overview-id');
expect(container).toHaveAttribute('data-read-only', 'true');
});
it('shows why the dashboard failed to load', async () => {
server.use(
rest.get(ENDPOINT, (_req, res, ctx) =>
res(
ctx.status(404),
ctx.json({
status: 'error',
error: { code: 'not_found', message: 'not provisioned' },
}),
),
),
);
render(<SystemDashboard host={HOST} />);
await expect(
screen.findByTestId('system-dashboard-error'),
).resolves.toHaveTextContent('not provisioned');
});
});

View File

@@ -1,36 +0,0 @@
import { getGetSystemDashboardQueryKey } from 'api/generated/services/dashboard';
import type {
DashboardtypesGettableDashboardV2DTO,
GetSystemDashboard200,
} from 'api/generated/services/sigNoz.schemas';
import type { DashboardQuerySource } from 'pages/DashboardPage/DashboardContainer/store/slices/editContextSlice';
export interface SystemDashboardHost {
/** Definition name without the `signoz---` prefix. */
name: string;
select: (
response: GetSystemDashboard200,
) => DashboardtypesGettableDashboardV2DTO;
source: DashboardQuerySource;
}
/**
* Call at module level: `select` and `source` must stay referentially stable.
* System dashboards carry no `id`; `id` keys the store's per-dashboard state
* (saved variable values), so keep it stable across releases.
*/
export function createSystemDashboardHost(
name: string,
id: string,
): SystemDashboardHost {
const select = (
response: GetSystemDashboard200,
): DashboardtypesGettableDashboardV2DTO =>
({ ...response.data, id }) as DashboardtypesGettableDashboardV2DTO;
return {
name,
select,
source: { queryKey: getGetSystemDashboardQueryKey({ name }), select },
};
}

View File

@@ -1,41 +0,0 @@
import { useCallback } from 'react';
import { useGetSystemDashboard } from 'api/generated/services/dashboard';
import type { GetSystemDashboardQueryError } from 'api/generated/services/dashboard';
import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';
import type { SystemDashboardHost } from './systemDashboardHost';
export interface UseSystemDashboardResult {
dashboard: DashboardtypesGettableDashboardV2DTO | undefined;
isLoading: boolean;
isError: boolean;
error: GetSystemDashboardQueryError | null;
refetch: () => void;
}
export function useSystemDashboard(
host: SystemDashboardHost,
): UseSystemDashboardResult {
const {
data: dashboard,
isLoading,
isError,
error,
refetch,
} = useGetSystemDashboard(
{ name: host.name },
{
query: {
select: host.select,
staleTime: Infinity,
refetchOnMount: false,
},
},
);
const refetchDashboard = useCallback((): void => {
void refetch();
}, [refetch]);
return { dashboard, isLoading, isError, error, refetch: refetchDashboard };
}

View File

@@ -175,7 +175,6 @@ function AutoRefresh({
}
>
<ButtonContainer
data-testid="auto-refresh-trigger"
title="Set auto refresh"
type={showAutoRefreshBtnPrimary ? 'primary' : 'default'}
>

View File

@@ -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));
});
});

View File

@@ -90,7 +90,7 @@ export const useHandleExplorerTabChange = (): {
},
redirectToUrl,
undefined,
newTab,
{ newTab },
);
},
[panelType, getUpdateQuery, redirectWithQueryBuilderData, viewKey],

View File

@@ -140,7 +140,7 @@ export const useSafeNavigate = (
const navigationOptions = {
...options,
replace: isDefaultParamsNavigation || options?.replace,
replace: options?.replace ?? isDefaultParamsNavigation,
};
if (typeof to === 'string') {

View File

@@ -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';

View File

@@ -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' });
/**

View File

@@ -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(),
);
};

View File

@@ -26,10 +26,7 @@ import { useErrorModal } from 'providers/ErrorModalProvider';
import APIError from 'types/api/error';
import AuthZDropdown from 'lib/authz/components/AuthZDropdown/AuthZDropdown';
import type {
AuthZDropdownItemType,
AuthZGroupChildType,
} from 'lib/authz/components/AuthZDropdown/types';
import type { AuthZDropdownItemType } from 'lib/authz/components/AuthZDropdown/types';
import { blockedBy } from 'lib/authz/components/AuthZDropdown/utils';
import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';
import { DashboardCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/dashboard.permissions';
@@ -42,7 +39,6 @@ import styles from './DashboardActions.module.scss';
import { useDeleteDashboardAction } from './useDeleteDashboardAction';
import { useDashboardStore } from '../../store/useDashboardStore';
import { useDashboardEditContext } from '../../hooks/useDashboardEditContext';
import { useDashboardControlGroup } from '../../controls/useDashboardControlGroup';
interface DashboardActionsProps {
title: string;
@@ -70,7 +66,6 @@ function DashboardActions({
deleteChecks,
deleteDisabledTooltip,
} = useDashboardEditContext();
const show = useDashboardControlGroup('dashboardActions');
const settingsRequest = useDashboardStore((s) => s.settingsRequest);
const clearSettingsRequest = useDashboardStore((s) => s.clearSettingsRequest);
const { safeNavigate } = useSafeNavigate();
@@ -78,7 +73,6 @@ function DashboardActions({
const { disabledTooltip: lockDisabledTooltip } = useDashboardLockPermission({
dashboardId: dashboard.id,
source: dashboard.source,
enabled: show.lock,
});
// Cloning creates a new dashboard, so it needs `create` too, and no lock gate.
@@ -168,68 +162,61 @@ function DashboardActions({
void handle.enter();
}, [dashboard.id, handle]);
// Unavailable items stay in the menu, carrying the reason; hidden ones are dropped.
const menuItems = useMemo<AuthZDropdownItemType[]>(() => {
const dashboardItems: AuthZGroupChildType[] = [
...(show.rename
? [
{
type: 'item' as const,
value: 'rename',
testId: 'dashboard-action-rename',
label: 'Rename',
prefix: <PenLine size={14} />,
checks: editChecks,
...blockedBy(editDisabledTooltip),
onClick: onOpenRename,
},
]
: []),
// Clone creates a new dashboard, so it's not lock-gated.
...(show.clone
? [
{
type: 'item' as const,
value: 'clone',
testId: 'dashboard-action-clone',
label: 'Clone dashboard',
prefix: <Copy size={14} />,
checks: cloneChecks,
loading: isCloning,
loadingTooltip: 'Cloning dashboard',
onClick: (): void => void handleClone(),
},
]
: []),
...(show.lock
? [
{
type: 'item' as const,
value: 'lock',
testId: 'dashboard-action-lock',
label: isDashboardLocked ? 'Unlock dashboard' : 'Lock dashboard',
prefix: <LockKeyhole size={14} />,
checks: editChecks,
...blockedBy(lockDisabledTooltip),
onClick: onLockToggle,
},
]
: []),
...(show.fullscreen
? [
{
type: 'item' as const,
value: 'fullscreen',
testId: 'dashboard-action-fullscreen',
label: 'Full screen',
prefix: <Fullscreen size={14} />,
onClick: handleEnterFullScreen,
},
]
: []),
];
const layoutItems: AuthZGroupChildType[] = show.newSection
? [
// Unavailable items stay in the menu, carrying the reason.
const menuItems = useMemo<AuthZDropdownItemType[]>(
() => [
{
type: 'group',
value: 'group-dashboard',
label: 'Dashboard',
items: [
{
type: 'item',
value: 'rename',
testId: 'dashboard-action-rename',
label: 'Rename',
prefix: <PenLine size={14} />,
checks: editChecks,
...blockedBy(editDisabledTooltip),
onClick: onOpenRename,
},
// Clone creates a new dashboard, so it's not lock-gated.
{
type: 'item',
value: 'clone',
testId: 'dashboard-action-clone',
label: 'Clone dashboard',
prefix: <Copy size={14} />,
checks: cloneChecks,
loading: isCloning,
loadingTooltip: 'Cloning dashboard',
onClick: (): void => void handleClone(),
},
{
type: 'item',
value: 'lock',
testId: 'dashboard-action-lock',
label: isDashboardLocked ? 'Unlock dashboard' : 'Lock dashboard',
prefix: <LockKeyhole size={14} />,
checks: editChecks,
...blockedBy(lockDisabledTooltip),
onClick: onLockToggle,
},
{
type: 'item',
value: 'fullscreen',
testId: 'dashboard-action-fullscreen',
label: 'Full screen',
prefix: <Fullscreen size={14} />,
onClick: handleEnterFullScreen,
},
],
},
{
type: 'group',
value: 'group-layout',
label: 'Layout',
items: [
{
type: 'item',
value: 'new-section',
@@ -240,96 +227,66 @@ function DashboardActions({
...blockedBy(editDisabledTooltip),
onClick: (): void => setIsNewSectionOpen(true),
},
]
: [];
return [
...(dashboardItems.length
? [
{
type: 'group' as const,
value: 'group-dashboard',
label: 'Dashboard',
items: dashboardItems,
},
]
: []),
...(layoutItems.length
? [
{
type: 'group' as const,
value: 'group-layout',
label: 'Layout',
items: layoutItems,
},
]
: []),
...(show.delete
? [
{ type: 'separator' as const, value: 'divider-danger' },
{
type: 'item' as const,
value: 'delete',
testId: 'dashboard-action-delete',
label: 'Delete dashboard',
prefix: <Trash2 size={14} />,
danger: true,
checks: deleteChecks,
// Independent of read/update, but a locked dashboard can't be removed.
...blockedBy(deleteDisabledTooltip),
onClick: confirmDeleteDashboard,
},
]
: []),
];
}, [
show,
editChecks,
editDisabledTooltip,
deleteChecks,
deleteDisabledTooltip,
cloneChecks,
isCloning,
lockDisabledTooltip,
isDashboardLocked,
onOpenRename,
handleClone,
onLockToggle,
handleEnterFullScreen,
confirmDeleteDashboard,
]);
],
},
{ type: 'separator', value: 'divider-danger' },
{
type: 'item',
value: 'delete',
testId: 'dashboard-action-delete',
label: 'Delete dashboard',
prefix: <Trash2 size={14} />,
danger: true,
checks: deleteChecks,
// Independent of read/update, but a locked dashboard can't be removed.
...blockedBy(deleteDisabledTooltip),
onClick: confirmDeleteDashboard,
},
],
[
editChecks,
editDisabledTooltip,
deleteChecks,
deleteDisabledTooltip,
cloneChecks,
isCloning,
lockDisabledTooltip,
isDashboardLocked,
onOpenRename,
handleClone,
onLockToggle,
handleEnterFullScreen,
confirmDeleteDashboard,
],
);
return (
<div className={styles.dashboardActionsContainer}>
{menuItems.length > 0 && (
<AuthZDropdown items={menuItems} nativeButton align="end" side="bottom">
<Button
variant="solid"
color="secondary"
size="md"
prefix={<Grid3X3 size="md" />}
testId="options"
>
Actions
</Button>
</AuthZDropdown>
)}
{show.configure && (
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
<Button
disabledTooltip={undefined}
variant="solid"
color="secondary"
prefix={<Configure size="md" />}
testId="show-drawer"
disabled={!isEditable}
onClick={handleOpenSettings}
size="md"
>
Configure
</Button>
</AuthZTooltip>
)}
<AuthZDropdown items={menuItems} nativeButton align="end" side="bottom">
<Button
variant="solid"
color="secondary"
size="md"
prefix={<Grid3X3 size="md" />}
testId="options"
>
Actions
</Button>
</AuthZDropdown>
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
<Button
disabledTooltip={undefined}
variant="solid"
color="secondary"
prefix={<Configure size="md" />}
testId="show-drawer"
disabled={!isEditable}
onClick={handleOpenSettings}
size="md"
>
Configure
</Button>
</AuthZTooltip>
<SettingsDrawer
drawerTitle="Dashboard Configuration"
isOpen={isSettingsDrawerOpen}
@@ -341,34 +298,30 @@ function DashboardActions({
>
<DashboardSettings dashboard={dashboard} />
</SettingsDrawer>
{show.json && (
<Button
variant="solid"
color="secondary"
prefix={<Braces size="md" />}
testId="edit-json"
onClick={handleOpenJsonEditor}
size="md"
>
JSON
</Button>
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
<Button
disabledTooltip={undefined}
variant="solid"
color="secondary"
prefix={<Braces size="md" />}
testId="edit-json"
onClick={handleOpenJsonEditor}
color="primary"
onClick={onAddPanel}
prefix={<Plus size="md" />}
testId="add-panel-header"
disabled={!isEditable}
size="md"
>
JSON
New Panel
</Button>
)}
{show.newPanel && (
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
<Button
disabledTooltip={undefined}
variant="solid"
color="primary"
onClick={onAddPanel}
prefix={<Plus size="md" />}
testId="add-panel-header"
disabled={!isEditable}
size="md"
>
New Panel
</Button>
</AuthZTooltip>
)}
</AuthZTooltip>
<JsonEditorDrawer
dashboard={dashboard}
isOpen={isJsonEditorOpen}

View File

@@ -24,11 +24,9 @@ import { openInNewTab } from 'utils/navigation';
import styles from './DashboardInfo.module.scss';
import TagsOverflowTooltip from './TagsOverflowTooltip';
import { getLockTooltip } from './utils';
import { DASHBOARD_NAME_MAX_LENGTH } from '../../constants';
import { useDashboardStore } from '../../store/useDashboardStore';
import { useDashboardEditContext } from '../../hooks/useDashboardEditContext';
import { useDashboardControlGroup } from '../../controls/useDashboardControlGroup';
// The tag cluster keeps a fixed footprint so a long title ellipsizes around it
// instead of collapsing the tags: show up to two tags, then a `+N` overflow badge.
@@ -77,19 +75,27 @@ function DashboardInfo({
}: DashboardInfoProps): JSX.Element {
const { isEditable: canEdit } = useDashboardEditContext();
const dashboardId = useDashboardStore((s) => s.dashboardId);
const show = useDashboardControlGroup('title');
const hasTags = show.tags && tags.length > 0;
const hasDescription = show.description && !isEmpty(description);
const hasTags = tags.length > 0;
const hasDescription = !isEmpty(description);
const visibleTags = tags.slice(0, MAX_VISIBLE_TAGS);
const remainingTags = tags.slice(MAX_VISIBLE_TAGS);
const lockTooltip = getLockTooltip({
isLocked: isDashboardLocked,
canToggle: !!onToggleLock,
disabledReason: lockDisabledTooltip,
});
// Without a toggle, say why it can't be toggled rather than only restating the
// lock state.
let lockTooltip: string;
if (onToggleLock) {
lockTooltip = isDashboardLocked
? 'Locked — click to unlock'
: 'Unlocked — click to lock';
} else if (lockDisabledTooltip) {
lockTooltip = lockDisabledTooltip;
} else {
lockTooltip = isDashboardLocked
? 'This dashboard is locked'
: 'This dashboard is unlocked';
}
const onKeyDown = (event: KeyboardEvent<HTMLInputElement>): void => {
if (event.key === 'Enter') {
@@ -122,68 +128,65 @@ function DashboardInfo({
return (
<div className={styles.dashboardInfo}>
{show.name && (
<img src={image} alt={title} className={styles.dashboardImage} />
)}
<img src={image} alt={title} className={styles.dashboardImage} />
{show.name &&
(isEditing ? (
<div className={styles.dashboardTitleEditor} onBlur={onEditorBlur}>
<Input
autoFocus
value={draft}
testId="dashboard-title-input"
maxLength={DASHBOARD_NAME_MAX_LENGTH}
className={styles.dashboardTitleInput}
onChange={(e): void => onDraftChange(e.target.value)}
onKeyDown={onKeyDown}
/>
<Button
type="button"
variant="solid"
color="primary"
size="sm"
icon
aria-label="Save title"
testId="dashboard-title-save"
onClick={onCommit}
{isEditing ? (
<div className={styles.dashboardTitleEditor} onBlur={onEditorBlur}>
<Input
autoFocus
value={draft}
testId="dashboard-title-input"
maxLength={DASHBOARD_NAME_MAX_LENGTH}
className={styles.dashboardTitleInput}
onChange={(e): void => onDraftChange(e.target.value)}
onKeyDown={onKeyDown}
/>
<Button
type="button"
variant="solid"
color="primary"
size="sm"
icon
aria-label="Save title"
testId="dashboard-title-save"
onClick={onCommit}
>
<Check size={14} />
</Button>
<Button
type="button"
variant="outlined"
color="secondary"
size="sm"
icon
aria-label="Cancel title edit"
testId="dashboard-title-cancel"
onClick={onCancel}
>
<X size={14} />
</Button>
</div>
) : (
<>
<Tooltip title={title}>
<Typography.Text
className={cx(styles.dashboardTitle, {
[styles.dashboardTitleHover]: canEdit,
})}
data-testid="dashboard-title"
onClick={canEdit ? onStartEdit : undefined}
>
<Check size={14} />
</Button>
<Button
type="button"
variant="outlined"
color="secondary"
size="sm"
icon
aria-label="Cancel title edit"
testId="dashboard-title-cancel"
onClick={onCancel}
>
<X size={14} />
</Button>
</div>
) : (
<>
<Tooltip title={title}>
<Typography.Text
className={cx(styles.dashboardTitle, {
[styles.dashboardTitleHover]: canEdit,
})}
data-testid="dashboard-title"
onClick={canEdit ? onStartEdit : undefined}
>
{title}
</Typography.Text>
</Tooltip>
<CopyButton
value={dashboardId}
ariaLabel="Copy dashboard ID"
testId="dashboard-copy-id"
onCopy={handleCopyId}
/>
</>
))}
{title}
</Typography.Text>
</Tooltip>
<CopyButton
value={dashboardId}
ariaLabel="Copy dashboard ID"
testId="dashboard-copy-id"
onCopy={handleCopyId}
/>
</>
)}
{hasDescription && (
<Tooltip
@@ -202,7 +205,7 @@ function DashboardInfo({
</Tooltip>
)}
{show.publicBadge && isPublicDashboard && (
{isPublicDashboard && (
<Tooltip title="This dashboard is publicly accessible. Click to open the public page.">
<Button
type="button"
@@ -219,7 +222,7 @@ function DashboardInfo({
</Tooltip>
)}
{show.lock && showLockToggle && (
{showLockToggle && (
<Tooltip title={onToggleLock ? lockTooltip : undefined}>
<Button
disabledTooltip={lockTooltip}

View File

@@ -1,19 +0,0 @@
// Without a toggle, say why it can't be toggled rather than only restating the
// lock state.
export function getLockTooltip({
isLocked,
canToggle,
disabledReason,
}: {
isLocked: boolean;
canToggle: boolean;
disabledReason?: string;
}): string {
if (canToggle) {
return isLocked ? 'Locked — click to unlock' : 'Unlocked — click to lock';
}
if (disabledReason) {
return disabledReason;
}
return isLocked ? 'This dashboard is locked' : 'This dashboard is unlocked';
}

View File

@@ -1,138 +0,0 @@
import type { FullScreenHandle } from 'react-full-screen';
import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';
import { useDashboardLockPermission } from 'hooks/dashboards/useDashboardLockPermission';
import { render, screen } from 'tests/test-utils';
import type { DashboardControlsInput } from '../../controls/types';
import { usePublicDashboardMeta } from '../../DashboardSettings/PublicDashboard/usePublicDashboardMeta';
import { useDashboardStore } from '../../store/useDashboardStore';
import DashboardPageToolbar from '../index';
const dashboard = {
id: 'dash-1',
locked: true,
source: 'user',
spec: {
display: { name: 'Checkout' },
panels: {},
layouts: [],
variables: [],
},
} as unknown as DashboardtypesGettableDashboardV2DTO;
const handle = { enter: jest.fn() } as unknown as FullScreenHandle;
jest.mock('../DashboardActions/DashboardActions', () => ({
__esModule: true,
default: (): JSX.Element => <div data-testid="dashboard-actions" />,
}));
jest.mock('../DashboardInfo/DashboardInfo', () => ({
__esModule: true,
default: (): JSX.Element => <div data-testid="dashboard-info" />,
}));
jest.mock('../../VariablesBar/VariablesBar', () => ({
__esModule: true,
default: (): JSX.Element => <div data-testid="variables-bar" />,
}));
jest.mock('container/TopNav/DateTimeSelectionV2', () => ({
__esModule: true,
default: (): JSX.Element => <div data-testid="time-selection" />,
}));
jest.mock(
'../../PanelsAndSectionsLayout/Panel/PanelTypeSelectionModal/PanelTypeSelectionModal',
() => ({ __esModule: true, default: (): null => null }),
);
jest.mock('../../hooks/useCreatePanel', () => ({
useCreatePanel: (): unknown => ({
isPickerOpen: false,
openPicker: jest.fn(),
closePicker: jest.fn(),
createPanel: jest.fn(),
targetLayoutIndex: 0,
}),
}));
jest.mock('../../hooks/useOptimisticPatch', () => ({
useOptimisticPatch: (): unknown => ({ patchAsync: jest.fn() }),
}));
jest.mock('hooks/dashboards/useToggleDashboardLock', () => ({
useToggleDashboardLock: (): unknown => ({ toggleLock: jest.fn() }),
}));
jest.mock('hooks/dashboards/useDashboardLockPermission', () => ({
useDashboardLockPermission: jest.fn(() => ({
canToggleLock: false,
isLoading: false,
disabledTooltip: '',
})),
}));
jest.mock(
'../../DashboardSettings/PublicDashboard/usePublicDashboardMeta',
() => ({
usePublicDashboardMeta: jest.fn(() => ({
isPublic: false,
publicMeta: undefined,
})),
}),
);
function renderToolbar(
ctx: { readOnly?: boolean; controls?: DashboardControlsInput } = {},
): void {
useDashboardStore
.getState()
.setEditContext({ dashboardId: 'dash-1', refetch: jest.fn(), ...ctx });
render(<DashboardPageToolbar dashboard={dashboard} handle={handle} />);
}
describe('DashboardPageToolbar - controls', () => {
afterEach(() => {
useDashboardStore
.getState()
.setEditContext({ dashboardId: '', refetch: jest.fn() });
jest.clearAllMocks();
});
it('renders every row and checks lock + share by default', () => {
renderToolbar();
expect(screen.getByTestId('dashboard-info')).toBeInTheDocument();
expect(screen.getByTestId('dashboard-actions')).toBeInTheDocument();
expect(screen.getByTestId('time-selection')).toBeInTheDocument();
expect(jest.mocked(useDashboardLockPermission)).toHaveBeenCalledWith(
expect.objectContaining({ enabled: true }),
);
expect(jest.mocked(usePublicDashboardMeta)).toHaveBeenCalledWith('dash-1', {
enabled: true,
});
});
it('skips the lock permission check on a read-only mount', () => {
renderToolbar({ readOnly: true });
expect(jest.mocked(useDashboardLockPermission)).toHaveBeenCalledWith(
expect.objectContaining({ enabled: false }),
);
});
it('drops the title row and actions the host hides, and their requests', () => {
renderToolbar({
readOnly: true,
controls: { title: false, dashboardActions: false },
});
expect(screen.queryByTestId('dashboard-info')).not.toBeInTheDocument();
expect(screen.queryByTestId('dashboard-actions')).not.toBeInTheDocument();
expect(jest.mocked(usePublicDashboardMeta)).toHaveBeenCalledWith('dash-1', {
enabled: false,
});
});
it('hides the time range and keeps the variables bar mounted but hidden', () => {
renderToolbar({
controls: { toolbar: { timeRange: false, variables: false } },
});
expect(screen.queryByTestId('time-selection')).not.toBeInTheDocument();
expect(screen.getByTestId('variables-bar')).not.toBeVisible();
});
});

View File

@@ -17,7 +17,6 @@ import { getAbsoluteUrl } from 'utils/basePath';
import { useCreatePanel } from '../hooks/useCreatePanel';
import { useOptimisticPatch } from '../hooks/useOptimisticPatch';
import { useDashboardControlGroup } from '../controls/useDashboardControlGroup';
import { usePublicDashboardMeta } from '../DashboardSettings/PublicDashboard/usePublicDashboardMeta';
import PanelTypeSelectionModal from '../PanelsAndSectionsLayout/Panel/PanelTypeSelectionModal/PanelTypeSelectionModal';
import DashboardActions from './DashboardActions/DashboardActions';
@@ -57,11 +56,6 @@ function DashboardPageToolbar(props: DashboardPageToolbarProps): JSX.Element {
[dashboard.tags],
);
const showTitle = useDashboardControlGroup('title');
const showActions = useDashboardControlGroup('dashboardActions');
const showToolbar = useDashboardControlGroup('toolbar');
const hasTitleRow = Object.values(showTitle).some(Boolean);
const hasActions = Object.values(showActions).some(Boolean);
const { showErrorModal } = useErrorModal();
const { patchAsync } = useOptimisticPatch();
const {
@@ -77,13 +71,10 @@ function DashboardPageToolbar(props: DashboardPageToolbarProps): JSX.Element {
useDashboardLockPermission({
dashboardId: id,
source: dashboard.source,
enabled: showTitle.lock || showActions.lock,
});
// Public-sharing meta (deduped react-query read); drives the header globe.
const { isPublic, publicMeta } = usePublicDashboardMeta(id, {
enabled: showTitle.publicBadge,
});
const { isPublic, publicMeta } = usePublicDashboardMeta(id);
const publicUrl = getAbsoluteUrl(publicMeta?.publicPath ?? '');
// Shared with the list's row menu — it owns the API call, the toast and the
@@ -164,66 +155,48 @@ function DashboardPageToolbar(props: DashboardPageToolbarProps): JSX.Element {
return (
<section className={styles.dashboardPageToolbarContainer}>
{(hasTitleRow || hasActions) && (
<div className={styles.dashboardInfoWithActions}>
{hasTitleRow && (
<DashboardInfo
title={title}
image={image}
tags={tags}
description={description}
isPublicDashboard={isPublic}
publicUrl={publicUrl}
isDashboardLocked={isDashboardLocked}
showLockToggle={showLockToggle}
onToggleLock={
canToggleLock
? (): void => handleLockDashboardToggle('header')
: undefined
}
lockDisabledTooltip={lockDisabledTooltip}
isEditing={isEditing}
draft={draft}
onDraftChange={setDraft}
onStartEdit={startEdit}
onCommit={commit}
onCancel={cancel}
/>
)}
{hasActions && (
<DashboardActions
title={title}
dashboard={dashboard}
handle={handle}
isDashboardLocked={isDashboardLocked}
onAddPanel={onAddPanel}
onLockToggle={(): void => handleLockDashboardToggle('menu')}
onOpenRename={startEdit}
/>
)}
</div>
)}
<div className={styles.dashboardInfoWithActions}>
<DashboardInfo
title={title}
image={image}
tags={tags}
description={description}
isPublicDashboard={isPublic}
publicUrl={publicUrl}
isDashboardLocked={isDashboardLocked}
showLockToggle={showLockToggle}
onToggleLock={
canToggleLock
? (): void => handleLockDashboardToggle('header')
: undefined
}
lockDisabledTooltip={lockDisabledTooltip}
isEditing={isEditing}
draft={draft}
onDraftChange={setDraft}
onStartEdit={startEdit}
onCommit={commit}
onCancel={cancel}
/>
<DashboardActions
title={title}
dashboard={dashboard}
handle={handle}
isDashboardLocked={isDashboardLocked}
onAddPanel={onAddPanel}
onLockToggle={(): void => handleLockDashboardToggle('menu')}
onOpenRename={startEdit}
/>
</div>
{/* Row 2: the time selector floats top-right (declared first so the
variables bar's content wraps around it); the variables bar
collapses to one line and, when expanded, wraps full-width under it. */}
<div className={styles.toolbarRow}>
{showToolbar.timeRange && (
<div className={styles.timeCluster}>
<DateTimeSelectionV2
showAutoRefresh={showToolbar.autoRefresh}
hideShareModal
/>
</div>
)}
{showToolbar.variables ? (
<VariablesBar dashboard={dashboard} />
) : (
// Still mounted: the selectors seed and auto-select the values panels query with.
<div hidden>
<VariablesBar dashboard={dashboard} />
</div>
)}
<div className={styles.timeCluster}>
<DateTimeSelectionV2 showAutoRefresh hideShareModal />
</div>
<VariablesBar dashboard={dashboard} />
</div>
<PanelTypeSelectionModal
open={isPickerOpen}

View File

@@ -26,13 +26,9 @@ const PUBLIC_META_STALE_TIME = 5 * 60 * 1000;
*/
export function usePublicDashboardMeta(
dashboardId: string,
options?: { enabled?: boolean },
): UsePublicDashboardMetaReturn {
const { isCloudUser, isEnterpriseSelfHostedUser } = useGetTenantLicense();
const enabled =
(options?.enabled ?? true) &&
!!dashboardId &&
(isCloudUser || isEnterpriseSelfHostedUser);
const enabled = !!dashboardId && (isCloudUser || isEnterpriseSelfHostedUser);
const { data, isLoading, isFetching, error, refetch } = useGetPublicDashboard(
{ id: dashboardId },

View File

@@ -2,17 +2,33 @@ import { renderHook } from '@testing-library/react';
import { useContextLinkVariables } from '../useContextLinkVariables';
const mockUseDashboardVariableNames = jest.fn();
const mockUseGetDashboardV2 = jest.fn();
const mockUseQueryBuilder = jest.fn();
jest.mock(
'pages/DashboardPage/DashboardContainer/store/useDashboardStore',
() => ({
useDashboardStore: (
selector: (s: { dashboardId: string }) => unknown,
): unknown => selector({ dashboardId: 'dash-1' }),
}),
);
jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
useQueryBuilder: (): unknown => mockUseQueryBuilder(),
}));
jest.mock('api/generated/services/dashboard', () => ({
useGetDashboardV2: (): unknown => mockUseGetDashboardV2(),
}));
// dtoToFormModel is exercised by its own suite; here we only need it to surface a name.
jest.mock(
'pages/DashboardPage/DashboardContainer/hooks/useDashboardVariableNames',
'pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/variableAdapters',
() => ({
useDashboardVariableNames: (): unknown => mockUseDashboardVariableNames(),
dtoToFormModel: (dto: { name: string }): { name: string } => ({
name: dto.name,
}),
}),
);
@@ -29,7 +45,11 @@ describe('useContextLinkVariables', () => {
},
},
});
mockUseDashboardVariableNames.mockReturnValue(['region', 'tier']);
mockUseGetDashboardV2.mockReturnValue({
data: {
data: { spec: { variables: [{ name: 'region' }, { name: 'tier' }] } },
},
});
});
it('orders globals, then _prefixed query fields (deduped), then dashboard vars', () => {
@@ -49,7 +69,9 @@ describe('useContextLinkVariables', () => {
mockUseQueryBuilder.mockReturnValue({
currentQuery: { builder: { queryData: [] } },
});
mockUseDashboardVariableNames.mockReturnValue([]);
// Loaded dashboard with no variables — useDashboardFetchRequired guarantees the
// dashboard is present, so the empty case is an empty spec, not `undefined`.
mockUseGetDashboardV2.mockReturnValue({ data: { data: { spec: {} } } });
const { result } = renderHook(() => useContextLinkVariables());

View File

@@ -10,7 +10,6 @@ import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';
import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import type { DashboardSection } from '../../../../utils';
import { useDashboardStore } from '../../../../store/useDashboardStore';
import { usePanelActionItems } from '../usePanelActionItems';
/** Keys of the disabled items, in order. */
@@ -495,43 +494,4 @@ describe('usePanelActionItems', () => {
click(actionRow(result.current.items, 'create-alert'));
expect(mockCreateAlert).toHaveBeenCalledWith(mockPanel, 'panel-1');
});
describe('host controls', () => {
afterEach(() => {
useDashboardStore
.getState()
.setEditContext({ dashboardId: '', refetch: jest.fn() });
});
it('drops every writing action on a read-only mount', () => {
useDashboardStore.getState().setEditContext({
dashboardId: 'dash-1',
refetch: jest.fn(),
readOnly: true,
});
const { result } = renderHook(() => usePanelActionItems(baseArgs));
expect(itemKeys(result.current)).toStrictEqual([
'view-panel',
'separator',
'download',
'create-alert',
]);
});
it('drops the actions the host hides', () => {
useDashboardStore.getState().setEditContext({
dashboardId: 'dash-1',
refetch: jest.fn(),
controls: { panelActions: { createAlert: false, delete: false } },
});
const { result } = renderHook(() => usePanelActionItems(baseArgs));
expect(itemKeys(result.current)).not.toContain('create-alert');
expect(itemKeys(result.current)).not.toContain('delete-panel');
expect(itemKeys(result.current)).toContain('edit-panel');
});
});
});

View File

@@ -29,7 +29,6 @@ import type { AuthZDropdownItemType } from 'lib/authz/components/AuthZDropdown/t
import { blockedBy } from 'lib/authz/components/AuthZDropdown/utils';
import { getBlockedPanelActions } from '../utils/getBlockedPanelActions';
import { useDashboardEditContext } from '../../../hooks/useDashboardEditContext';
import { useDashboardControlGroup } from '../../../controls/useDashboardControlGroup';
// Stable fallback so renders without layout context don't churn the mutation
// hooks' deps (a fresh [] each render would re-create their callbacks).
@@ -67,7 +66,6 @@ export function usePanelActionItems({
const blocked = useMemo(() => getBlockedPanelActions(panel), [panel]);
const { isEditable, editChecks, editDisabledTooltip } =
useDashboardEditContext();
const show = useDashboardControlGroup('panelActions');
const openPanelEditor = useOpenPanelEditor();
const createAlert = useCreateAlertFromPanel();
const { openView } = useViewPanel();
@@ -105,7 +103,7 @@ export function usePanelActionItems({
const editGate = { checks: editChecks, ...blockedBy(editDisabledTooltip) };
const panelGroup: AuthZDropdownItemType[] = [];
if (show.view && panelCapabilities.view) {
if (panelCapabilities.view) {
panelGroup.push({
type: 'item',
value: 'view-panel',
@@ -114,7 +112,7 @@ export function usePanelActionItems({
onClick: (): void => openView(panelId, panel),
});
}
if (show.edit && panelCapabilities.edit) {
if (panelCapabilities.edit) {
panelGroup.push({
type: 'item',
value: 'edit-panel',
@@ -124,7 +122,7 @@ export function usePanelActionItems({
onClick: (): void => openPanelEditor(panelId, { panel }),
});
}
if (show.clone && panelCapabilities.clone) {
if (panelCapabilities.clone) {
// Needs section context to place the copy; disabled without it.
panelGroup.push({
type: 'item',
@@ -144,13 +142,13 @@ export function usePanelActionItems({
}
const dataGroup: AuthZDropdownItemType[] = [];
if (show.download && downloadItem) {
if (downloadItem) {
dataGroup.push(downloadItem);
}
// Create Alerts opens a new tab and never mutates the dashboard, so —
// unlike edit/clone — it isn't gated on editability (V1 parity).
if (show.createAlert && panelCapabilities.createAlert) {
if (panelCapabilities.createAlert) {
dataGroup.push({
type: 'item',
value: 'create-alert',
@@ -161,9 +159,8 @@ export function usePanelActionItems({
});
}
const moveGroup: AuthZDropdownItemType[] = !show.move
? []
: isEditable && panelActions
const moveGroup: AuthZDropdownItemType[] =
isEditable && panelActions
? buildMoveItems({
sections,
currentLayoutIndex: panelActions.currentLayoutIndex,
@@ -180,19 +177,17 @@ export function usePanelActionItems({
},
];
const deleteGroup: AuthZDropdownItemType[] = !show.delete
? []
: [
{
type: 'item',
value: 'delete-panel',
label: 'Delete panel',
prefix: <Trash2 size={14} />,
danger: true,
...editGate,
onClick: (): void => requestDelete(),
},
];
const deleteGroup: AuthZDropdownItemType[] = [
{
type: 'item',
value: 'delete-panel',
label: 'Delete panel',
prefix: <Trash2 size={14} />,
danger: true,
...editGate,
onClick: (): void => requestDelete(),
},
];
return [panelGroup, dataGroup, moveGroup, deleteGroup]
.filter((group) => group.length > 0)
@@ -202,7 +197,6 @@ export function usePanelActionItems({
: [{ type: 'separator', value: `separator-${index}` }, ...group],
);
}, [
show,
isEditable,
editChecks,
editDisabledTooltip,

View File

@@ -14,7 +14,6 @@ import { EQueryType } from 'types/common/dashboard';
import styles from './ViewPanelModal.module.scss';
import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';
import { useDashboardEditContext } from '../../../hooks/useDashboardEditContext';
import { useDashboardControl } from '../../../controls/useDashboardControl';
interface ViewPanelModalHeaderBaseProps {
onSwitchToEdit: () => void;
@@ -71,7 +70,6 @@ function ViewPanelModalHeader(props: ViewPanelModalHeaderProps): JSX.Element {
editChecks,
editDisabledTooltip,
} = useDashboardEditContext();
const showSwitchToEdit = useDashboardControl('viewModal.switchToEdit');
// Same capabilities-guarded options as the editor's PanelTypeSwitcher, so the two
// selectors disable the same kinds (e.g. List under PromQL, metrics-only kinds).
const panelTypeItems = usePanelTypeSelectItems({
@@ -89,22 +87,20 @@ function ViewPanelModalHeader(props: ViewPanelModalHeaderProps): JSX.Element {
onChange={onChangePanelKind}
/>
</div>
{showSwitchToEdit && (
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
<Button
disabledTooltip={undefined}
size="md"
variant="outlined"
color="secondary"
prefix={<PenLine />}
disabled={!canSwitchToEdit}
onClick={onSwitchToEdit}
testId="view-panel-switch-to-edit"
>
Switch to Edit Mode
</Button>
</AuthZTooltip>
)}
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
<Button
disabledTooltip={undefined}
size="md"
variant="outlined"
color="secondary"
prefix={<PenLine />}
disabled={!canSwitchToEdit}
onClick={onSwitchToEdit}
testId="view-panel-switch-to-edit"
>
Switch to Edit Mode
</Button>
</AuthZTooltip>
{query && (
<Button
size="md"

View File

@@ -1,71 +0,0 @@
import { render, screen } from 'tests/test-utils';
import { useDashboardStore } from '../../../../store/useDashboardStore';
import ViewPanelModalHeader from '../ViewPanelModalHeader';
import type { DashboardControlsInput } from '../../../../controls/types';
jest.mock(
'pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext',
() => ({
useDashboardEditContext: (): unknown => ({
isEditable: true,
editChecks: [],
editDisabledTooltip: '',
}),
}),
);
jest.mock(
'pages/DashboardPage/DashboardContainer/PanelEditor/ConfigPane/PanelTypeSwitcher/usePanelTypeSelectItems',
() => ({ usePanelTypeSelectItems: (): unknown[] => [] }),
);
function renderHeader(
readOnly: boolean,
controls?: DashboardControlsInput,
): void {
useDashboardStore.getState().setEditContext({
dashboardId: 'dash-1',
refetch: jest.fn(),
readOnly,
controls,
});
render(
<ViewPanelModalHeader
mode="static"
panelKind="signoz/TimeSeriesPanel"
onChangePanelKind={jest.fn()}
onSwitchToEdit={jest.fn()}
/>,
);
}
describe('ViewPanelModalHeader - controls', () => {
afterEach(() => {
useDashboardStore
.getState()
.setEditContext({ dashboardId: '', refetch: jest.fn() });
});
it('offers Switch to Edit Mode on an editable mount', () => {
renderHeader(false);
expect(screen.getByTestId('view-panel-switch-to-edit')).toBeInTheDocument();
});
it('hides Switch to Edit Mode on a read-only mount', () => {
renderHeader(true);
expect(screen.getByTestId('view-panel-type-selector')).toBeInTheDocument();
expect(
screen.queryByTestId('view-panel-switch-to-edit'),
).not.toBeInTheDocument();
});
it('hides Switch to Edit Mode when the host hides it', () => {
renderHeader(false, { viewModal: false });
expect(
screen.queryByTestId('view-panel-switch-to-edit'),
).not.toBeInTheDocument();
});
});

View File

@@ -24,16 +24,11 @@ const mockPatchAsync = jest.fn().mockResolvedValue(undefined);
const DYNAMIC_KIND = 'signoz/DynamicVariable';
const QUERY_KIND = 'signoz/QueryVariable';
jest.mock(
'pages/DashboardPage/DashboardContainer/hooks/useDashboardFetchRequired',
() => ({
useDashboardFetchRequired: (): unknown => ({
dashboard: { spec: { variables: mockVariables } },
variables: mockVariables,
refetch: jest.fn(),
}),
jest.mock('api/generated/services/dashboard', () => ({
useGetDashboardV2: (): unknown => ({
data: { data: { spec: { variables: mockVariables } } },
}),
);
}));
jest.mock(
'pages/DashboardPage/DashboardContainer/hooks/useOptimisticPatch',
() => ({

View File

@@ -1,51 +0,0 @@
import { safeNavigateMock } from '__tests__/safeNavigateMock';
import { AllTheProviders, renderHook } from 'tests/test-utils';
import { CHARTS_ONLY } from '../../../../controls/presets';
import type { DashboardControlsInput } from '../../../../controls/types';
import { useDashboardStore } from '../../../../store/useDashboardStore';
import { usePanelInteractions } from '../usePanelInteractions';
function dragSelect(controls?: DashboardControlsInput): void {
useDashboardStore
.getState()
.setEditContext({ dashboardId: 'd1', refetch: jest.fn(), controls });
const { result } = renderHook(() => usePanelInteractions(), {
wrapper: AllTheProviders,
});
result.current.onDragSelect(1_000, 2_000);
}
describe('usePanelInteractions drag-to-zoom', () => {
afterEach(() => {
useDashboardStore
.getState()
.setEditContext({ dashboardId: '', refetch: jest.fn() });
});
it('writes the dragged range to the URL', () => {
dragSelect();
expect(safeNavigateMock).toHaveBeenCalledWith(
expect.stringContaining('startTime=1000&endTime=2000'),
);
});
it('does nothing when the host turns zoom off', () => {
dragSelect({ panelActions: { zoom: false } });
expect(safeNavigateMock).not.toHaveBeenCalled();
});
it('still zooms when the host hides the toolbar but leaves zoom on', () => {
dragSelect({ toolbar: false });
expect(safeNavigateMock).toHaveBeenCalled();
});
it('still zooms on a charts-only mount', () => {
dragSelect(CHARTS_ONLY);
expect(safeNavigateMock).toHaveBeenCalled();
});
});

View File

@@ -33,7 +33,6 @@ import { useDrilldownCoordinates } from './useDrilldownCoordinates';
import { useDrilldownDashboardVariables } from './useDrilldownDashboardVariables';
import { useDrilldownFilter } from './useDrilldownFilter';
import { useResolvedDrilldownQuery } from './useResolvedDrilldownQuery';
import { useDashboardControl } from 'pages/DashboardPage/DashboardContainer/controls/useDashboardControl';
import { useViewPanel } from './useViewPanel';
/** Which menu the popover shows; extend as submenus are added (e.g. dashboard variables). */
@@ -85,14 +84,12 @@ export function useDrilldown(
// Drilldown only for builder-authored panels with a query to drill into (PromQL /
// ClickHouse have no builder context to refine).
const showDrilldown = useDashboardControl('panelActions.drilldown');
const enableDrillDown = useMemo(
() =>
showDrilldown &&
getPanelDefinition(kind).actions.drilldown &&
getPanelQueryType(panel) === EQueryType.QUERY_BUILDER &&
getBuilderQueries(queries).length > 0,
[showDrilldown, kind, panel, queries],
[kind, panel, queries],
);
const v1Query = useMemo(

View File

@@ -13,7 +13,6 @@ import useUrlQuery from 'hooks/useUrlQuery';
import logEvent from 'api/common/logEvent';
import { DashboardDetailEvents } from 'pages/DashboardPage/constants/events';
import { UpdateTimeInterval } from 'store/actions';
import { useDashboardControl } from 'pages/DashboardPage/DashboardContainer/controls/useDashboardControl';
export interface PanelInteractions {
/** Drag-select a chart range → write it to the URL + global time so every panel re-fetches the same range. */
@@ -44,12 +43,8 @@ export function usePanelInteractions(): PanelInteractions {
[syncMode, syncFilterMode, dashboardId],
);
const canZoom = useDashboardControl('panelActions.zoom');
const onDragSelect = useCallback(
(start: number, end: number): void => {
if (!canZoom) {
return;
}
const startTimestamp = Math.trunc(start);
const endTimestamp = Math.trunc(end);
@@ -62,7 +57,7 @@ export function usePanelInteractions(): PanelInteractions {
void logEvent(DashboardDetailEvents.PanelZoomed, { context: 'panel' });
}
},
[canZoom, dispatch, pathname, safeNavigate, urlQuery],
[dispatch, pathname, safeNavigate, urlQuery],
);
return { onDragSelect, dashboardPreference };

View File

@@ -8,12 +8,12 @@ import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';
import { useCreatePanel } from '../../../hooks/useCreatePanel';
import type { DashboardSection } from '../../../utils';
import PanelTypeSelectionModal from '../../Panel/PanelTypeSelectionModal/PanelTypeSelectionModal';
import { useCloneSection } from '../hooks/useCloneSection';
import { useDeleteSection } from '../hooks/useDeleteSection';
import { usePanelPickerHighlight } from '../hooks/usePanelPickerHighlight';
import { usePanelPickerReveal } from '../hooks/usePanelPickerReveal';
import { useRenameSection } from '../hooks/useRenameSection';
import { useScrollIntoView } from '../hooks/useScrollIntoView';
import { useSectionHeaderActions } from '../hooks/useSectionHeaderActions';
import { useToggleSectionCollapse } from '../hooks/useToggleSectionCollapse';
import SectionTitleModal from '../SectionTitleModal';
import SectionGrid from '../SectionGrid/SectionGrid';
@@ -66,14 +66,7 @@ function Section({ section, sections, dragHandle }: SectionProps): JSX.Element {
setIsDeleteOpen(false);
}, [deleteSection]);
const openRename = useCallback((): void => setIsRenaming(true), []);
const openDelete = useCallback((): void => setIsDeleteOpen(true), []);
const actions = useSectionHeaderActions({
section,
openPicker,
openRename,
openDelete,
});
const cloneSection = useCloneSection();
const sectionRef = useRef<HTMLDivElement>(null);
useScrollIntoView(section.id, sectionRef);
@@ -123,30 +116,35 @@ function Section({ section, sections, dragHandle }: SectionProps): JSX.Element {
dragHandle={dragHandle}
disabledChecks={editChecks}
disabledTooltip={editDisabledTooltip}
actions={actions}
actions={{
onRename: (): void => setIsRenaming(true),
onAddPanel: (): void => openPicker(section.layoutIndex),
onCloneSection: (): void => void cloneSection(section),
onDeleteSection: (): void => setIsDeleteOpen(true),
}}
/>
{open &&
(section.items.length > 0 || pickerTarget
? grid
: actions.onAddPanel && (
<div className={styles.emptySection}>
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
<Button
size="md"
type="button"
variant="dashed"
color="secondary"
prefix={<Plus size="md" />}
onClick={
isEditable ? (): void => openPicker(section.layoutIndex) : undefined
}
testId={`section-add-panel-${section.id}`}
>
New Panel
</Button>
</AuthZTooltip>
</div>
))}
(section.items.length > 0 || pickerTarget ? (
grid
) : (
<div className={styles.emptySection}>
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
<Button
size="md"
type="button"
variant="dashed"
color="secondary"
prefix={<Plus size="md" />}
onClick={
isEditable ? (): void => openPicker(section.layoutIndex) : undefined
}
testId={`section-add-panel-${section.id}`}
>
New Panel
</Button>
</AuthZTooltip>
</div>
))}
<SectionTitleModal
open={isRenaming}
heading="Rename section"

View File

@@ -25,7 +25,7 @@ function SectionActionsMenu({
onRename,
onCloneSection,
onDeleteSection,
}: SectionActionsMenuProps): JSX.Element | null {
}: SectionActionsMenuProps): JSX.Element {
const items = useMemo<AuthZDropdownItemType[]>(() => {
const gate = { checks: disabledChecks, ...blockedBy(disabledTooltip) };
const result: AuthZDropdownItemType[] = [];
@@ -83,10 +83,6 @@ function SectionActionsMenu({
onDeleteSection,
]);
if (items.length === 0) {
return null;
}
return (
<AuthZDropdown
items={items}

View File

@@ -16,12 +16,12 @@ export interface SectionDragHandle {
setActivatorNodeRef: (element: HTMLElement | null) => void;
}
/** Section actions; an absent one isn't offered. */
/** Editable-mode section actions — present together or not at all. */
export interface SectionHeaderActions {
onRename?: () => void;
onAddPanel?: () => void;
onCloneSection?: () => void;
onDeleteSection?: () => void;
onRename: () => void;
onAddPanel: () => void;
onCloneSection: () => void;
onDeleteSection: () => void;
}
interface SectionHeaderProps {

View File

@@ -1,36 +0,0 @@
import { useMemo } from 'react';
import { useDashboardControlGroup } from '../../../controls/useDashboardControlGroup';
import type { DashboardSection } from '../../../utils';
import type { SectionHeaderActions } from '../SectionHeader/SectionHeader';
import { useCloneSection } from './useCloneSection';
/** The section menu's actions, minus the ones the host hides (`sectionActions`). */
export function useSectionHeaderActions({
section,
openPicker,
openRename,
openDelete,
}: {
section: DashboardSection;
openPicker: (layoutIndex: number) => void;
openRename: () => void;
openDelete: () => void;
}): SectionHeaderActions {
const show = useDashboardControlGroup('sectionActions');
const cloneSection = useCloneSection();
return useMemo(
() => ({
onRename: show.rename ? openRename : undefined,
onAddPanel: show.addPanel
? (): void => openPicker(section.layoutIndex)
: undefined,
onCloneSection: show.clone
? (): void => void cloneSection(section)
: undefined,
onDeleteSection: show.delete ? openDelete : undefined,
}),
[show, openRename, openPicker, section, cloneSection, openDelete],
);
}

View File

@@ -16,7 +16,6 @@ import { resolveDefaultSelection } from './utils/resolveVariableSelection';
import VariableSelector from './components/VariableSelector/VariableSelector';
import styles from './VariablesBar.module.scss';
import { useDashboardEditContext } from '../hooks/useDashboardEditContext';
import { useDashboardControl } from '../controls/useDashboardControl';
interface VariablesBarProps {
dashboard: DashboardtypesGettableDashboardV2DTO;
@@ -40,7 +39,6 @@ function VariablesBar({ dashboard }: VariablesBarProps): JSX.Element | null {
// Persisted per dashboard so the full/collapsed view survives reloads.
const expanded = useDashboardStore(selectVariablesExpanded(dashboardId));
const setVariablesExpanded = useDashboardStore((s) => s.setVariablesExpanded);
const showAddVariable = useDashboardControl('toolbar.addVariable');
const { containerRef, visibleCount, overflowCount } = useInlineOverflowCount({
itemCount: variables.length,
gap: 8,
@@ -51,7 +49,7 @@ function VariablesBar({ dashboard }: VariablesBarProps): JSX.Element | null {
// Editors can add a variable even before any exist; viewers with no variables
// have nothing to show.
if (variables.length === 0 && !(isEditable && showAddVariable)) {
if (variables.length === 0 && !isEditable) {
return null;
}
@@ -133,15 +131,13 @@ function VariablesBar({ dashboard }: VariablesBarProps): JSX.Element | null {
{/* After the more/less trigger, in every state. Kept inline (not block)
so the row still flows under the floated time selector, and always
mounted so measuring never toggles it. */}
{showAddVariable && (
<span className={styles.addSlot}>
<AddVariableIcon
checks={editChecks}
disabledTooltip={editDisabledTooltip}
isEditable={isEditable}
/>
</span>
)}
<span className={styles.addSlot}>
<AddVariableIcon
checks={editChecks}
disabledTooltip={editDisabledTooltip}
isEditable={isEditable}
/>
</span>
</div>
</div>
);

View File

@@ -1,72 +0,0 @@
import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';
import { render, screen } from 'tests/test-utils';
import { useDashboardStore } from '../../store/useDashboardStore';
import VariablesBar from '../VariablesBar';
import type { DashboardControlsInput } from '../../controls/types';
const dashboard = {
id: 'dash-1',
spec: { display: { name: 'D' }, panels: {}, layouts: [], variables: [] },
} as unknown as DashboardtypesGettableDashboardV2DTO;
jest.mock('../../hooks/useDashboardEditContext', () => ({
useDashboardEditContext: (): unknown => ({
isEditable: false,
editChecks: [],
editDisabledTooltip: '',
}),
}));
jest.mock('../hooks/useVariableSelection', () => ({
useVariableSelection: (): unknown => ({
variables: [{ name: 'env' }],
selection: {},
setSelection: jest.fn(),
autoSelect: jest.fn(),
}),
}));
jest.mock('../components/VariableSelector/VariableSelector', () => ({
__esModule: true,
default: (): JSX.Element => <div data-testid="variable-selector" />,
}));
function renderBar(readOnly: boolean, controls?: DashboardControlsInput): void {
useDashboardStore.getState().setEditContext({
dashboardId: 'dash-1',
refetch: jest.fn(),
readOnly,
controls,
});
render(<VariablesBar dashboard={dashboard} />);
}
describe('VariablesBar - controls', () => {
afterEach(() => {
useDashboardStore
.getState()
.setEditContext({ dashboardId: '', refetch: jest.fn() });
});
it('offers the add-variable trigger, disabled, to a viewer', () => {
renderBar(false);
expect(screen.getByTestId('dashboard-variables-add')).toBeInTheDocument();
});
it('renders the selectors but no add-variable trigger', () => {
renderBar(true);
expect(screen.getByTestId('variable-selector')).toBeInTheDocument();
expect(
screen.queryByTestId('dashboard-variables-add'),
).not.toBeInTheDocument();
});
it('renders no add-variable trigger when the host hides it', () => {
renderBar(false, { toolbar: { addVariable: false } });
expect(
screen.queryByTestId('dashboard-variables-add'),
).not.toBeInTheDocument();
});
});

View File

@@ -1,90 +0,0 @@
import { useQuery } from 'react-query';
import type {
DashboardtypesGettableDashboardV2DTO,
GetDashboardV2200,
} from 'api/generated/services/sigNoz.schemas';
import { render, screen, waitFor } from 'tests/test-utils';
import { dashboardResponse } from '../../stories/__story_mockdata__/dashboard';
import { DEFAULT_CONTROLS } from '../controls/dashboardControls';
import type { DashboardControlsInput } from '../controls/types';
import DashboardContainer from '../index';
import type { DashboardQuerySource } from '../store/slices/editContextSlice';
const QUERY_KEY = ['lockdown-dashboard'];
const ALL_CONTROLS_OFF = Object.fromEntries(
Object.keys(DEFAULT_CONTROLS).map((group) => [group, false]),
) as DashboardControlsInput;
const select = (
response: GetDashboardV2200,
): DashboardtypesGettableDashboardV2DTO => response.data;
const SOURCE: DashboardQuerySource = { queryKey: QUERY_KEY, select };
/**
* Interactive elements a host can't turn off: they read, never write, and the
* page is unusable without them. Anything else here must be a control.
*/
const ALLOWED_TEST_ID_PREFIXES = [
// Collapses a section in this browser only; it also carries the section title.
'dashboard-section-toggle-',
];
const INTERACTIVE =
'button, a[href], input, select, textarea, [role="button"], [role="menuitem"], [role="combobox"], [role="switch"], [role="checkbox"]';
function LockdownHost(): JSX.Element | null {
const { data } = useQuery(QUERY_KEY, () =>
dashboardResponse({
panels: 3,
sectioned: true,
variables: ['custom'],
locked: false,
}),
);
if (!data) {
return null;
}
return (
<DashboardContainer
dashboard={data.data}
refetch={jest.fn()}
source={SOURCE}
readOnly
controls={ALL_CONTROLS_OFF}
/>
);
}
function visibleInteractive(): Element[] {
return Array.from(document.body.querySelectorAll(INTERACTIVE)).filter(
(element) => !element.closest('[hidden]'),
);
}
function describeElement(element: Element): string {
return (
element.getAttribute('data-testid') ??
`<${element.tagName.toLowerCase()} aria-label="${element.getAttribute('aria-label') ?? ''}">${element.textContent?.trim().slice(0, 40) ?? ''}`
);
}
describe('DashboardContainer lockdown', () => {
// A control a host can't switch off, or one read-only doesn't remove, fails here.
it('renders nothing interactive with every control off on a read-only mount', async () => {
render(<LockdownHost />);
await waitFor(() =>
expect(screen.getAllByTestId(/^panel-/).length).toBeGreaterThan(0),
);
const leaked = visibleInteractive()
.map(describeElement)
.filter(
(id) => !ALLOWED_TEST_ID_PREFIXES.some((prefix) => id.startsWith(prefix)),
);
expect(leaked).toStrictEqual([]);
});
});

View File

@@ -1,7 +1,6 @@
import { memo } from 'react';
import HeaderRightSection from 'components/HeaderRightSection/HeaderRightSection';
import { useDashboardControlGroup } from '../../controls/useDashboardControlGroup';
import DashboardPageBreadcrumbs from './DashboardPageBreadcrumbs';
import { useShareVariablesOption } from './useShareVariablesOption';
@@ -17,16 +16,13 @@ function DashboardPageHeader({
image,
}: DashboardPageHeaderProps): JSX.Element {
const shareVariablesOption = useShareVariablesOption();
const show = useDashboardControlGroup('header');
return (
<div className={styles.dashboardPageHeader}>
{show.breadcrumbs && (
<DashboardPageBreadcrumbs title={title} image={image} />
)}
<DashboardPageBreadcrumbs title={title} image={image} />
<HeaderRightSection
enableAnnouncements={false}
enableShare={show.share}
enableFeedback={show.feedback}
enableShare
enableFeedback
shareModalExtraOption={shareVariablesOption}
/>
</div>

View File

@@ -1,57 +0,0 @@
import {
CONTROL_WRITES,
DEFAULT_CONTROLS,
isControlVisible,
resolveControls,
} from '../dashboardControls';
import type { DashboardControlId } from '../types';
const ALL_IDS = Object.keys(CONTROL_WRITES) as DashboardControlId[];
describe('resolveControls', () => {
it('shows every control when the host passes nothing', () => {
expect(resolveControls(undefined, false)).toStrictEqual(DEFAULT_CONTROLS);
});
it('hides a whole group from one boolean', () => {
const controls = resolveControls({ header: false }, false);
expect(controls.header).toStrictEqual({
breadcrumbs: false,
share: false,
feedback: false,
});
expect(controls.title.name).toBe(true);
});
it('hides single items and keeps the rest of the group', () => {
const controls = resolveControls(
{ panelActions: { createAlert: false } },
false,
);
expect(controls.panelActions.createAlert).toBe(false);
expect(controls.panelActions.download).toBe(true);
});
it('hides every writing control on a read-only mount, whatever the host asked', () => {
const controls = resolveControls(
{ dashboardActions: true, panelActions: { edit: true } },
true,
);
ALL_IDS.forEach((id) => {
expect([id, isControlVisible(controls, id)]).toStrictEqual([
id,
!CONTROL_WRITES[id],
]);
});
});
it('still lets the host hide non-writing controls on a read-only mount', () => {
const controls = resolveControls({ panelActions: { download: false } }, true);
expect(controls.panelActions.download).toBe(false);
expect(controls.panelActions.view).toBe(true);
});
});

View File

@@ -1,48 +0,0 @@
import { resolveControls } from '../dashboardControls';
import { CHARTS_ONLY, EMBEDDED, withControls } from '../presets';
describe('withControls', () => {
it('adds an override group the preset leaves alone', () => {
expect(
withControls(EMBEDDED, { toolbar: { autoRefresh: false } }),
).toStrictEqual({
header: false,
title: false,
dashboardActions: false,
toolbar: { autoRefresh: false },
});
});
it('turns single items back on inside a group the preset hides', () => {
const merged = withControls(CHARTS_ONLY, { panelActions: { view: true } });
const controls = resolveControls(merged, false);
expect(controls.panelActions.view).toBe(true);
expect(controls.panelActions.download).toBe(false);
expect(controls.panelActions.drilldown).toBe(false);
});
it('lets a later whole-group boolean replace earlier items', () => {
expect(
withControls(
{ panelActions: { createAlert: false } },
{ panelActions: true },
),
).toStrictEqual({ panelActions: true });
});
it('lets later items win over earlier ones', () => {
expect(
withControls(
{ toolbar: { timeRange: false, autoRefresh: false } },
{ toolbar: { timeRange: true } },
),
).toStrictEqual({ toolbar: { timeRange: true, autoRefresh: false } });
});
it('cannot turn a writing control back on for a read-only mount', () => {
const merged = withControls(EMBEDDED, { dashboardActions: { delete: true } });
expect(resolveControls(merged, true).dashboardActions.delete).toBe(false);
});
});

View File

@@ -1,136 +0,0 @@
import type {
DashboardControlGroup,
DashboardControlId,
DashboardControls,
DashboardControlsInput,
} from './types';
export const DEFAULT_CONTROLS: DashboardControls = {
header: { breadcrumbs: true, share: true, feedback: true },
title: {
name: true,
description: true,
tags: true,
lock: true,
publicBadge: true,
},
toolbar: {
timeRange: true,
autoRefresh: true,
variables: true,
addVariable: true,
},
dashboardActions: {
fullscreen: true,
rename: true,
clone: true,
lock: true,
newSection: true,
delete: true,
configure: true,
json: true,
newPanel: true,
},
sectionActions: { addPanel: true, rename: true, clone: true, delete: true },
panelActions: {
view: true,
edit: true,
clone: true,
download: true,
createAlert: true,
move: true,
delete: true,
drilldown: true,
zoom: true,
},
viewModal: { switchToEdit: true },
};
/**
* Whether each control writes to the dashboard. A read-only mount hides every
* `true` here regardless of what the host asked for. Exhaustive, so a new
* control can't ship without deciding.
*/
export const CONTROL_WRITES: Record<DashboardControlId, boolean> = {
'header.breadcrumbs': false,
'header.share': false,
'header.feedback': false,
'title.name': false,
'title.description': false,
'title.tags': false,
'title.lock': true,
'title.publicBadge': false,
'toolbar.timeRange': false,
'toolbar.autoRefresh': false,
'toolbar.variables': false,
'toolbar.addVariable': true,
'dashboardActions.fullscreen': false,
'dashboardActions.rename': true,
'dashboardActions.clone': true,
'dashboardActions.lock': true,
'dashboardActions.newSection': true,
'dashboardActions.delete': true,
'dashboardActions.configure': true,
// Opens read-only on a non-editable mount.
'dashboardActions.json': false,
'dashboardActions.newPanel': true,
'sectionActions.addPanel': true,
'sectionActions.rename': true,
'sectionActions.clone': true,
'sectionActions.delete': true,
'panelActions.view': false,
'panelActions.edit': true,
'panelActions.clone': true,
'panelActions.download': false,
'panelActions.createAlert': false,
'panelActions.move': true,
'panelActions.delete': true,
'panelActions.drilldown': false,
'panelActions.zoom': false,
'viewModal.switchToEdit': true,
};
function resolveGroup<G extends DashboardControlGroup>(
group: G,
input: DashboardControlsInput | undefined,
readOnly: boolean,
): DashboardControls[G] {
const defaults: Record<string, boolean> = DEFAULT_CONTROLS[group];
const override = input?.[group] as
| boolean
| Partial<Record<string, boolean>>
| undefined;
const items = Object.keys(defaults).map((item): [string, boolean] => {
const requested =
typeof override === 'boolean'
? override
: (override?.[item] ?? defaults[item]);
const writes = CONTROL_WRITES[`${group}.${item}` as DashboardControlId];
return [item, requested && !(readOnly && writes)];
});
return Object.fromEntries(items) as DashboardControls[G];
}
/** Host input over the defaults, then every writing control off when read-only. */
export function resolveControls(
input: DashboardControlsInput | undefined,
readOnly: boolean,
): DashboardControls {
return {
header: resolveGroup('header', input, readOnly),
title: resolveGroup('title', input, readOnly),
toolbar: resolveGroup('toolbar', input, readOnly),
dashboardActions: resolveGroup('dashboardActions', input, readOnly),
sectionActions: resolveGroup('sectionActions', input, readOnly),
panelActions: resolveGroup('panelActions', input, readOnly),
viewModal: resolveGroup('viewModal', input, readOnly),
};
}
export function isControlVisible(
controls: DashboardControls,
id: DashboardControlId,
): boolean {
const [group, item] = id.split('.') as [DashboardControlGroup, string];
return (controls[group] as Record<string, boolean>)[item];
}

View File

@@ -1,74 +0,0 @@
import { DEFAULT_CONTROLS } from './dashboardControls';
import type {
DashboardControlGroup,
DashboardControls,
DashboardControlsInput,
} from './types';
/**
* The host page owns the header, the title row and the dashboard-level actions.
* Layout presets only: `readOnly` stays a separate switch, so no preset can turn
* a writing control back on.
*/
export const EMBEDDED: DashboardControlsInput = {
header: false,
title: false,
dashboardActions: false,
};
/** Embedded, and panels are just charts: no panel menu, no drilldown. Charts still zoom. */
export const CHARTS_ONLY: DashboardControlsInput = {
...EMBEDDED,
panelActions: {
view: false,
edit: false,
clone: false,
download: false,
createAlert: false,
move: false,
delete: false,
drilldown: false,
},
};
type GroupInput<G extends DashboardControlGroup> =
| boolean
| Partial<DashboardControls[G]>;
function mergeGroup<G extends DashboardControlGroup>(
group: G,
base: GroupInput<G> | undefined,
next: GroupInput<G> | undefined,
): GroupInput<G> | undefined {
if (next === undefined) {
return base;
}
if (typeof next === 'boolean' || base === undefined) {
return next;
}
// A whole-group boolean underneath expands to its items before the override.
const expanded: Partial<DashboardControls[G]> =
typeof base === 'boolean'
? (Object.fromEntries(
Object.keys(DEFAULT_CONTROLS[group]).map((item) => [item, base]),
) as Partial<DashboardControls[G]>)
: base;
return { ...expanded, ...next };
}
/** Merges presets and overrides; later inputs win, item by item. */
export function withControls(
...inputs: DashboardControlsInput[]
): DashboardControlsInput {
const groups = Object.keys(DEFAULT_CONTROLS) as DashboardControlGroup[];
return inputs.reduce<DashboardControlsInput>((merged, input) => {
const result: DashboardControlsInput = { ...merged };
groups.forEach((group) => {
const value = mergeGroup(group, merged[group], input[group]);
if (value !== undefined) {
(result as Record<string, unknown>)[group] = value;
}
});
return result;
}, {});
}

View File

@@ -1,53 +0,0 @@
import type { PanelActionId } from '../PanelsAndSectionsLayout/Panel/PanelActionsMenu/panelActionMeta';
/** Every control a host can show or hide, grouped by where it renders. */
export interface DashboardControls {
header: { breadcrumbs: boolean; share: boolean; feedback: boolean };
title: {
name: boolean;
description: boolean;
tags: boolean;
lock: boolean;
publicBadge: boolean;
};
toolbar: {
timeRange: boolean;
autoRefresh: boolean;
variables: boolean;
addVariable: boolean;
};
dashboardActions: {
fullscreen: boolean;
rename: boolean;
clone: boolean;
lock: boolean;
newSection: boolean;
delete: boolean;
configure: boolean;
json: boolean;
newPanel: boolean;
};
sectionActions: {
addPanel: boolean;
rename: boolean;
clone: boolean;
delete: boolean;
};
// Keyed by the panel menu's own ids, so a new panel action needs a control.
// `drilldown` (click) and `zoom` (drag-select a time range) act on the chart itself.
panelActions: Record<PanelActionId | 'drilldown' | 'zoom', boolean>;
viewModal: { switchToEdit: boolean };
}
export type DashboardControlGroup = keyof DashboardControls;
export type DashboardControlId = {
[
G in DashboardControlGroup
]: `${G}.${Extract<keyof DashboardControls[G], string>}`;
}[DashboardControlGroup];
/** A whole group as one boolean, or single items; omitted means shown. */
export type DashboardControlsInput = {
[G in DashboardControlGroup]?: boolean | Partial<DashboardControls[G]>;
};

View File

@@ -1,12 +0,0 @@
import { useDashboardStore } from '../store/useDashboardStore';
import { isControlVisible } from './dashboardControls';
import type { DashboardControlId } from './types';
/**
* Whether a control renders on this mount: the host's `controls`, with every
* writing control off when read-only. Lock and permission state stay with
* `useDashboardEditContext`, which decides disabled + reason.
*/
export function useDashboardControl(id: DashboardControlId): boolean {
return useDashboardStore((s) => isControlVisible(s.controls, id));
}

View File

@@ -1,9 +0,0 @@
import { useDashboardStore } from '../store/useDashboardStore';
import type { DashboardControlGroup, DashboardControls } from './types';
/** Every control in a group, resolved for this mount (see `useDashboardControl`). */
export function useDashboardControlGroup<G extends DashboardControlGroup>(
group: G,
): DashboardControls[G] {
return useDashboardStore((s) => s.controls[group]);
}

View File

@@ -11,7 +11,6 @@ import {
buildDashboardUpdatePermission,
} from 'lib/authz/hooks/useAuthZ/permissions/dashboard.permissions';
import { useDashboardStore } from '../../store/useDashboardStore';
import { useDashboardEditContext } from '../useDashboardEditContext';
const DASHBOARD_ID = 'dash-1';
@@ -45,23 +44,6 @@ describe('useDashboardEditContext - AuthZ', () => {
afterEach(() => {
jest.restoreAllMocks();
server.resetHandlers();
useDashboardStore.setState({ readOnly: false });
});
// A host-forced view-only mount outranks every grant.
it('is read-only on a read-only mount despite full permissions', async () => {
server.use(setupAuthzAdmin());
useDashboardStore.setState({ readOnly: true });
const { result } = renderGuard();
await waitFor(() =>
expect(result.current.editDisabledTooltip).toBe('dashboard_read_only_here'),
);
expect(result.current.isEditable).toBe(false);
expect(result.current.canEditDashboard).toBe(false);
expect(result.current.canDeleteDashboard).toBe(false);
expect(result.current.deleteDisabledTooltip).toBe('dashboard_read_only_here');
});
describe('permission granted', () => {

View File

@@ -1,115 +1,57 @@
import type { ReactNode } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
import { renderHook } from 'tests/test-utils';
import {
type DashboardtypesGettableDashboardV2DTO,
type DashboardtypesVariableDTO,
DashboardtypesVariableEnvelopeGithubComSigNozSignozPkgTypesDashboardtypesTextVariableSpecDTOKind as TextVariableKind,
} from 'api/generated/services/sigNoz.schemas';
import { renderHook } from '@testing-library/react';
import type { DashboardQuerySource } from '../../store/slices/editContextSlice';
import { useDashboardFetchRequired } from '../useDashboardFetchRequired';
const QUERY_KEY = ['/api/v2/dashboards/dash-1'];
const mockRefetch = jest.fn();
let mockSource: DashboardQuerySource | null;
const mockUseGetDashboardV2 = jest.fn();
jest.mock(
'pages/DashboardPage/DashboardContainer/store/useDashboardStore',
() => ({
useDashboardStore: (
selector: (s: {
dashboardId: string;
dashboardQuerySource: DashboardQuerySource | null;
refetch: () => void;
}) => unknown,
): unknown =>
selector({
dashboardId: 'dash-1',
dashboardQuerySource: mockSource,
refetch: mockRefetch,
}),
selector: (s: { dashboardId: string }) => unknown,
): unknown => selector({ dashboardId: 'dash-1' }),
}),
);
function textVariable(name: string): DashboardtypesVariableDTO {
return {
kind: TextVariableKind.TextVariable,
spec: { name, display: { name }, value: '' },
};
}
function dashboardWith(
spec: Partial<DashboardtypesGettableDashboardV2DTO['spec']>,
): DashboardtypesGettableDashboardV2DTO {
return { id: 'dash-1', spec } as DashboardtypesGettableDashboardV2DTO;
}
function renderWithCache(
cached?: unknown,
): ReturnType<
typeof renderHook<ReturnType<typeof useDashboardFetchRequired>, void>
> {
const queryClient = new QueryClient();
if (cached !== undefined) {
queryClient.setQueryData(mockSource?.queryKey ?? QUERY_KEY, cached);
}
return renderHook(() => useDashboardFetchRequired(), {
wrapper: ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
),
});
}
jest.mock('api/generated/services/dashboard', () => ({
useGetDashboardV2: (): unknown => mockUseGetDashboardV2(),
}));
describe('useDashboardFetchRequired', () => {
beforeEach(() => {
mockSource = null;
});
it('returns the loaded dashboard and its variables', () => {
const dashboard = {
spec: { variables: [{ name: 'region' }, { name: 'tier' }] },
};
mockUseGetDashboardV2.mockReturnValue({ data: { data: dashboard } });
it('reads the dashboards API entry when the host sets no source', () => {
const variables = [textVariable('region'), textVariable('tier')];
const dashboard = dashboardWith({ variables });
const { result } = renderWithCache({ data: dashboard, status: 'success' });
const { result } = renderHook(() => useDashboardFetchRequired());
expect(result.current.dashboard).toBe(dashboard);
expect(result.current.variables).toBe(variables);
expect(result.current.refetch).toBe(mockRefetch);
});
it("reads a host's own cache entry through its select", () => {
const systemDashboard = { name: 'ai-o11y-overview', spec: {} };
mockSource = {
queryKey: ['/api/v2/dashboards/system/ai-o11y-overview'],
select: (response: { data: typeof systemDashboard }) =>
({
...response.data,
id: 'system-id',
}) as DashboardtypesGettableDashboardV2DTO,
};
const { result } = renderWithCache({ data: systemDashboard });
expect(result.current.dashboard).toStrictEqual({
name: 'ai-o11y-overview',
spec: {},
id: 'system-id',
});
expect(result.current.variables).toStrictEqual([
{ name: 'region' },
{ name: 'tier' },
]);
});
it('normalizes variables to an empty array when the spec has none', () => {
const { result } = renderWithCache({ data: dashboardWith({}) });
mockUseGetDashboardV2.mockReturnValue({ data: { data: { spec: {} } } });
const { result } = renderHook(() => useDashboardFetchRequired());
expect(result.current.variables).toStrictEqual([]);
});
it('throws when the source entry is empty', () => {
it('throws when used outside a loaded dashboard subtree', () => {
mockUseGetDashboardV2.mockReturnValue({ data: undefined });
// Suppress React's expected render-error logging for this case.
const consoleError = jest
.spyOn(console, 'error')
.mockImplementation(() => undefined);
expect(() => renderWithCache()).toThrow(/outside a loaded dashboard subtree/);
expect(() => renderHook(() => useDashboardFetchRequired())).toThrow(
/outside a loaded dashboard subtree/,
);
consoleError.mockRestore();
});

View File

@@ -111,32 +111,3 @@ describe('useGetQueryRangeV5 enabled gating', () => {
expect(mockQueryRangeV5).toHaveBeenCalledTimes(2);
});
});
describe('useGetQueryRangeV5 host fetch', () => {
it('fetches through the host fetch instead of query_range', async () => {
mockQueryRangeV5.mockReset();
const fetch = jest
.fn()
.mockResolvedValue({ status: 'success', data: {} } as QueryRangeV5200);
const wrapper = ({ children }: PropsWithChildren): JSX.Element => (
<QueryClientProvider client={new QueryClient()}>
{children}
</QueryClientProvider>
);
renderHook(
() =>
useGetQueryRangeV5({
requestPayload: REQUEST,
queryKey: KEY_A,
enabled: true,
fetch,
}),
{ wrapper },
);
await waitFor(() => expect(fetch).toHaveBeenCalledTimes(1));
expect(fetch.mock.calls[0][0]).toBe(REQUEST);
expect(mockQueryRangeV5).not.toHaveBeenCalled();
});
});

View File

@@ -19,12 +19,10 @@ jest.mock('api/generated/services/dashboard', () => ({
getGetDashboardV2QueryKey: jest.fn(() => ['/api/v2/dashboards/dash-1']),
}));
let mockReadOnly = false;
jest.mock('../../store/useDashboardStore', () => ({
useDashboardStore: jest.fn(
(selector: (s: { dashboardId: string; readOnly: boolean }) => unknown) =>
selector({ dashboardId: 'dash-1', readOnly: mockReadOnly }),
(selector: (s: { dashboardId: string; isEditable: boolean }) => unknown) =>
selector({ dashboardId: 'dash-1', isEditable: true }),
),
}));
@@ -37,7 +35,6 @@ const queryClient = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let captured: { fn: (ops: any) => unknown; options: any };
let mockMutateAsync: jest.Mock;
function dashboardEnvelope(name: string): GetDashboardV2200 {
return {
@@ -53,12 +50,10 @@ const replaceNameOp = {
beforeEach(() => {
jest.clearAllMocks();
mockReadOnly = false;
mockMutateAsync = jest.fn().mockResolvedValue(undefined);
(useQueryClient as jest.Mock).mockReturnValue(queryClient);
(useMutation as jest.Mock).mockImplementation((fn, options) => {
captured = { fn, options };
return { mutateAsync: mockMutateAsync, isLoading: false };
return { mutateAsync: jest.fn(), isLoading: false };
});
renderHook(() => useOptimisticPatch());
});
@@ -124,22 +119,4 @@ describe('useOptimisticPatch', () => {
// No follow-up GET (that could read stale data and flicker the UI back).
expect(queryClient.invalidateQueries).not.toHaveBeenCalled();
});
it('patchAsync rejects without sending on a read-only mount', async () => {
mockReadOnly = true;
const { result } = renderHook(() => useOptimisticPatch());
await expect(result.current.patchAsync([replaceNameOp])).rejects.toThrow(
'dashboard_read_only_here',
);
expect(mockMutateAsync).not.toHaveBeenCalled();
});
it('patchAsync sends the ops when the mount is editable', async () => {
const { result } = renderHook(() => useOptimisticPatch());
await result.current.patchAsync([replaceNameOp]);
expect(mockMutateAsync).toHaveBeenCalledWith([replaceNameOp]);
});
});

View File

@@ -11,7 +11,6 @@ import {
DASHBOARD_CACHE_TIME_ON_REFRESH_ENABLED,
} from 'constants/queryCacheTime';
import { useDashboardStore } from '../../store/useDashboardStore';
import { usePanelQuery } from '../usePanelQuery';
import { useGetQueryRangeV5 } from '../useGetQueryRangeV5';
@@ -599,58 +598,4 @@ describe('usePanelQuery', () => {
expect(cacheTime).toBe(DASHBOARD_CACHE_TIME_ON_REFRESH_ENABLED);
});
});
describe('with a host query runner', () => {
const runner = {
key: 'public:abc',
run: jest.fn().mockResolvedValue({ status: 'success', data: {} }),
};
beforeEach(() => {
useDashboardStore.getState().setEditContext({
dashboardId: 'd1',
refetch: jest.fn(),
queryRunner: runner,
});
});
afterEach(() => {
useDashboardStore
.getState()
.setEditContext({ dashboardId: '', refetch: jest.fn() });
});
it('keys the cache by the runner and runs the query through it with the panel id', async () => {
renderHook(() =>
usePanelQuery({
panel: builderPanel(),
panelId: 'p1',
queryCapabilities: TIME_SERIES_CAPABILITIES,
}),
);
const [{ queryKey, fetch, requestPayload }] =
mockUseGetQueryRangeV5.mock.calls[0];
expect(queryKey).toContain('public:abc');
await fetch(requestPayload);
expect(runner.run).toHaveBeenCalledWith({
panelId: 'p1',
requestPayload,
signal: undefined,
});
});
});
it('runs on query_range when no host runner is set', () => {
renderHook(() =>
usePanelQuery({
panel: builderPanel(),
panelId: 'p1',
queryCapabilities: TIME_SERIES_CAPABILITIES,
}),
);
const [{ fetch }] = mockUseGetQueryRangeV5.mock.calls[0];
expect(fetch).toBeUndefined();
});
});

View File

@@ -17,7 +17,6 @@ import { useDashboardFetchRequired } from './useDashboardFetchRequired';
*/
export function useDashboardEditContext(): DashboardEditContext {
const { dashboard } = useDashboardFetchRequired();
const readOnly = useDashboardStore((s) => s.readOnly);
const {
canRead,
canEdit,
@@ -25,8 +24,12 @@ export function useDashboardEditContext(): DashboardEditContext {
editChecks,
deletePermission,
areOtherPermissionsLoading,
} = useDashboardPermissions(dashboard.id, { enabled: !readOnly });
} = useDashboardPermissions(dashboard.id);
const { t } = useTranslation('dashboard');
const readOnlyOverride = useDashboardStore(
(s) => s.canEditDashboardOverride === false,
);
const deleteChecks = useMemo(() => [deletePermission], [deletePermission]);
return deriveEditContext({
@@ -41,6 +44,6 @@ export function useDashboardEditContext(): DashboardEditContext {
locked: t('dashboard_locked'),
readOnly: t('dashboard_read_only_here'),
},
readOnlyOverride: readOnly,
readOnlyOverride,
});
}

View File

@@ -1,52 +1,34 @@
import { useMemo } from 'react';
import { useQuery } from 'react-query';
import { getGetDashboardV2QueryKey } from 'api/generated/services/dashboard';
import type {
DashboardtypesGettableDashboardV2DTO,
DashboardtypesVariableDTO,
GetDashboardV2200,
} from 'api/generated/services/sigNoz.schemas';
import { useDashboardStore } from 'pages/DashboardPage/DashboardContainer/store/useDashboardStore';
import { useDashboardFetch } from './useDashboardFetch';
import type { UseDashboardFetchResult } from './useDashboardFetch';
export interface UseDashboardFetchRequiredResult {
/** Guaranteed present — the hook throws otherwise. */
dashboard: DashboardtypesGettableDashboardV2DTO;
/** Always an array, so callers skip `?? []` guards. */
variables: DashboardtypesVariableDTO[];
refetch: () => void;
refetch: UseDashboardFetchResult['refetch'];
}
const selectDashboardV2 = (
response: GetDashboardV2200,
): DashboardtypesGettableDashboardV2DTO => response.data;
/**
* Dashboard accessor for components rendered inside a loaded dashboard subtree. The
* root owns the fetch and publishes where it cached the dashboard
* (`dashboardQuerySource`); this observes that entry without fetching, and throws if
* it's empty — turning a silent `undefined` into a loud programmer error. It also
* derives spec collections (`variables`) since the dashboard is guaranteed here.
* root pages own the fetch and gate on a resolved dashboard before mounting their
* subtree, so this reuses the shared react-query cache entry and throws if the
* dashboard is missing — turning a silent `undefined` into a loud programmer error. It
* also derives spec collections (`variables`) since the dashboard is guaranteed here.
*
* Prefer this over `useDashboardFetch` outside the two root pages; the
* `signoz/no-dashboard-fetch-outside-root` lint rule enforces the split.
*/
export function useDashboardFetchRequired(): UseDashboardFetchRequiredResult {
const dashboardId = useDashboardStore((s) => s.dashboardId);
const source = useDashboardStore((s) => s.dashboardQuerySource);
const queryKey =
source?.queryKey ?? getGetDashboardV2QueryKey({ id: dashboardId });
const select = source?.select ?? selectDashboardV2;
const refetch = useDashboardStore((s) => s.refetch);
// Observe only: the root owns the request, so this never fetches.
const { data: dashboard } = useQuery<
unknown,
unknown,
DashboardtypesGettableDashboardV2DTO | undefined
>({
queryKey,
select: select as (response: unknown) => DashboardtypesGettableDashboardV2DTO,
enabled: false,
});
const { dashboard, refetch } = useDashboardFetch(dashboardId);
const variables = useMemo(
() => dashboard?.spec?.variables ?? [],
@@ -57,7 +39,7 @@ export function useDashboardFetchRequired(): UseDashboardFetchRequiredResult {
throw new Error(
'useDashboardFetchRequired was used outside a loaded dashboard subtree — the ' +
'dashboard is undefined. Only call it below a root page that gates rendering ' +
'on its fetch and seeds the edit context (DashboardContainer / PanelEditorPage).',
'on useDashboardFetch (DashboardPage / PanelEditorPage).',
);
}

View File

@@ -21,7 +21,6 @@ interface UseDashboardStaleCheck {
export function useDashboardStaleCheck(
dashboard: DashboardtypesGettableDashboardV2DTO,
refetch: () => void,
enabled = true,
): UseDashboardStaleCheck {
const {
id: dashboardId,
@@ -35,7 +34,7 @@ export function useDashboardStaleCheck(
const [dismissedAt, setDismissedAt] = useState<string | null>(null);
useEffect(() => {
if (!dashboardId || !enabled) {
if (!dashboardId) {
return undefined;
}
const probe = async (): Promise<void> => {
@@ -57,7 +56,7 @@ export function useDashboardStaleCheck(
document.removeEventListener('visibilitychange', probe);
window.removeEventListener('focus', probe);
};
}, [dashboardId, enabled]);
}, [dashboardId]);
const serverUpdatedAt = server?.updatedAt;

View File

@@ -15,11 +15,6 @@ export interface UseGetQueryRangeV5Args {
keepPreviousData?: boolean;
/** Unused-entry TTL; callers drop to 0 under auto-refresh to bound cache growth (V1 parity). */
cacheTime?: number;
/** Replaces the `query_range` call; the caller keys the cache for it. */
fetch?: (
requestPayload: Querybuildertypesv5QueryRangeRequestDTO,
signal?: AbortSignal,
) => Promise<QueryRangeV5200>;
}
/**
@@ -54,7 +49,6 @@ export function useGetQueryRangeV5({
enabled,
keepPreviousData,
cacheTime,
fetch,
}: UseGetQueryRangeV5Args): UseQueryResult<QueryRangeV5200, Error> {
const queryClient = useQueryClient();
// An errored key has no data, so it is always stale; keep it enabled so
@@ -63,7 +57,7 @@ export function useGetQueryRangeV5({
return useQuery<QueryRangeV5200, Error>({
queryKey,
queryFn: ({ signal }) => (fetch ?? queryRangeV5)(requestPayload, signal),
queryFn: ({ signal }) => queryRangeV5(requestPayload, signal),
enabled: enabled || hasErrored,
retry: retryUnlessClientError,
keepPreviousData,

View File

@@ -39,7 +39,6 @@ export function useOptimisticPatch(
const storeDashboardId = useDashboardStore((s) => s.dashboardId);
const dashboardId = dashboardIdOverride ?? storeDashboardId;
const { t } = useTranslation('dashboard');
const readOnly = useDashboardStore((s) => s.readOnly);
const queryClient = useQueryClient();
const queryKey = getGetDashboardV2QueryKey({ id: dashboardId });
@@ -79,10 +78,6 @@ export function useOptimisticPatch(
const { mutateAsync } = mutation;
const patchAsync = useCallback(
(ops: DashboardtypesJSONPatchOperationDTO[]): Promise<unknown> => {
// The UI renders no edit affordance on a read-only mount, so reaching here is a bug.
if (readOnly) {
return Promise.reject(new Error(t('dashboard_read_only_here')));
}
// Defense-in-depth against a lock, read straight from the cache this hook
// already owns. Permission is enforced by the UI and, definitively, by the
// backend — checking it here would drag authz into every mutation.
@@ -92,7 +87,7 @@ export function useOptimisticPatch(
}
return mutateAsync(ops);
},
[readOnly, queryClient, queryKey, mutateAsync, t],
[queryClient, queryKey, mutateAsync],
);
return {

View File

@@ -2,11 +2,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react';
import { useQueryClient } from 'react-query';
// eslint-disable-next-line no-restricted-imports -- TODO: migrate global time selector off redux
import { useSelector } from 'react-redux';
import type {
DashboardtypesPanelDTO,
Querybuildertypesv5QueryRangeRequestDTO,
QueryRangeV5200,
} from 'api/generated/services/sigNoz.schemas';
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
import {
DASHBOARD_CACHE_TIME,
DASHBOARD_CACHE_TIME_ON_REFRESH_ENABLED,
@@ -130,7 +126,6 @@ export function usePanelQuery({
// use it (V1 parity). Names come from the fetch context (all variables, even
// unresolved ones); null before the variable bar initializes it.
const dashboardId = useDashboardStore((s) => s.dashboardId);
const queryRunner = useDashboardStore((s) => s.queryRunner);
const variables = useDashboardStore(selectResolvedVariables(dashboardId));
const fetchContext = useDashboardStore((s) => s.variableFetchContext);
@@ -238,7 +233,6 @@ export function usePanelQuery({
// Only the variables this panel references re-key the cache, so an unrelated
// variable change doesn't refetch it.
scopedVariables,
queryRunner?.key ?? null,
],
[
panelId,
@@ -255,24 +249,10 @@ export function usePanelQuery({
offset,
pageSize,
scopedVariables,
queryRunner?.key,
],
);
const fetch = useMemo(
() =>
queryRunner
? (
payload: Querybuildertypesv5QueryRangeRequestDTO,
signal?: AbortSignal,
): Promise<QueryRangeV5200> =>
queryRunner.run({ panelId, requestPayload: payload, signal })
: undefined,
[queryRunner, panelId],
);
const response = useGetQueryRangeV5({
fetch,
requestPayload,
queryKey,
enabled: enabled && runnable && !isWaitingOnVariable,

View File

@@ -9,12 +9,6 @@ import PanelsAndSectionsLayout from './PanelsAndSectionsLayout';
import { useResolvedVariables } from './hooks/useResolvedVariables';
import { useSyncVariablesForSuggestions } from './hooks/useSyncVariablesForSuggestions';
import { useDashboardStore } from './store/useDashboardStore';
import type {
DashboardQuerySource,
QueryRunner,
} from './store/slices/editContextSlice';
import type { DashboardControlsInput } from './controls/types';
import { useDashboardControlGroup } from './controls/useDashboardControlGroup';
import styles from './DashboardContainer.module.scss';
import DashboardPageHeader from './components/DashboardPageHeader/DashboardPageHeader';
import LockedIndicator from './components/LockedIndicator/LockedIndicator';
@@ -25,23 +19,20 @@ import { resolveDashboardImage } from 'pages/DashboardPage/DashboardContainer/da
interface DashboardContainerProps {
dashboard: DashboardtypesGettableDashboardV2DTO;
refetch: () => void;
/** Where the host cached `dashboard`; defaults to the dashboards API entry. */
source?: DashboardQuerySource;
/** View-only mount: no edit affordance, no write, no server freshness probe. */
readOnly?: boolean;
/** What renders; omitted controls are shown. Writing controls are off when read-only. */
controls?: DashboardControlsInput;
/** Runs panel queries; omitted runs them on `query_range`. */
queryRunner?: QueryRunner;
/**
* @deprecated
* `canEditDashboardOverride` is a temporary solution to allow the dashboard to be view only.
* This is only used for LLM Observability.
* It will be removed in the future.
* TODO: @Ashwin / @Abhi — remove when the final solution is implemented.
*/
canEditDashboardOverride?: boolean;
}
function DashboardContainer({
dashboard,
refetch,
source,
readOnly = false,
controls,
queryRunner,
canEditDashboardOverride,
}: DashboardContainerProps): JSX.Element {
const spec = dashboard.spec;
const image = resolveDashboardImage(dashboard.image);
@@ -64,10 +55,7 @@ function DashboardContainer({
setEditContext({
dashboardId: dashboard.id,
refetch,
source,
readOnly,
controls,
queryRunner,
canEditDashboardOverride,
});
// Resolve the variable selection into the V5 query payload and publish it to
@@ -78,10 +66,7 @@ function DashboardContainer({
// suggests them ($variable) in the panel editor and dashboards-page builder.
useSyncVariablesForSuggestions(dashboard);
const staleCheck = useDashboardStaleCheck(dashboard, refetch, !readOnly);
const showHeader = Object.values(useDashboardControlGroup('header')).some(
Boolean,
);
const staleCheck = useDashboardStaleCheck(dashboard, refetch);
// In full screen show only the sections and panels — the header/toolbar chrome
// is hidden for a clean presentation view (exit with Esc).
@@ -93,12 +78,12 @@ function DashboardContainer({
<AutoRefreshTicker />
) : (
<>
{showHeader && <DashboardPageHeader title={name} image={image} />}
<DashboardPageHeader title={name} image={image} />
<DashboardPageToolbar dashboard={dashboard} handle={fullScreenHandle} />
</>
)}
<PanelsAndSectionsLayout layouts={spec.layouts} panels={spec.panels} />
{!!dashboard.locked && !readOnly && <LockedIndicator />}
{!!dashboard.locked && <LockedIndicator />}
<DashboardChangedDialog
open={staleCheck.showPrompt}
onReload={staleCheck.reload}

View File

@@ -1,119 +0,0 @@
import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';
import { useDashboardStore } from '../../useDashboardStore';
import type { DashboardQuerySource } from '../editContextSlice';
const refetch = (): void => undefined;
const systemSource: DashboardQuerySource = {
queryKey: ['/api/v2/dashboards/system/ai-o11y-overview'],
select: (response: { data: DashboardtypesGettableDashboardV2DTO }) =>
response.data,
};
function store(): ReturnType<typeof useDashboardStore.getState> {
return useDashboardStore.getState();
}
describe('editContextSlice.setEditContext', () => {
beforeEach(() => {
store().setEditContext({ dashboardId: '', refetch });
});
it('defaults to the dashboards API entry and an editable mount', () => {
store().setEditContext({ dashboardId: 'dash-1', refetch });
expect(store().dashboardQuerySource).toBeNull();
expect(store().readOnly).toBe(false);
});
it("stores a host's source and read-only flag", () => {
store().setEditContext({
dashboardId: 'system',
refetch,
source: systemSource,
readOnly: true,
});
expect(store().dashboardQuerySource).toBe(systemSource);
expect(store().readOnly).toBe(true);
});
it('clears read-only when the next mount does not ask for it', () => {
store().setEditContext({
dashboardId: 'system',
refetch,
source: systemSource,
readOnly: true,
});
store().setEditContext({ dashboardId: 'dash-1', refetch });
expect(store().readOnly).toBe(false);
expect(store().dashboardQuerySource).toBeNull();
});
// Called during render: a set on every call would re-render subscribers in a loop.
it('is a no-op when called again with equal values', () => {
store().setEditContext({ dashboardId: 'dash-1', refetch });
const listener = jest.fn();
const unsubscribe = useDashboardStore.subscribe(listener);
store().setEditContext({ dashboardId: 'dash-1', refetch });
expect(listener).not.toHaveBeenCalled();
unsubscribe();
});
it('is a no-op for an equal inline controls object', () => {
store().setEditContext({
dashboardId: 'dash-1',
refetch,
controls: { header: false },
});
const listener = jest.fn();
const unsubscribe = useDashboardStore.subscribe(listener);
store().setEditContext({
dashboardId: 'dash-1',
refetch,
controls: { header: false },
});
expect(listener).not.toHaveBeenCalled();
expect(store().controls.header.share).toBe(false);
unsubscribe();
});
it('resolves controls against read-only', () => {
store().setEditContext({ dashboardId: 'dash-1', refetch, readOnly: true });
expect(store().controls.panelActions.edit).toBe(false);
expect(store().controls.panelActions.view).toBe(true);
});
it('treats a runner with the same key as unchanged, a new key as a change', () => {
const run = jest.fn();
store().setEditContext({
dashboardId: 'dash-1',
refetch,
queryRunner: { key: 'public:a', run },
});
const listener = jest.fn();
const unsubscribe = useDashboardStore.subscribe(listener);
store().setEditContext({
dashboardId: 'dash-1',
refetch,
queryRunner: { key: 'public:a', run: jest.fn() },
});
expect(listener).not.toHaveBeenCalled();
store().setEditContext({
dashboardId: 'dash-1',
refetch,
queryRunner: { key: 'public:b', run },
});
expect(store().queryRunner?.key).toBe('public:b');
unsubscribe();
});
});

View File

@@ -1,65 +1,24 @@
import { isEqual } from 'lodash-es';
import type { QueryKey } from 'react-query';
import type { StateCreator } from 'zustand';
import type {
DashboardtypesGettableDashboardV2DTO,
Querybuildertypesv5QueryRangeRequestDTO,
QueryRangeV5200,
} from 'api/generated/services/sigNoz.schemas';
import { resolveControls } from '../../controls/dashboardControls';
import type {
DashboardControls,
DashboardControlsInput,
} from '../../controls/types';
import type { DashboardStore } from '../useDashboardStore';
/**
* The react-query entry a host loaded the dashboard into, and how to read the
* dashboard out of it. Must be referentially stable (module-level).
*/
export interface DashboardQuerySource {
queryKey: QueryKey;
// `never` accepts any host's response type; the one caller casts at the boundary.
select: (response: never) => DashboardtypesGettableDashboardV2DTO | undefined;
}
/**
* Runs a panel's query, when not via `POST /api/v5/query_range`. `key` joins
* every panel cache key, so results from different runners never mix.
*/
export interface QueryRunner {
key: string;
run: (request: {
panelId: string;
requestPayload: Querybuildertypesv5QueryRangeRequestDTO;
signal?: AbortSignal;
}) => Promise<QueryRangeV5200>;
}
/**
* The page context the subtree can't derive for itself: which dashboard is open,
* where its cached copy lives, how to refetch it, and whether the host forces it
* view-only. Editability is deliberately absent — `useDashboardEditContext`
* derives it from the caches.
* The one piece of page context the subtree can't derive for itself: which
* dashboard is open, and how to refetch it. Editability is deliberately absent —
* `useDashboardEditContext` derives it from the caches.
*/
export interface EditContextSlice {
dashboardId: string;
/** `null` reads the dashboards API entry for `dashboardId`. */
dashboardQuerySource: DashboardQuerySource | null;
refetch: () => void;
readOnly: boolean;
/** Resolved: the host's `controls` over the defaults, writing ones off when read-only. */
controls: DashboardControls;
/** `null` runs panel queries on `query_range`. */
queryRunner: QueryRunner | null;
/**
* @deprecated Forces a view-only mount regardless of permissions. Used only by
* LLM Observability; see SigNoz/pulse-pod#283.
*/
canEditDashboardOverride?: boolean;
setEditContext: (ctx: {
dashboardId: string;
refetch: () => void;
source?: DashboardQuerySource;
readOnly?: boolean;
controls?: DashboardControlsInput;
queryRunner?: QueryRunner;
canEditDashboardOverride?: boolean;
}) => void;
}
@@ -70,37 +29,22 @@ export const createEditContextSlice: StateCreator<
EditContextSlice
> = (set, get) => ({
dashboardId: '',
dashboardQuerySource: null,
refetch: (): void => undefined,
readOnly: false,
controls: resolveControls(undefined, false),
queryRunner: null,
canEditDashboardOverride: undefined,
// Idempotent (no-op when unchanged) so it's safe to call during render.
setEditContext: (ctx): void => {
const prev = get();
const source = ctx.source ?? null;
const readOnly = ctx.readOnly ?? false;
// Hosts pass `controls` inline, so compare by value, not reference.
const controls = resolveControls(ctx.controls, readOnly);
const queryRunner = ctx.queryRunner ?? null;
if (
prev.dashboardId === ctx.dashboardId &&
prev.refetch === ctx.refetch &&
prev.readOnly === readOnly &&
prev.dashboardQuerySource === source &&
isEqual(prev.controls, controls) &&
// The key identifies a runner, so an inline one doesn't re-seed on every render.
prev.queryRunner?.key === queryRunner?.key
prev.canEditDashboardOverride === ctx.canEditDashboardOverride
) {
return;
}
set({
dashboardId: ctx.dashboardId,
dashboardQuerySource: source,
refetch: ctx.refetch,
readOnly,
controls,
queryRunner,
canEditDashboardOverride: ctx.canEditDashboardOverride,
});
},
});

View File

@@ -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(

View File

@@ -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 },
};

View File

@@ -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 },
);
}
};

View File

@@ -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,

View File

@@ -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,
};

View 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');
};

View File

@@ -3,6 +3,7 @@
* Do not hand-edit: regenerate instead.
*/
import { StatusCodes } from 'http-status-codes';
import ROUTES from 'constants/routes';
import { rest } from 'msw';
import type { QueryRangeRequestV5 } from 'types/api/v5/queryRange';
@@ -15,12 +16,15 @@ import {
LLM_MODELS,
LLM_SERVICES,
llmPanelResponse,
llmSystemDashboardResponse,
} from './__story_mockdata__/llmOverview';
const PANELS = 'AI overview · panels';
/** The system dashboard definition, its panels and its variables. */
/**
* The dashboard itself is bundled with the app rather than fetched, so the only
* thing left to answer is the panels, the variables and the share state its
* header reads.
*/
export const llmOverviewMocks = defineStoryMocks({
controls: {
series: countControl('Breakdown series', {
@@ -32,10 +36,6 @@ export const llmOverviewMocks = defineStoryMocks({
}),
},
handlers: (values, response) => [
rest.get(
'http://localhost/api/v2/dashboards/system/ai-o11y-overview',
response.json(() => llmSystemDashboardResponse()),
),
rest.post(
'http://localhost/api/v5/query_range',
response.json(async (req) =>
@@ -58,6 +58,22 @@ export const llmOverviewMocks = defineStoryMocks({
};
}),
),
// The header reads the share state on every load, so it answers even while
// the panels are held in the loading or failed state.
rest.get('http://localhost/api/v1/dashboards/:id/public', (_req, res, ctx) =>
res(
ctx.status(StatusCodes.NOT_FOUND),
ctx.json({
status: 'error',
error: {
code: 'public_dashboard_not_found',
message: "the AI observability overview isn't public",
url: '',
errors: [],
},
}),
),
),
],
config: () => ({ route: ROUTES.AI_OBSERVABILITY_OVERVIEW }),
});

View File

@@ -11,8 +11,8 @@ type LLMOverviewArgs = PageStoryArgs<typeof llmOverviewMocks>;
const pageStory = storyMocks(llmOverviewMocks, { layout: 'app' });
/**
* The AI observability overview: the read-only system dashboard, with cost, token
* and latency panels over `query_range`.
* The AI observability overview: cost, token and latency panels over
* `query_range`.
*
* Route: `/ai-observability/overview`.
*/
@@ -20,7 +20,8 @@ const meta = {
title: 'Pages/AI Observability/Overview',
component: LLMObservabilityPage,
...pageStory,
parameters: { ...pageStory.parameters },
// The header's public-dashboard lookup is expected to 404, so every story opts out.
parameters: { ...pageStory.parameters, allowConsoleErrors: true },
} satisfies Meta<LLMOverviewArgs>;
export default meta;
@@ -28,7 +29,7 @@ export default meta;
type Story = StoryObj<LLMOverviewArgs>;
/**
* The system overview dashboard: spend, tokens, latency and errors across
* The bundled overview dashboard: spend, tokens, latency and errors across
* every model the workspace calls, scoped by the model, environment and
* service variables above it.
*/

View File

@@ -3,13 +3,6 @@
* Do not hand-edit: regenerate instead.
*/
import {
DashboardtypesSourceDTO,
type DashboardtypesGettableSystemDashboardDTO,
type GetSystemDashboard200,
} from 'api/generated/services/sigNoz.schemas';
// The backend's own definition, so the story renders what the server serves.
import aiOverviewDefinition from '../../../../../../../pkg/modules/dashboard/impldashboard/fs/definitions/ai-o11y-overview.json';
import type {
MetricRangePayloadV5,
QueryRangeRequestV5,
@@ -168,19 +161,3 @@ export const llmPanelResponse = (
},
]);
};
export function llmSystemDashboardResponse(): GetSystemDashboard200 {
const { definition } = aiOverviewDefinition;
return {
status: 'success',
data: {
orgId: 'storybook-org',
locked: true,
source: DashboardtypesSourceDTO.system,
name: definition.name,
schemaVersion: definition.schemaVersion,
tags: [],
spec: definition.spec as DashboardtypesGettableSystemDashboardDTO['spec'],
},
};
}

View File

@@ -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>;

View File

@@ -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,
};

View 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');
};

View File

@@ -39,7 +39,6 @@ import {
METER_VOLUMES,
meterAttributeKeys,
meterExplorerQuery,
meterSystemDashboardResponse,
meterFieldKeys,
meterFieldValues,
meterMetricSignal,
@@ -180,10 +179,6 @@ export const meterMocks = defineStoryMocks({
}),
},
handlers: (values, response) => [
rest.get(
'http://localhost/api/v2/dashboards/system/cost-meter-breakdown',
response.json(meterSystemDashboardResponse),
),
rest.post(
'http://localhost/api/v5/query_range',
response.json(async (req) => {

View File

@@ -3,12 +3,13 @@
* Do not hand-edit: regenerate instead.
*/
import type {
GetQuickFilters200,
ListMetrics200,
ListSavedViews200,
TelemetrytypesTelemetryFieldKeyDTO,
} from 'api/generated/services/sigNoz.schemas';
import {
type GetQuickFilters200,
type GetSystemDashboard200,
type ListMetrics200,
type ListSavedViews200,
type TelemetrytypesTelemetryFieldKeyDTO,
MetrictypesTemporalityDTO,
MetrictypesTypeDTO,
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTOSignal as MetricsSignal,
@@ -21,15 +22,16 @@ import {
TelemetrytypesFieldContextDTO,
TelemetrytypesFieldDataTypeDTO,
TelemetrytypesSourceDTO,
DashboardtypesSourceDTO,
type DashboardtypesGettableSystemDashboardDTO,
} from 'api/generated/services/sigNoz.schemas';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { EQueryType } from 'types/common/dashboard';
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
// The backend's own definition, so the story renders what the server serves.
import costMeterDefinition from '../../../../../../pkg/modules/dashboard/impldashboard/fs/definitions/cost-meter-breakdown.json';
import type { Time } from 'container/TopNav/DateTimeSelectionV2/types';
import {
getLogCountWidgetData,
getLogSizeWidgetData,
getMetricCountWidgetData,
getSpanCountWidgetData,
getSpanSizeWidgetData,
} from 'container/MeterExplorer/Breakdown/graphs';
import type { Widgets } from 'types/api/widgets/widget';
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
import type { TimeSeries } from 'types/api/v5/queryRange';
@@ -246,66 +248,20 @@ export const meterTimeWindow = (range: MeterTimeRange): MeterTimeWindow => {
return relativeWindow(24 * HOUR_IN_MS, '1d');
};
/** The query the explorer starts on: the metric's hourly increase, summed. */
export const meterExplorerQuery = (volume: MeterVolume): Query => {
const metricName = VOLUME_METRICS[volume];
return {
queryType: EQueryType.QUERY_BUILDER,
promql: [],
clickhouse_sql: [],
id: `meter-explorer-${volume}`,
builder: {
queryFormulas: [],
queryTraceOperator: [],
queryData: [
{
aggregateAttribute: {
dataType: DataTypes.Float64,
key: metricName,
id: `${metricName}--float64--Sum--true`,
type: 'Sum',
},
aggregateOperator: 'increase',
dataSource: DataSource.METRICS,
source: 'meter',
disabled: false,
expression: 'A',
filters: { items: [], op: 'AND' },
functions: [],
groupBy: [],
having: [],
legend: METRICS[metricName].unit === 'bytes' ? 'size' : 'count',
limit: null,
orderBy: [],
queryName: 'A',
reduceTo: ReduceOperators.SUM,
spaceAggregation: 'sum',
stepInterval: null,
timeAggregation: 'increase',
},
],
},
};
const EXPLORER_WIDGETS: Record<MeterVolume, () => Widgets> = {
'log-count': getLogCountWidgetData,
'log-size': getLogSizeWidgetData,
'span-count': getSpanCountWidgetData,
'span-size': getSpanSizeWidgetData,
'metric-datapoints': getMetricCountWidgetData,
};
/** The breakdown tab's system dashboard, as `GET /api/v2/dashboards/system/:name` serves it. */
export const meterSystemDashboardResponse = (): GetSystemDashboard200 => {
const { definition } = costMeterDefinition;
return {
status: 'success',
data: {
orgId: 'storybook-org',
locked: true,
source: DashboardtypesSourceDTO.system,
name: definition.name,
schemaVersion: definition.schemaVersion,
tags: [],
spec: definition.spec as DashboardtypesGettableSystemDashboardDTO['spec'],
},
};
};
/**
* The query the explorer starts on, taken from the breakdown widget for the
* same metric so the story asks for what the page itself would build.
*/
export const meterExplorerQuery = (volume: MeterVolume): Query =>
EXPLORER_WIDGETS[volume]().query;
/** The metric picker in the query builder lists what the meter reports. */
export const meterMetricsListResponse = (

View File

@@ -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,

View File

@@ -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,
};

View 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',
);
};

Some files were not shown because too many files have changed in this diff Show More