Compare commits

..

8 Commits

Author SHA1 Message Date
ashu8912
bef1303ace fix(authz): address open review comments on the rule FGA stack (#13813)
Some checks are pending
build-staging / prepare (push) Waiting to run
build-staging / js-build (push) Blocked by required conditions
build-staging / go-build (push) Blocked by required conditions
build-staging / staging (push) Blocked by required conditions
Release Drafter / update_release_draft (push) Waiting to run
cacheci / tests (push) Waiting to run
#### Description

Fixes from the open review threads on #13513, #13516, #13728 and #13756.

- Channel pickers keep virtual scroll: `popupMatchSelectWidth={false}`
turned it off. The empty state already wraps at the select's width.
- `LinkAccess` is an `allowed` / `pending` / `denied` union;
`AuthZSelectOption` extends it.
- `useLinkPickerAccess` merges the check results once, not per option.
- `usePlannedDowntimeFormPermissions` returns the rule options, lock
reason and `rule:list` denial.
- `useChannelPickerAccess` maps names to ids with `getChannelIds`.
- The rule views rail shows loading while its query is held, so
`useAlertRuleViews` no longer waits on `enabled`.
- Nits: `updatePermission`, `selectedChannelNames`, `useCallback` for
the create link, one Save click in the routing policy test, no cast in
the threshold test.

#### Issues closed by this PR

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

#### Additional Information

- No change for `EDIT_ALERTS`: `/alerts/edit` is in
`oldNewRoutesMapping` and redirects to `/alerts/overview` before the
role check, and `ALERT_OVERVIEW` is already in
`routeWithInitialAuthZSupport`.
- Existing stories already render both pickers and the views rail; no
story change.
2026-12-03 12:34:04 +00:00
Manika Malhotra
51828488b8 chore(frontend): remove dead code and styles from logs, traces and messaging queues (#13799)
#### Description

- Removes dead code and styles owned by @SigNoz/events-frontend: logs,
traces, API monitoring, messaging queues and pipelines. 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.
- 67 files, +2 / −2,313; 10 files deleted.
- Components only their own test used: the pipeline `Tags` cell and
`SpanLineActionButtons`.
- The v3 autocomplete mocks in the logs, live logs, traces and API
monitoring stories; nothing calls those endpoints.
- The `[data-radix-popper-content-wrapper]` check in `LogDetailBody`; no
Radix popover can render any more.
- Jest mocks of modules those tests never load, exported code nothing
imports, and CSS rules for classes nothing renders.
- 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 | 839 test files, 7,257
tests, 0 failed |
| **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**

- `KEY_ATTRIBUTE_KEYS`, for the key attributes section
`SpanDetailsPanel` has parked.
- `MQDetailPage/index.tsx` and `traceAttributeValuesResponse`, until
#13797 removes their last users. A follow-up removes them.
2026-12-03 12:26:25 +00:00
Pandey
0346b0c04c chore(codeowners): hand H4ad's paths to frontend-maintainers (#13853)
#### Description

- Replace `@H4ad` with `@SigNoz/frontend-maintainers` as owner of the
frontend authz, members, service accounts and Storybook paths.
2026-12-03 12:19:44 +00:00
Abhi kumar
86d9862462 fix(dashboard): drilldown and variable seeding fixes found while embedding (#13764)
#### Description

- A panel whose builder queries are all disabled draws only formulas, so
it offers no drilldown.
- Drilldown offers "Create variable" only when the viewer can edit the
dashboard.
- A custom variable keeps link-seeded values its list doesn't offer, as
typed values, and an auto-fill computed before the seed landed no longer
overwrites it a frame later.

#### Additional Information

Split out of #13568, which now stacks on this.
2026-12-03 05:23:11 +00:00
Gaurav Tewari
c2c0f0a766 fix(query-builder): catch a failed key suggestions request (#13846)
#### Description

- The query search loads key suggestions 300 ms after it mounts, with no
`catch`, so a failed keys request became an unhandled rejection. The
value suggestions already catch theirs.
- A failed key lookup now goes to Sentry and leaves the current
suggestions in place.
- This made `Pages/AI Observability/Explorer › QuickFiltersSettings`
flaky in Storybook CI. The `Failed` story answers every request with a
500. On a fast runner the rejection lands while `Failed` is still
showing, and it has no play to fail. On a slow one it lands during the
next story's play. Same failure on #13824, a backend-only PR: [storybook
(1)](https://github.com/SigNoz/signoz/actions/runs/46659077018/job/142683375286?pr=13824).

#### Issues closed by this PR

Closes SigNoz/nerve-pod#709

#### Screenshots / Screen Recordings

#### Additional Information

Co-authored-by: Gaurav Tewari <tewarig@users.noreply.github.com>
2026-12-03 05:15:56 +00:00
Nityananda Gohain
455e667378 feat(trace-details): implement the span list routes (#13667)
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
- Implements the four list routes: `/spans`, `/spans/{spanID}/children`,
`/descendants` and `/ancestors`.
- They share one path: the route decides which spans are listed, `view`
keeps the ones of its kind in its own order, then `offset` and `limit`
cut the page. It is the picker highlights use, so a highlights list
equals the first page of the same view.
- Two queries, the trace bounds and the tree. `selectFields` adds a read
by ID of the page's spans, at most 1,000; a name without a context is
looked up in both attributes and resource attributes, and a field no
returned span has is reported in `warnings`.
- `ai_usage` ranks by cost, or by tokens when none of the listed spans
has a cost.
  - `query` returns "not implemented" until the next PR.

  #### Additional Information

- Measured locally: 20 ms on a small trace, 45 ms on 30,000 spans, 0.43
s on 1 million spans.
- Measured locally: 20 ms on a small trace, 45 ms on 30,000 spans, 0.43
s on 1 million spans.
  Refs SigNoz/nerve-pod#651
2026-12-03 05:10:08 +00:00
Nityananda Gohain
e1346d7e9c feat(trace-details): open a span in the trace inspect endpoint (#13664)
#### Description

- Implements `GET /api/v1/traces/{traceID}/spans/{spanID}`. The four
list routes still return "not implemented".
- The response is the span itself: the stored fields, every attribute,
every resource attribute and every event. Values are returned whole.
- It makes two queries: the trace bounds, and the span's full row
through the existing `GetTraceSpansByIDs`. It does not load the trace's
tree, so its cost does not grow with the size of the trace.
- It returns no `treeStats` and no other span. A caller gets the tree
stats with the span in any span list, and the spans around it from the
children, descendants and ancestors routes.
- A span ID that is not in the trace returns 404 with code
`trace_span_not_found`. A span whose parent was never received keeps the
parent ID it was sent with.

  #### Additional Information

- There is no unit test for this route.
`tests/integration/tests/tracedetail/06_span.py` covers it: every field
of a span in both attribute layouts, a long value returned whole, a span
with no attributes or events, a root, a span with a missing parent, and
both 404s.

  Refs SigNoz/nerve-pod#651
2026-12-03 04:27:25 +00:00
Nityananda Gohain
fe0f68589a feat(trace-details): implement the trace highlights route (#13657)
- Implements `GET /api/v1/traces/{traceID}/highlights`.
- One query reads a small row for every span into an in-memory tree
(`TraceSkeleton`). The lists, the per-service totals and `treeStats` all
come from it; there is no second read.
- A new tree and not the waterfall's: on 1 million spans it holds about
125 MB against 1,073 MB.
- A span's references are read only when they hold more than the one to
its parent; the rest are rebuilt from the two ids.
  - gen_ai usage is read from the JSON attributes column only.
- `links` is about 97 bytes on every span and almost always holds only
the reference to the parent. The query compares it with that expected
text and sends it only when it differs (a span link, or a root); the
rest are rebuilt from the trace id and the parent id.

  #### Additional Information

- Measured locally: 25 ms on a small trace, 45 ms on 30,000 spans, 0.5 s
on 1 million spans. The tree is not cached.

  Refs SigNoz/nerve-pod#651
2026-12-03 03:56:54 +00:00
182 changed files with 3493 additions and 5583 deletions

View File

@@ -121,7 +121,6 @@ Before writing the clicks, list what has to be on screen for the play's target t
- A second list beside the main one, such as saved views. At 0, loading or failed, its actions are gone.
- Text that depends on an arg. A disabled rule offers Enable, not Disable. A write that fails raises a different toast from one that lands, and one left loading raises none. Pick the expected text from the args.
- Rows that move. A view, a sort or pinning changes which row is locked, pinned or legacy, so find the row by what it is, not by its index.
- A response control that a second request depends on. In the traces explorer span drawer, the `Trace summary` control on `not found` means the trace views would 404 too, so the drawer drops the trace pane, and a span the list doesn't show becomes not found. The Waterfall tab play and the url plays still expected the pane and the span. When one response decides whether another part of the page exists, branch on it too.
Make those checks with the page's own code instead of restating a condition. Build the rows with the builder the handler uses and the view's own filter, and check a permission with the page's own check through `accessFor(...).allows(...)`, or the role against the constant the page gates on, such as `componentPermission.action`. Export the checks from the mocks module, next to the handlers, so a handler change moves them too. The alert rules page has `listedRules`, `hasRowMenu`, `showsNoRulesPage` and `listsSavedViews`; the dashboards list has `listedDashboards`, `canList`, `canCreate` and `canUpdate`.

36
.github/CODEOWNERS vendored
View File

@@ -113,21 +113,21 @@ go.mod @therealpandey
/pkg/modules/role/ @therealpandey
/pkg/types/coretypes/ @therealpandey @vikrantgupta25
/frontend/src/lib/authz/ @H4ad
/frontend/src/container/RolesSettings/ @H4ad
/frontend/src/components/RolesSelect/ @H4ad
/frontend/src/pages/MembersSettings/ @H4ad
/frontend/src/container/MembersSettings/ @H4ad
/frontend/src/components/MembersTable/ @H4ad
/frontend/src/components/EditMemberDrawer/ @H4ad
/frontend/src/components/InviteMembersModal/ @H4ad
/frontend/src/hooks/member/ @H4ad
/frontend/src/pages/ServiceAccountsSettings/ @H4ad
/frontend/src/container/ServiceAccountsSettings/ @H4ad
/frontend/src/components/ServiceAccountsTable/ @H4ad
/frontend/src/components/ServiceAccountDrawer/ @H4ad
/frontend/src/components/CreateServiceAccountModal/ @H4ad
/frontend/src/hooks/serviceAccount/ @H4ad
/frontend/src/lib/authz/ @SigNoz/frontend-maintainers
/frontend/src/container/RolesSettings/ @SigNoz/frontend-maintainers
/frontend/src/components/RolesSelect/ @SigNoz/frontend-maintainers
/frontend/src/pages/MembersSettings/ @SigNoz/frontend-maintainers
/frontend/src/container/MembersSettings/ @SigNoz/frontend-maintainers
/frontend/src/components/MembersTable/ @SigNoz/frontend-maintainers
/frontend/src/components/EditMemberDrawer/ @SigNoz/frontend-maintainers
/frontend/src/components/InviteMembersModal/ @SigNoz/frontend-maintainers
/frontend/src/hooks/member/ @SigNoz/frontend-maintainers
/frontend/src/pages/ServiceAccountsSettings/ @SigNoz/frontend-maintainers
/frontend/src/container/ServiceAccountsSettings/ @SigNoz/frontend-maintainers
/frontend/src/components/ServiceAccountsTable/ @SigNoz/frontend-maintainers
/frontend/src/components/ServiceAccountDrawer/ @SigNoz/frontend-maintainers
/frontend/src/components/CreateServiceAccountModal/ @SigNoz/frontend-maintainers
/frontend/src/hooks/serviceAccount/ @SigNoz/frontend-maintainers
# IdentN Owners
@@ -308,9 +308,9 @@ go.mod @therealpandey
/frontend/src/container/BottomStrip/ @aks07
## Storybook
/frontend/.storybook/ @H4ad
/frontend/src/storybook/ @H4ad
/.claude/skills/signoz-page-story/ @H4ad
/frontend/.storybook/ @SigNoz/frontend-maintainers
/frontend/src/storybook/ @SigNoz/frontend-maintainers
/.claude/skills/signoz-page-story/ @SigNoz/frontend-maintainers
## AI Assistant
/frontend/src/container/AIAssistant/ @SigNoz/nerve @SigNoz/frontend-maintainers

View File

@@ -13065,6 +13065,12 @@ components:
additionalProperties: {}
description: All of them for a span read by ID; the selected ones in a list.
type: object
db_name:
description: Omitted when empty, and in a list unless selected.
type: string
db_operation:
description: Omitted when empty, and in a list unless selected.
type: string
duration_nano:
minimum: 0
type: integer
@@ -13073,8 +13079,26 @@ components:
items:
$ref: '#/components/schemas/SpantypesEvent'
type: array
external_http_method:
description: Method of an outgoing HTTP call. Omitted when empty, and in
a list unless selected.
type: string
external_http_url:
description: Host of an outgoing HTTP call. Omitted when empty, and in a
list unless selected.
type: string
has_error:
type: boolean
http_host:
description: Host or server address. Omitted when empty, and in a list unless
selected.
type: string
http_method:
description: Omitted when empty, and in a list unless selected.
type: string
http_url:
description: Omitted when empty, and in a list unless selected.
type: string
kind_string:
description: For example Server, Client or Internal.
type: string
@@ -13097,6 +13121,11 @@ components:
response_status_code:
description: HTTP or gRPC status code, for example 404.
type: string
scope:
allOf:
- $ref: '#/components/schemas/SpantypesScope'
description: Instrumentation scope. Omitted when empty, and in a list unless
selected.
span_id:
type: string
status_code_string:
@@ -13110,6 +13139,9 @@ components:
type: integer
trace_id:
type: string
trace_state:
description: W3C trace state. Omitted when empty, and in a list unless selected.
type: string
required:
- span_id
- trace_id

View File

@@ -1,6 +0,0 @@
// Test stub for the flame graph's layout worker: jest can't parse
// `import.meta.url` (see moduleNameMapper in jest.config.ts). jsdom has no
// Worker, so the hook computes the layout in place and never calls this.
export function createLayoutWorker(): Worker {
throw new Error('No layout worker under jest');
}

View File

@@ -18,8 +18,6 @@ const config: Config.InitialOptions = {
// The icon glob module uses `import.meta.glob` (Vite-only); jest can't parse
// it, so redirect any import of it to a stub.
'(^|/)iconAssets$': '<rootDir>/__mocks__/iconAssetsMock.ts',
// The flame graph's layout worker is built from `import.meta.url` (Vite-only).
'(^|/)createLayoutWorker$': '<rootDir>/__mocks__/createLayoutWorkerMock.ts',
'^@/(.*)$': '<rootDir>/src/$1',
'\\.(css|less|scss)$': '<rootDir>/__mocks__/cssMock.ts',
'\\.module\\.mjs$': '<rootDir>/__mocks__/cssMock.ts',

View File

@@ -14681,6 +14681,16 @@ export interface SpantypesSpanDTO {
* @description All of them for a span read by ID; the selected ones in a list.
*/
attributes: SpantypesSpanDTOAttributes;
/**
* @type string
* @description Omitted when empty, and in a list unless selected.
*/
db_name?: string;
/**
* @type string
* @description Omitted when empty, and in a list unless selected.
*/
db_operation?: string;
/**
* @type integer
* @minimum 0
@@ -14691,10 +14701,35 @@ export interface SpantypesSpanDTO {
* @description All of them for a span read by ID; none in a list.
*/
events: SpantypesEventDTO[];
/**
* @type string
* @description Method of an outgoing HTTP call. Omitted when empty, and in a list unless selected.
*/
external_http_method?: string;
/**
* @type string
* @description Host of an outgoing HTTP call. Omitted when empty, and in a list unless selected.
*/
external_http_url?: string;
/**
* @type boolean
*/
has_error: boolean;
/**
* @type string
* @description Host or server address. Omitted when empty, and in a list unless selected.
*/
http_host?: string;
/**
* @type string
* @description Omitted when empty, and in a list unless selected.
*/
http_method?: string;
/**
* @type string
* @description Omitted when empty, and in a list unless selected.
*/
http_url?: string;
/**
* @type string
* @description For example Server, Client or Internal.
@@ -14724,6 +14759,10 @@ export interface SpantypesSpanDTO {
* @description HTTP or gRPC status code, for example 404.
*/
response_status_code: string;
/**
* @description Instrumentation scope. Omitted when empty, and in a list unless selected.
*/
scope?: SpantypesScopeDTO;
/**
* @type string
*/
@@ -14747,6 +14786,11 @@ export interface SpantypesSpanDTO {
* @type string
*/
trace_id: string;
/**
* @type string
* @description W3C trace state. Omitted when empty, and in a list unless selected.
*/
trace_state?: string;
}
export interface SpantypesSpanTextMatchDTO {

View File

@@ -8,7 +8,6 @@ import {
const getTraceV4 = async (
props: GetTraceV4PayloadProps,
signal?: AbortSignal,
): Promise<SuccessResponse<GetTraceV4SuccessResponse> | ErrorResponse> => {
let uncollapsedSpans = [...props.uncollapsedSpans];
if (!props.isSelectedSpanIDUnCollapsed) {
@@ -29,7 +28,6 @@ const getTraceV4 = async (
selectedSpanId: props.selectedSpanId,
uncollapsedSpans,
},
signal,
);
// Generated client unwraps the axios response; .data is the waterfall payload.

View File

@@ -1,5 +1,5 @@
import { ReactNode } from 'react';
import { Drawer, type DrawerWidthType } from '@signozhq/ui/drawer';
import { Drawer } from '@signozhq/ui/drawer';
interface DetailsPanelDrawerProps {
isOpen: boolean;
@@ -9,7 +9,6 @@ interface DetailsPanelDrawerProps {
headerSuffix?: ReactNode;
loading?: boolean;
testId?: string;
width?: DrawerWidthType;
}
function DetailsPanelDrawer({
@@ -20,7 +19,6 @@ function DetailsPanelDrawer({
headerSuffix,
loading,
testId,
width,
}: DetailsPanelDrawerProps): JSX.Element {
return (
<Drawer
@@ -29,7 +27,7 @@ function DetailsPanelDrawer({
open={isOpen}
onClose={onClose}
title={title}
width={width}
width="extra-wide"
closePosition="start"
headerSuffix={headerSuffix}
loading={loading}
@@ -44,7 +42,6 @@ DetailsPanelDrawer.defaultProps = {
headerSuffix: undefined,
loading: false,
testId: undefined,
width: 'extra-wide',
};
export default DetailsPanelDrawer;

View File

@@ -72,7 +72,6 @@ function LogDetailBody({
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;

View File

@@ -155,14 +155,6 @@
background: var(--l2-background);
box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.1);
.context-btn {
width: 50% !important;
}
.copy-link-btn {
width: 50% !important;
border-left: 1px solid var(--l1-border) !important;
}
.ant-btn-default {
border: none;
box-shadow: none;

View File

@@ -83,9 +83,3 @@ export const LogText = styled.div<LogTextProps>`
: 'white-space: nowrap;'};
};
`;
export const SelectedLog = styled.div`
display: flex;
width: 100%;
overflow: hidden;
`;

View File

@@ -27,14 +27,3 @@
border-color: var(--l1-border) !important;
}
}
// In table/column view, keep action buttons visible at the viewport's right edge
.log-line-action-buttons.table-view-log-actions {
position: absolute;
top: 50%;
right: 8px;
left: auto;
transform: translateY(-50%);
margin: 0;
z-index: 5;
}

View File

@@ -1,7 +1,4 @@
import { blue } from '@ant-design/colors';
import { Color } from '@signozhq/design-tokens';
import Space from 'periscope/components/Space/Space';
import Col from 'periscope/components/Col/Col';
import Row from 'periscope/components/Row/Row';
import { FontSize } from 'container/OptionsMenu/types';
import { Info } from '@signozhq/icons';
@@ -73,12 +70,6 @@ export const InfoIconWrapper = styled(Info)`
height: auto;
`;
export const ExpandIconWrapper = styled(Col)`
color: ${blue[6]};
padding: 0.25rem 0.375rem;
cursor: pointer;
`;
export const RawLogContent = styled.div<RawLogContentProps>`
margin-bottom: 0;
font-family: 'SF Mono', monospace;
@@ -112,11 +103,3 @@ export const RawLogContent = styled.div<RawLogContentProps>`
cursor: ${({ $isActiveLog, $isReadOnly }): string =>
$isActiveLog || $isReadOnly ? 'initial' : 'pointer'};
`;
export const ActionButtonsWrapper = styled(Space)`
position: absolute;
transform: translate(-50%, -50%);
top: 50%;
right: 0;
cursor: pointer;
`;

View File

@@ -187,177 +187,6 @@
padding: 12px;
}
.add-new-column-container {
display: flex;
flex-direction: column;
.add-new-column-header {
display: flex;
flex-direction: column;
padding: 8px;
gap: 8px;
.back-icon {
cursor: pointer;
}
.title {
display: flex;
gap: 4px;
align-items: center;
color: var(--muted-foreground);
}
}
.add-new-column-content {
display: flex;
flex-direction: column;
padding-bottom: 16px;
min-height: 240px;
max-height: 400px;
.loading-container {
padding: 8px;
}
.column-format-new-options {
overflow-y: auto;
overflow-x: hidden;
.column-name {
padding: 4px 8px;
border-radius: 1px;
color: var(--l2-foreground);
&.selected {
background-color: var(--l3-background);
cursor: pointer;
}
}
&::-webkit-scrollbar {
height: 1rem;
width: 0.2rem;
}
}
}
}
.selected-item-content-container {
.add-new-column-header {
padding: 8px;
}
.title {
color: var(--l1-foreground);
margin-bottom: 12px;
display: flex;
justify-content: space-between;
align-items: center;
.lucide {
color: var(--l2-foreground);
cursor: pointer;
}
}
.horizontal-line {
height: 1px;
background: var(--l3-background);
}
.loading-container {
margin: 12px 0;
}
.item-content {
padding: 12px;
.column-format,
.column-format-new-options {
display: flex;
gap: 12px;
flex-direction: column;
margin-top: 12px;
.column-name {
color: var(--l2-foreground);
display: flex;
justify-content: space-between;
align-items: center;
gap: 8px;
cursor: pointer;
&.default-column {
color: var(--l2-foreground);
cursor: not-allowed;
}
&.no-columns-selected {
color: var(--l3-foreground);
cursor: not-allowed;
}
&.add-new-column-btn {
color: var(--l2-foreground);
cursor: pointer;
}
.name {
flex: 1;
overflow: hidden;
white-space: nowrap;
overflow: hidden;
cursor: pointer;
}
.delete-btn {
display: none;
flex: 0 0 16px;
cursor: pointer;
}
&:hover {
.delete-btn {
display: block;
}
}
}
overflow-x: hidden;
&::-webkit-scrollbar {
height: 1rem;
width: 0.2rem;
}
}
.column-format {
max-height: 150px;
overflow: auto;
overflow-x: hidden;
}
.column-format-new-options {
max-height: 150px;
overflow-y: auto;
overflow-x: hidden;
}
.column-divider {
margin: 12px 0;
border-top: 2px solid var(--l1-border);
}
}
}
&.active {
.nested-menu-container {
backdrop-filter: blur(18px);
@@ -368,26 +197,6 @@
}
}
}
.selected-item-content-container {
width: 110%;
margin-left: -5%;
border-radius: 4px;
border: 1px solid var(--l1-border);
background: linear-gradient(
139deg,
color-mix(in srgb, var(--surface-2) 80%, transparent) 0%,
color-mix(in srgb, var(--surface-2) 90%, transparent) 98.68%
);
box-shadow: 4px 10px 16px 2px rgba(0, 0, 0, 0.2);
backdrop-filter: blur(20px);
.column-format {
margin-top: 0px;
}
}
}
}
}

View File

@@ -26,9 +26,3 @@
width: max-content;
}
}
.select-label-with-coming-soon {
display: flex;
align-items: center;
justify-content: space-between;
}

View File

@@ -1,39 +1,8 @@
import { Color } from '@signozhq/design-tokens';
import { Tooltip } from 'antd';
import type { DefaultOptionType } from 'antd/es/select';
import { Info } from '@signozhq/icons';
import './MQCommon.styles.scss';
export function ComingSoon(): JSX.Element {
return (
<Tooltip
title={
<div>
Join our Slack community for more details:{' '}
<a
href="https://signoz.io/slack"
rel="noopener noreferrer"
target="_blank"
onClick={(e): void => e.stopPropagation()}
>
SigNoz Community
</a>
</div>
}
placement="top"
overlayClassName="tooltip-overlay"
>
<div className="coming-soon">
<div className="coming-soon__text">Coming Soon</div>
<div className="coming-soon__icon">
<Info size={10} color={Color.BG_SIENNA_400} />
</div>
</div>
</Tooltip>
);
}
export function SelectMaxTagPlaceholder(
omittedValues: Partial<DefaultOptionType>[],
): JSX.Element {
@@ -43,15 +12,3 @@ export function SelectMaxTagPlaceholder(
</Tooltip>
);
}
export function SelectLabelWithComingSoon({
label,
}: {
label: string;
}): JSX.Element {
return (
<div className="select-label-with-coming-soon">
{label} <ComingSoon />
</div>
);
}

View File

@@ -1,3 +1,4 @@
import { useCallback } from 'react';
import { Button } from '@signozhq/ui/button';
import { Typography } from '@signozhq/ui/typography';
import ROUTES from 'constants/routes';
@@ -22,6 +23,10 @@ function NotificationChannelsNotFound({
}: NotificationChannelsNotFoundProps): JSX.Element {
const { isGranted, isLoading, error } = useAuthZ(CREATE_CHECKS);
const canCreate = !!error || isGranted(NotificationChannelCreatePermission);
const openCreateChannel = useCallback(
(): void => openInNewTab(ROUTES.CHANNELS_NEW),
[],
);
return (
<div className={styles.container}>
@@ -43,7 +48,7 @@ function NotificationChannelsNotFound({
color="primary"
size="sm"
testId="channels-not-found-create"
onClick={(): void => openInNewTab(ROUTES.CHANNELS_NEW)}
onClick={openCreateChannel}
>
Create one here.
</Button>

View File

@@ -16,6 +16,7 @@ import {
startCompletion,
} from '@codemirror/autocomplete';
import { javascript } from '@codemirror/lang-javascript';
import * as Sentry from '@sentry/react';
import { Color } from '@signozhq/design-tokens';
import { copilot } from '@uiw/codemirror-theme-copilot';
import { githubLight } from '@uiw/codemirror-theme-github';
@@ -361,9 +362,12 @@ function QuerySearch({
metricNamespace,
},
builderQueryType,
);
).catch((error: unknown) => {
Sentry.captureException(error);
return null;
});
if (response.data.keys) {
if (response?.data.keys) {
const { keys } = response.data;
const options = generateOptions(keys);
// Deduplicate by full variant identity (name + context + data type), NOT by

View File

@@ -1,51 +1,3 @@
export const MOCK_USE_QUERIES_DATA = [
{
isLoading: false,
isError: false,
error: null,
data: {
statusCode: 200,
payload: [
{
exceptionType: '*errors.errorString',
exceptionMessage: 'redis timeout',
exceptionCount: 2510,
lastSeen: '2025-04-14T18:27:57.797616374Z',
firstSeen: '2025-04-14T17:58:00.262775497Z',
serviceName: 'redis-manual',
groupID: '511b9c91a92b9c5166ecb77235f5743b',
},
],
},
},
{
status: 'success',
isLoading: false,
isSuccess: true,
isError: false,
isIdle: false,
data: {
statusCode: 200,
error: null,
payload: 525,
},
dataUpdatedAt: 1744661020341,
error: null,
errorUpdatedAt: 0,
failureCount: 0,
errorUpdateCount: 0,
isFetched: true,
isFetchedAfterMount: true,
isFetching: false,
isRefetching: false,
isLoadingError: false,
isPlaceholderData: false,
isPreviousData: false,
isRefetchError: false,
isStale: true,
},
];
export const INIT_URL_WITH_COMMON_QUERY =
'/exceptions?compositeQuery=%257B%2522queryType%2522%253A%2522builder%2522%252C%2522builder%2522%253A%257B%2522queryData%2522%253A%255B%257B%2522dataSource%2522%253A%2522traces%2522%252C%2522queryName%2522%253A%2522A%2522%252C%2522aggregateOperator%2522%253A%2522noop%2522%252C%2522aggregateAttribute%2522%253A%257B%2522id%2522%253A%2522----resource--false%2522%252C%2522dataType%2522%253A%2522%2522%252C%2522key%2522%253A%2522%2522%252C%2522isColumn%2522%253Afalse%252C%2522type%2522%253A%2522resource%2522%252C%2522isJSON%2522%253Afalse%257D%252C%2522timeAggregation%2522%253A%2522rate%2522%252C%2522spaceAggregation%2522%253A%2522sum%2522%252C%2522functions%2522%253A%255B%255D%252C%2522filters%2522%253A%257B%2522items%2522%253A%255B%257B%2522id%2522%253A%2522db118ac7-9313-4adb-963f-f31b5b32c496%2522%252C%2522op%2522%253A%2522in%2522%252C%2522key%2522%253A%257B%2522key%2522%253A%2522deployment.environment%2522%252C%2522dataType%2522%253A%2522string%2522%252C%2522type%2522%253A%2522resource%2522%252C%2522isColumn%2522%253Afalse%252C%2522isJSON%2522%253Afalse%257D%252C%2522value%2522%253A%2522mq-kafka%2522%257D%255D%252C%2522op%2522%253A%2522AND%2522%257D%252C%2522expression%2522%253A%2522A%2522%252C%2522disabled%2522%253Afalse%252C%2522stepInterval%2522%253A60%252C%2522having%2522%253A%255B%255D%252C%2522limit%2522%253Anull%252C%2522orderBy%2522%253A%255B%255D%252C%2522groupBy%2522%253A%255B%255D%252C%2522legend%2522%253A%2522%2522%252C%2522reduceTo%2522%253A%2522avg%2522%257D%255D%252C%2522queryFormulas%2522%253A%255B%255D%257D%252C%2522promql%2522%253A%255B%257B%2522name%2522%253A%2522A%2522%252C%2522query%2522%253A%2522%2522%252C%2522legend%2522%253A%2522%2522%252C%2522disabled%2522%253Afalse%257D%255D%252C%2522clickhouse_sql%2522%253A%255B%257B%2522name%2522%253A%2522A%2522%252C%2522legend%2522%253A%2522%2522%252C%2522disabled%2522%253Afalse%252C%2522query%2522%253A%2522%2522%257D%255D%252C%2522id%2522%253A%2522dd576d04-0822-476d-b0c2-807a7af2e5e7%2522%257D';

View File

@@ -50,16 +50,6 @@
font-family: var(--code-base-500-font-family);
}
.radio-button {
display: flex;
align-items: center;
justify-content: center;
padding-top: var(--padding-1);
border: 1px solid var(--l1-border);
background: var(--l3-background);
box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.1);
}
.round-metric-tag {
display: inline-flex;
padding: 2px 8px;
@@ -783,80 +773,5 @@
gap: 12px;
cursor: pointer;
}
.no-dependent-services-message-container {
height: 30vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
.no-dependent-services-message-content {
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: center;
width: fit-content;
padding: 24px;
}
.no-dependent-services-message {
margin-top: 8px;
}
}
}
}
.end-point-details-zero-state-wrapper {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 4px;
height: 100%;
.end-point-details-zero-state-content {
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: center;
gap: 4px;
height: 100%;
}
.end-point-details-zero-state-content-wrapper {
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: flex-start;
gap: 12px;
.end-point-details-zero-state-text-content {
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: center;
gap: 8px;
.title {
color: var(--l1-foreground);
}
.description {
color: var(--l2-foreground);
}
}
.ant-select {
width: 100%;
}
}
.ant-select-item,
.ant-select-item-option-content {
flex: auto;
white-space: normal;
overflow-wrap: break-word;
}
}

View File

@@ -69,13 +69,6 @@ jest.mock('antd', () => {
))}
</div>
)),
Typography: {
Text: jest
.fn()
.mockImplementation(({ children }) => (
<div data-testid="typography-text">{children}</div>
)),
},
};
});

View File

@@ -130,13 +130,6 @@ jest.mock('antd', () => {
{children}
</div>
)),
Typography: {
Text: jest
.fn()
.mockImplementation(({ children }) => (
<div data-testid="typography-text">{children}</div>
)),
},
Button: {
...originalModule.Button,
Group: jest.fn().mockImplementation(({ children, className }) => (

View File

@@ -46,13 +46,6 @@ jest.mock('antd', () => {
)}
</div>
)),
Typography: {
Text: jest.fn().mockImplementation(({ children, className }) => (
<div data-testid="typography-text" className={className}>
{children}
</div>
)),
},
};
});

View File

@@ -1,16 +1,3 @@
import { domainNameKey } from './constants';
export interface APIMonitoringResponseRow {
data: {
endpoints: number | string;
error_rate: number | string;
lastseen: number | string;
[domainNameKey]: string;
p99: number | string;
rps: number | string;
};
}
export interface APIMonitoringResponseColumn {
name: string;
signal: string;
@@ -22,12 +9,6 @@ export interface APIMonitoringResponseColumn {
columnType: string;
}
export interface EndPointsResponseRow {
data: {
[key: string]: string | number | undefined;
};
}
export interface APIDomainsRowData {
key: string;
domainName: string;

View File

@@ -1,32 +1,24 @@
import { ReactNode } from 'react';
import { TableColumnType as ColumnType, Tooltip } from 'antd';
import { Progress } from '@signozhq/ui/progress';
import { Badge } from '@signozhq/ui/badge';
import { combineInitialAndUserExpression } from 'components/QueryBuilderV2/QueryV2/QuerySearch/utils';
import { formatValueForExpression } from 'components/QueryBuilderV2/utils';
import {
FiltersType,
IQuickFiltersConfig,
} from 'components/QuickFilters/types';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { GraphClickMetaData } from 'container/WidgetCard/hooks/useNavigateToExplorerPages';
import { getWidgetQueryBuilder } from 'container/MetricsApplication/MetricsApplication.factory';
import { convertNanoToMilliseconds } from 'container/MetricsExplorer/Summary/utils';
import dayjs from 'dayjs';
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
import { cloneDeep } from 'lodash-es';
import { ArrowUpDown, ChevronDown, ChevronRight, Info } from '@signozhq/icons';
import { ArrowUpDown, Info } from '@signozhq/icons';
import { getWidgetQuery } from 'pages/MessagingQueues/MQDetails/MetricPage/MetricPageUtil';
import { Widgets } from 'types/api/widgets/widget';
import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
import {
BaseAutocompleteData,
DataTypes,
} from 'types/api/queryBuilder/queryAutocompleteResponse';
import {
IBuilderQuery,
OrderByPayload,
TagFilterItem,
} from 'types/api/queryBuilder/queryBuilderData';
import {
@@ -41,11 +33,7 @@ import { v4 } from 'uuid';
import { domainNameKey } from './constants';
import { SPAN_ATTRIBUTES } from './Explorer/Domains/DomainDetails/constants';
import {
APIDomainsRowData,
APIMonitoringResponseColumn,
EndPointsResponseRow,
} from './types';
import { APIDomainsRowData, APIMonitoringResponseColumn } from './types';
function metricProgressColor(
percent: number,
@@ -91,40 +79,6 @@ export const getDomainScopeExpression = (
.filter(Boolean)
.join(' AND ');
export const ApiMonitoringQuickFiltersConfig: IQuickFiltersConfig[] = [
{
type: FiltersType.CHECKBOX,
title: 'Environment',
attributeKey: {
key: 'deployment.environment',
dataType: DataTypes.String,
type: 'resource',
},
defaultOpen: true,
},
{
type: FiltersType.CHECKBOX,
title: 'Service Name',
attributeKey: {
key: 'service.name',
dataType: DataTypes.String,
type: 'resource',
},
defaultOpen: true,
},
{
type: FiltersType.CHECKBOX,
title: 'RPC Method',
attributeKey: {
key: 'rpc.method',
dataType: DataTypes.String,
type: 'tag',
},
defaultOpen: true,
},
];
export const getLastUsedRelativeTime = (lastRefresh: number): string => {
const currentTime = dayjs();
@@ -571,258 +525,6 @@ const defaultGroupBy = [
// },
];
export const getEndPointsQueryPayload = (
groupBy: BaseAutocompleteData[],
domainName: string,
start: number,
end: number,
): GetQueryResultsProps[] => {
const isGroupedByAttribute = groupBy.length > 0;
return [
{
selectedTime: 'GLOBAL_TIME',
graphType: PANEL_TYPES.TABLE,
query: {
builder: {
queryData: [
{
aggregateAttribute: {
dataType: DataTypes.String,
key: 'span_id',
type: '',
},
aggregateOperator: 'count',
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [
{
id: 'ec316e57',
key: {
dataType: DataTypes.String,
key: SPAN_ATTRIBUTES.SERVER_NAME,
type: '',
},
op: '=',
value: domainName,
},
{
id: '212678b9',
key: {
key: 'kind_string',
dataType: DataTypes.String,
type: '',
},
op: '=',
value: 'Client',
},
],
op: 'AND',
},
functions: [],
groupBy: isGroupedByAttribute ? groupBy : defaultGroupBy,
having: [],
legend: '',
limit: 1000,
orderBy: [],
queryName: 'A',
reduceTo: ReduceOperators.AVG,
spaceAggregation: 'sum',
stepInterval: 60,
timeAggregation: 'count',
},
{
aggregateAttribute: {
dataType: DataTypes.Float64,
key: 'duration_nano',
type: '',
},
aggregateOperator: 'p99',
dataSource: DataSource.TRACES,
disabled: false,
expression: 'B',
filters: {
items: [
{
id: '46d57857',
key: {
dataType: DataTypes.String,
key: SPAN_ATTRIBUTES.SERVER_NAME,
type: '',
},
op: '=',
value: domainName,
},
{
id: '212678b9',
key: {
key: 'kind_string',
dataType: DataTypes.String,
type: '',
},
op: '=',
value: 'Client',
},
],
op: 'AND',
},
functions: [],
groupBy: isGroupedByAttribute ? groupBy : defaultGroupBy,
having: [],
legend: '',
limit: 1000,
orderBy: [],
queryName: 'B',
reduceTo: ReduceOperators.AVG,
spaceAggregation: 'sum',
stepInterval: 60,
timeAggregation: 'p99',
},
{
aggregateAttribute: {
dataType: DataTypes.String,
id: 'timestamp------false',
key: 'timestamp',
type: '',
},
aggregateOperator: 'max',
dataSource: DataSource.TRACES,
disabled: false,
expression: 'C',
filters: {
items: [
{
id: '4a237616',
key: {
dataType: DataTypes.String,
key: SPAN_ATTRIBUTES.SERVER_NAME,
type: '',
},
op: '=',
value: domainName,
},
{
id: '212678b9',
key: {
key: 'kind_string',
dataType: DataTypes.String,
type: '',
},
op: '=',
value: 'Client',
},
],
op: 'AND',
},
functions: [],
groupBy: isGroupedByAttribute ? groupBy : defaultGroupBy,
having: [],
legend: '',
limit: 1000,
orderBy: [],
queryName: 'C',
reduceTo: ReduceOperators.AVG,
spaceAggregation: 'sum',
stepInterval: 60,
timeAggregation: 'max',
},
{
aggregateAttribute: {
dataType: DataTypes.String,
key: 'span_id',
type: '',
},
aggregateOperator: 'count',
dataSource: DataSource.TRACES,
disabled: true,
expression: 'D',
filters: {
items: [
{
id: 'f162de1e',
key: {
dataType: DataTypes.String,
key: SPAN_ATTRIBUTES.SERVER_NAME,
type: '',
},
op: '=',
value: domainName,
},
{
id: '3df0ac1d',
key: {
dataType: DataTypes.bool,
key: 'has_error',
type: '',
},
op: '=',
value: 'true',
},
{
id: '212678b9',
key: {
key: 'kind_string',
dataType: DataTypes.String,
type: '',
},
op: '=',
value: 'Client',
},
],
op: 'AND',
},
functions: [],
groupBy: isGroupedByAttribute ? groupBy : defaultGroupBy,
having: [],
legend: '',
limit: 1000,
orderBy: [],
queryName: 'D',
reduceTo: ReduceOperators.AVG,
spaceAggregation: 'sum',
stepInterval: 60,
timeAggregation: 'count',
},
],
queryFormulas: [
{
queryName: 'F1',
expression: '(D/A)*100',
disabled: false,
legend: 'error percentage',
},
],
queryTraceOperator: [],
},
clickhouse_sql: [
{
disabled: false,
legend: '',
name: 'A',
query: '',
},
],
id: '315b15fa-ff0c-442f-89f8-2bf4fb1af2f2',
promql: [
{
disabled: false,
legend: '',
name: 'A',
query: '',
},
],
queryType: EQueryType.QUERY_BUILDER,
},
variables: {},
formatForWeb: true,
start,
end,
step: 60,
},
];
};
function buildFilterExpression(
domainName: string,
filterExpression: string,
@@ -907,16 +609,6 @@ export const getTopErrorsQueryPayload = (
};
};
export interface EndPointsTableRowData {
key: string;
endpointName: string;
callCount: number | string;
latency: number | string;
errorRate: number | string;
lastUsed: string | number;
groupedByMeta?: Record<string, string | number>;
}
export const extractPortAndEndpoint = (
url: string,
): { port: string; endpoint: string } => {
@@ -937,258 +629,6 @@ export const extractPortAndEndpoint = (
}
};
export const getEndPointsColumnsConfig = (
isGroupedByAttribute: boolean,
expandedRowKeys: React.Key[],
// eslint-disable-next-line sonarjs/cognitive-complexity
): ColumnType<EndPointsTableRowData>[] => [
{
title: (
<div className="endpoint-name-header">
{isGroupedByAttribute ? 'Endpoint group' : 'Endpoint'}
</div>
),
dataIndex: 'endpointName',
key: 'endpointName',
width: 180,
ellipsis: true,
sorter: false,
className: 'column',
render: (text: string, record: EndPointsTableRowData): React.ReactNode => {
const endPointName = isGroupedByAttribute
? text
: extractPortAndEndpoint(record.endpointName).endpoint;
return (
<div className="endpoint-name-value">
{((): React.ReactNode => {
if (!isGroupedByAttribute) {
return null;
}
return expandedRowKeys.includes(record.key) ? (
<ChevronDown size={14} />
) : (
<ChevronRight size={14} />
);
})()}
{isGroupedByAttribute
? text.split(',').map((value) => (
<Badge
textTransform="none"
variant="solid"
key={value}
color="secondary"
>
{value === '' ? '<no-value>' : value}
</Badge>
))
: endPointName}
</div>
);
},
},
{
title: <div className="column-header">Port</div>,
dataIndex: 'port',
key: 'port',
width: 180,
ellipsis: true,
sorter: false,
align: 'right',
className: `column`,
},
{
title: (
<div className="column-header">
Num of calls <ArrowUpDown size={14} />
</div>
),
dataIndex: 'callCount',
key: 'callCount',
width: 180,
ellipsis: true,
align: 'right',
className: `column`,
},
{
title: (
<div>
Error <span className="round-metric-tag">%</span>
</div>
),
dataIndex: 'errorRate',
key: 'errorRate',
width: 120,
sorter: true,
align: 'right',
className: `column`,
render: (errorRate: number | string): React.ReactNode => (
<div className="progress-bar error-rate">
<Progress
percent={Number(
(
(errorRate === 'n/a' || errorRate === '-' ? 0 : errorRate) as number
).toFixed(1),
)}
showInfo
color={metricProgressColor(
Number(
(
(errorRate === 'n/a' || errorRate === '-' ? 0 : errorRate) as number
).toFixed(1),
),
)}
/>
</div>
),
},
{
title: (
<div>
Latency <span className="round-metric-tag">ms</span>
</div>
),
dataIndex: 'latency',
key: 'latency',
width: 120,
sorter: true,
align: 'right',
className: `column`,
},
{
title: <div>Last used</div>,
dataIndex: 'lastUsed',
key: 'lastUsed',
width: 120,
sorter: true,
align: 'right',
className: `column`,
// eslint-disable-next-line sonarjs/no-identical-functions
render: (lastUsed: string): string =>
lastUsed === 'n/a' || lastUsed === '-'
? '-'
: getLastUsedRelativeTime(new Date(lastUsed).getTime()),
},
];
export const formatEndPointsDataForTable = (
data: EndPointsResponseRow[] | undefined,
groupBy: BaseAutocompleteData[],
orderBy?: OrderByPayload | null,
// eslint-disable-next-line sonarjs/cognitive-complexity
): EndPointsTableRowData[] => {
if (!data) {
return [];
}
const isGroupedByAttribute = groupBy.length > 0;
let formattedData: EndPointsTableRowData[] = [];
if (!isGroupedByAttribute) {
formattedData = data?.map((endpoint) => {
const { port } = extractPortAndEndpoint(
(endpoint.data[SPAN_ATTRIBUTES.HTTP_URL] as string) || '',
);
return {
key: v4(),
endpointName: (endpoint.data[SPAN_ATTRIBUTES.HTTP_URL] as string) || '-',
port,
callCount:
endpoint.data.A === 'n/a' || endpoint.data.A === undefined
? '-'
: endpoint.data.A,
latency:
endpoint.data.B === 'n/a' || endpoint.data.B === undefined
? '-'
: Math.round(Number(endpoint.data.B) / 1000000), // Convert from nanoseconds to milliseconds
lastUsed:
endpoint.data.C === 'n/a' || endpoint.data.C === undefined
? '-'
: new Date(Math.floor(Number(endpoint.data.C) / 1000000)).toISOString(), // Convert from nanoseconds to milliseconds
errorRate:
endpoint.data.F1 === undefined || endpoint.data.F1 === 'n/a'
? 0
: Number(endpoint.data.F1),
};
});
} else {
const groupedByAttributeData = groupBy.map((attribute) => attribute.key);
formattedData = data?.map((endpoint) => {
const newEndpointName = groupedByAttributeData
.map((attribute) => endpoint.data[attribute])
.join(',');
return {
key: v4(),
endpointName: newEndpointName,
callCount:
endpoint.data.A === 'n/a' || endpoint.data.A === undefined
? '-'
: endpoint.data.A,
latency:
endpoint.data.B === 'n/a' || endpoint.data.B === undefined
? '-'
: Math.round(Number(endpoint.data.B) / 1000000), // Convert from nanoseconds to milliseconds
lastUsed:
endpoint.data.C === 'n/a' || endpoint.data.C === undefined
? '-'
: getLastUsedRelativeTime(Math.floor(Number(endpoint.data.C) / 1000000)), // Convert from nanoseconds to milliseconds
errorRate:
endpoint.data.D === 'n/a' || endpoint.data.D === undefined
? 0
: Number(endpoint.data.D),
groupedByMeta: groupedByAttributeData.reduce(
(acc, attribute) => {
acc[attribute] = endpoint.data[attribute] || '';
return acc;
},
{} as Record<string, string | number>,
),
};
});
}
// Apply sorting if orderBy is provided
if (orderBy) {
formattedData.sort((a, b) => {
let valueA: number | string = a[
orderBy.columnName as keyof EndPointsTableRowData
] as number | string;
let valueB: number | string = b[
orderBy.columnName as keyof EndPointsTableRowData
] as number | string;
// Handle special cases for each column type
if (
orderBy.columnName === 'callCount' ||
orderBy.columnName === 'latency' ||
orderBy.columnName === 'errorRate'
) {
valueA = valueA === '-' || valueA === 'n/a' ? 0 : Number(valueA);
valueB = valueB === '-' || valueB === 'n/a' ? 0 : Number(valueB);
} else if (orderBy.columnName === 'lastUsed') {
// confirm once the implication of this
valueA =
valueA === '-' || valueA === 'n/a'
? new Date(0).getTime()
: new Date(valueA as string).getTime();
valueB =
valueB === '-' || valueB === 'n/a'
? new Date(0).getTime()
: new Date(valueB as string).getTime();
}
// Apply sort direction
if (orderBy.order === 'asc') {
return valueA > valueB ? 1 : -1;
}
return valueA < valueB ? 1 : -1;
});
}
return formattedData;
};
export type TopErrorsResponseRow = ScalarData;
export interface TopErrorsTableRowData {
@@ -1333,37 +773,6 @@ export const getTopErrorsColumnsConfig =
},
];
export const createFiltersForSelectedRowData = (
selectedRowData: EndPointsTableRowData,
currentFilters?: IBuilderQuery['filters'],
): IBuilderQuery['filters'] => {
const baseFilters: IBuilderQuery['filters'] = {
items: [...(currentFilters?.items || [])],
op: 'and',
};
if (!selectedRowData) {
return baseFilters;
}
const { groupedByMeta = {} } = selectedRowData;
// Replace for...of with Object.keys().map()
baseFilters.items.push(
...Object.keys(groupedByMeta).map((key) => ({
key: {
key,
type: null,
},
op: '=',
value: groupedByMeta[key] || '',
id: key,
})),
);
return baseFilters;
};
// First query payload for endpoint metrics
// Second query payload for endpoint status code table
// Third query payload for endpoint dependant services
@@ -2465,21 +1874,6 @@ export const dependentServicesColumns: ColumnType<DependentServicesData>[] = [
},
];
export const getFormattedChartData = (
data: MetricRangePayloadProps,
newLegendArray: string[],
): MetricRangePayloadProps => {
const result = cloneDeep(data);
if (result?.data?.result) {
result.data.result = result?.data?.result?.map((series, index) => ({
...series,
legend: newLegendArray[index],
}));
}
return result;
};
const getStatusCodeClass = (statusCode: string): string => {
const code = parseInt(statusCode, 10);
@@ -3100,40 +2494,6 @@ const getStartAndEndStatusCode = (
}
};
/**
* Creates filter items for bar chart based on group by fields and request data
* Used specifically for filtering status code ranges in bar charts
* @param groupBy Array of group by fields to create filters for
* @param requestData Data from graph click containing values to filter on
* @returns Array of TagFilterItems with >= and < operators for status code ranges
*/
export const createGroupByFiltersForBarChart = (
groupBy: BaseAutocompleteData[],
requestData: GraphClickMetaData,
): TagFilterItem[] =>
groupBy
.map((gb) => {
const value = requestData[gb.key];
const [startStatusCode, endStatusCode] = getStartAndEndStatusCode(value);
return value
? [
{
id: v4(),
key: gb,
op: '>=',
value: startStatusCode,
},
{
id: v4(),
key: gb,
op: '<=',
value: endStatusCode,
},
]
: [];
})
.flat();
export const getCustomFiltersForBarChart = (
metric:
| {

View File

@@ -191,7 +191,6 @@ function ThresholdItem({
updateThreshold(threshold.id, 'channels', value)
}
data-testid="threshold-notification-channel-select"
popupMatchSelectWidth={false}
style={{ width: 350 }}
options={channelOptions}
onDropdownVisibleChange={onPickerVisibleChange}

View File

@@ -11,7 +11,6 @@ import {
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 {
@@ -532,7 +531,7 @@ describe('ThresholdItem', () => {
...mockUseAuthZDeny()([]),
isLoading: true,
permissions: null,
} as UseAuthZResult);
});
renderThresholdItem();
await openPicker();

View File

@@ -22,13 +22,13 @@ export function useAlertRuleSaveChecks(): UseAlertRuleSaveChecksReturn {
useCreateAlertState();
const { data: channels, isLoading } = useChannelOptions();
const selectedChannels = useMemo(
const selectedChannelNames = useMemo(
() => thresholdState.thresholds.flatMap((threshold) => threshold.channels),
[thresholdState.thresholds],
);
return useMemo(() => {
const selectedChannelIds = getChannelIds(channels, selectedChannels);
const selectedChannelIds = getChannelIds(channels, selectedChannelNames);
return {
saveChecks: getRuleSaveChecks({
@@ -38,11 +38,12 @@ export function useAlertRuleSaveChecks(): UseAlertRuleSaveChecksReturn {
}),
testChecks: getRuleCreateChecks(selectedChannelIds),
isResolvingChannels:
isLoading && (selectedChannels.length > 0 || savedChannelNames.length > 0),
isLoading &&
(selectedChannelNames.length > 0 || savedChannelNames.length > 0),
};
}, [
channels,
selectedChannels,
selectedChannelNames,
savedChannelNames,
isEditMode,
ruleId,

View File

@@ -13,11 +13,6 @@ export const DashedContainer = styled.div`
align-items: center;
`;
export const ButtonContainer = styled.div`
display: flex;
gap: 1rem;
`;
export const EventContainer = styled.div`
display: flex;
justify-content: space-between;

View File

@@ -14,8 +14,8 @@ import Card from 'periscope/components/Card/Card';
import { isModifierKeyPressed } from 'utils/app';
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
import {
RuleCreatePermission,
RuleListPermission,
RuleCreateChecks,
RuleListChecks,
} from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
import { withAuthZContent } from 'lib/authz/components/withAuthZ/withAuthZContent';
@@ -26,9 +26,6 @@ import AlertRulesDenied from './AlertRulesDenied';
import AlertRulesLoading from './AlertRulesLoading';
import { useHomeAlertRules } from './useHomeAlertRules';
const LIST_CHECKS = [RuleListPermission];
const CREATE_CHECKS = [RuleCreatePermission];
function AlertRules({
onUpdateChecklistDoneItem,
loadingUserPreferences,
@@ -73,7 +70,7 @@ function AlertRules({
<div className="empty-actions-container">
<AuthZButton
checks={CREATE_CHECKS}
checks={RuleCreateChecks}
size="md"
variant="solid"
color="secondary"
@@ -224,8 +221,8 @@ function AlertRules({
}
export default withAuthZContent(AlertRules, {
checks: LIST_CHECKS,
preloadChecks: CREATE_CHECKS,
checks: RuleListChecks,
preloadChecks: RuleCreateChecks,
fallback: ({ deniedPermissions }) => (
<AlertRulesDenied deniedPermissions={deniedPermissions} />
),

View File

@@ -6,7 +6,7 @@ import { Typography } from '@signozhq/ui/typography';
import logEvent from 'api/common/logEvent';
import ROUTES from 'constants/routes';
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
import { RuleCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
import { RuleCreateChecks } from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import { DataSource } from 'types/common/queryBuilder';
import { isModifierKeyPressed } from 'utils/app';
@@ -32,8 +32,6 @@ const alertLogEvents = (
void logEvent(title, dataSource ? { ...attributes, dataSource } : attributes);
};
const CREATE_CHECKS = [RuleCreatePermission];
interface AlertsEmptyStateProps {
onRefresh?: () => void;
}
@@ -91,7 +89,7 @@ export function AlertsEmptyState({
<div className={styles.actionContainer}>
<div className={styles.buttonGroup}>
<AuthZButton
checks={CREATE_CHECKS}
checks={RuleCreateChecks}
size="md"
variant="solid"
color="primary"

View File

@@ -0,0 +1,14 @@
import { AllTheProviders, renderHook } from 'tests/test-utils';
import { useRuleViews } from '../useRuleViews';
describe('useRuleViews', () => {
it('reports loading while the views query is held', () => {
const { result } = renderHook(() => useRuleViews({ enabled: false }), {
wrapper: AllTheProviders,
});
expect(result.current.isLoading).toBe(true);
expect(result.current.views).toStrictEqual([]);
});
});

View File

@@ -4,14 +4,12 @@ import { ColumnSelector } from 'components/TanStackTableView';
import type { TableColumnDef } from 'components/TanStackTableView';
import TextToolTip from 'components/TextToolTip';
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
import { RuleCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
import { RuleCreateChecks } from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
import type { AlertRule } from '../types';
import styles from './AlertRulesHeaderActions.module.scss';
const CREATE_CHECKS = [RuleCreatePermission];
interface Props {
columns: TableColumnDef<AlertRule>[];
/** False on the empty list, whose own button creates the first rule. */
@@ -33,7 +31,7 @@ function AlertRulesHeaderActions({
/>
{showNewAlert && (
<AuthZButton
checks={CREATE_CHECKS}
checks={RuleCreateChecks}
variant="solid"
size="sm"
prefix={<Plus size={14} />}

View File

@@ -13,7 +13,7 @@ import { useTableParams } from 'components/TanStackTableView/useTableParams';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import { AuthZGuardContent } from 'lib/authz/components/AuthZGuard/AuthZGuardContent';
import PermissionDeniedCallout from 'lib/authz/components/PermissionDeniedCallout/PermissionDeniedCallout';
import { RuleListPermission } from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
import { RuleListChecks } from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
import { useAppContext } from 'providers/App/App';
import { useTimezone } from 'providers/Timezone';
@@ -51,7 +51,6 @@ const CLIENT_VIEW_LIMIT = 200;
const DEFAULT_PAGE = 1;
const DEFAULT_LIMIT = 10;
const RULE_LIST_CHECKS = [RuleListPermission];
function ListAlertRules(): JSX.Element {
const { user } = useAppContext();
@@ -76,7 +75,7 @@ function ListAlertRules(): JSX.Element {
const { filter, applyFilter, submitQuery, changeStates, changeSort } =
useAlertRulesListFilter({ orderBy, setOrderBy, setPage });
const listAccess = useAuthZ(RULE_LIST_CHECKS);
const listAccess = useAuthZ(RuleListChecks);
const ruleViews = useAlertRuleViews({
filter,
applyFilter,
@@ -91,7 +90,7 @@ function ListAlertRules(): JSX.Element {
}, [setRailCollapsed, railCollapsed]);
const guardViewsRail = useCallback(
(content: ReactElement): ReactElement => (
<ViewsRailGuard checks={RULE_LIST_CHECKS} shouldRenderUntilDenied>
<ViewsRailGuard checks={RuleListChecks} shouldRenderUntilDenied>
{content}
</ViewsRailGuard>
),
@@ -295,7 +294,7 @@ function ListAlertRules(): JSX.Element {
<div ref={containerRef} className={styles.tableContainer}>
<AuthZGuardContent
checks={RULE_LIST_CHECKS}
checks={RuleListChecks}
fallback={({ deniedPermissions }): JSX.Element => (
<PermissionDeniedCallout
deniedPermissions={deniedPermissions}

View File

@@ -21,8 +21,7 @@ export interface UseAlertRuleViewsResult extends UseListViewsResult<RuleListFilt
}
// A link carrying only `view=<custom id>` gets that view's filter applied once
// the views load; a link carrying its own filter params keeps them. A held
// query reports no loading, so the link also waits for `enabled`.
// the views load; a link carrying its own filter params keeps them.
export function useAlertRuleViews({
filter,
applyFilter,
@@ -51,7 +50,7 @@ export function useAlertRuleViews({
const hasResolvedLinkedView = useRef(false);
useEffect(() => {
if (hasResolvedLinkedView.current || !enabled || api.isLoading) {
if (hasResolvedLinkedView.current || api.isLoading) {
return;
}
hasResolvedLinkedView.current = true;
@@ -62,7 +61,7 @@ export function useAlertRuleViews({
) {
applyFilter(activeView.filter);
}
}, [enabled, api.isLoading, activeView, applyFilter, filter]);
}, [api.isLoading, activeView, applyFilter, filter]);
return { ...views, customViewsLoading: api.isLoading };
}

View File

@@ -70,7 +70,7 @@ export function useRuleViews({
enabled,
}: UseRuleViewsArgs): SavedListViewsApi<RuleListFilter> {
const queryClient = useQueryClient();
const { data, isLoading } = useListRuleViews({ query: { enabled } });
const { data, isLoading, isIdle } = useListRuleViews({ query: { enabled } });
const views = useMemo<RuleView[]>(
() => (data?.data?.views ?? []).map(toRuleView),
@@ -147,5 +147,11 @@ export function useRuleViews({
[deleteMutation],
);
return { views, isLoading, createView, updateView, deleteView };
return {
views,
isLoading: isLoading || isIdle,
createView,
updateView,
deleteView,
};
}

View File

@@ -42,10 +42,6 @@
align-items: flex-start;
flex-direction: column;
.ant-typography {
color: var(--l1-foreground);
}
.loading-gif {
height: 72px;
margin-left: -24px;

View File

@@ -3,10 +3,6 @@ import {
initialQueryBuilderFormValuesMap,
} from 'constants/queryBuilder';
import { ORDERBY_FILTERS } from 'container/QueryBuilder/filters/OrderByFilter/config';
import {
BaseAutocompleteData,
DataTypes,
} from 'types/api/queryBuilder/queryAutocompleteResponse';
import { IBuilderQuery, Query } from 'types/api/queryBuilder/queryBuilderData';
import { LogsAggregatorOperator } from 'types/common/queryBuilder';
@@ -44,9 +40,3 @@ export const liveLogsCompositeQuery = constructCompositeQuery({
initialQueryData: initialQueryBuilderFormValuesMap.logs,
customQueryData: defaultLiveQueryDataConfig,
});
export const idObject: BaseAutocompleteData = {
key: 'id',
type: '',
dataType: DataTypes.String,
};

View File

@@ -1,35 +0,0 @@
.json-view-container {
border-radius: 3px;
border: 1px solid var(--l1-border);
padding-top: 16px;
.json-view-footer {
height: 36px;
display: flex;
align-items: center;
border-top: 1px solid var(--l1-border);
}
.log-switch {
display: flex;
justify-content: space-between;
align-items: center;
.wrap-word-switch {
display: flex;
gap: 8px;
margin-left: var(--margin-3);
align-items: center;
}
.log-switch-btn {
border: 1px solid var(--l1-border);
background-color: var(--l2-background);
width: 40px;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
}
}

View File

@@ -35,13 +35,6 @@
display: flex;
align-items: center;
.wrap-word-switch {
display: flex;
gap: 8px;
margin-left: var(--margin-3);
align-items: center;
}
.log-switch-btn {
border: 1px solid var(--l1-border);
background-color: var(--l2-background);
@@ -53,74 +46,12 @@
}
}
.attribute-table {
margin-top: var(--margin-1);
}
.ant-collapse {
border: 1px solid var(--l1-border);
}
.collapse-content {
border-bottom: 1px solid var(--l1-border);
.ant-collapse-header {
align-items: center;
border-radius: 2px;
background-color: var(--l3-background);
border: 1px solid var(--l3-border);
padding: 8px;
.ant-collapse-extra {
display: flex;
align-items: center;
.action-btn {
display: flex;
.ant-btn {
background: color-mix(in srgb, var(--bg-robin-400) 8%, transparent);
}
}
}
}
.ant-collapse-content {
padding: 0;
background: var(--l2-background);
border-top: 1px solid var(--l1-border);
.ant-collapse-content-box {
padding: var(--padding-2) 0 0 0;
}
}
}
.logs-body-content {
padding-top: 12px;
}
[data-slot='badge'] {
border-radius: 2px;
background: color-mix(in srgb, var(--bg-robin-400) 8%, transparent);
}
.attribute-collapse {
.ant-collapse-content {
.ant-collapse-content-box {
padding: 0;
}
}
}
.ant-table-wrapper .ant-table-cell {
padding: 14px 14px;
}
.attribute-tab-header {
display: flex;
align-items: center;
justify-content: space-between;
}
}

View File

@@ -1,5 +0,0 @@
export const DROPDOWN_KEY = {
FILTER_IN: 'filterIn',
FILTER_OUT: 'filterOut',
GROUP_BY: 'groupBy',
};

View File

@@ -76,9 +76,6 @@ export const generateFieldKeyForArray = (
return `body.${newResultNodeKey}`;
};
export const removeObjectFromString = (str: string): string =>
str.replace(/\[object Object\]./g, '');
// Split `str` on the first occurrence of `delimiter`
// For example, will return `['a', 'b.c']` when splitting `'a.b.c'` at dots
const splitOnce = (str: string, delimiter: string): string[] => {
@@ -303,30 +300,6 @@ export const unescapeString = (str: string): string =>
String.fromCharCode(parseInt(hex, 16)),
); // Replaces Unicode escape sequences
export function findKeyPath(
obj: AnyObject,
targetKey: string,
currentPath = '',
): string | null {
let finalPath = null;
Object.keys(obj).forEach((key) => {
const value = obj[key];
const newPath = currentPath ? `${currentPath}.${key}` : key;
if (key === targetKey) {
finalPath = newPath;
}
if (typeof value === 'object' && value !== null) {
const result = findKeyPath(value, targetKey, newPath);
if (result) {
finalPath = result;
}
}
});
return finalPath;
}
export const getSanitizedLogBody = (
text: string,
options: { shouldEscapeHtml?: boolean } = {},

View File

@@ -1,10 +0,0 @@
.qb-search-view-container {
padding: 8px 16px;
.ant-select-selector {
border-radius: 2px;
border: 1px solid var(--l1-border) !important;
background-color: var(--l1-background) !important;
color: var(--l2-foreground);
}
}

View File

@@ -7,8 +7,6 @@ import { useShareBuilderUrl } from 'hooks/queryBuilder/useShareBuilderUrl';
import { ExplorerViews } from 'pages/LogsExplorer/utils';
import { DataSource } from 'types/common/queryBuilder';
import './LogsExplorerQuerySection.styles.scss';
function LogExplorerQuerySection({
selectedView,
}: {

View File

@@ -62,16 +62,6 @@ const SEVERITY_VARIANT_COLORS: Record<string, string> = {
PANIC: Color.BG_SAKURA_600,
};
// Simple function to get severity color for any component
export function getSeverityColor(severityText: string): string {
const variantColor = SEVERITY_VARIANT_COLORS[severityText.trim()];
if (variantColor) {
return variantColor;
}
return Color.BG_ROBIN_500; // Default fallback
}
export function getColorsForSeverityLabels(
label: string,
index: number,

View File

@@ -7,252 +7,6 @@
letter-spacing: -0.005em;
text-align: left;
min-height: 0;
.logs-list-table-view-container {
.data-table-container {
border: none !important;
}
table {
thead {
tr {
th {
font-size: 12px;
color: white !important;
.cursor-col-resize {
width: 24px !important;
cursor: col-resize !important;
opacity: 1 !important;
background-color: transparent !important;
border: none !important;
&:hover {
opacity: 1 !important;
}
}
}
td {
font-size: 12px;
}
border-bottom: 1px solid var(--l1-border) !important;
}
border-bottom: 1px solid var(--l1-border) !important;
background-color: var(--l2-background) !important;
tr {
&:hover {
background-color: var(--l2-background) !important;
}
}
}
tbody {
tr {
td {
font-size: 12px;
padding: 4px !important;
white-space: pre-wrap !important;
overflow: hidden !important;
}
&:hover {
background-color: var(--l1-border) !important;
}
border-bottom: 1px solid var(--l1-border) !important;
}
tr:has(.active-log) {
background-color: rgba(78, 116, 248, 0.5) !important; // same as bg-robin-500
color: var(--l1-foreground) !important;
}
}
thead {
z-index: 2 !important;
}
.log-state-indicator {
padding-left: 0 !important;
.line {
margin: 0 0 !important;
}
}
}
.sticky-header-table-container {
&::-webkit-scrollbar {
width: 0.4rem;
height: 0.4rem;
}
&::-webkit-scrollbar-track {
background: transparent;
}
&::-webkit-scrollbar-thumb {
background: var(--l3-background);
}
&::-webkit-scrollbar-thumb:hover {
background: var(--l3-background);
}
}
&[data-max-lines-per-row='1'] {
tbody {
tr {
td {
.table-cell-content {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 1;
overflow: hidden;
}
}
}
}
}
&[data-max-lines-per-row='2'] {
tbody {
tr {
td {
.table-cell-content {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
overflow: hidden;
}
}
}
}
}
&[data-max-lines-per-row='3'] {
tbody {
tr {
td {
.table-cell-content {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
overflow: hidden;
}
}
}
}
}
&[data-max-lines-per-row='4'] {
tbody {
tr {
td {
.table-cell-content {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 4;
overflow: hidden;
}
}
}
}
}
&[data-max-lines-per-row='5'] {
tbody {
tr {
td {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 5;
overflow: hidden;
}
}
}
}
&[data-max-lines-per-row='6'] {
tbody {
tr {
td {
.table-cell-content {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 6;
overflow: hidden;
}
}
}
}
}
&[data-max-lines-per-row='7'] {
tbody {
tr {
td {
.table-cell-content {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 7;
overflow: hidden;
}
}
}
}
}
&[data-max-lines-per-row='8'] {
tbody {
tr {
td {
.table-cell-content {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 8;
overflow: hidden;
}
}
}
}
}
&[data-max-lines-per-row='9'] {
tbody {
tr {
td {
.table-cell-content {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 9;
overflow: hidden;
}
}
}
}
}
&[data-max-lines-per-row='10'] {
tbody {
tr {
td {
.table-cell-content {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 10;
overflow: hidden;
}
}
}
}
}
}
}
.logs-linked-row td {

View File

@@ -132,16 +132,6 @@
align-items: center;
gap: 4px;
}
.order-by-select {
width: 100px;
.ant-select-selector {
border: none;
box-shadow: none;
background-color: transparent;
}
}
}
}

View File

@@ -20,17 +20,6 @@
font-weight: 400;
line-height: 18px;
font-family: Inter;
.ant-typography {
background-color: transparent;
color: var(--l1-foreground);
margin-bottom: 0;
font-size: 13px;
font-style: normal;
font-weight: 400;
line-height: 18px;
font-family: Inter;
}
padding: 14px 8px;
border: none;
cursor: pointer;

View File

@@ -29,15 +29,6 @@ export const ProcessorTypeContainer = styled.div`
gap: 0.313rem;
`;
export const Container = styled.div`
display: flex;
flex-direction: row;
align-items: flex-start;
padding: 0rem;
gap: 1rem;
width: 100%;
`;
export const FormWrapper = styled.div`
width: 100%;
`;

View File

@@ -1,7 +0,0 @@
.sample-logs-notice-container {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}

View File

@@ -1,24 +0,0 @@
import { Badge } from '@signozhq/ui/badge';
function Tags({ tags }: TagsProps): JSX.Element {
return (
<span>
{tags?.map((tag) => (
<Badge
textTransform="none"
variant="solid"
color="highlight-danger"
key={tag}
>
{tag}
</Badge>
))}
</span>
);
}
interface TagsProps {
tags: Array<string>;
}
export default Tags;

View File

@@ -2,8 +2,6 @@ import { Pipeline, PipelineData } from 'types/api/pipeline/def';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
export const configurationVersion = '1.0';
export function mockPipelineFilter(
key: string,
op: string,

View File

@@ -1,11 +0,0 @@
import Tags from 'container/PipelinePage/PipelineListsView/TableComponents/Tags';
import { render } from 'tests/test-utils';
const tags = ['server', 'app'];
describe('PipelinePage container test', () => {
it('should render Tags section', () => {
const { asFragment } = render(<Tags tags={tags} />);
expect(asFragment()).toMatchSnapshot();
});
});

View File

@@ -1,42 +0,0 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`PipelinePage container test should render Tags section 1`] = `
<DocumentFragment>
<span>
<span
class="_badge_1wurm_1"
data-color="highlight-danger"
data-slot="badge"
data-text-overflow="ellipsis"
data-text-transform="none"
data-trigger-disabled=""
data-variant="solid"
id="base-ui-:r1:"
>
<span
class="_badge__label_1wurm_141"
data-slot="badge-label"
>
server
</span>
</span>
<span
class="_badge_1wurm_1"
data-color="highlight-danger"
data-slot="badge"
data-text-overflow="ellipsis"
data-text-transform="none"
data-trigger-disabled=""
data-variant="solid"
id="base-ui-:r3:"
>
<span
class="_badge__label_1wurm_141"
data-slot="badge-label"
>
app
</span>
</span>
</span>
</DocumentFragment>
`;

View File

@@ -1,10 +1,4 @@
import React, {
type ReactNode,
useCallback,
useEffect,
useMemo,
useState,
} from 'react';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { Check, Info } from '@signozhq/icons';
import {
DatePicker,
@@ -37,14 +31,8 @@ import dayjs from 'dayjs';
import timezone from 'dayjs/plugin/timezone';
import utc from 'dayjs/plugin/utc';
import { useNotifications } from 'hooks/useNotifications';
import { formatDeniedMessage } from 'lib/authz/components/formatDeniedMessage';
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
import { RuleListPermission } from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
import { useAppContext } from 'providers/App/App';
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
import AuthZSelect from 'lib/authz/components/AuthZSelect/AuthZSelect';
import type { AuthZSelectOption } from 'lib/authz/components/AuthZSelect/types';
import { deniedReason } from 'lib/authz/components/deniedTooltip';
import { defaultTo, isEmpty } from 'lodash-es';
import { useErrorModal } from 'providers/ErrorModalProvider';
import APIError from 'types/api/error';
@@ -84,9 +72,6 @@ const TZ_OPTIONS: DefaultOptionType[] = ALL_TIME_ZONES.map(
type AlertRuleScope = 'all' | 'specific';
// Module-level so the useQueries identity stays stable across renders.
const RULE_LIST_CHECKS = [RuleListPermission];
interface PlannedDowntimeFormData {
name: string;
startTime: dayjs.Dayjs | null;
@@ -159,7 +144,9 @@ export function PlannedDowntimeForm(
isReadOnly,
readOnlyReason,
saveChecks,
getRuleAccess,
ruleOptions,
getRuleLockReason,
ruleListDenial,
onPickerVisibleChange,
} = usePlannedDowntimeFormPermissions({
initialValues,
@@ -169,36 +156,6 @@ export function PlannedDowntimeForm(
selectedRules: selectedTags,
});
const { user } = useAppContext();
const ruleList = useAuthZ(RULE_LIST_CHECKS);
const isRuleListDenied =
!ruleList.isLoading &&
!ruleList.error &&
!ruleList.isGranted(RuleListPermission);
const gatedAlertOptions = useMemo(
() =>
alertOptions.map((option): AuthZSelectOption => ({
...getRuleAccess(String(option.value)),
value: String(option.value),
label:
typeof option.label === 'string' ? option.label : String(option.value),
testId: `downtime-rule-option-${option.value}`,
})),
[alertOptions, getRuleAccess],
);
const getRuleLockReason = useCallback(
(ruleId: string): ReactNode => {
const { disabled, reason, denied } = getRuleAccess(ruleId);
if (!disabled || !reason) {
return undefined;
}
return denied ? deniedReason(reason) : reason;
},
[getRuleAccess],
);
const requiredFieldRule = [{ required: true }];
const datePickerFooter = (mode: string): JSX.Element | null =>
@@ -600,14 +557,12 @@ export function PlannedDowntimeForm(
tagRender={noTagRenderer}
onChange={handleAlertRulesChange}
showSearch
options={gatedAlertOptions}
options={ruleOptions}
data-testid="downtime-alert-rules"
onDropdownVisibleChange={onPickerVisibleChange}
notFoundContent={
isRuleListDenied ? (
<span data-testid="downtime-rules-denied">
{formatDeniedMessage([RuleListPermission], user.id)}
</span>
ruleListDenial ? (
<span data-testid="downtime-rules-denied">{ruleListDenial}</span>
) : isLoading ? (
<span>
<Spin size="small" /> Loading...

View File

@@ -1,4 +1,4 @@
import { type ReactNode, useMemo } from 'react';
import { type ReactNode, useCallback, useMemo } from 'react';
import type { DefaultOptionType } from 'antd/es/select';
import type { AlertmanagertypesPlannedMaintenanceDTO } from 'api/generated/services/sigNoz.schemas';
import {
@@ -9,12 +9,20 @@ import {
import {
buildRuleAttachPermission,
buildRuleDetachPermission,
RuleListChecks,
RuleListPermission,
} from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
import { deniedTooltip } from 'lib/authz/components/deniedTooltip';
import type { AuthZSelectOption } from 'lib/authz/components/AuthZSelect/types';
import {
deniedReason,
deniedTooltip,
} from 'lib/authz/components/deniedTooltip';
import { formatDeniedMessage } from 'lib/authz/components/formatDeniedMessage';
import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';
import type {
LinkAccess,
LinkPermissions,
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
import {
type LinkPermissions,
LinkAccessState,
} from 'lib/authz/hooks/useLinkPickerAccess/types';
import { useLinkPickerAccess } from 'lib/authz/hooks/useLinkPickerAccess/useLinkPickerAccess';
import { useAppContext } from 'providers/App/App';
@@ -35,8 +43,12 @@ export interface UsePlannedDowntimeFormPermissionsReturn {
/** The denial a read-only control shows; set whenever editing, so a control keeps its tooltip. */
readOnlyReason?: ReactNode;
saveChecks: BrandedPermission[];
/** Whether a rule can be added or, if the schedule already has it, removed. */
getRuleAccess: (ruleId: string) => LinkAccess;
/** The rule picker's options, each disabled with the reason when locked. */
ruleOptions: AuthZSelectOption[];
/** Why a selected rule's tag cannot be removed; undefined when it can. */
getRuleLockReason: (ruleId: string) => ReactNode;
/** The `rule:list` denial, shown in place of an empty picker. */
ruleListDenial?: string;
/** Starts the `attach` checks on unsilenced rules once the picker opens. */
onPickerVisibleChange: (open: boolean) => void;
}
@@ -116,6 +128,37 @@ export function usePlannedDowntimeFormPermissions({
[scheduleId, storedIds, incomingIds],
);
const ruleOptions = useMemo(
() =>
alertOptions.map((option): AuthZSelectOption => ({
...getAccess(String(option.value)),
value: String(option.value),
label:
typeof option.label === 'string' ? option.label : String(option.value),
testId: `downtime-rule-option-${option.value}`,
})),
[alertOptions, getAccess],
);
const getRuleLockReason = useCallback(
(ruleId: string): ReactNode => {
const access = getAccess(ruleId);
if (access.state === LinkAccessState.Allowed) {
return undefined;
}
return access.state === LinkAccessState.Denied
? deniedReason(access.reason)
: access.reason;
},
[getAccess],
);
const ruleList = useAuthZ(RuleListChecks);
const isRuleListDenied =
!ruleList.isLoading &&
!ruleList.error &&
!ruleList.isGranted(RuleListPermission);
const readOnlyReason = useMemo(
() => (update ? deniedTooltip([update], user.id) : undefined),
[update, user.id],
@@ -125,7 +168,11 @@ export function usePlannedDowntimeFormPermissions({
isReadOnly: !!update && isOwnerDenied(update),
readOnlyReason,
saveChecks,
getRuleAccess: getAccess,
ruleOptions,
getRuleLockReason,
ruleListDenial: isRuleListDenied
? formatDeniedMessage(RuleListChecks, user.id)
: undefined,
onPickerVisibleChange,
};
}

View File

@@ -186,7 +186,6 @@ function RoutingPolicyDetails({
>
<AuthZSelect
options={channelOptions}
popupMatchSelectWidth={false}
onDropdownVisibleChange={onPickerVisibleChange}
placeholder="Select notification channels"
aria-label="Notification Channels"

View File

@@ -169,8 +169,6 @@ describe('RoutingPolicyDetails', () => {
await waitFor(() => expect(option).toHaveAttribute('aria-disabled', 'false'));
await user.click(option);
await user.click(screen.getByTestId(SAVE_BUTTON));
await waitForSaveEnabled();
await user.click(screen.getByTestId(SAVE_BUTTON));

View File

@@ -36,7 +36,7 @@ export function useRoutingPolicyFormPermissions(
): UseRoutingPolicyFormPermissionsReturn {
const policyId = mode === 'edit' ? routingPolicy?.id : undefined;
const update = useMemo(
const updatePermission = useMemo(
() => (policyId ? buildRoutePolicyUpdatePermission(policyId) : undefined),
[policyId],
);
@@ -50,7 +50,10 @@ export function useRoutingPolicyFormPermissions(
: undefined,
[policyId],
);
const ownerChecks = useMemo(() => (update ? [update] : []), [update]);
const ownerChecks = useMemo(
() => (updatePermission ? [updatePermission] : []),
[updatePermission],
);
const {
options: channelOptions,
@@ -67,12 +70,12 @@ export function useRoutingPolicyFormPermissions(
});
const saveChecks = useMemo(
() => (update ? [update] : RoutePolicyCreateChecks),
[update],
() => (updatePermission ? [updatePermission] : RoutePolicyCreateChecks),
[updatePermission],
);
return {
isReadOnly: !!update && isOwnerDenied(update),
isReadOnly: !!updatePermission && isOwnerDenied(updatePermission),
saveChecks,
channelOptions,
onPickerVisibleChange,

View File

@@ -115,23 +115,14 @@ function ListView({
queryKeyRef.current = queryKey;
}
const {
rows,
warning,
isFetching,
isLoading,
isIdle,
isNewQueryLoading,
isError,
error,
loadMore,
} = useListViewInfiniteQuery({
query: requestQuery,
queryKey,
enabled:
// don't make api call while the time range state in redux is loading
!timeRangeUpdateLoading && !!stagedQuery && panelType === PANEL_TYPES.LIST,
});
const { rows, warning, isFetching, isLoading, isError, error, loadMore } =
useListViewInfiniteQuery({
query: requestQuery,
queryKey,
enabled:
// don't make api call while the time range state in redux is loading
!timeRangeUpdateLoading && !!stagedQuery && panelType === PANEL_TYPES.LIST,
});
useEffect(() => {
setWarning(warning);
@@ -146,7 +137,7 @@ function ListView({
}, [isLoading, isFetching, setIsLoadingQueries]);
const { tableProps, openTraceColumn, drawerProps, onPressInside } =
useSpanDrawer(rows, isLoading || isIdle || isNewQueryLoading);
useSpanDrawer(rows);
const columns = useMemo<TableColumnDef<TracesTableRow>[]>(() => {
const fields = [

View File

@@ -1,12 +1,5 @@
import { CSSProperties } from 'react';
import styled from 'styled-components';
export const tableStyles: CSSProperties = {
cursor: 'unset',
};
export const Container = styled.div`
display: flex;
flex-direction: column;
--typography-color: var(--l1-foreground);
`;

View File

@@ -20,10 +20,6 @@ type UseListViewInfiniteQueryResult = {
rows: TracesTableRow[];
warning: Warning | undefined;
isLoading: boolean;
/** Disabled before its first fetch: no staged query yet, or the time range still loading. */
isIdle: boolean;
/** A new query is loading; `rows` stay empty until it answers. */
isNewQueryLoading: boolean;
isFetching: boolean;
isError: boolean;
error: Error | null;
@@ -40,7 +36,6 @@ export function useListViewInfiniteQuery({
const {
data,
isLoading,
isIdle,
isFetching,
isFetchingNextPage,
isError,
@@ -105,8 +100,6 @@ export function useListViewInfiniteQuery({
rows,
warning: data?.pages[data.pages.length - 1]?.warning,
isLoading,
isIdle,
isNewQueryLoading: !keepRows,
isFetching,
isError,
error: error as Error | null,

View File

@@ -1,28 +0,0 @@
import TraceFlamegraph from 'pages/TraceDetailsV3/TraceFlamegraph/TraceFlamegraph';
import { NO_FILTERED_SPANS } from './constants';
import { TRACE_VIEW_LOADER } from './TraceViewLoader';
type DrawerFlamegraphProps = {
traceId: string;
totalSpansCount: number | undefined;
};
function DrawerFlamegraph({
traceId,
totalSpansCount,
}: DrawerFlamegraphProps): JSX.Element {
return (
<TraceFlamegraph
traceId={traceId}
filteredSpanIds={NO_FILTERED_SPANS}
isFilterActive={false}
// Only a sampled flame graph reads it, and the drawer never shows one.
selectedSpan={undefined}
totalSpansCount={totalSpansCount ?? 0}
loadingFallback={TRACE_VIEW_LOADER}
/>
);
}
export default DrawerFlamegraph;

View File

@@ -1,37 +0,0 @@
import type { UseTraceWaterfallDataResult } from 'pages/TraceDetailsV3/hooks/useTraceWaterfallData';
import TraceWaterfall from 'pages/TraceDetailsV3/TraceWaterfall/TraceWaterfall';
import { NO_FILTERED_SPANS } from './constants';
import { TRACE_VIEW_LOADER } from './TraceViewLoader';
type DrawerWaterfallProps = {
traceId: string;
waterfall: UseTraceWaterfallDataResult;
};
function DrawerWaterfall({
traceId,
waterfall,
}: DrawerWaterfallProps): JSX.Element {
return (
<TraceWaterfall
traceId={traceId}
traceData={waterfall.traceData}
isFetchingTraceData={waterfall.isFetchingTraceData}
errorFetchingTraceData={waterfall.errorFetchingTraceData}
interestedSpanId={waterfall.interestedSpanId}
setInterestedSpanId={waterfall.setInterestedSpanId}
uncollapsedNodes={waterfall.uncollapsedNodes}
isFullDataLoaded={waterfall.isFullDataLoaded}
localUncollapsedNodes={waterfall.localUncollapsedNodes}
setLocalUncollapsedNodes={waterfall.setLocalUncollapsedNodes}
selectedSpan={waterfall.selectedSpan}
setSelectedSpan={waterfall.setSelectedSpan}
filteredSpanIds={NO_FILTERED_SPANS}
isFilterActive={false}
loadingFallback={TRACE_VIEW_LOADER}
/>
);
}
export default DrawerWaterfall;

View File

@@ -2,6 +2,7 @@ import { useMemo } from 'react';
import { Button } from '@signozhq/ui/button';
import { ButtonGroup } from '@signozhq/ui/button-group';
import { ChevronDown, ChevronUp, CornerUpRight } from '@signozhq/icons';
import { useGetTraceSummary } from 'api/generated/services/tracedetail';
import { HeaderAction } from 'components/DetailsPanel';
import { PANEL_TYPES } from 'constants/queryBuilder';
import type { UseRowNavigationResult } from 'components/TanStackTableView/useRowNavigation';
@@ -11,50 +12,28 @@ import {
} from 'container/TracesExplorer/events';
import { getTraceLink } from 'container/TracesExplorer/ListView/utils';
import { TracesTableRow } from 'container/TracesExplorer/TracesTable/getFieldColumn';
import NoData from 'pages/TraceDetailsV3/NoData/NoData';
import { SpanDetailVariant } from 'pages/TraceDetailsV3/SpanDetailsPanel/constants';
import SpanDetailsPanel from 'pages/TraceDetailsV3/SpanDetailsPanel/SpanDetailsPanel';
import { useTraceSummary } from 'pages/TraceDetailsV3/TraceDetailsHeader/useTraceSummary';
import { noop } from 'lodash-es';
import { openInNewTab } from 'utils/navigation';
import SpanDrawerTracePane from './SpanDrawerTracePane';
import { useArrowKeyNavigation } from './useArrowKeyNavigation';
import { useDrawerSpan } from './useDrawerSpan';
import { useDrawerTraceView } from './useDrawerTraceView';
import { toSpanV3 } from './utils';
export type SpanDrawerProps = {
traceId: string | null;
spanId: string | null;
/** The list row of the open span, when it is loaded. */
row: TracesTableRow | null;
onClose: () => void;
/** Null when no list row anchors ↑/↓. */
navigation: UseRowNavigationResult | null;
/** The list's first load; until it settles a missing `row` is not final. */
isListLoading: boolean;
navigation: UseRowNavigationResult;
};
function SpanDrawer({
traceId,
spanId,
row,
onClose,
navigation,
isListLoading,
}: SpanDrawerProps): JSX.Element {
const isOpen = !!traceId && !!spanId;
const hasNavigation = navigation !== null;
const goToPrev = navigation?.goToPrev ?? noop;
const goToNext = navigation?.goToNext ?? noop;
const isPrevDisabled = navigation?.isPrevDisabled ?? true;
const isNextDisabled = navigation?.isNextDisabled ?? true;
const { goToPrev, goToNext, isPrevDisabled, isNextDisabled } = navigation;
const isOpen = row !== null;
useArrowKeyNavigation({
enabled: isOpen && hasNavigation,
onPrev: goToPrev,
onNext: goToNext,
});
useArrowKeyNavigation({ enabled: isOpen, onPrev: goToPrev, onNext: goToNext });
const panelState = useMemo(
() => ({ isOpen, open: (): void => {}, close: onClose }),
@@ -62,10 +41,10 @@ function SpanDrawer({
);
const headerActions = useMemo((): HeaderAction[] => {
if (!traceId || !spanId) {
if (!row) {
return [];
}
const actions: HeaderAction[] = [
return [
{
key: 'view-full-trace',
component: (
@@ -76,7 +55,7 @@ function SpanDrawer({
prefix={<CornerUpRight />}
onClick={(): void => {
logOpenTraceClicked(PANEL_TYPES.LIST, OpenTraceSource.SpanDrawer);
openInNewTab(getTraceLink({ trace_id: traceId, span_id: spanId }));
openInNewTab(getTraceLink(row));
}}
testId="span-drawer-view-full-trace"
>
@@ -84,12 +63,6 @@ function SpanDrawer({
</Button>
),
},
];
if (!hasNavigation) {
return actions;
}
return [
...actions,
{
key: 'nav',
component: (
@@ -120,37 +93,16 @@ function SpanDrawer({
),
},
];
}, [
traceId,
spanId,
hasNavigation,
goToPrev,
goToNext,
isPrevDisabled,
isNextDisabled,
]);
}, [row, goToPrev, goToNext, isPrevDisabled, isNextDisabled]);
// Each trace's own summary: the counts and the 404 must not describe the last one.
const {
data: traceSummary,
isLoading: isTraceBoundsLoading,
isNotFound: isSummaryNotFound,
} = useTraceSummary(traceId ?? '', { keepPreviousData: false, retry: false });
const totalSpansCount = traceSummary?.totalSpansCount;
const traceView = useDrawerTraceView({
traceId,
totalSpansCount,
isSummaryLoading: isTraceBoundsLoading,
});
const span = useMemo(() => (row ? toSpanV3(row) : undefined), [row]);
const { span, isStale, isTraceMissing, waterfall } = useDrawerSpan({
traceId,
spanId,
row,
isListLoading,
isWaterfallShown: traceView.isWaterfallShown,
isSummaryNotFound,
});
const traceId = span?.trace_id ?? '';
const { data: traceSummary, isLoading: isTraceBoundsLoading } =
useGetTraceSummary(
{ traceID: traceId },
{ query: { enabled: !!traceId, retry: false } },
);
return (
<SpanDetailsPanel
@@ -158,24 +110,9 @@ function SpanDrawer({
selectedSpan={span}
variant={SpanDetailVariant.DRAWER}
headerActions={headerActions}
traceStartTime={traceSummary?.startTimestampMillis}
traceEndTime={traceSummary?.endTimestampMillis}
// The bounds are for the next span; hold the stale one's logs.
isTraceBoundsLoading={isTraceBoundsLoading || isStale}
isStale={isStale}
emptyState={isTraceMissing ? <NoData /> : undefined}
tracePane={
traceId && !isTraceMissing && !isSummaryNotFound ? (
<SpanDrawerTracePane
traceId={traceId}
traceView={traceView}
waterfall={waterfall}
totalSpansCount={totalSpansCount}
totalErrorSpansCount={traceSummary?.totalErrorSpansCount}
hasMissingSpans={!!traceSummary?.hasMissingSpans}
/>
) : null
}
traceStartTime={traceSummary?.data?.startTimestampMillis}
traceEndTime={traceSummary?.data?.endTimestampMillis}
isTraceBoundsLoading={isTraceBoundsLoading}
/>
);
}

View File

@@ -1,36 +0,0 @@
// Fixed above the scrolling span details.
.pane {
flex-shrink: 0;
border-bottom: 1px solid var(--l2-border);
background: var(--l2-background);
}
.toolbar {
display: flex;
align-items: center;
gap: var(--spacing-4);
height: 44px;
padding: 0 var(--spacing-4) 0 var(--spacing-6);
border-bottom: 1px solid var(--l2-border);
}
.views {
// The trace views paint their own surfaces in --l1-background; the drawer is --l2.
--l1-background: var(--l2-background);
}
.banner {
padding-top: var(--spacing-6);
}
.spacer {
flex: 1;
}
.viewLoader {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
color: var(--l2-foreground);
}

View File

@@ -1,110 +0,0 @@
import { ToggleGroup } from '@signozhq/ui/toggle-group';
import { ChartNoAxesGantt, Flame } from '@signozhq/icons';
import type { UseTraceWaterfallDataResult } from 'pages/TraceDetailsV3/hooks/useTraceWaterfallData';
import TraceStoreSync from 'pages/TraceDetailsV3/stores/TraceStoreSync';
import TraceCounts from 'pages/TraceDetailsV3/TraceCounts/TraceCounts';
import MissingSpansBanner from 'pages/TraceDetailsV3/TraceDetailsHeader/MissingSpansBanner';
import { ResizableBox } from 'periscope/components/ResizableBox';
import { FLAMEGRAPH_UNAVAILABLE_TOOLTIP, TRACE_PANE_HEIGHT } from './constants';
import DrawerFlamegraph from './DrawerFlamegraph';
import DrawerWaterfall from './DrawerWaterfall';
import TraceViewLoader from './TraceViewLoader';
import type { UseDrawerTraceViewResult } from './useDrawerTraceView';
import styles from './SpanDrawerTracePane.module.scss';
type SpanDrawerTracePaneProps = {
traceId: string;
traceView: UseDrawerTraceViewResult;
waterfall: UseTraceWaterfallDataResult;
totalSpansCount: number | undefined;
totalErrorSpansCount: number | undefined;
hasMissingSpans: boolean;
};
/** One trace view above the span details, each scrolling on its own. */
function SpanDrawerTracePane({
traceId,
traceView,
waterfall,
totalSpansCount,
totalErrorSpansCount,
hasMissingSpans,
}: SpanDrawerTracePaneProps): JSX.Element {
const { view, setView, isPending, areTabsShown, hasFlamegraph } = traceView;
// Keyed by trace: the views keep the last trace's data while the next loads.
let content = <TraceViewLoader />;
if (!isPending) {
content =
view === 'waterfall' ? (
<DrawerWaterfall key={traceId} traceId={traceId} waterfall={waterfall} />
) : (
<DrawerFlamegraph
key={traceId}
traceId={traceId}
totalSpansCount={totalSpansCount}
/>
);
}
return (
<TraceStoreSync>
<div className={styles.pane} data-testid="span-drawer-trace-pane">
<div className={styles.toolbar}>
{areTabsShown && (
<ToggleGroup
variant="outlined"
color="secondary"
type="single"
size="sm"
value={view}
onChange={(next: string): void => {
if (next === 'flamegraph' || next === 'waterfall') {
setView(next);
}
}}
testId="span-drawer-trace-view"
items={[
{
value: 'flamegraph',
label: 'Flame Graph',
prefix: <Flame size={12} />,
disabled: !hasFlamegraph,
disabledTooltip: FLAMEGRAPH_UNAVAILABLE_TOOLTIP,
},
{
value: 'waterfall',
label: 'Waterfall',
prefix: <ChartNoAxesGantt size={12} />,
},
]}
/>
)}
<span className={styles.spacer} />
<TraceCounts
totalSpansCount={totalSpansCount}
totalErrorSpansCount={totalErrorSpansCount}
/>
</div>
{hasMissingSpans && (
<div className={styles.banner}>
{/* A dismissal holds for this trace only. */}
<MissingSpansBanner key={traceId} />
</div>
)}
<ResizableBox
className={styles.views}
defaultHeight={TRACE_PANE_HEIGHT.default}
minHeight={TRACE_PANE_HEIGHT.min}
maxHeight={TRACE_PANE_HEIGHT.max}
>
{content}
</ResizableBox>
</div>
</TraceStoreSync>
);
}
export default SpanDrawerTracePane;

View File

@@ -1,21 +0,0 @@
import { Spinner } from '@signozhq/ui/spinner';
import styles from './SpanDrawerTracePane.module.scss';
/** Holds a trace view's place from the span count until the view has its data. */
function TraceViewLoader(): JSX.Element {
return (
<output
className={styles.viewLoader}
aria-label="Loading trace"
data-testid="span-drawer-trace-loading"
>
<Spinner size={20} />
</output>
);
}
/** One element, so the views' memoised content doesn't rebuild on each render. */
export const TRACE_VIEW_LOADER = <TraceViewLoader />;
export default TraceViewLoader;

View File

@@ -1,82 +0,0 @@
import { ReactNode } from 'react';
import { initialQueriesMap } from 'constants/queryBuilder';
import { ExplorerViews } from 'pages/LogsExplorer/utils';
import { AllTheProviders, renderHook } from 'tests/test-utils';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { useCloseSpanDrawerOnQueryChange } from '../useCloseSpanDrawerOnQueryChange';
import { useSpanDrawerParams } from '../useSpanDrawerParams';
type HarnessProps = { view: ExplorerViews; queryId: string | null };
const stagedQueryOf = (queryId: string | null): Query | null =>
queryId ? { ...initialQueriesMap.traces, id: queryId } : null;
const renderDrawer = (initialProps: HarnessProps) => {
let queryId = initialProps.queryId;
const utils = renderHook(
({ view }: HarnessProps) => {
useCloseSpanDrawerOnQueryChange(view);
return useSpanDrawerParams()[0];
},
{
initialProps,
wrapper: function Wrapper({ children }: { children: ReactNode }) {
return (
<AllTheProviders
initialRoute="/?traceId=trace-1&spanId=span-a"
queryBuilderOverrides={{ stagedQuery: stagedQueryOf(queryId) }}
>
{children}
</AllTheProviders>
);
},
},
);
return {
...utils,
rerender: (props: HarnessProps): void => {
queryId = props.queryId;
utils.rerender(props);
},
};
};
const OPEN = { traceId: 'trace-1', spanId: 'span-a' };
const CLOSED = { traceId: null, spanId: null };
describe('useCloseSpanDrawerOnQueryChange', () => {
it('closes the drawer on a new query', () => {
const { result, rerender } = renderDrawer({
view: ExplorerViews.LIST,
queryId: 'query-1',
});
rerender({ view: ExplorerViews.LIST, queryId: 'query-2' });
expect(result.current).toStrictEqual(CLOSED);
});
it('closes the drawer on another view, where the list is not mounted', () => {
const { result, rerender } = renderDrawer({
view: ExplorerViews.LIST,
queryId: 'query-1',
});
rerender({ view: ExplorerViews.TIMESERIES, queryId: 'query-1' });
expect(result.current).toStrictEqual(CLOSED);
});
it('keeps a linked drawer open while the staged query resets and loads', () => {
const { result, rerender } = renderDrawer({
view: ExplorerViews.LIST,
queryId: 'previous-page-query',
});
rerender({ view: ExplorerViews.LIST, queryId: null });
rerender({ view: ExplorerViews.LIST, queryId: 'query-1' });
expect(result.current).toStrictEqual(OPEN);
});
});

View File

@@ -1,233 +0,0 @@
import { ReactNode } from 'react';
import type {
GetWaterfallV4200,
SpantypesWaterfallSpanDTO,
} from 'api/generated/services/sigNoz.schemas';
import { TracesTableRow } from 'container/TracesExplorer/TracesTable/getFieldColumn';
import { rest, server } from 'mocks-server/server';
import { useSelectedSpanId } from 'pages/TraceDetailsV3/hooks/useSelectedSpanId';
import { AllTheProviders, renderHook, waitFor } from 'tests/test-utils';
import { useDrawerSpan } from '../useDrawerSpan';
const span = (
spanId: string,
parentSpanId: string,
): SpantypesWaterfallSpanDTO => ({
span_id: spanId,
parent_span_id: parentSpanId,
trace_id: 'trace-1',
level: parentSpanId ? 1 : 0,
has_children: !parentSpanId,
name: spanId,
time_unix: 1_700_000_000_000,
duration_nano: 1_000_000,
references: [],
});
const listRow: TracesTableRow = {
id: 'row-a',
trace_id: 'trace-1',
span_id: 'span-a',
name: 'span-a',
timestamp: '2026-11-19T13:28:21.309Z',
};
let requestedTraceIds: string[];
let totalSpansCount: number;
beforeEach(() => {
requestedTraceIds = [];
totalSpansCount = 2;
server.use(
rest.post('*/api/v4/traces/:traceId/waterfall', (req, res, ctx) => {
const traceId = String(req.params.traceId);
requestedTraceIds.push(traceId);
if (traceId === 'failing-trace') {
return res(ctx.status(500), ctx.json({ status: 'error' }));
}
if (traceId !== 'trace-1') {
return res(ctx.status(404), ctx.json({ status: 'error' }));
}
const body: GetWaterfallV4200 = {
status: 'success',
data: {
spans: [span('root', ''), span('child', 'root')],
totalSpansCount,
uncollapsedSpans: [],
startTimestampMillis: 0,
endTimestampMillis: 1,
},
};
return res(ctx.delay(20), ctx.status(200), ctx.json(body));
}),
);
});
type HarnessProps = {
traceId: string;
row: TracesTableRow | null;
isListLoading?: boolean;
isWaterfallShown?: boolean;
isSummaryNotFound?: boolean;
};
const renderDrawerSpan = (initialProps: HarnessProps, spanId: string) =>
renderHook(
({
traceId,
row,
isListLoading = false,
isWaterfallShown = false,
isSummaryNotFound = false,
}: HarnessProps) => {
const [urlSpanId] = useSelectedSpanId();
return {
urlSpanId,
...useDrawerSpan({
traceId,
spanId: urlSpanId,
row,
isListLoading,
isWaterfallShown,
isSummaryNotFound,
}),
};
},
{
initialProps,
wrapper: function Wrapper({ children }: { children: ReactNode }) {
return (
<AllTheProviders initialRoute={`/?spanId=${spanId}`}>
{children}
</AllTheProviders>
);
},
},
);
describe('useDrawerSpan', () => {
it('shows a list row without fetching the trace', async () => {
const { result } = renderDrawerSpan(
{ traceId: 'trace-1', row: listRow },
'span-a',
);
await waitFor(() =>
expect(result.current.waterfall.isFetchingTraceData).toBe(false),
);
expect(result.current.span?.span_id).toBe('span-a');
expect(requestedTraceIds).toStrictEqual([]);
});
it('waits for the list before fetching the trace', async () => {
const { result } = renderDrawerSpan(
{ traceId: 'trace-1', row: null, isListLoading: true },
'span-a',
);
await waitFor(() =>
expect(result.current.waterfall.isFetchingTraceData).toBe(false),
);
expect(requestedTraceIds).toStrictEqual([]);
});
it('fetches the trace for a list row while the waterfall shows', async () => {
const { result } = renderDrawerSpan(
{ traceId: 'trace-1', row: listRow, isWaterfallShown: true },
'span-a',
);
await waitFor(() =>
expect(result.current.waterfall.allSpans).toHaveLength(2),
);
expect(requestedTraceIds).toStrictEqual(['trace-1']);
expect(result.current.span?.span_id).toBe('span-a');
});
it('shows a span outside the list from the trace', async () => {
const { result } = renderDrawerSpan(
{ traceId: 'trace-1', row: null },
'child',
);
await waitFor(() => expect(result.current.span?.span_id).toBe('child'));
expect(result.current.isStale).toBe(false);
});
it('keeps the last span dimmed while the next one loads', () => {
const { result, rerender } = renderDrawerSpan(
{ traceId: 'trace-1', row: listRow },
'span-a',
);
rerender({ traceId: 'trace-1', row: null });
expect(result.current.span?.span_id).toBe('span-a');
expect(result.current.isStale).toBe(true);
});
it('falls back to the root span when the trace has no such span', async () => {
const { result } = renderDrawerSpan(
{ traceId: 'trace-1', row: null },
'no-such-span',
);
await waitFor(() => expect(result.current.urlSpanId).toBe('root'));
expect(result.current.span?.span_id).toBe('root');
});
it('falls back to the root span of a windowed trace', async () => {
totalSpansCount = 500;
const { result } = renderDrawerSpan(
{ traceId: 'trace-1', row: null },
'no-such-span',
);
await waitFor(() => expect(result.current.urlSpanId).toBe('root'));
expect(result.current.span?.span_id).toBe('root');
});
it('reports a trace that does not exist', async () => {
const { result } = renderDrawerSpan(
{ traceId: 'no-such-trace', row: null },
'span-a',
);
await waitFor(() => expect(result.current.isTraceMissing).toBe(true));
expect(result.current.span).toBeUndefined();
});
it('keeps a trace whose request fails for another reason', async () => {
const { result } = renderDrawerSpan(
{ traceId: 'failing-trace', row: null },
'span-a',
);
await waitFor(() =>
expect(result.current.waterfall.errorFetchingTraceData).toBeTruthy(),
);
expect(result.current.isTraceMissing).toBe(false);
});
it('reports a trace without a summary as missing once the list settles, without fetching it', async () => {
const { result, rerender } = renderDrawerSpan(
{
traceId: 'trace-1',
row: null,
isListLoading: true,
isSummaryNotFound: true,
},
'span-a',
);
expect(result.current.isTraceMissing).toBe(false);
rerender({ traceId: 'trace-1', row: null, isSummaryNotFound: true });
expect(result.current.isTraceMissing).toBe(true);
await waitFor(() =>
expect(result.current.waterfall.isFetchingTraceData).toBe(false),
);
expect(requestedTraceIds).toStrictEqual([]);
});
});

View File

@@ -1,116 +0,0 @@
import { FLAMEGRAPH_SPAN_LIMIT } from 'pages/TraceDetailsV3/TraceFlamegraph/constants';
import { act, renderHook } from 'tests/test-utils';
import { useDrawerTraceView } from '../useDrawerTraceView';
type Props = Parameters<typeof useDrawerTraceView>[0];
const SMALL_TRACE: Props = {
traceId: 'trace-1',
totalSpansCount: 10,
isSummaryLoading: false,
};
const BIG_TRACE: Props = {
traceId: 'trace-big',
totalSpansCount: FLAMEGRAPH_SPAN_LIMIT + 1,
isSummaryLoading: false,
};
const LOADING_TRACE: Props = {
traceId: 'trace-2',
totalSpansCount: undefined,
isSummaryLoading: true,
};
const renderTraceView = (initialProps: Props) =>
renderHook((props: Props) => useDrawerTraceView(props), { initialProps });
describe('useDrawerTraceView', () => {
it('opens on the flame graph', () => {
const { result } = renderTraceView(SMALL_TRACE);
expect(result.current).toMatchObject({
view: 'flamegraph',
hasFlamegraph: true,
isWaterfallShown: false,
});
});
it('shows the waterfall above the flame graph limit', () => {
const { result } = renderTraceView(BIG_TRACE);
expect(result.current).toMatchObject({
view: 'waterfall',
hasFlamegraph: false,
isWaterfallShown: true,
});
});
it('keeps the flame graph at the limit', () => {
const { result } = renderTraceView({
...BIG_TRACE,
totalSpansCount: FLAMEGRAPH_SPAN_LIMIT,
});
expect(result.current).toMatchObject({
view: 'flamegraph',
hasFlamegraph: true,
});
});
it('offers the flame graph when the span count fails to load', () => {
const { result } = renderTraceView({
...LOADING_TRACE,
isSummaryLoading: false,
});
expect(result.current).toMatchObject({
view: 'flamegraph',
isPending: false,
areTabsShown: true,
hasFlamegraph: true,
});
});
it('hides the tabs once the drawer closes', () => {
const { result, rerender } = renderTraceView(BIG_TRACE);
rerender({ ...BIG_TRACE, traceId: null });
expect(result.current).toMatchObject({
isPending: false,
areTabsShown: false,
hasFlamegraph: true,
});
});
it('mounts no view until the span count loads', () => {
const { result } = renderTraceView(LOADING_TRACE);
expect(result.current).toMatchObject({
isPending: true,
areTabsShown: false,
isWaterfallShown: false,
});
});
it("keeps the last trace's tabs while the next span count loads", () => {
const { result, rerender } = renderTraceView(BIG_TRACE);
rerender(LOADING_TRACE);
expect(result.current).toMatchObject({
isPending: true,
areTabsShown: true,
hasFlamegraph: false,
});
});
it('keeps the chosen tab on the next trace', () => {
const { result, rerender } = renderTraceView(SMALL_TRACE);
act(() => result.current.setView('waterfall'));
rerender({ ...SMALL_TRACE, traceId: 'trace-3' });
expect(result.current.view).toBe('waterfall');
});
});

View File

@@ -0,0 +1,44 @@
import { act, renderHook } from 'tests/test-utils';
import { TracesTableRow } from 'container/TracesExplorer/TracesTable/getFieldColumn';
import { useSpanDrawer } from '../useSpanDrawer';
let mockQueryId = 'query-1';
jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
useQueryBuilder: (): unknown => ({ stagedQuery: { id: mockQueryId } }),
}));
const rows: TracesTableRow[] = [{ id: 'span-a' }, { id: 'span-b' }];
describe('useSpanDrawer', () => {
beforeEach(() => {
mockQueryId = 'query-1';
});
it('does not reopen a span that a refetch dropped and a later one brings back', () => {
const { result, rerender } = renderHook(
({ current }: { current: TracesTableRow[] }) => useSpanDrawer(current),
{ initialProps: { current: rows } },
);
act(() => result.current.tableProps.onRowClick?.(rows[1]));
expect(result.current.drawerProps?.row).toBe(rows[1]);
rerender({ current: [rows[0]] });
expect(result.current.drawerProps?.row).toBeNull();
rerender({ current: rows });
expect(result.current.drawerProps?.row).toBeNull();
});
it('closes on a new query while the old rows are still shown', () => {
const { result, rerender } = renderHook(() => useSpanDrawer(rows));
act(() => result.current.tableProps.onRowClick?.(rows[1]));
expect(result.current.drawerProps?.row).toBe(rows[1]);
mockQueryId = 'query-2';
rerender();
expect(result.current.drawerProps?.row).toBeNull();
});
});

View File

@@ -1,96 +0,0 @@
import { ReactNode } from 'react';
import { act, AllTheProviders, renderHook } from 'tests/test-utils';
import { TracesTableRow } from 'container/TracesExplorer/TracesTable/getFieldColumn';
import { useSelectedSpanId } from 'pages/TraceDetailsV3/hooks/useSelectedSpanId';
import { useSpanDrawer } from '../useSpanDrawer';
const rows: TracesTableRow[] = [
{ id: 'row-a', trace_id: 'trace-1', span_id: 'span-a' },
{ id: 'row-b', trace_id: 'trace-1', span_id: 'span-b' },
];
const renderSpanDrawer = (initialRows: TracesTableRow[], initialRoute = '/') =>
renderHook(
({ current }: { current: TracesTableRow[] }) => ({
drawer: useSpanDrawer(current, false),
setSpanId: useSelectedSpanId()[1],
}),
{
initialProps: { current: initialRows },
wrapper: function Wrapper({ children }: { children: ReactNode }) {
return (
<AllTheProviders initialRoute={initialRoute}>{children}</AllTheProviders>
);
},
},
);
describe('useSpanDrawer', () => {
it('opens the span the url names, with ↑/↓ from its row', () => {
const { result } = renderSpanDrawer(rows, '/?traceId=trace-1&spanId=span-b');
expect(result.current.drawer.drawerProps.row).toBe(rows[1]);
expect(result.current.drawer.tableProps.activeRowIndex).toBe(1);
act(() => result.current.drawer.drawerProps.navigation?.goToPrev());
expect(result.current.drawer.drawerProps.spanId).toBe('span-a');
});
it('keeps a span open after its row leaves the list, without ↑/↓', () => {
const { result, rerender } = renderSpanDrawer(rows);
act(() => result.current.drawer.tableProps.onRowClick?.(rows[1]));
expect(result.current.drawer.drawerProps.navigation).not.toBeNull();
rerender({ current: [rows[0]] });
expect(result.current.drawer.drawerProps).toMatchObject({
traceId: 'trace-1',
spanId: 'span-b',
row: null,
navigation: null,
});
});
it('keeps ↑/↓ on the last list row while the url names a span outside the list', () => {
const { result } = renderSpanDrawer(rows);
act(() => result.current.drawer.tableProps.onRowClick?.(rows[0]));
act(() => result.current.setSpanId('span-b'));
act(() => result.current.setSpanId('span-outside'));
expect(result.current.drawer.drawerProps.row).toBeNull();
expect(result.current.drawer.tableProps.activeRowIndex).toBe(1);
act(() => result.current.drawer.drawerProps.navigation?.goToPrev());
expect(result.current.drawer.drawerProps.spanId).toBe('span-a');
});
it('steps past a span stored twice', () => {
const withDuplicate: TracesTableRow[] = [
{ id: 'row-a', trace_id: 'trace-1', span_id: 'span-a' },
{ id: 'row-a-copy', trace_id: 'trace-1', span_id: 'span-a' },
{ id: 'row-b', trace_id: 'trace-1', span_id: 'span-b' },
];
const { result } = renderSpanDrawer(withDuplicate);
act(() => result.current.drawer.tableProps.onRowClick?.(withDuplicate[0]));
act(() => result.current.drawer.drawerProps.navigation?.goToNext());
expect(result.current.drawer.tableProps.activeRowIndex).toBe(1);
act(() => result.current.drawer.drawerProps.navigation?.goToNext());
expect(result.current.drawer.drawerProps.spanId).toBe('span-b');
});
it('forgets the ↑/↓ row once the url closes the drawer', () => {
const { result } = renderSpanDrawer(rows);
act(() => result.current.drawer.tableProps.onRowClick?.(rows[1]));
act(() => result.current.setSpanId(null));
act(() => result.current.setSpanId('span-outside'));
expect(result.current.drawer.drawerProps.spanId).toBe('span-outside');
expect(result.current.drawer.tableProps.activeRowIndex).toBe(-1);
expect(result.current.drawer.drawerProps.navigation).toBeNull();
});
});

View File

@@ -1,9 +0,0 @@
import { FLAMEGRAPH_SPAN_LIMIT } from 'pages/TraceDetailsV3/TraceFlamegraph/constants';
export const FLAMEGRAPH_UNAVAILABLE_TOOLTIP = `Flame graph is not available for traces over ${Math.floor(FLAMEGRAPH_SPAN_LIMIT / 1000)}k spans`;
/** Pixels; the pane resizes between `min` and `max`. */
export const TRACE_PANE_HEIGHT = { default: 320, min: 120, max: 640 };
/** The drawer's trace views have no span filter. */
export const NO_FILTERED_SPANS: string[] = [];

View File

@@ -1,28 +0,0 @@
import { useEffect, useRef } from 'react';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { ExplorerViews } from 'pages/LogsExplorer/utils';
import { useSpanDrawerParams } from './useSpanDrawerParams';
/**
* Closes the span drawer when the query or the explorer view changes. It runs at
* page level because the list that hosts the drawer unmounts on another view.
*/
export function useCloseSpanDrawerOnQueryChange(view: ExplorerViews): void {
const [{ traceId, spanId }, setSpanDrawerParams] = useSpanDrawerParams();
const isOpen = !!traceId || !!spanId;
const { stagedQuery } = useQueryBuilder();
const queryId = stagedQuery?.id;
const lastRef = useRef({ queryId, view });
useEffect(() => {
const last = lastRef.current;
// The provider clears the staged query on a route change, so only one query id
// replacing another is a new query.
const isNewQuery = !!last.queryId && !!queryId && last.queryId !== queryId;
if (isOpen && (isNewQuery || last.view !== view)) {
void setSpanDrawerParams({ traceId: null, spanId: null });
}
lastRef.current = { queryId, view };
}, [queryId, view, isOpen, setSpanDrawerParams]);
}

View File

@@ -1,113 +0,0 @@
import { useEffect, useMemo } from 'react';
import { TracesTableRow } from 'container/TracesExplorer/TracesTable/getFieldColumn';
import { StatusCodes } from 'http-status-codes';
import { useSelectedSpanId } from 'pages/TraceDetailsV3/hooks/useSelectedSpanId';
import {
useTraceWaterfallData,
UseTraceWaterfallDataResult,
} from 'pages/TraceDetailsV3/hooks/useTraceWaterfallData';
import { SpanV3 } from 'types/api/trace/getTraceV3';
import { useLastShownSpan } from './useLastShownSpan';
import { toSpanV3 } from './utils';
type UseDrawerSpanParams = {
traceId: string | null;
spanId: string | null;
/** The list row of the open span, when it is loaded. */
row: TracesTableRow | null;
/** The list's first load; until it settles a missing `row` is not final. */
isListLoading: boolean;
isWaterfallShown: boolean;
/** The trace views read the same summary, so they 404 too. */
isSummaryNotFound: boolean;
};
type UseDrawerSpanResult = {
span: SpanV3 | undefined;
/** `span` is the previously shown one; the requested span is still loading. */
isStale: boolean;
isTraceMissing: boolean;
/** Fetched while shown, or for a span that is not a list row. */
waterfall: UseTraceWaterfallDataResult;
};
/**
* Picks the span to show: the waterfall's copy, else the list row's, else the
* last span shown until the requested one loads. A span id the trace doesn't
* have falls back to the trace's root span.
*/
export function useDrawerSpan({
traceId,
spanId,
row,
isListLoading,
isWaterfallShown,
isSummaryNotFound,
}: UseDrawerSpanParams): UseDrawerSpanResult {
const isOpen = !!traceId && !!spanId;
const isOutsideList = !row && !isListLoading;
const isWaterfallNeeded =
isOpen && !isSummaryNotFound && (isWaterfallShown || isOutsideList);
const waterfall = useTraceWaterfallData(traceId ?? '', {
enabled: isWaterfallNeeded,
});
const {
traceData,
allSpans,
isFetchingTraceData,
isPreviousData,
errorFetchingTraceData,
isFullDataLoaded,
interestedSpanId,
} = waterfall;
const [, setSpanId] = useSelectedSpanId();
const loadedSpan = useMemo(
() => allSpans.find((s) => s.span_id === spanId),
[allSpans, spanId],
);
const rowSpan = useMemo(() => (row ? toSpanV3(row) : undefined), [row]);
const currentSpan = loadedSpan ?? rowSpan;
const isSettled = isWaterfallNeeded && !isFetchingTraceData && !isPreviousData;
// Other errors keep the pane, whose views show their own error state.
const isTraceMissing = isSummaryNotFound
? isOutsideList
: isSettled &&
(errorFetchingTraceData?.response?.status === StatusCodes.NOT_FOUND ||
(!!traceData && allSpans.length === 0));
// A windowed response centres on the span it was asked for, so it is final
// only once that request has returned.
const rootSpanId =
isSettled &&
!currentSpan &&
allSpans.length > 0 &&
(isFullDataLoaded || interestedSpanId.spanId === spanId)
? allSpans[0].span_id
: null;
useEffect(() => {
if (rootSpanId) {
setSpanId(rootSpanId);
}
}, [rootSpanId, setSpanId]);
const lastShownSpan = useLastShownSpan(currentSpan, isOpen);
if (currentSpan) {
return {
span: currentSpan,
isStale: false,
isTraceMissing: false,
waterfall,
};
}
const isStale = !isTraceMissing && isOpen && !!lastShownSpan;
return {
span: isStale ? lastShownSpan : undefined,
isStale,
isTraceMissing,
waterfall,
};
}

View File

@@ -1,60 +0,0 @@
import { useState } from 'react';
import { FLAMEGRAPH_SPAN_LIMIT } from 'pages/TraceDetailsV3/TraceFlamegraph/constants';
export type TraceView = 'flamegraph' | 'waterfall';
type UseDrawerTraceViewParams = {
traceId: string | null;
/** Undefined until the open trace's summary has loaded. */
totalSpansCount: number | undefined;
isSummaryLoading: boolean;
};
export type UseDrawerTraceViewResult = {
/** The view on screen; the waterfall when the flame graph is unavailable. */
view: TraceView;
setView: (view: TraceView) => void;
/** The span count hasn't loaded, so no view is mounted yet. */
isPending: boolean;
/** False until a span count has loaded since the drawer opened. */
areTabsShown: boolean;
/** False above the flame graph limit. */
hasFlamegraph: boolean;
isWaterfallShown: boolean;
};
/** The trace view the drawer shows: Flame Graph first, one view at a time. */
export function useDrawerTraceView({
traceId,
totalSpansCount,
isSummaryLoading,
}: UseDrawerTraceViewParams): UseDrawerTraceViewResult {
const [chosenView, setView] = useState<TraceView>('flamegraph');
const loadedHasFlamegraph = isSummaryLoading
? undefined
: (totalSpansCount ?? 0) <= FLAMEGRAPH_SPAN_LIMIT;
// Moving to another trace keeps the last trace's tabs until its count loads.
const [heldHasFlamegraph, setHeldHasFlamegraph] =
useState(loadedHasFlamegraph);
const tabsHasFlamegraph = traceId
? (loadedHasFlamegraph ?? heldHasFlamegraph)
: undefined;
if (tabsHasFlamegraph !== heldHasFlamegraph) {
setHeldHasFlamegraph(tabsHasFlamegraph);
}
const isPending = !!traceId && loadedHasFlamegraph === undefined;
const hasFlamegraph = tabsHasFlamegraph ?? true;
const view: TraceView = hasFlamegraph ? chosenView : 'waterfall';
return {
view,
setView,
isPending,
areTabsShown: tabsHasFlamegraph !== undefined,
hasFlamegraph,
isWaterfallShown: !isPending && view === 'waterfall',
};
}

View File

@@ -1,16 +0,0 @@
import { useState } from 'react';
import { SpanV3 } from 'types/api/trace/getTraceV3';
/** The span shown last while the drawer is open, held until the next one loads. */
export function useLastShownSpan(
currentSpan: SpanV3 | undefined,
isOpen: boolean,
): SpanV3 | undefined {
const [lastShownSpan, setLastShownSpan] = useState<SpanV3>();
if (currentSpan && currentSpan !== lastShownSpan) {
setLastShownSpan(currentSpan);
} else if (!isOpen && lastShownSpan) {
setLastShownSpan(undefined);
}
return lastShownSpan;
}

View File

@@ -1,21 +1,22 @@
import { PointerEvent, useCallback, useMemo, useState } from 'react';
import {
PointerEvent,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import type { TableColumnDef } from 'components/TanStackTableView/types';
import { useRowNavigation } from 'components/TanStackTableView/useRowNavigation';
import { TracesTableRow } from 'container/TracesExplorer/TracesTable/getFieldColumn';
import type { TracesTableProps } from 'container/TracesExplorer/TracesTable/TracesTable';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useCloseOnOutsidePress } from 'hooks/useCloseOnOutsidePress';
import { OPEN_TRACE_COLUMN } from './openTraceColumn';
import type { SpanDrawerProps } from './SpanDrawer';
import { useSpanDrawerParams } from './useSpanDrawerParams';
import { findSpanRow } from './utils';
/**
* The highlighted row that ↑/↓ step from: the last row opened from the list. It
* stays while the drawer shows a span outside the list. The index tells
* duplicate rows apart.
*/
type Anchor = { traceId: string; spanId: string; index: number };
type ActiveSpan = { id: string; index: number };
type UseSpanDrawerResult = {
tableProps: Pick<
@@ -29,95 +30,78 @@ type UseSpanDrawerResult = {
onPressInside: (event: PointerEvent) => void;
};
const toAnchor = (row: TracesTableRow, index: number): Anchor => ({
traceId: String(row.trace_id),
spanId: String(row.span_id),
index,
});
export function useSpanDrawer(rows: TracesTableRow[]): UseSpanDrawerResult {
// The index lets navigation step past a duplicate span; the id survives a refetch.
const [activeSpan, setActiveSpan] = useState<ActiveSpan | null>(null);
export function useSpanDrawer(
rows: TracesTableRow[],
isListLoading: boolean,
): UseSpanDrawerResult {
const [{ traceId, spanId }, setSpanDrawerParams] = useSpanDrawerParams();
const isOpen = !!traceId && !!spanId;
const [anchor, setAnchor] = useState<Anchor | null>(null);
// The url can close the drawer too (Back, a new query).
if (!isOpen && anchor) {
setAnchor(null);
}
const anchorRowIndex = useMemo(
() => (anchor ? findSpanRow(rows, anchor, anchor.index) : -1),
[rows, anchor],
);
const openRowIndex = useMemo(() => {
if (!traceId || !spanId) {
const activeRowIndex = useMemo(() => {
if (!activeSpan) {
return -1;
}
if (anchor?.traceId === traceId && anchor.spanId === spanId) {
return anchorRowIndex;
}
return findSpanRow(rows, { traceId, spanId });
}, [rows, traceId, spanId, anchor, anchorRowIndex]);
// A span opened from the url (a link, a refresh) anchors ↑/↓ once its row loads.
if (openRowIndex !== -1 && openRowIndex !== anchorRowIndex) {
setAnchor(toAnchor(rows[openRowIndex], openRowIndex));
}
let activeRowIndex = -1;
if (isOpen) {
activeRowIndex = openRowIndex === -1 ? anchorRowIndex : openRowIndex;
}
return rows[activeSpan.index]?.id === activeSpan.id
? activeSpan.index
: rows.findIndex((row) => row.id === activeSpan.id);
}, [rows, activeSpan]);
const isRowActive = useCallback(
(row: TracesTableRow): boolean => row === rows[activeRowIndex],
[rows, activeRowIndex],
);
const openSpan = useCallback(
const handleNavigate = useCallback(
(row: TracesTableRow, index: number): void => {
const next = toAnchor(row, index);
setAnchor(next);
void setSpanDrawerParams({ traceId: next.traceId, spanId: next.spanId });
setActiveSpan({ id: row.id, index });
},
[setSpanDrawerParams],
[],
);
const openRow = useCallback(
(row: TracesTableRow): void => openSpan(row, rows.indexOf(row)),
[openSpan, rows],
const selectRow = useCallback(
(row: TracesTableRow): void => handleNavigate(row, rows.indexOf(row)),
[handleNavigate, rows],
);
const closeDrawer = useCallback((): void => {
setAnchor(null);
void setSpanDrawerParams({ traceId: null, spanId: null });
}, [setSpanDrawerParams]);
const clearActiveSpan = useCallback((): void => setActiveSpan(null), []);
const onPressInside = useCloseOnOutsidePress(isOpen, closeDrawer);
// A refetch can drop the open span; forget it so a later page can't reopen it.
useEffect(() => {
if (activeSpan && activeRowIndex === -1) {
setActiveSpan(null);
}
}, [activeSpan, activeRowIndex]);
// A new query closes the drawer at once instead of waiting for its rows.
const { stagedQuery } = useQueryBuilder();
const queryId = stagedQuery?.id;
const lastQueryIdRef = useRef(queryId);
useEffect(() => {
if (lastQueryIdRef.current && lastQueryIdRef.current !== queryId) {
setActiveSpan(null);
}
lastQueryIdRef.current = queryId;
}, [queryId]);
const onPressInside = useCloseOnOutsidePress(
activeRowIndex !== -1,
clearActiveSpan,
);
const navigation = useRowNavigation({
rows,
activeIndex: activeRowIndex,
onNavigate: openSpan,
onNavigate: handleNavigate,
});
return {
tableProps: {
onRowClick: openRow,
onRowClick: selectRow,
isRowActive,
activeRowIndex,
},
openTraceColumn: OPEN_TRACE_COLUMN,
drawerProps: {
traceId: isOpen ? traceId : null,
spanId: isOpen ? spanId : null,
row: rows[openRowIndex] ?? null,
onClose: closeDrawer,
navigation: activeRowIndex === -1 ? null : navigation,
isListLoading,
row: rows[activeRowIndex] ?? null,
onClose: clearActiveSpan,
navigation,
},
onPressInside,
};

View File

@@ -1,13 +0,0 @@
import { parseAsString, useQueryStates, UseQueryStatesReturn } from 'nuqs';
import { SELECTED_SPAN_ID_PARAM } from 'pages/TraceDetailsV3/hooks/useSelectedSpanId';
// `spanId` is shared with the trace views (useSelectedSpanId); same options.
const spanDrawerParams = {
traceId: parseAsString,
[SELECTED_SPAN_ID_PARAM]: parseAsString,
};
/** The url params of the span open in the drawer. */
export const useSpanDrawerParams = (): UseQueryStatesReturn<
typeof spanDrawerParams
> => useQueryStates(spanDrawerParams, { shallow: false });

View File

@@ -38,14 +38,3 @@ export const toSpanV3 = (row: TracesTableRow): SpanV3 => {
),
} as unknown as SpanV3;
};
/** Index of the row for this span; `hintIndex` wins when it is a copy of it. */
export const findSpanRow = (
rows: TracesTableRow[],
{ traceId, spanId }: { traceId: string; spanId: string },
hintIndex = -1,
): number => {
const isSpan = (row: TracesTableRow | undefined): boolean =>
row?.trace_id === traceId && row?.span_id === spanId;
return isSpan(rows[hintIndex]) ? hintIndex : rows.findIndex(isSpan);
};

View File

@@ -3,11 +3,6 @@ import { ScalarFieldValue } from 'utils/stringUtils';
import { ILog } from 'types/api/logs/log';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
export type LogTimeRange = {
start: number;
end: number;
};
export type UseCopyLogLink = {
isHighlighted: boolean;
isLogsExplorerPage: boolean;

View File

@@ -2,6 +2,7 @@ import { server } from 'mocks-server/server';
import { act, AllTheProviders, renderHook, waitFor } from 'tests/test-utils';
import { buildNotificationChannelAttachPermission } from 'lib/authz/hooks/useAuthZ/permissions/notification-channel.permissions';
import { formatPermission } from 'lib/authz/hooks/useAuthZ/utils';
import { LinkAccessState } from 'lib/authz/hooks/useLinkPickerAccess/types';
import { setupAuthzDeny } from 'lib/authz/utils/authz-test-utils';
import { useChannelPickerAccess } from '../useChannelPickerAccess';
@@ -31,16 +32,18 @@ describe('useChannelPickerAccess', () => {
act(() => result.current.onPickerVisibleChange(true));
await waitFor(() =>
expect(result.current.options[1].reason).toContain(formatPermission(denied)),
expect(result.current.options[1].state).toBe(LinkAccessState.Denied),
);
const [open, locked] = result.current.options;
expect(open).toMatchObject({
value: 'ops-slack',
label: 'ops-slack',
disabled: false,
state: LinkAccessState.Allowed,
testId: 'picker-option-c1',
});
expect(locked).toMatchObject({ disabled: true, denied: true });
expect(locked.reason).toContain(formatPermission(denied));
expect(locked).toMatchObject({
state: LinkAccessState.Denied,
reason: expect.stringContaining(formatPermission(denied)),
});
});
});

View File

@@ -6,6 +6,7 @@ import type { LinkPermissions } from 'lib/authz/hooks/useLinkPickerAccess/types'
import { useLinkPickerAccess } from 'lib/authz/hooks/useLinkPickerAccess/useLinkPickerAccess';
import type { ChannelOption } from './useChannelOptions';
import { getChannelIds } from './utils';
interface UseChannelPickerAccessArgs {
/** The `attach`/`detach` of the rule or policy being edited; absent when new. */
@@ -44,14 +45,14 @@ export function useChannelPickerAccess({
channels,
testIdPrefix,
}: UseChannelPickerAccessArgs): UseChannelPickerAccessReturn {
const linkedIds = useMemo(() => {
const saved = new Set(savedChannelNames);
return channels.filter((c) => saved.has(c.name)).map((c) => c.id);
}, [savedChannelNames, channels]);
const exemptIds = useMemo(() => {
const exempt = new Set(exemptChannelNames);
return channels.filter((c) => exempt.has(c.name)).map((c) => c.id);
}, [exemptChannelNames, channels]);
const linkedIds = useMemo(
() => getChannelIds(channels, savedChannelNames),
[channels, savedChannelNames],
);
const exemptIds = useMemo(
() => getChannelIds(channels, exemptChannelNames),
[channels, exemptChannelNames],
);
const optionIds = useMemo(() => channels.map((c) => c.id), [channels]);
const { getAccess, onPickerVisibleChange, isOwnerDenied } =

View File

@@ -1,115 +0,0 @@
import {
getFlamegraph,
getGetTraceSummaryQueryKey,
} from 'api/generated/services/tracedetail';
import type {
GetFlamegraph200,
GetTraceSummary200,
} from 'api/generated/services/sigNoz.schemas';
import {
AllTheProviders,
queryClient,
renderHook,
waitFor,
} from 'tests/test-utils';
import useGetTraceFlamegraphV3 from '../useGetTraceFlamegraphV3';
jest.mock('api/generated/services/tracedetail', () => ({
__esModule: true,
getFlamegraph: jest.fn(),
getGetTraceSummaryQueryKey: jest.requireActual(
'api/generated/services/tracedetail',
).getGetTraceSummaryQueryKey,
}));
const mockGetFlamegraph = jest.mocked(getFlamegraph);
const flamegraphResponse: GetFlamegraph200 = {
status: 'success',
data: {
spans: [],
hasMore: false,
startTimestampMillis: 0,
endTimestampMillis: 0,
},
};
const summaryWithMissingSpans: GetTraceSummary200 = {
status: 'success',
data: {
hasMissingSpans: true,
rootServiceName: 'frontend',
rootServiceEntryPoint: 'GET /',
rootSpanStatusCode: 'Unset',
startTimestampMillis: 0,
endTimestampMillis: 0,
totalSpansCount: 1,
totalErrorSpansCount: 0,
},
};
const requestSignal = (call: number): AbortSignal | undefined =>
mockGetFlamegraph.mock.calls[call][2];
describe('useGetTraceFlamegraphV3', () => {
beforeEach(() => {
mockGetFlamegraph.mockReset();
});
it('cancels the request for the previous trace when the trace changes', async () => {
mockGetFlamegraph.mockReturnValue(new Promise(() => {}));
const { rerender } = renderHook(
({ traceId }) => useGetTraceFlamegraphV3({ traceId, enabled: true }),
{ wrapper: AllTheProviders, initialProps: { traceId: 't1' } },
);
await waitFor(() => expect(mockGetFlamegraph).toHaveBeenCalledTimes(1));
expect(requestSignal(0)?.aborted).toBe(false);
rerender({ traceId: 't2' });
await waitFor(() => expect(mockGetFlamegraph).toHaveBeenCalledTimes(2));
expect(requestSignal(0)?.aborted).toBe(true);
expect(requestSignal(1)?.aborted).toBe(false);
});
it('serves a reopened trace from the cache', async () => {
mockGetFlamegraph.mockResolvedValue(flamegraphResponse);
const wrapper = AllTheProviders;
const first = renderHook(
() => useGetTraceFlamegraphV3({ traceId: 't1', enabled: true }),
{ wrapper },
);
await waitFor(() => expect(first.result.current.isSuccess).toBe(true));
first.unmount();
const second = renderHook(
() => useGetTraceFlamegraphV3({ traceId: 't1', enabled: true }),
{ wrapper },
);
expect(second.result.current.data).toStrictEqual(flamegraphResponse.data);
expect(mockGetFlamegraph).toHaveBeenCalledTimes(1);
});
it('refetches a reopened trace whose summary reports missing spans', async () => {
mockGetFlamegraph.mockResolvedValue(flamegraphResponse);
queryClient.setQueryData(
getGetTraceSummaryQueryKey({ traceID: 't1' }),
summaryWithMissingSpans,
);
const wrapper = AllTheProviders;
const first = renderHook(
() => useGetTraceFlamegraphV3({ traceId: 't1', enabled: true }),
{ wrapper },
);
await waitFor(() => expect(first.result.current.isSuccess).toBe(true));
first.unmount();
renderHook(() => useGetTraceFlamegraphV3({ traceId: 't1', enabled: true }), {
wrapper,
});
await waitFor(() => expect(mockGetFlamegraph).toHaveBeenCalledTimes(2));
});
});

View File

@@ -1,157 +0,0 @@
import {
getGetTraceSummaryQueryKey,
getWaterfallV4,
} from 'api/generated/services/tracedetail';
import type {
GetTraceSummary200,
GetWaterfallV4200,
SpantypesWaterfallSpanDTO,
} from 'api/generated/services/sigNoz.schemas';
import {
AllTheProviders,
queryClient,
renderHook,
waitFor,
} from 'tests/test-utils';
import { GetTraceV4PayloadProps } from 'types/api/trace/getTraceV3';
import useGetTraceV4 from '../useGetTraceV4';
jest.mock('api/generated/services/tracedetail', () => ({
__esModule: true,
getWaterfallV4: jest.fn(),
getGetTraceSummaryQueryKey: jest.requireActual(
'api/generated/services/tracedetail',
).getGetTraceSummaryQueryKey,
}));
const mockGetWaterfallV4 = jest.mocked(getWaterfallV4);
const rootSpan: SpantypesWaterfallSpanDTO = {
span_id: 'root',
parent_span_id: '',
trace_id: 't1',
level: 0,
has_children: false,
name: 'root',
time_unix: 0,
duration_nano: 1,
references: [],
};
const waterfallResponse = (totalSpansCount: number): GetWaterfallV4200 => ({
status: 'success',
data: {
spans: [rootSpan],
totalSpansCount,
startTimestampMillis: 0,
endTimestampMillis: 0,
},
});
const payload = (traceId: string): GetTraceV4PayloadProps => ({
traceId,
selectedSpanId: '',
uncollapsedSpans: [],
isSelectedSpanIDUnCollapsed: false,
});
const summaryWithMissingSpans: GetTraceSummary200 = {
status: 'success',
data: {
hasMissingSpans: true,
rootServiceName: 'frontend',
rootServiceEntryPoint: 'GET /',
rootSpanStatusCode: 'Unset',
startTimestampMillis: 0,
endTimestampMillis: 0,
totalSpansCount: 1,
totalErrorSpansCount: 0,
},
};
const requestSignal = (call: number): AbortSignal | undefined =>
mockGetWaterfallV4.mock.calls[call][2];
describe('useGetTraceV4', () => {
beforeEach(() => {
mockGetWaterfallV4.mockReset();
});
it('cancels the request for the previous trace when the trace changes', async () => {
mockGetWaterfallV4.mockReturnValue(new Promise(() => {}));
const { rerender } = renderHook(
({ traceId }) => useGetTraceV4(payload(traceId)),
{ wrapper: AllTheProviders, initialProps: { traceId: 't1' } },
);
await waitFor(() => expect(mockGetWaterfallV4).toHaveBeenCalledTimes(1));
expect(requestSignal(0)?.aborted).toBe(false);
rerender({ traceId: 't2' });
await waitFor(() => expect(mockGetWaterfallV4).toHaveBeenCalledTimes(2));
expect(requestSignal(0)?.aborted).toBe(true);
expect(requestSignal(1)?.aborted).toBe(false);
});
it('serves a reopened trace from the cache', async () => {
mockGetWaterfallV4.mockResolvedValue(waterfallResponse(1));
const wrapper = AllTheProviders;
const first = renderHook(() => useGetTraceV4(payload('t1')), { wrapper });
await waitFor(() => expect(first.result.current.isSuccess).toBe(true));
first.unmount();
const second = renderHook(() => useGetTraceV4(payload('t1')), { wrapper });
expect(second.result.current.isSuccess).toBe(true);
expect(mockGetWaterfallV4).toHaveBeenCalledTimes(1);
});
it('refetches a reopened windowed trace', async () => {
mockGetWaterfallV4.mockResolvedValue(waterfallResponse(20_000));
const wrapper = AllTheProviders;
const first = renderHook(() => useGetTraceV4(payload('t1')), { wrapper });
await waitFor(() => expect(first.result.current.isSuccess).toBe(true));
first.unmount();
renderHook(() => useGetTraceV4(payload('t1')), { wrapper });
await waitFor(() => expect(mockGetWaterfallV4).toHaveBeenCalledTimes(2));
});
it('refetches a reopened trace whose summary reports missing spans', async () => {
mockGetWaterfallV4.mockResolvedValue(waterfallResponse(1));
queryClient.setQueryData(
getGetTraceSummaryQueryKey({ traceID: 't1' }),
summaryWithMissingSpans,
);
const wrapper = AllTheProviders;
const first = renderHook(() => useGetTraceV4(payload('t1')), { wrapper });
await waitFor(() => expect(first.result.current.isSuccess).toBe(true));
first.unmount();
renderHook(() => useGetTraceV4(payload('t1')), { wrapper });
await waitFor(() => expect(mockGetWaterfallV4).toHaveBeenCalledTimes(2));
});
it('refetches a trace with missing spans when switching back to it', async () => {
mockGetWaterfallV4.mockResolvedValue(waterfallResponse(1));
queryClient.setQueryData(
getGetTraceSummaryQueryKey({ traceID: 't1' }),
summaryWithMissingSpans,
);
const { result, rerender } = renderHook(
({ traceId }) => useGetTraceV4(payload(traceId)),
{ wrapper: AllTheProviders, initialProps: { traceId: 't1' } },
);
await waitFor(() => expect(result.current.isSuccess).toBe(true));
rerender({ traceId: 't2' });
await waitFor(() => expect(mockGetWaterfallV4).toHaveBeenCalledTimes(2));
rerender({ traceId: 't1' });
await waitFor(() => expect(mockGetWaterfallV4).toHaveBeenCalledTimes(3));
expect(mockGetWaterfallV4.mock.calls[2][0]).toStrictEqual({ traceID: 't1' });
});
});

View File

@@ -7,8 +7,6 @@ import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { useQuery, UseQueryResult } from 'react-query';
import { TelemetryFieldKey } from 'types/api/v5/queryRange';
import { useTraceQueryStaleTime } from './useTraceQueryStaleTime';
export interface GetTraceFlamegraphV3Props {
traceId: string;
selectedSpanId?: string;
@@ -18,10 +16,9 @@ export interface GetTraceFlamegraphV3Props {
const useGetTraceFlamegraphV3 = (
props: GetTraceFlamegraphV3Props,
): UseQueryResult<SpantypesGettableFlamegraphTraceDTO, unknown> => {
const staleTime = useTraceQueryStaleTime(props.traceId);
return useQuery({
queryFn: ({ signal }) =>
): UseQueryResult<SpantypesGettableFlamegraphTraceDTO, unknown> =>
useQuery({
queryFn: () =>
getFlamegraph(
{ traceID: props.traceId },
{
@@ -30,7 +27,6 @@ const useGetTraceFlamegraphV3 = (
// the literal-union vs enum nominal types differ
selectFields: props.selectFields as TelemetrytypesTelemetryFieldKeyDTO[],
},
signal,
).then((res) => res.data),
queryKey: [
REACT_QUERY_KEY.GET_TRACE_V3_FLAMEGRAPH,
@@ -41,8 +37,6 @@ const useGetTraceFlamegraphV3 = (
enabled: props.enabled,
keepPreviousData: true,
refetchOnWindowFocus: false,
staleTime,
});
};
export default useGetTraceFlamegraphV3;

View File

@@ -1,6 +1,4 @@
import { useQuery, useQueryClient, UseQueryResult } from 'react-query';
import type { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';
import type { ErrorType } from 'api/generatedAPIInstance';
import { useQuery, UseQueryResult } from 'react-query';
import getTraceV4 from 'api/trace/getTraceV4';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { ErrorResponse, SuccessResponse } from 'types/api';
@@ -9,50 +7,23 @@ import {
GetTraceV4SuccessResponse,
} from 'types/api/trace/getTraceV3';
import { useTraceQueryStaleTime } from './useTraceQueryStaleTime';
type UseGetTraceV4Options = {
/** Defaults to true; the query also needs a trace id. */
enabled?: boolean;
};
const useGetTraceV4 = (
props: GetTraceV4PayloadProps,
{ enabled = true }: UseGetTraceV4Options = {},
): UseTraceV4 => {
const traceStaleTime = useTraceQueryStaleTime(props.traceId);
const queryClient = useQueryClient();
const queryKey = [
REACT_QUERY_KEY.GET_TRACE_V4_WATERFALL,
props.traceId,
props.selectedSpanId,
props.isSelectedSpanIDUnCollapsed,
];
// A windowed response depends on `uncollapsedSpans`, which the key leaves out: each
// response's list feeds the next request, so keying on it would fetch twice.
const isCachedTraceComplete = isCompleteTrace(
queryClient.getQueryData<UseTraceV4['data']>(queryKey),
);
return useQuery({
queryFn: ({ signal }) => getTraceV4(props, signal),
queryKey,
enabled: enabled && !!props.traceId,
const useGetTraceV4 = (props: GetTraceV4PayloadProps): UseTraceV4 =>
useQuery({
queryFn: () => getTraceV4(props),
queryKey: [
REACT_QUERY_KEY.GET_TRACE_V4_WATERFALL,
props.traceId,
props.selectedSpanId,
props.isSelectedSpanIDUnCollapsed,
],
enabled: !!props.traceId,
keepPreviousData: true,
refetchOnWindowFocus: false,
staleTime: isCachedTraceComplete ? traceStaleTime : 0,
});
};
const isCompleteTrace = (data: UseTraceV4['data']): boolean => {
const totalSpansCount = data?.payload?.totalSpansCount ?? 0;
return (
totalSpansCount > 0 && totalSpansCount <= (data?.payload?.spans.length ?? 0)
);
};
type UseTraceV4 = UseQueryResult<
SuccessResponse<GetTraceV4SuccessResponse> | ErrorResponse,
ErrorType<RenderErrorResponseDTO>
unknown
>;
export default useGetTraceV4;

View File

@@ -1,17 +0,0 @@
import { useQueryClient } from 'react-query';
import type { GetTraceSummary200 } from 'api/generated/services/sigNoz.schemas';
import { getGetTraceSummaryQueryKey } from 'api/generated/services/tracedetail';
const TRACE_QUERY_STALE_TIME_MS = 5 * 60 * 1000;
/**
* A trace whose cached summary reports missing spans may still be ingesting,
* so its queries refetch on each open instead of serving the cache.
*/
export function useTraceQueryStaleTime(traceId: string): number {
const queryClient = useQueryClient();
const summary = queryClient.getQueryData<GetTraceSummary200>(
getGetTraceSummaryQueryKey({ traceID: traceId }),
);
return summary?.data?.hasMissingSpans ? 0 : TRACE_QUERY_STALE_TIME_MS;
}

View File

@@ -2,6 +2,11 @@ import { TooltipProvider } from '@signozhq/ui/tooltip';
import { render, screen, userEvent, within } from 'tests/test-utils';
import AuthZSelect from './AuthZSelect';
import {
type LinkAccess,
LinkAccessState,
} from 'lib/authz/hooks/useLinkPickerAccess/types';
import type { AuthZSelectOption } from './types';
const DENIAL =
@@ -9,21 +14,25 @@ const DENIAL =
const option = (
value: string,
access: Partial<AuthZSelectOption> = {},
overrides: Partial<Pick<AuthZSelectOption, 'label'>> & {
access?: LinkAccess;
} = {},
): AuthZSelectOption => ({
...(overrides.access ?? { state: LinkAccessState.Allowed }),
value,
label: value,
disabled: false,
denied: false,
label: overrides.label ?? value,
testId: `option-${value}`,
...access,
});
const OPTIONS = [
option('open'),
option('c-9', { label: 'PagerDuty' }),
option('pending', { disabled: true, reason: 'Checking permissions' }),
option('locked-channel', { disabled: true, reason: DENIAL, denied: true }),
option('pending', {
access: { state: LinkAccessState.Pending, reason: 'Checking permissions' },
}),
option('locked-channel', {
access: { state: LinkAccessState.Denied, reason: DENIAL },
}),
];
const renderSelect = (value: string[] = []): void => {

View File

@@ -1,15 +1,11 @@
import type { SelectProps } from 'antd';
import type { LinkAccess } from 'lib/authz/hooks/useLinkPickerAccess/types';
export interface AuthZSelectOption {
export type AuthZSelectOption = LinkAccess & {
value: string;
label: string;
disabled: boolean;
/** Why it is disabled: a denial, or that the check is still running. */
reason?: string;
/** `reason` is a denial, shown on the red tooltip. */
denied: boolean;
testId: string;
}
};
export type AuthZSelectProps = Omit<
SelectProps<string[]>,

View File

@@ -1,4 +1,5 @@
import type { BaseOptionType, DefaultOptionType } from 'antd/es/select';
import { LinkAccessState } from 'lib/authz/hooks/useLinkPickerAccess/types';
import AuthZSelectLabel from './AuthZSelectLabel';
import type { AuthZSelectOption } from './types';
@@ -14,26 +15,32 @@ const truncate = (text: string, maxLength?: number): string =>
export const toSelectOption = (
option: AuthZSelectOption,
maxTagTextLength?: number,
): DefaultOptionType => ({
value: option.value,
label: option.label,
disabled: option.disabled,
reason: option.reason,
denied: option.denied,
// An empty title keeps the browser's own tooltip from doubling ours.
title: option.reason ? '' : undefined,
'aria-disabled': option.disabled,
'aria-description': option.reason,
'data-testid': option.testId,
// A string lets the select truncate the tag itself.
[TAG_LABEL_PROP]: option.reason ? (
<AuthZSelectLabel reason={option.reason} denied={option.denied}>
{truncate(option.label, maxTagTextLength)}
</AuthZSelectLabel>
) : (
option.label
),
});
): DefaultOptionType => {
const reason =
option.state === LinkAccessState.Allowed ? undefined : option.reason;
const denied = option.state === LinkAccessState.Denied;
return {
value: option.value,
label: option.label,
disabled: !!reason,
reason,
denied,
// An empty title keeps the browser's own tooltip from doubling ours.
title: reason ? '' : undefined,
'aria-disabled': !!reason,
'aria-description': reason,
'data-testid': option.testId,
// A string lets the select truncate the tag itself.
[TAG_LABEL_PROP]: reason ? (
<AuthZSelectLabel reason={reason} denied={denied}>
{truncate(option.label, maxTagTextLength)}
</AuthZSelectLabel>
) : (
option.label
),
};
};
export const renderOption = ({
data,

View File

@@ -7,6 +7,8 @@ export const RuleListPermission = buildPermission('list', 'rule:*');
export const RuleCreatePermission = buildPermission('create', 'rule:*');
// A new rule has no id yet, so linking its channels is checked on the wildcard.
export const RuleAttachPermission = buildPermission('attach', 'rule:*');
export const RuleListChecks = [RuleListPermission];
export const RuleCreateChecks = [RuleCreatePermission];
// Resource-level. Requires a specific rule id.
export const buildRuleReadPermission = (id: string): BrandedPermission =>

View File

@@ -1,13 +1,17 @@
import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';
export interface LinkAccess {
disabled: boolean;
/** The denial, or that the check is still running. */
reason?: string;
/** A check refused it, as opposed to one still running. */
denied: boolean;
export enum LinkAccessState {
Allowed = 'allowed',
Pending = 'pending',
Denied = 'denied',
}
export type LinkAccess =
| { state: LinkAccessState.Allowed }
/** `reason` says the check is still running. */
| { state: LinkAccessState.Pending; reason: string }
| { state: LinkAccessState.Denied; reason: string };
export interface LinkPermissions {
attach: BrandedPermission;
detach: BrandedPermission;

View File

@@ -7,7 +7,11 @@ import { buildPermission } from 'lib/authz/hooks/useAuthZ/utils';
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
import { mockUseAuthZGrantAll } from 'lib/authz/utils/authz-test-utils';
import type { LinkPermissions, UseLinkPickerAccessArgs } from './types';
import {
type LinkPermissions,
LinkAccessState,
type UseLinkPickerAccessArgs,
} from './types';
import { useLinkPickerAccess } from './useLinkPickerAccess';
jest.mock('lib/authz/hooks/useAuthZ/useAuthZ');
@@ -100,9 +104,9 @@ describe('useLinkPickerAccess', () => {
upfront: [],
picker: [OWNER.attach, item('c').attach],
});
expect(result.current.getAccess('a').disabled).toBe(false);
expect(result.current.getAccess('b').disabled).toBe(false);
expect(result.current.getAccess('c').disabled).toBe(true);
expect(result.current.getAccess('a').state).toBe(LinkAccessState.Allowed);
expect(result.current.getAccess('b').state).toBe(LinkAccessState.Allowed);
expect(result.current.getAccess('c').state).toBe(LinkAccessState.Denied);
});
it('tells a refused item from one still being checked', () => {
@@ -124,13 +128,7 @@ describe('useLinkPickerAccess', () => {
optionIds: ['a', 'b'],
});
expect(result.current.getAccess('a')).toMatchObject({
disabled: true,
denied: true,
});
expect(result.current.getAccess('b')).toMatchObject({
disabled: true,
denied: false,
});
expect(result.current.getAccess('a').state).toBe(LinkAccessState.Denied);
expect(result.current.getAccess('b').state).toBe(LinkAccessState.Pending);
});
});

View File

@@ -5,19 +5,19 @@ import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
import { useAppContext } from 'providers/App/App';
import type {
LinkAccess,
UseLinkPickerAccessArgs,
UseLinkPickerAccessReturn,
import {
type LinkAccess,
LinkAccessState,
type UseLinkPickerAccessArgs,
type UseLinkPickerAccessReturn,
} from './types';
const NO_CHECKS: BrandedPermission[] = [];
const NO_IDS: string[] = [];
const ALLOWED: LinkAccess = { disabled: false, denied: false };
const ALLOWED: LinkAccess = { state: LinkAccessState.Allowed };
const PENDING: LinkAccess = {
disabled: true,
state: LinkAccessState.Pending,
reason: AUTHZ_LOADING_TOOLTIP,
denied: false,
};
/**
@@ -78,6 +78,11 @@ export function useLinkPickerAccess({
enabled: hasPickerOpened && pickerChecks.length > 0,
});
const results = useMemo(
() => ({ ...upfront.permissions, ...picker.permissions }),
[upfront.permissions, picker.permissions],
);
const getAccess = useCallback(
(id: string): LinkAccess => {
if (exempt.has(id)) {
@@ -88,7 +93,6 @@ export function useLinkPickerAccess({
(permission) =>
!(upfrontSet.has(permission) ? upfront.error : picker.error),
);
const results = { ...upfront.permissions, ...picker.permissions };
// A check reports loading only once its fetch starts, a render after the
// picker opens; a missing result keeps the option from flashing enabled.
if (required.some((permission) => !results[permission])) {
@@ -100,9 +104,8 @@ export function useLinkPickerAccess({
);
return denied.length > 0
? {
disabled: true,
state: LinkAccessState.Denied,
reason: formatDeniedMessage(denied, user.id),
denied: true,
}
: ALLOWED;
},
@@ -111,9 +114,8 @@ export function useLinkPickerAccess({
requiredFor,
upfrontSet,
upfront.error,
upfront.permissions,
picker.error,
picker.permissions,
results,
user.id,
],
);

View File

@@ -1,4 +1,5 @@
import { ArrowLeft, Plus, Settings, X } from '@signozhq/icons';
import { Tooltip } from '@signozhq/ui/tooltip';
import OverlayScrollbar from 'components/OverlayScrollbar/OverlayScrollbar';
import {
type DrilldownVariableAction,
@@ -47,29 +48,36 @@ function DrilldownDashboardVariablesMenu({
options={{ overflow: { x: 'hidden' } }}
>
<>
{actions.map(({ fieldName, fieldValue, kind, onClick }) => (
<ContextMenu.Item
key={fieldName}
icon={ICON_BY_KIND[kind]}
onClick={onClick}
>
{kind === DrilldownVariableActionKind.Unset && (
<span data-testid="drilldown-var-unset">
Unset <strong>${fieldName}</strong>
</span>
)}
{kind === DrilldownVariableActionKind.Set && (
<span data-testid="drilldown-var-set">
Set <strong>${fieldName}</strong> to <strong>{fieldValue}</strong>
</span>
)}
{kind === DrilldownVariableActionKind.Create && (
<span data-testid="drilldown-var-create">
Create var <strong>${fieldName}</strong>:<strong>{fieldValue}</strong>
</span>
)}
</ContextMenu.Item>
))}
{actions.map(
({ fieldName, fieldValue, kind, onClick, disabledTooltip }) => (
<Tooltip key={fieldName} title={disabledTooltip} side="right">
<div>
<ContextMenu.Item
icon={ICON_BY_KIND[kind]}
onClick={onClick}
disabled={!!disabledTooltip}
>
{kind === DrilldownVariableActionKind.Unset && (
<span data-testid="drilldown-var-unset">
Unset <strong>${fieldName}</strong>
</span>
)}
{kind === DrilldownVariableActionKind.Set && (
<span data-testid="drilldown-var-set">
Set <strong>${fieldName}</strong> to <strong>{fieldValue}</strong>
</span>
)}
{kind === DrilldownVariableActionKind.Create && (
<span data-testid="drilldown-var-create">
Create var <strong>${fieldName}</strong>:
<strong>{fieldValue}</strong>
</span>
)}
</ContextMenu.Item>
</div>
</Tooltip>
),
)}
</>
</OverlayScrollbar>
</>

View File

@@ -62,6 +62,25 @@ describe('DrilldownDashboardVariablesMenu', () => {
expect(onSet).toHaveBeenCalledTimes(1);
});
it('renders a disabled entry that does not fire its onClick', async () => {
const onCreate = jest.fn();
render(
<DrilldownDashboardVariablesMenu
onBack={jest.fn()}
actions={[
action({
kind: DrilldownVariableActionKind.Create,
onClick: onCreate,
disabledTooltip: 'no edit access',
}),
]}
/>,
);
await userEvent.click(screen.getByTestId('drilldown-var-create'));
expect(onCreate).not.toHaveBeenCalled();
});
it('returns to the base menu when the back arrow is clicked', async () => {
const onBack = jest.fn();
render(

View File

@@ -15,13 +15,8 @@ const mockNavigate = jest.fn();
const mockGetBuilderQueries = jest.fn();
const mockGetPanelQueryType = jest.fn();
let mockResolved = { resolvedQuery: 'RESOLVED_QUERY', isResolving: false };
let mockDashboardVariables: {
hasFieldVariables: boolean;
actions: unknown[];
} = {
hasFieldVariables: true,
actions: [],
};
const SET_ACTION = { fieldName: 'service.name' };
let mockDashboardVariables: { actions: unknown[] } = { actions: [SET_ACTION] };
// Boundaries tested elsewhere / needing external context — mocked so this suite isolates
// useDrilldown's orchestration (gating, which menu shows, the View-modal handoff).
@@ -145,10 +140,7 @@ describe('useDrilldown', () => {
mockGetBuilderQueries.mockReturnValue([{ name: 'A' }]);
mockGetPanelQueryType.mockReturnValue(EQueryType.QUERY_BUILDER);
mockResolved = { resolvedQuery: 'RESOLVED_QUERY', isResolving: false };
mockDashboardVariables = {
hasFieldVariables: true,
actions: [],
};
mockDashboardVariables = { actions: [SET_ACTION] };
});
describe('enableDrillDown', () => {
@@ -169,6 +161,24 @@ describe('useDrilldown', () => {
expect(result.current.enableDrillDown).toBe(false);
});
it('is false when every builder query is disabled, leaving only formulas to draw', () => {
mockGetBuilderQueries.mockReturnValue([
{ name: 'A', disabled: true },
{ name: 'B', disabled: true },
]);
const { result } = renderHook(() => useDrilldown(tsPanel, 'p1'));
expect(result.current.enableDrillDown).toBe(false);
});
it('is true when at least one builder query is enabled', () => {
mockGetBuilderQueries.mockReturnValue([
{ name: 'A', disabled: true },
{ name: 'B' },
]);
const { result } = renderHook(() => useDrilldown(tsPanel, 'p1'));
expect(result.current.enableDrillDown).toBe(true);
});
it.each([EQueryType.PROM, EQueryType.CLICKHOUSE, undefined])(
'is false when the query type is %s (not the builder)',
(queryType) => {
@@ -266,7 +276,7 @@ describe('useDrilldown', () => {
});
it('hides the Dashboard Variables entry when there are no group-by fields', () => {
mockDashboardVariables = { hasFieldVariables: false, actions: [] };
mockDashboardVariables = { actions: [] };
const { result } = renderHook(() => useDrilldown(tsPanel, 'p1'));
act(() =>
result.current.onPanelClick({

View File

@@ -4,7 +4,10 @@ import { DashboardtypesDynamicVariableSignalDTO } from 'api/generated/services/s
import type { FilterData } from 'container/QueryTable/Drilldown/drilldownUtils';
import DrilldownDashboardVariablesMenu from '../DrilldownMenu/DrilldownDashboardVariablesMenu';
import { useDrilldownDashboardVariables } from '../hooks/useDrilldownDashboardVariables';
import {
DrilldownVariableActionKind,
useDrilldownDashboardVariables,
} from '../hooks/useDrilldownDashboardVariables';
// Fake dashboard variables + runtime selection, mutated per test. `dtoToFormModel` is mocked to
// derive `type` from the plugin kind (like the real adapter), so these DTOs carry the plugin
@@ -18,6 +21,7 @@ let mockVariables: Array<{
let mockSelectionMap: Record<string, { value: unknown; allSelected: boolean }> =
{};
let mockIsEditable = true;
const mockSetVariableValue = jest.fn();
const mockPatchAsync = jest.fn().mockResolvedValue(undefined);
@@ -29,6 +33,15 @@ jest.mock('api/generated/services/dashboard', () => ({
data: { data: { spec: { variables: mockVariables } } },
}),
}));
jest.mock(
'pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext',
() => ({
useDashboardEditContext: (): unknown => ({
isEditable: mockIsEditable,
editDisabledTooltip: 'no edit access',
}),
}),
);
jest.mock(
'pages/DashboardPage/DashboardContainer/hooks/useOptimisticPatch',
() => ({
@@ -97,21 +110,22 @@ function renderItems(): void {
describe('useDrilldownDashboardVariables', () => {
beforeEach(() => {
mockIsEditable = true;
jest.clearAllMocks();
mockVariables = [];
mockSelectionMap = {};
});
it('hasFieldVariables reflects the clicked point group-by fields', () => {
it('offers an action per clicked point group-by field', () => {
const withFields = renderHook(() =>
useDrilldownDashboardVariables({ filters, onClose: jest.fn() }),
);
expect(withFields.result.current.hasFieldVariables).toBe(true);
expect(withFields.result.current.actions).toHaveLength(1);
const noFields = renderHook(() =>
useDrilldownDashboardVariables({ filters: [], onClose: jest.fn() }),
);
expect(noFields.result.current.hasFieldVariables).toBe(false);
expect(noFields.result.current.actions).toStrictEqual([]);
});
it('offers Set — writing an array for a multi-select var so the selector shows it', async () => {
@@ -171,6 +185,41 @@ describe('useDrilldownDashboardVariables', () => {
});
});
it('offers Create disabled with the reason on a dashboard the viewer cannot edit', () => {
mockVariables = [];
mockIsEditable = false;
const { result } = renderHook(() =>
useDrilldownDashboardVariables({ filters, onClose: jest.fn() }),
);
expect(result.current.actions).toMatchObject([
{
kind: DrilldownVariableActionKind.Create,
disabledTooltip: 'no edit access',
},
]);
});
it('still offers Set on a dashboard the viewer cannot edit', async () => {
mockVariables = [
{
name: 'svc',
dynamicAttribute: 'service.name',
multiSelect: true,
spec: { plugin: { kind: DYNAMIC_KIND } },
},
];
mockSelectionMap = { svc: { value: ['backend'], allSelected: false } };
mockIsEditable = false;
renderItems();
await userEvent.click(screen.getByTestId('drilldown-var-set'));
expect(mockSetVariableValue).toHaveBeenCalledWith('d1', 'svc', {
value: ['frontend'],
allSelected: false,
});
});
it('offers Create and persists a new dynamic variable when none matches', async () => {
mockVariables = [];
renderItems();

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