Compare commits

...

79 Commits

Author SHA1 Message Date
Hardik
d6a2141217 test(e2e): number the audit specs from TC-01 in each file 2026-12-02 20:04:39 +05:30
Hardik
5bb52df642 Merge branch 'split/3-page' into split/4-e2e 2026-12-02 20:03:08 +05:30
Hardik
43d9a5e535 test(audit-logs): type the global time instead of casting the store 2026-12-02 20:02:51 +05:30
Hardik
8e26feea44 Merge branch 'split/3-page' into split/4-e2e 2026-12-02 19:53:25 +05:30
Hardik
4c20dafc34 test(audit-logs): keep the log fixture with the audit tests 2026-12-02 19:53:08 +05:30
Hardik
16248a93a1 Merge branch 'split/3-page' into split/4-e2e 2026-12-02 19:51:12 +05:30
Hardik
2307f02d0c Merge branch 'split/2-audit-source' into split/3-page 2026-12-02 19:51:09 +05:30
Hardik
0e4b7996e3 Merge branch 'split/1-logs-components' into split/2-audit-source
# Conflicts:
#	frontend/src/api/v5/queryRange/convertV5Response.ts
2026-12-02 19:50:51 +05:30
Hardik
fcaf591cde feat(query-range): lift resource.attributes onto resource in raw rows 2026-12-02 19:50:26 +05:30
Hardik
c37b197ef6 test(logs): drop the row view and copy link tests 2026-12-02 19:50:16 +05:30
Hardik
559bdc773e Merge branch 'split/3-page' into split/4-e2e 2026-12-02 19:37:02 +05:30
Hardik
c363f7a150 refactor(audit-logs): read resource attributes from the flat resource 2026-12-02 19:36:42 +05:30
Hardik
777150a0f5 Merge branch 'split/2-audit-source' into split/3-page 2026-12-02 19:36:20 +05:30
Hardik
23bbddfad4 feat(query-range): lift resource.attributes onto resource in raw rows 2026-12-02 19:35:55 +05:30
Hardik
56ad40cf38 Merge branch 'split/1-logs-components' into split/2-audit-source 2026-12-02 19:35:50 +05:30
Hardik
c439308d7e refactor(logs): drop the resource attributes lift from getLogFieldValue 2026-12-02 19:35:25 +05:30
Hardik
cabac4739e test(logs): type the mocks in the log row and hook tests 2026-12-02 19:26:15 +05:30
Hardik
afa60e6a37 Merge branch 'split/3-page' into split/4-e2e 2026-12-02 19:18:01 +05:30
Hardik
0c2690903d refactor(audit-logs): reuse the log row views through getLogFieldValue
Drops getAuditFieldValue and the row view generics.
2026-12-02 19:17:49 +05:30
Hardik
7f01315612 Merge branch 'split/2-audit-source' into split/3-page 2026-12-02 19:10:15 +05:30
Hardik
d769be317d Merge branch 'split/1-logs-components' into split/2-audit-source 2026-12-02 19:10:05 +05:30
Hardik
a72a8d0063 refactor(logs): drop the generics and getFieldValue from the row views
Resolve audit resource attributes in getLogFieldValue instead.
2026-12-02 19:06:52 +05:30
Hardik
189ebaad72 Merge branch 'split/3-page' into split/4-e2e 2026-12-02 15:36:36 +05:30
Hardik
62201a6289 Merge branch 'split/2-audit-source' into split/3-page 2026-12-02 15:36:19 +05:30
Hardik
7700246e4a Merge branch 'split/1-logs-components' into split/2-audit-source 2026-12-02 15:36:01 +05:30
Hardik
11df5721c9 refactor(logs): drop showCopyLink from the row views 2026-12-02 15:32:47 +05:30
Hardik
7b92439d93 refactor(audit-logs): drop the row copy link prop 2026-12-02 15:32:19 +05:30
Hardik
565440ed21 fix(audit-logs): type the row body as a string or a log body object 2026-12-02 15:19:36 +05:30
Hardik
60b35b8222 refactor(logs): drop the flush prop from the log state indicator 2026-12-02 15:07:24 +05:30
Hardik
b910ccc618 refactor(audit-logs): use the default log state indicator spacing in the drawer 2026-12-02 15:06:22 +05:30
Hardik
a1e8febab5 Merge branch 'split/3-page' into split/4-e2e 2026-12-02 15:00:03 +05:30
Hardik
0eda2c3080 Merge branch 'split/2-audit-source' into split/3-page 2026-12-02 14:58:45 +05:30
Hardik
62099763dc Merge branch 'split/1-logs-components' into split/2-audit-source 2026-12-02 14:58:27 +05:30
Hardik
0a15b0f9be refactor(logs): inline add-to-query back into useActiveLog 2026-12-02 14:58:06 +05:30
Hardik
ca6045a462 fix(audit-logs): read the drawer body through getBodyMessage 2026-12-02 14:56:26 +05:30
Hardik
f80c6be217 Merge branch 'split/3-page' into split/4-e2e 2026-12-02 13:08:30 +05:30
Hardik
d0ee0d913b feat(audit-logs): label the explorer tab with an icon 2026-12-02 13:08:12 +05:30
Hardik
f057d5894e test(audit-logs): wait for the next page, merge the link tests, and skip clipboard outside Chromium 2026-12-02 10:18:35 +05:30
Hardik
c6b1e8ea0e Merge branch 'split/3-page' into split/4-e2e 2026-12-02 10:01:06 +05:30
Hardik
c31870110a refactor(audit-logs): return the query key from the hook and drop casts and the cancel effect 2026-12-02 10:00:42 +05:30
Hardik
8f201eeb76 fix(audit-logs): show query warnings and follow the state and test rules 2026-12-02 09:44:22 +05:30
Hardik
b1261610b0 refactor(logs): drop the empty items guard from the options menu 2026-12-02 09:35:06 +05:30
Hardik
ac1a12c390 Merge branch 'split/2-audit-source' into split/3-page 2026-12-02 09:34:02 +05:30
Hardik
f7ad5f2f47 Merge branch 'split/1-logs-components' into split/2-audit-source 2026-12-02 09:33:50 +05:30
Hardik
1ecb2ea954 feat(logs): add test ids to the max lines buttons 2026-12-02 09:33:26 +05:30
Hardik
e75768f981 Merge branch 'split/3-page' into split/4-e2e 2026-12-02 08:46:02 +05:30
Hardik
e10731fb7c Merge branch 'split/2-audit-source' into split/3-page 2026-12-02 08:45:52 +05:30
Hardik
d28421004e refactor(query-builder): map every quick filter source and use the audit source enum 2026-12-02 08:45:33 +05:30
Hardik
136d98311e Merge branch 'split/3-page' into split/4-e2e 2026-12-02 08:34:13 +05:30
Hardik
083f70c70f refactor(audit-logs): pass showCopyLink to the log rows 2026-12-02 08:33:49 +05:30
Hardik
1cdf7e82ee Merge branch 'split/2-audit-source' into split/3-page 2026-12-02 08:33:23 +05:30
Hardik
79f49f56fc Merge branch 'split/1-logs-components' into split/2-audit-source 2026-12-02 08:33:18 +05:30
Hardik
e395459783 refactor(logs): rename showActions to showCopyLink and share the log id type 2026-12-02 08:32:58 +05:30
Hardik
59a23fbc2d test(audit-logs): assert the copied link keeps the principal filter 2026-12-01 16:54:52 +05:30
Hardik
8f5450df7c feat(audit-logs): add the audit logs stories 2026-12-01 16:35:44 +05:30
Hardik
d7ecc1034d feat(query-builder): add audit as a logs query source 2026-12-01 16:35:44 +05:30
Hardik
245cca1cb5 feat(audit-logs): add the audit logs route and its admin-only permission 2026-12-01 16:35:44 +05:30
Hardik
4f4a793558 test(audit-logs): add the audit logs e2e specs and seeding 2026-12-01 16:35:44 +05:30
Hardik
7413f3f427 feat(audit-logs): show the audit logs entry in the side nav to admins 2026-12-01 16:35:44 +05:30
Hardik
89f1c7cc72 feat(audit-logs): add the audit logs explorer page and its route 2026-12-01 16:35:44 +05:30
Hardik
8b068c827f feat(logs): let the options menu hide the format section 2026-12-01 16:35:44 +05:30
Hardik
cc389a3d73 refactor(logs): let the log row and detail components take any log shape 2026-12-01 16:32:28 +05:30
Hardik
322b288daf refactor(logs): make the active log and add-to-query hooks generic 2026-12-01 16:32:27 +05:30
swapnil-signoz
c017fc7436 refactor(telemetrymetadata): move audit discovery to audit.go and bound queries to 30 days 2026-12-01 16:20:57 +05:30
Swapnil Nakade
18aab1a293 Merge branch 'main' into keystone-pod/issues/12 2026-12-01 12:26:02 +05:30
Aditya Singh
7ee8e18863 refactor(query-builder): remove the legacy v3/v4 query code (#13757)
#### Description

- The backend plans to remove the v3 autocomplete APIs and the v3/v4
`query_range` APIs. The frontend no longer calls them, but the old code
is still there.
- This PR deletes the v3 clients, types and hooks for attribute keys,
values, aggregate attributes and suggestions. It also deletes the old
`AggregatorFilter` and `HavingFilter` components, which nothing renders.
- It deletes the legacy v3/v4 `query_range` path. Every caller already
sends its query to the v5 API.
- It removes the query builder's `version` prop and the `v3`/`v4` checks
behind it. Every caller already got the v5 behaviour, so users see no
change.
- It deletes the helpers, constants, mock handlers and tests that only
this code used.

#### Issues closed by this PR

Part of https://github.com/SigNoz/events-pod/issues/161

#### Additional Information

- Part of https://github.com/SigNoz/events-pod/issues/156.
- No screen renders differently, so no story changes.
- Two hook tests ran on the removed v4 path. They now check the v5
defaults that users get. Two new tests check the time aggregation
options for sum and gauge metrics.
- The query range hooks and `GetMetricQueryRange` still take a `version`
argument, which is always v5. A follow-up PR removes it.
- `ApiV4Instance` stays, because the ApDex settings still read metric
metadata from the v4 API.
2026-12-01 06:14:51 +00:00
ashu8912
5ff867a5af feat(authz): alert rule views FGA (#13756)
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
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
#### Description

- Gates the alert rules list's saved views on `rule:list`, the only
permission the four `/api/v2/rule_views` routes check.
- Without `rule:list` the views rail shows the same permission callout
as the table, and the views are not requested.
- The views wait for the check. When the check itself fails, the rail
shows and loads as before, like the table beside it.
- Moves the dashboards views rail guard to
`components/ListViews/ViewsRail` so both lists share it; it takes the
list's checks.

#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/684

#### Screenshots / Screen Recordings

[Storybook visual
diff](https://claude.ai/artifact/9pFFBKQYhH1pRuWkKGY1LJ), against
#13730: 2 changed, 138 pixel-identical, 14 noise, out of 154 shots of
Alert Rules and the Dashboards list. The change is the `NoList` story,
where the views rail now shows the permission callout; the Dashboards
list renders the same.

#### Additional Information

- Stacked on #13730.
- There are no per-view verbs, so anyone with `rule:list` can still
create, rename and delete views.
- The dashboards rail still shows its denial when the check request
fails; the rules rail fails open to match its table.
- Storybook: the Rules `NoList` play also checks the rail's callout.
2026-12-01 01:25:44 +00:00
ashu8912
e0fa2ef8c4 feat(alerts): gate the alert details page and history on rule permissions (#13730)
#### Description

- Gates the alert details page and its history tab on rule permissions.
Blocked actions show disabled with the reason.
- Page: the full-page denial without `read` on the rule, instead of
"Alert not found".
- Header: the enable toggle, the rule name and its labels need `update`;
Clone needs `read` and `create`, plus `attach` on the rule and on its
channels when it has any; Delete needs `delete`.
- Stats and overall status need only `read`, which the page gate covers.

#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/683

#### Screenshots / Screen Recordings

[Storybook visual
diff](https://claude.ai/artifact/BGJkqMwmkzmdorz6BAerX1), against
#13728: 6 changed, 53 pixel-identical, 9 noise, out of 68 shots of
Overview, History and Create. The changes are the full-page denial
without `read`, where the header used to stay up, and the header, Clone
and Delete locked. Both sides run this PR's stories, so each screen is
compared with itself; where the base code cannot reach a play's state,
before shows where the play stopped.

#### Additional Information

- Stacked on #13728.
- The ticket asks for the history to name the telemetry the server
refused. After review, a server 403 there renders like any other error;
only the authz components explain permissions.
- Storybook: Overview and History each move to `<Page>/Overview` with an
`Authz` folder, one story per permission.
- Top contributors failing now shows the generic error, as the timeline
does; it used to spin forever.
2026-11-30 20:11:44 +00:00
ashu8912
66ab2b4a5f feat(alerts): gate the rule create and edit form on rule permissions (#13728)
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
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
#### Description

- Moves the rule create and edit form onto rule permissions. Blocked
actions show disabled with the reason instead of failing on submit.
- Save: `rule:create` for a new rule, `update` on the rule for an edit,
plus `attach`/`detach` on the rule and on each channel the rule gains or
loses. Channels it keeps are not checked.
  - Test notification: what creating the rule needs.
- Channel picker: a channel the rule cannot gain or lose is disabled,
and explains why on hover (`AuthZSelect`): the denial on the red
tooltip, or "Checking permissions" while its check runs.
- A channel another threshold holds, or a saved one this threshold no
longer holds, needs no check: the rule keeps it either way.
- A new rule has no id, so its own `attach` is checked on Save, as for a
new routing policy.
  - Edit page: the full-page denial without `read` on the rule.
- "No channels yet" is one component, shared with routing policies, and
offers "Create one here" on `notification-channel:create` instead of the
admin role.

#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/682

#### Screenshots / Screen Recordings

[Storybook visual
diff](https://claude.ai/artifact/UVfZw3Z2wnxri9moL5jHa8), against
#13520: 14 changed, 79 pixel-identical, 41 noise, out of 134 shots of
Create, Overview, Routing Policies and every story that shows a
permission callout. The changes are Save and Test locked, each
threshold's channel picker explaining locked channels on hover, and the
shared "No channels yet" prompt. Both sides run this PR's stories, so
each screen is compared with itself; where the base code cannot reach a
play's state, before shows where the play stopped.

#### Additional Information

- Stacked on #13520.
- The ticket asks for a callout naming the permission when the server
refuses a save or test. After review, a server 403 renders like any
other error, in the error modal; only the authz components explain
permissions.
- The channel picker and the attach/detach diff are shared with routing
policies and downtimes (`useChannelPickerAccess`, `getLinkSaveChecks`),
from #13513 and #13516.
- The legacy `FormAlertRules` form is gone from main, so there is
nothing to gate there.
- Storybook: Create moves to `Create/Overview` with a `Create/Authz`
folder, one story per permission. The alert overview plays move out of
the story file and branch on `read`, `update` and `create`. The details
page's own authz stories come with its gate in the next PR.
- The form's fixed footer now clears a pinned side nav; it used to start
at `left: 63px` and slide under it, hiding Discard.
2026-11-30 19:41:21 +00:00
ashu8912
a38b24c357 feat(authz): alert rules list FGA (#13520)
#### Description

- Moves the alert rules list off role checks and onto rule permissions.
Blocked actions show disabled with the reason instead of hidden.
- Table: `rule:list`, else a permission callout instead of "Failed to
load alert rules".
  - New Alert and the empty-state button: `rule:create`.
- Row menu: Enable/Disable needs `update`; Edit and Edit in New Tab need
`read` and `update`; Clone needs `read` on the rule and `create`; Delete
needs `delete`.
- Home page Alert Rules widget: gated with `withAuthZContent`, showing a
permission callout without `rule:list`, where a 403 used to leave the
skeleton up for good. Create Alert Rule is gated on `rule:create`
instead of `role !== VIEWER`.
- Drops the `add_new_alert` and `action` role keys, which nothing uses
now.

#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/681

#### Screenshots / Screen Recordings

[Storybook visual
diff](https://claude.ai/artifact/WC3cvaHUhPNycdCPnWPxed), against
#13516: 26 changed, 61 pixel-identical, 7 noise, out of 94 shots of
Alert Rules and Home. The changes are the table becoming a callout
without `list`, and viewers seeing New Alert and the Actions column,
locked. The row-action toast stories move only because the base code
stops their plays with the menu open. Both sides run this PR's stories,
so each screen is compared with itself; where the base code cannot reach
a play's state, before shows where the play stopped.

#### Additional Information

- Stacked on #13516.
- Viewers used to get no Actions column and no New Alert button at all.
They now see both, disabled with the reason.
- The table is gated with `AuthZGuardContent`, with the table itself as
the loading fallback. Mounting the table only after the check broke the
saved-view URL sync.
- Clone checks only `read` and `create` here. #13253 also checks
`attach` on the rule's channels and read on the data it queries, which
the list cannot know up front, so the API decides those.
- Storybook: the page moves to `Rules/Overview` with a new `Rules/Authz`
folder, one story per permission. The `viewer` preset now lists and
reads rules, routing policies, planned downtime and channels, as the
backend's managed viewer role does, so the Viewer stories of all three
pages drop their own grants.
2026-11-30 18:25:35 +00:00
Swapnil Nakade
80adedb0db chore: update cloud integration agent version (#13807)
<!--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
- chore: update cloud integration agent version
2026-11-30 17:28:48 +00:00
Swapnil Nakade
31160581bc feat(quickfilter): add audit source and default quick filters (#13794)
#### Description

- Add `audit` (`SourceAudit`) to `quickfiltertypes.Source` and seed five
default audit quick filters for new organizations

<!--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/12
2026-11-30 17:21:26 +00:00
ashu8912
606f8e80d3 feat(authz): planned downtime FGA (#13516)
#### Description

- Registers `planned-maintenance` for the frontend: allow-list,
regenerated types, builders, and a Planned Downtime panel in the custom
role editor.
- Replaces `role !== VIEWER` on the planned downtime tab with permission
checks. Blocked actions show disabled with the reason instead of hidden.
  - Tab: `planned-maintenance:list`, else a permission callout.
  - New downtime: `create` and `attach` on all schedules.
- Row menu: Edit needs `update`, Delete needs `delete`, on that
schedule. The form opens from the row and the update route does not
check `read`.
- Form: read-only without `update`. Save needs exactly what the route
checks, worked out from the rules picked (`getDowntimeSaveChecks`). The
rule picker locks rules the user cannot `rule:attach`, and silenced ones
they cannot `rule:detach`.
- Silenced rules are checked when the form opens, since their tags can
be removed without the picker; the rest once the picker opens. A rule
waiting on its check is disabled.
- Locked rules explain why on hover, in the picker (`AuthZSelect`) and
on their tags, on the red tooltip for a denial. The All/Specific radios
lock with the rest of the form.
- While "Specific alert rules" has nothing picked, Save asks only for
`create`/`update` and leaves the empty pick to the validator.
- Without `rule:list` the picker says so instead of showing an empty
list, and editing keeps the schedule's rules, shown by id, so saving
does not drop them.
- Each control checks only the permission it needs through `useAuthZ` or
the AuthZ components. The form asks for `detach` on silenced rules and
`attach` on the rest.

#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/680

#### Screenshots / Screen Recordings

[Storybook visual
diff](https://claude.ai/artifact/CM2e889SbL7b4kKvzMFVeY), against
#13513: 53 changed, 42 pixel-identical, 11 noise, out of 106 shots of
the role pages and Planned Downtime. The changes are the Planned
Downtime row on the role pages, and downtimes locked with the reason: a
read-only form including the rule scope, locked rules explained on
hover, and rules kept without `rule:list`. Both sides run this PR's
stories, so each screen is compared with itself; where the base code
cannot reach a play's state, before shows where the play stopped.

#### Additional Information

- Stacked on #13513.
- The ticket says an empty alert list needs only
`planned-maintenance:create`. The route in #13250 reads it as every
rule, so creating one for all rules also needs `attach` on the schedule
and `rule:attach` on `*`.
- An edit reads an empty list as every rule on both sides of the diff
(`DowntimeRuleIDsExtractor`), so re-saving an all-rules schedule needs
only `update`, and widening to all rules needs `attach` on `*` and
`detach` on the old rules.
- When there is no room below the rule picker, antd opens its dropdown
upward over the fields above.
- Storybook: the page moves to `Planned Downtime/Overview` with a new
`Planned Downtime/Authz` folder, one story per permission. The `Viewer`
story now grants `list` and `read`, which real viewers hold and the
story preset does not.
- Two console warnings in the stories come from existing code: a `<div>`
inside `<thead>` from the shared table, and `useForm` not connected,
from `PlannedDowntime.tsx` resetting the form while its modal is closed.
2026-11-30 16:57:18 +00:00
Vinicius Lourenço
7bd71304bb ci(storybook): test the static build instead of the dev server (#13675)
#### Description

Storybook CI now tests the static build instead of the dev server. The
build doubles as the compile check, and it runs the same production code
users get, which is how the Vite worker and role editor fixes in their
own PRs were found.

Each shard builds Storybook and then serves files instead of running the
dev server.

| Every story, 4 shards | Dev server (median of 28 PR runs) | Static
build (this PR) |
| --- | --- | --- |
| Slowest shard | 8.6 min | 7.0 min |
| Runner time | 29.6 min | 24.4 min |

Four stories failed only on the static build, and this PR fixes them.
Three tooltip plays hovered once before React rendered, because
production React has no `act`. A Query Builder play raced the panel type
being applied. A Noz story inherited requests the previous story still
had in flight.

#### Additional Information

`pnpm test:storybook` now builds Storybook first. Set
`STORYBOOK_STATIC_DIR` to test an existing build instead.
2026-11-30 16:01:20 +00:00
Manika Malhotra
dc64cea7b9 chore(frontend): remove dead code and styles from dashboards, alerts and infra monitoring (#13798)
#### Description

- Removes dead code and styles owned by @SigNoz/pulse-frontend:
dashboards, alerts and infra monitoring. Part of #13738, split by code
owner into #13797–#13802 so each needs one reviewer; this one merges on
its own. No change in behavior or visuals is intended.
- 113 files, +12 / −2,385; 9 files deleted.
- The unused dashboard first-section migration flow:
`AddSectionControl`, `FirstSectionMigrationModal`,
`useFirstSectionMigration` and its event. Nothing renders it.
- The `AddColumnDropdown` and `PanelTypeSelectionModal` CSS modules,
which nothing imports since #13087.
  - The histogram legend test, whose subject nothing in the app uses.
- Exported code nothing imports (one commit each for infra monitoring,
alerts and dashboards), and CSS rules for classes nothing renders.
- The Hosts and K8s `:global(.periscope-btn) &.ghost` rules, which
compile to a hashed class nothing uses, so they never applied.
- Each commit is one kind of change. The last ones keep `export` on code
that stays and apply review fixes.

#### Additional Information

**Verification**

| Check | Result |
|---|---|
| `tsgo`, `oxlint`, `stylelint` | Run on every commit by the pre-commit
hooks; 0 errors on the head |
| `vite build` | Passes |
| jest, every test that imports a changed file | 873 test files pass.
One timing-sensitive test (see #13797) failed under heavy load, as it
does on `main` |
| **All six PRs merged on `main`:** | |
| full jest, 10 shards | 1,171 test files, 10,950 tests, 0 failed, 15
skipped |
| Storybook interaction runner | 137 story files, 1,428 tests pass |
| Playwright e2e, Chromium, CI settings, one backend built from `main` |
768 passed, 1 failed (it fails on `main` too), 6 passed on retry. The 8
spec files behind every failure in either run, rerun back to back on an
idle machine: 44 of 44 pass on this build, and on `main` (3 there on
retry) |
| CSS a direct visit loads, per lazily loaded page (384) | Same global
rules as `main` wherever one can apply |

**Kept on purpose**

- The `SPEC_FIELDS` exhaustiveness check in
`CreateAlertChannels/channelConfig.ts`: nothing imports it, but it fails
the build when a channel field would be dropped on save.
- `PANEL_ACTION_META`: nothing reads it, but its comment calls it the
source of truth for each panel action's kind gate (see below).
- `types/api/alerts/getTriggered.ts`, until #13797 removes its last
importer. A follow-up removes it.

**Found while auditing, not changed here**

- `usePanelActionItems` doesn't read `PANEL_ACTION_META`.
- The panel-type drawer has had no custom scrollbar since #13087: its
rule targeted the drawer by `data-testid`.
- Some alert stylesheets apply app-wide once loaded: `.ant-popover-arrow
{ display: none }` in `EvaluationSettings`, and similar rules in
`EvaluationCadence` and `Summary`.
2026-11-30 15:51:29 +00:00
swapnil-signoz
01790cd6dc fix(telemetrymetadata): avoid double-escaping ILike fields and use shared field test helpers 2026-11-30 13:00:32 +05:30
swapnil-signoz
4f20848baa Merge remote-tracking branch 'origin/main' into keystone-pod/issues/12 2026-11-30 12:24:10 +05:30
swapnil-signoz
bd8000d0c5 chore(openapi): regenerate openapi spec and frontend schema docs 2026-11-30 10:26:11 +05:30
swapnil-signoz
a1662e453e feat(telemetrymetadata): discover audit field keys and values from signoz_audit 2026-11-30 09:36:43 +05:30
453 changed files with 12175 additions and 6838 deletions

View File

@@ -88,7 +88,7 @@ Say the numbers plainly: how many screens changed, how many are new, how many ar
- A full capture is hundreds of shots. Scope with `--title "Pages/Alerts"` or `--stories "a,b,c"` (substring match on id or Title/Name, repeatable).
- **On macOS a capture can pin itself to one story at a time.** sbshot picks how many to shoot at once by sampling free memory, and off Linux it reads `os.freemem()`, which counts only truly free pages. macOS parks almost everything in "inactive" instead, which is reclaimable on demand, so the sampler can read ~100 MB on a 25 GB machine and shrink to one forever. `--jobs` does not help: it is only an upper cap. Check `parallelism` in `<run>/events.ndjson`; if it sits at 1 while `vm_stat` shows gigabytes inactive, that is this. A 124-shot run takes about 90 minutes pinned and about 6 minutes at four at a time, so it is worth spotting before a long capture.
- A fresh worktree cannot build Storybook: `i18n-translations-hash.json` is gitignored and generated. Run `node ./i18-generate-hash.cjs` in `<worktree>/frontend`, and symlink `node_modules` from the main checkout.
- `pnpm test:storybook` starts its own server on 6006 and hangs silently if something already holds that port. Free it first.
- `pnpm test:storybook` builds Storybook and serves the build on 6006, and refuses to start if something already holds that port. Free it first.
- ImageMagick on macOS may have no default font, so `--mode green-parallel` fails with ``unable to read font `' ``. Map Helvetica to a real file in `~/.config/ImageMagick/type.xml`.
- `sbshot link <dir> <name>` adds a run from elsewhere into the workspace, but it symlinks. Keep the source directory alive until you have exported.
- The export directory is build output. Delete it when done, or gitignore it.

View File

@@ -137,6 +137,7 @@ func runGenerateAuthz(_ context.Context) error {
coretypes.NewResourceRef(coretypes.ResourceOrganization).String(): true,
coretypes.NewResourceRef(coretypes.ResourceMetaResourceRule).String(): true,
coretypes.NewResourceRef(coretypes.ResourceMetaResourceRoutePolicy).String(): true,
coretypes.NewResourceRef(coretypes.ResourceMetaResourcePlannedMaintenance).String(): true,
}
allowedTypes := map[string]bool{}

View File

@@ -11469,6 +11469,7 @@ components:
- exceptions
- meter
- ai_observability
- audit
type: string
QuickfiltertypesSourceFilters:
properties:
@@ -16033,15 +16034,15 @@ paths:
- $ref: '#/components/schemas/TelemetrytypesSignal'
description: 'The signal to look up keys in: traces, logs or metrics. Empty
searches every signal.'
- description: The data source within the signal. Use meter for Cost Meter metrics;
empty means the default source.
- description: The data source within the signal. Use audit for audit logs or
meter for Cost Meter metrics; empty means the default source.
in: query
name: source
schema:
allOf:
- $ref: '#/components/schemas/TelemetrytypesSource'
description: The data source within the signal. Use meter for Cost Meter
metrics; empty means the default source.
description: The data source within the signal. Use audit for audit logs
or meter for Cost Meter metrics; empty means the default source.
- description: Maximum number of results per signal. Defaults to 1000 for keys
and 50 for values. For keys, intrinsic and materialized fields are added
on top, and an empty signal applies the limit to traces, logs and metrics
@@ -16055,27 +16056,31 @@ paths:
metrics separately, so the response can exceed it.
type: integer
- description: Start of the lookup window in Unix milliseconds, rounded down
to a 6 hour boundary. Ignored for key lookups and meter lookups; trace and
log values apply it at calendar-day granularity; metric attribute values
and relatedValues apply it. Omit for no lower bound.
to a 6 hour boundary. Ignored for key lookups, audit lookups (fixed 30 day
lookback) and meter lookups; trace and log values apply it at calendar-day
granularity; metric attribute values and relatedValues apply it. Omit for
no lower bound.
in: query
name: startUnixMilli
schema:
description: Start of the lookup window in Unix milliseconds, rounded down
to a 6 hour boundary. Ignored for key lookups and meter lookups; trace
and log values apply it at calendar-day granularity; metric attribute
values and relatedValues apply it. Omit for no lower bound.
to a 6 hour boundary. Ignored for key lookups, audit lookups (fixed 30
day lookback) and meter lookups; trace and log values apply it at calendar-day
granularity; metric attribute values and relatedValues apply it. Omit
for no lower bound.
format: int64
type: integer
- description: End of the lookup window in Unix milliseconds. Ignored for key
lookups, trace and log value lookups and meter lookups; applied to metric
attribute values and relatedValues. Omit for no upper bound.
lookups, trace and log value lookups, audit lookups (fixed 30 day lookback)
and meter lookups; applied to metric attribute values and relatedValues.
Omit for no upper bound.
in: query
name: endUnixMilli
schema:
description: End of the lookup window in Unix milliseconds. Ignored for
key lookups, trace and log value lookups and meter lookups; applied to
metric attribute values and relatedValues. Omit for no upper bound.
key lookups, trace and log value lookups, audit lookups (fixed 30 day
lookback) and meter lookups; applied to metric attribute values and relatedValues.
Omit for no upper bound.
format: int64
type: integer
- description: 'Restricts keys to one context: resource, attribute, scope, span,
@@ -16183,15 +16188,15 @@ paths:
- $ref: '#/components/schemas/TelemetrytypesSignal'
description: 'The signal to look up keys in: traces, logs or metrics. Empty
searches every signal.'
- description: The data source within the signal. Use meter for Cost Meter metrics;
empty means the default source.
- description: The data source within the signal. Use audit for audit logs or
meter for Cost Meter metrics; empty means the default source.
in: query
name: source
schema:
allOf:
- $ref: '#/components/schemas/TelemetrytypesSource'
description: The data source within the signal. Use meter for Cost Meter
metrics; empty means the default source.
description: The data source within the signal. Use audit for audit logs
or meter for Cost Meter metrics; empty means the default source.
- description: Maximum number of results per signal. Defaults to 1000 for keys
and 50 for values. For keys, intrinsic and materialized fields are added
on top, and an empty signal applies the limit to traces, logs and metrics
@@ -16205,27 +16210,31 @@ paths:
metrics separately, so the response can exceed it.
type: integer
- description: Start of the lookup window in Unix milliseconds, rounded down
to a 6 hour boundary. Ignored for key lookups and meter lookups; trace and
log values apply it at calendar-day granularity; metric attribute values
and relatedValues apply it. Omit for no lower bound.
to a 6 hour boundary. Ignored for key lookups, audit lookups (fixed 30 day
lookback) and meter lookups; trace and log values apply it at calendar-day
granularity; metric attribute values and relatedValues apply it. Omit for
no lower bound.
in: query
name: startUnixMilli
schema:
description: Start of the lookup window in Unix milliseconds, rounded down
to a 6 hour boundary. Ignored for key lookups and meter lookups; trace
and log values apply it at calendar-day granularity; metric attribute
values and relatedValues apply it. Omit for no lower bound.
to a 6 hour boundary. Ignored for key lookups, audit lookups (fixed 30
day lookback) and meter lookups; trace and log values apply it at calendar-day
granularity; metric attribute values and relatedValues apply it. Omit
for no lower bound.
format: int64
type: integer
- description: End of the lookup window in Unix milliseconds. Ignored for key
lookups, trace and log value lookups and meter lookups; applied to metric
attribute values and relatedValues. Omit for no upper bound.
lookups, trace and log value lookups, audit lookups (fixed 30 day lookback)
and meter lookups; applied to metric attribute values and relatedValues.
Omit for no upper bound.
in: query
name: endUnixMilli
schema:
description: End of the lookup window in Unix milliseconds. Ignored for
key lookups, trace and log value lookups and meter lookups; applied to
metric attribute values and relatedValues. Omit for no upper bound.
key lookups, trace and log value lookups, audit lookups (fixed 30 day
lookback) and meter lookups; applied to metric attribute values and relatedValues.
Omit for no upper bound.
format: int64
type: integer
- description: 'Restricts keys to one context: resource, attribute, scope, span,
@@ -28671,15 +28680,15 @@ paths:
- $ref: '#/components/schemas/TelemetrytypesSignal'
description: 'The signal to look up keys in: traces, logs or metrics. Empty
searches every signal.'
- description: The data source within the signal. Use meter for Cost Meter metrics;
empty means the default source.
- description: The data source within the signal. Use audit for audit logs or
meter for Cost Meter metrics; empty means the default source.
in: query
name: source
schema:
allOf:
- $ref: '#/components/schemas/TelemetrytypesSource'
description: The data source within the signal. Use meter for Cost Meter
metrics; empty means the default source.
description: The data source within the signal. Use audit for audit logs
or meter for Cost Meter metrics; empty means the default source.
- description: Maximum number of results per signal. Defaults to 1000 for keys
and 50 for values. For keys, intrinsic and materialized fields are added
on top, and an empty signal applies the limit to traces, logs and metrics
@@ -28693,27 +28702,31 @@ paths:
metrics separately, so the response can exceed it.
type: integer
- description: Start of the lookup window in Unix milliseconds, rounded down
to a 6 hour boundary. Ignored for key lookups and meter lookups; trace and
log values apply it at calendar-day granularity; metric attribute values
and relatedValues apply it. Omit for no lower bound.
to a 6 hour boundary. Ignored for key lookups, audit lookups (fixed 30 day
lookback) and meter lookups; trace and log values apply it at calendar-day
granularity; metric attribute values and relatedValues apply it. Omit for
no lower bound.
in: query
name: startUnixMilli
schema:
description: Start of the lookup window in Unix milliseconds, rounded down
to a 6 hour boundary. Ignored for key lookups and meter lookups; trace
and log values apply it at calendar-day granularity; metric attribute
values and relatedValues apply it. Omit for no lower bound.
to a 6 hour boundary. Ignored for key lookups, audit lookups (fixed 30
day lookback) and meter lookups; trace and log values apply it at calendar-day
granularity; metric attribute values and relatedValues apply it. Omit
for no lower bound.
format: int64
type: integer
- description: End of the lookup window in Unix milliseconds. Ignored for key
lookups, trace and log value lookups and meter lookups; applied to metric
attribute values and relatedValues. Omit for no upper bound.
lookups, trace and log value lookups, audit lookups (fixed 30 day lookback)
and meter lookups; applied to metric attribute values and relatedValues.
Omit for no upper bound.
in: query
name: endUnixMilli
schema:
description: End of the lookup window in Unix milliseconds. Ignored for
key lookups, trace and log value lookups and meter lookups; applied to
metric attribute values and relatedValues. Omit for no upper bound.
key lookups, trace and log value lookups, audit lookups (fixed 30 day
lookback) and meter lookups; applied to metric attribute values and relatedValues.
Omit for no upper bound.
format: int64
type: integer
- description: 'Restricts keys to one context: resource, attribute, scope, span,
@@ -28845,15 +28858,15 @@ paths:
- $ref: '#/components/schemas/TelemetrytypesSignal'
description: 'The signal to look up keys in: traces, logs or metrics. Empty
searches every signal.'
- description: The data source within the signal. Use meter for Cost Meter metrics;
empty means the default source.
- description: The data source within the signal. Use audit for audit logs or
meter for Cost Meter metrics; empty means the default source.
in: query
name: source
schema:
allOf:
- $ref: '#/components/schemas/TelemetrytypesSource'
description: The data source within the signal. Use meter for Cost Meter
metrics; empty means the default source.
description: The data source within the signal. Use audit for audit logs
or meter for Cost Meter metrics; empty means the default source.
- description: Maximum number of results per signal. Defaults to 1000 for keys
and 50 for values. For keys, intrinsic and materialized fields are added
on top, and an empty signal applies the limit to traces, logs and metrics
@@ -28867,27 +28880,31 @@ paths:
metrics separately, so the response can exceed it.
type: integer
- description: Start of the lookup window in Unix milliseconds, rounded down
to a 6 hour boundary. Ignored for key lookups and meter lookups; trace and
log values apply it at calendar-day granularity; metric attribute values
and relatedValues apply it. Omit for no lower bound.
to a 6 hour boundary. Ignored for key lookups, audit lookups (fixed 30 day
lookback) and meter lookups; trace and log values apply it at calendar-day
granularity; metric attribute values and relatedValues apply it. Omit for
no lower bound.
in: query
name: startUnixMilli
schema:
description: Start of the lookup window in Unix milliseconds, rounded down
to a 6 hour boundary. Ignored for key lookups and meter lookups; trace
and log values apply it at calendar-day granularity; metric attribute
values and relatedValues apply it. Omit for no lower bound.
to a 6 hour boundary. Ignored for key lookups, audit lookups (fixed 30
day lookback) and meter lookups; trace and log values apply it at calendar-day
granularity; metric attribute values and relatedValues apply it. Omit
for no lower bound.
format: int64
type: integer
- description: End of the lookup window in Unix milliseconds. Ignored for key
lookups, trace and log value lookups and meter lookups; applied to metric
attribute values and relatedValues. Omit for no upper bound.
lookups, trace and log value lookups, audit lookups (fixed 30 day lookback)
and meter lookups; applied to metric attribute values and relatedValues.
Omit for no upper bound.
in: query
name: endUnixMilli
schema:
description: End of the lookup window in Unix milliseconds. Ignored for
key lookups, trace and log value lookups and meter lookups; applied to
metric attribute values and relatedValues. Omit for no upper bound.
key lookups, trace and log value lookups, audit lookups (fixed 30 day
lookback) and meter lookups; applied to metric attribute values and relatedValues.
Omit for no upper bound.
format: int64
type: integer
- description: 'Restricts keys to one context: resource, attribute, scope, span,

View File

@@ -112,12 +112,17 @@ const preview: Preview = {
'Alerts',
[
'Rules',
['Overview', 'Authz'],
'Triggered',
'Overview',
['Overview', 'Authz'],
'History',
['Overview', 'Authz'],
'Create',
['Overview', 'Authz'],
'Edit',
'Planned Downtime',
['Overview', 'Authz'],
'Routing Policies',
['Overview', 'Authz'],
'Channels',
@@ -185,6 +190,7 @@ const preview: Preview = {
['Overview', 'Kafka', 'Kafka Detail', 'Celery'],
'Onboarding',
['Questionnaire', 'Add Data Source'],
'Audit Logs',
'Settings',
[
'Workspace',

View File

@@ -1,17 +1,12 @@
import { getStoryContext } from '@storybook/test-runner';
import type { TestRunnerConfig } from '@storybook/test-runner';
import type { Page } from 'playwright';
import type { Page, Request } from 'playwright';
const IGNORED_MESSAGES = [
// `preview-head.html` swaps a local stylesheet in for Google Fonts, but the
// browser still warns on the real cross-origin one it briefly requests
// before msw starts (no CORS headers), regardless of story content.
/Can't access cssRules/,
// Pre-existing dev-server noise, unrelated to any story.
/Couldn't load preload assets/,
// Fires because a Jest-driven browser sets a global testing flag React
// checks for; unrelated to anything a story does.
/current testing environment is not configured to support act/,
// React and antd route dev-only warnings (missing keys, DOM nesting, API
// deprecations) through `console.error` under this prefix; app-wide and
// tracked separately from story regressions.
@@ -37,10 +32,35 @@ interface CapturedMessage {
text: string;
}
const PREPARE_TIMEOUT_MS = 180_000;
const messagesByPage = new WeakMap<Page, CapturedMessage[]>();
const SETTLE_TIMEOUT_MS = 1_000;
const SETTLE_POLL_MS = 25;
const requestsByPage = new WeakMap<Page, Set<Request>>();
/**
* The runner opens the next story in this page as soon as the previous one has
* rendered, so what that one still has in flight answers into state both share:
* the Noz store holds a single thread id. Requests held open on purpose never
* end, so the wait gives up and forgets them.
*/
const settleRequests = async (page: Page): Promise<void> => {
const pending = requestsByPage.get(page);
if (!pending) {
return;
}
const deadline = Date.now() + SETTLE_TIMEOUT_MS;
while (pending.size > 0 && Date.now() < deadline) {
await new Promise((resolve) => {
setTimeout(resolve, SETTLE_POLL_MS);
});
}
pending.clear();
};
/**
* When the story under test started rendering, stamped by the preview's
* `beforeEach`. Messages captured before it belong to the previous story: the
@@ -61,16 +81,9 @@ const config: TestRunnerConfig = {
// msw logs every mocked request at `log`; keep it out of the failure dump
// unless the job is re-run with debug logging (GitHub sets RUNNER_DEBUG=1).
logLevel: process.env.RUNNER_DEBUG === '1' ? 'info' : 'warn',
// The runner's default prepare, minus Playwright's 30s navigation timeout: on
// a cold dev server the first load compiles the whole preview, which outlasts
// it on a shared CI runner.
async prepare({ page }): Promise<void> {
await page.goto(new URL('iframe.html', process.env.TARGET_URL).toString(), {
waitUntil: 'load',
timeout: PREPARE_TIMEOUT_MS,
});
},
async preVisit(page): Promise<void> {
await settleRequests(page);
const existing = messagesByPage.get(page);
if (existing) {
existing.length = 0;
@@ -79,6 +92,11 @@ const config: TestRunnerConfig = {
const messages: CapturedMessage[] = [];
messagesByPage.set(page, messages);
const pending = new Set<Request>();
requestsByPage.set(page, pending);
page.on('request', (request) => pending.add(request));
page.on('requestfinished', (request) => pending.delete(request));
page.on('requestfailed', (request) => pending.delete(request));
page.on('console', (message) => {
if (
message.type() === 'error' &&

View File

@@ -61,5 +61,6 @@
"AI_OBSERVABILITY_OVERVIEW": "SigNoz | AI Observability Overview",
"AI_OBSERVABILITY_EXPLORER": "SigNoz | AI Observability Explorer",
"AI_OBSERVABILITY_CONFIGURATION": "SigNoz | AI Observability Configuration",
"AI_OBSERVABILITY_ATTRIBUTE_MAPPING": "SigNoz | AI Observability Attribute Mapping"
"AI_OBSERVABILITY_ATTRIBUTE_MAPPING": "SigNoz | AI Observability Attribute Mapping",
"AUDIT_LOGS": "SigNoz | Audit Logs"
}

View File

@@ -82,5 +82,6 @@
"AI_OBSERVABILITY_OVERVIEW": "SigNoz | AI Observability Overview",
"AI_OBSERVABILITY_EXPLORER": "SigNoz | AI Observability Explorer",
"AI_OBSERVABILITY_CONFIGURATION": "SigNoz | AI Observability Configuration",
"AI_OBSERVABILITY_ATTRIBUTE_MAPPING": "SigNoz | AI Observability Attribute Mapping"
"AI_OBSERVABILITY_ATTRIBUTE_MAPPING": "SigNoz | AI Observability Attribute Mapping",
"AUDIT_LOGS": "SigNoz | Audit Logs"
}

View File

@@ -1,33 +1,34 @@
#!/usr/bin/env bash
set -euo pipefail
story_count=$(find src -name '*.stories.tsx' | wc -l)
if [ "$story_count" -eq 0 ]; then
echo "No *.stories.tsx found under src/" >&2
port=6006
static_dir=${STORYBOOK_STATIC_DIR:-}
if [ -z "$static_dir" ]; then
static_dir=storybook-static
pnpm storybook:build --quiet
fi
if [ ! -f "$static_dir/index.json" ]; then
echo "No Storybook build in $static_dir/" >&2
exit 1
fi
# jest splits the sorted story files into contiguous shards and exits 1 when a
# shard is empty, which happens on every shard above the file count. The runner
# rejects jest's own `--passWithNoTests`, so skip those shards here.
for arg in "$@"; do
if [[ $arg == --shard=* ]]; then
shard_index=${arg#--shard=}
if [ "${shard_index%%/*}" -gt "$story_count" ]; then
echo "Skipping ${arg#--shard=}: only ${story_count} story files"
exit 0
fi
fi
done
if curl -s -o /dev/null "http://127.0.0.1:$port/"; then
echo "Port $port is taken; stop whatever serves it first." >&2
exit 1
fi
pnpm storybook --ci --quiet &
SB_PID=$!
trap 'kill "$SB_PID" 2>/dev/null || true' EXIT
node_modules/.bin/vite preview --outDir "$static_dir" --host 127.0.0.1 --port "$port" --strictPort --no-open >/dev/null &
SERVER_PID=$!
trap 'kill "$SERVER_PID" 2>/dev/null || true' EXIT
until curl -sf http://127.0.0.1:6006/index.json >/dev/null 2>&1; do
until curl -sf "http://127.0.0.1:$port/index.json" >/dev/null 2>&1; do
kill -0 "$SERVER_PID" 2>/dev/null || {
echo "Static server exited" >&2
exit 1
}
sleep 1
done
# The first story of a heavy page compiles it on the cold dev server inside its
# own test, which outlasts 30s on a loaded runner.
pnpm exec test-storybook --ci --maxWorkers=2 --testTimeout 60000 "$@"
# Index-json mode names its tests after story titles, so story file arguments
# would match nothing.
pnpm exec test-storybook --ci --no-index-json --url "http://127.0.0.1:$port" --maxWorkers=2 --testTimeout 30000 "$@"

View File

@@ -449,9 +449,9 @@ describe('PrivateRoute', () => {
assertStaysOnRoute(ROUTES.HOME);
});
it('should redirect to unauthorized when VIEWER tries to access admin-only route /alerts/new', async () => {
it('should redirect to unauthorized when VIEWER tries to access admin-only route /licenses', async () => {
renderPrivateRoute({
initialRoute: ROUTES.ALERTS_NEW,
initialRoute: ROUTES.LIST_LICENSES,
appContext: {
isLoggedIn: true,
user: createMockUser({ role: USER_ROLES.VIEWER as ROLES }),
@@ -1688,6 +1688,9 @@ describe('PrivateRoute', () => {
AuthzRouteCase
> = {
LIST_ALL_ALERT: { path: ROUTES.LIST_ALL_ALERT, deniedRoles: DENIED_ROLES },
ALERTS_NEW: { path: ROUTES.ALERTS_NEW, deniedRoles: DENIED_ROLES },
ALERT_OVERVIEW: { path: ROUTES.ALERT_OVERVIEW, deniedRoles: DENIED_ROLES },
ALERT_HISTORY: { path: ROUTES.ALERT_HISTORY, deniedRoles: DENIED_ROLES },
CHANNELS_NEW: { path: ROUTES.CHANNELS_NEW, deniedRoles: DENIED_ROLES },
CHANNELS_EDIT: {
path: ROUTES.CHANNELS_EDIT.replace(':channelId', 'channel-id-1'),
@@ -1775,7 +1778,6 @@ describe('PrivateRoute', () => {
// Routes with no authz check - legacy role check still applies
const NON_AUTHZ_ROUTE_CASES: [string, string, ROLES][] = [
['ALERTS_NEW', ROUTES.ALERTS_NEW, USER_ROLES.VIEWER as ROLES],
['LIST_LICENSES', ROUTES.LIST_LICENSES, USER_ROLES.EDITOR as ROLES],
['ONBOARDING', ROUTES.ONBOARDING, USER_ROLES.VIEWER as ROLES],
['APPLICATION', ROUTES.APPLICATION, USER_ROLES.ANONYMOUS as ROLES],

View File

@@ -292,3 +292,10 @@ export const LLMObservabilityPage = Loadable(
/* webpackChunkName: "LLM Observability Page" */ 'pages/LLMObservability'
),
);
export const AuditLogsPage = Loadable(
() =>
import(
/* webpackChunkName: "Audit Logs Page" */ 'pages/AuditLogsModule/AuditLogsModule'
),
);

View File

@@ -7,6 +7,7 @@ import {
AlertOverview,
AllErrors,
ApiMonitoring,
AuditLogsPage,
ChannelsEdit,
ChannelsNew,
CreateNewAlerts,
@@ -408,6 +409,12 @@ const routes: AppRoutes[] = [
key: 'AI_OBSERVABILITY_CONFIGURATION',
isPrivate: true,
},
{
path: ROUTES.AUDIT_LOGS,
component: AuditLogsPage,
key: 'AUDIT_LOGS',
isPrivate: true,
},
];
export const SUPPORT_ROUTE: AppRoutes = {

View File

@@ -12587,6 +12587,7 @@ export enum QuickfiltertypesSourceDTO {
exceptions = 'exceptions',
meter = 'meter',
ai_observability = 'ai_observability',
audit = 'audit',
}
export interface QuickfiltertypesSourceFiltersDTO {
/**
@@ -15516,7 +15517,7 @@ export type GetFieldsKeysParams = {
*/
signal?: TelemetrytypesSignalDTO;
/**
* @description The data source within the signal. Use meter for Cost Meter metrics; empty means the default source.
* @description The data source within the signal. Use audit for audit logs or meter for Cost Meter metrics; empty means the default source.
*/
source?: TelemetrytypesSourceDTO;
/**
@@ -15527,13 +15528,13 @@ export type GetFieldsKeysParams = {
/**
* @type integer
* @format int64
* @description Start of the lookup window in Unix milliseconds, rounded down to a 6 hour boundary. Ignored for key lookups and meter lookups; trace and log values apply it at calendar-day granularity; metric attribute values and relatedValues apply it. Omit for no lower bound.
* @description Start of the lookup window in Unix milliseconds, rounded down to a 6 hour boundary. Ignored for key lookups, audit lookups (fixed 30 day lookback) and meter lookups; trace and log values apply it at calendar-day granularity; metric attribute values and relatedValues apply it. Omit for no lower bound.
*/
startUnixMilli?: number;
/**
* @type integer
* @format int64
* @description End of the lookup window in Unix milliseconds. Ignored for key lookups, trace and log value lookups and meter lookups; applied to metric attribute values and relatedValues. Omit for no upper bound.
* @description End of the lookup window in Unix milliseconds. Ignored for key lookups, trace and log value lookups, audit lookups (fixed 30 day lookback) and meter lookups; applied to metric attribute values and relatedValues. Omit for no upper bound.
*/
endUnixMilli?: number;
/**
@@ -15575,7 +15576,7 @@ export type GetFieldsValuesParams = {
*/
signal?: TelemetrytypesSignalDTO;
/**
* @description The data source within the signal. Use meter for Cost Meter metrics; empty means the default source.
* @description The data source within the signal. Use audit for audit logs or meter for Cost Meter metrics; empty means the default source.
*/
source?: TelemetrytypesSourceDTO;
/**
@@ -15586,13 +15587,13 @@ export type GetFieldsValuesParams = {
/**
* @type integer
* @format int64
* @description Start of the lookup window in Unix milliseconds, rounded down to a 6 hour boundary. Ignored for key lookups and meter lookups; trace and log values apply it at calendar-day granularity; metric attribute values and relatedValues apply it. Omit for no lower bound.
* @description Start of the lookup window in Unix milliseconds, rounded down to a 6 hour boundary. Ignored for key lookups, audit lookups (fixed 30 day lookback) and meter lookups; trace and log values apply it at calendar-day granularity; metric attribute values and relatedValues apply it. Omit for no lower bound.
*/
startUnixMilli?: number;
/**
* @type integer
* @format int64
* @description End of the lookup window in Unix milliseconds. Ignored for key lookups, trace and log value lookups and meter lookups; applied to metric attribute values and relatedValues. Omit for no upper bound.
* @description End of the lookup window in Unix milliseconds. Ignored for key lookups, trace and log value lookups, audit lookups (fixed 30 day lookback) and meter lookups; applied to metric attribute values and relatedValues. Omit for no upper bound.
*/
endUnixMilli?: number;
/**
@@ -17130,7 +17131,7 @@ export type GetRuleHistoryFilterKeysParams = {
*/
signal?: TelemetrytypesSignalDTO;
/**
* @description The data source within the signal. Use meter for Cost Meter metrics; empty means the default source.
* @description The data source within the signal. Use audit for audit logs or meter for Cost Meter metrics; empty means the default source.
*/
source?: TelemetrytypesSourceDTO;
/**
@@ -17141,13 +17142,13 @@ export type GetRuleHistoryFilterKeysParams = {
/**
* @type integer
* @format int64
* @description Start of the lookup window in Unix milliseconds, rounded down to a 6 hour boundary. Ignored for key lookups and meter lookups; trace and log values apply it at calendar-day granularity; metric attribute values and relatedValues apply it. Omit for no lower bound.
* @description Start of the lookup window in Unix milliseconds, rounded down to a 6 hour boundary. Ignored for key lookups, audit lookups (fixed 30 day lookback) and meter lookups; trace and log values apply it at calendar-day granularity; metric attribute values and relatedValues apply it. Omit for no lower bound.
*/
startUnixMilli?: number;
/**
* @type integer
* @format int64
* @description End of the lookup window in Unix milliseconds. Ignored for key lookups, trace and log value lookups and meter lookups; applied to metric attribute values and relatedValues. Omit for no upper bound.
* @description End of the lookup window in Unix milliseconds. Ignored for key lookups, trace and log value lookups, audit lookups (fixed 30 day lookback) and meter lookups; applied to metric attribute values and relatedValues. Omit for no upper bound.
*/
endUnixMilli?: number;
/**
@@ -17192,7 +17193,7 @@ export type GetRuleHistoryFilterValuesParams = {
*/
signal?: TelemetrytypesSignalDTO;
/**
* @description The data source within the signal. Use meter for Cost Meter metrics; empty means the default source.
* @description The data source within the signal. Use audit for audit logs or meter for Cost Meter metrics; empty means the default source.
*/
source?: TelemetrytypesSourceDTO;
/**
@@ -17203,13 +17204,13 @@ export type GetRuleHistoryFilterValuesParams = {
/**
* @type integer
* @format int64
* @description Start of the lookup window in Unix milliseconds, rounded down to a 6 hour boundary. Ignored for key lookups and meter lookups; trace and log values apply it at calendar-day granularity; metric attribute values and relatedValues apply it. Omit for no lower bound.
* @description Start of the lookup window in Unix milliseconds, rounded down to a 6 hour boundary. Ignored for key lookups, audit lookups (fixed 30 day lookback) and meter lookups; trace and log values apply it at calendar-day granularity; metric attribute values and relatedValues apply it. Omit for no lower bound.
*/
startUnixMilli?: number;
/**
* @type integer
* @format int64
* @description End of the lookup window in Unix milliseconds. Ignored for key lookups, trace and log value lookups and meter lookups; applied to metric attribute values and relatedValues. Omit for no upper bound.
* @description End of the lookup window in Unix milliseconds. Ignored for key lookups, trace and log value lookups, audit lookups (fixed 30 day lookback) and meter lookups; applied to metric attribute values and relatedValues. Omit for no upper bound.
*/
endUnixMilli?: number;
/**

View File

@@ -15,7 +15,7 @@ import { getBasePath } from 'utils/basePath';
import { eventEmitter } from 'utils/getEventEmitter';
import { getIsNoAuthMode } from 'utils/noAuthMode';
import apiV1, { apiAlertManager, apiV2, apiV3, apiV4, apiV5 } from './apiV1';
import apiV1, { apiAlertManager, apiV2, apiV4, apiV5 } from './apiV1';
import { Logout } from './utils';
const RESPONSE_TIMEOUT_THRESHOLD = 5000; // 5 seconds
@@ -193,19 +193,6 @@ ApiV2Instance.interceptors.response.use(
ApiV2Instance.interceptors.request.use(interceptorsRequestResponse);
ApiV2Instance.interceptors.request.use(interceptorsRequestBasePath);
// axios V3
export const ApiV3Instance = axios.create({
baseURL: `${ENVIRONMENT.baseURL}${apiV3}`,
});
ApiV3Instance.interceptors.response.use(
interceptorsResponse,
interceptorRejected,
);
ApiV3Instance.interceptors.request.use(interceptorsRequestResponse);
ApiV3Instance.interceptors.request.use(interceptorsRequestBasePath);
//
// axios V4
export const ApiV4Instance = axios.create({
baseURL: `${ENVIRONMENT.baseURL}${apiV4}`,

View File

@@ -1,49 +0,0 @@
import { ApiV3Instance, ApiV4Instance } from 'api';
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
import { AxiosError } from 'axios';
import { ENTITY_VERSION_V4 } from 'constants/app';
import { ErrorResponse, SuccessResponse, Warning } from 'types/api';
import {
MetricRangePayloadV3,
QueryRangePayload,
} from 'types/api/metrics/getQueryRange';
export const getMetricsQueryRange = async (
props: QueryRangePayload,
version: string,
signal: AbortSignal,
headers?: Record<string, string>,
): Promise<
(SuccessResponse<MetricRangePayloadV3> & { warning?: Warning }) | ErrorResponse
> => {
try {
if (version && version === ENTITY_VERSION_V4) {
const response = await ApiV4Instance.post('/query_range', props, {
signal,
});
return {
statusCode: 200,
error: null,
message: response.data.status,
payload: response.data,
params: props,
};
}
const response = await ApiV3Instance.post('/query_range', props, {
signal,
headers,
});
return {
statusCode: 200,
error: null,
message: response.data.status,
payload: response.data,
params: props,
};
} catch (error) {
return ErrorResponseHandler(error as AxiosError);
}
};

View File

@@ -1,50 +0,0 @@
import { ApiV3Instance } from 'api';
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
import { AxiosError, AxiosResponse } from 'axios';
import { baseAutoCompleteIdKeysOrder } from 'constants/queryBuilder';
import { createIdFromObjectFields } from 'lib/createIdFromObjectFields';
import createQueryParams from 'lib/createQueryParams';
// ** Helpers
import { ErrorResponse, SuccessResponse } from 'types/api';
// ** Types
import { IGetAggregateAttributePayload } from 'types/api/queryBuilder/getAggregatorAttribute';
import {
BaseAutocompleteData,
IQueryAutocompleteResponse,
} from 'types/api/queryBuilder/queryAutocompleteResponse';
export const getAggregateAttribute = async ({
aggregateOperator,
searchText,
dataSource,
source,
}: IGetAggregateAttributePayload): Promise<
SuccessResponse<IQueryAutocompleteResponse> | ErrorResponse
> => {
try {
const response: AxiosResponse<{
data: IQueryAutocompleteResponse;
}> = await ApiV3Instance.get(
`/autocomplete/aggregate_attributes?${createQueryParams({
aggregateOperator,
searchText,
dataSource: source === 'meter' ? 'meter' : dataSource,
})}`,
);
const payload: BaseAutocompleteData[] =
response.data.data.attributeKeys?.map(({ id: _, ...item }) => ({
...item,
id: createIdFromObjectFields(item, baseAutoCompleteIdKeysOrder),
})) || [];
return {
statusCode: 200,
error: null,
message: response.statusText,
payload: { attributeKeys: payload },
};
} catch (e) {
return ErrorResponseHandler(e as AxiosError);
}
};

View File

@@ -1,50 +0,0 @@
import { ApiV3Instance } from 'api';
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
import { AxiosError, AxiosResponse } from 'axios';
import { baseAutoCompleteIdKeysOrder } from 'constants/queryBuilder';
import { createIdFromObjectFields } from 'lib/createIdFromObjectFields';
import createQueryParams from 'lib/createQueryParams';
import { ErrorResponse, SuccessResponse } from 'types/api';
import { IGetAttributeKeysPayload } from 'types/api/queryBuilder/getAttributeKeys';
import {
BaseAutocompleteData,
IQueryAutocompleteResponse,
} from 'types/api/queryBuilder/queryAutocompleteResponse';
export const getAggregateKeys = async ({
aggregateOperator,
searchText,
dataSource,
aggregateAttribute,
tagType,
}: IGetAttributeKeysPayload): Promise<
SuccessResponse<IQueryAutocompleteResponse> | ErrorResponse
> => {
try {
const response: AxiosResponse<{
data: IQueryAutocompleteResponse;
}> = await ApiV3Instance.get(
`/autocomplete/attribute_keys?${createQueryParams({
aggregateOperator,
searchText,
dataSource,
aggregateAttribute,
})}&tagType=${tagType}`,
);
const payload: BaseAutocompleteData[] =
response.data.data.attributeKeys?.map(({ id: _, ...item }) => ({
...item,
id: createIdFromObjectFields(item, baseAutoCompleteIdKeysOrder),
})) || [];
return {
statusCode: 200,
error: null,
message: response.statusText,
payload: { attributeKeys: payload },
};
} catch (e) {
return ErrorResponseHandler(e as AxiosError);
}
};

View File

@@ -1,63 +0,0 @@
import { ApiV3Instance } from 'api';
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
import { AxiosError, AxiosResponse } from 'axios';
import { baseAutoCompleteIdKeysOrder } from 'constants/queryBuilder';
import { encode } from 'js-base64';
import { createIdFromObjectFields } from 'lib/createIdFromObjectFields';
import createQueryParams from 'lib/createQueryParams';
import { ErrorResponse, SuccessResponse } from 'types/api';
import {
IGetAttributeSuggestionsPayload,
IGetAttributeSuggestionsSuccessResponse,
} from 'types/api/queryBuilder/getAttributeSuggestions';
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
export const getAttributeSuggestions = async ({
searchText,
dataSource,
filters,
}: IGetAttributeSuggestionsPayload): Promise<
SuccessResponse<IGetAttributeSuggestionsSuccessResponse> | ErrorResponse
> => {
try {
let base64EncodedFiltersString;
try {
// the replace function is to remove the padding at the end of base64 encoded string which is auto added to make it a multiple of 4
// why ? because the current working of qs doesn't work well with padding
base64EncodedFiltersString = encode(JSON.stringify(filters)).replace(
/=+$/,
'',
);
} catch {
// default base64 encoded string for empty filters object
base64EncodedFiltersString = 'eyJpdGVtcyI6W10sIm9wIjoiQU5EIn0';
}
const response: AxiosResponse<{
data: IGetAttributeSuggestionsSuccessResponse;
}> = await ApiV3Instance.get(
`/filter_suggestions?${createQueryParams({
searchText,
dataSource,
existingFilter: base64EncodedFiltersString,
})}`,
);
const payload: BaseAutocompleteData[] =
response.data.data.attributes?.map(({ id: _, ...item }) => ({
...item,
id: createIdFromObjectFields(item, baseAutoCompleteIdKeysOrder),
})) || [];
return {
statusCode: 200,
error: null,
message: response.statusText,
payload: {
attributes: payload,
example_queries: response.data.data.example_queries,
},
};
} catch (e) {
return ErrorResponseHandler(e as AxiosError);
}
};

View File

@@ -1,42 +0,0 @@
import { ApiV3Instance } from 'api';
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
import { AxiosError } from 'axios';
import createQueryParams from 'lib/createQueryParams';
import { ErrorResponse, SuccessResponse } from 'types/api';
import {
IAttributeValuesResponse,
IGetAttributeValuesPayload,
} from 'types/api/queryBuilder/getAttributesValues';
export const getAttributesValues = async ({
aggregateOperator,
dataSource,
aggregateAttribute,
attributeKey,
filterAttributeKeyDataType,
tagType,
searchText,
}: IGetAttributeValuesPayload): Promise<
SuccessResponse<IAttributeValuesResponse> | ErrorResponse
> => {
try {
const response = await ApiV3Instance.get(
`/autocomplete/attribute_values?${createQueryParams({
aggregateOperator,
dataSource,
aggregateAttribute,
attributeKey,
searchText,
})}&filterAttributeKeyDataType=${filterAttributeKeyDataType}&tagType=${tagType}`,
);
return {
statusCode: 200,
error: null,
message: response.data.status,
payload: response.data.data,
};
} catch (error) {
return ErrorResponseHandler(error as AxiosError);
}
};

View File

@@ -396,16 +396,20 @@ describe('convertV5ResponseToLegacy', () => {
meta: { rowsScanned: 0, bytesScanned: 0, durationMs: 0, stepIntervals: {} },
} as unknown as QueryRangeResponseV5;
const baseSpec = {
name: 'A',
stepInterval: 60,
disabled: false,
aggregations: [],
};
const params = makeBaseParams(type as RequestType, [
{
type: 'builder_query',
spec: {
name: 'A',
signal: type === 'trace' ? 'traces' : 'logs',
stepInterval: 60,
disabled: false,
aggregations: [],
},
spec:
type === 'trace'
? { ...baseSpec, signal: 'traces' }
: { ...baseSpec, signal: 'logs' },
},
]);
@@ -467,5 +471,34 @@ describe('convertV5ResponseToLegacy', () => {
const data = (result.payload.data.result[0].list?.[0] as any)?.data ?? {};
expect('body' in data).toBe(false);
});
const getRowData = (
result: ReturnType<typeof convertV5ResponseToLegacy>,
): Record<string, unknown> =>
(result.payload.data.result[0].list?.[0] as any)?.data ?? {};
it('lifts resource.attributes onto resource', () => {
const result = makeRawResult([
{
timestamp: '2026-07-21T00:00:00Z',
data: {
resource: { attributes: { 'signoz.resource.kind': 'dashboard' } },
},
},
]);
expect(getRowData(result).resource).toStrictEqual({
'signoz.resource.kind': 'dashboard',
});
});
it('leaves a flat resource unchanged', () => {
const resource = { 'service.name': 'signoz' };
const result = makeRawResult([
{ timestamp: '2026-07-21T00:00:00Z', data: { resource } },
]);
expect(getRowData(result).resource).toStrictEqual(resource);
});
});
});

View File

@@ -1,5 +1,5 @@
import { extractOnlyMessageBody } from 'lib/logs/logBody';
import { cloneDeep, isEmpty } from 'lodash-es';
import { cloneDeep, get, isEmpty, isPlainObject } from 'lodash-es';
import { SuccessResponse, Warning } from 'types/api';
import { MetricRangePayloadV3 } from 'types/api/metrics/getQueryRange';
import {
@@ -305,6 +305,12 @@ function convertRawData(
data.body = extractOnlyMessageBody(row.data.body);
}
// Audit rows nest resource keys under resource.attributes; lift them so resource is flat and FlatLogData flattens it.
const resourceAttributes = get(row.data, ['resource', 'attributes']);
if (isPlainObject(resourceAttributes)) {
data.resource = resourceAttributes;
}
return {
timestamp: row.timestamp,
data,

View File

@@ -643,6 +643,28 @@ describe('prepareQueryRangePayloadV5', () => {
);
});
it('sends source audit on a logs query that targets audit', () => {
const [envelope] = convertBuilderQueriesToV5(
{
A: baseBuilderQuery({ dataSource: DataSource.LOGS, source: 'audit' }),
},
'raw',
);
expect(envelope.spec).toMatchObject({ signal: 'logs', source: 'audit' });
});
it('sends no source on a plain logs query', () => {
const [envelope] = convertBuilderQueriesToV5(
{
A: baseBuilderQuery({ dataSource: DataSource.LOGS, source: '' }),
},
'raw',
);
expect(envelope.spec).not.toHaveProperty('source');
});
it('builds payload for builder queries with filters array but no filter expression', () => {
const props: GetQueryResultsProps = {
query: {

View File

@@ -1,5 +1,6 @@
/* eslint-disable sonarjs/cognitive-complexity */
/* eslint-disable sonarjs/no-identical-functions */
import { TelemetrytypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import { convertFiltersToExpression } from 'components/QueryBuilderV2/utils';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
@@ -341,6 +342,9 @@ export function convertBuilderQueriesToV5(
spec = {
name: queryName,
signal: 'logs' as const,
...(queryData.source === TelemetrytypesSourceDTO.audit && {
source: TelemetrytypesSourceDTO.audit,
}),
...baseSpec,
aggregations: aggregations as LogAggregation[],
};

View File

@@ -29,33 +29,6 @@
min-width: 0;
}
.overflowTrigger {
all: unset;
cursor: pointer;
}
.labelPopover {
display: flex;
flex-direction: column;
gap: 6px;
padding: 8px;
max-height: 300px;
overflow-y: auto;
}
.labelTooltip {
display: flex;
flex-direction: column;
gap: 6px;
max-height: 300px;
overflow-y: auto;
}
.labelValue {
text-overflow: ellipsis;
overflow: hidden;
}
.tooltipContent {
display: flex;
align-items: center;

View File

@@ -1,29 +1,5 @@
import type { BadgeColorType } from '@signozhq/ui/badge';
export const STATE_ORDER = ['firing', 'pending', 'inactive', 'disabled'];
export const SEVERITY_ORDER = ['critical', 'error', 'warning', 'info'];
export const STATE_LABELS: Record<string, string> = {
firing: 'Firing',
pending: 'Pending',
inactive: 'OK',
disabled: 'Disabled',
};
export const STATE_COLORS: Record<string, string> = {
firing: 'var(--bg-cherry-500)',
pending: 'var(--bg-amber-500)',
inactive: 'var(--bg-forest-500)',
disabled: 'var(--l2-foreground)',
};
export const SEVERITY_COLORS: Record<string, string> = {
critical: 'var(--bg-cherry-500)',
error: 'var(--bg-cherry-400)',
warning: 'var(--bg-amber-500)',
info: 'var(--bg-robin-500)',
};
export const SEVERITY_BADGE_COLORS: Record<string, BadgeColorType> = {
critical: 'danger',
error: 'danger',

View File

@@ -24,11 +24,6 @@
flex-wrap: wrap;
}
.filtersLabel {
color: var(--l2-foreground);
margin-right: 2px;
}
.filterControls {
display: flex;
align-items: center;

View File

@@ -8,8 +8,3 @@
border-top: 1px solid var(--l2-border);
background: var(--l1-background);
}
.count {
font-size: var(--label-small-400-font-size);
color: var(--l3-foreground);
}

View File

@@ -74,10 +74,6 @@
padding: 1px 6px;
}
.deleteName {
color: var(--danger-background);
}
.row {
position: relative;
display: flex;

View File

@@ -1,19 +1,32 @@
import type { ReactElement } from 'react';
import { AuthZGuardContent } from 'lib/authz/components/AuthZGuard/AuthZGuardContent';
import PermissionDeniedCallout from 'lib/authz/components/PermissionDeniedCallout/PermissionDeniedCallout';
import { LIST_CHECKS } from 'pages/DashboardsListPage/constants/permissions';
import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';
import styles from './ViewsRailGuard.module.scss';
interface Props {
/** What reading the list's saved views needs. */
checks: BrandedPermission[];
/**
* Show the rail until the check denies it: while it runs, and when the check
* itself fails, leaving the API to decide. For a list that renders before its
* own check does.
*/
shouldRenderUntilDenied?: boolean;
children: ReactElement;
}
function ViewsRailGuard({ children }: Props): JSX.Element {
function ViewsRailGuard({
checks,
shouldRenderUntilDenied = false,
children,
}: Props): JSX.Element {
return (
<AuthZGuardContent
checks={LIST_CHECKS}
onFailRenderContent={false}
checks={checks}
onFailRenderContent={shouldRenderUntilDenied}
fallbackOnLoading={shouldRenderUntilDenied ? children : undefined}
fallback={({ deniedPermissions }): ReactElement => (
<div className={styles.denied} data-testid="views-rail-denied">
<PermissionDeniedCallout deniedPermissions={deniedPermissions} />

View File

@@ -4,10 +4,9 @@ import { render, screen } from 'tests/test-utils';
import { setupAuthzAllow } from 'lib/authz/utils/authz-test-utils';
import { DashboardListPermission } from 'lib/authz/hooks/useAuthZ/permissions/dashboard.permissions';
import ViewsRailGuard from 'pages/DashboardsListPage/components/DashboardsList/ViewsRailGuard';
import type { BuiltinListView } from '../../types';
import ViewsRail from '../ViewsRail';
import ViewsRailGuard from '../ViewsRailGuard';
const BUILTIN_VIEWS: BuiltinListView[] = [
{
@@ -38,7 +37,11 @@ function renderRail(
onDelete={jest.fn()}
onRename={jest.fn()}
testIdPrefix="dashboards"
guard={(content): JSX.Element => <ViewsRailGuard>{content}</ViewsRailGuard>}
guard={(content): JSX.Element => (
<ViewsRailGuard checks={[DashboardListPermission]}>
{content}
</ViewsRailGuard>
)}
{...props}
/>,
);

View File

@@ -1,7 +1,6 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useCallback, useMemo, useState } from 'react';
import { Button } from '@signozhq/ui/button';
import { ToggleGroup } from '@signozhq/ui/toggle-group';
import { Typography } from '@signozhq/ui/typography';
import { Tooltip } from 'antd';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import LogStateIndicator from 'components/Logs/LogStateIndicator/LogStateIndicator';
@@ -20,22 +19,17 @@ import useInitialQuery from 'container/LogsExplorerContext/useInitialQuery';
import { useOptionsMenu } from 'container/OptionsMenu';
import { FontSize } from 'container/OptionsMenu/types';
import { useArrowKeyNavigation } from 'container/TracesExplorer/SpanDrawer/useArrowKeyNavigation';
import { useCloseOnOutsideClick } from 'hooks/logs/useCloseOnOutsideClick';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { getBodyMessage } from 'lib/logs/logBody';
import { cloneDeep } from 'lodash-es';
import {
ArrowDown,
ArrowUp,
Filter,
Histogram,
Table,
TextSelect,
} from '@signozhq/icons';
import { Filter, Histogram, Table, TextSelect } from '@signozhq/icons';
import { Query, TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource, StringOperators } from 'types/common/queryBuilder';
import { RESOURCE_KEYS, VIEW_TYPES, VIEWS } from './constants';
import { LogDetailBodyProps } from './LogDetail.interfaces';
import { LogNavigationHint } from './LogNavigationHint/LogNavigationHint';
import LogHighlights from './LogHighlights/LogHighlights';
/* eslint-disable-next-line sonarjs/cognitive-complexity */
@@ -61,33 +55,7 @@ function LogDetailBody({
const [isEdit, setIsEdit] = useState<boolean>(false);
const { stagedQuery } = useQueryBuilder();
// Handle clicks outside to close drawer, except on explicitly ignored regions
useEffect(() => {
const handleClickOutside = (e: MouseEvent): void => {
const target = e.target as HTMLElement;
// Don't close if clicking on drawer content, overlays, or portal elements
if (
target.closest('[data-log-detail-ignore="true"]') ||
target.closest('.cm-tooltip-autocomplete') ||
target.closest('.drawer-popover') ||
target.closest('.query-status-popover') ||
target.closest('[data-radix-popper-content-wrapper]') ||
target.closest('[data-base-ui-portal]')
) {
return;
}
// Close the drawer for any other outside click
onClose();
};
document.addEventListener('mousedown', handleClickOutside);
return (): void => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [onClose]);
useCloseOnOutsideClick(true, onClose);
// Only listen in the OVERVIEW tab so we don't hijack arrow keys from the
// JSON editor / context view.
@@ -329,31 +297,7 @@ function LogDetailBody({
{selectedView === VIEW_TYPES.OVERVIEW && (
<div className="log-detail-drawer__footer-hint">
<div className="log-detail-drawer__footer-hint-content">
<Typography
variant="paragraph"
size="base"
weight="regular"
color="secondary"
as="span"
textOverflow="wrap"
>
Use
</Typography>
<ArrowUp size={14} className="log-detail-drawer__footer-hint-icon" />
<span>/</span>
<ArrowDown size={14} className="log-detail-drawer__footer-hint-icon" />
<Typography
variant="paragraph"
size="base"
weight="regular"
color="secondary"
as="span"
textOverflow="wrap"
>
to view previous/next log
</Typography>
</div>
<LogNavigationHint />
</div>
)}
</div>

View File

@@ -110,17 +110,5 @@
color: var(--l3-foreground);
background: var(--drawer-background);
z-index: 10;
.log-detail-drawer__footer-hint-content {
display: flex;
align-items: center;
gap: 4px;
}
.log-detail-drawer__footer-hint-icon {
display: inline;
vertical-align: middle;
color: var(--l3-foreground);
}
}
}

View File

@@ -0,0 +1,99 @@
import { act, renderHook } from 'tests/test-utils';
import { useLogNavigation } from '../useLogNavigation';
interface TestLog {
id: string;
label: string;
}
const logs: TestLog[] = [
{ id: 'a', label: 'first' },
{ id: 'b', label: 'second' },
{ id: 'c', label: 'third' },
];
const onNavigateLog = jest.fn() as jest.MockedFunction<(log: TestLog) => void>;
const onScrollToLog = jest.fn() as jest.MockedFunction<(id: string) => void>;
function renderNavigation(
activeLogId: string,
list: TestLog[] | undefined = logs,
) {
return renderHook(() =>
useLogNavigation<TestLog>({
logs: list,
activeLogId,
onNavigateLog,
onScrollToLog,
}),
);
}
beforeEach(() => {
jest.clearAllMocks();
});
describe('useLogNavigation', () => {
it('disables previous on the first log', () => {
const { result } = renderNavigation('a');
expect(result.current.isPrevDisabled).toBe(true);
expect(result.current.isNextDisabled).toBe(false);
});
it('disables next on the last log', () => {
const { result } = renderNavigation('c');
expect(result.current.isPrevDisabled).toBe(false);
expect(result.current.isNextDisabled).toBe(true);
});
it('enables both in the middle', () => {
const { result } = renderNavigation('b');
expect(result.current.isPrevDisabled).toBe(false);
expect(result.current.isNextDisabled).toBe(false);
});
it('moves to the next log and scrolls to it', () => {
const { result } = renderNavigation('b');
act(() => result.current.goToNext());
expect(onNavigateLog).toHaveBeenCalledWith(logs[2]);
expect(onScrollToLog).toHaveBeenCalledWith('c');
});
it('moves to the previous log and scrolls to it', () => {
const { result } = renderNavigation('b');
act(() => result.current.goToPrev());
expect(onNavigateLog).toHaveBeenCalledWith(logs[0]);
expect(onScrollToLog).toHaveBeenCalledWith('a');
});
it('does nothing past the ends', () => {
const { result } = renderNavigation('a');
act(() => result.current.goToPrev());
expect(onNavigateLog).not.toHaveBeenCalled();
expect(onScrollToLog).not.toHaveBeenCalled();
});
it('disables both when the active log is not in the list', () => {
const { result } = renderNavigation('missing');
expect(result.current.isPrevDisabled).toBe(true);
expect(result.current.isNextDisabled).toBe(true);
});
it('disables both without logs', () => {
const { result } = renderNavigation('a', []);
expect(result.current.isPrevDisabled).toBe(true);
expect(result.current.isNextDisabled).toBe(true);
});
});

View File

@@ -1,10 +1,10 @@
import { useCallback, useMemo } from 'react';
import { ILog } from 'types/api/logs/log';
import { LogWithId } from 'hooks/logs/types';
interface UseLogNavigationParams {
logs?: ILog[];
interface UseLogNavigationParams<T extends LogWithId> {
logs?: T[];
activeLogId: string;
onNavigateLog?: (log: ILog) => void;
onNavigateLog?: (log: T) => void;
onScrollToLog?: (id: string) => void;
}
@@ -15,12 +15,12 @@ interface UseLogNavigationReturn {
isNextDisabled: boolean;
}
export function useLogNavigation({
export function useLogNavigation<T extends LogWithId>({
logs,
activeLogId,
onNavigateLog,
onScrollToLog,
}: UseLogNavigationParams): UseLogNavigationReturn {
}: UseLogNavigationParams<T>): UseLogNavigationReturn {
const currentIndex = useMemo(
() => logs?.findIndex((l) => l.id === activeLogId) ?? -1,
[logs, activeLogId],

View File

@@ -0,0 +1,11 @@
.content {
display: flex;
align-items: center;
gap: var(--spacing-2);
}
.icon {
display: inline;
vertical-align: middle;
color: var(--l3-foreground);
}

View File

@@ -0,0 +1,34 @@
import { ArrowDown, ArrowUp } from '@signozhq/icons';
import { Typography } from '@signozhq/ui/typography';
import styles from './LogNavigationHint.module.scss';
export function LogNavigationHint(): JSX.Element {
return (
<div className={styles.content}>
<Typography
variant="paragraph"
size="base"
weight="regular"
color="secondary"
as="span"
textOverflow="wrap"
>
Use
</Typography>
<ArrowUp size={14} className={styles.icon} />
<span>/</span>
<ArrowDown size={14} className={styles.icon} />
<Typography
variant="paragraph"
size="base"
weight="regular"
color="secondary"
as="span"
textOverflow="wrap"
>
to view previous/next log
</Typography>
</div>
);
}

View File

@@ -0,0 +1,5 @@
import Spinner from 'components/Spinner';
export function LogsLoadingFooter(): JSX.Element {
return <Spinner height={20} tip="Getting Logs" testId="logs-loading-footer" />;
}

View File

@@ -191,6 +191,7 @@ function OptionsMenu({
type="button"
className="periscope-btn"
aria-label="Fewer lines per row"
data-testid="max-lines-fewer"
onClick={(): void => handleLinesPerRowChange(maxLinesPerRow - 1)}
>
<Minus size={12} />
@@ -211,6 +212,7 @@ function OptionsMenu({
type="button"
className="periscope-btn"
aria-label="More lines per row"
data-testid="max-lines-more"
onClick={(): void => handleLinesPerRowChange(maxLinesPerRow + 1)}
>
<Plus size={12} />

View File

@@ -3,6 +3,7 @@ import { screen, userEvent } from 'storybook/test';
import { withCanvas } from '@/storybook/decorators/withCanvas';
import type { GlobalMockArgs } from '@/storybook/globals';
import { hoverTruncated } from '@/storybook/play/truncatedText';
import { CustomMultiSelect, CustomSelect } from '../index';
@@ -142,7 +143,7 @@ export const TruncatedOption: Story = {
await userEvent.click(
await screen.findByRole('combobox', { name: 'Service' }),
);
await userEvent.hover(
await hoverTruncated(
await screen.findByRole('option', { name: LONG_LABEL_OPTION.label }),
);
await screen.findByRole('tooltip', { name: LONG_LABEL_OPTION.label });
@@ -156,7 +157,7 @@ export const TruncatedValue: Story = {
value: LONG_LABEL_OPTION.value,
},
play: async (): Promise<void> => {
await userEvent.hover(await screen.findByText(LONG_LABEL_OPTION.label));
await hoverTruncated(await screen.findByText(LONG_LABEL_OPTION.label));
await screen.findByRole('tooltip', { name: LONG_LABEL_OPTION.label });
},
};
@@ -173,7 +174,7 @@ export const MultiTruncatedOption: Story = {
await userEvent.click(
await screen.findByRole('combobox', { name: 'Services' }),
);
await userEvent.hover(
await hoverTruncated(
await screen.findByRole('option', { name: LONG_LABEL_OPTION.label }),
);
await screen.findByRole('tooltip', { name: LONG_LABEL_OPTION.label });

View File

@@ -62,16 +62,6 @@ $custom-border-color: #2c3044;
}
}
.all-selected-text {
position: absolute;
left: 12px;
top: 50%;
transform: translateY(-50%);
color: var(--l2-foreground);
z-index: 1;
pointer-events: none;
}
.ant-select-selector {
max-height: 200px;
overflow: auto;
@@ -450,8 +440,7 @@ $custom-border-color: #2c3044;
width: 100%;
background-color: var(--l2-background);
.select-all-option,
.custom-value-option {
.select-all-option {
padding: 8px 12px;
border-bottom: 1px solid $custom-border-color;
margin-bottom: 8px;
@@ -461,16 +450,6 @@ $custom-border-color: #2c3044;
z-index: 1;
}
.selected-values-section {
padding: 0 0 8px 0;
border-bottom: 1px solid $custom-border-color;
margin-bottom: 8px;
.selected-option {
padding: 4px 12px;
}
}
.select-group {
margin-bottom: 12px;
overflow: hidden;
@@ -656,14 +635,6 @@ $custom-border-color: #2c3044;
font-weight: 500;
}
// Custom option styles for keyboard navigation
.custom-option {
&.focused,
&.ant-select-item-option-active {
background-color: var(--l1-border) !important;
}
}
// Improve the sticky headers appearance
.custom-select-dropdown-container {
.group-label,
@@ -744,12 +715,6 @@ $custom-border-color: #2c3044;
.custom-multiselect-dropdown {
@include custom-scrollbar;
// Main content area
.options-container {
@include custom-scrollbar;
padding-right: 2px; // Add slight padding to prevent content touching scrollbar
}
// Non-sectioned options
.no-section-options {
@include nested-scrollbar;
@@ -762,11 +727,6 @@ $custom-border-color: #2c3044;
.custom-select-dropdown-container,
.custom-multiselect-dropdown-container {
@include custom-scrollbar;
// Add subtle shadow inside to indicate scrollable area
&.has-overflow {
box-shadow: inset 0 -10px 10px -10px rgba(0, 0, 0, 0.2);
}
}
// Light Mode Overrides
@@ -958,16 +918,11 @@ $custom-border-color: #2c3044;
}
.custom-multiselect-dropdown {
.select-all-option,
.custom-value-option {
.select-all-option {
border-bottom: 1px solid #f0f0f0;
background-color: #fafafa;
}
.selected-values-section {
border-bottom: 1px solid #f0f0f0;
}
.status-message {
color: rgba(0, 0, 0, 0.65);
border-top: 1px dashed #f0f0f0;
@@ -984,13 +939,6 @@ $custom-border-color: #2c3044;
background-color: rgba(24, 144, 255, 0.2);
}
.custom-option {
&.focused,
&.ant-select-item-option-active {
background-color: #f5f5f5 !important;
}
}
.custom-select-dropdown-container {
.group-label,
.ant-select-item-group {

View File

@@ -35,7 +35,6 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
isRawQuery = false,
showOnlyWhereClause = false,
showTraceOperator = false,
version,
onSignalSourceChange,
signalSourceChangeEnabled = false,
savePreviousQuery = false,
@@ -235,12 +234,11 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
isMultiQueryAllowed={isMultiQueryAllowed}
showTraceOperator={canShowTraceOperator}
hasTraceOperator={hasTraceOperator}
version={version}
isAvailableToDisable={false}
queryVariant={config?.queryVariant || 'dropdown'}
showOnlyWhereClause={showOnlyWhereClause}
isRawQuery={isRawQuery}
signalSource={activeBuilder.queryData[0].source as 'meter' | ''}
signalSource={activeBuilder.queryData[0].source}
onSignalSourceChange={onSignalSourceChange || ((): void => {})}
signalSourceChangeEnabled={signalSourceChangeEnabled}
queriesCount={1}
@@ -255,7 +253,6 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
query={query}
fieldsConfig={fieldsConfig}
allowedDataSources={queryDataSources}
version={version}
isMultiQueryAllowed={isMultiQueryAllowed}
isAvailableToDisable={false}
showTraceOperator={canShowTraceOperator}
@@ -263,7 +260,7 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
queryVariant={config?.queryVariant || 'dropdown'}
showOnlyWhereClause={showOnlyWhereClause}
isRawQuery={isRawQuery}
signalSource={query.source as 'meter' | ''}
signalSource={query.source}
onSignalSourceChange={onSignalSourceChange || ((): void => {})}
signalSourceChangeEnabled={signalSourceChangeEnabled}
queriesCount={activeBuilder.queryData.length}

View File

@@ -23,13 +23,11 @@ import './MetricsAggregateSection.styles.scss';
const MetricsAggregateSection = memo(function MetricsAggregateSection({
query,
index,
version,
panelType,
fieldsConfig,
}: {
query: IBuilderQuery;
index: number;
version: string;
panelType: PANEL_TYPES | null;
fieldsConfig?: QueryBuilderFieldsConfig;
}): JSX.Element {
@@ -46,7 +44,6 @@ const MetricsAggregateSection = memo(function MetricsAggregateSection({
} = useQueryOperations({
index,
query,
entityVersion: version,
});
// this function is only relevant for metrics and now operators are part of aggregations

View File

@@ -29,7 +29,6 @@ export const SOURCE_OPTIONS: SelectOption<string, string>[] = [
export const MetricsSelect = memo(function MetricsSelect({
query,
index,
version,
signalSource,
onSignalSourceChange,
signalSourceChangeEnabled = false,
@@ -37,7 +36,6 @@ export const MetricsSelect = memo(function MetricsSelect({
}: {
query: IBuilderQuery;
index: number;
version: string;
signalSource: 'meter' | '';
onSignalSourceChange: (value: string) => void;
signalSourceChangeEnabled: boolean;
@@ -46,7 +44,6 @@ export const MetricsSelect = memo(function MetricsSelect({
const { handleChangeAggregatorAttribute } = useQueryOperations({
index,
query,
entityVersion: version,
});
const { updateAllQueriesOperators, handleSetQueryData, panelType } =

View File

@@ -53,7 +53,6 @@ import './QueryAddOns.styles.scss';
function QueryAddOns({
query,
version,
isRawQuery,
showReduceTo,
panelType,
@@ -62,7 +61,6 @@ function QueryAddOns({
isForTraceOperator = false,
}: {
query: IBuilderQuery;
version: string;
isRawQuery: boolean;
showReduceTo: boolean;
panelType: PANEL_TYPES | null;
@@ -78,7 +76,6 @@ function QueryAddOns({
const { handleChangeQueryData } = useQueryOperations({
index,
query,
entityVersion: '',
isForTraceOperator,
});
@@ -433,7 +430,6 @@ function QueryAddOns({
</Tooltip>
<div className="input">
<OrderByFilter
entityVersion={version}
query={query}
onChange={handleChangeOrderByKeys}
isRawQuery={isRawQuery}

View File

@@ -8,7 +8,6 @@ import {
} from 'react';
import { Dropdown, type DropdownItemType } from '@signozhq/ui/dropdown';
import cx from 'classnames';
import { ENTITY_VERSION_V4, ENTITY_VERSION_V5 } from 'constants/app';
import QBEntityOptions from 'container/QueryBuilder/components/QBEntityOptions/QBEntityOptions';
import { QueryProps } from 'container/QueryBuilder/type';
import SpanScopeSelector from 'container/QueryBuilder/filters/QueryBuilderSearchV2/SpanScopeSelector';
@@ -42,7 +41,6 @@ export const QueryV2 = forwardRef(function QueryV2(
isRawQuery = false,
showTraceOperator = false,
hasTraceOperator = false,
version,
showOnlyWhereClause = false,
signalSource = '',
isMultiQueryAllowed = false,
@@ -77,7 +75,6 @@ export const QueryV2 = forwardRef(function QueryV2(
index,
query,
isRawQuery,
entityVersion: version,
savePreviousQuery,
});
@@ -193,8 +190,7 @@ export const QueryV2 = forwardRef(function QueryV2(
isMetricsDataSource={dataSource === DataSource.METRICS}
showFunctions={
!functions.hidden &&
((version && version === ENTITY_VERSION_V4) ||
query.dataSource === DataSource.LOGS ||
(query.dataSource === DataSource.LOGS ||
query.dataSource === DataSource.METRICS ||
hasQueryFunctions ||
false)
@@ -265,7 +261,6 @@ export const QueryV2 = forwardRef(function QueryV2(
<MetricsSelect
query={query}
index={index}
version={ENTITY_VERSION_V5}
signalSource={signalSource as 'meter' | ''}
onSignalSourceChange={onSignalSourceChange}
signalSourceChangeEnabled={signalSourceChangeEnabled}
@@ -317,7 +312,6 @@ export const QueryV2 = forwardRef(function QueryV2(
query={query}
index={index}
key={`metrics-aggregate-section-${query.queryName}-${query.dataSource}-${signalSource}`}
version="v4"
fieldsConfig={fieldsConfig}
/>
)}
@@ -327,7 +321,6 @@ export const QueryV2 = forwardRef(function QueryV2(
<QueryAddOns
index={index}
query={query}
version="v3"
isRawQuery={isRawQuery}
showReduceTo={showReduceTo}
panelType={panelType}

View File

@@ -31,7 +31,6 @@ export default function TraceOperator({
const { handleChangeQueryData } = useQueryOperations({
index: 0,
query: traceOperator,
entityVersion: '',
isForTraceOperator: true,
});
@@ -116,7 +115,6 @@ export default function TraceOperator({
<QueryAddOns
index={0}
query={traceOperator}
version="v3"
isForTraceOperator
isRawQuery={false}
showReduceTo={false}

View File

@@ -177,7 +177,6 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
<QueryV2
index={0}
query={queryA}
version="v4"
isAvailableToDisable={false}
isMultiQueryAllowed
queriesCount={queriesCount}
@@ -190,7 +189,7 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
};
it('renders limit input when dataSource is logs', () => {
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} />);
// Ensure the Limit add-on input is present and is of type number
const limitInput = screen.getByPlaceholderText(
@@ -204,7 +203,7 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
it('Cmd+Enter on the limit input triggers handleRunQuery via container handler', async () => {
const user = userEvent.setup();
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} />);
screen.getByTestId('input-Limit-field').focus();
await user.keyboard('{Meta>}{Enter}{/Meta}');
@@ -214,7 +213,7 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
it('Cmd+Enter on the legend input triggers handleRunQuery via container handler', async () => {
const user = userEvent.setup();
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} />);
screen.getByPlaceholderText('Write legend format').focus();
await user.keyboard('{Meta>}{Enter}{/Meta}');
@@ -224,7 +223,7 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
it('Cmd+Enter in the where clause editor triggers handleRunQuery via container handler', async () => {
const user = userEvent.setup();
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} />);
const editorWrapper = await screen.findByTestId('query-where-clause-editor');
within(editorWrapper).getByRole('textbox').focus();
@@ -249,7 +248,7 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
});
expect(() =>
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />),
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} />),
).not.toThrow();
// query list still renders from queryData, formulas block is skipped
@@ -342,7 +341,7 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
},
});
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} />);
const fxButton = screen.getByTestId('query-functions-fx-btn');
expect(fxButton).toBeInTheDocument();

View File

@@ -103,7 +103,6 @@ describe('QueryAddOns', () => {
render(
<QueryAddOns
query={baseQuery()}
version="v5"
isRawQuery={false}
showReduceTo
panelType={PANEL_TYPES.VALUE}
@@ -127,7 +126,6 @@ describe('QueryAddOns', () => {
dataSource: DataSource.METRICS,
groupBy: ['service.name'],
})}
version="v5"
isRawQuery={false}
showReduceTo={false}
panelType={PANEL_TYPES.TIME_SERIES}
@@ -143,7 +141,6 @@ describe('QueryAddOns', () => {
render(
<QueryAddOns
query={baseQuery()}
version="v5"
isRawQuery
showReduceTo={false}
panelType={PANEL_TYPES.LIST}
@@ -159,7 +156,6 @@ describe('QueryAddOns', () => {
render(
<QueryAddOns
query={baseQuery({ limit: 5 })}
version="v5"
isRawQuery={false}
showReduceTo={false}
panelType={PANEL_TYPES.TIME_SERIES}
@@ -193,7 +189,6 @@ describe('QueryAddOns', () => {
render(
<QueryAddOns
query={baseQuery()}
version="v5"
isRawQuery={false}
showReduceTo={false}
panelType={PANEL_TYPES.TIME_SERIES}
@@ -215,7 +210,6 @@ describe('QueryAddOns', () => {
render(
<QueryAddOns
query={baseQuery()}
version="v5"
isRawQuery={false}
showReduceTo={false}
panelType={PANEL_TYPES.TIME_SERIES}
@@ -237,7 +231,6 @@ describe('QueryAddOns', () => {
render(
<QueryAddOns
query={baseQuery()}
version="v5"
isRawQuery={false}
showReduceTo={false}
panelType={PANEL_TYPES.TOP_LIST}
@@ -311,7 +304,6 @@ describe('QueryAddOns', () => {
render(
<QueryAddOns
query={query}
version="v5"
isRawQuery={false}
showReduceTo={false}
panelType={PANEL_TYPES.TIME_SERIES}
@@ -332,7 +324,6 @@ describe('QueryAddOns', () => {
render(
<QueryAddOns
query={baseQuery()}
version="v5"
isRawQuery={false}
showReduceTo
panelType={PANEL_TYPES.TIME_SERIES}
@@ -348,7 +339,6 @@ describe('QueryAddOns', () => {
render(
<QueryAddOns
query={baseQuery({ reduceTo: ReduceOperators.SUM })}
version="v5"
isRawQuery={false}
showReduceTo
panelType={PANEL_TYPES.TIME_SERIES}
@@ -371,7 +361,6 @@ describe('QueryAddOns', () => {
render(
<QueryAddOns
query={query}
version="v5"
isRawQuery={false}
showReduceTo
panelType={PANEL_TYPES.TIME_SERIES}
@@ -423,7 +412,6 @@ describe('QueryAddOns', () => {
render(
<QueryAddOns
query={query}
version="v5"
isRawQuery={false}
showReduceTo={false}
panelType={PANEL_TYPES.TIME_SERIES}
@@ -447,7 +435,6 @@ describe('QueryAddOns', () => {
render(
<QueryAddOns
query={baseQuery()}
version="v5"
isRawQuery={false}
showReduceTo={false}
panelType={PANEL_TYPES.TIME_SERIES}
@@ -474,7 +461,6 @@ describe('QueryAddOns', () => {
render(
<QueryAddOns
query={query}
version="v5"
isRawQuery={false}
showReduceTo={false}
panelType={PANEL_TYPES.TIME_SERIES}
@@ -496,7 +482,6 @@ describe('QueryAddOns', () => {
render(
<QueryAddOns
query={baseQuery({ dataSource: DataSource.METRICS, ...overrides })}
version="v5"
isRawQuery={false}
showReduceTo={false}
panelType={PANEL_TYPES.HEATMAP}
@@ -518,7 +503,6 @@ describe('QueryAddOns', () => {
render(
<QueryAddOns
query={baseQuery({ dataSource: DataSource.METRICS })}
version="v5"
isRawQuery={false}
showReduceTo={false}
panelType={PANEL_TYPES.TIME_SERIES}

View File

@@ -42,7 +42,6 @@ jest.mock(
},
);
jest.mock('container/QueryBuilder/filters', () => ({
AggregatorFilter: (): JSX.Element => <div />,
MetricNameSelector: (): JSX.Element => <div />,
}));
// Mock hooks
@@ -150,7 +149,6 @@ describe('MetricsSelect - signal source switching (standalone)', () => {
render(
<QueryBuilderV2
panelType={PANEL_TYPES.TABLE}
version="v5"
signalSourceChangeEnabled
savePreviousQuery
/>,
@@ -185,11 +183,7 @@ describe('MetricsSelect - signal source switching (standalone)', () => {
const user = userEvent.setup();
// render WITHOUT savePreviousQuery enabled
render(
<QueryBuilderV2
panelType={PANEL_TYPES.TABLE}
version="v5"
signalSourceChangeEnabled
/>,
<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} signalSourceChangeEnabled />,
);
// open Source and choose Meter
@@ -307,7 +301,6 @@ describe('DataSource change - Logs to Traces', () => {
render(
<QueryBuilderV2
panelType={PANEL_TYPES.TABLE}
version="v5"
signalSourceChangeEnabled
savePreviousQuery
/>,
@@ -333,11 +326,7 @@ describe('DataSource change - Logs to Traces', () => {
const user = userEvent.setup();
render(
<QueryBuilderV2
panelType={PANEL_TYPES.TABLE}
version="v5"
signalSourceChangeEnabled
/>,
<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} signalSourceChangeEnabled />,
);
const logsTrigger = within(

View File

@@ -21,22 +21,18 @@ jest.mock('../QueryV2/QueryV2', () => ({
jest.mock('../QueryV2/QueryFooter/QueryFooter', () => (): null => null);
function renderWith(currentQuery: Query): void {
render(
<QueryBuilderV2 panelType={PANEL_TYPES.TIME_SERIES} version="v3" />,
undefined,
{
queryBuilderOverrides: {
currentQuery,
panelType: PANEL_TYPES.TIME_SERIES,
initialDataSource: null,
handleSetConfig: jest.fn(),
addNewBuilderQuery: jest.fn(),
addNewFormula: jest.fn(),
addTraceOperator: jest.fn(),
handleRunQuery: jest.fn(),
},
render(<QueryBuilderV2 panelType={PANEL_TYPES.TIME_SERIES} />, undefined, {
queryBuilderOverrides: {
currentQuery,
panelType: PANEL_TYPES.TIME_SERIES,
initialDataSource: null,
handleSetConfig: jest.fn(),
addNewBuilderQuery: jest.fn(),
addNewFormula: jest.fn(),
addTraceOperator: jest.fn(),
handleRunQuery: jest.fn(),
},
);
});
}
const builderWithQuery = (

View File

@@ -51,7 +51,7 @@ describe('QueryBuilderV2 provider config sync', () => {
it('leaves the data source unset for a bar panel without a static config', () => {
const handleSetConfig = mockContext({});
render(<QueryBuilderV2 panelType={PANEL_TYPES.BAR} version="v3" />);
render(<QueryBuilderV2 panelType={PANEL_TYPES.BAR} />);
expect(handleSetConfig).toHaveBeenCalledWith(PANEL_TYPES.BAR, null);
});
@@ -61,7 +61,6 @@ describe('QueryBuilderV2 provider config sync', () => {
render(
<QueryBuilderV2
version="v3"
panelType={PANEL_TYPES.BAR}
config={{ initialDataSource: DataSource.LOGS, queryVariant: 'static' }}
/>,
@@ -78,7 +77,6 @@ describe('QueryBuilderV2 provider config sync', () => {
render(
<QueryBuilderV2
version="v3"
panelType={PANEL_TYPES.BAR}
config={{ initialDataSource: DataSource.TRACES, queryVariant: 'static' }}
/>,
@@ -98,7 +96,6 @@ describe('QueryBuilderV2 provider config sync', () => {
render(
<QueryBuilderV2
version="v3"
panelType={PANEL_TYPES.TIME_SERIES}
config={{ initialDataSource: DataSource.TRACES, queryVariant: 'static' }}
/>,

View File

@@ -1,16 +1,13 @@
import { negateOperator, OPERATORS } from 'constants/antlrQueryConstants';
import { initialQueryBuilderFormValuesMap } from 'constants/queryBuilder';
import {
BaseAutocompleteData,
DataTypes,
} from 'types/api/queryBuilder/queryAutocompleteResponse';
import { Query, TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
import { extractQueryPairs } from 'utils/queryContextUtils';
import {
adjustQueryForV5,
convertAggregationToExpression,
convertExpressionToFilters,
convertFiltersToExpression,
@@ -1687,31 +1684,3 @@ describe('formatValueForExpression', () => {
});
});
});
describe('adjustQueryForV5', () => {
it('adjusts the AI builder slot for AI query builder queries', () => {
const emptyBuilder = {
queryData: [],
queryFormulas: [],
queryTraceOperator: [],
};
const query: Query = {
id: 'q',
queryType: EQueryType.AI_QUERY_BUILDER,
promql: [],
clickhouse_sql: [],
builder: emptyBuilder,
builder_ai_query: {
...emptyBuilder,
queryData: [initialQueryBuilderFormValuesMap.logs],
},
};
const result = adjustQueryForV5(query);
expect(result.builder).toBe(emptyBuilder);
expect(result.builder_ai_query?.queryData[0]).not.toHaveProperty(
'aggregateOperator',
);
});
});

View File

@@ -1,5 +1,4 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, waitFor } from 'storybook/test';
import { withCanvas } from '@/storybook/decorators/withCanvas';
@@ -9,15 +8,18 @@ import { DataSource } from 'types/common/queryBuilder';
import { QueryBuilderV2 } from '../QueryBuilderV2';
import {
addOnToggles,
appendToAggregation,
expectGaugeDefaults,
expectHistogramDefaults,
expectSingleAggregation,
expectTablePanelAddOns,
expectTimeSeriesAddOns,
expectValuePanelAddOns,
} from './__story_mockdata__/queryBuilder.play';
import {
DEFAULT_ARGS,
expectFirstQuery,
PANEL_EDITOR_ARGS,
PANEL_EDITOR_PATH,
payloadIn,
routeWith,
selectMetric,
} from './QueryBuilderV2.stories.mocks';
import QueryProbe from './QueryProbe';
@@ -60,11 +62,7 @@ export const LogsOnValuePanel: Story = {
parameters: {
signoz: { route: routeWith(PANEL_EDITOR_PATH, initialQueriesMap.logs) },
},
play: async ({ canvasElement }) => {
await waitFor(() =>
expect(addOnToggles(canvasElement)).toStrictEqual(['legend_format']),
);
},
play: expectValuePanelAddOns,
};
/** Metrics on a Table: reduce-to is offered; group by lives in the aggregation row. */
@@ -73,17 +71,7 @@ export const MetricsOnTablePanel: Story = {
parameters: {
signoz: { route: routeWith(PANEL_EDITOR_PATH, initialQueriesMap.metrics) },
},
play: async ({ canvasElement }) => {
await waitFor(() =>
expect(addOnToggles(canvasElement)).toStrictEqual([
'having',
'order_by',
'limit',
'legend_format',
'reduce_to',
]),
);
},
play: expectTablePanelAddOns,
};
/** Traces on a time series: every add-on, with group by as a toggle. */
@@ -92,54 +80,21 @@ export const TracesOnTimeSeriesPanel: Story = {
parameters: {
signoz: { route: routeWith(PANEL_EDITOR_PATH, initialQueriesMap.traces) },
},
play: async ({ canvasElement }) => {
await waitFor(() =>
expect(addOnToggles(canvasElement)).toStrictEqual([
'group_by',
'having',
'order_by',
'limit',
'legend_format',
]),
);
},
play: expectTimeSeriesAddOns,
};
/** Picking a gauge defaults to avg over time and avg across series. */
export const GaugeMetricDefaults: Story = {
args: METRICS_EXPLORER_ARGS,
parameters: { signoz: { route: metricsExplorerRoute } },
play: async ({ canvasElement }) => {
await selectMetric(canvasElement, 'container_cpu_utilization');
await expectFirstQuery(canvasElement, {
aggregations: [
expect.objectContaining({
metricName: 'container_cpu_utilization',
timeAggregation: 'avg',
spaceAggregation: 'avg',
}),
],
});
},
play: expectGaugeDefaults,
};
/** Picking a histogram defaults to the p90 across series. */
export const HistogramMetricDefaults: Story = {
args: METRICS_EXPLORER_ARGS,
parameters: { signoz: { route: metricsExplorerRoute } },
play: async ({ canvasElement }) => {
await selectMetric(canvasElement, 'signoz_latency_bucket');
await expectFirstQuery(canvasElement, {
aggregations: [
expect.objectContaining({
metricName: 'signoz_latency_bucket',
spaceAggregation: 'p90',
}),
],
});
},
play: expectHistogramDefaults,
};
/** A Value panel takes a single aggregation: a second one is not accepted. */
@@ -148,22 +103,5 @@ export const ValuePanelTakesOneAggregation: Story = {
parameters: {
signoz: { route: routeWith(PANEL_EDITOR_PATH, initialQueriesMap.logs) },
},
play: async ({ canvasElement }) => {
await expectFirstQuery(canvasElement, {
aggregations: [{ expression: 'count()' }],
});
const { before, after } = appendToAggregation(
canvasElement,
', count_distinct(service.name)',
);
await expect(after).toBe(before);
await expectFirstQuery(canvasElement, {
aggregations: [{ expression: 'count()' }],
});
await expect(
payloadIn(canvasElement).queries[0].spec.aggregations,
).toHaveLength(1);
},
play: expectSingleAggregation,
};

View File

@@ -3,6 +3,7 @@
* Do not hand-edit: regenerate instead.
*/
import type { TransactionSpec } from '@codemirror/state';
import { EditorView } from '@codemirror/view';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
@@ -134,6 +135,40 @@ export const selectMetric = async (
await waitFor(() => expect(screen.queryByRole('listbox')).toBeNull());
};
const aggregationEditor = (canvasElement: HTMLElement): EditorView => {
const content = within(canvasElement)
.getByTestId('query-aggregation-editor')
.querySelector<HTMLElement>('.cm-content');
const view = content ? EditorView.findFromDOM(content) : null;
if (!view) {
throw new Error('aggregation editor not mounted');
}
return view;
};
const appendTo = (view: EditorView, text: string): TransactionSpec => ({
changes: { from: view.state.doc.length, insert: text },
selection: { anchor: view.state.doc.length + text.length },
userEvent: 'input.type',
});
/**
* Waits until query `A`'s aggregation editor refuses `text`. The builder
* applies a panel's limits one commit after mounting, which a fast static
* build can beat. `state.update` runs the editor's filters without changing
* the document.
*/
export const waitForAggregationLimit = async (
canvasElement: HTMLElement,
text: string,
): Promise<void> => {
await waitFor(() => {
const view = aggregationEditor(canvasElement);
const attempt = view.state.update(appendTo(view, text));
return expect(attempt.newDoc.toString()).toBe(view.state.doc.toString());
});
};
/**
* Appends `text` to query `A`'s aggregation editor and returns its document
* before and after. Dispatched as a CodeMirror transaction: `userEvent.type`
@@ -144,19 +179,9 @@ export const appendToAggregation = (
canvasElement: HTMLElement,
text: string,
): { before: string; after: string } => {
const content = within(canvasElement)
.getByTestId('query-aggregation-editor')
.querySelector<HTMLElement>('.cm-content');
const view = content ? EditorView.findFromDOM(content) : null;
if (!view) {
throw new Error('aggregation editor not mounted');
}
const view = aggregationEditor(canvasElement);
const before = view.state.doc.toString();
view.dispatch({
changes: { from: before.length, insert: text },
selection: { anchor: before.length + text.length },
userEvent: 'input.type',
});
view.dispatch(appendTo(view, text));
// Read synchronously: the document is the editor's own verdict, before
// React state catches up.
return { before, after: view.state.doc.toString() };
@@ -164,7 +189,6 @@ export const appendToAggregation = (
export const DEFAULT_ARGS: Partial<QueryBuilderProps> = {
panelType: PANEL_TYPES.TIME_SERIES,
version: 'v3',
};
/**

View File

@@ -15,7 +15,14 @@ import {
ResolvedQueryBuilderField,
resolveQueryBuilderField,
} from '../../queryBuilderFields.utils';
import { expectFirstQuery, payloadIn } from '../QueryBuilderV2.stories.mocks';
import {
addOnToggles,
appendToAggregation,
expectFirstQuery,
payloadIn,
selectMetric,
waitForAggregationLimit,
} from '../QueryBuilderV2.stories.mocks';
interface PlayContext {
canvasElement: HTMLElement;
@@ -197,3 +204,95 @@ export const hoverAddFunction = async ({
await hoverForLearnMore(button, 'Add new function');
};
export const expectValuePanelAddOns = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await waitFor(() =>
expect(addOnToggles(canvasElement)).toStrictEqual(['legend_format']),
);
};
export const expectTablePanelAddOns = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await waitFor(() =>
expect(addOnToggles(canvasElement)).toStrictEqual([
'having',
'order_by',
'limit',
'legend_format',
'reduce_to',
]),
);
};
export const expectTimeSeriesAddOns = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await waitFor(() =>
expect(addOnToggles(canvasElement)).toStrictEqual([
'group_by',
'having',
'order_by',
'limit',
'legend_format',
]),
);
};
export const expectGaugeDefaults = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await selectMetric(canvasElement, 'container_cpu_utilization');
await expectFirstQuery(canvasElement, {
aggregations: [
expect.objectContaining({
metricName: 'container_cpu_utilization',
timeAggregation: 'avg',
spaceAggregation: 'avg',
}),
],
});
};
export const expectHistogramDefaults = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await selectMetric(canvasElement, 'signoz_latency_bucket');
await expectFirstQuery(canvasElement, {
aggregations: [
expect.objectContaining({
metricName: 'signoz_latency_bucket',
spaceAggregation: 'p90',
}),
],
});
};
const SECOND_AGGREGATION = ', count_distinct(service.name)';
export const expectSingleAggregation = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await expectFirstQuery(canvasElement, {
aggregations: [{ expression: 'count()' }],
});
await waitForAggregationLimit(canvasElement, SECOND_AGGREGATION);
const { before, after } = appendToAggregation(
canvasElement,
SECOND_AGGREGATION,
);
await expect(after).toBe(before);
await expectFirstQuery(canvasElement, {
aggregations: [{ expression: 'count()' }],
});
await expect(
payloadIn(canvasElement).queries[0].spec.aggregations,
).toHaveLength(1);
};

View File

@@ -9,11 +9,6 @@ import {
QUERY_BUILDER_FUNCTIONS,
} from 'constants/antlrQueryConstants';
import { getOperatorValue } from 'container/QueryBuilder/filters/QueryBuilderSearchV2/utils';
import {
getActiveBuilder,
getBuilderSlotKeyForQueryType,
isBuilderQueryType,
} from 'lib/query/builderSlot';
import FilterQueryLexer from 'parser/FilterQueryLexer';
import FilterQueryParser, {
AndExpressionContext,
@@ -29,7 +24,6 @@ import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteRe
import {
Having,
IBuilderQuery,
Query,
TagFilter,
TagFilterItem,
} from 'types/api/queryBuilder/queryBuilderData';
@@ -1032,57 +1026,3 @@ export function getQueryLabelWithAggregation(
return labels;
}
export const adjustQueryForV5 = (currentQuery: Query): Query => {
if (isBuilderQueryType(currentQuery.queryType)) {
const activeBuilder = getActiveBuilder(currentQuery);
const newQueryData = activeBuilder.queryData.map((query) => {
const aggregations = query.aggregations?.map((aggregation) => {
if (query.dataSource === DataSource.METRICS) {
const metricAggregation = aggregation as MetricAggregation;
return {
...aggregation,
metricName:
metricAggregation.metricName || query.aggregateAttribute?.key || '',
timeAggregation:
metricAggregation.timeAggregation || query.timeAggregation || '',
spaceAggregation:
metricAggregation.spaceAggregation || query.spaceAggregation || '',
reduceTo: metricAggregation.reduceTo || query.reduceTo || 'avg',
};
}
return aggregation;
});
const {
aggregateAttribute: _aggregateAttribute,
aggregateOperator: _aggregateOperator,
timeAggregation: _timeAggregation,
spaceAggregation: _spaceAggregation,
reduceTo: _reduceTo,
filters: _filters,
...retainedQuery
} = query;
const newAggregations =
query.dataSource === DataSource.METRICS
? (aggregations as MetricAggregation[])
: (aggregations as (TraceAggregation | LogAggregation)[]);
return {
...retainedQuery,
aggregations: newAggregations,
};
});
return {
...currentQuery,
[getBuilderSlotKeyForQueryType(currentQuery.queryType)]: {
...activeBuilder,
queryData: newQueryData,
},
};
}
return currentQuery;
};

View File

@@ -1,7 +1,9 @@
import { useMemo } from 'react';
import { TelemetrytypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import { FieldValuesConfig } from 'api/querySuggestions/types';
import { QUICK_FILTER_SOURCE_TO_SIGNAL } from 'components/QuickFilters/constants';
import {
QUICK_FILTER_SOURCE_TO_SIGNAL,
QUICK_FILTER_SOURCE_TO_SOURCE,
} from 'components/QuickFilters/constants';
import {
IQuickFiltersConfig,
QuickFiltersSource,
@@ -27,12 +29,6 @@ interface UseFieldValuesReturn {
isFetching: boolean;
}
const QUICK_FILTERS_SOURCE_TO_SOURCE: Partial<
Record<QuickFiltersSource, TelemetrytypesSourceDTO>
> = {
[QuickFiltersSource.METER_EXPLORER]: TelemetrytypesSourceDTO.meter,
};
export function useFieldValues({
filter,
searchText,
@@ -65,7 +61,7 @@ export function useFieldValues({
searchText,
existingQuery,
metricNamespace,
source: QUICK_FILTERS_SOURCE_TO_SOURCE[quickFilterSource],
source: QUICK_FILTER_SOURCE_TO_SOURCE[quickFilterSource],
startUnixMilli,
// This field does not affect the backend but I wanted to keep it here
// in case we add the support in the future

View File

@@ -1,12 +1,12 @@
import { useMemo } from 'react';
import { Button, Skeleton } from 'antd';
import {
QuickfiltertypesSourceDTO,
TelemetrytypesSourceDTO,
} from 'api/generated/services/sigNoz.schemas';
import { QuickfiltertypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import { FieldKeysConfig } from 'api/querySuggestions/types';
import OverlayScrollbar from 'components/OverlayScrollbar/OverlayScrollbar';
import { QUICK_FILTER_SOURCE_TO_SIGNAL } from 'components/QuickFilters/constants';
import {
QUICK_FILTER_SOURCE_TO_SIGNAL,
QUICK_FILTER_SOURCE_TO_SOURCE,
} from 'components/QuickFilters/constants';
import { buildCompositeKey } from 'container/OptionsMenu/utils';
import { useFieldKeysSuggestion } from 'hooks/querySuggestions/useFieldKeysSuggestion';
import {
@@ -43,8 +43,6 @@ function OtherFilters({
addedFilters: TelemetryFieldKey[];
setAddedFilters: React.Dispatch<React.SetStateAction<TelemetryFieldKey[]>>;
}): JSX.Element {
const isMeterDataSource =
savedFiltersSource === QuickfiltertypesSourceDTO.meter;
const isAIObservability =
savedFiltersSource === QuickfiltertypesSourceDTO.ai_observability;
@@ -57,7 +55,7 @@ function OtherFilters({
: {
searchText: inputValue,
signal: QUICK_FILTER_SOURCE_TO_SIGNAL[savedFiltersSource],
source: isMeterDataSource ? TelemetrytypesSourceDTO.meter : undefined,
source: QUICK_FILTER_SOURCE_TO_SOURCE[savedFiltersSource],
};
const { data: fetchedKeys, isFetching } = useFieldKeysSuggestion(

View File

@@ -1,4 +1,7 @@
import { TelemetrytypesSignalDTO } from 'api/generated/services/sigNoz.schemas';
import {
TelemetrytypesSignalDTO,
TelemetrytypesSourceDTO,
} from 'api/generated/services/sigNoz.schemas';
import { QuickFiltersSource } from './types';
@@ -13,4 +16,19 @@ export const QUICK_FILTER_SOURCE_TO_SIGNAL: Record<
[QuickFiltersSource.AI_OBSERVABILITY]: TelemetrytypesSignalDTO.traces,
[QuickFiltersSource.METER_EXPLORER]: TelemetrytypesSignalDTO.metrics,
[QuickFiltersSource.INFRA_MONITORING]: TelemetrytypesSignalDTO.metrics,
[QuickFiltersSource.AUDIT_LOGS]: TelemetrytypesSignalDTO.logs,
};
export const QUICK_FILTER_SOURCE_TO_SOURCE: Record<
QuickFiltersSource,
TelemetrytypesSourceDTO | undefined
> = {
[QuickFiltersSource.LOGS_EXPLORER]: undefined,
[QuickFiltersSource.TRACES_EXPLORER]: undefined,
[QuickFiltersSource.EXCEPTIONS]: undefined,
[QuickFiltersSource.API_MONITORING]: undefined,
[QuickFiltersSource.AI_OBSERVABILITY]: undefined,
[QuickFiltersSource.METER_EXPLORER]: TelemetrytypesSourceDTO.meter,
[QuickFiltersSource.INFRA_MONITORING]: undefined,
[QuickFiltersSource.AUDIT_LOGS]: TelemetrytypesSourceDTO.audit,
};

View File

@@ -60,6 +60,7 @@ export const QuickFiltersSource = {
API_MONITORING: QuickfiltertypesSourceDTO.api_monitoring,
METER_EXPLORER: QuickfiltertypesSourceDTO.meter,
AI_OBSERVABILITY: QuickfiltertypesSourceDTO.ai_observability,
AUDIT_LOGS: QuickfiltertypesSourceDTO.audit,
/** No saved filter list: renders `config` as given. */
INFRA_MONITORING: 'infra-monitoring',
} as const;

View File

@@ -48,10 +48,8 @@ export const getFilterConfig = (
({
type: getFilterType(att),
title: getFilterName(att.name),
// The type mapping below exists only for the old v3 attribute-values fetch
// (useCheckboxFilterValues), the sole reader of attributeKey.dataType/type.
// Once the values fetch moves to fields/values, remove this and reduce
// attributeKey to { id, key }.
// TODO: nothing reads dataType/type; reduce attributeKey to { id, key }
// once the TagFilterItem.key readers are checked.
attributeKey: {
id: att.name,
key: att.name,

View File

@@ -12,8 +12,6 @@ export const INVITE_MEMBERS_HASH = '#invite-team-members';
export const DASHBOARD_TIME_IN_DURATION = 'refreshInterval';
export const DEFAULT_ENTITY_VERSION = 'v3';
export const ENTITY_VERSION_V4 = 'v4';
export const ENTITY_VERSION_V5 = 'v5';
export const SIGNOZ_ADMIN_EMAIL = 'admin@signoz.cloud';

View File

@@ -48,4 +48,5 @@ export enum LOCALSTORAGE {
ALERT_RULES_LIST_VIEWS = 'ALERT_RULES_LIST_VIEWS',
DASHBOARD_V2_PANEL_COLUMN_WIDTHS = 'DASHBOARD_V2_PANEL_COLUMN_WIDTHS',
LLM_ATTRIBUTE_MAPPING_TEST_SPAN = 'LLM_ATTRIBUTE_MAPPING_TEST_SPAN',
AUDIT_LOGS_OPTIONS = 'AUDIT_LOGS_OPTIONS',
}

View File

@@ -5,15 +5,12 @@ import {
} from 'api/generated/services/sigNoz.schemas';
import { createIdFromObjectFields } from 'lib/createIdFromObjectFields';
import { createNewBuilderItemName } from 'lib/newQueryBuilder/createNewBuilderItemName';
import { IAttributeValuesResponse } from 'types/api/queryBuilder/getAttributesValues';
import {
AutocompleteType,
BaseAutocompleteData,
DataTypes,
LocalDataType,
} from 'types/api/queryBuilder/queryAutocompleteResponse';
import {
HavingForm,
IBuilderFormula,
IBuilderQuery,
IBuilderTraceOperator,
@@ -57,19 +54,11 @@ export const MAX_QUERIES = 26;
export const TRACE_OPERATOR_QUERY_NAME = 'Trace Operator';
export const idDivider = '--';
export const selectValueDivider = '__';
export const baseAutoCompleteIdKeysOrder: (keyof Omit<
BaseAutocompleteData,
'id' | 'isIndexed'
>)[] = ['key', 'dataType', 'type'];
export const autocompleteType: Record<AutocompleteType, AutocompleteType> = {
resource: 'resource',
tag: 'tag',
'': '',
};
export const formulasNames: string[] = Array.from(
Array(MAX_FORMULAS),
(_, i) => `F${i + 1}`,
@@ -77,12 +66,6 @@ export const formulasNames: string[] = Array.from(
const alpha: number[] = Array.from(Array(MAX_QUERIES), (_, i) => i + 65);
export const alphabet: string[] = alpha.map((str) => String.fromCharCode(str));
export enum QueryBuilderKeys {
GET_AGGREGATE_ATTRIBUTE = 'GET_AGGREGATE_ATTRIBUTE',
GET_AGGREGATE_KEYS = 'GET_AGGREGATE_KEYS',
GET_ATTRIBUTE_SUGGESTIONS = 'GET_ATTRIBUTE_SUGGESTIONS',
}
export const mapOfOperators = {
metrics: metricAggregateOperatorOptions,
logs: logsAggregateOperatorOptions,
@@ -110,12 +93,6 @@ export const REDUCE_TO_VALUES: SelectOption<ReduceOperators, string>[] = [
{ value: ReduceOperators.MIN, label: 'Min of values in timeframe' },
];
export const initialHavingValues: HavingForm = {
columnName: '',
op: '',
value: [],
};
export const initialAutocompleteData: BaseAutocompleteData = {
id: createIdFromObjectFields(
{ dataType: null, key: '', type: null },
@@ -525,17 +502,6 @@ export const OPERATORS_CONFIG = {
],
};
export const HAVING_OPERATORS: string[] = [
OPERATORS['='],
OPERATORS['!='],
OPERATORS.IN,
OPERATORS.NIN,
OPERATORS['>='],
OPERATORS['>'],
OPERATORS['<='],
OPERATORS['<'],
];
export enum PanelDisplay {
TIME_SERIES = 'Time Series',
VALUE = 'Number',
@@ -546,21 +512,6 @@ export enum PanelDisplay {
HISTOGRAM = 'Histogram',
}
export const DATA_TYPE_VS_ATTRIBUTE_VALUES_KEY: Record<
DataTypes,
keyof IAttributeValuesResponse
> = {
[DataTypes.String]: 'stringAttributeValues',
[DataTypes.Float64]: 'numberAttributeValues',
[DataTypes.Int64]: 'numberAttributeValues',
[DataTypes.bool]: 'boolAttributeValues',
[DataTypes.ArrayFloat64]: 'numberAttributeValues',
[DataTypes.ArrayInt64]: 'numberAttributeValues',
[DataTypes.ArrayString]: 'stringAttributeValues',
[DataTypes.ArrayBool]: 'boolAttributeValues',
[DataTypes.EMPTY]: 'stringAttributeValues',
};
export const listViewInitialLogQuery: Query = {
...initialQueriesMap.logs,
builder: {

View File

@@ -12,6 +12,7 @@ export const REACT_QUERY_KEY = {
GET_PUBLIC_DASHBOARD_WIDGET_DATA: 'GET_PUBLIC_DASHBOARD_WIDGET_DATA',
GET_ALL_LICENCES: 'GET_ALL_LICENCES',
GET_QUERY_RANGE: 'GET_QUERY_RANGE',
GET_AUDIT_LOGS: 'GET_AUDIT_LOGS',
GET_ALL_DASHBOARDS: 'GET_ALL_DASHBOARDS',
GET_TRIGGERED_ALERTS: 'GET_TRIGGERED_ALERTS',
DASHBOARD_BY_ID: 'DASHBOARD_BY_ID',

View File

@@ -2,10 +2,4 @@ import { TRACE_OPERATOR_QUERY_NAME } from './queryBuilder';
export const FORMULA_REGEXP = /F\d+/;
export const HAVING_FILTER_REGEXP = /^[-\d.,\s]+$/;
export const TYPE_ADDON_REGEXP = /_(.+)/;
export const SPLIT_FIRST_UNDERSCORE = /(?<!^)_/;
export const TRACE_OPERATOR_REGEXP = new RegExp(TRACE_OPERATOR_QUERY_NAME);

View File

@@ -41,6 +41,7 @@ const ROUTES = {
LOGS_PIPELINES: '/logs/pipelines',
PASSWORD_RESET: '/password-reset',
LIST_LICENSES: '/licenses',
AUDIT_LOGS: '/audit-logs',
LOGS_INDEX_FIELDS: '/logs-explorer/index-fields',
TRACE_EXPLORER: '/trace-explorer',
BILLING: '/settings/billing',

View File

@@ -94,21 +94,9 @@
&__text {
color: var(--l2-foreground);
line-height: 18px;
.bold-text {
color: var(--l1-foreground);
}
}
&__button-wrapper {
margin-top: 12px;
.configure-alert-rule-button {
padding: 8px 16px;
border-radius: 2px;
background: var(--l3-background);
border-width: 0;
color: var(--l1-foreground);
display: flex;
align-items: center;
}
}
}
}

View File

@@ -1,4 +1,6 @@
import { useMemo } from 'react';
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
import ErrorContent from 'components/ErrorModal/components/ErrorContent';
import { useGetAlertRuleDetailsTopContributors } from 'pages/AlertDetails/hooks';
import { labelsArrayToObject } from 'container/AlertHistory/utils/labelAdapters';
import DataStateRenderer from 'periscope/components/DataStateRenderer/DataStateRenderer';
@@ -13,8 +15,9 @@ type TopContributorsRendererProps = {
function TopContributorsRenderer({
totalCurrentTriggers,
}: TopContributorsRendererProps): JSX.Element {
const { isLoading, isRefetching, isError, data, isValidRuleId, ruleId } =
const { isLoading, isRefetching, data, error, isValidRuleId, ruleId } =
useGetAlertRuleDetailsTopContributors();
const apiError = useMemo(() => convertToApiError(error), [error]);
// TODO(shaheer): render the DataStateRenderer inside the TopContributorsCard, it should display the title and view all
const adaptedData = useMemo((): AlertRuleTopContributors[] | null => {
@@ -31,11 +34,19 @@ function TopContributorsRenderer({
}));
}, [data?.data]);
if (apiError) {
return (
<div data-testid="top-contributors-error">
<ErrorContent error={apiError} />
</div>
);
}
return (
<DataStateRenderer
isLoading={isLoading}
isRefetching={isRefetching}
isError={isError || !isValidRuleId || !ruleId}
isError={!isValidRuleId || !ruleId}
data={adaptedData}
>
{(topContributorsData): JSX.Element => (

View File

@@ -19,14 +19,4 @@
line-height: 18px;
letter-spacing: -0.06px;
}
&__chart {
.chart-placeholder {
width: 100%;
height: 52px;
background: color-mix(in srgb, var(--l1-foreground) 12%, transparent);
display: flex;
align-items: center;
justify-content: center;
}
}
}

View File

@@ -0,0 +1,38 @@
import ROUTES from 'constants/routes';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { render, screen, within } from 'tests/test-utils';
import TopContributorsRenderer from '../Statistics/TopContributorsRenderer/TopContributorsRenderer';
const RULE_ID = 'rule-1';
const route = `${ROUTES.ALERT_HISTORY}?ruleId=${RULE_ID}&relativeTime=6h`;
const failWith = (status: number, code: string): ReturnType<typeof rest.get> =>
rest.get(
`http://localhost/api/v2/rules/${RULE_ID}/history/top_contributors`,
(_req, res, ctx) =>
res(
ctx.status(status),
ctx.json({ status: 'error', error: { code, message: 'refused' } }),
),
);
describe('TopContributorsRenderer', () => {
afterEach(() => {
server.resetHandlers();
});
it.each([
[500, 'internal'],
[403, 'authz_forbidden'],
])('shows the generic error for a %i', async (status, code) => {
server.use(failWith(status, code));
render(<TopContributorsRenderer totalCurrentTriggers={0} />, undefined, {
initialRoute: route,
});
const error = await screen.findByTestId('top-contributors-error');
expect(within(error).getByText(code)).toBeInTheDocument();
});
});

View File

@@ -62,7 +62,6 @@ function DomainList(): JSX.Element {
const { handleChangeQueryData } = useQueryOperations({
index: 0,
query,
entityVersion: '',
});
const compositeData = useGetCompositeQueryParam();

View File

@@ -100,33 +100,6 @@ describe('TopErrors', () => {
),
),
);
// Mock V4 API endpoint for dropdown data
server.use(
rest.post('*/api/v1/query_range', (_req, res, ctx) =>
res(
ctx.status(200),
ctx.json({
payload: {
data: {
result: [
{
table: {
rows: [
{
http_url: '/api/test',
A: 100,
},
],
},
},
],
},
},
}),
),
),
);
});
it('renders component correctly', async () => {

View File

@@ -1,15 +1,16 @@
import { useMemo, useState } from 'react';
import { Input } from '@signozhq/ui/input';
import { Button, Select, Tooltip } from 'antd';
import AuthZSelect from 'lib/authz/components/AuthZSelect/AuthZSelect';
import { Typography } from '@signozhq/ui/typography';
import { CircleX, Trash } from '@signozhq/icons';
import { useAppContext } from 'providers/App/App';
import NotificationChannelsNotFound from 'components/NotificationChannelsNotFound/NotificationChannelsNotFound';
import { useCreateAlertState } from '../context';
import { AlertThresholdOperator } from '../context/types';
import { normalizeOperator } from '../utils';
import { ThresholdItemProps } from './types';
import { NotificationChannelsNotFoundContent } from './utils';
import { useAlertRuleChannelAccess } from './useAlertRuleChannelAccess';
function ThresholdItem({
threshold,
@@ -23,8 +24,13 @@ function ThresholdItem({
isLoadingChannels,
isAnomaly = false,
}: ThresholdItemProps): JSX.Element {
const { user } = useAppContext();
const { thresholdState, notificationSettings } = useCreateAlertState();
const { options: channelOptions, onPickerVisibleChange } =
useAlertRuleChannelAccess(
threshold,
channels,
`threshold-${threshold.label}-channel-option`,
);
const [showRecoveryThreshold, setShowRecoveryThreshold] = useState(false);
const yAxisUnitSelect = useMemo(() => {
@@ -179,19 +185,16 @@ function ThresholdItem({
>
send to
</Typography>
<Select
<AuthZSelect
value={threshold.channels}
onChange={(value): void =>
updateThreshold(threshold.id, 'channels', value)
}
data-testid="threshold-notification-channel-select"
popupMatchSelectWidth={false}
style={{ width: 350 }}
options={channels.map((channel) => ({
value: channel.name,
label: channel.name,
'data-testid': `threshold-notification-channel-option-${threshold.label}`,
}))}
mode="multiple"
options={channelOptions}
onDropdownVisibleChange={onPickerVisibleChange}
placeholder="Select notification channels"
showSearch
maxTagCount={2}
@@ -199,16 +202,10 @@ function ThresholdItem({
`+${omittedValues.length} more`
}
maxTagTextLength={10}
filterOption={(input, option): boolean =>
option?.label?.toLowerCase().includes(input.toLowerCase()) || false
}
status={isErrorChannels ? 'error' : undefined}
disabled={isLoadingChannels}
notFoundContent={
<NotificationChannelsNotFoundContent
user={user}
refreshChannels={refreshChannels}
/>
<NotificationChannelsNotFound onRefresh={refreshChannels} />
}
/>
</>

View File

@@ -102,15 +102,6 @@ jest.mock('hooks/notificationChannels/useChannelOptions', () => ({
})),
}));
// Mock alert format categories
jest.mock('constants/formats/alertFormatCategories', () => ({
getCategoryByOptionId: jest.fn(() => ({ name: 'bytes' })),
getCategorySelectOptionByName: jest.fn(() => [
{ label: 'Bytes', value: 'bytes' },
{ label: 'KB', value: 'kb' },
]),
}));
jest.mock('container/CreateAlert/utils', () => ({
...jest.requireActual('container/CreateAlert/utils'),
}));

View File

@@ -1,15 +1,33 @@
import { fireEvent, render, screen } from 'tests/test-utils';
import { fireEvent, render, screen, userEvent, within } from 'tests/test-utils';
import type { DefaultOptionType } from 'antd/es/select';
import { INITIAL_ALERT_THRESHOLD_STATE } from 'container/CreateAlert/context/constants';
import type { Threshold } from 'container/CreateAlert/context/types';
import { createMockAlertContextState } from 'container/CreateAlert/EvaluationSettings/__tests__/testUtils';
import { getAppContextMockState } from 'container/RoutingPolicies/__tests__/testUtils';
import * as appHooks from 'providers/App/App';
import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
import {
buildNotificationChannelAttachPermission,
buildNotificationChannelDetachPermission,
NotificationChannelCreatePermission,
} from 'lib/authz/hooks/useAuthZ/permissions/notification-channel.permissions';
import { buildRuleDetachPermission } from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
import type { UseAuthZResult } from 'lib/authz/hooks/useAuthZ/types';
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
import { formatPermission } from 'lib/authz/hooks/useAuthZ/utils';
import {
denyPermissions,
mockUseAuthZDeny,
} from 'lib/authz/utils/authz-test-utils';
import * as context from '../../context';
import ThresholdItem from '../ThresholdItem';
import { ThresholdItemProps } from '../types';
jest.spyOn(appHooks, 'useAppContext').mockReturnValue(getAppContextMockState());
jest.mock('lib/authz/hooks/useAuthZ/useAuthZ');
beforeEach(() => {
denyPermissions();
});
jest.mock('uplot', () => {
const paths = {
@@ -372,4 +390,177 @@ describe('ThresholdItem', () => {
const channelSelectors = screen.getAllByRole('combobox');
expect(channelSelectors).toHaveLength(2); // Should have both unit and channel selectors
});
describe('authz', () => {
const RULE_ID = 'rule-1';
const option = (
channelId: string,
label: string = TEST_CONSTANTS.CRITICAL_LABEL,
): Promise<HTMLElement> =>
screen.findByTestId(`threshold-${label}-channel-option-${channelId}`);
const openPicker = async (): Promise<void> => {
await userEvent
.setup()
.click(
within(
screen.getByTestId('threshold-notification-channel-select'),
).getByRole('combobox'),
);
};
const withChannels = (
channels: string[],
overrides: Partial<Threshold> = {},
): Threshold => ({ ...mockThreshold, channels, ...overrides });
const editing = (
savedChannelNames: string[],
thresholds: Threshold[] = [mockThreshold],
): void => {
jest.spyOn(context, 'useCreateAlertState').mockReturnValue(
createMockAlertContextState({
isEditMode: true,
ruleId: RULE_ID,
savedChannelNames,
thresholdState: { ...INITIAL_ALERT_THRESHOLD_STATE, thresholds },
}),
);
};
afterEach(() => {
jest.spyOn(context, 'useCreateAlertState').mockReturnValue(
createMockAlertContextState({
setThresholdState: mockSetThresholdState,
setAlertState: mockSetAlertState,
}),
);
});
it('disables a channel the user cannot attach, naming the permission', async () => {
const attach = buildNotificationChannelAttachPermission(
TEST_CONSTANTS.CHANNEL_2,
);
denyPermissions(attach);
renderThresholdItem();
await openPicker();
const denied = await option(TEST_CONSTANTS.CHANNEL_2);
expect(denied).toHaveAttribute('aria-disabled', 'true');
expect(denied).toHaveAttribute(
'aria-description',
expect.stringContaining(formatPermission(attach)),
);
await expect(option(TEST_CONSTANTS.CHANNEL_3)).resolves.toHaveAttribute(
'aria-disabled',
'false',
);
});
it('locks a saved channel the user cannot detach', async () => {
const detach = buildNotificationChannelDetachPermission(
TEST_CONSTANTS.CHANNEL_1,
);
denyPermissions(detach);
const critical = withChannels([TEST_CONSTANTS.EMAIL_CHANNEL_NAME]);
editing([TEST_CONSTANTS.EMAIL_CHANNEL_NAME], [critical]);
renderThresholdItem({ threshold: critical });
await openPicker();
const saved = await option(TEST_CONSTANTS.CHANNEL_1);
expect(saved).toHaveAttribute('aria-disabled', 'true');
expect(saved).toHaveAttribute(
'aria-description',
expect.stringContaining(formatPermission(detach)),
);
});
describe('with several thresholds', () => {
const EMAIL = TEST_CONSTANTS.EMAIL_CHANNEL_NAME;
const warningId = 'test-threshold-2';
beforeEach(() => {
denyPermissions(
buildNotificationChannelDetachPermission(TEST_CONSTANTS.CHANNEL_1),
buildRuleDetachPermission(RULE_ID),
);
});
it('lets a saved channel be removed while another threshold still has it', async () => {
const critical = withChannels([EMAIL]);
const warning = withChannels([EMAIL], {
id: warningId,
label: TEST_CONSTANTS.WARNING_LABEL,
});
editing([EMAIL], [critical, warning]);
renderThresholdItem({ threshold: critical });
await openPicker();
await expect(option(TEST_CONSTANTS.CHANNEL_1)).resolves.toHaveAttribute(
'aria-disabled',
'false',
);
});
it('lets a channel saved on one threshold be added to another', async () => {
const critical = withChannels([EMAIL]);
const warning = withChannels([], {
id: warningId,
label: TEST_CONSTANTS.WARNING_LABEL,
});
editing([EMAIL], [critical, warning]);
renderThresholdItem({ threshold: warning });
await openPicker();
await expect(
option(TEST_CONSTANTS.CHANNEL_1, TEST_CONSTANTS.WARNING_LABEL),
).resolves.toHaveAttribute('aria-disabled', 'false');
});
it('lets a saved channel that no threshold has anymore be added back', async () => {
const critical = withChannels([]);
editing([EMAIL], [critical]);
renderThresholdItem({ threshold: critical });
await openPicker();
await expect(option(TEST_CONSTANTS.CHANNEL_1)).resolves.toHaveAttribute(
'aria-disabled',
'false',
);
});
});
it('keeps channels disabled while their check is pending', async () => {
jest.mocked(useAuthZ).mockReturnValue({
...mockUseAuthZDeny()([]),
isLoading: true,
permissions: null,
} as UseAuthZResult);
renderThresholdItem();
await openPicker();
const pending = await option(TEST_CONSTANTS.CHANNEL_2);
expect(pending).toHaveAttribute('aria-disabled', 'true');
expect(pending).toHaveAttribute('aria-description', 'Checking permissions');
});
it('offers to create a channel with notification-channel:create', async () => {
renderThresholdItem({ channels: [] });
await openPicker();
await expect(
screen.findByTestId('channels-not-found-create'),
).resolves.toBeInTheDocument();
});
it('asks for an admin without notification-channel:create', async () => {
denyPermissions(NotificationChannelCreatePermission);
renderThresholdItem({ channels: [] });
await openPicker();
await expect(
screen.findByText('Please ask your admin to create one.'),
).resolves.toBeInTheDocument();
expect(
screen.queryByTestId('channels-not-found-create'),
).not.toBeInTheDocument();
});
});
});

View File

@@ -205,46 +205,6 @@
}
}
}
.recovery-threshold-input-group {
display: flex;
align-items: center;
gap: 0;
margin-left: 28px;
.recovery-threshold-label {
pointer-events: none;
cursor: default;
}
.recovery-threshold-btn {
pointer-events: none;
cursor: default;
color: var(--muted-foreground);
background-color: var(--surface-2) !important;
border: 1px solid var(--l1-border);
border-radius: 4px;
display: flex;
align-items: center;
justify-content: center;
}
.ant-input {
background-color: var(--surface-2);
border: 1px solid var(--l1-border);
color: var(--l1-foreground);
height: 32px;
&:hover {
border-color: var(--l1-border);
}
&:focus {
border-color: var(--l1-border);
box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.1);
}
}
}
}
}
@@ -275,15 +235,10 @@
gap: 4px;
}
}
.ant-typography {
color: var(--accent-primary);
}
}
}
.condensed-alert-threshold-container,
.condensed-anomaly-threshold-container {
.condensed-alert-threshold-container {
width: 100%;
}

View File

@@ -0,0 +1,66 @@
import { useMemo } from 'react';
import type { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
import {
type UseChannelPickerAccessReturn,
useChannelPickerAccess,
} from 'hooks/notificationChannels/useChannelPickerAccess';
import {
buildRuleAttachPermission,
buildRuleDetachPermission,
} from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
import { useCreateAlertState } from '../context';
import type { Threshold } from '../context/types';
/**
* One threshold's channel picker. An edit checks `attach`/`detach` on the rule
* and each channel; a new rule has no id, so its own `attach` is checked on
* Save, as for a new routing policy. The backend diffs the rule's channels as
* one set, so a channel another threshold holds, or a saved one this threshold
* no longer holds, needs no check.
*/
export function useAlertRuleChannelAccess(
threshold: Threshold,
channels: ChannelOption[],
testIdPrefix: string,
): Pick<UseChannelPickerAccessReturn, 'options' | 'onPickerVisibleChange'> {
const { isEditMode, ruleId, savedChannelNames, thresholdState } =
useCreateAlertState();
const editedRuleId = isEditMode && ruleId ? ruleId : undefined;
const owner = useMemo(
() =>
editedRuleId
? {
attach: buildRuleAttachPermission(editedRuleId),
detach: buildRuleDetachPermission(editedRuleId),
}
: undefined,
[editedRuleId],
);
const exemptChannelNames = useMemo(() => {
const own = new Set(threshold.channels);
return [
...thresholdState.thresholds
.filter((other) => other.id !== threshold.id)
.flatMap((other) => other.channels),
...savedChannelNames.filter((name) => !own.has(name)),
];
}, [
threshold.id,
threshold.channels,
thresholdState.thresholds,
savedChannelNames,
]);
const { options, onPickerVisibleChange } = useChannelPickerAccess({
owner,
savedChannelNames,
exemptChannelNames,
channels,
testIdPrefix,
});
return { options, onPickerVisibleChange };
}

View File

@@ -1,12 +1,10 @@
import { Button, SelectProps } from 'antd';
import Flex from 'periscope/components/Flex/Flex';
import { Switch } from '@signozhq/ui/switch';
import { Typography } from '@signozhq/ui/typography';
import type { BaseOptionType, DefaultOptionType } from 'antd/es/select';
import { getInvolvedQueriesInTraceOperator } from 'components/QueryBuilderV2/QueryV2/TraceOperator/utils/utils';
import { YAxisSource } from 'components/YAxisUnitSelector/types';
import { getYAxisCategories } from 'components/YAxisUnitSelector/utils';
import ROUTES from 'constants/routes';
import {
AlertThresholdMatchType,
AlertThresholdOperator,
@@ -15,12 +13,9 @@ import { getSelectedQueryOptions } from 'container/FormAlertRules/utils';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import { getActiveBuilder } from 'lib/query/builderSlot';
import { ArrowRight } from '@signozhq/icons';
import { IUser } from 'providers/App/types';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { QueryFunction } from 'types/api/v5/queryRange';
import { EQueryType } from 'types/common/dashboard';
import { USER_ROLES } from 'types/roles';
import { openInNewTab } from 'utils/navigation';
import { ROUTING_POLICIES_ROUTE } from './constants';
import { Threshold } from '../context/types';
@@ -427,66 +422,6 @@ export const getMatchTypeTooltip = (
}
};
export function NotificationChannelsNotFoundContent({
user,
refreshChannels,
}: {
user: IUser;
refreshChannels: () => void;
}): JSX.Element {
return (
<Flex justify="space-between">
<Flex gap={4} align="center">
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="wrap"
>
No channels yet.
</Typography>
{user?.role === USER_ROLES.ADMIN ? (
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="wrap"
>
Create one
<Button
style={{ padding: '0 4px' }}
type="link"
onClick={(): void => {
openInNewTab(ROUTES.CHANNELS_NEW);
}}
>
here.
</Button>
</Typography>
) : (
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="wrap"
>
Please ask your admin to create one.
</Typography>
)}
</Flex>
<Button type="text" onClick={refreshChannels}>
Refresh
</Button>
</Flex>
);
}
export function RoutingPolicyBanner({
notificationSettings,
setNotificationSettings,

View File

@@ -2,6 +2,8 @@ import { useCallback, useMemo } from 'react';
import { Input } from '@signozhq/ui/input';
import classNames from 'classnames';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { buildRuleUpdatePermission } from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
import { useAuthZDisabled } from 'lib/authz/hooks/useAuthZDisabled/useAuthZDisabled';
import { getActiveBuilder } from 'lib/query/builderSlot';
import { useAlertRuleOptional } from 'providers/Alert';
import { Labels } from 'types/api/alerts/def';
@@ -12,7 +14,15 @@ import LabelsInput from './LabelsInput';
import './styles.scss';
function CreateAlertHeader(): JSX.Element {
const { alertState, setAlertState, isEditMode } = useCreateAlertState();
const { alertState, setAlertState, isEditMode, ruleId } =
useCreateAlertState();
// Renaming or relabelling a saved rule is an update; a new rule is gated on
// its Save.
const updateChecks = useMemo(
() => (isEditMode && ruleId ? [buildRuleUpdatePermission(ruleId)] : []),
[isEditMode, ruleId],
);
const updateLock = useAuthZDisabled(updateChecks);
const alertRuleContext = useAlertRuleOptional();
const { currentQuery } = useQueryBuilder();
@@ -60,6 +70,8 @@ function CreateAlertHeader(): JSX.Element {
}
}}
placeholder="Enter alert rule name"
disabled={updateLock.disabled}
disabledTooltip={updateLock.disabledTooltip}
testId="alert-name-input"
/>
</div>
@@ -69,6 +81,8 @@ function CreateAlertHeader(): JSX.Element {
setAlertState({ type: 'SET_ALERT_LABELS', payload: labels })
}
validateLabelsKey={validateLabelsKey}
disabled={updateLock.disabled}
disabledTooltip={updateLock.disabledTooltip}
/>
</div>
</div>

View File

@@ -1,5 +1,6 @@
import React, { useCallback, useState } from 'react';
import { X } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import { useNotifications } from 'hooks/useNotifications';
import { LabelInputState, LabelsInputProps } from './types';
@@ -8,6 +9,8 @@ function LabelsInput({
labels,
onLabelsChange,
validateLabelsKey,
disabled = false,
disabledTooltip,
}: LabelsInputProps): JSX.Element {
const { notifications } = useNotifications();
const [inputState, setInputState] = useState<LabelInputState>({
@@ -134,6 +137,8 @@ function LabelsInput({
type="button"
className="labels-input__remove-button"
aria-label={`Remove label ${key}`}
data-testid={`label-remove-${key}`}
disabled={disabled}
onClick={(): void => handleRemoveLabel(key)}
>
<X size="md" />
@@ -144,14 +149,19 @@ function LabelsInput({
)}
{!isAdding ? (
<button
className="labels-input__add-button"
type="button"
onClick={handleAddLabelsClick}
data-testid="alert-add-label-button"
>
+ Add labels
</button>
<div className="labels-input__add">
<Button
variant="outlined"
color="secondary"
size="sm"
disabled={disabled}
disabledTooltip={disabledTooltip}
onClick={handleAddLabelsClick}
testId="alert-add-label-button"
>
+ Add labels
</Button>
</div>
) : (
<div className="labels-input__input-container">
<input

View File

@@ -1,4 +1,6 @@
import { initialQueryAIWithType } from 'constants/queryBuilder';
import { buildRuleUpdatePermission } from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
import { denyPermissions } from 'lib/authz/utils/authz-test-utils';
import { defaultPostableAlertRuleV2 } from 'container/CreateAlert/constants';
import { getCreateAlertLocalStateFromAlertDef } from 'container/CreateAlert/utils';
import { getActiveBuilder } from 'lib/query/builderSlot';
@@ -43,6 +45,12 @@ jest.mock('uplot', () => {
mockAppLocation({ search: '' });
jest.mock('lib/authz/hooks/useAuthZ/useAuthZ');
beforeEach(() => {
denyPermissions();
});
const ENTER_ALERT_RULE_NAME_PLACEHOLDER = 'Enter alert rule name';
const renderCreateAlertHeader = (): ReturnType<typeof render> =>
@@ -142,4 +150,54 @@ describe('CreateAlertHeader', () => {
alertStateSpy.mockRestore();
});
describe('authz', () => {
const RULE_ID = 'rule-1';
const renderEdit = (): void => {
render(
<CreateAlertProvider
isEditMode
ruleId={RULE_ID}
initialAlertType={AlertTypes.METRICS_BASED_ALERT}
initialAlertState={getCreateAlertLocalStateFromAlertDef(
defaultPostableAlertRuleV2,
)}
>
<CreateAlertHeader />
</CreateAlertProvider>,
);
};
const nameField = (): HTMLElement =>
screen.getByPlaceholderText(ENTER_ALERT_RULE_NAME_PLACEHOLDER);
it('locks renaming and relabelling a saved rule without update', () => {
denyPermissions(buildRuleUpdatePermission(RULE_ID));
renderEdit();
expect(nameField()).toBeDisabled();
expect(screen.getByTestId('alert-add-label-button')).toHaveAttribute(
'aria-disabled',
'true',
);
expect(screen.getByTestId('label-remove-severity')).toBeDisabled();
});
it('lets a saved rule be renamed and relabelled with update', () => {
renderEdit();
expect(nameField()).toBeEnabled();
expect(screen.getByTestId('alert-add-label-button')).not.toHaveAttribute(
'aria-disabled',
'true',
);
expect(screen.getByTestId('label-remove-severity')).toBeEnabled();
});
it('never locks naming a new rule', () => {
denyPermissions(buildRuleUpdatePermission(RULE_ID));
renderCreateAlertHeader();
expect(nameField()).toBeEnabled();
});
});
});

View File

@@ -60,20 +60,8 @@
flex-direction: column;
gap: 8px;
&__add-button {
width: fit-content;
font-size: 13px;
color: var(--l2-foreground);
border: 1px solid var(--l1-border);
background-color: transparent;
cursor: pointer;
padding: 4px 8px;
border-radius: 4px;
&:hover {
border-color: var(--l1-border);
color: var(--l1-foreground);
}
&__add {
display: flex;
}
&__existing-labels {

View File

@@ -1,9 +1,13 @@
import type { ReactNode } from 'react';
import { Labels } from 'types/api/alerts/def';
export interface LabelsInputProps {
labels: Labels;
onLabelsChange: (labels: Labels) => void;
validateLabelsKey: (key: string) => string | null;
disabled?: boolean;
/** Shown on Add labels while disabled. */
disabledTooltip?: ReactNode;
}
export interface LabelInputState {

View File

@@ -11,11 +11,6 @@
gap: 16px;
padding: 16px;
.ant-typography {
color: var(--l1-foreground);
font-size: 13px;
}
.ant-btn-group {
.ant-btn {
border: 1px solid var(--l1-border);
@@ -133,12 +128,6 @@
flex-direction: column;
gap: 4px;
.ant-typography {
color: var(--l1-foreground);
font-size: 13px;
font-weight: 500;
}
.ant-select {
border: 1px solid var(--l1-border);

View File

@@ -35,6 +35,7 @@ export const createMockAlertContextState = (
updateAlertRule: jest.fn(),
isEditMode: false,
ruleId: '',
savedChannelNames: [],
...overrides,
});

View File

@@ -1,53 +1,3 @@
.evaluation-settings-container {
margin: 16px;
.evaluate-alert-conditions-container {
display: flex;
align-items: center;
gap: 16px;
background-color: var(--l2-background);
padding: 16px;
border-radius: 4px;
border: 1px solid var(--l1-border);
margin-bottom: 16px;
.ant-typography {
color: var(--l2-foreground);
}
.evaluate-alert-conditions-separator {
flex: 1;
height: 1px;
border-top: 1px dashed var(--l1-border);
}
.ant-btn {
display: flex;
align-items: center;
justify-content: space-between;
background-color: var(--l2-background);
border: 1px solid var(--l1-border);
.evaluate-alert-conditions-button-left {
color: var(--l2-foreground);
padding-right: 16px;
}
.evaluate-alert-conditions-button-right {
display: flex;
align-items: center;
color: var(--muted-foreground);
gap: 8px;
.evaluate-alert-conditions-button-right-text {
background-color: var(--l2-background);
padding: 1px 4px;
}
}
}
}
}
.advanced-options-container {
.ant-collapse {
.ant-collapse-item {
@@ -118,18 +68,9 @@
margin: 0 -16px;
padding: 4px 16px;
.ant-typography {
color: var(--muted-foreground);
font-weight: 400;
}
&.active {
background-color: var(--l1-background);
border-left: 2px solid var(--bg-robin-500);
.ant-typography {
font-weight: 500;
color: var(--l1-foreground);
}
}
&:hover {
@@ -147,25 +88,12 @@
gap: 16px;
width: 400px;
.ant-typography {
color: var(--muted-foreground);
}
.ant-btn {
width: fit-content;
}
}
}
.evaluation-window-footer {
display: flex;
justify-content: flex-end;
gap: 8px;
background-color: var(--l2-background);
border-top: 1px solid var(--l1-border);
padding: 16px;
}
.ant-btn {
background-color: var(--l3-background);
border: 1px solid var(--l1-border);
@@ -188,13 +116,6 @@
display: flex;
flex-direction: column;
gap: 2px;
.ant-typography {
color: var(--l3-foreground);
font-size: 11px;
line-height: 18px;
font-weight: 500;
}
}
.time-select-group {
@@ -218,12 +139,6 @@
}
}
.ant-typography {
color: var(--l2-foreground);
font-size: 13px;
font-weight: 500;
}
.ant-select {
width: 60%;
background-color: var(--l2-background);

View File

@@ -57,14 +57,6 @@ export interface IEvaluationCadencePreviewProps {
setIsOpen: Dispatch<SetStateAction<boolean>>;
}
export interface TimeInputProps {
value?: string; // Format: "HH:MM:SS"
onChange?: (value: string) => void;
placeholder?: string;
disabled?: boolean;
className?: string;
}
export interface IEditCustomScheduleProps {
setIsEvaluationCadenceDetailsVisible: (isOpen: boolean) => void;
setIsPreviewVisible: (isOpen: boolean) => void;

View File

@@ -7,12 +7,16 @@ import { AxiosError } from 'axios';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import { Check, Send, X } from '@signozhq/icons';
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
import { AUTHZ_LOADING_TOOLTIP } from 'lib/authz/components/constants';
import { useErrorModal } from 'providers/ErrorModalProvider';
import { toPostableRuleDTO } from 'types/api/alerts/convert';
import APIError from 'types/api/error';
import { isModifierKeyPressed } from 'utils/app';
import { useCreateAlertState } from '../context';
import { WAIT_FOR_SAVE, WAIT_FOR_TEST_NOTIFICATION } from './constants';
import { useAlertRuleSaveChecks } from './useAlertRuleSaveChecks';
import { buildCreateAlertRulePayload, validateCreateAlertState } from './utils';
import './styles.scss';
@@ -42,13 +46,13 @@ function Footer(): JSX.Element {
} = useCreateAlertState();
const { currentQuery } = useQueryBuilder();
const { safeNavigate } = useSafeNavigate();
const { saveChecks, testChecks, isResolvingChannels } =
useAlertRuleSaveChecks();
const { showErrorModal } = useErrorModal();
const handleApiError = useCallback(
(error: unknown): void => {
showErrorModal(
convertToApiError(error as AxiosError<RenderErrorResponseDTO>) as APIError,
);
(error: AxiosError<RenderErrorResponseDTO>): void => {
showErrorModal(convertToApiError(error) as APIError);
},
[showErrorModal],
);
@@ -178,65 +182,64 @@ function Footer(): JSX.Element {
const isSavingAlertRule = isCreatingAlertRule || isUpdatingAlertRule;
const disableButtons = isSavingAlertRule || isTestingAlertRule;
const saveBlockedReason =
alertValidationMessage ||
(isTestingAlertRule
? WAIT_FOR_TEST_NOTIFICATION
: isResolvingChannels
? AUTHZ_LOADING_TOOLTIP
: undefined);
const testBlockedReason =
alertValidationMessage ||
(isSavingAlertRule
? WAIT_FOR_SAVE
: isResolvingChannels
? AUTHZ_LOADING_TOOLTIP
: undefined);
const saveAlertButton = useMemo(
() => (
<Button
disabledTooltip={
alertValidationMessage || 'Wait for the test notification to finish'
}
<AuthZButton
checks={saveChecks}
disabledTooltip={saveBlockedReason}
size="md"
variant="solid"
color="primary"
onClick={handleSaveAlert}
disabled={isTestingAlertRule || Boolean(alertValidationMessage)}
loading={isSavingAlertRule}
prefix={<Check data-testid="save-alert-rule-check-icon" size={14} />}
testId="save-alert-rule-button"
>
Save Alert Rule
</Button>
</AuthZButton>
),
[
alertValidationMessage,
handleSaveAlert,
isSavingAlertRule,
isTestingAlertRule,
],
[saveChecks, saveBlockedReason, handleSaveAlert, isSavingAlertRule],
);
const testAlertButton = useMemo(
() => (
<Button
disabledTooltip={
alertValidationMessage || 'Wait for the alert rule to finish saving'
}
<AuthZButton
checks={testChecks}
disabledTooltip={testBlockedReason}
size="md"
variant="solid"
color="secondary"
onClick={handleTestNotification}
disabled={isSavingAlertRule || Boolean(alertValidationMessage)}
loading={isTestingAlertRule}
prefix={<Send data-testid="test-notification-send-icon" size={14} />}
testId="test-notification-button"
>
Test Notification
</Button>
</AuthZButton>
),
[
alertValidationMessage,
handleTestNotification,
isSavingAlertRule,
isTestingAlertRule,
],
[testChecks, testBlockedReason, handleTestNotification, isTestingAlertRule],
);
return (
<div className="create-alert-v2-footer">
<Button
disabledTooltip={
isTestingAlertRule
? 'Wait for the test notification to finish'
: 'Wait for the alert rule to finish saving'
isTestingAlertRule ? WAIT_FOR_TEST_NOTIFICATION : WAIT_FOR_SAVE
}
size="md"
variant="solid"

View File

@@ -1,39 +1,56 @@
import { fireEvent, render, screen } from '@testing-library/react';
import type { AxiosError } from 'axios';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';
import type { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';
import {
AlertThresholdMatchType,
AlertThresholdOperator,
} from 'container/CreateAlert/context/types';
import { createMockAlertContextState } from 'container/CreateAlert/EvaluationSettings/__tests__/testUtils';
import { useChannelOptions } from 'hooks/notificationChannels/useChannelOptions';
import { buildNotificationChannelAttachPermission } from 'lib/authz/hooks/useAuthZ/permissions/notification-channel.permissions';
import {
buildRuleUpdatePermission,
RuleCreatePermission,
} from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
import { denyPermissions } from 'lib/authz/utils/authz-test-utils';
import type { ICreateAlertContextProps } from '../../context/types';
import * as createAlertState from '../../context';
import Footer from '../Footer';
import MockQueryClientProvider from 'providers/test/MockQueryClientProvider';
// Mock the hooks used by Footer component
jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
useQueryBuilder: jest.fn(),
}));
const mockShowErrorModal = jest.fn();
jest.mock('providers/ErrorModalProvider', () => ({
...jest.requireActual('providers/ErrorModalProvider'),
useErrorModal: (): { showErrorModal: jest.Mock } => ({
showErrorModal: jest.fn(),
showErrorModal: mockShowErrorModal,
}),
}));
jest.mock('lib/authz/hooks/useAuthZ/useAuthZ');
jest.mock('hooks/useSafeNavigate', () => ({
useSafeNavigate: jest.fn(),
}));
const { useQueryBuilder } = jest.requireMock(
'hooks/queryBuilder/useQueryBuilder',
);
const CHANNELS_URL = 'http://localhost/api/v2/notification_channels';
const CHANNELS = [
{ id: 'ch-test', displayName: 'test-channel' },
{ id: 'ch-other', displayName: 'other-channel' },
];
const SAVE = 'save-alert-rule-button';
const TEST = 'test-notification-button';
const DISCARD = 'discard-alert-rule-button';
const mockCreateAlertRule = jest.fn();
const mockTestAlertRule = jest.fn();
const mockUpdateAlertRule = jest.fn();
const mockDiscardAlertRule = jest.fn();
// Import the mocked hooks
const { useQueryBuilder } = jest.requireMock(
'hooks/queryBuilder/useQueryBuilder',
);
const { useSafeNavigate } = jest.requireMock('hooks/useSafeNavigate');
const mockAlertContextState = createMockAlertContextState({
createAlertRule: mockCreateAlertRule,
testAlertRule: mockTestAlertRule,
@@ -64,19 +81,52 @@ const mockAlertContextState = createMockAlertContextState({
},
});
const WrappedFooter = (): JSX.Element => (
<MockQueryClientProvider>
<Footer />
</MockQueryClientProvider>
);
const withState = (overrides: Partial<ICreateAlertContextProps>): void => {
jest
.spyOn(createAlertState, 'useCreateAlertState')
.mockReturnValue({ ...mockAlertContextState, ...overrides });
};
jest
.spyOn(createAlertState, 'useCreateAlertState')
.mockReturnValue(mockAlertContextState);
const withoutChannels = (
routingPolicies: boolean,
): Partial<ICreateAlertContextProps> => ({
notificationSettings: {
...mockAlertContextState.notificationSettings,
routingPolicies,
},
thresholdState: {
...mockAlertContextState.thresholdState,
thresholds: [
{ ...mockAlertContextState.thresholdState.thresholds[0], channels: [] },
],
},
});
const SAVE_ALERT_RULE_TEXT = 'Save Alert Rule';
const TEST_NOTIFICATION_TEXT = 'Test Notification';
const DISCARD_TEXT = 'Discard';
/** Reads the channel list the footer reads, so a test knows it has loaded. */
function ChannelsProbe(): JSX.Element {
const { data } = useChannelOptions();
return <output data-testid="channels-probe">{data.length}</output>;
}
const renderFooter = async (): Promise<void> => {
render(
<>
<ChannelsProbe />
<Footer />
</>,
);
await waitFor(() =>
expect(screen.getByTestId('channels-probe')).toHaveTextContent(
String(CHANNELS.length),
),
);
};
const user = (): ReturnType<typeof userEvent.setup> =>
userEvent.setup({ pointerEventsCheck: 0 });
const lockOf = (testId: string): string | null =>
screen.getByTestId(testId).getAttribute('aria-disabled');
describe('Footer', () => {
beforeEach(() => {
@@ -91,217 +141,219 @@ describe('Footer', () => {
queryType: 'builder',
},
});
useSafeNavigate.mockReturnValue({
safeNavigate: jest.fn(),
});
denyPermissions();
withState({});
server.use(
rest.get(CHANNELS_URL, (_req, res, ctx) =>
res(
ctx.json({
status: 'success',
data: { channels: CHANNELS, total: CHANNELS.length },
}),
),
),
);
});
it('should render the component with 3 buttons', () => {
render(<WrappedFooter />);
expect(screen.getByText(SAVE_ALERT_RULE_TEXT)).toBeInTheDocument();
expect(screen.getByText(TEST_NOTIFICATION_TEXT)).toBeInTheDocument();
expect(screen.getByText(DISCARD_TEXT)).toBeInTheDocument();
afterEach(() => {
jest.clearAllMocks();
server.resetHandlers();
});
it('discard action works correctly', () => {
render(<WrappedFooter />);
fireEvent.click(screen.getByText(DISCARD_TEXT));
it('should render the component with 3 buttons', async () => {
await renderFooter();
expect(screen.getByTestId(SAVE)).toBeInTheDocument();
expect(screen.getByTestId(TEST)).toBeInTheDocument();
expect(screen.getByTestId(DISCARD)).toBeInTheDocument();
});
it('discard action works correctly', async () => {
await renderFooter();
await user().click(screen.getByTestId(DISCARD));
expect(mockDiscardAlertRule).toHaveBeenCalled();
});
it('save alert rule action works correctly', () => {
render(<WrappedFooter />);
fireEvent.click(screen.getByText(SAVE_ALERT_RULE_TEXT));
it('save alert rule action works correctly', async () => {
await renderFooter();
await user().click(screen.getByTestId(SAVE));
expect(mockCreateAlertRule).toHaveBeenCalled();
});
it('update alert rule action works correctly', () => {
jest.spyOn(createAlertState, 'useCreateAlertState').mockReturnValueOnce({
...mockAlertContextState,
isEditMode: true,
});
render(<WrappedFooter />);
fireEvent.click(screen.getByText(SAVE_ALERT_RULE_TEXT));
it('update alert rule action works correctly', async () => {
withState({ isEditMode: true });
await renderFooter();
await user().click(screen.getByTestId(SAVE));
expect(mockUpdateAlertRule).toHaveBeenCalled();
});
it('test notification action works correctly', () => {
render(<WrappedFooter />);
fireEvent.click(screen.getByText(TEST_NOTIFICATION_TEXT));
it('test notification action works correctly', async () => {
await renderFooter();
await user().click(screen.getByTestId(TEST));
expect(mockTestAlertRule).toHaveBeenCalled();
});
it('all buttons are disabled when creating alert rule', () => {
jest.spyOn(createAlertState, 'useCreateAlertState').mockReturnValueOnce({
...mockAlertContextState,
isCreatingAlertRule: true,
});
render(<WrappedFooter />);
it.each([
['creating', { isCreatingAlertRule: true }],
['updating', { isUpdatingAlertRule: true }],
['testing', { isTestingAlertRule: true }],
])('all buttons are disabled when %s alert rule', async (_label, state) => {
withState(state);
await renderFooter();
expect(
screen.getByRole('button', { name: /save alert rule/i }),
).toHaveAttribute('aria-disabled', 'true');
expect(
screen.getByRole('button', { name: /test notification/i }),
).toHaveAttribute('aria-disabled', 'true');
expect(screen.getByRole('button', { name: /discard/i })).toHaveAttribute(
'aria-disabled',
'true',
);
expect(lockOf(SAVE)).toBe('true');
expect(lockOf(TEST)).toBe('true');
expect(lockOf(DISCARD)).toBe('true');
});
it('all buttons are disabled when updating alert rule', () => {
jest.spyOn(createAlertState, 'useCreateAlertState').mockReturnValueOnce({
...mockAlertContextState,
isUpdatingAlertRule: true,
it('create and test buttons are disabled when alert name is missing', async () => {
withState({
alertState: { ...mockAlertContextState.alertState, name: '' },
});
render(<WrappedFooter />);
await renderFooter();
// Target the button elements directly instead of the text spans inside them
expect(
screen.getByRole('button', { name: /save alert rule/i }),
).toHaveAttribute('aria-disabled', 'true');
expect(
screen.getByRole('button', { name: /test notification/i }),
).toHaveAttribute('aria-disabled', 'true');
expect(screen.getByRole('button', { name: /discard/i })).toHaveAttribute(
'aria-disabled',
'true',
);
expect(lockOf(SAVE)).toBe('true');
expect(lockOf(TEST)).toBe('true');
});
it('all buttons are disabled when testing alert rule', () => {
jest.spyOn(createAlertState, 'useCreateAlertState').mockReturnValueOnce({
...mockAlertContextState,
isTestingAlertRule: true,
});
render(<WrappedFooter />);
it('create and test buttons are disabled when notifcation channels are missing and routing policies are disabled', async () => {
withState(withoutChannels(false));
await renderFooter();
// Target the button elements directly instead of the text spans inside them
expect(
screen.getByRole('button', { name: /save alert rule/i }),
).toHaveAttribute('aria-disabled', 'true');
expect(
screen.getByRole('button', { name: /test notification/i }),
).toHaveAttribute('aria-disabled', 'true');
expect(screen.getByRole('button', { name: /discard/i })).toHaveAttribute(
'aria-disabled',
'true',
);
expect(lockOf(SAVE)).toBe('true');
expect(lockOf(TEST)).toBe('true');
});
it('create and test buttons are disabled when alert name is missing', () => {
jest.spyOn(createAlertState, 'useCreateAlertState').mockReturnValueOnce({
...mockAlertContextState,
alertState: {
...mockAlertContextState.alertState,
name: '',
},
});
render(<WrappedFooter />);
it('buttons are enabled even with no notification channels when routing policies are enabled', async () => {
withState(withoutChannels(true));
await renderFooter();
expect(
screen.getByRole('button', { name: /save alert rule/i }),
).toHaveAttribute('aria-disabled', 'true');
expect(
screen.getByRole('button', { name: /test notification/i }),
).toHaveAttribute('aria-disabled', 'true');
expect(lockOf(SAVE)).toBe('false');
expect(lockOf(TEST)).toBe('false');
expect(lockOf(DISCARD)).toBe('false');
});
it('create and test buttons are disabled when notifcation channels are missing and routing policies are disabled', () => {
jest.spyOn(createAlertState, 'useCreateAlertState').mockReturnValueOnce({
...mockAlertContextState,
notificationSettings: {
...mockAlertContextState.notificationSettings,
routingPolicies: false,
},
thresholdState: {
...mockAlertContextState.thresholdState,
thresholds: [
{
...mockAlertContextState.thresholdState.thresholds[0],
channels: [],
it('should show loading state on test notification button when testing alert rule', async () => {
withState({ isTestingAlertRule: true });
await renderFooter();
expect(screen.getByTestId(TEST)).toHaveAttribute('aria-busy', 'true');
});
it.each([
['updating', { isUpdatingAlertRule: true }],
['creating', { isCreatingAlertRule: true }],
])(
'should show loading state on save alert rule button when %s alert rule',
async (_label, state) => {
withState(state);
await renderFooter();
expect(screen.getByTestId(SAVE)).toHaveAttribute('aria-busy', 'true');
},
);
describe('authz', () => {
const RULE_ID = 'rule-1';
const editing = (savedChannelNames: string[]): void => {
withState({ isEditMode: true, ruleId: RULE_ID, savedChannelNames });
};
it('locks Save and Test without create, naming it', async () => {
denyPermissions(RuleCreatePermission);
await renderFooter();
for (const testId of [SAVE, TEST]) {
expect(lockOf(testId)).toBe('true');
expect(screen.getByTestId(testId)).toHaveAttribute(
'data-denied-permissions',
expect.stringContaining(RuleCreatePermission),
);
}
});
it('locks Save without attach on a picked channel', async () => {
const attach = buildNotificationChannelAttachPermission('ch-test');
denyPermissions(attach);
await renderFooter();
expect(screen.getByTestId(SAVE)).toHaveAttribute(
'data-denied-permissions',
attach,
);
});
it('saves an edit with update alone when the channels are unchanged', async () => {
denyPermissions(buildNotificationChannelAttachPermission('ch-test'));
editing(['test-channel']);
await renderFooter();
expect(lockOf(SAVE)).toBe('false');
});
it('locks Save on an edit without update, leaving Test open', async () => {
const update = buildRuleUpdatePermission(RULE_ID);
denyPermissions(update);
editing(['test-channel']);
await renderFooter();
expect(screen.getByTestId(SAVE)).toHaveAttribute(
'data-denied-permissions',
update,
);
expect(lockOf(TEST)).toBe('false');
});
it('needs attach on a channel the edit adds', async () => {
const attach = buildNotificationChannelAttachPermission('ch-test');
denyPermissions(attach);
editing(['other-channel']);
await renderFooter();
expect(screen.getByTestId(SAVE)).toHaveAttribute(
'data-denied-permissions',
expect.stringContaining(attach),
);
});
it('keeps Save and Test locked while the channel list loads', () => {
server.use(
rest.get(CHANNELS_URL, (_req, res, ctx) => res(ctx.delay('infinite'))),
);
render(<Footer />);
for (const testId of [SAVE, TEST]) {
expect(lockOf(testId)).toBe('true');
expect(screen.getByTestId(testId)).not.toHaveAttribute(
'data-denied-permissions',
);
}
});
});
it('shows a server 403 in the error modal like any other failure', async () => {
const forbidden = {
isAxiosError: true,
response: {
status: 403,
data: {
status: 'error',
error: {
code: 'authz_forbidden',
message: 'user/u-1 is not authorized to perform metric:read',
},
],
},
},
} as AxiosError<RenderErrorResponseDTO>;
mockShowErrorModal.mockClear();
await renderFooter();
await user().click(screen.getByTestId(SAVE));
const [, { onError }] = mockCreateAlertRule.mock.calls.at(-1);
await act(async () => {
onError(forbidden);
});
render(<WrappedFooter />);
expect(
screen.getByRole('button', { name: /save alert rule/i }),
).toHaveAttribute('aria-disabled', 'true');
expect(
screen.getByRole('button', { name: /test notification/i }),
).toHaveAttribute('aria-disabled', 'true');
});
it('buttons are enabled even with no notification channels when routing policies are enabled', () => {
jest.spyOn(createAlertState, 'useCreateAlertState').mockReturnValueOnce({
...mockAlertContextState,
notificationSettings: {
...mockAlertContextState.notificationSettings,
routingPolicies: true,
},
thresholdState: {
...mockAlertContextState.thresholdState,
thresholds: [
{
...mockAlertContextState.thresholdState.thresholds[0],
channels: [],
},
],
},
});
render(<WrappedFooter />);
expect(
screen.getByRole('button', { name: /save alert rule/i }),
).not.toHaveAttribute('aria-disabled', 'true');
expect(
screen.getByRole('button', { name: /test notification/i }),
).not.toHaveAttribute('aria-disabled', 'true');
expect(screen.getByRole('button', { name: /discard/i })).not.toHaveAttribute(
'aria-disabled',
'true',
);
});
it('should show loading state on test notification button when testing alert rule', () => {
jest.spyOn(createAlertState, 'useCreateAlertState').mockReturnValueOnce({
...mockAlertContextState,
isTestingAlertRule: true,
});
render(<WrappedFooter />);
expect(
screen.getByRole('button', { name: /test notification/i }),
).toHaveAttribute('aria-busy', 'true');
});
it('should show loading state on save alert rule button when updating alert rule', () => {
jest.spyOn(createAlertState, 'useCreateAlertState').mockReturnValueOnce({
...mockAlertContextState,
isUpdatingAlertRule: true,
});
render(<WrappedFooter />);
expect(
screen.getByRole('button', { name: /save alert rule/i }),
).toHaveAttribute('aria-busy', 'true');
});
it('should show loading state on save alert rule button when creating alert rule', () => {
jest.spyOn(createAlertState, 'useCreateAlertState').mockReturnValueOnce({
...mockAlertContextState,
isCreatingAlertRule: true,
});
render(<WrappedFooter />);
expect(
screen.getByRole('button', { name: /save alert rule/i }),
).toHaveAttribute('aria-busy', 'true');
expect(mockShowErrorModal).toHaveBeenCalledTimes(1);
});
});

View File

@@ -0,0 +1,3 @@
export const WAIT_FOR_TEST_NOTIFICATION =
'Wait for the test notification to finish';
export const WAIT_FOR_SAVE = 'Wait for the alert rule to finish saving';

View File

@@ -32,3 +32,8 @@
color: var(--l2-foreground);
}
}
// A pinned side nav is 240px wide, not the collapsed one the left offset clears.
.app-layout.side-nav-pinned .create-alert-v2-footer {
left: 240px;
}

View File

@@ -0,0 +1,51 @@
import { useMemo } from 'react';
import { useChannelOptions } from 'hooks/notificationChannels/useChannelOptions';
import { getChannelIds } from 'hooks/notificationChannels/utils';
import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';
import { useCreateAlertState } from '../context';
import { getRuleCreateChecks, getRuleSaveChecks } from '../ruleSaveChecks';
export interface UseAlertRuleSaveChecksReturn {
saveChecks: BrandedPermission[];
testChecks: BrandedPermission[];
/** The channel list is still loading, so the channel checks are not known yet. */
isResolvingChannels: boolean;
}
/**
* Save and Test notification checks for the rule form. The channel ids come
* from the channel list the form already loads.
*/
export function useAlertRuleSaveChecks(): UseAlertRuleSaveChecksReturn {
const { thresholdState, savedChannelNames, isEditMode, ruleId } =
useCreateAlertState();
const { data: channels, isLoading } = useChannelOptions();
const selectedChannels = useMemo(
() => thresholdState.thresholds.flatMap((threshold) => threshold.channels),
[thresholdState.thresholds],
);
return useMemo(() => {
const selectedChannelIds = getChannelIds(channels, selectedChannels);
return {
saveChecks: getRuleSaveChecks({
ruleId: isEditMode ? ruleId : undefined,
savedChannelIds: getChannelIds(channels, savedChannelNames),
selectedChannelIds,
}),
testChecks: getRuleCreateChecks(selectedChannelIds),
isResolvingChannels:
isLoading && (selectedChannels.length > 0 || savedChannelNames.length > 0),
};
}, [
channels,
selectedChannels,
savedChannelNames,
isEditMode,
ruleId,
isLoading,
]);
}

View File

@@ -101,84 +101,12 @@
display: flex;
flex-direction: column;
gap: 8px;
.ant-typography {
display: flex;
gap: 4px;
align-items: center;
}
}
.ant-select {
width: 300px;
}
}
.re-notification-container {
display: flex;
flex-direction: column;
gap: 16px;
background-color: var(--l2-background);
border: 1px solid var(--l1-border);
padding: 16px;
margin-top: 16px;
.advanced-option-item {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 16px;
.advanced-option-item-left-content {
display: flex;
flex-direction: column;
gap: 6px;
}
}
.border-bottom {
border-bottom: 1px solid var(--l1-border);
width: 100%;
margin-left: -16px;
margin-right: -32px;
}
.re-notification-condition {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: nowrap;
.ant-typography {
color: var(--l2-foreground);
white-space: nowrap;
}
.ant-select {
width: 200px;
height: 32px;
flex-shrink: 0;
.ant-select-selector {
border: 1px solid var(--l1-border);
&:hover {
border-color: var(--l1-border);
}
&:focus {
border-color: var(--l1-border);
box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.1);
}
}
}
.ant-input {
width: 200px;
flex-shrink: 0;
border: 1px solid var(--l1-border);
}
}
}
}
}

View File

@@ -15,11 +15,6 @@
border-bottom: none;
margin-bottom: -1px;
.prom-ql-icon {
height: 13px;
width: 13px;
}
.explorer-view-option {
display: flex;
align-items: center;

View File

@@ -0,0 +1,65 @@
import {
buildNotificationChannelAttachPermission,
buildNotificationChannelDetachPermission,
} from 'lib/authz/hooks/useAuthZ/permissions/notification-channel.permissions';
import {
buildRuleAttachPermission,
buildRuleDetachPermission,
buildRuleUpdatePermission,
RuleAttachPermission,
RuleCreatePermission,
} from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
import { getRuleCreateChecks, getRuleSaveChecks } from '../ruleSaveChecks';
const ID = 'rule-1';
const UPDATE = buildRuleUpdatePermission(ID);
describe('getRuleCreateChecks', () => {
it('needs only create without channels', () => {
expect(getRuleCreateChecks([])).toStrictEqual([RuleCreatePermission]);
});
it('attaches the rule and each channel once', () => {
expect(getRuleCreateChecks(['a', 'b', 'a'])).toStrictEqual([
RuleCreatePermission,
RuleAttachPermission,
buildNotificationChannelAttachPermission('a'),
buildNotificationChannelAttachPermission('b'),
]);
});
});
describe('getRuleSaveChecks', () => {
it('creates a new rule with its channels', () => {
expect(
getRuleSaveChecks({ savedChannelIds: [], selectedChannelIds: ['a'] }),
).toStrictEqual(getRuleCreateChecks(['a']));
});
it('needs only update when the channels are unchanged', () => {
expect(
getRuleSaveChecks({
ruleId: ID,
savedChannelIds: ['a', 'b'],
selectedChannelIds: ['b', 'a'],
}),
).toStrictEqual([UPDATE]);
});
it('attaches added channels and detaches removed ones', () => {
expect(
getRuleSaveChecks({
ruleId: ID,
savedChannelIds: ['a', 'b'],
selectedChannelIds: ['b', 'c'],
}),
).toStrictEqual([
UPDATE,
buildRuleAttachPermission(ID),
buildNotificationChannelAttachPermission('c'),
buildRuleDetachPermission(ID),
buildNotificationChannelDetachPermission('a'),
]);
});
});

View File

@@ -319,6 +319,20 @@ export function CreateAlertProvider(
handleAlertTypeChange(AlertTypes.METRICS_BASED_ALERT);
}, [handleAlertTypeChange]);
const savedChannelNames = useMemo(
() =>
isEditMode && initialAlertState
? [
...new Set(
initialAlertState.threshold.thresholds.flatMap(
(threshold) => threshold.channels,
),
),
]
: [],
[isEditMode, initialAlertState],
);
const { mutate: createAlertRule, isLoading: isCreatingAlertRule } =
useCreateRule();
@@ -350,6 +364,7 @@ export function CreateAlertProvider(
isUpdatingAlertRule,
isEditMode: isEditMode || false,
ruleId: ruleId || '',
savedChannelNames,
}),
[
createAlertState,
@@ -369,6 +384,7 @@ export function CreateAlertProvider(
isUpdatingAlertRule,
isEditMode,
ruleId,
savedChannelNames,
],
);

View File

@@ -54,6 +54,7 @@ export interface ICreateAlertContextProps {
>;
isEditMode: boolean;
ruleId: string;
savedChannelNames: string[];
}
export interface ICreateAlertProviderProps {
@@ -64,13 +65,6 @@ export interface ICreateAlertProviderProps {
ruleId?: string;
}
export enum AlertCreationStep {
ALERT_DEFINITION = 0,
ALERT_CONDITION = 1,
EVALUATION_SETTINGS = 2,
NOTIFICATION_SETTINGS = 3,
}
export interface AlertState {
name: string;
labels: Labels;

View File

@@ -0,0 +1,55 @@
import { buildNotificationChannelLinkPermissions } from 'lib/authz/hooks/useAuthZ/permissions/notification-channel.permissions';
import {
buildRuleAttachPermission,
buildRuleDetachPermission,
buildRuleUpdatePermission,
RuleAttachPermission,
RuleCreatePermission,
} from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';
import { getLinkSaveChecks } from 'lib/authz/utils/getLinkSaveChecks';
/**
* What creating a rule, or sending a test notification, needs: `create`, and
* `attach` on the rule and on every channel it notifies.
*/
export function getRuleCreateChecks(channelIds: string[]): BrandedPermission[] {
return getLinkSaveChecks({
ownerChecks: [RuleCreatePermission],
owner: {
attach: RuleAttachPermission,
detach: buildRuleDetachPermission('*'),
},
buildItemPermissions: buildNotificationChannelLinkPermissions,
savedIds: [],
incomingIds: channelIds,
});
}
interface RuleSaveChecksInput {
/** Absent for a new rule. */
ruleId?: string;
savedChannelIds: string[];
selectedChannelIds: string[];
}
/** What saving a rule needs, as the rule routes check it. */
export function getRuleSaveChecks({
ruleId,
savedChannelIds,
selectedChannelIds,
}: RuleSaveChecksInput): BrandedPermission[] {
if (!ruleId) {
return getRuleCreateChecks(selectedChannelIds);
}
return getLinkSaveChecks({
ownerChecks: [buildRuleUpdatePermission(ruleId)],
owner: {
attach: buildRuleAttachPermission(ruleId),
detach: buildRuleDetachPermission(ruleId),
},
buildItemPermissions: buildNotificationChannelLinkPermissions,
savedIds: savedChannelIds,
incomingIds: selectedChannelIds,
});
}

View File

@@ -1,21 +1,5 @@
import { AlertTypes } from 'types/api/alerts/alertTypes';
import {
AdvancedOptionsState,
AlertState,
AlertThresholdState,
EvaluationWindowState,
NotificationSettingsState,
} from './context/types';
export interface CreateAlertProps {
alertType: AlertTypes;
}
export interface GetCreateAlertLocalStateFromAlertDefReturn {
basicAlertState: AlertState;
thresholdState: AlertThresholdState;
advancedOptionsState: AdvancedOptionsState;
evaluationWindowState: EvaluationWindowState;
notificationSettingsState: NotificationSettingsState;
}

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