mirror of
https://github.com/SigNoz/signoz.git
synced 2026-12-03 13:40:42 +00:00
Compare commits
57 Commits
chore/dead
...
feat/syste
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
167f0c9325 | ||
|
|
7b689e4ee9 | ||
|
|
9d0dca6c0e | ||
|
|
d1508cb5c5 | ||
|
|
ba18445827 | ||
|
|
45095468e9 | ||
|
|
455e667378 | ||
|
|
e1346d7e9c | ||
|
|
fe0f68589a | ||
|
|
72b084df28 | ||
|
|
761df6bf23 | ||
|
|
091a7a2fef | ||
|
|
5f90b3e68b | ||
|
|
095c2224c0 | ||
|
|
b0794a372b | ||
|
|
d983fe0970 | ||
|
|
711a2d1284 | ||
|
|
c17f72835d | ||
|
|
fcd8249e3f | ||
|
|
8d6ce5c257 | ||
|
|
ecae1813bc | ||
|
|
9429555e15 | ||
|
|
1ac3e95f14 | ||
|
|
dd7a3398d0 | ||
|
|
dd377bec63 | ||
|
|
bbf2fb4ec4 | ||
|
|
eb9e1b9a93 | ||
|
|
3c4eda82eb | ||
|
|
3ac1479cc3 | ||
|
|
fb55fbd303 | ||
|
|
24bd5efe7c | ||
|
|
79894a0f96 | ||
|
|
1d8655c606 | ||
|
|
a34b75f86d | ||
|
|
7339662720 | ||
|
|
d1dd086cec | ||
|
|
909c378c9b | ||
|
|
1c7a93bd7a | ||
|
|
dabd6bf45e | ||
|
|
3fd05f57ba | ||
|
|
79f7d35033 | ||
|
|
5c9379e4ad | ||
|
|
11bda9f282 | ||
|
|
726f89a893 | ||
|
|
3851339e6c | ||
|
|
a4dde27546 | ||
|
|
0402254209 | ||
|
|
4225452554 | ||
|
|
50dfec7247 | ||
|
|
ce1117eaa0 | ||
|
|
2eb46f19fb | ||
|
|
e37e94af53 | ||
|
|
f060e262d2 | ||
|
|
27a11ada95 | ||
|
|
a4d83ea2fd | ||
|
|
2e4d47a124 | ||
|
|
5a62bcd85c |
21
.claude/rules/dashboard-controls.md
Normal file
21
.claude/rules/dashboard-controls.md
Normal file
@@ -0,0 +1,21 @@
|
||||
---
|
||||
paths:
|
||||
- "frontend/src/pages/DashboardPage/DashboardContainer/**"
|
||||
---
|
||||
|
||||
# Dashboard controls
|
||||
|
||||
`DashboardContainer` is mounted by hosts other than the dashboard page (system dashboards, the cost meter). Each host picks what renders through `controls` ([`controls/types.ts`](../../frontend/src/pages/DashboardPage/DashboardContainer/controls/types.ts)); a read-only mount hides every writing control on top of that.
|
||||
|
||||
Anything the container renders that a host might not want is a control, and every control is wired in four places. The first two are type-checked; the last two are not, so check them on every change. The `add-dashboard-control` skill ([`frontend/.claude/skills/add-dashboard-control/SKILL.md`](../../frontend/.claude/skills/add-dashboard-control/SKILL.md)) walks through them.
|
||||
|
||||
- **Declare it** in `DashboardControls` under the group it renders in. A new group also extends `DashboardControlsInput`.
|
||||
- **Default it** in `DEFAULT_CONTROLS` and say whether it writes the dashboard in `CONTROL_WRITES_DASHBOARD`. Both are exhaustive, so this fails to compile until done.
|
||||
- **Read it where it renders**, with `useDashboardControl('group.item')` or `useDashboardControlGroup('group')`. A control nobody reads is a lie to the host: the thing still renders.
|
||||
- **Revisit the presets** in `controls/presets.ts`; a control that belongs to the host page goes off in `EMBEDDED`.
|
||||
|
||||
Rules of thumb:
|
||||
|
||||
- A new field drawn from the dashboard JSON (a badge, a line in the title row, a toolbar item) needs a control before it ships, not after a host complains.
|
||||
- Derive a control's dependents in `resolveControls`, never at the render site (Rename needs the title shown).
|
||||
- Lock and permission state are not controls. They decide disabled + reason through `useDashboardEditContext`; controls decide shown or hidden.
|
||||
@@ -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
|
||||
|
||||
30
frontend/.claude/skills/add-dashboard-control/SKILL.md
Normal file
30
frontend/.claude/skills/add-dashboard-control/SKILL.md
Normal file
@@ -0,0 +1,30 @@
|
||||
---
|
||||
name: add-dashboard-control
|
||||
description: Add or change a host-toggleable control on the embeddable DashboardContainer (header, title row, toolbar, dashboard/section/panel actions, view modal). Use when a new element renders inside DashboardContainer, when a host page (system dashboard, cost meter) needs to hide something, or when DashboardControls, DEFAULT_CONTROLS, CONTROL_WRITES_DASHBOARD or the presets change.
|
||||
---
|
||||
|
||||
# Add a dashboard control
|
||||
|
||||
Everything lives under `src/pages/DashboardPage/DashboardContainer/controls/`. The rule that applies is [`.claude/rules/dashboard-controls.md`](../../../../.claude/rules/dashboard-controls.md).
|
||||
|
||||
## Steps
|
||||
|
||||
1. **Declare** the control in `DashboardControls` (`types.ts`), in the group where it renders. Panel actions are keyed by `PanelActionId`, so a new panel menu item is already a control.
|
||||
2. **Default** it in `DEFAULT_CONTROLS` and classify it in `CONTROL_WRITES_DASHBOARD` (`dashboardControls.ts`). `true` means the control edits the dashboard and a read-only mount hides it whatever the host asked. The compiler fails until both have the key.
|
||||
3. **Read** it at the render site:
|
||||
- one control: `useDashboardControl('group.item')`
|
||||
- a group: `useDashboardControlGroup('group')`, then branch on its keys
|
||||
|
||||
Hide the element when the control is off. Do not reach for `readOnly` or `isEditable` here; those decide disabled + reason, not visibility.
|
||||
4. **Dependents** (a control that is meaningless without another) go in `resolveControls`, next to the Rename/title rule, with a case in `__tests__/dashboardControls.test.ts`.
|
||||
5. **Presets** (`presets.ts`): turn it off in `EMBEDDED` when the host page owns that area, and in `CHARTS_ONLY` when a bare chart should not show it.
|
||||
6. **Check every host**: `grep -rn '<DashboardContainer' src` and confirm each mount still shows what it should.
|
||||
|
||||
## Verify
|
||||
|
||||
```bash
|
||||
pnpm exec tsc --noEmit -p tsconfig.json
|
||||
pnpm exec jest src/pages/DashboardPage/DashboardContainer/controls
|
||||
```
|
||||
|
||||
A control that compiles but is never read still renders. Grep for its id before calling the change done.
|
||||
89
frontend/.claude/skills/migrate-page-to-dashboard/SKILL.md
Normal file
89
frontend/.claude/skills/migrate-page-to-dashboard/SKILL.md
Normal file
@@ -0,0 +1,89 @@
|
||||
---
|
||||
name: migrate-page-to-dashboard
|
||||
description: Replace a page that hand-assembles charts (its own widget configs, grid, panel components) with a dashboard entity mounted through DashboardContainer. Use when a page like the cost meter breakdown or an LLM/APM overview renders a fixed set of charts, when someone asks to "make X a dashboard", "turn this page into a system dashboard", or "embed a dashboard in this page", or when a page duplicates panel code that DashboardContainer already has.
|
||||
---
|
||||
|
||||
# Migrate a page to a dashboard entity
|
||||
|
||||
The page stops owning charts. It builds or fetches one `DashboardtypesGettableDashboardV2DTO` and mounts `DashboardContainer` from `src/pages/DashboardPage/DashboardContainer` read-only, with `controls` deciding what renders. Worked example: `src/container/MeterExplorer/Breakdown` (built in the frontend) and `src/container/LLMObservability/Overview` (served by the API).
|
||||
|
||||
## 1. Pick where the dashboard comes from
|
||||
|
||||
| The panels are | Source | Example |
|
||||
| --- | --- | --- |
|
||||
| Fixed, known at build time, no per-org content | Build the DTO in the frontend, `dashboard.ts` beside the page | `Breakdown/dashboard.ts` |
|
||||
| Served by the backend as a system dashboard | `useGetSystemDashboard({ name })` | `Overview/hooks/useSystemDashboard.ts` |
|
||||
|
||||
Either way the container reads the dashboard back from react-query, never from props or Zustand (`.claude/rules/frontend-state.md`). The host passes a `DashboardQuerySource` (`{ queryKey, select }`, module-level so it is referentially stable) as `querySource`.
|
||||
|
||||
## 2. Inventory the old page
|
||||
|
||||
Before deleting anything, list what depends on it:
|
||||
|
||||
```bash
|
||||
grep -rn "<PageDir>/" src tests/e2e --include=*.ts --include=*.tsx -l
|
||||
```
|
||||
|
||||
Expect: widget config files (`graphs.ts`, `*.config.ts`), styles, unit tests, story mock data that imports the widget configs, and e2e drivers that locate sections or panels by the page's own test ids. Each one is a step below.
|
||||
|
||||
## 3. Build the DTO (frontend-built source)
|
||||
|
||||
- Describe the page as data first: sections → panels (`{ id, name, metric, unit }`), then map that to the DTO with small builders (`buildQuery`, `buildPanel`, `buildGridLayout`). Readers compare the table, not the JSON.
|
||||
- `id` is namespaced (`signoz-app:<page>`): the store keys persisted per-dashboard state on it, so it must never collide with a server id. `source: system`, `locked: true`, `schemaVersion: 'v6'`.
|
||||
- Panel ids are stable slugs (`total-log-size`); layouts reference them with `content: { $ref: '#/spec/panels/<id>' }`. Section test ids derive from the first panel id, which e2e drivers rely on (step 7).
|
||||
- Grid math uses `GRID_COLS` from `DashboardContainer/patchOps`; name the panel sizes (`TOTAL_PANEL_SIZE`), don't inline 4/6/12.
|
||||
- Units come from `UniversalYAxisUnit` (`components/YAxisUnitSelector/types`), enums from `api/generated/services/sigNoz.schemas` (alias the long names at the import).
|
||||
- Put the constant in the cache so the container can observe it:
|
||||
|
||||
```ts
|
||||
const QUERY_KEY = ['<page>-dashboard'];
|
||||
const QUERY_SOURCE: DashboardQuerySource = { queryKey: QUERY_KEY, select: identity };
|
||||
useQuery(QUERY_KEY, () => PAGE_DASHBOARD, { initialData: PAGE_DASHBOARD, staleTime: Infinity });
|
||||
```
|
||||
|
||||
For an API-served dashboard, `select` stamps a fixed `id` onto the response instead (system dashboards have none).
|
||||
|
||||
## 4. Mount it
|
||||
|
||||
```tsx
|
||||
<DashboardContainer
|
||||
dashboard={dashboard}
|
||||
refetch={noop /* or the query's refetch */}
|
||||
querySource={QUERY_SOURCE}
|
||||
readOnly
|
||||
controls={withControls(CHARTS_ONLY, { toolbar: { autoRefresh: false } })}
|
||||
/>
|
||||
```
|
||||
|
||||
- Start from a preset in `DashboardContainer/controls/presets.ts`: `EMBEDDED` keeps the panel menu and drilldown, `CHARTS_ONLY` leaves bare charts that still zoom. Override single items with `withControls`.
|
||||
- `readOnly` already hides every writing control; don't repeat that in `controls`.
|
||||
- Keep page chrome (banners, notices, date warnings) above the container in the page; nothing goes inside it. A new element that hosts might want off is a control, see the `add-dashboard-control` skill.
|
||||
- The tab title is set by `DashboardPage` only; an embedded mount never changes `document.title`.
|
||||
|
||||
## 5. Delete the old chart code
|
||||
|
||||
Widget config files, per-chart components, grid styles, and the `.styles.scss` they used. Move what survives (a notice, a banner) to a CSS module. Nothing should still import the deleted files after step 2's grep comes back empty.
|
||||
|
||||
## 6. Tests
|
||||
|
||||
Mock `pages/DashboardPage/DashboardContainer` with a stub that echoes `dashboard.id`, `readOnly` and `controls` into data attributes, then assert:
|
||||
|
||||
- the mount is read-only with the expected id;
|
||||
- the resolved controls (`resolveControls(controls, true)`) hide and show what the page intends;
|
||||
- page chrome is still there;
|
||||
- for a frontend-built DTO: every panel is placed exactly once and the section titles are in order (see `Breakdown/__tests__/BreakDown.test.tsx`).
|
||||
|
||||
## 7. Stories and e2e
|
||||
|
||||
- Story mock data that imported the old widget configs now builds its own query, or derives it from the new DTO; `query_range` handlers answer per panel.
|
||||
- Drivers under `tests/e2e/drivers/` that used the page's section test ids switch to the container's: `dashboard-section-sec-<first panel id>`; keep a comment pointing at `dashboard.ts` so the mapping stays traceable.
|
||||
|
||||
## Verify
|
||||
|
||||
```bash
|
||||
pnpm exec tsc --noEmit -p tsconfig.json
|
||||
pnpm exec jest <page dir>
|
||||
pnpm exec oxlint <page dir>
|
||||
```
|
||||
|
||||
Then open the page: panels render under the global time range, sections match the old order, and nothing from the old page is reachable by its old test id.
|
||||
@@ -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 {
|
||||
|
||||
@@ -3,18 +3,6 @@
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-8);
|
||||
padding: var(--spacing-0) var(--spacing-0);
|
||||
//TODO: remove this once we have a proper dashboard page.
|
||||
// The embedded V2 DashboardContainer renders its own page header (dashboard
|
||||
// title + share/feedback chrome) removed it for now
|
||||
:global([class*='dashboardPageHeader']),
|
||||
:global([class*='dashboardInfoWithActions']) {
|
||||
display: none;
|
||||
}
|
||||
// Embedded read-only: the add-variable and panel-action triggers are dead here.
|
||||
:global([class*='addSlot']),
|
||||
:global([data-testid^='panel-actions-']) {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.errorState {
|
||||
|
||||
@@ -3,8 +3,12 @@ import { Typography } from '@signozhq/ui/typography';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import Spinner from 'components/Spinner';
|
||||
import DashboardContainer from 'pages/DashboardPage/DashboardContainer';
|
||||
import { EMBEDDED } from 'pages/DashboardPage/DashboardContainer/controls/presets';
|
||||
|
||||
import { useSystemDashboard } from './hooks/useSystemDashboard';
|
||||
import {
|
||||
SYSTEM_DASHBOARD_SOURCE,
|
||||
useSystemDashboard,
|
||||
} from './hooks/useSystemDashboard';
|
||||
import styles from './Overview.module.scss';
|
||||
|
||||
function Overview(): JSX.Element {
|
||||
@@ -51,7 +55,9 @@ function Overview(): JSX.Element {
|
||||
<DashboardContainer
|
||||
dashboard={dashboard}
|
||||
refetch={refetch}
|
||||
canEditDashboardOverride={false}
|
||||
querySource={SYSTEM_DASHBOARD_SOURCE}
|
||||
readOnly
|
||||
controls={EMBEDDED}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,20 +1,34 @@
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { useQueryClient } from 'react-query';
|
||||
import { useCallback } from 'react';
|
||||
|
||||
import {
|
||||
getGetDashboardV2QueryKey,
|
||||
getGetSystemDashboardQueryKey,
|
||||
useGetSystemDashboard,
|
||||
} from 'api/generated/services/dashboard';
|
||||
import type { GetSystemDashboardQueryError } from 'api/generated/services/dashboard';
|
||||
import type {
|
||||
DashboardtypesGettableDashboardV2DTO,
|
||||
GetDashboardV2200,
|
||||
GetSystemDashboard200,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import type { DashboardQuerySource } from 'pages/DashboardPage/DashboardContainer/store/slices/editContextSlice';
|
||||
|
||||
const SYSTEM_DASHBOARD_NAME = 'ai-o11y-overview';
|
||||
|
||||
const DASHBOARD_ID = 'llm-observability-overview';
|
||||
|
||||
// System dashboards have no `id`; a fixed one keys the store's per-dashboard state.
|
||||
const selectDashboard = (
|
||||
response: GetSystemDashboard200,
|
||||
): DashboardtypesGettableDashboardV2DTO =>
|
||||
({
|
||||
...response.data,
|
||||
id: DASHBOARD_ID,
|
||||
}) as DashboardtypesGettableDashboardV2DTO;
|
||||
|
||||
export const SYSTEM_DASHBOARD_SOURCE: DashboardQuerySource = {
|
||||
queryKey: getGetSystemDashboardQueryKey({ name: SYSTEM_DASHBOARD_NAME }),
|
||||
select: selectDashboard,
|
||||
};
|
||||
|
||||
export interface UseSystemDashboardResult {
|
||||
dashboard: DashboardtypesGettableDashboardV2DTO | undefined;
|
||||
isLoading: boolean;
|
||||
@@ -24,30 +38,23 @@ export interface UseSystemDashboardResult {
|
||||
}
|
||||
|
||||
export function useSystemDashboard(): UseSystemDashboardResult {
|
||||
const queryClient = useQueryClient();
|
||||
const { data, isLoading, isError, error, refetch } = useGetSystemDashboard(
|
||||
const {
|
||||
data: dashboard,
|
||||
isLoading,
|
||||
isError,
|
||||
error,
|
||||
refetch,
|
||||
} = useGetSystemDashboard(
|
||||
{ name: SYSTEM_DASHBOARD_NAME },
|
||||
{ query: { staleTime: Infinity, refetchOnMount: false } },
|
||||
{
|
||||
query: {
|
||||
select: selectDashboard,
|
||||
staleTime: Infinity,
|
||||
refetchOnMount: false,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const dashboard = useMemo(
|
||||
() =>
|
||||
data
|
||||
? ({
|
||||
...data.data,
|
||||
id: DASHBOARD_ID,
|
||||
} as DashboardtypesGettableDashboardV2DTO)
|
||||
: undefined,
|
||||
[data],
|
||||
);
|
||||
|
||||
if (dashboard) {
|
||||
queryClient.setQueryData<GetDashboardV2200>(
|
||||
getGetDashboardV2QueryKey({ id: DASHBOARD_ID }),
|
||||
{ data: dashboard, status: 'success' },
|
||||
);
|
||||
}
|
||||
|
||||
const refetchDashboard = useCallback((): void => {
|
||||
void refetch();
|
||||
}, [refetch]);
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
.breakdown {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.notices {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-6);
|
||||
padding: var(--spacing-8) var(--spacing-10) 0;
|
||||
|
||||
&:empty {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
.meter-explorer-breakdown {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.meter-explorer-date-time {
|
||||
display: flex;
|
||||
min-height: 30px;
|
||||
justify-content: end;
|
||||
border-bottom: 1px solid var(--l1-border);
|
||||
padding: 10px 16px;
|
||||
}
|
||||
|
||||
.meter-explorer-graphs {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 20px;
|
||||
gap: 36px;
|
||||
|
||||
.info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.meter-column-graph {
|
||||
.row-card {
|
||||
background-color: var(--l2-background);
|
||||
padding-left: 10px;
|
||||
height: 32px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
|
||||
.section-title {
|
||||
color: var(--l2-foreground);
|
||||
font-family: Inter;
|
||||
font-size: 14px;
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
line-height: 20px;
|
||||
letter-spacing: -0.07px;
|
||||
}
|
||||
}
|
||||
|
||||
.graph-description {
|
||||
padding: 10px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.meter-page-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
.meter-graph {
|
||||
height: 400px;
|
||||
padding: 10px;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.total {
|
||||
.meter-column-graph {
|
||||
.meter-page-grid {
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
|
||||
.meter-graph {
|
||||
height: 200px;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,131 +1,37 @@
|
||||
import { useCallback } from 'react';
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { useDispatch, useSelector } from 'react-redux';
|
||||
import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
import { navigate } from 'lib/router/navigation';
|
||||
import { useSelector } from 'react-redux';
|
||||
import { Alert } from 'antd';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import getLocalStorageApi from 'api/browser/localstorage/get';
|
||||
import setLocalStorageApi from 'api/browser/localstorage/set';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import GridCard from 'container/WidgetCard/Card';
|
||||
import { Card, CardContainer } from 'container/WidgetCard/styles';
|
||||
import DateTimeSelectionV2 from 'container/TopNav/DateTimeSelectionV2';
|
||||
import dayjs from 'dayjs';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import { UpdateTimeInterval } from 'store/actions';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { Widgets } from 'types/api/widgets/widget';
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
|
||||
import { identity, noop } from 'lodash-es';
|
||||
import DashboardContainer from 'pages/DashboardPage/DashboardContainer';
|
||||
import {
|
||||
getLogCountWidgetData,
|
||||
getLogSizeWidgetData,
|
||||
getMetricCountWidgetData,
|
||||
getSpanCountWidgetData,
|
||||
getSpanSizeWidgetData,
|
||||
getTotalLogSizeWidgetData,
|
||||
getTotalMetricDatapointCountWidgetData,
|
||||
getTotalTraceSizeWidgetData,
|
||||
} from './graphs';
|
||||
CHARTS_ONLY,
|
||||
withControls,
|
||||
} from 'pages/DashboardPage/DashboardContainer/controls/presets';
|
||||
import type { DashboardQuerySource } from 'pages/DashboardPage/DashboardContainer/store/slices/editContextSlice';
|
||||
import { useQuery } from 'react-query';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
|
||||
import './BreakDown.styles.scss';
|
||||
import { COST_METER_DASHBOARD } from './dashboard';
|
||||
|
||||
type MetricSection = {
|
||||
id: string;
|
||||
title: string;
|
||||
graphs: Widgets[];
|
||||
import styles from './BreakDown.module.scss';
|
||||
|
||||
const CONTROLS = withControls(CHARTS_ONLY, {
|
||||
toolbar: { autoRefresh: false },
|
||||
});
|
||||
|
||||
// Built in the frontend, never fetched: the container reads it back from this cache entry.
|
||||
const QUERY_KEY = ['cost-meter-breakdown-dashboard'];
|
||||
const QUERY_SOURCE: DashboardQuerySource = {
|
||||
queryKey: QUERY_KEY,
|
||||
select: identity,
|
||||
};
|
||||
|
||||
const sections: MetricSection[] = [
|
||||
{
|
||||
id: uuid(),
|
||||
title: 'Total',
|
||||
graphs: [
|
||||
getTotalLogSizeWidgetData(),
|
||||
getTotalTraceSizeWidgetData(),
|
||||
getTotalMetricDatapointCountWidgetData(),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: uuid(),
|
||||
title: 'Logs',
|
||||
graphs: [getLogCountWidgetData(), getLogSizeWidgetData()],
|
||||
},
|
||||
{
|
||||
id: uuid(),
|
||||
title: 'Traces',
|
||||
graphs: [getSpanCountWidgetData(), getSpanSizeWidgetData()],
|
||||
},
|
||||
{
|
||||
id: uuid(),
|
||||
title: 'Metrics',
|
||||
graphs: [getMetricCountWidgetData()],
|
||||
},
|
||||
];
|
||||
|
||||
function Section(section: MetricSection): JSX.Element {
|
||||
const isDarkMode = useIsDarkMode();
|
||||
const { title, graphs } = section;
|
||||
const { pathname } = useAppLocation();
|
||||
const dispatch = useDispatch();
|
||||
const urlQuery = useUrlQuery();
|
||||
|
||||
const onDragSelect = useCallback(
|
||||
(start: number, end: number) => {
|
||||
const startTimestamp = Math.trunc(start);
|
||||
const endTimestamp = Math.trunc(end);
|
||||
|
||||
urlQuery.set(QueryParams.startTime, startTimestamp.toString());
|
||||
urlQuery.set(QueryParams.endTime, endTimestamp.toString());
|
||||
const generatedUrl = `${pathname}?${urlQuery.toString()}`;
|
||||
navigate(generatedUrl);
|
||||
|
||||
if (startTimestamp !== endTimestamp) {
|
||||
dispatch(UpdateTimeInterval('custom', [startTimestamp, endTimestamp]));
|
||||
}
|
||||
},
|
||||
[dispatch, pathname, urlQuery],
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="meter-column-graph"
|
||||
data-testid={`meter-breakdown-section-${title.toLowerCase()}`}
|
||||
>
|
||||
<CardContainer className="row-card" isDarkMode={isDarkMode}>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="medium"
|
||||
color="secondary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
{title}
|
||||
</Typography>
|
||||
</CardContainer>
|
||||
<div className="meter-page-grid">
|
||||
{graphs.map((widget) => (
|
||||
<Card
|
||||
key={widget?.id}
|
||||
isDarkMode={isDarkMode}
|
||||
$panelType={PANEL_TYPES.BAR}
|
||||
className="meter-graph"
|
||||
>
|
||||
<GridCard widget={widget} onDragSelect={onDragSelect} />
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BreakDown(): JSX.Element {
|
||||
const { isCloudUser } = useGetTenantLicense();
|
||||
const { maxTime, minTime } = useSelector<AppState, GlobalReducer>(
|
||||
@@ -140,14 +46,17 @@ function BreakDown(): JSX.Element {
|
||||
};
|
||||
const showShortRangeWarning = (maxTime - minTime) / 1e6 < 61 * 60 * 1000;
|
||||
|
||||
useQuery(QUERY_KEY, () => COST_METER_DASHBOARD, {
|
||||
initialData: COST_METER_DASHBOARD,
|
||||
staleTime: Infinity,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="meter-explorer-breakdown">
|
||||
<section className="meter-explorer-date-time">
|
||||
<DateTimeSelectionV2 showAutoRefresh={false} />
|
||||
</section>
|
||||
<section className="meter-explorer-graphs">
|
||||
<div className={styles.breakdown}>
|
||||
<section className={styles.notices}>
|
||||
{showInfo && (
|
||||
<Alert
|
||||
data-testid="cost-meter-utc-notice"
|
||||
type="info"
|
||||
showIcon
|
||||
closable
|
||||
@@ -188,28 +97,14 @@ function BreakDown(): JSX.Element {
|
||||
}
|
||||
/>
|
||||
)}
|
||||
<section className="total">
|
||||
<Section
|
||||
id={sections[0].id}
|
||||
title={sections[0].title}
|
||||
graphs={sections[0].graphs}
|
||||
/>
|
||||
</section>
|
||||
{sections.map((section, idx) => {
|
||||
if (idx === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
return (
|
||||
<Section
|
||||
key={section.id}
|
||||
id={section.id}
|
||||
title={section.title}
|
||||
graphs={section.graphs}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</section>
|
||||
<DashboardContainer
|
||||
dashboard={COST_METER_DASHBOARD}
|
||||
refetch={noop}
|
||||
querySource={QUERY_SOURCE}
|
||||
readOnly
|
||||
controls={CONTROLS}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import type { DashboardControlsInput } from 'pages/DashboardPage/DashboardContainer/controls/types';
|
||||
import { resolveControls } from 'pages/DashboardPage/DashboardContainer/controls/dashboardControls';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import BreakDown from '../BreakDown';
|
||||
import { COST_METER_DASHBOARD, COST_METER_DASHBOARD_ID } from '../dashboard';
|
||||
|
||||
jest.mock('pages/DashboardPage/DashboardContainer', () => ({
|
||||
__esModule: true,
|
||||
default: ({
|
||||
dashboard,
|
||||
readOnly,
|
||||
controls,
|
||||
}: {
|
||||
dashboard: DashboardtypesGettableDashboardV2DTO;
|
||||
readOnly: boolean;
|
||||
controls: DashboardControlsInput;
|
||||
}): JSX.Element => (
|
||||
<div
|
||||
data-testid="dashboard-container"
|
||||
data-dashboard-id={dashboard.id}
|
||||
data-read-only={String(readOnly)}
|
||||
data-controls={JSON.stringify(controls)}
|
||||
/>
|
||||
),
|
||||
}));
|
||||
|
||||
describe('Cost meter breakdown', () => {
|
||||
it('mounts the assembled dashboard read-only as charts only, without auto-refresh', () => {
|
||||
render(<BreakDown />);
|
||||
|
||||
const dashboard = screen.getByTestId('dashboard-container');
|
||||
expect(dashboard).toHaveAttribute(
|
||||
'data-dashboard-id',
|
||||
COST_METER_DASHBOARD_ID,
|
||||
);
|
||||
expect(dashboard).toHaveAttribute('data-read-only', 'true');
|
||||
const controls = resolveControls(
|
||||
JSON.parse(dashboard.getAttribute('data-controls') ?? ''),
|
||||
true,
|
||||
);
|
||||
expect(controls.header.breadcrumbs).toBe(false);
|
||||
expect(controls.panelActions.createAlert).toBe(false);
|
||||
expect(controls.panelActions.drilldown).toBe(false);
|
||||
expect(controls.panelActions.zoom).toBe(true);
|
||||
expect(controls.toolbar.autoRefresh).toBe(false);
|
||||
expect(controls.toolbar.timeRange).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps the UTC billing notice above the dashboard', () => {
|
||||
render(<BreakDown />);
|
||||
|
||||
expect(screen.getByTestId('cost-meter-utc-notice')).toHaveTextContent(
|
||||
'Billing is calculated in UTC',
|
||||
);
|
||||
});
|
||||
|
||||
it('places every panel exactly once, in its section', () => {
|
||||
const placed = COST_METER_DASHBOARD.spec.layouts.flatMap((layout) =>
|
||||
(layout.spec.items ?? []).map((item) =>
|
||||
item.content?.$ref?.replace('#/spec/panels/', ''),
|
||||
),
|
||||
);
|
||||
|
||||
const panelIds = Object.keys(COST_METER_DASHBOARD.spec.panels);
|
||||
expect(placed).toHaveLength(panelIds.length);
|
||||
expect(new Set(placed)).toStrictEqual(new Set(panelIds));
|
||||
expect(
|
||||
COST_METER_DASHBOARD.spec.layouts.map(
|
||||
(layout) => layout.spec.display?.title,
|
||||
),
|
||||
).toStrictEqual(['Total', 'Logs', 'Traces', 'Metrics']);
|
||||
});
|
||||
});
|
||||
222
frontend/src/container/MeterExplorer/Breakdown/dashboard.ts
Normal file
222
frontend/src/container/MeterExplorer/Breakdown/dashboard.ts
Normal file
@@ -0,0 +1,222 @@
|
||||
import {
|
||||
DashboardtypesLayoutEnvelopeGithubComPersesSpecGoDashboardGridLayoutSpecDTOKind as GridKind,
|
||||
DashboardtypesPanelKindDTO as PanelKind,
|
||||
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpecDTOKind as BarChartKind,
|
||||
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesNumberPanelSpecDTOKind as NumberKind,
|
||||
DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBuilderQuerySpecDTOKind as BuilderQueryKind,
|
||||
DashboardtypesSourceDTO,
|
||||
DashboardtypesTimePreferenceDTO,
|
||||
MetrictypesSpaceAggregationDTO,
|
||||
MetrictypesTimeAggregationDTO,
|
||||
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTOSignal as MetricSignal,
|
||||
Querybuildertypesv5ReduceToDTO,
|
||||
Querybuildertypesv5RequestTypeDTO as RequestType,
|
||||
TelemetrytypesSourceDTO,
|
||||
type DashboardtypesGettableDashboardV2DTO,
|
||||
type DashboardtypesLayoutDTO,
|
||||
type DashboardtypesPanelDTO,
|
||||
type DashboardtypesQueryDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { UniversalYAxisUnit } from 'components/YAxisUnitSelector/types';
|
||||
import { GRID_COLS } from 'pages/DashboardPage/DashboardContainer/patchOps';
|
||||
|
||||
/** Namespaced: persisted per-dashboard state keys on it, so it must never match a server id. */
|
||||
export const COST_METER_DASHBOARD_ID = 'signoz-app:cost-meter-breakdown';
|
||||
|
||||
const BYTES = UniversalYAxisUnit.BYTES_IEC;
|
||||
const COUNT = UniversalYAxisUnit.MISC_SHORT;
|
||||
|
||||
const TOTAL_PANEL_SIZE = { width: 4, height: 3 };
|
||||
const HOURLY_PANEL_SIZE = { width: 6, height: 6 };
|
||||
|
||||
interface MeterPanel {
|
||||
id: string;
|
||||
name: string;
|
||||
metric: string;
|
||||
unit: typeof BYTES | typeof COUNT;
|
||||
}
|
||||
|
||||
interface MeterSection {
|
||||
title: string;
|
||||
/** Window totals as numbers; otherwise hourly bars. */
|
||||
isTotal?: boolean;
|
||||
panels: MeterPanel[];
|
||||
}
|
||||
|
||||
const SECTIONS: MeterSection[] = [
|
||||
{
|
||||
title: 'Total',
|
||||
isTotal: true,
|
||||
panels: [
|
||||
{
|
||||
id: 'total-log-size',
|
||||
name: 'Total size of log records ingested',
|
||||
metric: 'signoz.meter.log.size',
|
||||
unit: BYTES,
|
||||
},
|
||||
{
|
||||
id: 'total-span-size',
|
||||
name: 'Total size of spans ingested',
|
||||
metric: 'signoz.meter.span.size',
|
||||
unit: BYTES,
|
||||
},
|
||||
{
|
||||
id: 'total-metric-datapoints',
|
||||
name: 'Total metric datapoints ingested',
|
||||
metric: 'signoz.meter.metric.datapoint.count',
|
||||
unit: COUNT,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Logs',
|
||||
panels: [
|
||||
{
|
||||
id: 'log-count',
|
||||
name: 'Count of log records ingested',
|
||||
metric: 'signoz.meter.log.count',
|
||||
unit: COUNT,
|
||||
},
|
||||
{
|
||||
id: 'log-size',
|
||||
name: 'Size of log records ingested',
|
||||
metric: 'signoz.meter.log.size',
|
||||
unit: BYTES,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Traces',
|
||||
panels: [
|
||||
{
|
||||
id: 'span-count',
|
||||
name: 'Count of spans ingested',
|
||||
metric: 'signoz.meter.span.count',
|
||||
unit: COUNT,
|
||||
},
|
||||
{
|
||||
id: 'span-size',
|
||||
name: 'Size of spans ingested',
|
||||
metric: 'signoz.meter.span.size',
|
||||
unit: BYTES,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Metrics',
|
||||
panels: [
|
||||
{
|
||||
id: 'metric-datapoints',
|
||||
name: 'Count of metric datapoints ingested',
|
||||
metric: 'signoz.meter.metric.datapoint.count',
|
||||
unit: COUNT,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const buildMeterQuery = (
|
||||
{ metric, unit }: MeterPanel,
|
||||
kind: RequestType,
|
||||
): DashboardtypesQueryDTO => ({
|
||||
kind,
|
||||
spec: {
|
||||
plugin: {
|
||||
kind: BuilderQueryKind['signoz/BuilderQuery'],
|
||||
spec: {
|
||||
name: 'A',
|
||||
signal: MetricSignal.metrics,
|
||||
source: TelemetrytypesSourceDTO.meter,
|
||||
aggregations: [
|
||||
{
|
||||
metricName: metric,
|
||||
timeAggregation: MetrictypesTimeAggregationDTO.increase,
|
||||
spaceAggregation: MetrictypesSpaceAggregationDTO.sum,
|
||||
reduceTo: Querybuildertypesv5ReduceToDTO.sum,
|
||||
},
|
||||
],
|
||||
legend: unit === BYTES ? 'size' : 'count',
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const buildMeterPanel = (
|
||||
panel: MeterPanel,
|
||||
isTotal: boolean,
|
||||
): DashboardtypesPanelDTO => ({
|
||||
kind: PanelKind.Panel,
|
||||
spec: {
|
||||
display: { name: panel.name },
|
||||
plugin: isTotal
|
||||
? {
|
||||
kind: NumberKind['signoz/NumberPanel'],
|
||||
spec: {
|
||||
formatting: { unit: panel.unit },
|
||||
visualization: {
|
||||
timePreference: DashboardtypesTimePreferenceDTO.global_time,
|
||||
},
|
||||
},
|
||||
}
|
||||
: {
|
||||
kind: BarChartKind['signoz/BarChartPanel'],
|
||||
spec: {
|
||||
formatting: { unit: panel.unit },
|
||||
visualization: { stackedBarChart: false },
|
||||
},
|
||||
},
|
||||
queries: [
|
||||
buildMeterQuery(
|
||||
panel,
|
||||
isTotal ? RequestType.scalar : RequestType.time_series,
|
||||
),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const buildGridLayout = ({
|
||||
title,
|
||||
isTotal,
|
||||
panels,
|
||||
}: MeterSection): DashboardtypesLayoutDTO => {
|
||||
const { width, height } = isTotal ? TOTAL_PANEL_SIZE : HOURLY_PANEL_SIZE;
|
||||
const perRow = GRID_COLS / width;
|
||||
|
||||
return {
|
||||
kind: GridKind.Grid,
|
||||
spec: {
|
||||
display: { title },
|
||||
items: panels.map((panel, index) => ({
|
||||
x: (index % perRow) * width,
|
||||
y: Math.floor(index / perRow) * height,
|
||||
width,
|
||||
height,
|
||||
content: { $ref: `#/spec/panels/${panel.id}` },
|
||||
})),
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const COST_METER_DASHBOARD: DashboardtypesGettableDashboardV2DTO = {
|
||||
id: COST_METER_DASHBOARD_ID,
|
||||
orgId: '',
|
||||
name: 'cost-meter-breakdown',
|
||||
schemaVersion: 'v6',
|
||||
source: DashboardtypesSourceDTO.system,
|
||||
locked: true,
|
||||
tags: [],
|
||||
spec: {
|
||||
display: {
|
||||
name: 'Cost Meter Breakdown',
|
||||
description:
|
||||
'Logs, spans and metric datapoints ingested, from the signoz.meter.* metrics. Aggregated hourly; billing is calculated in UTC.',
|
||||
},
|
||||
variables: [],
|
||||
layouts: SECTIONS.map(buildGridLayout),
|
||||
panels: Object.fromEntries(
|
||||
SECTIONS.flatMap(({ isTotal = false, panels }) =>
|
||||
panels.map((panel) => [panel.id, buildMeterPanel(panel, isTotal)]),
|
||||
),
|
||||
),
|
||||
},
|
||||
};
|
||||
@@ -1,374 +0,0 @@
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { GetWidgetQueryBuilderProps } from 'container/MetricsApplication/types';
|
||||
import { Widgets } from 'types/api/widgets/widget';
|
||||
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import {
|
||||
IBuilderFormula,
|
||||
IBuilderQuery,
|
||||
} from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
|
||||
interface GetWidgetQueryProps {
|
||||
title: string;
|
||||
description: string;
|
||||
queryData: IBuilderQuery[];
|
||||
queryFormulas?: IBuilderFormula[];
|
||||
panelTypes?: PANEL_TYPES;
|
||||
yAxisUnit?: string;
|
||||
columnUnits?: Record<string, string>;
|
||||
}
|
||||
|
||||
interface GetWidgetQueryPropsReturn extends GetWidgetQueryBuilderProps {
|
||||
description?: string;
|
||||
nullZeroValues: string;
|
||||
columnUnits?: Record<string, string>;
|
||||
}
|
||||
|
||||
export const getWidgetQueryBuilder = ({
|
||||
query,
|
||||
title = '',
|
||||
panelTypes,
|
||||
yAxisUnit = '',
|
||||
fillSpans = false,
|
||||
id,
|
||||
nullZeroValues,
|
||||
description,
|
||||
}: GetWidgetQueryPropsReturn): Widgets => ({
|
||||
description: description || '',
|
||||
id: id || uuid(),
|
||||
nullZeroValues: nullZeroValues || '',
|
||||
opacity: '1',
|
||||
panelTypes,
|
||||
query,
|
||||
timePreferance: 'GLOBAL_TIME',
|
||||
title,
|
||||
yAxisUnit,
|
||||
softMax: null,
|
||||
softMin: null,
|
||||
selectedLogFields: [],
|
||||
selectedTracesFields: [],
|
||||
fillSpans,
|
||||
});
|
||||
|
||||
export function getWidgetQuery(
|
||||
props: GetWidgetQueryProps,
|
||||
): GetWidgetQueryPropsReturn {
|
||||
const { title, description, panelTypes, yAxisUnit, columnUnits } = props;
|
||||
return {
|
||||
title,
|
||||
yAxisUnit: yAxisUnit || 'none',
|
||||
panelTypes: panelTypes || PANEL_TYPES.TIME_SERIES,
|
||||
fillSpans: false,
|
||||
description,
|
||||
nullZeroValues: 'zero',
|
||||
columnUnits,
|
||||
query: {
|
||||
queryType: EQueryType.QUERY_BUILDER,
|
||||
promql: [],
|
||||
builder: {
|
||||
queryData: props.queryData,
|
||||
queryFormulas: (props.queryFormulas as IBuilderFormula[]) || [],
|
||||
queryTraceOperator: [],
|
||||
},
|
||||
clickhouse_sql: [],
|
||||
id: uuid(),
|
||||
},
|
||||
};
|
||||
}
|
||||
export const getTotalLogSizeWidgetData = (): Widgets =>
|
||||
getWidgetQueryBuilder(
|
||||
getWidgetQuery({
|
||||
queryData: [
|
||||
{
|
||||
aggregateAttribute: {
|
||||
dataType: DataTypes.Float64,
|
||||
key: 'signoz.meter.log.size',
|
||||
id: 'signoz.meter.log.size--float64--Sum--true',
|
||||
type: 'Sum',
|
||||
},
|
||||
aggregateOperator: 'increase',
|
||||
dataSource: DataSource.METRICS,
|
||||
source: 'meter',
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: { items: [], op: 'AND' },
|
||||
functions: [],
|
||||
groupBy: [],
|
||||
having: [],
|
||||
legend: 'count',
|
||||
limit: null,
|
||||
orderBy: [],
|
||||
queryName: 'A',
|
||||
reduceTo: ReduceOperators.SUM,
|
||||
spaceAggregation: 'sum',
|
||||
stepInterval: null,
|
||||
timeAggregation: 'increase',
|
||||
},
|
||||
],
|
||||
title: 'Total size of log records ingested',
|
||||
description: '',
|
||||
panelTypes: PANEL_TYPES.VALUE,
|
||||
yAxisUnit: 'bytes',
|
||||
}),
|
||||
);
|
||||
|
||||
export const getTotalTraceSizeWidgetData = (): Widgets =>
|
||||
getWidgetQueryBuilder(
|
||||
getWidgetQuery({
|
||||
queryData: [
|
||||
{
|
||||
aggregateAttribute: {
|
||||
dataType: DataTypes.Float64,
|
||||
key: 'signoz.meter.span.size',
|
||||
id: 'signoz.meter.span.size--float64--Sum--true',
|
||||
type: 'Sum',
|
||||
},
|
||||
aggregateOperator: 'increase',
|
||||
dataSource: DataSource.METRICS,
|
||||
source: 'meter',
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: { items: [], op: 'AND' },
|
||||
functions: [],
|
||||
groupBy: [],
|
||||
having: [],
|
||||
legend: 'count',
|
||||
limit: null,
|
||||
orderBy: [],
|
||||
queryName: 'A',
|
||||
reduceTo: ReduceOperators.SUM,
|
||||
spaceAggregation: 'sum',
|
||||
stepInterval: null,
|
||||
timeAggregation: 'increase',
|
||||
},
|
||||
],
|
||||
title: 'Total size of spans ingested',
|
||||
description: '',
|
||||
panelTypes: PANEL_TYPES.VALUE,
|
||||
yAxisUnit: 'bytes',
|
||||
}),
|
||||
);
|
||||
|
||||
export const getTotalMetricDatapointCountWidgetData = (): Widgets =>
|
||||
getWidgetQueryBuilder(
|
||||
getWidgetQuery({
|
||||
queryData: [
|
||||
{
|
||||
aggregateAttribute: {
|
||||
dataType: DataTypes.Float64,
|
||||
key: 'signoz.meter.metric.datapoint.count',
|
||||
id: 'signoz.meter.metric.datapoint.count--float64--Sum--true',
|
||||
type: 'Sum',
|
||||
},
|
||||
aggregateOperator: 'increase',
|
||||
dataSource: DataSource.METRICS,
|
||||
source: 'meter',
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: { items: [], op: 'AND' },
|
||||
functions: [],
|
||||
groupBy: [],
|
||||
having: [],
|
||||
legend: 'count',
|
||||
limit: null,
|
||||
orderBy: [],
|
||||
queryName: 'A',
|
||||
reduceTo: ReduceOperators.SUM,
|
||||
spaceAggregation: 'sum',
|
||||
stepInterval: null,
|
||||
timeAggregation: 'increase',
|
||||
},
|
||||
],
|
||||
title: 'Total metric datapoints ingested',
|
||||
description: '',
|
||||
panelTypes: PANEL_TYPES.VALUE,
|
||||
yAxisUnit: 'short',
|
||||
}),
|
||||
);
|
||||
|
||||
export const getLogCountWidgetData = (): Widgets =>
|
||||
getWidgetQueryBuilder(
|
||||
getWidgetQuery({
|
||||
queryData: [
|
||||
{
|
||||
aggregateAttribute: {
|
||||
dataType: DataTypes.Float64,
|
||||
key: 'signoz.meter.log.count',
|
||||
id: 'signoz.meter.log.count--float64--Sum--true',
|
||||
type: 'Sum',
|
||||
},
|
||||
aggregateOperator: 'increase',
|
||||
dataSource: DataSource.METRICS,
|
||||
source: 'meter',
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: { items: [], op: 'AND' },
|
||||
functions: [],
|
||||
groupBy: [],
|
||||
having: [],
|
||||
legend: 'count',
|
||||
limit: null,
|
||||
orderBy: [],
|
||||
queryName: 'A',
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
spaceAggregation: 'sum',
|
||||
stepInterval: null,
|
||||
timeAggregation: 'increase',
|
||||
},
|
||||
],
|
||||
title: 'Count of log records ingested',
|
||||
description: '',
|
||||
panelTypes: PANEL_TYPES.BAR,
|
||||
yAxisUnit: 'short',
|
||||
}),
|
||||
);
|
||||
|
||||
export const getLogSizeWidgetData = (): Widgets =>
|
||||
getWidgetQueryBuilder(
|
||||
getWidgetQuery({
|
||||
queryData: [
|
||||
{
|
||||
aggregateAttribute: {
|
||||
dataType: DataTypes.Float64,
|
||||
key: 'signoz.meter.log.size',
|
||||
id: 'signoz.meter.log.size--float64--Sum--true',
|
||||
type: 'Sum',
|
||||
},
|
||||
aggregateOperator: 'increase',
|
||||
dataSource: DataSource.METRICS,
|
||||
source: 'meter',
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: { items: [], op: 'AND' },
|
||||
functions: [],
|
||||
groupBy: [],
|
||||
having: [],
|
||||
legend: 'size',
|
||||
limit: null,
|
||||
orderBy: [],
|
||||
queryName: 'A',
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
spaceAggregation: 'sum',
|
||||
stepInterval: null,
|
||||
timeAggregation: 'increase',
|
||||
},
|
||||
],
|
||||
title: 'Size of log records ingested',
|
||||
description: '',
|
||||
panelTypes: PANEL_TYPES.BAR,
|
||||
yAxisUnit: 'bytes',
|
||||
}),
|
||||
);
|
||||
|
||||
export const getSpanCountWidgetData = (): Widgets =>
|
||||
getWidgetQueryBuilder(
|
||||
getWidgetQuery({
|
||||
queryData: [
|
||||
{
|
||||
aggregateAttribute: {
|
||||
dataType: DataTypes.Float64,
|
||||
key: 'signoz.meter.span.count',
|
||||
id: 'signoz.meter.span.count--float64--Sum--true',
|
||||
type: 'Sum',
|
||||
},
|
||||
aggregateOperator: 'increase',
|
||||
dataSource: DataSource.METRICS,
|
||||
source: 'meter',
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: { items: [], op: 'AND' },
|
||||
functions: [],
|
||||
groupBy: [],
|
||||
having: [],
|
||||
legend: 'count',
|
||||
limit: null,
|
||||
orderBy: [],
|
||||
queryName: 'A',
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
spaceAggregation: 'sum',
|
||||
stepInterval: null,
|
||||
timeAggregation: 'increase',
|
||||
},
|
||||
],
|
||||
title: 'Count of spans ingested',
|
||||
description: '',
|
||||
panelTypes: PANEL_TYPES.BAR,
|
||||
yAxisUnit: 'short',
|
||||
}),
|
||||
);
|
||||
|
||||
export const getSpanSizeWidgetData = (): Widgets =>
|
||||
getWidgetQueryBuilder(
|
||||
getWidgetQuery({
|
||||
queryData: [
|
||||
{
|
||||
aggregateAttribute: {
|
||||
dataType: DataTypes.Float64,
|
||||
key: 'signoz.meter.span.size',
|
||||
id: 'signoz.meter.span.size--float64--Sum--true',
|
||||
type: 'Sum',
|
||||
},
|
||||
aggregateOperator: 'increase',
|
||||
dataSource: DataSource.METRICS,
|
||||
source: 'meter',
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: { items: [], op: 'AND' },
|
||||
functions: [],
|
||||
groupBy: [],
|
||||
having: [],
|
||||
legend: 'size',
|
||||
limit: null,
|
||||
orderBy: [],
|
||||
queryName: 'A',
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
spaceAggregation: 'sum',
|
||||
stepInterval: null,
|
||||
timeAggregation: 'increase',
|
||||
},
|
||||
],
|
||||
title: 'Size of spans ingested',
|
||||
description: '',
|
||||
panelTypes: PANEL_TYPES.BAR,
|
||||
yAxisUnit: 'bytes',
|
||||
}),
|
||||
);
|
||||
|
||||
export const getMetricCountWidgetData = (): Widgets =>
|
||||
getWidgetQueryBuilder(
|
||||
getWidgetQuery({
|
||||
queryData: [
|
||||
{
|
||||
aggregateAttribute: {
|
||||
dataType: DataTypes.Float64,
|
||||
key: 'signoz.meter.metric.datapoint.count',
|
||||
id: 'signoz.meter.metric.datapoint.count--float64--Sum--true',
|
||||
type: 'Sum',
|
||||
},
|
||||
aggregateOperator: 'increase',
|
||||
dataSource: DataSource.METRICS,
|
||||
source: 'meter',
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: { items: [], op: 'AND' },
|
||||
functions: [],
|
||||
groupBy: [],
|
||||
having: [],
|
||||
legend: 'count',
|
||||
limit: null,
|
||||
orderBy: [],
|
||||
queryName: 'A',
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
spaceAggregation: 'sum',
|
||||
stepInterval: null,
|
||||
timeAggregation: 'increase',
|
||||
},
|
||||
],
|
||||
title: 'Count of metric datapoints ingested',
|
||||
description: '',
|
||||
panelTypes: PANEL_TYPES.BAR,
|
||||
yAxisUnit: 'short',
|
||||
}),
|
||||
);
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { FullScreenHandle } from 'react-full-screen';
|
||||
import { buildRoutePath } from 'lib/router/buildRoutePath';
|
||||
import {
|
||||
@@ -26,19 +26,21 @@ import { useErrorModal } from 'providers/ErrorModalProvider';
|
||||
import APIError from 'types/api/error';
|
||||
|
||||
import AuthZDropdown from 'lib/authz/components/AuthZDropdown/AuthZDropdown';
|
||||
import type { AuthZDropdownItemType } from 'lib/authz/components/AuthZDropdown/types';
|
||||
import type {
|
||||
AuthZDropdownItemType,
|
||||
AuthZGroupChildType,
|
||||
} from 'lib/authz/components/AuthZDropdown/types';
|
||||
import { blockedBy } from 'lib/authz/components/AuthZDropdown/utils';
|
||||
import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';
|
||||
import { DashboardCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/dashboard.permissions';
|
||||
import DashboardSettings from '../../DashboardSettings';
|
||||
import { useAddSection } from '../../PanelsAndSectionsLayout/Section/hooks/useAddSection';
|
||||
import SectionTitleModal from '../../PanelsAndSectionsLayout/Section/SectionTitleModal';
|
||||
import JsonEditorDrawer from '../JsonEditorDrawer/JsonEditorDrawer';
|
||||
import SettingsDrawer from '../SettingsDrawer';
|
||||
import styles from './DashboardActions.module.scss';
|
||||
import { useDeleteDashboardAction } from './useDeleteDashboardAction';
|
||||
import { useDashboardStore } from '../../store/useDashboardStore';
|
||||
import { useDashboardEditContext } from '../../hooks/useDashboardEditContext';
|
||||
import { useDashboardControlGroup } from '../../controls/useDashboardControlGroup';
|
||||
|
||||
interface DashboardActionsProps {
|
||||
title: string;
|
||||
@@ -66,13 +68,14 @@ function DashboardActions({
|
||||
deleteChecks,
|
||||
deleteDisabledTooltip,
|
||||
} = useDashboardEditContext();
|
||||
const settingsRequest = useDashboardStore((s) => s.settingsRequest);
|
||||
const clearSettingsRequest = useDashboardStore((s) => s.clearSettingsRequest);
|
||||
const actionControls = useDashboardControlGroup('dashboardActions');
|
||||
const requestSettings = useDashboardStore((s) => s.requestSettings);
|
||||
const { safeNavigate } = useSafeNavigate();
|
||||
const { showErrorModal } = useErrorModal();
|
||||
const { disabledTooltip: lockDisabledTooltip } = useDashboardLockPermission({
|
||||
dashboardId: dashboard.id,
|
||||
source: dashboard.source,
|
||||
enabled: actionControls.lock,
|
||||
});
|
||||
|
||||
// Cloning creates a new dashboard, so it needs `create` too, and no lock gate.
|
||||
@@ -81,8 +84,6 @@ function DashboardActions({
|
||||
[editChecks],
|
||||
);
|
||||
|
||||
const [isSettingsDrawerOpen, setIsSettingsDrawerOpen] =
|
||||
useState<boolean>(false);
|
||||
const [isJsonEditorOpen, setIsJsonEditorOpen] = useState<boolean>(false);
|
||||
const [isCloning, setIsCloning] = useState<boolean>(false);
|
||||
const [isNewSectionOpen, setIsNewSectionOpen] = useState<boolean>(false);
|
||||
@@ -94,14 +95,6 @@ function DashboardActions({
|
||||
panelCount: Object.keys(dashboard.spec.panels).length,
|
||||
});
|
||||
|
||||
// Open the settings drawer when something in the tree requests it (e.g. the
|
||||
// variables bar's "Add variable" button).
|
||||
useEffect(() => {
|
||||
if (settingsRequest) {
|
||||
setIsSettingsDrawerOpen(true);
|
||||
}
|
||||
}, [settingsRequest]);
|
||||
|
||||
const { addSection, isSaving: isAddingSection } = useAddSection({
|
||||
layouts: dashboard.spec.layouts,
|
||||
});
|
||||
@@ -143,8 +136,8 @@ function DashboardActions({
|
||||
void logEvent(DashboardDetailEvents.SettingsOpened, {
|
||||
dashboardId: dashboard.id,
|
||||
});
|
||||
setIsSettingsDrawerOpen(true);
|
||||
}, [dashboard.id]);
|
||||
requestSettings({ tab: 'Overview' });
|
||||
}, [dashboard.id, requestSettings]);
|
||||
|
||||
const handleOpenJsonEditor = useCallback((): void => {
|
||||
void logEvent(DashboardDetailEvents.JsonEditorOpened, {
|
||||
@@ -162,166 +155,183 @@ function DashboardActions({
|
||||
void handle.enter();
|
||||
}, [dashboard.id, handle]);
|
||||
|
||||
// Unavailable items stay in the menu, carrying the reason.
|
||||
const menuItems = useMemo<AuthZDropdownItemType[]>(
|
||||
() => [
|
||||
{
|
||||
// Unavailable items stay in the menu, carrying the reason; hidden ones are dropped.
|
||||
const menuItems = useMemo<AuthZDropdownItemType[]>(() => {
|
||||
const dashboardItems: AuthZGroupChildType[] = [];
|
||||
if (actionControls.rename) {
|
||||
dashboardItems.push({
|
||||
type: 'item',
|
||||
value: 'rename',
|
||||
testId: 'dashboard-action-rename',
|
||||
label: 'Rename',
|
||||
prefix: <PenLine size={14} />,
|
||||
checks: editChecks,
|
||||
...blockedBy(editDisabledTooltip),
|
||||
onClick: onOpenRename,
|
||||
});
|
||||
}
|
||||
// Clone creates a new dashboard, so it's not lock-gated.
|
||||
if (actionControls.clone) {
|
||||
dashboardItems.push({
|
||||
type: 'item',
|
||||
value: 'clone',
|
||||
testId: 'dashboard-action-clone',
|
||||
label: 'Clone dashboard',
|
||||
prefix: <Copy size={14} />,
|
||||
checks: cloneChecks,
|
||||
loading: isCloning,
|
||||
loadingTooltip: 'Cloning dashboard',
|
||||
onClick: (): void => void handleClone(),
|
||||
});
|
||||
}
|
||||
if (actionControls.lock) {
|
||||
dashboardItems.push({
|
||||
type: 'item',
|
||||
value: 'lock',
|
||||
testId: 'dashboard-action-lock',
|
||||
label: isDashboardLocked ? 'Unlock dashboard' : 'Lock dashboard',
|
||||
prefix: <LockKeyhole size={14} />,
|
||||
checks: editChecks,
|
||||
...blockedBy(lockDisabledTooltip),
|
||||
onClick: onLockToggle,
|
||||
});
|
||||
}
|
||||
if (actionControls.fullscreen) {
|
||||
dashboardItems.push({
|
||||
type: 'item',
|
||||
value: 'fullscreen',
|
||||
testId: 'dashboard-action-fullscreen',
|
||||
label: 'Full screen',
|
||||
prefix: <Fullscreen size={14} />,
|
||||
onClick: handleEnterFullScreen,
|
||||
});
|
||||
}
|
||||
|
||||
const layoutItems: AuthZGroupChildType[] = [];
|
||||
if (actionControls.newSection) {
|
||||
layoutItems.push({
|
||||
type: 'item',
|
||||
value: 'new-section',
|
||||
testId: 'dashboard-action-new-section',
|
||||
label: 'New section',
|
||||
prefix: <SquareStack size={14} />,
|
||||
checks: editChecks,
|
||||
...blockedBy(editDisabledTooltip),
|
||||
onClick: (): void => setIsNewSectionOpen(true),
|
||||
});
|
||||
}
|
||||
|
||||
const items: AuthZDropdownItemType[] = [];
|
||||
if (dashboardItems.length) {
|
||||
items.push({
|
||||
type: 'group',
|
||||
value: 'group-dashboard',
|
||||
label: 'Dashboard',
|
||||
items: [
|
||||
{
|
||||
type: 'item',
|
||||
value: 'rename',
|
||||
testId: 'dashboard-action-rename',
|
||||
label: 'Rename',
|
||||
prefix: <PenLine size={14} />,
|
||||
checks: editChecks,
|
||||
...blockedBy(editDisabledTooltip),
|
||||
onClick: onOpenRename,
|
||||
},
|
||||
// Clone creates a new dashboard, so it's not lock-gated.
|
||||
{
|
||||
type: 'item',
|
||||
value: 'clone',
|
||||
testId: 'dashboard-action-clone',
|
||||
label: 'Clone dashboard',
|
||||
prefix: <Copy size={14} />,
|
||||
checks: cloneChecks,
|
||||
loading: isCloning,
|
||||
loadingTooltip: 'Cloning dashboard',
|
||||
onClick: (): void => void handleClone(),
|
||||
},
|
||||
{
|
||||
type: 'item',
|
||||
value: 'lock',
|
||||
testId: 'dashboard-action-lock',
|
||||
label: isDashboardLocked ? 'Unlock dashboard' : 'Lock dashboard',
|
||||
prefix: <LockKeyhole size={14} />,
|
||||
checks: editChecks,
|
||||
...blockedBy(lockDisabledTooltip),
|
||||
onClick: onLockToggle,
|
||||
},
|
||||
{
|
||||
type: 'item',
|
||||
value: 'fullscreen',
|
||||
testId: 'dashboard-action-fullscreen',
|
||||
label: 'Full screen',
|
||||
prefix: <Fullscreen size={14} />,
|
||||
onClick: handleEnterFullScreen,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
items: dashboardItems,
|
||||
});
|
||||
}
|
||||
if (layoutItems.length) {
|
||||
items.push({
|
||||
type: 'group',
|
||||
value: 'group-layout',
|
||||
label: 'Layout',
|
||||
items: [
|
||||
{
|
||||
type: 'item',
|
||||
value: 'new-section',
|
||||
testId: 'dashboard-action-new-section',
|
||||
label: 'New section',
|
||||
prefix: <SquareStack size={14} />,
|
||||
checks: editChecks,
|
||||
...blockedBy(editDisabledTooltip),
|
||||
onClick: (): void => setIsNewSectionOpen(true),
|
||||
},
|
||||
],
|
||||
},
|
||||
{ type: 'separator', value: 'divider-danger' },
|
||||
{
|
||||
type: 'item',
|
||||
value: 'delete',
|
||||
testId: 'dashboard-action-delete',
|
||||
label: 'Delete dashboard',
|
||||
prefix: <Trash2 size={14} />,
|
||||
danger: true,
|
||||
checks: deleteChecks,
|
||||
// Independent of read/update, but a locked dashboard can't be removed.
|
||||
...blockedBy(deleteDisabledTooltip),
|
||||
onClick: confirmDeleteDashboard,
|
||||
},
|
||||
],
|
||||
[
|
||||
editChecks,
|
||||
editDisabledTooltip,
|
||||
deleteChecks,
|
||||
deleteDisabledTooltip,
|
||||
cloneChecks,
|
||||
isCloning,
|
||||
lockDisabledTooltip,
|
||||
isDashboardLocked,
|
||||
onOpenRename,
|
||||
handleClone,
|
||||
onLockToggle,
|
||||
handleEnterFullScreen,
|
||||
confirmDeleteDashboard,
|
||||
],
|
||||
);
|
||||
items: layoutItems,
|
||||
});
|
||||
}
|
||||
if (actionControls.delete) {
|
||||
items.push(
|
||||
{ type: 'separator', value: 'divider-danger' },
|
||||
{
|
||||
type: 'item',
|
||||
value: 'delete',
|
||||
testId: 'dashboard-action-delete',
|
||||
label: 'Delete dashboard',
|
||||
prefix: <Trash2 size={14} />,
|
||||
danger: true,
|
||||
checks: deleteChecks,
|
||||
// Independent of read/update, but a locked dashboard can't be removed.
|
||||
...blockedBy(deleteDisabledTooltip),
|
||||
onClick: confirmDeleteDashboard,
|
||||
},
|
||||
);
|
||||
}
|
||||
return items;
|
||||
}, [
|
||||
actionControls,
|
||||
editChecks,
|
||||
editDisabledTooltip,
|
||||
deleteChecks,
|
||||
deleteDisabledTooltip,
|
||||
cloneChecks,
|
||||
isCloning,
|
||||
lockDisabledTooltip,
|
||||
isDashboardLocked,
|
||||
onOpenRename,
|
||||
handleClone,
|
||||
onLockToggle,
|
||||
handleEnterFullScreen,
|
||||
confirmDeleteDashboard,
|
||||
]);
|
||||
|
||||
return (
|
||||
<div className={styles.dashboardActionsContainer}>
|
||||
<AuthZDropdown items={menuItems} nativeButton align="end" side="bottom">
|
||||
{menuItems.length > 0 && (
|
||||
<AuthZDropdown items={menuItems} nativeButton align="end" side="bottom">
|
||||
<Button
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
size="md"
|
||||
prefix={<Grid3X3 size="md" />}
|
||||
testId="options"
|
||||
>
|
||||
Actions
|
||||
</Button>
|
||||
</AuthZDropdown>
|
||||
)}
|
||||
{actionControls.configure && (
|
||||
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
|
||||
<Button
|
||||
disabledTooltip={undefined}
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
prefix={<Configure size="md" />}
|
||||
testId="show-drawer"
|
||||
disabled={!isEditable}
|
||||
onClick={handleOpenSettings}
|
||||
size="md"
|
||||
>
|
||||
Configure
|
||||
</Button>
|
||||
</AuthZTooltip>
|
||||
)}
|
||||
{actionControls.json && (
|
||||
<Button
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
size="md"
|
||||
prefix={<Grid3X3 size="md" />}
|
||||
testId="options"
|
||||
>
|
||||
Actions
|
||||
</Button>
|
||||
</AuthZDropdown>
|
||||
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
|
||||
<Button
|
||||
disabledTooltip={undefined}
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
prefix={<Configure size="md" />}
|
||||
testId="show-drawer"
|
||||
disabled={!isEditable}
|
||||
onClick={handleOpenSettings}
|
||||
prefix={<Braces size="md" />}
|
||||
testId="edit-json"
|
||||
onClick={handleOpenJsonEditor}
|
||||
size="md"
|
||||
>
|
||||
Configure
|
||||
JSON
|
||||
</Button>
|
||||
</AuthZTooltip>
|
||||
<SettingsDrawer
|
||||
drawerTitle="Dashboard Configuration"
|
||||
isOpen={isSettingsDrawerOpen}
|
||||
destroyOnClose
|
||||
onClose={(): void => {
|
||||
setIsSettingsDrawerOpen(false);
|
||||
clearSettingsRequest();
|
||||
}}
|
||||
>
|
||||
<DashboardSettings dashboard={dashboard} />
|
||||
</SettingsDrawer>
|
||||
<Button
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
prefix={<Braces size="md" />}
|
||||
testId="edit-json"
|
||||
onClick={handleOpenJsonEditor}
|
||||
size="md"
|
||||
>
|
||||
JSON
|
||||
</Button>
|
||||
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
|
||||
<Button
|
||||
disabledTooltip={undefined}
|
||||
variant="solid"
|
||||
color="primary"
|
||||
onClick={onAddPanel}
|
||||
prefix={<Plus size="md" />}
|
||||
testId="add-panel-header"
|
||||
disabled={!isEditable}
|
||||
size="md"
|
||||
>
|
||||
New Panel
|
||||
</Button>
|
||||
</AuthZTooltip>
|
||||
)}
|
||||
{actionControls.newPanel && (
|
||||
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
|
||||
<Button
|
||||
disabledTooltip={undefined}
|
||||
variant="solid"
|
||||
color="primary"
|
||||
onClick={onAddPanel}
|
||||
prefix={<Plus size="md" />}
|
||||
testId="add-panel-header"
|
||||
disabled={!isEditable}
|
||||
size="md"
|
||||
>
|
||||
New Panel
|
||||
</Button>
|
||||
</AuthZTooltip>
|
||||
)}
|
||||
<JsonEditorDrawer
|
||||
dashboard={dashboard}
|
||||
isOpen={isJsonEditorOpen}
|
||||
|
||||
@@ -23,9 +23,11 @@ import { openInNewTab } from 'utils/navigation';
|
||||
import styles from './DashboardInfo.module.scss';
|
||||
|
||||
import TagsOverflowTooltip from './TagsOverflowTooltip';
|
||||
import { getLockTooltip } from './utils';
|
||||
import { DASHBOARD_NAME_MAX_LENGTH } from '../../constants';
|
||||
import { useDashboardStore } from '../../store/useDashboardStore';
|
||||
import { useDashboardEditContext } from '../../hooks/useDashboardEditContext';
|
||||
import { useDashboardControlGroup } from '../../controls/useDashboardControlGroup';
|
||||
|
||||
// The tag cluster keeps a fixed footprint so a long title ellipsizes around it
|
||||
// instead of collapsing the tags: show up to two tags, then a `+N` overflow badge.
|
||||
@@ -74,27 +76,19 @@ function DashboardInfo({
|
||||
}: DashboardInfoProps): JSX.Element {
|
||||
const { isEditable: canEdit } = useDashboardEditContext();
|
||||
const dashboardId = useDashboardStore((s) => s.dashboardId);
|
||||
const titleControls = useDashboardControlGroup('title');
|
||||
|
||||
const hasTags = tags.length > 0;
|
||||
const hasDescription = !isEmpty(description);
|
||||
const hasTags = titleControls.tags && tags.length > 0;
|
||||
const hasDescription = titleControls.description && !isEmpty(description);
|
||||
|
||||
const visibleTags = tags.slice(0, MAX_VISIBLE_TAGS);
|
||||
const remainingTags = tags.slice(MAX_VISIBLE_TAGS);
|
||||
|
||||
// Without a toggle, say why it can't be toggled rather than only restating the
|
||||
// lock state.
|
||||
let lockTooltip: string;
|
||||
if (onToggleLock) {
|
||||
lockTooltip = isDashboardLocked
|
||||
? 'Locked — click to unlock'
|
||||
: 'Unlocked — click to lock';
|
||||
} else if (lockDisabledTooltip) {
|
||||
lockTooltip = lockDisabledTooltip;
|
||||
} else {
|
||||
lockTooltip = isDashboardLocked
|
||||
? 'This dashboard is locked'
|
||||
: 'This dashboard is unlocked';
|
||||
}
|
||||
const lockTooltip = getLockTooltip({
|
||||
isLocked: isDashboardLocked,
|
||||
canToggle: !!onToggleLock,
|
||||
disabledReason: lockDisabledTooltip,
|
||||
});
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent<HTMLInputElement>): void => {
|
||||
if (event.key === 'Enter') {
|
||||
@@ -143,68 +137,71 @@ function DashboardInfo({
|
||||
|
||||
return (
|
||||
<div className={styles.dashboardInfo}>
|
||||
<img src={image} alt={title} className={styles.dashboardImage} />
|
||||
{titleControls.name && (
|
||||
<img src={image} alt={title} className={styles.dashboardImage} />
|
||||
)}
|
||||
|
||||
{isEditing ? (
|
||||
<div className={styles.dashboardTitleEditor} onBlur={onEditorBlur}>
|
||||
<div className={styles.dashboardTitleInput}>
|
||||
<Input
|
||||
autoFocus
|
||||
value={draft}
|
||||
testId="dashboard-title-input"
|
||||
maxLength={DASHBOARD_NAME_MAX_LENGTH}
|
||||
onChange={(e): void => onDraftChange(e.target.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
size="sm"
|
||||
icon
|
||||
aria-label="Save title"
|
||||
testId="dashboard-title-save"
|
||||
onClick={onCommit}
|
||||
>
|
||||
<Check size={14} />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
icon
|
||||
aria-label="Cancel title edit"
|
||||
testId="dashboard-title-cancel"
|
||||
onClick={onCancel}
|
||||
>
|
||||
<X size={14} />
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{canEdit ? (
|
||||
{titleControls.name &&
|
||||
(isEditing ? (
|
||||
<div className={styles.dashboardTitleEditor} onBlur={onEditorBlur}>
|
||||
<div className={styles.dashboardTitleInput}>
|
||||
<Input
|
||||
autoFocus
|
||||
value={draft}
|
||||
testId="dashboard-title-input"
|
||||
maxLength={DASHBOARD_NAME_MAX_LENGTH}
|
||||
onChange={(e): void => onDraftChange(e.target.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="link"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
size="sm"
|
||||
icon
|
||||
aria-label="Save title"
|
||||
testId="dashboard-title-save"
|
||||
onClick={onCommit}
|
||||
>
|
||||
<Check size={14} />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
onClick={onStartEdit}
|
||||
icon
|
||||
aria-label="Cancel title edit"
|
||||
testId="dashboard-title-cancel"
|
||||
onClick={onCancel}
|
||||
>
|
||||
{titleText}
|
||||
<X size={14} />
|
||||
</Button>
|
||||
) : (
|
||||
titleText
|
||||
)}
|
||||
<CopyButton
|
||||
value={dashboardId}
|
||||
ariaLabel="Copy dashboard ID"
|
||||
testId="dashboard-copy-id"
|
||||
onCopy={handleCopyId}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{canEdit ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="link"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
onClick={onStartEdit}
|
||||
>
|
||||
{titleText}
|
||||
</Button>
|
||||
) : (
|
||||
titleText
|
||||
)}
|
||||
<CopyButton
|
||||
value={dashboardId}
|
||||
ariaLabel="Copy dashboard ID"
|
||||
testId="dashboard-copy-id"
|
||||
onCopy={handleCopyId}
|
||||
/>
|
||||
</>
|
||||
))}
|
||||
|
||||
{hasDescription && (
|
||||
<Tooltip
|
||||
@@ -223,7 +220,7 @@ function DashboardInfo({
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
{isPublicDashboard && (
|
||||
{titleControls.publicBadge && isPublicDashboard && (
|
||||
<Tooltip title="This dashboard is publicly accessible. Click to open the public page.">
|
||||
<Button
|
||||
type="button"
|
||||
@@ -240,7 +237,7 @@ function DashboardInfo({
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
{showLockToggle && (
|
||||
{titleControls.lock && showLockToggle && (
|
||||
<Tooltip title={onToggleLock ? lockTooltip : undefined}>
|
||||
<Button
|
||||
disabledTooltip={lockTooltip}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
// Without a toggle, say why it can't be toggled rather than only restating the
|
||||
// lock state.
|
||||
export function getLockTooltip({
|
||||
isLocked,
|
||||
canToggle,
|
||||
disabledReason,
|
||||
}: {
|
||||
isLocked: boolean;
|
||||
canToggle: boolean;
|
||||
disabledReason?: string;
|
||||
}): string {
|
||||
if (canToggle) {
|
||||
return isLocked ? 'Locked — click to unlock' : 'Unlocked — click to lock';
|
||||
}
|
||||
if (disabledReason) {
|
||||
return disabledReason;
|
||||
}
|
||||
return isLocked ? 'This dashboard is locked' : 'This dashboard is unlocked';
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import type { FullScreenHandle } from 'react-full-screen';
|
||||
import { useDashboardLockPermission } from 'hooks/dashboards/useDashboardLockPermission';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import { dashboardResponse } from '../../../stories/__story_mockdata__/dashboard';
|
||||
import type { DashboardControlsInput } from '../../controls/types';
|
||||
|
||||
import { usePublicDashboardMeta } from '../../DashboardSettings/PublicDashboard/usePublicDashboardMeta';
|
||||
import { useDashboardStore } from '../../store/useDashboardStore';
|
||||
import DashboardPageToolbar from '../index';
|
||||
|
||||
const { data: dashboard } = dashboardResponse({
|
||||
panels: 0,
|
||||
sectioned: false,
|
||||
variables: [],
|
||||
locked: true,
|
||||
});
|
||||
|
||||
const handle: FullScreenHandle = {
|
||||
active: false,
|
||||
enter: jest.fn(),
|
||||
exit: jest.fn(),
|
||||
node: { current: null },
|
||||
};
|
||||
|
||||
jest.mock('../DashboardActions/DashboardActions', () => ({
|
||||
__esModule: true,
|
||||
default: (): JSX.Element => <div data-testid="dashboard-actions" />,
|
||||
}));
|
||||
jest.mock('../DashboardInfo/DashboardInfo', () => ({
|
||||
__esModule: true,
|
||||
default: (): JSX.Element => <div data-testid="dashboard-info" />,
|
||||
}));
|
||||
jest.mock('../../VariablesBar/VariablesBar', () => ({
|
||||
__esModule: true,
|
||||
default: (): JSX.Element => <div data-testid="variables-bar" />,
|
||||
}));
|
||||
jest.mock('container/TopNav/DateTimeSelectionV2', () => ({
|
||||
__esModule: true,
|
||||
default: (): JSX.Element => <div data-testid="time-selection" />,
|
||||
}));
|
||||
jest.mock(
|
||||
'../../PanelsAndSectionsLayout/Panel/PanelTypeSelectionModal/PanelTypeSelectionModal',
|
||||
() => ({ __esModule: true, default: (): null => null }),
|
||||
);
|
||||
jest.mock('../../hooks/useCreatePanel', () => ({
|
||||
useCreatePanel: (): unknown => ({
|
||||
isPickerOpen: false,
|
||||
openPicker: jest.fn(),
|
||||
closePicker: jest.fn(),
|
||||
createPanel: jest.fn(),
|
||||
targetLayoutIndex: 0,
|
||||
}),
|
||||
}));
|
||||
jest.mock('../../hooks/useOptimisticPatch', () => ({
|
||||
useOptimisticPatch: (): unknown => ({ patchAsync: jest.fn() }),
|
||||
}));
|
||||
jest.mock('hooks/dashboards/useToggleDashboardLock', () => ({
|
||||
useToggleDashboardLock: (): unknown => ({ toggleLock: jest.fn() }),
|
||||
}));
|
||||
jest.mock('hooks/dashboards/useDashboardLockPermission', () => ({
|
||||
useDashboardLockPermission: jest.fn(() => ({
|
||||
canToggleLock: false,
|
||||
isLoading: false,
|
||||
disabledTooltip: '',
|
||||
})),
|
||||
}));
|
||||
jest.mock(
|
||||
'../../DashboardSettings/PublicDashboard/usePublicDashboardMeta',
|
||||
() => ({
|
||||
usePublicDashboardMeta: jest.fn(() => ({
|
||||
isPublic: false,
|
||||
publicMeta: undefined,
|
||||
})),
|
||||
}),
|
||||
);
|
||||
|
||||
function renderToolbar(
|
||||
ctx: { readOnly?: boolean; controls?: DashboardControlsInput } = {},
|
||||
): void {
|
||||
useDashboardStore
|
||||
.getState()
|
||||
.setEditContext({ dashboardId: dashboard.id, refetch: jest.fn(), ...ctx });
|
||||
render(<DashboardPageToolbar dashboard={dashboard} handle={handle} />);
|
||||
}
|
||||
|
||||
describe('DashboardPageToolbar - controls', () => {
|
||||
afterEach(() => {
|
||||
useDashboardStore
|
||||
.getState()
|
||||
.setEditContext({ dashboardId: '', refetch: jest.fn() });
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders every row and checks lock + share by default', () => {
|
||||
renderToolbar();
|
||||
|
||||
expect(screen.getByTestId('dashboard-info')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('dashboard-actions')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('time-selection')).toBeInTheDocument();
|
||||
expect(jest.mocked(useDashboardLockPermission)).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ enabled: true }),
|
||||
);
|
||||
expect(jest.mocked(usePublicDashboardMeta)).toHaveBeenCalledWith(
|
||||
dashboard.id,
|
||||
{
|
||||
enabled: true,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it('skips the lock permission check on a read-only mount', () => {
|
||||
renderToolbar({ readOnly: true });
|
||||
|
||||
expect(jest.mocked(useDashboardLockPermission)).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ enabled: false }),
|
||||
);
|
||||
});
|
||||
|
||||
it('drops the title row and actions the host hides, and their requests', () => {
|
||||
renderToolbar({
|
||||
readOnly: true,
|
||||
controls: { title: false, dashboardActions: false },
|
||||
});
|
||||
|
||||
expect(screen.queryByTestId('dashboard-info')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('dashboard-actions')).not.toBeInTheDocument();
|
||||
expect(jest.mocked(usePublicDashboardMeta)).toHaveBeenCalledWith(
|
||||
dashboard.id,
|
||||
{
|
||||
enabled: false,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it('hides the time range and keeps the variables bar mounted but hidden', () => {
|
||||
renderToolbar({
|
||||
controls: { toolbar: { timeRange: false, variables: false } },
|
||||
});
|
||||
|
||||
expect(screen.queryByTestId('time-selection')).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('variables-bar')).not.toBeVisible();
|
||||
});
|
||||
|
||||
it('hides the whole toolbar when the host turns every row off', () => {
|
||||
renderToolbar({
|
||||
readOnly: true,
|
||||
controls: { title: false, dashboardActions: false, toolbar: false },
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('dashboard-page-toolbar')).not.toBeVisible();
|
||||
expect(screen.getByTestId('variables-bar')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps the toolbar when only the variables bar is on', () => {
|
||||
renderToolbar({
|
||||
readOnly: true,
|
||||
controls: {
|
||||
title: false,
|
||||
dashboardActions: false,
|
||||
toolbar: { timeRange: false, autoRefresh: false, variables: true },
|
||||
},
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('dashboard-page-toolbar')).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -17,6 +17,8 @@ import { getAbsoluteUrl } from 'utils/basePath';
|
||||
|
||||
import { useCreatePanel } from '../hooks/useCreatePanel';
|
||||
import { useOptimisticPatch } from '../hooks/useOptimisticPatch';
|
||||
import { hasVisibleControl } from '../controls/dashboardControls';
|
||||
import { useDashboardControlGroup } from '../controls/useDashboardControlGroup';
|
||||
import { usePublicDashboardMeta } from '../DashboardSettings/PublicDashboard/usePublicDashboardMeta';
|
||||
import PanelTypeSelectionModal from '../PanelsAndSectionsLayout/Panel/PanelTypeSelectionModal/PanelTypeSelectionModal';
|
||||
import DashboardActions from './DashboardActions/DashboardActions';
|
||||
@@ -56,6 +58,16 @@ function DashboardPageToolbar(props: DashboardPageToolbarProps): JSX.Element {
|
||||
[dashboard.tags],
|
||||
);
|
||||
|
||||
const titleControls = useDashboardControlGroup('title');
|
||||
const actionControls = useDashboardControlGroup('dashboardActions');
|
||||
const toolbarControls = useDashboardControlGroup('toolbar');
|
||||
const hasTitleRow = hasVisibleControl(titleControls);
|
||||
const hasActions = hasVisibleControl(actionControls);
|
||||
const hasVisibleRows =
|
||||
hasTitleRow ||
|
||||
hasActions ||
|
||||
toolbarControls.timeRange ||
|
||||
toolbarControls.variables;
|
||||
const { showErrorModal } = useErrorModal();
|
||||
const { patchAsync } = useOptimisticPatch();
|
||||
const {
|
||||
@@ -71,10 +83,13 @@ function DashboardPageToolbar(props: DashboardPageToolbarProps): JSX.Element {
|
||||
useDashboardLockPermission({
|
||||
dashboardId: id,
|
||||
source: dashboard.source,
|
||||
enabled: titleControls.lock || actionControls.lock,
|
||||
});
|
||||
|
||||
// Public-sharing meta (deduped react-query read); drives the header globe.
|
||||
const { isPublic, publicMeta } = usePublicDashboardMeta(id);
|
||||
const { isPublic, publicMeta } = usePublicDashboardMeta(id, {
|
||||
enabled: titleControls.publicBadge,
|
||||
});
|
||||
const publicUrl = getAbsoluteUrl(publicMeta?.publicPath ?? '');
|
||||
|
||||
// Shared with the list's row menu — it owns the API call, the toast and the
|
||||
@@ -154,49 +169,67 @@ function DashboardPageToolbar(props: DashboardPageToolbarProps): JSX.Element {
|
||||
}, [id, openPicker]);
|
||||
|
||||
return (
|
||||
<section className={styles.dashboardPageToolbarContainer}>
|
||||
<div className={styles.dashboardInfoWithActions}>
|
||||
<DashboardInfo
|
||||
title={title}
|
||||
image={image}
|
||||
tags={tags}
|
||||
description={description}
|
||||
isPublicDashboard={isPublic}
|
||||
publicUrl={publicUrl}
|
||||
isDashboardLocked={isDashboardLocked}
|
||||
showLockToggle={showLockToggle}
|
||||
onToggleLock={
|
||||
canToggleLock
|
||||
? (): void => handleLockDashboardToggle('header')
|
||||
: undefined
|
||||
}
|
||||
lockDisabledTooltip={lockDisabledTooltip}
|
||||
isEditing={isEditing}
|
||||
draft={draft}
|
||||
onDraftChange={setDraft}
|
||||
onStartEdit={startEdit}
|
||||
onCommit={commit}
|
||||
onCancel={cancel}
|
||||
/>
|
||||
<DashboardActions
|
||||
title={title}
|
||||
dashboard={dashboard}
|
||||
handle={handle}
|
||||
isDashboardLocked={isDashboardLocked}
|
||||
onAddPanel={onAddPanel}
|
||||
onLockToggle={(): void => handleLockDashboardToggle('menu')}
|
||||
onOpenRename={startEdit}
|
||||
/>
|
||||
</div>
|
||||
<section
|
||||
className={styles.dashboardPageToolbarContainer}
|
||||
data-testid="dashboard-page-toolbar"
|
||||
hidden={!hasVisibleRows}
|
||||
>
|
||||
{(hasTitleRow || hasActions) && (
|
||||
<div className={styles.dashboardInfoWithActions}>
|
||||
{hasTitleRow && (
|
||||
<DashboardInfo
|
||||
title={title}
|
||||
image={image}
|
||||
tags={tags}
|
||||
description={description}
|
||||
isPublicDashboard={isPublic}
|
||||
publicUrl={publicUrl}
|
||||
isDashboardLocked={isDashboardLocked}
|
||||
showLockToggle={showLockToggle}
|
||||
onToggleLock={
|
||||
canToggleLock
|
||||
? (): void => handleLockDashboardToggle('header')
|
||||
: undefined
|
||||
}
|
||||
lockDisabledTooltip={lockDisabledTooltip}
|
||||
isEditing={isEditing}
|
||||
draft={draft}
|
||||
onDraftChange={setDraft}
|
||||
onStartEdit={startEdit}
|
||||
onCommit={commit}
|
||||
onCancel={cancel}
|
||||
/>
|
||||
)}
|
||||
{hasActions && (
|
||||
<DashboardActions
|
||||
title={title}
|
||||
dashboard={dashboard}
|
||||
handle={handle}
|
||||
isDashboardLocked={isDashboardLocked}
|
||||
onAddPanel={onAddPanel}
|
||||
onLockToggle={(): void => handleLockDashboardToggle('menu')}
|
||||
onOpenRename={startEdit}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Row 2: the time selector floats top-right (declared first so the
|
||||
variables bar's content wraps around it); the variables bar
|
||||
collapses to one line and, when expanded, wraps full-width under it. */}
|
||||
<div className={styles.toolbarRow}>
|
||||
<div className={styles.timeCluster}>
|
||||
<DateTimeSelectionV2 showAutoRefresh hideShareModal />
|
||||
{toolbarControls.timeRange && (
|
||||
<div className={styles.timeCluster}>
|
||||
<DateTimeSelectionV2
|
||||
showAutoRefresh={toolbarControls.autoRefresh}
|
||||
hideShareModal
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{/* Mounted even when hidden: the selectors seed and auto-select the values panels query with. */}
|
||||
<div hidden={!toolbarControls.variables}>
|
||||
<VariablesBar dashboard={dashboard} />
|
||||
</div>
|
||||
<VariablesBar dashboard={dashboard} />
|
||||
</div>
|
||||
<PanelTypeSelectionModal
|
||||
open={isPickerOpen}
|
||||
|
||||
@@ -26,9 +26,13 @@ const PUBLIC_META_STALE_TIME = 5 * 60 * 1000;
|
||||
*/
|
||||
export function usePublicDashboardMeta(
|
||||
dashboardId: string,
|
||||
options?: { enabled?: boolean },
|
||||
): UsePublicDashboardMetaReturn {
|
||||
const { isCloudUser, isEnterpriseSelfHostedUser } = useGetTenantLicense();
|
||||
const enabled = !!dashboardId && (isCloudUser || isEnterpriseSelfHostedUser);
|
||||
const enabled =
|
||||
(options?.enabled ?? true) &&
|
||||
!!dashboardId &&
|
||||
(isCloudUser || isEnterpriseSelfHostedUser);
|
||||
|
||||
const { data, isLoading, isFetching, error, refetch } = useGetPublicDashboard(
|
||||
{ id: dashboardId },
|
||||
|
||||
@@ -2,33 +2,17 @@ import { renderHook } from '@testing-library/react';
|
||||
|
||||
import { useContextLinkVariables } from '../useContextLinkVariables';
|
||||
|
||||
const mockUseGetDashboardV2 = jest.fn();
|
||||
const mockUseDashboardVariableNames = jest.fn();
|
||||
const mockUseQueryBuilder = jest.fn();
|
||||
|
||||
jest.mock(
|
||||
'pages/DashboardPage/DashboardContainer/store/useDashboardStore',
|
||||
() => ({
|
||||
useDashboardStore: (
|
||||
selector: (s: { dashboardId: string }) => unknown,
|
||||
): unknown => selector({ dashboardId: 'dash-1' }),
|
||||
}),
|
||||
);
|
||||
|
||||
jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
|
||||
useQueryBuilder: (): unknown => mockUseQueryBuilder(),
|
||||
}));
|
||||
|
||||
jest.mock('api/generated/services/dashboard', () => ({
|
||||
useGetDashboardV2: (): unknown => mockUseGetDashboardV2(),
|
||||
}));
|
||||
|
||||
// dtoToFormModel is exercised by its own suite; here we only need it to surface a name.
|
||||
jest.mock(
|
||||
'pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/variableAdapters',
|
||||
'pages/DashboardPage/DashboardContainer/hooks/useDashboardVariableNames',
|
||||
() => ({
|
||||
dtoToFormModel: (dto: { name: string }): { name: string } => ({
|
||||
name: dto.name,
|
||||
}),
|
||||
useDashboardVariableNames: (): unknown => mockUseDashboardVariableNames(),
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -45,11 +29,7 @@ describe('useContextLinkVariables', () => {
|
||||
},
|
||||
},
|
||||
});
|
||||
mockUseGetDashboardV2.mockReturnValue({
|
||||
data: {
|
||||
data: { spec: { variables: [{ name: 'region' }, { name: 'tier' }] } },
|
||||
},
|
||||
});
|
||||
mockUseDashboardVariableNames.mockReturnValue(['region', 'tier']);
|
||||
});
|
||||
|
||||
it('orders globals, then _prefixed query fields (deduped), then dashboard vars', () => {
|
||||
@@ -69,9 +49,7 @@ describe('useContextLinkVariables', () => {
|
||||
mockUseQueryBuilder.mockReturnValue({
|
||||
currentQuery: { builder: { queryData: [] } },
|
||||
});
|
||||
// Loaded dashboard with no variables — useDashboardFetchRequired guarantees the
|
||||
// dashboard is present, so the empty case is an empty spec, not `undefined`.
|
||||
mockUseGetDashboardV2.mockReturnValue({ data: { data: { spec: {} } } });
|
||||
mockUseDashboardVariableNames.mockReturnValue([]);
|
||||
|
||||
const { result } = renderHook(() => useContextLinkVariables());
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import { useDashboardStore } from '../../store/useDashboardStore';
|
||||
import PanelTypeSelectionModal from '../Panel/PanelTypeSelectionModal/PanelTypeSelectionModal';
|
||||
import styles from './DashboardEmptyState.module.scss';
|
||||
import { useDashboardEditContext } from '../../hooks/useDashboardEditContext';
|
||||
import { useDashboardControl } from '../../controls/useDashboardControl';
|
||||
|
||||
interface DashboardEmptyStateProps {
|
||||
canAddPanel: boolean;
|
||||
@@ -24,9 +25,11 @@ function DashboardEmptyState({
|
||||
const { isPickerOpen, openPicker, closePicker, createPanel } =
|
||||
useCreatePanel();
|
||||
const requestSettings = useDashboardStore((s) => s.requestSettings);
|
||||
const isConfigureVisible = useDashboardControl('dashboardActions.configure');
|
||||
const isNewPanelVisible = useDashboardControl('dashboardActions.newPanel');
|
||||
|
||||
return (
|
||||
<section className={styles.emptyState}>
|
||||
<section className={styles.emptyState} data-testid="dashboard-empty-state">
|
||||
<div className={styles.content}>
|
||||
<div className={styles.heading}>
|
||||
<img src={dashboardEmojiUrl} alt="" className={styles.emoji} />
|
||||
@@ -53,90 +56,94 @@ function DashboardEmptyState({
|
||||
</div>
|
||||
|
||||
<div className={styles.steps}>
|
||||
<div className={styles.step}>
|
||||
<div className={styles.stepText}>
|
||||
<Configure size={14} className={styles.stepIcon} />
|
||||
<div className={styles.stepCopy}>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="medium"
|
||||
color="main"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Configure your new dashboard
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="tertiary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Give it a name, add description, tags and variables
|
||||
</Typography>
|
||||
{isConfigureVisible && (
|
||||
<div className={styles.step}>
|
||||
<div className={styles.stepText}>
|
||||
<Configure size={14} className={styles.stepIcon} />
|
||||
<div className={styles.stepCopy}>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="medium"
|
||||
color="main"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Configure your new dashboard
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="tertiary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Give it a name, add description, tags and variables
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
|
||||
<Button
|
||||
disabledTooltip={undefined}
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
width="140px"
|
||||
prefix={<Configure size="md" />}
|
||||
disabled={!isEditable}
|
||||
onClick={(): void => requestSettings({ tab: 'Overview' })}
|
||||
testId="empty-configure"
|
||||
>
|
||||
Configure
|
||||
</Button>
|
||||
</AuthZTooltip>
|
||||
</div>
|
||||
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
|
||||
<Button
|
||||
disabledTooltip={undefined}
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
width="140px"
|
||||
prefix={<Configure size="md" />}
|
||||
disabled={!isEditable}
|
||||
onClick={(): void => requestSettings({ tab: 'Overview' })}
|
||||
testId="empty-configure"
|
||||
>
|
||||
Configure
|
||||
</Button>
|
||||
</AuthZTooltip>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={styles.step}>
|
||||
<div className={styles.stepText}>
|
||||
<img src={landscapeUrl} alt="" className={styles.stepIcon} />
|
||||
<div className={styles.stepCopy}>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="medium"
|
||||
color="main"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Add panels
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="tertiary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Add panels to visualize your data
|
||||
</Typography>
|
||||
{isNewPanelVisible && (
|
||||
<div className={styles.step}>
|
||||
<div className={styles.stepText}>
|
||||
<img src={landscapeUrl} alt="" className={styles.stepIcon} />
|
||||
<div className={styles.stepCopy}>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="medium"
|
||||
color="main"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Add panels
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="tertiary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Add panels to visualize your data
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
|
||||
<Button
|
||||
disabledTooltip={undefined}
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
prefix={<Plus size="md" />}
|
||||
disabled={!canAddPanel}
|
||||
onClick={(): void => openPicker()}
|
||||
testId="add-panel"
|
||||
>
|
||||
New Panel
|
||||
</Button>
|
||||
</AuthZTooltip>
|
||||
</div>
|
||||
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
|
||||
<Button
|
||||
disabledTooltip={undefined}
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
prefix={<Plus size="md" />}
|
||||
disabled={!canAddPanel}
|
||||
onClick={(): void => openPicker()}
|
||||
testId="add-panel"
|
||||
>
|
||||
New Panel
|
||||
</Button>
|
||||
</AuthZTooltip>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<PanelTypeSelectionModal
|
||||
|
||||
@@ -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>
|
||||
</>
|
||||
|
||||
@@ -10,6 +10,7 @@ import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';
|
||||
import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
|
||||
|
||||
import type { DashboardSection } from '../../../../utils';
|
||||
import { useDashboardStore } from '../../../../store/useDashboardStore';
|
||||
import { usePanelActionItems } from '../usePanelActionItems';
|
||||
|
||||
/** Keys of the disabled items, in order. */
|
||||
@@ -494,4 +495,43 @@ describe('usePanelActionItems', () => {
|
||||
click(actionRow(result.current.items, 'create-alert'));
|
||||
expect(mockCreateAlert).toHaveBeenCalledWith(mockPanel, 'panel-1');
|
||||
});
|
||||
|
||||
describe('host controls', () => {
|
||||
afterEach(() => {
|
||||
useDashboardStore
|
||||
.getState()
|
||||
.setEditContext({ dashboardId: '', refetch: jest.fn() });
|
||||
});
|
||||
|
||||
it('drops every writing action on a read-only mount', () => {
|
||||
useDashboardStore.getState().setEditContext({
|
||||
dashboardId: 'dash-1',
|
||||
refetch: jest.fn(),
|
||||
readOnly: true,
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => usePanelActionItems(baseArgs));
|
||||
|
||||
expect(itemKeys(result.current)).toStrictEqual([
|
||||
'view-panel',
|
||||
'separator',
|
||||
'download',
|
||||
'create-alert',
|
||||
]);
|
||||
});
|
||||
|
||||
it('drops the actions the host hides', () => {
|
||||
useDashboardStore.getState().setEditContext({
|
||||
dashboardId: 'dash-1',
|
||||
refetch: jest.fn(),
|
||||
controls: { panelActions: { createAlert: false, delete: false } },
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => usePanelActionItems(baseArgs));
|
||||
|
||||
expect(itemKeys(result.current)).not.toContain('create-alert');
|
||||
expect(itemKeys(result.current)).not.toContain('delete-panel');
|
||||
expect(itemKeys(result.current)).toContain('edit-panel');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -28,6 +28,7 @@ import { buildMoveItems } from '../utils/buildMoveItems';
|
||||
import type { AuthZDropdownItemType } from 'lib/authz/components/AuthZDropdown/types';
|
||||
import { blockedBy } from 'lib/authz/components/AuthZDropdown/utils';
|
||||
import { useDashboardEditContext } from '../../../hooks/useDashboardEditContext';
|
||||
import { useDashboardControlGroup } from '../../../controls/useDashboardControlGroup';
|
||||
|
||||
// Stable fallback so renders without layout context don't churn the mutation
|
||||
// hooks' deps (a fresh [] each render would re-create their callbacks).
|
||||
@@ -64,6 +65,7 @@ export function usePanelActionItems({
|
||||
const panelKind = panel.spec.plugin.kind;
|
||||
const { isEditable, editChecks, editDisabledTooltip } =
|
||||
useDashboardEditContext();
|
||||
const panelControls = useDashboardControlGroup('panelActions');
|
||||
const openPanelEditor = useOpenPanelEditor();
|
||||
const createAlert = useCreateAlertFromPanel();
|
||||
const { openView } = useViewPanel();
|
||||
@@ -101,7 +103,7 @@ export function usePanelActionItems({
|
||||
const editGate = { checks: editChecks, ...blockedBy(editDisabledTooltip) };
|
||||
|
||||
const panelGroup: AuthZDropdownItemType[] = [];
|
||||
if (panelCapabilities.view) {
|
||||
if (panelControls.view && panelCapabilities.view) {
|
||||
panelGroup.push({
|
||||
type: 'item',
|
||||
value: 'view-panel',
|
||||
@@ -110,7 +112,7 @@ export function usePanelActionItems({
|
||||
onClick: (): void => openView(panelId, panel),
|
||||
});
|
||||
}
|
||||
if (panelCapabilities.edit) {
|
||||
if (panelControls.edit && panelCapabilities.edit) {
|
||||
panelGroup.push({
|
||||
type: 'item',
|
||||
value: 'edit-panel',
|
||||
@@ -120,7 +122,7 @@ export function usePanelActionItems({
|
||||
onClick: (): void => openPanelEditor(panelId, { panel }),
|
||||
});
|
||||
}
|
||||
if (panelCapabilities.clone) {
|
||||
if (panelControls.clone && panelCapabilities.clone) {
|
||||
// Needs section context to place the copy; disabled without it.
|
||||
panelGroup.push({
|
||||
type: 'item',
|
||||
@@ -140,13 +142,13 @@ export function usePanelActionItems({
|
||||
}
|
||||
|
||||
const dataGroup: AuthZDropdownItemType[] = [];
|
||||
if (downloadItem) {
|
||||
if (panelControls.download && downloadItem) {
|
||||
dataGroup.push(downloadItem);
|
||||
}
|
||||
|
||||
// Create Alerts opens a new tab and never mutates the dashboard, so —
|
||||
// unlike edit/clone — it isn't gated on editability (V1 parity).
|
||||
if (panelCapabilities.createAlert) {
|
||||
if (panelControls.createAlert && panelCapabilities.createAlert) {
|
||||
dataGroup.push({
|
||||
type: 'item',
|
||||
value: 'create-alert',
|
||||
@@ -156,8 +158,9 @@ export function usePanelActionItems({
|
||||
});
|
||||
}
|
||||
|
||||
const moveGroup: AuthZDropdownItemType[] =
|
||||
isEditable && panelActions
|
||||
const moveGroup: AuthZDropdownItemType[] = !panelControls.move
|
||||
? []
|
||||
: isEditable && panelActions
|
||||
? buildMoveItems({
|
||||
sections,
|
||||
currentLayoutIndex: panelActions.currentLayoutIndex,
|
||||
@@ -174,17 +177,19 @@ export function usePanelActionItems({
|
||||
},
|
||||
];
|
||||
|
||||
const deleteGroup: AuthZDropdownItemType[] = [
|
||||
{
|
||||
type: 'item',
|
||||
value: 'delete-panel',
|
||||
label: 'Delete panel',
|
||||
prefix: <Trash2 size={14} />,
|
||||
danger: true,
|
||||
...editGate,
|
||||
onClick: (): void => requestDelete(),
|
||||
},
|
||||
];
|
||||
const deleteGroup: AuthZDropdownItemType[] = !panelControls.delete
|
||||
? []
|
||||
: [
|
||||
{
|
||||
type: 'item',
|
||||
value: 'delete-panel',
|
||||
label: 'Delete panel',
|
||||
prefix: <Trash2 size={14} />,
|
||||
danger: true,
|
||||
...editGate,
|
||||
onClick: (): void => requestDelete(),
|
||||
},
|
||||
];
|
||||
|
||||
return [panelGroup, dataGroup, moveGroup, deleteGroup]
|
||||
.filter((group) => group.length > 0)
|
||||
@@ -194,6 +199,7 @@ export function usePanelActionItems({
|
||||
: [{ type: 'separator', value: `separator-${index}` }, ...group],
|
||||
);
|
||||
}, [
|
||||
panelControls,
|
||||
isEditable,
|
||||
editChecks,
|
||||
editDisabledTooltip,
|
||||
|
||||
@@ -14,6 +14,7 @@ import { EQueryType } from 'types/common/dashboard';
|
||||
import styles from './ViewPanelModal.module.scss';
|
||||
import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';
|
||||
import { useDashboardEditContext } from '../../../hooks/useDashboardEditContext';
|
||||
import { useDashboardControl } from '../../../controls/useDashboardControl';
|
||||
|
||||
interface ViewPanelModalHeaderBaseProps {
|
||||
onSwitchToEdit: () => void;
|
||||
@@ -70,6 +71,7 @@ function ViewPanelModalHeader(props: ViewPanelModalHeaderProps): JSX.Element {
|
||||
editChecks,
|
||||
editDisabledTooltip,
|
||||
} = useDashboardEditContext();
|
||||
const isSwitchToEditVisible = useDashboardControl('viewModal.switchToEdit');
|
||||
// Same capabilities-guarded options as the editor's PanelTypeSwitcher, so the two
|
||||
// selectors disable the same kinds (e.g. List under PromQL, metrics-only kinds).
|
||||
const panelTypeItems = usePanelTypeSelectItems({
|
||||
@@ -87,20 +89,22 @@ function ViewPanelModalHeader(props: ViewPanelModalHeaderProps): JSX.Element {
|
||||
onChange={onChangePanelKind}
|
||||
/>
|
||||
</div>
|
||||
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
|
||||
<Button
|
||||
disabledTooltip={undefined}
|
||||
size="md"
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
prefix={<PenLine />}
|
||||
disabled={!canSwitchToEdit}
|
||||
onClick={onSwitchToEdit}
|
||||
testId="view-panel-switch-to-edit"
|
||||
>
|
||||
Switch to Edit Mode
|
||||
</Button>
|
||||
</AuthZTooltip>
|
||||
{isSwitchToEditVisible && (
|
||||
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
|
||||
<Button
|
||||
disabledTooltip={undefined}
|
||||
size="md"
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
prefix={<PenLine />}
|
||||
disabled={!canSwitchToEdit}
|
||||
onClick={onSwitchToEdit}
|
||||
testId="view-panel-switch-to-edit"
|
||||
>
|
||||
Switch to Edit Mode
|
||||
</Button>
|
||||
</AuthZTooltip>
|
||||
)}
|
||||
{query && (
|
||||
<Button
|
||||
size="md"
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import { useDashboardStore } from '../../../../store/useDashboardStore';
|
||||
import ViewPanelModalHeader from '../ViewPanelModalHeader';
|
||||
import type { DashboardControlsInput } from '../../../../controls/types';
|
||||
|
||||
jest.mock(
|
||||
'pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext',
|
||||
() => ({
|
||||
useDashboardEditContext: (): unknown => ({
|
||||
isEditable: true,
|
||||
editChecks: [],
|
||||
editDisabledTooltip: '',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
jest.mock(
|
||||
'pages/DashboardPage/DashboardContainer/PanelEditor/ConfigPane/PanelTypeSwitcher/usePanelTypeSelectItems',
|
||||
() => ({ usePanelTypeSelectItems: (): unknown[] => [] }),
|
||||
);
|
||||
|
||||
function renderHeader(
|
||||
readOnly: boolean,
|
||||
controls?: DashboardControlsInput,
|
||||
): void {
|
||||
useDashboardStore.getState().setEditContext({
|
||||
dashboardId: 'dash-1',
|
||||
refetch: jest.fn(),
|
||||
readOnly,
|
||||
controls,
|
||||
});
|
||||
render(
|
||||
<ViewPanelModalHeader
|
||||
mode="static"
|
||||
panelKind="signoz/TimeSeriesPanel"
|
||||
onChangePanelKind={jest.fn()}
|
||||
onSwitchToEdit={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('ViewPanelModalHeader - controls', () => {
|
||||
afterEach(() => {
|
||||
useDashboardStore
|
||||
.getState()
|
||||
.setEditContext({ dashboardId: '', refetch: jest.fn() });
|
||||
});
|
||||
|
||||
it('offers Switch to Edit Mode on an editable mount', () => {
|
||||
renderHeader(false);
|
||||
|
||||
expect(screen.getByTestId('view-panel-switch-to-edit')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides Switch to Edit Mode on a read-only mount', () => {
|
||||
renderHeader(true);
|
||||
|
||||
expect(screen.getByTestId('view-panel-type-selector')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('view-panel-switch-to-edit'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides Switch to Edit Mode when the host hides it', () => {
|
||||
renderHeader(false, { viewModal: false });
|
||||
|
||||
expect(
|
||||
screen.queryByTestId('view-panel-switch-to-edit'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -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(
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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,17 +21,32 @@ let mockVariables: Array<{
|
||||
let mockSelectionMap: Record<string, { value: unknown; allSelected: boolean }> =
|
||||
{};
|
||||
|
||||
let mockIsEditable = true;
|
||||
const mockSetVariableValue = jest.fn();
|
||||
const mockPatchAsync = jest.fn().mockResolvedValue(undefined);
|
||||
|
||||
const DYNAMIC_KIND = 'signoz/DynamicVariable';
|
||||
const QUERY_KIND = 'signoz/QueryVariable';
|
||||
|
||||
jest.mock('api/generated/services/dashboard', () => ({
|
||||
useGetDashboardV2: (): unknown => ({
|
||||
data: { data: { spec: { variables: mockVariables } } },
|
||||
jest.mock(
|
||||
'pages/DashboardPage/DashboardContainer/hooks/useDashboardFetchRequired',
|
||||
() => ({
|
||||
useDashboardFetchRequired: (): unknown => ({
|
||||
dashboard: { spec: { variables: mockVariables } },
|
||||
variables: mockVariables,
|
||||
refetch: jest.fn(),
|
||||
}),
|
||||
}),
|
||||
}));
|
||||
);
|
||||
jest.mock(
|
||||
'pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext',
|
||||
() => ({
|
||||
useDashboardEditContext: (): unknown => ({
|
||||
isEditable: mockIsEditable,
|
||||
editDisabledTooltip: 'no edit access',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
jest.mock(
|
||||
'pages/DashboardPage/DashboardContainer/hooks/useOptimisticPatch',
|
||||
() => ({
|
||||
@@ -97,21 +115,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 +190,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();
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { safeNavigateMock } from '__tests__/safeNavigateMock';
|
||||
import { AllTheProviders, renderHook } from 'tests/test-utils';
|
||||
|
||||
import { CHARTS_ONLY } from '../../../../controls/presets';
|
||||
import type { DashboardControlsInput } from '../../../../controls/types';
|
||||
import { useDashboardStore } from '../../../../store/useDashboardStore';
|
||||
import { usePanelInteractions } from '../usePanelInteractions';
|
||||
|
||||
function dragSelect(controls?: DashboardControlsInput): void {
|
||||
useDashboardStore
|
||||
.getState()
|
||||
.setEditContext({ dashboardId: 'd1', refetch: jest.fn(), controls });
|
||||
const { result } = renderHook(() => usePanelInteractions(), {
|
||||
wrapper: AllTheProviders,
|
||||
});
|
||||
result.current.onDragSelect(1_000, 2_000);
|
||||
}
|
||||
|
||||
describe('usePanelInteractions drag-to-zoom', () => {
|
||||
afterEach(() => {
|
||||
useDashboardStore
|
||||
.getState()
|
||||
.setEditContext({ dashboardId: '', refetch: jest.fn() });
|
||||
});
|
||||
|
||||
it('writes the dragged range to the URL', () => {
|
||||
dragSelect();
|
||||
|
||||
expect(safeNavigateMock).toHaveBeenCalledWith(
|
||||
expect.stringContaining('startTime=1000&endTime=2000'),
|
||||
);
|
||||
});
|
||||
|
||||
it('does nothing when the host turns zoom off', () => {
|
||||
dragSelect({ panelActions: { zoom: false } });
|
||||
|
||||
expect(safeNavigateMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('still zooms when the host hides the toolbar but leaves zoom on', () => {
|
||||
dragSelect({ toolbar: false });
|
||||
|
||||
expect(safeNavigateMock).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('still zooms on a charts-only mount', () => {
|
||||
dragSelect(CHARTS_ONLY);
|
||||
|
||||
expect(safeNavigateMock).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -37,6 +37,7 @@ import { useDrilldownCoordinates } from './useDrilldownCoordinates';
|
||||
import { useDrilldownDashboardVariables } from './useDrilldownDashboardVariables';
|
||||
import { useDrilldownFilter } from './useDrilldownFilter';
|
||||
import { useResolvedDrilldownQuery } from './useResolvedDrilldownQuery';
|
||||
import { useDashboardControl } from 'pages/DashboardPage/DashboardContainer/controls/useDashboardControl';
|
||||
import { useViewPanel } from './useViewPanel';
|
||||
|
||||
/** Which menu the popover shows; extend as submenus are added (e.g. dashboard variables). */
|
||||
@@ -87,16 +88,19 @@ export function useDrilldown(
|
||||
const queries = panel.spec.queries;
|
||||
|
||||
// Drilldown only for builder-authored panels with a query to drill into (PromQL /
|
||||
// ClickHouse have no builder context to refine).
|
||||
// ClickHouse have no builder context to refine). A panel whose builder queries
|
||||
// are all disabled draws only formulas, which have no series to drill into.
|
||||
const isDrilldownVisible = useDashboardControl('panelActions.drilldown');
|
||||
const enableDrillDown = useMemo(() => {
|
||||
const queryType = getPanelQueryType(panel);
|
||||
return (
|
||||
isDrilldownVisible &&
|
||||
getPanelDefinition(kind).actions.drilldown &&
|
||||
!!queryType &&
|
||||
isBuilderQueryType(queryType) &&
|
||||
getBuilderQueries(queries).length > 0
|
||||
getBuilderQueries(queries).some((query) => !query.disabled)
|
||||
);
|
||||
}, [kind, panel, queries]);
|
||||
}, [isDrilldownVisible, kind, panel, queries]);
|
||||
|
||||
const slotQuery = useMemo(
|
||||
() => fromPerses(queries, panelType),
|
||||
@@ -241,7 +245,7 @@ export function useDrilldown(
|
||||
query={v1Query}
|
||||
isResolving={isResolving}
|
||||
links={panel.spec.links}
|
||||
canSetDashboardVariables={dashboardVariables.hasFieldVariables}
|
||||
canSetDashboardVariables={dashboardVariables.actions.length > 0}
|
||||
onViewLogs={(): void => navigate('view_logs')}
|
||||
onViewTraces={(): void => navigate('view_traces')}
|
||||
onBreakout={openBreakout}
|
||||
@@ -254,7 +258,6 @@ export function useDrilldown(
|
||||
breakout.queryData,
|
||||
breakout.onBreakout,
|
||||
dashboardVariables.actions,
|
||||
dashboardVariables.hasFieldVariables,
|
||||
filter.isGroupColumnClick,
|
||||
filter.onFilter,
|
||||
context,
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
type VariableFormModel,
|
||||
} from 'pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/variableFormModel';
|
||||
import { buildVariablesPatch } from 'pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/utils/variablePatchOps';
|
||||
import { useDashboardEditContext } from 'pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext';
|
||||
import { useDashboardFetchRequired } from 'pages/DashboardPage/DashboardContainer/hooks/useDashboardFetchRequired';
|
||||
import { useOptimisticPatch } from 'pages/DashboardPage/DashboardContainer/hooks/useOptimisticPatch';
|
||||
import { selectVariableValues } from 'pages/DashboardPage/DashboardContainer/store/slices/variableSelectionSlice';
|
||||
@@ -41,11 +42,11 @@ export interface DrilldownVariableAction {
|
||||
kind: DrilldownVariableActionKind;
|
||||
/** Applies the action and closes the popover. */
|
||||
onClick: () => void;
|
||||
/** Why the action can't run; the entry renders disabled with it. */
|
||||
disabledTooltip?: string;
|
||||
}
|
||||
|
||||
export interface UseDrilldownDashboardVariablesApi {
|
||||
/** Whether the clicked point exposes any field to bind to a variable (gates the base-menu entry). */
|
||||
hasFieldVariables: boolean;
|
||||
/** Resolved menu entries, one per group-by field on the clicked point. */
|
||||
actions: DrilldownVariableAction[];
|
||||
}
|
||||
@@ -74,6 +75,8 @@ export function useDrilldownDashboardVariables({
|
||||
const selection = useDashboardStore(selectVariableValues(dashboardId));
|
||||
const setVariableValue = useDashboardStore((state) => state.setVariableValue);
|
||||
const { patchAsync } = useOptimisticPatch();
|
||||
// Create writes the dashboard spec; Set/Unset only change this view's selection.
|
||||
const { isEditable, editDisabledTooltip } = useDashboardEditContext();
|
||||
|
||||
const fieldVariables = useMemo<[string, string | number][]>(
|
||||
() =>
|
||||
@@ -153,6 +156,7 @@ export function useDrilldownDashboardVariables({
|
||||
onClick: (): void => {
|
||||
void handleCreate(fieldName, fieldValue);
|
||||
},
|
||||
disabledTooltip: isEditable ? undefined : editDisabledTooltip,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -186,6 +190,8 @@ export function useDrilldownDashboardVariables({
|
||||
}),
|
||||
[
|
||||
fieldVariables,
|
||||
isEditable,
|
||||
editDisabledTooltip,
|
||||
dynamicVariables,
|
||||
selection,
|
||||
setSelection,
|
||||
@@ -195,5 +201,5 @@ export function useDrilldownDashboardVariables({
|
||||
],
|
||||
);
|
||||
|
||||
return { hasFieldVariables: fieldVariables.length > 0, actions };
|
||||
return { actions };
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { DashboardDetailEvents } from 'pages/DashboardPage/constants/events';
|
||||
import { UpdateTimeInterval } from 'store/actions';
|
||||
import { useDashboardControl } from 'pages/DashboardPage/DashboardContainer/controls/useDashboardControl';
|
||||
|
||||
export interface PanelInteractions {
|
||||
/** Drag-select a chart range → write it to the URL + global time so every panel re-fetches the same range. */
|
||||
@@ -43,8 +44,12 @@ export function usePanelInteractions(): PanelInteractions {
|
||||
[syncMode, syncFilterMode, dashboardId],
|
||||
);
|
||||
|
||||
const canZoom = useDashboardControl('panelActions.zoom');
|
||||
const onDragSelect = useCallback(
|
||||
(start: number, end: number): void => {
|
||||
if (!canZoom) {
|
||||
return;
|
||||
}
|
||||
const startTimestamp = Math.trunc(start);
|
||||
const endTimestamp = Math.trunc(end);
|
||||
|
||||
@@ -57,7 +62,7 @@ export function usePanelInteractions(): PanelInteractions {
|
||||
void logEvent(DashboardDetailEvents.PanelZoomed, { context: 'panel' });
|
||||
}
|
||||
},
|
||||
[dispatch, pathname, safeNavigate, urlQuery],
|
||||
[canZoom, dispatch, pathname, safeNavigate, urlQuery],
|
||||
);
|
||||
|
||||
return { onDragSelect, dashboardPreference };
|
||||
|
||||
@@ -8,12 +8,12 @@ import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';
|
||||
import { useCreatePanel } from '../../../hooks/useCreatePanel';
|
||||
import type { DashboardSection } from '../../../utils';
|
||||
import PanelTypeSelectionModal from '../../Panel/PanelTypeSelectionModal/PanelTypeSelectionModal';
|
||||
import { useCloneSection } from '../hooks/useCloneSection';
|
||||
import { useDeleteSection } from '../hooks/useDeleteSection';
|
||||
import { usePanelPickerHighlight } from '../hooks/usePanelPickerHighlight';
|
||||
import { usePanelPickerReveal } from '../hooks/usePanelPickerReveal';
|
||||
import { useRenameSection } from '../hooks/useRenameSection';
|
||||
import { useScrollIntoView } from '../hooks/useScrollIntoView';
|
||||
import { useSectionHeaderActions } from '../hooks/useSectionHeaderActions';
|
||||
import { useToggleSectionCollapse } from '../hooks/useToggleSectionCollapse';
|
||||
import SectionTitleModal from '../SectionTitleModal';
|
||||
import SectionGrid from '../SectionGrid/SectionGrid';
|
||||
@@ -66,7 +66,14 @@ function Section({ section, sections, dragHandle }: SectionProps): JSX.Element {
|
||||
setIsDeleteOpen(false);
|
||||
}, [deleteSection]);
|
||||
|
||||
const cloneSection = useCloneSection();
|
||||
const openRename = useCallback((): void => setIsRenaming(true), []);
|
||||
const openDelete = useCallback((): void => setIsDeleteOpen(true), []);
|
||||
const actions = useSectionHeaderActions({
|
||||
section,
|
||||
openPicker,
|
||||
openRename,
|
||||
openDelete,
|
||||
});
|
||||
|
||||
const sectionRef = useRef<HTMLDivElement>(null);
|
||||
useScrollIntoView(section.id, sectionRef);
|
||||
@@ -116,35 +123,30 @@ function Section({ section, sections, dragHandle }: SectionProps): JSX.Element {
|
||||
dragHandle={dragHandle}
|
||||
disabledChecks={editChecks}
|
||||
disabledTooltip={editDisabledTooltip}
|
||||
actions={{
|
||||
onRename: (): void => setIsRenaming(true),
|
||||
onAddPanel: (): void => openPicker(section.layoutIndex),
|
||||
onCloneSection: (): void => void cloneSection(section),
|
||||
onDeleteSection: (): void => setIsDeleteOpen(true),
|
||||
}}
|
||||
actions={actions}
|
||||
/>
|
||||
{open &&
|
||||
(section.items.length > 0 || pickerTarget ? (
|
||||
grid
|
||||
) : (
|
||||
<div className={styles.emptySection}>
|
||||
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
|
||||
<Button
|
||||
size="md"
|
||||
type="button"
|
||||
variant="dashed"
|
||||
color="secondary"
|
||||
prefix={<Plus size="md" />}
|
||||
onClick={
|
||||
isEditable ? (): void => openPicker(section.layoutIndex) : undefined
|
||||
}
|
||||
testId={`section-add-panel-${section.id}`}
|
||||
>
|
||||
New Panel
|
||||
</Button>
|
||||
</AuthZTooltip>
|
||||
</div>
|
||||
))}
|
||||
(section.items.length > 0 || pickerTarget
|
||||
? grid
|
||||
: actions.onAddPanel && (
|
||||
<div className={styles.emptySection}>
|
||||
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
|
||||
<Button
|
||||
size="md"
|
||||
type="button"
|
||||
variant="dashed"
|
||||
color="secondary"
|
||||
prefix={<Plus size="md" />}
|
||||
onClick={
|
||||
isEditable ? (): void => openPicker(section.layoutIndex) : undefined
|
||||
}
|
||||
testId={`section-add-panel-${section.id}`}
|
||||
>
|
||||
New Panel
|
||||
</Button>
|
||||
</AuthZTooltip>
|
||||
</div>
|
||||
))}
|
||||
<SectionTitleModal
|
||||
open={isRenaming}
|
||||
heading="Rename section"
|
||||
|
||||
@@ -13,8 +13,8 @@ interface SectionActionsMenuProps {
|
||||
disabledTooltip?: string;
|
||||
onAddPanel?: () => void;
|
||||
onRename?: () => void;
|
||||
onCloneSection?: () => void;
|
||||
onDeleteSection?: () => void;
|
||||
onClone?: () => void;
|
||||
onDelete?: () => void;
|
||||
}
|
||||
|
||||
function SectionActionsMenu({
|
||||
@@ -23,9 +23,9 @@ function SectionActionsMenu({
|
||||
disabledTooltip = '',
|
||||
onAddPanel,
|
||||
onRename,
|
||||
onCloneSection,
|
||||
onDeleteSection,
|
||||
}: SectionActionsMenuProps): JSX.Element {
|
||||
onClone,
|
||||
onDelete,
|
||||
}: SectionActionsMenuProps): JSX.Element | null {
|
||||
const items = useMemo<AuthZDropdownItemType[]>(() => {
|
||||
const gate = { checks: disabledChecks, ...blockedBy(disabledTooltip) };
|
||||
const result: AuthZDropdownItemType[] = [];
|
||||
@@ -49,17 +49,17 @@ function SectionActionsMenu({
|
||||
onClick: onRename,
|
||||
});
|
||||
}
|
||||
if (onCloneSection) {
|
||||
if (onClone) {
|
||||
result.push({
|
||||
type: 'item',
|
||||
value: 'clone-section',
|
||||
label: 'Clone section',
|
||||
prefix: <Copy size={14} />,
|
||||
...gate,
|
||||
onClick: onCloneSection,
|
||||
onClick: onClone,
|
||||
});
|
||||
}
|
||||
if (onDeleteSection) {
|
||||
if (onDelete) {
|
||||
result.push(
|
||||
{ type: 'separator', value: 'before-delete-section' },
|
||||
{
|
||||
@@ -69,19 +69,16 @@ function SectionActionsMenu({
|
||||
prefix: <Trash2 size={14} />,
|
||||
danger: true,
|
||||
...gate,
|
||||
onClick: onDeleteSection,
|
||||
onClick: onDelete,
|
||||
},
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}, [
|
||||
disabledChecks,
|
||||
disabledTooltip,
|
||||
onAddPanel,
|
||||
onRename,
|
||||
onCloneSection,
|
||||
onDeleteSection,
|
||||
]);
|
||||
}, [disabledChecks, disabledTooltip, onAddPanel, onRename, onClone, onDelete]);
|
||||
|
||||
if (items.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthZDropdown
|
||||
|
||||
@@ -35,7 +35,7 @@ describe('SectionActionsMenu', () => {
|
||||
disabledChecks={[updatePermission]}
|
||||
disabledTooltip="This dashboard is locked"
|
||||
onRename={jest.fn()}
|
||||
onDeleteSection={jest.fn()}
|
||||
onDelete={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
await openMenu();
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useMemo } from 'react';
|
||||
import GridLayout, { WidthProvider, type Layout } from 'react-grid-layout';
|
||||
import cx from 'classnames';
|
||||
|
||||
import { newPanelSlot } from '../../../patchOps';
|
||||
import { GRID_COLS, newPanelSlot } from '../../../patchOps';
|
||||
import type { PanelKind } from '../../../Panels/types/panelKind';
|
||||
import type { DashboardSection } from '../../../utils';
|
||||
import { usePersistLayout } from '../hooks/usePersistLayout';
|
||||
@@ -53,7 +53,7 @@ function SectionGrid({
|
||||
return (
|
||||
<ResponsiveGridLayout
|
||||
className={cx(styles.grid, { [styles.instantHeight]: !!placeholderKind })}
|
||||
cols={12}
|
||||
cols={GRID_COLS}
|
||||
rowHeight={GRID_ROW_HEIGHT}
|
||||
autoSize
|
||||
useCSSTransforms
|
||||
|
||||
@@ -8,6 +8,7 @@ import cx from 'classnames';
|
||||
import SectionActionsMenu from '../SectionActionsMenu/SectionActionsMenu';
|
||||
|
||||
import styles from './SectionHeader.module.scss';
|
||||
import type { DashboardControls } from '../../../controls/types';
|
||||
import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';
|
||||
|
||||
export interface SectionDragHandle {
|
||||
@@ -16,13 +17,12 @@ export interface SectionDragHandle {
|
||||
setActivatorNodeRef: (element: HTMLElement | null) => void;
|
||||
}
|
||||
|
||||
/** Editable-mode section actions — present together or not at all. */
|
||||
export interface SectionHeaderActions {
|
||||
onRename: () => void;
|
||||
onAddPanel: () => void;
|
||||
onCloneSection: () => void;
|
||||
onDeleteSection: () => void;
|
||||
}
|
||||
/** One handler per `sectionActions` control; an absent one isn't offered. */
|
||||
export type SectionHeaderActions = {
|
||||
[
|
||||
K in keyof DashboardControls['sectionActions'] as `on${Capitalize<K>}`
|
||||
]?: () => void;
|
||||
};
|
||||
|
||||
interface SectionHeaderProps {
|
||||
sectionId: string;
|
||||
@@ -131,8 +131,8 @@ function SectionHeader({
|
||||
disabledTooltip={disabledTooltip}
|
||||
onAddPanel={actions.onAddPanel}
|
||||
onRename={actions.onRename}
|
||||
onCloneSection={actions.onCloneSection}
|
||||
onDeleteSection={actions.onDeleteSection}
|
||||
onClone={actions.onClone}
|
||||
onDelete={actions.onDelete}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import { useDashboardControlGroup } from '../../../controls/useDashboardControlGroup';
|
||||
import type { DashboardSection } from '../../../utils';
|
||||
import type { SectionHeaderActions } from '../SectionHeader/SectionHeader';
|
||||
import { useCloneSection } from './useCloneSection';
|
||||
|
||||
interface UseSectionHeaderActionsArgs {
|
||||
section: DashboardSection;
|
||||
openPicker: (layoutIndex: number) => void;
|
||||
openRename: () => void;
|
||||
openDelete: () => void;
|
||||
}
|
||||
|
||||
/** The section menu's actions, minus the ones the host hides (`sectionActions`). */
|
||||
export function useSectionHeaderActions({
|
||||
section,
|
||||
openPicker,
|
||||
openRename,
|
||||
openDelete,
|
||||
}: UseSectionHeaderActionsArgs): SectionHeaderActions {
|
||||
const sectionControls = useDashboardControlGroup('sectionActions');
|
||||
const cloneSection = useCloneSection();
|
||||
|
||||
return useMemo(
|
||||
() => ({
|
||||
onRename: sectionControls.rename ? openRename : undefined,
|
||||
onAddPanel: sectionControls.addPanel
|
||||
? (): void => openPicker(section.layoutIndex)
|
||||
: undefined,
|
||||
onClone: sectionControls.clone
|
||||
? (): void => void cloneSection(section)
|
||||
: undefined,
|
||||
onDelete: sectionControls.delete ? openDelete : undefined,
|
||||
}),
|
||||
[sectionControls, openRename, openPicker, section, cloneSection, openDelete],
|
||||
);
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import { resolveDefaultSelection } from './utils/resolveVariableSelection';
|
||||
import VariableSelector from './components/VariableSelector/VariableSelector';
|
||||
import styles from './VariablesBar.module.scss';
|
||||
import { useDashboardEditContext } from '../hooks/useDashboardEditContext';
|
||||
import { useDashboardControl } from '../controls/useDashboardControl';
|
||||
|
||||
interface VariablesBarProps {
|
||||
dashboard: DashboardtypesGettableDashboardV2DTO;
|
||||
@@ -39,6 +40,7 @@ function VariablesBar({ dashboard }: VariablesBarProps): JSX.Element | null {
|
||||
// Persisted per dashboard so the full/collapsed view survives reloads.
|
||||
const expanded = useDashboardStore(selectVariablesExpanded(dashboardId));
|
||||
const setVariablesExpanded = useDashboardStore((s) => s.setVariablesExpanded);
|
||||
const isAddVariableVisible = useDashboardControl('toolbar.addVariable');
|
||||
const { containerRef, visibleCount, overflowCount } = useInlineOverflowCount({
|
||||
itemCount: variables.length,
|
||||
gap: 8,
|
||||
@@ -49,7 +51,7 @@ function VariablesBar({ dashboard }: VariablesBarProps): JSX.Element | null {
|
||||
|
||||
// Editors can add a variable even before any exist; viewers with no variables
|
||||
// have nothing to show.
|
||||
if (variables.length === 0 && !isEditable) {
|
||||
if (variables.length === 0 && !(isEditable && isAddVariableVisible)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -131,13 +133,15 @@ function VariablesBar({ dashboard }: VariablesBarProps): JSX.Element | null {
|
||||
{/* After the more/less trigger, in every state. Kept inline (not block)
|
||||
so the row still flows under the floated time selector, and always
|
||||
mounted so measuring never toggles it. */}
|
||||
<span className={styles.addSlot}>
|
||||
<AddVariableIcon
|
||||
checks={editChecks}
|
||||
disabledTooltip={editDisabledTooltip}
|
||||
isEditable={isEditable}
|
||||
/>
|
||||
</span>
|
||||
{isAddVariableVisible && (
|
||||
<span className={styles.addSlot}>
|
||||
<AddVariableIcon
|
||||
checks={editChecks}
|
||||
disabledTooltip={editDisabledTooltip}
|
||||
isEditable={isEditable}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import { dashboardResponse } from '../../../stories/__story_mockdata__/dashboard';
|
||||
import { useDashboardStore } from '../../store/useDashboardStore';
|
||||
import VariablesBar from '../VariablesBar';
|
||||
import type { DashboardControlsInput } from '../../controls/types';
|
||||
|
||||
const { data: dashboard } = dashboardResponse({
|
||||
panels: 0,
|
||||
sectioned: false,
|
||||
variables: [],
|
||||
locked: false,
|
||||
});
|
||||
|
||||
jest.mock('../../hooks/useDashboardEditContext', () => ({
|
||||
useDashboardEditContext: (): unknown => ({
|
||||
isEditable: false,
|
||||
editChecks: [],
|
||||
editDisabledTooltip: '',
|
||||
}),
|
||||
}));
|
||||
jest.mock('../hooks/useVariableSelection', () => ({
|
||||
useVariableSelection: (): unknown => ({
|
||||
variables: [{ name: 'env' }],
|
||||
selection: {},
|
||||
setSelection: jest.fn(),
|
||||
autoSelect: jest.fn(),
|
||||
}),
|
||||
}));
|
||||
jest.mock('../components/VariableSelector/VariableSelector', () => ({
|
||||
__esModule: true,
|
||||
default: (): JSX.Element => <div data-testid="variable-selector" />,
|
||||
}));
|
||||
|
||||
function renderBar(readOnly: boolean, controls?: DashboardControlsInput): void {
|
||||
useDashboardStore.getState().setEditContext({
|
||||
dashboardId: dashboard.id,
|
||||
refetch: jest.fn(),
|
||||
readOnly,
|
||||
controls,
|
||||
});
|
||||
render(<VariablesBar dashboard={dashboard} />);
|
||||
}
|
||||
|
||||
describe('VariablesBar - controls', () => {
|
||||
afterEach(() => {
|
||||
useDashboardStore
|
||||
.getState()
|
||||
.setEditContext({ dashboardId: '', refetch: jest.fn() });
|
||||
});
|
||||
|
||||
it('offers the add-variable trigger, disabled, to a viewer', () => {
|
||||
renderBar(false);
|
||||
|
||||
expect(screen.getByTestId('dashboard-variables-add')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders the selectors but no add-variable trigger', () => {
|
||||
renderBar(true);
|
||||
|
||||
expect(screen.getByTestId('variable-selector')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('dashboard-variables-add'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders no add-variable trigger when the host hides it', () => {
|
||||
renderBar(false, { toolbar: { addVariable: false } });
|
||||
|
||||
expect(
|
||||
screen.queryByTestId('dashboard-variables-add'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -68,6 +68,49 @@ describe('useSeedVariableSelection', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps URL values a custom list does not offer, as typed values', () => {
|
||||
mockUrlValues = { ops: ['overflow_operation', 'GET /cart'] };
|
||||
const dash = dashboard('d1', [
|
||||
model({
|
||||
name: 'ops',
|
||||
type: 'CUSTOM',
|
||||
multiSelect: true,
|
||||
customValue: 'overflow_operation',
|
||||
}),
|
||||
]);
|
||||
|
||||
renderHook(() => useSeedVariableSelection(dash));
|
||||
|
||||
expect(seededValue('d1', 'ops')).toStrictEqual({
|
||||
value: ['overflow_operation', 'GET /cart'],
|
||||
allSelected: false,
|
||||
customValues: ['GET /cart'],
|
||||
});
|
||||
});
|
||||
|
||||
it('marks typed URL values even when the store already holds them unmarked', () => {
|
||||
useDashboardStore.getState().setVariableValues('d1', {
|
||||
ops: { value: ['overflow_operation', 'GET /cart'], allSelected: false },
|
||||
});
|
||||
mockUrlValues = { ops: ['overflow_operation', 'GET /cart'] };
|
||||
const dash = dashboard('d1', [
|
||||
model({
|
||||
name: 'ops',
|
||||
type: 'CUSTOM',
|
||||
multiSelect: true,
|
||||
customValue: 'overflow_operation',
|
||||
}),
|
||||
]);
|
||||
|
||||
renderHook(() => useSeedVariableSelection(dash));
|
||||
|
||||
expect(seededValue('d1', 'ops')).toStrictEqual({
|
||||
value: ['overflow_operation', 'GET /cart'],
|
||||
allSelected: false,
|
||||
customValues: ['GET /cart'],
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back to the stored value when the URL has no entry', () => {
|
||||
useDashboardStore
|
||||
.getState()
|
||||
|
||||
@@ -128,6 +128,47 @@ describe('useVariableSelection — setSelection', () => {
|
||||
expect(svcCycleId()).toBe(before + 1);
|
||||
});
|
||||
|
||||
it('drops an auto-fill when the selection moves before it flushes', async () => {
|
||||
const { result } = renderHook(() => useVariableSelection(dashboard));
|
||||
act(() => {
|
||||
result.current.setSelection('env', { value: ['a'], allSelected: false });
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.autoSelect('env', { value: ['a', 'b'], allSelected: false });
|
||||
});
|
||||
act(() => {
|
||||
result.current.setSelection('env', { value: ['c'], allSelected: false });
|
||||
});
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
|
||||
});
|
||||
|
||||
expect(useDashboardStore.getState().variableValues.d1?.env).toStrictEqual({
|
||||
value: ['c'],
|
||||
allSelected: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('drops an auto-fill when the seed commits a first value before it flushes', async () => {
|
||||
const { result } = renderHook(() => useVariableSelection(dashboard));
|
||||
|
||||
act(() => {
|
||||
result.current.autoSelect('env', { value: ['a'], allSelected: false });
|
||||
});
|
||||
act(() => {
|
||||
result.current.setSelection('env', { value: ['x'], allSelected: false });
|
||||
});
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
|
||||
});
|
||||
|
||||
expect(useDashboardStore.getState().variableValues.d1?.env).toStrictEqual({
|
||||
value: ['x'],
|
||||
allSelected: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('still cascades a genuine change', () => {
|
||||
const { result } = renderHook(() => useVariableSelection(dashboard));
|
||||
|
||||
|
||||
@@ -71,6 +71,15 @@ function fromUrlValue(
|
||||
if (raw === ALL_SELECTED && model.multiSelect && model.showAllOption) {
|
||||
return { value: null, allSelected: true };
|
||||
}
|
||||
// Values a link carries that the custom list doesn't offer were typed by whoever
|
||||
// made it (or set by a host page); keep them as typed instead of dropping them.
|
||||
if (model.type === 'CUSTOM' && model.multiSelect && Array.isArray(raw)) {
|
||||
const options = knownVariableOptions(model);
|
||||
const customValues = raw.map(String).filter((v) => !options.includes(v));
|
||||
if (customValues.length > 0) {
|
||||
return { value: raw, allSelected: false, customValues };
|
||||
}
|
||||
}
|
||||
return { value: raw, allSelected: false };
|
||||
}
|
||||
|
||||
|
||||
@@ -119,12 +119,30 @@ export function useVariableSelection(
|
||||
// store write + one `enqueueDescendantsBatch` means dependents re-fetch once
|
||||
// with the settled parent values, instead of once per fill.
|
||||
const pendingAutoFillRef = useRef<VariableSelectionMap>({});
|
||||
// The selection each pending fill was computed from.
|
||||
const pendingAutoFillBaseRef = useRef<
|
||||
Record<string, VariableSelection | undefined>
|
||||
>({});
|
||||
const autoFillFrameRef = useRef<number | null>(null);
|
||||
|
||||
const flushAutoFills = useCallback((): void => {
|
||||
autoFillFrameRef.current = null;
|
||||
const fills = pendingAutoFillRef.current;
|
||||
const bases = pendingAutoFillBaseRef.current;
|
||||
pendingAutoFillRef.current = {};
|
||||
pendingAutoFillBaseRef.current = {};
|
||||
// A fill reconciles the selection it saw. If that selection has moved since (the
|
||||
// seed committed a typed value, the user picked one), the fill answers a question
|
||||
// nobody is asking any more and would overwrite the newer value.
|
||||
Object.keys(fills).forEach((name) => {
|
||||
const base = bases[name];
|
||||
const latest = selectionRef.current[name];
|
||||
const hasSelectionMoved =
|
||||
base && latest ? !areSelectionsEqual(base, latest) : base !== latest;
|
||||
if (hasSelectionMoved) {
|
||||
delete fills[name];
|
||||
}
|
||||
});
|
||||
const names = Object.keys(fills);
|
||||
if (names.length === 0 || !dashboardId) {
|
||||
return;
|
||||
@@ -146,6 +164,9 @@ export function useVariableSelection(
|
||||
|
||||
const autoSelect = useCallback(
|
||||
(name: string, next: VariableSelection): void => {
|
||||
if (!(name in pendingAutoFillBaseRef.current)) {
|
||||
pendingAutoFillBaseRef.current[name] = selectionRef.current[name];
|
||||
}
|
||||
pendingAutoFillRef.current[name] = next;
|
||||
if (autoFillFrameRef.current == null) {
|
||||
autoFillFrameRef.current = requestAnimationFrame(flushAutoFills);
|
||||
|
||||
@@ -237,13 +237,14 @@ function valueSetKey(value: SelectedVariableValue): string {
|
||||
return list.map(String).sort().join('||');
|
||||
}
|
||||
|
||||
/** True when two selections carry the same ALL flag and the same value set. */
|
||||
/** True when two selections carry the same ALL flag, value set and typed values. */
|
||||
export function areSelectionsEqual(
|
||||
a: VariableSelection,
|
||||
b: VariableSelection,
|
||||
): boolean {
|
||||
return (
|
||||
!!a.allSelected === !!b.allSelected &&
|
||||
valueSetKey(a.value) === valueSetKey(b.value)
|
||||
valueSetKey(a.value) === valueSetKey(b.value) &&
|
||||
valueSetKey(a.customValues ?? []) === valueSetKey(b.customValues ?? [])
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { useQuery } from 'react-query';
|
||||
import type {
|
||||
DashboardtypesGettableDashboardV2DTO,
|
||||
GetDashboardV2200,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import { dashboardResponse } from '../../stories/__story_mockdata__/dashboard';
|
||||
import { DEFAULT_CONTROLS } from '../controls/dashboardControls';
|
||||
import type { DashboardControlsInput } from '../controls/types';
|
||||
import DashboardContainer from '../index';
|
||||
import type { DashboardQuerySource } from '../store/slices/editContextSlice';
|
||||
|
||||
const QUERY_KEY = ['lockdown-dashboard'];
|
||||
|
||||
const ALL_CONTROLS_OFF = Object.fromEntries(
|
||||
Object.keys(DEFAULT_CONTROLS).map((group) => [group, false]),
|
||||
) as DashboardControlsInput;
|
||||
|
||||
const select = (
|
||||
response: GetDashboardV2200,
|
||||
): DashboardtypesGettableDashboardV2DTO => response.data;
|
||||
const SOURCE: DashboardQuerySource = { queryKey: QUERY_KEY, select };
|
||||
|
||||
/**
|
||||
* Interactive elements a host can't turn off: they read, never write, and the
|
||||
* page is unusable without them. Anything else here must be a control.
|
||||
*/
|
||||
const ALLOWED_TEST_ID_PREFIXES = [
|
||||
// Collapses a section in this browser only; it also carries the section title.
|
||||
'dashboard-section-toggle-',
|
||||
];
|
||||
|
||||
const INTERACTIVE =
|
||||
'button, a[href], input, select, textarea, [role="button"], [role="menuitem"], [role="combobox"], [role="switch"], [role="checkbox"]';
|
||||
|
||||
function LockdownHost({ panels }: { panels: number }): JSX.Element | null {
|
||||
const { data } = useQuery(QUERY_KEY, () =>
|
||||
dashboardResponse({
|
||||
panels,
|
||||
sectioned: panels > 0,
|
||||
variables: ['custom'],
|
||||
locked: false,
|
||||
}),
|
||||
);
|
||||
if (!data) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<DashboardContainer
|
||||
dashboard={data.data}
|
||||
refetch={jest.fn()}
|
||||
querySource={SOURCE}
|
||||
readOnly
|
||||
controls={ALL_CONTROLS_OFF}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function visibleInteractive(): Element[] {
|
||||
return Array.from(
|
||||
// oxlint-disable-next-line signoz/no-dom-node-access -- sweeps every interactive element, whatever role or test id it carries
|
||||
document.body.querySelectorAll(INTERACTIVE),
|
||||
).filter(
|
||||
// oxlint-disable-next-line signoz/no-dom-node-access -- a `hidden` ancestor is what hides it, not a queryable element
|
||||
(element) => !element.closest('[hidden]'),
|
||||
);
|
||||
}
|
||||
|
||||
function describeElement(element: Element): string {
|
||||
return (
|
||||
element.getAttribute('data-testid') ??
|
||||
`<${element.tagName.toLowerCase()} aria-label="${element.getAttribute('aria-label') ?? ''}">${element.textContent?.trim().slice(0, 40) ?? ''}`
|
||||
);
|
||||
}
|
||||
|
||||
function leakedInteractive(): string[] {
|
||||
return visibleInteractive()
|
||||
.map(describeElement)
|
||||
.filter(
|
||||
(id) => !ALLOWED_TEST_ID_PREFIXES.some((prefix) => id.startsWith(prefix)),
|
||||
);
|
||||
}
|
||||
|
||||
describe('DashboardContainer lockdown', () => {
|
||||
// A control a host can't switch off, or one read-only doesn't remove, fails here.
|
||||
it('renders nothing interactive with every control off on a read-only mount', async () => {
|
||||
render(<LockdownHost panels={3} />);
|
||||
|
||||
await screen.findAllByTestId(/^panel-/);
|
||||
|
||||
expect(leakedInteractive()).toStrictEqual([]);
|
||||
});
|
||||
|
||||
it('renders nothing interactive on an empty dashboard', async () => {
|
||||
render(<LockdownHost panels={0} />);
|
||||
|
||||
await screen.findByTestId('dashboard-empty-state');
|
||||
|
||||
expect(leakedInteractive()).toStrictEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { useQuery } from 'react-query';
|
||||
import type {
|
||||
DashboardtypesGettableDashboardV2DTO,
|
||||
GetDashboardV2200,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { act, render, screen } from 'tests/test-utils';
|
||||
|
||||
import { dashboardResponse } from '../../stories/__story_mockdata__/dashboard';
|
||||
import DashboardContainer from '../index';
|
||||
import type { DashboardQuerySource } from '../store/slices/editContextSlice';
|
||||
import { useDashboardStore } from '../store/useDashboardStore';
|
||||
|
||||
jest.mock('../DashboardSettings', () => ({
|
||||
__esModule: true,
|
||||
default: (): JSX.Element => <div data-testid="dashboard-settings" />,
|
||||
}));
|
||||
|
||||
const QUERY_KEY = ['settings-drawer-dashboard'];
|
||||
const select = (
|
||||
response: GetDashboardV2200,
|
||||
): DashboardtypesGettableDashboardV2DTO => response.data;
|
||||
const SOURCE: DashboardQuerySource = { queryKey: QUERY_KEY, select };
|
||||
|
||||
function Host(): JSX.Element | null {
|
||||
const { data } = useQuery(QUERY_KEY, () =>
|
||||
dashboardResponse({
|
||||
panels: 0,
|
||||
sectioned: false,
|
||||
variables: [],
|
||||
locked: false,
|
||||
}),
|
||||
);
|
||||
if (!data) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<DashboardContainer
|
||||
dashboard={data.data}
|
||||
refetch={jest.fn()}
|
||||
querySource={SOURCE}
|
||||
controls={{ dashboardActions: false }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
describe('DashboardContainer settings drawer', () => {
|
||||
it('opens on request when the host hides the dashboard actions', async () => {
|
||||
render(<Host />);
|
||||
await screen.findByTestId('dashboard-empty-state');
|
||||
|
||||
act(() => {
|
||||
useDashboardStore
|
||||
.getState()
|
||||
.requestSettings({ tab: 'Variables', addVariable: true });
|
||||
});
|
||||
|
||||
await expect(
|
||||
screen.findByTestId('dashboard-settings'),
|
||||
).resolves.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import { useQuery } from 'react-query';
|
||||
import type {
|
||||
DashboardtypesGettableDashboardV2DTO,
|
||||
GetDashboardV2200,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { render, waitFor } from 'tests/test-utils';
|
||||
|
||||
import { dashboardResponse } from '../../stories/__story_mockdata__/dashboard';
|
||||
import DashboardContainer from '../index';
|
||||
import type { DashboardQuerySource } from '../store/slices/editContextSlice';
|
||||
import { useDashboardStore } from '../store/useDashboardStore';
|
||||
|
||||
const QUERY_KEY = ['variable-seed-dashboard'];
|
||||
const select = (
|
||||
response: GetDashboardV2200,
|
||||
): DashboardtypesGettableDashboardV2DTO => response.data;
|
||||
const SOURCE: DashboardQuerySource = { queryKey: QUERY_KEY, select };
|
||||
|
||||
function withOperationsVariable(): GetDashboardV2200 {
|
||||
const response = dashboardResponse({
|
||||
panels: 0,
|
||||
sectioned: false,
|
||||
variables: [],
|
||||
locked: false,
|
||||
});
|
||||
response.data.spec.variables = [
|
||||
{
|
||||
kind: 'ListVariable',
|
||||
spec: {
|
||||
name: 'ops',
|
||||
display: { name: 'ops' },
|
||||
allowMultiple: true,
|
||||
allowAllValue: false,
|
||||
sort: 'none',
|
||||
plugin: {
|
||||
kind: 'signoz/CustomVariable',
|
||||
spec: { customValue: 'overflow_operation' },
|
||||
},
|
||||
},
|
||||
},
|
||||
] as GetDashboardV2200['data']['spec']['variables'];
|
||||
return response;
|
||||
}
|
||||
|
||||
function Host(): JSX.Element | null {
|
||||
const { data } = useQuery(QUERY_KEY, withOperationsVariable);
|
||||
if (!data) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<DashboardContainer
|
||||
dashboard={data.data}
|
||||
refetch={jest.fn()}
|
||||
querySource={SOURCE}
|
||||
readOnly
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
describe('DashboardContainer variable seeding', () => {
|
||||
it('keeps custom-variable values a link seeds that the list does not offer', async () => {
|
||||
const seeded = ['overflow_operation', 'GET /cart', 'POST /checkout'];
|
||||
render(<Host />, undefined, {
|
||||
initialRoute: `/?variables=${encodeURIComponent(JSON.stringify({ ops: seeded }))}`,
|
||||
});
|
||||
|
||||
// The selector's first auto-fill is scheduled for the next frame; let it run.
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
useDashboardStore.getState().variableValues[
|
||||
useDashboardStore.getState().dashboardId
|
||||
]?.ops?.value,
|
||||
).toStrictEqual(seeded),
|
||||
);
|
||||
await new Promise((resolve) => {
|
||||
requestAnimationFrame(resolve);
|
||||
});
|
||||
|
||||
expect(
|
||||
useDashboardStore.getState().variableValues[
|
||||
useDashboardStore.getState().dashboardId
|
||||
]?.ops?.value,
|
||||
).toStrictEqual(seeded);
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import { UpdateTimeInterval } from 'store/actions';
|
||||
import { act, render, screen } from 'tests/test-utils';
|
||||
import { getUnstableCurrentSearchParams } from 'utils/getUnstableCurrentSearchParams';
|
||||
|
||||
import { resolveControls } from '../controls/dashboardControls';
|
||||
import DashboardContainer from '../index';
|
||||
|
||||
jest.mock('store/actions', () => ({
|
||||
@@ -21,7 +22,11 @@ const mockSelectorMount = jest.fn() as jest.MockedFunction<
|
||||
const mockPanelMount = jest.fn() as jest.MockedFunction<
|
||||
(search: string) => void
|
||||
>;
|
||||
const mockStore = { resetVariableFetch: jest.fn(), setEditContext: jest.fn() };
|
||||
const mockStore = {
|
||||
resetVariableFetch: jest.fn(),
|
||||
setEditContext: jest.fn(),
|
||||
controls: resolveControls(undefined, false),
|
||||
};
|
||||
jest.mock('../store/useDashboardStore', () => ({
|
||||
useDashboardStore: (selector: (state: typeof mockStore) => unknown): unknown =>
|
||||
selector(mockStore),
|
||||
@@ -68,6 +73,13 @@ jest.mock('../components/LockedIndicator/LockedIndicator', () => ({
|
||||
__esModule: true,
|
||||
default: (): null => null,
|
||||
}));
|
||||
jest.mock(
|
||||
'../components/DashboardSettingsDrawer/DashboardSettingsDrawer',
|
||||
() => ({
|
||||
__esModule: true,
|
||||
default: (): null => null,
|
||||
}),
|
||||
);
|
||||
jest.mock(
|
||||
'../components/DashboardChangedDialog/DashboardChangedDialog',
|
||||
() => ({ __esModule: true, default: (): null => null }),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { memo } from 'react';
|
||||
import HeaderRightSection from 'components/HeaderRightSection/HeaderRightSection';
|
||||
|
||||
import { useDashboardControlGroup } from '../../controls/useDashboardControlGroup';
|
||||
import DashboardPageBreadcrumbs from './DashboardPageBreadcrumbs';
|
||||
import { useShareVariablesOption } from './useShareVariablesOption';
|
||||
|
||||
@@ -16,13 +17,16 @@ function DashboardPageHeader({
|
||||
image,
|
||||
}: DashboardPageHeaderProps): JSX.Element {
|
||||
const shareVariablesOption = useShareVariablesOption();
|
||||
const headerControls = useDashboardControlGroup('header');
|
||||
return (
|
||||
<div className={styles.dashboardPageHeader}>
|
||||
<DashboardPageBreadcrumbs title={title} image={image} />
|
||||
{headerControls.breadcrumbs && (
|
||||
<DashboardPageBreadcrumbs title={title} image={image} />
|
||||
)}
|
||||
<HeaderRightSection
|
||||
enableAnnouncements={false}
|
||||
enableShare
|
||||
enableFeedback
|
||||
enableShare={headerControls.share}
|
||||
enableFeedback={headerControls.feedback}
|
||||
shareModalExtraOption={shareVariablesOption}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import DashboardSettings from '../../DashboardSettings';
|
||||
import SettingsDrawer from '../../DashboardPageToolbar/SettingsDrawer';
|
||||
import { useDashboardStore } from '../../store/useDashboardStore';
|
||||
|
||||
interface DashboardSettingsDrawerProps {
|
||||
dashboard: DashboardtypesGettableDashboardV2DTO;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens on any `requestSettings` in the tree. Mounted by the container, so it
|
||||
* works whichever controls a host hides.
|
||||
*/
|
||||
function DashboardSettingsDrawer({
|
||||
dashboard,
|
||||
}: DashboardSettingsDrawerProps): JSX.Element {
|
||||
const settingsRequest = useDashboardStore((s) => s.settingsRequest);
|
||||
const clearSettingsRequest = useDashboardStore((s) => s.clearSettingsRequest);
|
||||
|
||||
return (
|
||||
<SettingsDrawer
|
||||
drawerTitle="Dashboard Configuration"
|
||||
isOpen={!!settingsRequest}
|
||||
destroyOnClose
|
||||
onClose={clearSettingsRequest}
|
||||
>
|
||||
<DashboardSettings dashboard={dashboard} />
|
||||
</SettingsDrawer>
|
||||
);
|
||||
}
|
||||
|
||||
export default DashboardSettingsDrawer;
|
||||
@@ -0,0 +1,64 @@
|
||||
import {
|
||||
CONTROL_WRITES_DASHBOARD,
|
||||
DEFAULT_CONTROLS,
|
||||
isControlVisible,
|
||||
resolveControls,
|
||||
} from '../dashboardControls';
|
||||
import type { DashboardControlId } from '../types';
|
||||
|
||||
const ALL_IDS = Object.keys(CONTROL_WRITES_DASHBOARD) as DashboardControlId[];
|
||||
|
||||
describe('resolveControls', () => {
|
||||
it('shows every control when the host passes nothing', () => {
|
||||
expect(resolveControls(undefined, false)).toStrictEqual(DEFAULT_CONTROLS);
|
||||
});
|
||||
|
||||
it('hides a whole group from one boolean', () => {
|
||||
const controls = resolveControls({ header: false }, false);
|
||||
|
||||
expect(controls.header).toStrictEqual({
|
||||
breadcrumbs: false,
|
||||
share: false,
|
||||
feedback: false,
|
||||
});
|
||||
expect(controls.title.name).toBe(true);
|
||||
});
|
||||
|
||||
it('hides single items and keeps the rest of the group', () => {
|
||||
const controls = resolveControls(
|
||||
{ panelActions: { createAlert: false } },
|
||||
false,
|
||||
);
|
||||
|
||||
expect(controls.panelActions.createAlert).toBe(false);
|
||||
expect(controls.panelActions.download).toBe(true);
|
||||
});
|
||||
|
||||
it('drops Rename when the host hides the title it edits', () => {
|
||||
const controls = resolveControls({ title: { name: false } }, false);
|
||||
|
||||
expect(controls.dashboardActions.rename).toBe(false);
|
||||
expect(controls.dashboardActions.clone).toBe(true);
|
||||
});
|
||||
|
||||
it('hides every writing control on a read-only mount, whatever the host asked', () => {
|
||||
const controls = resolveControls(
|
||||
{ dashboardActions: true, panelActions: { edit: true } },
|
||||
true,
|
||||
);
|
||||
|
||||
ALL_IDS.forEach((id) => {
|
||||
expect([id, isControlVisible(controls, id)]).toStrictEqual([
|
||||
id,
|
||||
!CONTROL_WRITES_DASHBOARD[id],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it('still lets the host hide non-writing controls on a read-only mount', () => {
|
||||
const controls = resolveControls({ panelActions: { download: false } }, true);
|
||||
|
||||
expect(controls.panelActions.download).toBe(false);
|
||||
expect(controls.panelActions.view).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import { resolveControls } from '../dashboardControls';
|
||||
import { CHARTS_ONLY, EMBEDDED, withControls } from '../presets';
|
||||
|
||||
describe('withControls', () => {
|
||||
it('adds an override group the preset leaves alone', () => {
|
||||
expect(
|
||||
withControls(EMBEDDED, { toolbar: { autoRefresh: false } }),
|
||||
).toStrictEqual({
|
||||
header: false,
|
||||
title: false,
|
||||
dashboardActions: false,
|
||||
toolbar: { autoRefresh: false },
|
||||
});
|
||||
});
|
||||
|
||||
it('turns single items back on inside a group the preset hides', () => {
|
||||
const merged = withControls(CHARTS_ONLY, { panelActions: { view: true } });
|
||||
const controls = resolveControls(merged, false);
|
||||
|
||||
expect(controls.panelActions.view).toBe(true);
|
||||
expect(controls.panelActions.download).toBe(false);
|
||||
expect(controls.panelActions.drilldown).toBe(false);
|
||||
});
|
||||
|
||||
it('lets a later whole-group boolean replace earlier items', () => {
|
||||
expect(
|
||||
withControls(
|
||||
{ panelActions: { createAlert: false } },
|
||||
{ panelActions: true },
|
||||
),
|
||||
).toStrictEqual({ panelActions: true });
|
||||
});
|
||||
|
||||
it('lets later items win over earlier ones', () => {
|
||||
expect(
|
||||
withControls(
|
||||
{ toolbar: { timeRange: false, autoRefresh: false } },
|
||||
{ toolbar: { timeRange: true } },
|
||||
),
|
||||
).toStrictEqual({ toolbar: { timeRange: true, autoRefresh: false } });
|
||||
});
|
||||
|
||||
it('cannot turn a writing control back on for a read-only mount', () => {
|
||||
const merged = withControls(EMBEDDED, { dashboardActions: { delete: true } });
|
||||
|
||||
expect(resolveControls(merged, true).dashboardActions.delete).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,147 @@
|
||||
import type {
|
||||
DashboardControlGroup,
|
||||
DashboardControlId,
|
||||
DashboardControls,
|
||||
DashboardControlsInput,
|
||||
} from './types';
|
||||
|
||||
export const DEFAULT_CONTROLS: DashboardControls = {
|
||||
header: { breadcrumbs: true, share: true, feedback: true },
|
||||
title: {
|
||||
name: true,
|
||||
description: true,
|
||||
tags: true,
|
||||
lock: true,
|
||||
publicBadge: true,
|
||||
},
|
||||
toolbar: {
|
||||
timeRange: true,
|
||||
autoRefresh: true,
|
||||
variables: true,
|
||||
addVariable: true,
|
||||
},
|
||||
dashboardActions: {
|
||||
fullscreen: true,
|
||||
rename: true,
|
||||
clone: true,
|
||||
lock: true,
|
||||
newSection: true,
|
||||
delete: true,
|
||||
configure: true,
|
||||
json: true,
|
||||
newPanel: true,
|
||||
},
|
||||
sectionActions: { addPanel: true, rename: true, clone: true, delete: true },
|
||||
panelActions: {
|
||||
view: true,
|
||||
edit: true,
|
||||
clone: true,
|
||||
download: true,
|
||||
createAlert: true,
|
||||
move: true,
|
||||
delete: true,
|
||||
drilldown: true,
|
||||
zoom: true,
|
||||
},
|
||||
viewModal: { switchToEdit: true },
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether each control writes to the dashboard. A read-only mount hides every
|
||||
* `true` here regardless of what the host asked for. Exhaustive, so a new
|
||||
* control can't ship without deciding.
|
||||
*/
|
||||
export const CONTROL_WRITES_DASHBOARD: Record<DashboardControlId, boolean> = {
|
||||
'header.breadcrumbs': false,
|
||||
'header.share': false,
|
||||
'header.feedback': false,
|
||||
'title.name': false,
|
||||
'title.description': false,
|
||||
'title.tags': false,
|
||||
'title.lock': true,
|
||||
'title.publicBadge': false,
|
||||
'toolbar.timeRange': false,
|
||||
'toolbar.autoRefresh': false,
|
||||
'toolbar.variables': false,
|
||||
'toolbar.addVariable': true,
|
||||
'dashboardActions.fullscreen': false,
|
||||
'dashboardActions.rename': true,
|
||||
'dashboardActions.clone': true,
|
||||
'dashboardActions.lock': true,
|
||||
'dashboardActions.newSection': true,
|
||||
'dashboardActions.delete': true,
|
||||
'dashboardActions.configure': true,
|
||||
// Opens read-only on a non-editable mount.
|
||||
'dashboardActions.json': false,
|
||||
'dashboardActions.newPanel': true,
|
||||
'sectionActions.addPanel': true,
|
||||
'sectionActions.rename': true,
|
||||
'sectionActions.clone': true,
|
||||
'sectionActions.delete': true,
|
||||
'panelActions.view': false,
|
||||
'panelActions.edit': true,
|
||||
'panelActions.clone': true,
|
||||
'panelActions.download': false,
|
||||
'panelActions.createAlert': false,
|
||||
'panelActions.move': true,
|
||||
'panelActions.delete': true,
|
||||
'panelActions.drilldown': false,
|
||||
'panelActions.zoom': false,
|
||||
'viewModal.switchToEdit': true,
|
||||
};
|
||||
|
||||
function resolveGroup<G extends DashboardControlGroup>(
|
||||
group: G,
|
||||
input: DashboardControlsInput | undefined,
|
||||
readOnly: boolean,
|
||||
): DashboardControls[G] {
|
||||
const defaults: Record<string, boolean> = DEFAULT_CONTROLS[group];
|
||||
const override = input?.[group] as
|
||||
| boolean
|
||||
| Partial<Record<string, boolean>>
|
||||
| undefined;
|
||||
const items = Object.keys(defaults).map((item): [string, boolean] => {
|
||||
const requested =
|
||||
typeof override === 'boolean'
|
||||
? override
|
||||
: (override?.[item] ?? defaults[item]);
|
||||
const writes =
|
||||
CONTROL_WRITES_DASHBOARD[`${group}.${item}` as DashboardControlId];
|
||||
return [item, requested && !(readOnly && writes)];
|
||||
});
|
||||
return Object.fromEntries(items) as DashboardControls[G];
|
||||
}
|
||||
|
||||
/** Host input over the defaults, then every writing control off when read-only. */
|
||||
export function resolveControls(
|
||||
input: DashboardControlsInput | undefined,
|
||||
readOnly: boolean,
|
||||
): DashboardControls {
|
||||
const title = resolveGroup('title', input, readOnly);
|
||||
const dashboardActions = resolveGroup('dashboardActions', input, readOnly);
|
||||
return {
|
||||
header: resolveGroup('header', input, readOnly),
|
||||
title,
|
||||
toolbar: resolveGroup('toolbar', input, readOnly),
|
||||
// Rename edits the title in place, so it needs the title shown.
|
||||
dashboardActions: {
|
||||
...dashboardActions,
|
||||
rename: dashboardActions.rename && title.name,
|
||||
},
|
||||
sectionActions: resolveGroup('sectionActions', input, readOnly),
|
||||
panelActions: resolveGroup('panelActions', input, readOnly),
|
||||
viewModal: resolveGroup('viewModal', input, readOnly),
|
||||
};
|
||||
}
|
||||
|
||||
export function hasVisibleControl(group: Record<string, boolean>): boolean {
|
||||
return Object.values(group).some(Boolean);
|
||||
}
|
||||
|
||||
export function isControlVisible(
|
||||
controls: DashboardControls,
|
||||
id: DashboardControlId,
|
||||
): boolean {
|
||||
const [group, item] = id.split('.') as [DashboardControlGroup, string];
|
||||
return (controls[group] as Record<string, boolean>)[item];
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { DEFAULT_CONTROLS } from './dashboardControls';
|
||||
import type {
|
||||
DashboardControlGroup,
|
||||
DashboardControls,
|
||||
DashboardControlsInput,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* The host page owns the header, the title row and the dashboard-level actions.
|
||||
* Layout presets only: `readOnly` stays a separate switch, so no preset can turn
|
||||
* a writing control back on.
|
||||
*/
|
||||
export const EMBEDDED: DashboardControlsInput = {
|
||||
header: false,
|
||||
title: false,
|
||||
dashboardActions: false,
|
||||
};
|
||||
|
||||
/** Embedded, and panels are just charts: no panel menu, no drilldown. Charts still zoom. */
|
||||
export const CHARTS_ONLY: DashboardControlsInput = {
|
||||
...EMBEDDED,
|
||||
panelActions: {
|
||||
view: false,
|
||||
edit: false,
|
||||
clone: false,
|
||||
download: false,
|
||||
createAlert: false,
|
||||
move: false,
|
||||
delete: false,
|
||||
drilldown: false,
|
||||
},
|
||||
};
|
||||
|
||||
type GroupInput<G extends DashboardControlGroup> =
|
||||
| boolean
|
||||
| Partial<DashboardControls[G]>;
|
||||
|
||||
function mergeGroup<G extends DashboardControlGroup>(
|
||||
group: G,
|
||||
base: GroupInput<G> | undefined,
|
||||
next: GroupInput<G> | undefined,
|
||||
): GroupInput<G> | undefined {
|
||||
if (next === undefined) {
|
||||
return base;
|
||||
}
|
||||
if (typeof next === 'boolean' || base === undefined) {
|
||||
return next;
|
||||
}
|
||||
// A whole-group boolean underneath expands to its items before the override.
|
||||
const expanded: Partial<DashboardControls[G]> =
|
||||
typeof base === 'boolean'
|
||||
? (Object.fromEntries(
|
||||
Object.keys(DEFAULT_CONTROLS[group]).map((item) => [item, base]),
|
||||
) as Partial<DashboardControls[G]>)
|
||||
: base;
|
||||
return { ...expanded, ...next };
|
||||
}
|
||||
|
||||
/** Merges presets and overrides; later inputs win, item by item. */
|
||||
export function withControls(
|
||||
...inputs: DashboardControlsInput[]
|
||||
): DashboardControlsInput {
|
||||
const groups = Object.keys(DEFAULT_CONTROLS) as DashboardControlGroup[];
|
||||
return inputs.reduce<DashboardControlsInput>((merged, input) => {
|
||||
const result: DashboardControlsInput = { ...merged };
|
||||
groups.forEach((group) => {
|
||||
const value = mergeGroup(group, merged[group], input[group]);
|
||||
if (value !== undefined) {
|
||||
(result as Record<string, unknown>)[group] = value;
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}, {});
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { PanelActionId } from '../PanelsAndSectionsLayout/Panel/PanelActionsMenu/panelActionMeta';
|
||||
|
||||
/** Every control a host can show or hide, grouped by where it renders. */
|
||||
export interface DashboardControls {
|
||||
header: { breadcrumbs: boolean; share: boolean; feedback: boolean };
|
||||
title: {
|
||||
name: boolean;
|
||||
description: boolean;
|
||||
tags: boolean;
|
||||
lock: boolean;
|
||||
publicBadge: boolean;
|
||||
};
|
||||
toolbar: {
|
||||
timeRange: boolean;
|
||||
autoRefresh: boolean;
|
||||
variables: boolean;
|
||||
addVariable: boolean;
|
||||
};
|
||||
dashboardActions: {
|
||||
fullscreen: boolean;
|
||||
rename: boolean;
|
||||
clone: boolean;
|
||||
lock: boolean;
|
||||
newSection: boolean;
|
||||
delete: boolean;
|
||||
configure: boolean;
|
||||
json: boolean;
|
||||
newPanel: boolean;
|
||||
};
|
||||
sectionActions: {
|
||||
addPanel: boolean;
|
||||
rename: boolean;
|
||||
clone: boolean;
|
||||
delete: boolean;
|
||||
};
|
||||
// Keyed by the panel menu's own ids, so a new panel action needs a control.
|
||||
// `drilldown` (click) and `zoom` (drag-select a time range) act on the chart itself.
|
||||
panelActions: Record<PanelActionId | 'drilldown' | 'zoom', boolean>;
|
||||
viewModal: { switchToEdit: boolean };
|
||||
}
|
||||
|
||||
export type DashboardControlGroup = keyof DashboardControls;
|
||||
|
||||
export type DashboardControlId = {
|
||||
[
|
||||
G in DashboardControlGroup
|
||||
]: `${G}.${Extract<keyof DashboardControls[G], string>}`;
|
||||
}[DashboardControlGroup];
|
||||
|
||||
/** A whole group as one boolean, or single items; omitted means shown. */
|
||||
export type DashboardControlsInput = {
|
||||
[G in DashboardControlGroup]?: boolean | Partial<DashboardControls[G]>;
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
import { useDashboardStore } from '../store/useDashboardStore';
|
||||
import { isControlVisible } from './dashboardControls';
|
||||
import type { DashboardControlId } from './types';
|
||||
|
||||
/**
|
||||
* Whether a control renders on this mount: the host's `controls`, with every
|
||||
* writing control off when read-only. Lock and permission state stay with
|
||||
* `useDashboardEditContext`, which decides disabled + reason.
|
||||
*/
|
||||
export function useDashboardControl(id: DashboardControlId): boolean {
|
||||
return useDashboardStore((s) => isControlVisible(s.controls, id));
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { useDashboardStore } from '../store/useDashboardStore';
|
||||
import type { DashboardControlGroup, DashboardControls } from './types';
|
||||
|
||||
/** Every control in a group, resolved for this mount (see `useDashboardControl`). */
|
||||
export function useDashboardControlGroup<G extends DashboardControlGroup>(
|
||||
group: G,
|
||||
): DashboardControls[G] {
|
||||
return useDashboardStore((s) => s.controls[group]);
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
buildDashboardUpdatePermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/dashboard.permissions';
|
||||
|
||||
import { useDashboardStore } from '../../store/useDashboardStore';
|
||||
import { useDashboardEditContext } from '../useDashboardEditContext';
|
||||
|
||||
const DASHBOARD_ID = 'dash-1';
|
||||
@@ -44,6 +45,23 @@ describe('useDashboardEditContext - AuthZ', () => {
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
server.resetHandlers();
|
||||
useDashboardStore.setState({ readOnly: false });
|
||||
});
|
||||
|
||||
// A host-forced view-only mount outranks every grant.
|
||||
it('is read-only on a read-only mount despite full permissions', async () => {
|
||||
server.use(setupAuthzAdmin());
|
||||
useDashboardStore.setState({ readOnly: true });
|
||||
|
||||
const { result } = renderGuard();
|
||||
|
||||
await waitFor(() =>
|
||||
expect(result.current.editDisabledTooltip).toBe('dashboard_read_only_here'),
|
||||
);
|
||||
expect(result.current.isEditable).toBe(false);
|
||||
expect(result.current.canEditDashboard).toBe(false);
|
||||
expect(result.current.canDeleteDashboard).toBe(false);
|
||||
expect(result.current.deleteDisabledTooltip).toBe('dashboard_read_only_here');
|
||||
});
|
||||
|
||||
describe('permission granted', () => {
|
||||
|
||||
@@ -1,57 +1,127 @@
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { omit } from 'lodash-es';
|
||||
import { QueryClient, QueryClientProvider } from 'react-query';
|
||||
import { renderHook } from 'tests/test-utils';
|
||||
import {
|
||||
type DashboardtypesGettableDashboardV2DTO,
|
||||
type DashboardtypesVariableDTO,
|
||||
DashboardtypesVariableEnvelopeGithubComSigNozSignozPkgTypesDashboardtypesTextVariableSpecDTOKind as TextVariableKind,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import { dashboardResponse } from '../../../stories/__story_mockdata__/dashboard';
|
||||
import type { DashboardQuerySource } from '../../store/slices/editContextSlice';
|
||||
import { useDashboardFetchRequired } from '../useDashboardFetchRequired';
|
||||
|
||||
const mockUseGetDashboardV2 = jest.fn();
|
||||
const QUERY_KEY = ['/api/v2/dashboards/dash-1'];
|
||||
const mockRefetch = jest.fn();
|
||||
let mockSource: DashboardQuerySource | null;
|
||||
|
||||
jest.mock(
|
||||
'pages/DashboardPage/DashboardContainer/store/useDashboardStore',
|
||||
() => ({
|
||||
useDashboardStore: (
|
||||
selector: (s: { dashboardId: string }) => unknown,
|
||||
): unknown => selector({ dashboardId: 'dash-1' }),
|
||||
selector: (s: {
|
||||
dashboardId: string;
|
||||
querySource: DashboardQuerySource | null;
|
||||
refetch: () => void;
|
||||
}) => unknown,
|
||||
): unknown =>
|
||||
selector({
|
||||
dashboardId: 'dash-1',
|
||||
querySource: mockSource,
|
||||
refetch: mockRefetch,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
jest.mock('api/generated/services/dashboard', () => ({
|
||||
useGetDashboardV2: (): unknown => mockUseGetDashboardV2(),
|
||||
}));
|
||||
function textVariable(name: string): DashboardtypesVariableDTO {
|
||||
return {
|
||||
kind: TextVariableKind.TextVariable,
|
||||
spec: { name, display: { name }, value: '' },
|
||||
};
|
||||
}
|
||||
|
||||
function dashboardWith(
|
||||
variables: DashboardtypesVariableDTO[],
|
||||
): DashboardtypesGettableDashboardV2DTO {
|
||||
const { data } = dashboardResponse({
|
||||
panels: 0,
|
||||
sectioned: false,
|
||||
variables: [],
|
||||
locked: false,
|
||||
});
|
||||
return { ...data, spec: { ...data.spec, variables } };
|
||||
}
|
||||
|
||||
function renderWithCache(
|
||||
cached?: unknown,
|
||||
): ReturnType<
|
||||
typeof renderHook<ReturnType<typeof useDashboardFetchRequired>, void>
|
||||
> {
|
||||
const queryClient = new QueryClient();
|
||||
if (cached !== undefined) {
|
||||
queryClient.setQueryData(mockSource?.queryKey ?? QUERY_KEY, cached);
|
||||
}
|
||||
return renderHook(() => useDashboardFetchRequired(), {
|
||||
wrapper: ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
describe('useDashboardFetchRequired', () => {
|
||||
it('returns the loaded dashboard and its variables', () => {
|
||||
const dashboard = {
|
||||
spec: { variables: [{ name: 'region' }, { name: 'tier' }] },
|
||||
};
|
||||
mockUseGetDashboardV2.mockReturnValue({ data: { data: dashboard } });
|
||||
beforeEach(() => {
|
||||
mockSource = null;
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useDashboardFetchRequired());
|
||||
it('reads the dashboards API entry when the host sets no source', () => {
|
||||
const variables = [textVariable('region'), textVariable('tier')];
|
||||
const dashboard = dashboardWith(variables);
|
||||
|
||||
const { result } = renderWithCache({ data: dashboard, status: 'success' });
|
||||
|
||||
expect(result.current.dashboard).toBe(dashboard);
|
||||
expect(result.current.variables).toStrictEqual([
|
||||
{ name: 'region' },
|
||||
{ name: 'tier' },
|
||||
]);
|
||||
expect(result.current.variables).toBe(variables);
|
||||
expect(result.current.refetch).toBe(mockRefetch);
|
||||
});
|
||||
|
||||
it("reads a host's own cache entry through its select", () => {
|
||||
const systemDashboard = { name: 'ai-o11y-overview', spec: {} };
|
||||
mockSource = {
|
||||
queryKey: ['/api/v2/dashboards/system/ai-o11y-overview'],
|
||||
select: (response: { data: typeof systemDashboard }) =>
|
||||
({
|
||||
...response.data,
|
||||
id: 'system-id',
|
||||
}) as DashboardtypesGettableDashboardV2DTO,
|
||||
};
|
||||
|
||||
const { result } = renderWithCache({ data: systemDashboard });
|
||||
|
||||
expect(result.current.dashboard).toStrictEqual({
|
||||
name: 'ai-o11y-overview',
|
||||
spec: {},
|
||||
id: 'system-id',
|
||||
});
|
||||
});
|
||||
|
||||
it('normalizes variables to an empty array when the spec has none', () => {
|
||||
mockUseGetDashboardV2.mockReturnValue({ data: { data: { spec: {} } } });
|
||||
|
||||
const { result } = renderHook(() => useDashboardFetchRequired());
|
||||
const dashboard = dashboardWith([]);
|
||||
// Older payloads omit `variables`, which the generated type marks required.
|
||||
const { result } = renderWithCache({
|
||||
data: { ...dashboard, spec: omit(dashboard.spec, 'variables') },
|
||||
});
|
||||
|
||||
expect(result.current.variables).toStrictEqual([]);
|
||||
});
|
||||
|
||||
it('throws when used outside a loaded dashboard subtree', () => {
|
||||
mockUseGetDashboardV2.mockReturnValue({ data: undefined });
|
||||
|
||||
it('throws when the source entry is empty', () => {
|
||||
// Suppress React's expected render-error logging for this case.
|
||||
const consoleError = jest
|
||||
.spyOn(console, 'error')
|
||||
.mockImplementation(() => undefined);
|
||||
|
||||
expect(() => renderHook(() => useDashboardFetchRequired())).toThrow(
|
||||
/outside a loaded dashboard subtree/,
|
||||
);
|
||||
expect(() => renderWithCache()).toThrow(/outside a loaded dashboard subtree/);
|
||||
|
||||
consoleError.mockRestore();
|
||||
});
|
||||
|
||||
@@ -8,7 +8,10 @@ import type {
|
||||
QueryRangeV5200,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import { useGetQueryRangeV5 } from '../useGetQueryRangeV5';
|
||||
import {
|
||||
useGetQueryRangeV5,
|
||||
type UseGetQueryRangeV5Args,
|
||||
} from '../useGetQueryRangeV5';
|
||||
|
||||
jest.mock('api/generated/services/querier', () => ({
|
||||
queryRangeV5: jest.fn(),
|
||||
@@ -111,3 +114,36 @@ describe('useGetQueryRangeV5 enabled gating', () => {
|
||||
expect(mockQueryRangeV5).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('useGetQueryRangeV5 host fetch', () => {
|
||||
it('fetches through the host fetch instead of query_range', async () => {
|
||||
mockQueryRangeV5.mockReset();
|
||||
const runQueryRange: jest.MockedFunction<
|
||||
NonNullable<UseGetQueryRangeV5Args['runQueryRange']>
|
||||
> = jest.fn();
|
||||
runQueryRange.mockResolvedValue({
|
||||
status: 'success',
|
||||
data: {},
|
||||
} as QueryRangeV5200);
|
||||
const wrapper = ({ children }: PropsWithChildren): JSX.Element => (
|
||||
<QueryClientProvider client={new QueryClient()}>
|
||||
{children}
|
||||
</QueryClientProvider>
|
||||
);
|
||||
|
||||
renderHook(
|
||||
() =>
|
||||
useGetQueryRangeV5({
|
||||
requestPayload: REQUEST,
|
||||
queryKey: KEY_A,
|
||||
enabled: true,
|
||||
runQueryRange,
|
||||
}),
|
||||
{ wrapper },
|
||||
);
|
||||
|
||||
await waitFor(() => expect(runQueryRange).toHaveBeenCalledTimes(1));
|
||||
expect(runQueryRange.mock.calls[0][0]).toBe(REQUEST);
|
||||
expect(mockQueryRangeV5).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -19,10 +19,12 @@ jest.mock('api/generated/services/dashboard', () => ({
|
||||
getGetDashboardV2QueryKey: jest.fn(() => ['/api/v2/dashboards/dash-1']),
|
||||
}));
|
||||
|
||||
let mockReadOnly = false;
|
||||
|
||||
jest.mock('../../store/useDashboardStore', () => ({
|
||||
useDashboardStore: jest.fn(
|
||||
(selector: (s: { dashboardId: string; isEditable: boolean }) => unknown) =>
|
||||
selector({ dashboardId: 'dash-1', isEditable: true }),
|
||||
(selector: (s: { dashboardId: string; readOnly: boolean }) => unknown) =>
|
||||
selector({ dashboardId: 'dash-1', readOnly: mockReadOnly }),
|
||||
),
|
||||
}));
|
||||
|
||||
@@ -35,6 +37,7 @@ const queryClient = {
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let captured: { fn: (ops: any) => unknown; options: any };
|
||||
let mockMutateAsync: jest.Mock;
|
||||
|
||||
function dashboardEnvelope(name: string): GetDashboardV2200 {
|
||||
return {
|
||||
@@ -50,10 +53,12 @@ const replaceNameOp = {
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockReadOnly = false;
|
||||
mockMutateAsync = jest.fn().mockResolvedValue(undefined);
|
||||
(useQueryClient as jest.Mock).mockReturnValue(queryClient);
|
||||
(useMutation as jest.Mock).mockImplementation((fn, options) => {
|
||||
captured = { fn, options };
|
||||
return { mutateAsync: jest.fn(), isLoading: false };
|
||||
return { mutateAsync: mockMutateAsync, isLoading: false };
|
||||
});
|
||||
renderHook(() => useOptimisticPatch());
|
||||
});
|
||||
@@ -119,4 +124,22 @@ describe('useOptimisticPatch', () => {
|
||||
// No follow-up GET (that could read stale data and flicker the UI back).
|
||||
expect(queryClient.invalidateQueries).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('patchAsync rejects without sending on a read-only mount', async () => {
|
||||
mockReadOnly = true;
|
||||
const { result } = renderHook(() => useOptimisticPatch());
|
||||
|
||||
await expect(result.current.patchAsync([replaceNameOp])).rejects.toThrow(
|
||||
'dashboard_read_only_here',
|
||||
);
|
||||
expect(mockMutateAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('patchAsync sends the ops when the mount is editable', async () => {
|
||||
const { result } = renderHook(() => useOptimisticPatch());
|
||||
|
||||
await result.current.patchAsync([replaceNameOp]);
|
||||
|
||||
expect(mockMutateAsync).toHaveBeenCalledWith([replaceNameOp]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,6 +4,7 @@ import { act, renderHook } from '@testing-library/react';
|
||||
import {
|
||||
type DashboardtypesPanelDTO,
|
||||
Querybuildertypesv5RequestTypeDTO,
|
||||
type QueryRangeV5200,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import type { PanelQueryCapabilities } from 'pages/DashboardPage/DashboardContainer/Panels/types/panelCapabilities';
|
||||
import {
|
||||
@@ -11,6 +12,8 @@ import {
|
||||
DASHBOARD_CACHE_TIME_ON_REFRESH_ENABLED,
|
||||
} from 'constants/queryCacheTime';
|
||||
|
||||
import type { QueryRunner } from '../../store/slices/editContextSlice';
|
||||
import { useDashboardStore } from '../../store/useDashboardStore';
|
||||
import { usePanelQuery } from '../usePanelQuery';
|
||||
import { useGetQueryRangeV5 } from '../useGetQueryRangeV5';
|
||||
|
||||
@@ -598,4 +601,57 @@ describe('usePanelQuery', () => {
|
||||
expect(cacheTime).toBe(DASHBOARD_CACHE_TIME_ON_REFRESH_ENABLED);
|
||||
});
|
||||
});
|
||||
|
||||
describe('with a host query runner', () => {
|
||||
const run: jest.MockedFunction<QueryRunner['run']> = jest.fn();
|
||||
run.mockResolvedValue({ status: 'success', data: {} } as QueryRangeV5200);
|
||||
const runner: QueryRunner = { key: 'public:abc', run };
|
||||
|
||||
beforeEach(() => {
|
||||
useDashboardStore.getState().setEditContext({
|
||||
dashboardId: 'd1',
|
||||
refetch: jest.fn(),
|
||||
queryRunner: runner,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
useDashboardStore
|
||||
.getState()
|
||||
.setEditContext({ dashboardId: '', refetch: jest.fn() });
|
||||
});
|
||||
|
||||
it('keys the cache by the runner and runs the query through it with the panel id', async () => {
|
||||
renderHook(() =>
|
||||
usePanelQuery({
|
||||
panel: builderPanel(),
|
||||
panelId: 'p1',
|
||||
queryCapabilities: TIME_SERIES_CAPABILITIES,
|
||||
}),
|
||||
);
|
||||
const [{ queryKey, runQueryRange, requestPayload }] =
|
||||
mockUseGetQueryRangeV5.mock.calls[0];
|
||||
|
||||
expect(queryKey).toContain('public:abc');
|
||||
await runQueryRange(requestPayload);
|
||||
expect(runner.run).toHaveBeenCalledWith({
|
||||
panelId: 'p1',
|
||||
requestPayload,
|
||||
signal: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('runs on query_range when no host runner is set', () => {
|
||||
renderHook(() =>
|
||||
usePanelQuery({
|
||||
panel: builderPanel(),
|
||||
panelId: 'p1',
|
||||
queryCapabilities: TIME_SERIES_CAPABILITIES,
|
||||
}),
|
||||
);
|
||||
const [{ runQueryRange }] = mockUseGetQueryRangeV5.mock.calls[0];
|
||||
|
||||
expect(runQueryRange).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -17,6 +17,7 @@ import { useDashboardFetchRequired } from './useDashboardFetchRequired';
|
||||
*/
|
||||
export function useDashboardEditContext(): DashboardEditContext {
|
||||
const { dashboard } = useDashboardFetchRequired();
|
||||
const readOnly = useDashboardStore((s) => s.readOnly);
|
||||
const {
|
||||
canRead,
|
||||
canEdit,
|
||||
@@ -24,12 +25,8 @@ export function useDashboardEditContext(): DashboardEditContext {
|
||||
editChecks,
|
||||
deletePermission,
|
||||
areOtherPermissionsLoading,
|
||||
} = useDashboardPermissions(dashboard.id);
|
||||
} = useDashboardPermissions(dashboard.id, { enabled: !readOnly });
|
||||
const { t } = useTranslation('dashboard');
|
||||
const readOnlyOverride = useDashboardStore(
|
||||
(s) => s.canEditDashboardOverride === false,
|
||||
);
|
||||
|
||||
const deleteChecks = useMemo(() => [deletePermission], [deletePermission]);
|
||||
|
||||
return deriveEditContext({
|
||||
@@ -44,6 +41,6 @@ export function useDashboardEditContext(): DashboardEditContext {
|
||||
locked: t('dashboard_locked'),
|
||||
readOnly: t('dashboard_read_only_here'),
|
||||
},
|
||||
readOnlyOverride,
|
||||
readOnlyOverride: readOnly,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,34 +1,52 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useQuery } from 'react-query';
|
||||
import { getGetDashboardV2QueryKey } from 'api/generated/services/dashboard';
|
||||
import type {
|
||||
DashboardtypesGettableDashboardV2DTO,
|
||||
DashboardtypesVariableDTO,
|
||||
GetDashboardV2200,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { useDashboardStore } from 'pages/DashboardPage/DashboardContainer/store/useDashboardStore';
|
||||
|
||||
import { useDashboardFetch } from './useDashboardFetch';
|
||||
import type { UseDashboardFetchResult } from './useDashboardFetch';
|
||||
|
||||
export interface UseDashboardFetchRequiredResult {
|
||||
/** Guaranteed present — the hook throws otherwise. */
|
||||
dashboard: DashboardtypesGettableDashboardV2DTO;
|
||||
/** Always an array, so callers skip `?? []` guards. */
|
||||
variables: DashboardtypesVariableDTO[];
|
||||
refetch: UseDashboardFetchResult['refetch'];
|
||||
refetch: () => void;
|
||||
}
|
||||
|
||||
const selectDashboardV2 = (
|
||||
response: GetDashboardV2200,
|
||||
): DashboardtypesGettableDashboardV2DTO => response.data;
|
||||
|
||||
/**
|
||||
* Dashboard accessor for components rendered inside a loaded dashboard subtree. The
|
||||
* root pages own the fetch and gate on a resolved dashboard before mounting their
|
||||
* subtree, so this reuses the shared react-query cache entry and throws if the
|
||||
* dashboard is missing — turning a silent `undefined` into a loud programmer error. It
|
||||
* also derives spec collections (`variables`) since the dashboard is guaranteed here.
|
||||
* root owns the fetch and publishes where it cached the dashboard
|
||||
* (`querySource`); this observes that entry without fetching, and throws if
|
||||
* it's empty — turning a silent `undefined` into a loud programmer error. It also
|
||||
* derives spec collections (`variables`) since the dashboard is guaranteed here.
|
||||
*
|
||||
* Prefer this over `useDashboardFetch` outside the two root pages; the
|
||||
* `signoz/no-dashboard-fetch-outside-root` lint rule enforces the split.
|
||||
*/
|
||||
export function useDashboardFetchRequired(): UseDashboardFetchRequiredResult {
|
||||
const dashboardId = useDashboardStore((s) => s.dashboardId);
|
||||
const { dashboard, refetch } = useDashboardFetch(dashboardId);
|
||||
const source = useDashboardStore((s) => s.querySource);
|
||||
const queryKey =
|
||||
source?.queryKey ?? getGetDashboardV2QueryKey({ id: dashboardId });
|
||||
const select = source?.select ?? selectDashboardV2;
|
||||
const refetch = useDashboardStore((s) => s.refetch);
|
||||
// Observe only: the root owns the request, so this never fetches.
|
||||
const { data: dashboard } = useQuery<
|
||||
never,
|
||||
unknown,
|
||||
DashboardtypesGettableDashboardV2DTO | undefined
|
||||
>({
|
||||
queryKey,
|
||||
select,
|
||||
enabled: false,
|
||||
});
|
||||
|
||||
const variables = useMemo(
|
||||
() => dashboard?.spec?.variables ?? [],
|
||||
@@ -39,7 +57,7 @@ export function useDashboardFetchRequired(): UseDashboardFetchRequiredResult {
|
||||
throw new Error(
|
||||
'useDashboardFetchRequired was used outside a loaded dashboard subtree — the ' +
|
||||
'dashboard is undefined. Only call it below a root page that gates rendering ' +
|
||||
'on useDashboardFetch (DashboardPage / PanelEditorPage).',
|
||||
'on its fetch and seeds the edit context (DashboardContainer / PanelEditorPage).',
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,9 @@ interface UseDashboardStaleCheck {
|
||||
export function useDashboardStaleCheck(
|
||||
dashboard: DashboardtypesGettableDashboardV2DTO,
|
||||
refetch: () => void,
|
||||
options?: { enabled?: boolean },
|
||||
): UseDashboardStaleCheck {
|
||||
const enabled = options?.enabled ?? true;
|
||||
const {
|
||||
id: dashboardId,
|
||||
updatedAt: loadedUpdatedAt,
|
||||
@@ -34,7 +36,7 @@ export function useDashboardStaleCheck(
|
||||
const [dismissedAt, setDismissedAt] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!dashboardId) {
|
||||
if (!dashboardId || !enabled) {
|
||||
return undefined;
|
||||
}
|
||||
const probe = async (): Promise<void> => {
|
||||
@@ -56,7 +58,7 @@ export function useDashboardStaleCheck(
|
||||
document.removeEventListener('visibilitychange', probe);
|
||||
window.removeEventListener('focus', probe);
|
||||
};
|
||||
}, [dashboardId]);
|
||||
}, [dashboardId, enabled]);
|
||||
|
||||
const serverUpdatedAt = server?.updatedAt;
|
||||
|
||||
|
||||
@@ -15,6 +15,11 @@ export interface UseGetQueryRangeV5Args {
|
||||
keepPreviousData?: boolean;
|
||||
/** Unused-entry TTL; callers drop to 0 under auto-refresh to bound cache growth (V1 parity). */
|
||||
cacheTime?: number;
|
||||
/** Replaces the `query_range` call; the caller keys the cache for it. */
|
||||
runQueryRange?: (
|
||||
requestPayload: Querybuildertypesv5QueryRangeRequestDTO,
|
||||
signal?: AbortSignal,
|
||||
) => Promise<QueryRangeV5200>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -49,6 +54,7 @@ export function useGetQueryRangeV5({
|
||||
enabled,
|
||||
keepPreviousData,
|
||||
cacheTime,
|
||||
runQueryRange,
|
||||
}: UseGetQueryRangeV5Args): UseQueryResult<QueryRangeV5200, Error> {
|
||||
const queryClient = useQueryClient();
|
||||
// An errored key has no data, so it is always stale; keep it enabled so
|
||||
@@ -57,7 +63,8 @@ export function useGetQueryRangeV5({
|
||||
|
||||
return useQuery<QueryRangeV5200, Error>({
|
||||
queryKey,
|
||||
queryFn: ({ signal }) => queryRangeV5(requestPayload, signal),
|
||||
queryFn: ({ signal }) =>
|
||||
(runQueryRange ?? queryRangeV5)(requestPayload, signal),
|
||||
enabled: enabled || hasErrored,
|
||||
retry: retryUnlessClientError,
|
||||
keepPreviousData,
|
||||
|
||||
@@ -39,6 +39,7 @@ export function useOptimisticPatch(
|
||||
const storeDashboardId = useDashboardStore((s) => s.dashboardId);
|
||||
const dashboardId = dashboardIdOverride ?? storeDashboardId;
|
||||
const { t } = useTranslation('dashboard');
|
||||
const readOnly = useDashboardStore((s) => s.readOnly);
|
||||
const queryClient = useQueryClient();
|
||||
const queryKey = getGetDashboardV2QueryKey({ id: dashboardId });
|
||||
|
||||
@@ -78,6 +79,10 @@ export function useOptimisticPatch(
|
||||
const { mutateAsync } = mutation;
|
||||
const patchAsync = useCallback(
|
||||
(ops: DashboardtypesJSONPatchOperationDTO[]): Promise<unknown> => {
|
||||
// The UI renders no edit affordance on a read-only mount, so reaching here is a bug.
|
||||
if (readOnly) {
|
||||
return Promise.reject(new Error(t('dashboard_read_only_here')));
|
||||
}
|
||||
// Defense-in-depth against a lock, read straight from the cache this hook
|
||||
// already owns. Permission is enforced by the UI and, definitively, by the
|
||||
// backend — checking it here would drag authz into every mutation.
|
||||
@@ -87,7 +92,7 @@ export function useOptimisticPatch(
|
||||
}
|
||||
return mutateAsync(ops);
|
||||
},
|
||||
[queryClient, queryKey, mutateAsync],
|
||||
[readOnly, queryClient, queryKey, mutateAsync, t],
|
||||
);
|
||||
|
||||
return {
|
||||
|
||||
@@ -2,7 +2,11 @@ import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useQueryClient } from 'react-query';
|
||||
// eslint-disable-next-line no-restricted-imports -- TODO: migrate global time selector off redux
|
||||
import { useSelector } from 'react-redux';
|
||||
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import type {
|
||||
DashboardtypesPanelDTO,
|
||||
Querybuildertypesv5QueryRangeRequestDTO,
|
||||
QueryRangeV5200,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
DASHBOARD_CACHE_TIME,
|
||||
DASHBOARD_CACHE_TIME_ON_REFRESH_ENABLED,
|
||||
@@ -126,6 +130,7 @@ export function usePanelQuery({
|
||||
// use it (V1 parity). Names come from the fetch context (all variables, even
|
||||
// unresolved ones); null before the variable bar initializes it.
|
||||
const dashboardId = useDashboardStore((s) => s.dashboardId);
|
||||
const queryRunner = useDashboardStore((s) => s.queryRunner);
|
||||
const variables = useDashboardStore(selectResolvedVariables(dashboardId));
|
||||
const fetchContext = useDashboardStore((s) => s.variableFetchContext);
|
||||
|
||||
@@ -233,6 +238,7 @@ export function usePanelQuery({
|
||||
// Only the variables this panel references re-key the cache, so an unrelated
|
||||
// variable change doesn't refetch it.
|
||||
scopedVariables,
|
||||
queryRunner?.key ?? null,
|
||||
],
|
||||
[
|
||||
panelId,
|
||||
@@ -249,10 +255,24 @@ export function usePanelQuery({
|
||||
offset,
|
||||
pageSize,
|
||||
scopedVariables,
|
||||
queryRunner?.key,
|
||||
],
|
||||
);
|
||||
|
||||
const runQueryRange = useMemo(
|
||||
() =>
|
||||
queryRunner
|
||||
? (
|
||||
payload: Querybuildertypesv5QueryRangeRequestDTO,
|
||||
signal?: AbortSignal,
|
||||
): Promise<QueryRangeV5200> =>
|
||||
queryRunner.run({ panelId, requestPayload: payload, signal })
|
||||
: undefined,
|
||||
[queryRunner, panelId],
|
||||
);
|
||||
|
||||
const response = useGetQueryRangeV5({
|
||||
runQueryRange,
|
||||
requestPayload,
|
||||
queryKey,
|
||||
enabled: enabled && runnable && !isWaitingOnVariable,
|
||||
|
||||
@@ -9,10 +9,18 @@ import PanelsAndSectionsLayout from './PanelsAndSectionsLayout';
|
||||
import { useResolvedVariables } from './hooks/useResolvedVariables';
|
||||
import { useSyncVariablesForSuggestions } from './hooks/useSyncVariablesForSuggestions';
|
||||
import { useDashboardStore } from './store/useDashboardStore';
|
||||
import type {
|
||||
DashboardQuerySource,
|
||||
QueryRunner,
|
||||
} from './store/slices/editContextSlice';
|
||||
import type { DashboardControlsInput } from './controls/types';
|
||||
import { hasVisibleControl } from './controls/dashboardControls';
|
||||
import { useDashboardControlGroup } from './controls/useDashboardControlGroup';
|
||||
import styles from './DashboardContainer.module.scss';
|
||||
import DashboardPageHeader from './components/DashboardPageHeader/DashboardPageHeader';
|
||||
import LockedIndicator from './components/LockedIndicator/LockedIndicator';
|
||||
import DashboardChangedDialog from './components/DashboardChangedDialog/DashboardChangedDialog';
|
||||
import DashboardSettingsDrawer from './components/DashboardSettingsDrawer/DashboardSettingsDrawer';
|
||||
import { useDashboardStaleCheck } from './hooks/useDashboardStaleCheck';
|
||||
import { useDashboardDefaultTime } from './hooks/useDashboardDefaultTime';
|
||||
import { resolveDashboardImage } from 'pages/DashboardPage/DashboardContainer/dashboardIcons';
|
||||
@@ -20,30 +28,28 @@ import { resolveDashboardImage } from 'pages/DashboardPage/DashboardContainer/da
|
||||
interface DashboardContainerProps {
|
||||
dashboard: DashboardtypesGettableDashboardV2DTO;
|
||||
refetch: () => void;
|
||||
/**
|
||||
* @deprecated
|
||||
* `canEditDashboardOverride` is a temporary solution to allow the dashboard to be view only.
|
||||
* This is only used for LLM Observability.
|
||||
* It will be removed in the future.
|
||||
* TODO: @Ashwin / @Abhi — remove when the final solution is implemented.
|
||||
*/
|
||||
canEditDashboardOverride?: boolean;
|
||||
/** Where the host cached `dashboard`; defaults to the dashboards API entry. */
|
||||
querySource?: DashboardQuerySource;
|
||||
/** View-only mount: no edit affordance, no write, no server freshness probe. */
|
||||
readOnly?: boolean;
|
||||
/** What renders; omitted controls are shown. Writing controls are off when read-only. */
|
||||
controls?: DashboardControlsInput;
|
||||
/** Runs panel queries; omitted runs them on `query_range`. */
|
||||
queryRunner?: QueryRunner;
|
||||
}
|
||||
|
||||
function DashboardContainer({
|
||||
dashboard,
|
||||
refetch,
|
||||
canEditDashboardOverride,
|
||||
querySource,
|
||||
readOnly = false,
|
||||
controls,
|
||||
queryRunner,
|
||||
}: DashboardContainerProps): JSX.Element | null {
|
||||
const spec = dashboard.spec;
|
||||
const isTimeInitialized = useDashboardDefaultTime(dashboard.id, spec.duration);
|
||||
const image = resolveDashboardImage(dashboard.image);
|
||||
const name = spec.display.name;
|
||||
|
||||
useEffect(() => {
|
||||
document.title = name;
|
||||
}, [name]);
|
||||
|
||||
// Store is app-level and outlives the page: clear transient variable fetch state on
|
||||
// unmount so the next visit doesn't inherit stale states / climbing cycle ids.
|
||||
const resetVariableFetch = useDashboardStore((s) => s.resetVariableFetch);
|
||||
@@ -57,7 +63,10 @@ function DashboardContainer({
|
||||
setEditContext({
|
||||
dashboardId: dashboard.id,
|
||||
refetch,
|
||||
canEditDashboardOverride,
|
||||
querySource,
|
||||
readOnly,
|
||||
controls,
|
||||
queryRunner,
|
||||
});
|
||||
|
||||
// Resolve the variable selection into the V5 query payload and publish it to
|
||||
@@ -68,7 +77,10 @@ function DashboardContainer({
|
||||
// suggests them ($variable) in the panel editor and dashboards-page builder.
|
||||
useSyncVariablesForSuggestions(dashboard);
|
||||
|
||||
const staleCheck = useDashboardStaleCheck(dashboard, refetch);
|
||||
const staleCheck = useDashboardStaleCheck(dashboard, refetch, {
|
||||
enabled: !readOnly,
|
||||
});
|
||||
const hasHeader = hasVisibleControl(useDashboardControlGroup('header'));
|
||||
|
||||
if (!isTimeInitialized) {
|
||||
return null;
|
||||
@@ -84,12 +96,13 @@ function DashboardContainer({
|
||||
<AutoRefreshTicker />
|
||||
) : (
|
||||
<>
|
||||
<DashboardPageHeader title={name} image={image} />
|
||||
{hasHeader && <DashboardPageHeader title={name} image={image} />}
|
||||
<DashboardPageToolbar dashboard={dashboard} handle={fullScreenHandle} />
|
||||
</>
|
||||
)}
|
||||
<PanelsAndSectionsLayout layouts={spec.layouts} panels={spec.panels} />
|
||||
{!!dashboard.locked && <LockedIndicator />}
|
||||
{!!dashboard.locked && !readOnly && <LockedIndicator />}
|
||||
{!readOnly && <DashboardSettingsDrawer dashboard={dashboard} />}
|
||||
<DashboardChangedDialog
|
||||
open={staleCheck.showPrompt}
|
||||
onReload={staleCheck.reload}
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import { useDashboardStore } from '../../useDashboardStore';
|
||||
import type { DashboardQuerySource } from '../editContextSlice';
|
||||
|
||||
const refetch = (): void => undefined;
|
||||
|
||||
const systemSource: DashboardQuerySource = {
|
||||
queryKey: ['/api/v2/dashboards/system/ai-o11y-overview'],
|
||||
select: (response: { data: DashboardtypesGettableDashboardV2DTO }) =>
|
||||
response.data,
|
||||
};
|
||||
|
||||
function store(): ReturnType<typeof useDashboardStore.getState> {
|
||||
return useDashboardStore.getState();
|
||||
}
|
||||
|
||||
describe('editContextSlice.setEditContext', () => {
|
||||
beforeEach(() => {
|
||||
store().setEditContext({ dashboardId: '', refetch });
|
||||
});
|
||||
|
||||
it('defaults to the dashboards API entry and an editable mount', () => {
|
||||
store().setEditContext({ dashboardId: 'dash-1', refetch });
|
||||
|
||||
expect(store().querySource).toBeNull();
|
||||
expect(store().readOnly).toBe(false);
|
||||
});
|
||||
|
||||
it("stores a host's source and read-only flag", () => {
|
||||
store().setEditContext({
|
||||
dashboardId: 'system',
|
||||
refetch,
|
||||
querySource: systemSource,
|
||||
readOnly: true,
|
||||
});
|
||||
|
||||
expect(store().querySource).toBe(systemSource);
|
||||
expect(store().readOnly).toBe(true);
|
||||
});
|
||||
|
||||
it('clears read-only when the next mount does not ask for it', () => {
|
||||
store().setEditContext({
|
||||
dashboardId: 'system',
|
||||
refetch,
|
||||
querySource: systemSource,
|
||||
readOnly: true,
|
||||
});
|
||||
store().setEditContext({ dashboardId: 'dash-1', refetch });
|
||||
|
||||
expect(store().readOnly).toBe(false);
|
||||
expect(store().querySource).toBeNull();
|
||||
});
|
||||
|
||||
// Called during render: a set on every call would re-render subscribers in a loop.
|
||||
it('is a no-op when called again with equal values', () => {
|
||||
store().setEditContext({ dashboardId: 'dash-1', refetch });
|
||||
const listener = jest.fn();
|
||||
const unsubscribe = useDashboardStore.subscribe(listener);
|
||||
|
||||
store().setEditContext({ dashboardId: 'dash-1', refetch });
|
||||
|
||||
expect(listener).not.toHaveBeenCalled();
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
it('is a no-op for an equal inline controls object', () => {
|
||||
store().setEditContext({
|
||||
dashboardId: 'dash-1',
|
||||
refetch,
|
||||
controls: { header: false },
|
||||
});
|
||||
const listener = jest.fn();
|
||||
const unsubscribe = useDashboardStore.subscribe(listener);
|
||||
|
||||
store().setEditContext({
|
||||
dashboardId: 'dash-1',
|
||||
refetch,
|
||||
controls: { header: false },
|
||||
});
|
||||
|
||||
expect(listener).not.toHaveBeenCalled();
|
||||
expect(store().controls.header.share).toBe(false);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
it('resolves controls against read-only', () => {
|
||||
store().setEditContext({ dashboardId: 'dash-1', refetch, readOnly: true });
|
||||
|
||||
expect(store().controls.panelActions.edit).toBe(false);
|
||||
expect(store().controls.panelActions.view).toBe(true);
|
||||
});
|
||||
|
||||
it('treats a runner with the same key as unchanged, a new key as a change', () => {
|
||||
const run = jest.fn();
|
||||
store().setEditContext({
|
||||
dashboardId: 'dash-1',
|
||||
refetch,
|
||||
queryRunner: { key: 'public:a', run },
|
||||
});
|
||||
const listener = jest.fn();
|
||||
const unsubscribe = useDashboardStore.subscribe(listener);
|
||||
|
||||
store().setEditContext({
|
||||
dashboardId: 'dash-1',
|
||||
refetch,
|
||||
queryRunner: { key: 'public:a', run: jest.fn() },
|
||||
});
|
||||
expect(listener).not.toHaveBeenCalled();
|
||||
|
||||
store().setEditContext({
|
||||
dashboardId: 'dash-1',
|
||||
refetch,
|
||||
queryRunner: { key: 'public:b', run },
|
||||
});
|
||||
expect(store().queryRunner?.key).toBe('public:b');
|
||||
unsubscribe();
|
||||
});
|
||||
});
|
||||
@@ -1,24 +1,65 @@
|
||||
import { isEqual } from 'lodash-es';
|
||||
import type { QueryKey } from 'react-query';
|
||||
import type { StateCreator } from 'zustand';
|
||||
import type {
|
||||
DashboardtypesGettableDashboardV2DTO,
|
||||
Querybuildertypesv5QueryRangeRequestDTO,
|
||||
QueryRangeV5200,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import { resolveControls } from '../../controls/dashboardControls';
|
||||
import type {
|
||||
DashboardControls,
|
||||
DashboardControlsInput,
|
||||
} from '../../controls/types';
|
||||
import type { DashboardStore } from '../useDashboardStore';
|
||||
|
||||
/**
|
||||
* The one piece of page context the subtree can't derive for itself: which
|
||||
* dashboard is open, and how to refetch it. Editability is deliberately absent —
|
||||
* `useDashboardEditContext` derives it from the caches.
|
||||
* The react-query entry a host loaded the dashboard into, and how to read the
|
||||
* dashboard out of it. Must be referentially stable (module-level).
|
||||
*/
|
||||
export interface DashboardQuerySource {
|
||||
queryKey: QueryKey;
|
||||
// `never` accepts any host's response type; the one caller casts at the boundary.
|
||||
select: (response: never) => DashboardtypesGettableDashboardV2DTO | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a panel's query, when not via `POST /api/v5/query_range`. `key` joins
|
||||
* every panel cache key, so results from different runners never mix.
|
||||
*/
|
||||
export interface QueryRunner {
|
||||
key: string;
|
||||
run: (request: {
|
||||
panelId: string;
|
||||
requestPayload: Querybuildertypesv5QueryRangeRequestDTO;
|
||||
signal?: AbortSignal;
|
||||
}) => Promise<QueryRangeV5200>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The page context the subtree can't derive for itself: which dashboard is open,
|
||||
* where its cached copy lives, how to refetch it, and whether the host forces it
|
||||
* view-only. Editability is deliberately absent — `useDashboardEditContext`
|
||||
* derives it from the caches.
|
||||
*/
|
||||
export interface EditContextSlice {
|
||||
dashboardId: string;
|
||||
/** `null` reads the dashboards API entry for `dashboardId`. */
|
||||
querySource: DashboardQuerySource | null;
|
||||
refetch: () => void;
|
||||
/**
|
||||
* @deprecated Forces a view-only mount regardless of permissions. Used only by
|
||||
* LLM Observability; see SigNoz/pulse-pod#283.
|
||||
*/
|
||||
canEditDashboardOverride?: boolean;
|
||||
readOnly: boolean;
|
||||
/** Resolved: the host's `controls` over the defaults, writing ones off when read-only. */
|
||||
controls: DashboardControls;
|
||||
/** `null` runs panel queries on `query_range`. */
|
||||
queryRunner: QueryRunner | null;
|
||||
setEditContext: (ctx: {
|
||||
dashboardId: string;
|
||||
refetch: () => void;
|
||||
canEditDashboardOverride?: boolean;
|
||||
querySource?: DashboardQuerySource;
|
||||
readOnly?: boolean;
|
||||
controls?: DashboardControlsInput;
|
||||
queryRunner?: QueryRunner;
|
||||
}) => void;
|
||||
}
|
||||
|
||||
@@ -29,22 +70,37 @@ export const createEditContextSlice: StateCreator<
|
||||
EditContextSlice
|
||||
> = (set, get) => ({
|
||||
dashboardId: '',
|
||||
querySource: null,
|
||||
refetch: (): void => undefined,
|
||||
canEditDashboardOverride: undefined,
|
||||
readOnly: false,
|
||||
controls: resolveControls(undefined, false),
|
||||
queryRunner: null,
|
||||
// Idempotent (no-op when unchanged) so it's safe to call during render.
|
||||
setEditContext: (ctx): void => {
|
||||
const prev = get();
|
||||
const querySource = ctx.querySource ?? null;
|
||||
const readOnly = ctx.readOnly ?? false;
|
||||
// Hosts pass `controls` inline, so compare by value, not reference.
|
||||
const controls = resolveControls(ctx.controls, readOnly);
|
||||
const queryRunner = ctx.queryRunner ?? null;
|
||||
if (
|
||||
prev.dashboardId === ctx.dashboardId &&
|
||||
prev.refetch === ctx.refetch &&
|
||||
prev.canEditDashboardOverride === ctx.canEditDashboardOverride
|
||||
prev.readOnly === readOnly &&
|
||||
prev.querySource === querySource &&
|
||||
isEqual(prev.controls, controls) &&
|
||||
// The key identifies a runner, so an inline one doesn't re-seed on every render.
|
||||
prev.queryRunner?.key === queryRunner?.key
|
||||
) {
|
||||
return;
|
||||
}
|
||||
set({
|
||||
dashboardId: ctx.dashboardId,
|
||||
querySource,
|
||||
refetch: ctx.refetch,
|
||||
canEditDashboardOverride: ctx.canEditDashboardOverride,
|
||||
readOnly,
|
||||
controls,
|
||||
queryRunner,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
@@ -39,6 +39,12 @@ function DashboardPage(): JSX.Element {
|
||||
});
|
||||
}, [dashboard]);
|
||||
|
||||
useEffect(() => {
|
||||
if (dashboard) {
|
||||
document.title = dashboard.spec.display.name;
|
||||
}
|
||||
}, [dashboard]);
|
||||
|
||||
if (isLoading) {
|
||||
return <Spinner tip="Loading dashboard..." />;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
* Do not hand-edit: regenerate instead.
|
||||
*/
|
||||
|
||||
import { StatusCodes } from 'http-status-codes';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { rest } from 'msw';
|
||||
import type { QueryRangeRequestV5 } from 'types/api/v5/queryRange';
|
||||
@@ -16,15 +15,12 @@ import {
|
||||
LLM_MODELS,
|
||||
LLM_SERVICES,
|
||||
llmPanelResponse,
|
||||
llmSystemDashboardResponse,
|
||||
} from './__story_mockdata__/llmOverview';
|
||||
|
||||
const PANELS = 'AI overview · panels';
|
||||
|
||||
/**
|
||||
* The dashboard itself is bundled with the app rather than fetched, so the only
|
||||
* thing left to answer is the panels, the variables and the share state its
|
||||
* header reads.
|
||||
*/
|
||||
/** The system dashboard definition, its panels and its variables. */
|
||||
export const llmOverviewMocks = defineStoryMocks({
|
||||
controls: {
|
||||
series: countControl('Breakdown series', {
|
||||
@@ -36,6 +32,10 @@ export const llmOverviewMocks = defineStoryMocks({
|
||||
}),
|
||||
},
|
||||
handlers: (values, response) => [
|
||||
rest.get(
|
||||
'http://localhost/api/v2/dashboards/system/ai-o11y-overview',
|
||||
response.json(() => llmSystemDashboardResponse()),
|
||||
),
|
||||
rest.post(
|
||||
'http://localhost/api/v5/query_range',
|
||||
response.json(async (req) =>
|
||||
@@ -58,22 +58,6 @@ export const llmOverviewMocks = defineStoryMocks({
|
||||
};
|
||||
}),
|
||||
),
|
||||
// The header reads the share state on every load, so it answers even while
|
||||
// the panels are held in the loading or failed state.
|
||||
rest.get('http://localhost/api/v1/dashboards/:id/public', (_req, res, ctx) =>
|
||||
res(
|
||||
ctx.status(StatusCodes.NOT_FOUND),
|
||||
ctx.json({
|
||||
status: 'error',
|
||||
error: {
|
||||
code: 'public_dashboard_not_found',
|
||||
message: "the AI observability overview isn't public",
|
||||
url: '',
|
||||
errors: [],
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
],
|
||||
config: () => ({ route: ROUTES.AI_OBSERVABILITY_OVERVIEW }),
|
||||
});
|
||||
|
||||
@@ -11,8 +11,8 @@ type LLMOverviewArgs = PageStoryArgs<typeof llmOverviewMocks>;
|
||||
const pageStory = storyMocks(llmOverviewMocks, { layout: 'app' });
|
||||
|
||||
/**
|
||||
* The AI observability overview: cost, token and latency panels over
|
||||
* `query_range`.
|
||||
* The AI observability overview: the read-only system dashboard, with cost, token
|
||||
* and latency panels over `query_range`.
|
||||
*
|
||||
* Route: `/ai-observability/overview`.
|
||||
*/
|
||||
@@ -20,8 +20,7 @@ const meta = {
|
||||
title: 'Pages/AI Observability/Overview',
|
||||
component: LLMObservabilityPage,
|
||||
...pageStory,
|
||||
// The header's public-dashboard lookup is expected to 404, so every story opts out.
|
||||
parameters: { ...pageStory.parameters, allowConsoleErrors: true },
|
||||
parameters: { ...pageStory.parameters },
|
||||
} satisfies Meta<LLMOverviewArgs>;
|
||||
|
||||
export default meta;
|
||||
@@ -29,7 +28,7 @@ export default meta;
|
||||
type Story = StoryObj<LLMOverviewArgs>;
|
||||
|
||||
/**
|
||||
* The bundled overview dashboard: spend, tokens, latency and errors across
|
||||
* The system overview dashboard: spend, tokens, latency and errors across
|
||||
* every model the workspace calls, scoped by the model, environment and
|
||||
* service variables above it.
|
||||
*/
|
||||
|
||||
@@ -3,6 +3,13 @@
|
||||
* Do not hand-edit: regenerate instead.
|
||||
*/
|
||||
|
||||
import {
|
||||
DashboardtypesSourceDTO,
|
||||
type DashboardtypesGettableSystemDashboardDTO,
|
||||
type GetSystemDashboard200,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
// The backend's own definition, so the story renders what the server serves.
|
||||
import aiOverviewDefinition from '../../../../../../../pkg/modules/dashboard/impldashboard/fs/definitions/ai-o11y-overview.json';
|
||||
import type {
|
||||
MetricRangePayloadV5,
|
||||
QueryRangeRequestV5,
|
||||
@@ -161,3 +168,19 @@ export const llmPanelResponse = (
|
||||
},
|
||||
]);
|
||||
};
|
||||
|
||||
export function llmSystemDashboardResponse(): GetSystemDashboard200 {
|
||||
const { definition } = aiOverviewDefinition;
|
||||
return {
|
||||
status: 'success',
|
||||
data: {
|
||||
orgId: 'storybook-org',
|
||||
locked: true,
|
||||
source: DashboardtypesSourceDTO.system,
|
||||
name: definition.name,
|
||||
schemaVersion: definition.schemaVersion,
|
||||
tags: [],
|
||||
spec: definition.spec as DashboardtypesGettableSystemDashboardDTO['spec'],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -3,13 +3,11 @@
|
||||
* Do not hand-edit: regenerate instead.
|
||||
*/
|
||||
|
||||
import type {
|
||||
GetQuickFilters200,
|
||||
ListMetrics200,
|
||||
ListSavedViews200,
|
||||
TelemetrytypesTelemetryFieldKeyDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
type GetQuickFilters200,
|
||||
type ListMetrics200,
|
||||
type ListSavedViews200,
|
||||
type TelemetrytypesTelemetryFieldKeyDTO,
|
||||
MetrictypesTemporalityDTO,
|
||||
MetrictypesTypeDTO,
|
||||
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTOSignal as MetricsSignal,
|
||||
@@ -23,15 +21,11 @@ import {
|
||||
TelemetrytypesFieldDataTypeDTO,
|
||||
TelemetrytypesSourceDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { initialQueryBuilderFormValuesMap } from 'constants/queryBuilder';
|
||||
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { ReduceOperators } from 'types/common/queryBuilder';
|
||||
import type { Time } from 'container/TopNav/DateTimeSelectionV2/types';
|
||||
import {
|
||||
getLogCountWidgetData,
|
||||
getLogSizeWidgetData,
|
||||
getMetricCountWidgetData,
|
||||
getSpanCountWidgetData,
|
||||
getSpanSizeWidgetData,
|
||||
} from 'container/MeterExplorer/Breakdown/graphs';
|
||||
import type { Widgets } from 'types/api/widgets/widget';
|
||||
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import type { TimeSeries } from 'types/api/v5/queryRange';
|
||||
|
||||
@@ -248,20 +242,47 @@ export const meterTimeWindow = (range: MeterTimeRange): MeterTimeWindow => {
|
||||
return relativeWindow(24 * HOUR_IN_MS, '1d');
|
||||
};
|
||||
|
||||
const EXPLORER_WIDGETS: Record<MeterVolume, () => Widgets> = {
|
||||
'log-count': getLogCountWidgetData,
|
||||
'log-size': getLogSizeWidgetData,
|
||||
'span-count': getSpanCountWidgetData,
|
||||
'span-size': getSpanSizeWidgetData,
|
||||
'metric-datapoints': getMetricCountWidgetData,
|
||||
};
|
||||
/** The query the explorer starts on: the metric's hourly increase, summed. */
|
||||
export const meterExplorerQuery = (volume: MeterVolume): Query => {
|
||||
const metricName = VOLUME_METRICS[volume];
|
||||
|
||||
/**
|
||||
* The query the explorer starts on, taken from the breakdown widget for the
|
||||
* same metric so the story asks for what the page itself would build.
|
||||
*/
|
||||
export const meterExplorerQuery = (volume: MeterVolume): Query =>
|
||||
EXPLORER_WIDGETS[volume]().query;
|
||||
return {
|
||||
queryType: EQueryType.QUERY_BUILDER,
|
||||
promql: [],
|
||||
clickhouse_sql: [],
|
||||
id: `meter-explorer-${volume}`,
|
||||
builder: {
|
||||
queryFormulas: [],
|
||||
queryTraceOperator: [],
|
||||
queryData: [
|
||||
{
|
||||
...initialQueryBuilderFormValuesMap.metrics,
|
||||
aggregations: [
|
||||
{
|
||||
metricName,
|
||||
temporality: '',
|
||||
timeAggregation: 'increase',
|
||||
spaceAggregation: 'sum',
|
||||
reduceTo: ReduceOperators.SUM,
|
||||
},
|
||||
],
|
||||
aggregateAttribute: {
|
||||
dataType: DataTypes.Float64,
|
||||
key: metricName,
|
||||
id: `${metricName}--float64--Sum--true`,
|
||||
type: 'Sum',
|
||||
},
|
||||
aggregateOperator: 'increase',
|
||||
source: 'meter',
|
||||
legend: METRICS[metricName].unit === 'bytes' ? 'size' : 'count',
|
||||
reduceTo: ReduceOperators.SUM,
|
||||
spaceAggregation: 'sum',
|
||||
timeAggregation: 'increase',
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/** The metric picker in the query builder lists what the meter reports. */
|
||||
export const meterMetricsListResponse = (
|
||||
|
||||
@@ -142,7 +142,7 @@ const meterNotice =
|
||||
}
|
||||
|
||||
await screen.findByTestId(
|
||||
'meter-breakdown-section-total',
|
||||
'dashboard-section-sec-total-log-size',
|
||||
undefined,
|
||||
untilLoaded,
|
||||
);
|
||||
|
||||
@@ -3,7 +3,6 @@ package impltracedetail
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/http/binding"
|
||||
"github.com/SigNoz/signoz/pkg/http/render"
|
||||
"github.com/SigNoz/signoz/pkg/modules/tracedetail"
|
||||
@@ -129,27 +128,84 @@ func (h *handler) GetThread(rw http.ResponseWriter, r *http.Request) {
|
||||
render.Success(rw, http.StatusOK, result)
|
||||
}
|
||||
|
||||
// These routes are registered for their place in the API spec; the implementation follows.
|
||||
func (h *handler) GetTraceHighlights(rw http.ResponseWriter, _ *http.Request) {
|
||||
render.Error(rw, errors.New(errors.TypeUnsupported, errors.CodeUnsupported, "trace highlights is not implemented yet"))
|
||||
func (h *handler) GetTraceHighlights(rw http.ResponseWriter, r *http.Request) {
|
||||
claims, err := authtypes.ClaimsFromContext(r.Context())
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
params := new(spantypes.GetTraceHighlightsParams)
|
||||
if err := binding.Query.BindQuery(r.URL.Query(), params); err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
query, err := spantypes.NewTraceHighlightsQuery(params)
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.module.GetTraceHighlights(r.Context(), valuer.MustNewUUID(claims.OrgID), mux.Vars(r)["traceID"], query)
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
render.Success(rw, http.StatusOK, result)
|
||||
}
|
||||
|
||||
func (h *handler) ListTraceSpans(rw http.ResponseWriter, _ *http.Request) {
|
||||
render.Error(rw, errors.New(errors.TypeUnsupported, errors.CodeUnsupported, "trace span list is not implemented yet"))
|
||||
func (h *handler) GetTraceSpan(rw http.ResponseWriter, r *http.Request) {
|
||||
result, err := h.module.GetTraceSpan(r.Context(), mux.Vars(r)["traceID"], mux.Vars(r)["spanID"])
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
render.Success(rw, http.StatusOK, result)
|
||||
}
|
||||
|
||||
func (h *handler) GetTraceSpan(rw http.ResponseWriter, _ *http.Request) {
|
||||
render.Error(rw, errors.New(errors.TypeUnsupported, errors.CodeUnsupported, "trace span is not implemented yet"))
|
||||
func (h *handler) ListTraceSpans(rw http.ResponseWriter, r *http.Request) {
|
||||
h.listTraceSpans(rw, r, spantypes.SpanScopeTrace)
|
||||
}
|
||||
|
||||
func (h *handler) ListTraceSpanChildren(rw http.ResponseWriter, _ *http.Request) {
|
||||
render.Error(rw, errors.New(errors.TypeUnsupported, errors.CodeUnsupported, "trace span children is not implemented yet"))
|
||||
func (h *handler) ListTraceSpanChildren(rw http.ResponseWriter, r *http.Request) {
|
||||
h.listTraceSpans(rw, r, spantypes.SpanScopeChildren)
|
||||
}
|
||||
|
||||
func (h *handler) ListTraceSpanDescendants(rw http.ResponseWriter, _ *http.Request) {
|
||||
render.Error(rw, errors.New(errors.TypeUnsupported, errors.CodeUnsupported, "trace span descendants is not implemented yet"))
|
||||
func (h *handler) ListTraceSpanDescendants(rw http.ResponseWriter, r *http.Request) {
|
||||
h.listTraceSpans(rw, r, spantypes.SpanScopeDescendants)
|
||||
}
|
||||
|
||||
func (h *handler) ListTraceSpanAncestors(rw http.ResponseWriter, _ *http.Request) {
|
||||
render.Error(rw, errors.New(errors.TypeUnsupported, errors.CodeUnsupported, "trace span ancestors is not implemented yet"))
|
||||
func (h *handler) ListTraceSpanAncestors(rw http.ResponseWriter, r *http.Request) {
|
||||
h.listTraceSpans(rw, r, spantypes.SpanScopeAncestors)
|
||||
}
|
||||
|
||||
func (h *handler) listTraceSpans(rw http.ResponseWriter, r *http.Request, scope spantypes.SpanScope) {
|
||||
claims, err := authtypes.ClaimsFromContext(r.Context())
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
params := new(spantypes.ListTraceSpansParams)
|
||||
if err := binding.Query.BindQuery(r.URL.Query(), params); err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
query, err := spantypes.NewSpanListQuery(params, scope, mux.Vars(r)["spanID"])
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.module.ListTraceSpans(r.Context(), valuer.MustNewUUID(claims.OrgID), mux.Vars(r)["traceID"], query)
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
render.Success(rw, http.StatusOK, result)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/factory"
|
||||
"github.com/SigNoz/signoz/pkg/modules/tracedetail"
|
||||
"github.com/SigNoz/signoz/pkg/types/spantypes"
|
||||
@@ -292,3 +293,55 @@ func (m *module) getWindowedFlamegraph(ctx context.Context, traceID, selectedSpa
|
||||
enrichedSpans := flamegraphTrace.EnrichSelectedSpans(selectedSpans, fullSpans, selectFields)
|
||||
return spantypes.NewGettableFlamegraphTrace(enrichedSpans, start, end, true), nil
|
||||
}
|
||||
|
||||
func (m *module) GetTraceHighlights(ctx context.Context, orgID valuer.UUID, traceID string, query *spantypes.TraceHighlightsQuery) (*spantypes.TraceHighlights, error) {
|
||||
bounds, err := m.store.GetTraceBounds(ctx, traceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
skeleton, err := m.store.GetTraceSkeleton(ctx, orgID, traceID, bounds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return spantypes.NewTraceHighlights(skeleton, query), nil
|
||||
}
|
||||
|
||||
func (m *module) GetTraceSpan(ctx context.Context, traceID string, spanID string) (*spantypes.Span, error) {
|
||||
bounds, err := m.store.GetTraceBounds(ctx, traceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows, err := m.store.GetTraceSpansByIDs(ctx, traceID, bounds.Start, bounds.End, []string{spanID})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil, errors.NewNotFoundf(spantypes.ErrCodeTraceSpanNotFound, "span %s not found in trace %s", spanID, traceID)
|
||||
}
|
||||
return spantypes.NewSpan(traceID, &rows[0]), nil
|
||||
}
|
||||
|
||||
func (m *module) ListTraceSpans(ctx context.Context, orgID valuer.UUID, traceID string, query *spantypes.SpanListQuery) (*spantypes.SpanList, error) {
|
||||
bounds, err := m.store.GetTraceBounds(ctx, traceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
skeleton, err := m.store.GetTraceSkeleton(ctx, orgID, traceID, bounds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
page, err := spantypes.NewSpanListPage(skeleton, query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// The attributes of the page's spans are read only when the response shows some of them.
|
||||
var rows []spantypes.StorableSpan
|
||||
if len(query.SelectFields) > 0 {
|
||||
rows, err = m.store.GetTraceSpansByIDs(ctx, traceID, bounds.Start, bounds.End, page.SpanIDs())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return spantypes.NewSpanList(page, rows), nil
|
||||
}
|
||||
|
||||
@@ -24,11 +24,26 @@ import (
|
||||
|
||||
const colServiceName = `resource_string_service$$$$name` // $ gets escaped so $$$$ converts to $$.
|
||||
|
||||
// The collector marks an exception event with isError when it writes the span.
|
||||
const colHasExceptionEvent = `(NOT has_error AND arrayExists(e -> position(e, '"isError":true') > 0, events)) AS has_exception_event`
|
||||
|
||||
// The collector writes a span link as a FOLLOWS_FROM reference; the parent is a CHILD_OF one.
|
||||
const colHasLink = `(position(links, '"refType":"FOLLOWS_FROM"') > 0) AS has_link`
|
||||
|
||||
var genAIUsageValues = []struct{ key, alias string }{
|
||||
{aiobservabilitytypes.GenAIUsageInputTokens, "input_tokens_value"},
|
||||
{aiobservabilitytypes.GenAIUsageOutputTokens, "output_tokens_value"},
|
||||
{aiobservabilitytypes.GenAIUsageCacheReadInputTokens, "cache_read_tokens_value"},
|
||||
{aiobservabilitytypes.GenAIUsageCacheCreationInputTokens, "cache_write_tokens_value"},
|
||||
{aiobservabilitytypes.GenAIUsageReasoningOutputTokens, "reasoning_tokens_value"},
|
||||
{aiobservabilitytypes.SignozGenAITotalCost, "total_cost_value"},
|
||||
}
|
||||
|
||||
// storableSpanColumns are the columns a waterfall span scans. A row's legacy maps are blanked when its
|
||||
// JSON holds the attributes.
|
||||
var storableSpanColumns = []string{
|
||||
"DISTINCT ON (span_id) timestamp", "duration_nano", "span_id", "has_error", "kind",
|
||||
colServiceName, "name", "attributes", "resources_string", "scope",
|
||||
colServiceName, "name", "attributes", "resource", "scope",
|
||||
"if(notEmpty(attributes), map(), attributes_string) AS attributes_string",
|
||||
"if(notEmpty(attributes), map(), attributes_number) AS attributes_number",
|
||||
"if(notEmpty(attributes), map(), attributes_bool) AS attributes_bool",
|
||||
@@ -174,17 +189,8 @@ func (s *traceStore) GetTraceStats(ctx context.Context, orgID valuer.UUID, trace
|
||||
|
||||
// genAISpanColumns returns the gen_ai columns aggregated per span, resolved across attribute evolutions.
|
||||
func (s *traceStore) genAISpanColumns(ctx context.Context, orgID valuer.UUID, bounds *spantypes.TraceBounds, sb *sqlbuilder.SelectBuilder) ([]string, error) {
|
||||
values := []struct{ key, alias string }{
|
||||
{aiobservabilitytypes.GenAIUsageInputTokens, "input_tokens_value"},
|
||||
{aiobservabilitytypes.GenAIUsageOutputTokens, "output_tokens_value"},
|
||||
{aiobservabilitytypes.GenAIUsageCacheReadInputTokens, "cache_read_tokens_value"},
|
||||
{aiobservabilitytypes.GenAIUsageCacheCreationInputTokens, "cache_write_tokens_value"},
|
||||
{aiobservabilitytypes.GenAIUsageReasoningOutputTokens, "reasoning_tokens_value"},
|
||||
{aiobservabilitytypes.SignozGenAITotalCost, "total_cost_value"},
|
||||
}
|
||||
|
||||
names := slices.Clone(aiobservabilitytypes.GenAISpanGateKeys)
|
||||
for _, value := range values {
|
||||
for _, value := range genAIUsageValues {
|
||||
names = append(names, value.key)
|
||||
}
|
||||
keys, err := s.genAIFieldKeys(ctx, orgID, names)
|
||||
@@ -205,9 +211,17 @@ func (s *traceStore) genAISpanColumns(ctx context.Context, orgID valuer.UUID, bo
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
columns := []string{isGenAI + " AS is_gen_ai", isLLMCall + " AS is_llm_call", isToolCall + " AS is_tool_call"}
|
||||
usageColumns, err := s.genAIUsageColumns(ctx, q, keys)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return append([]string{isGenAI + " AS is_gen_ai", isLLMCall + " AS is_llm_call", isToolCall + " AS is_tool_call"}, usageColumns...), nil
|
||||
}
|
||||
|
||||
for _, value := range values {
|
||||
// genAIUsageColumns returns the token and cost columns of a span, resolved across attribute evolutions.
|
||||
func (s *traceStore) genAIUsageColumns(ctx context.Context, q qbtypes.QueryInfo, keys map[string][]*telemetrytypes.TelemetryFieldKey) ([]string, error) {
|
||||
columns := make([]string, 0, len(genAIUsageValues))
|
||||
for _, value := range genAIUsageValues {
|
||||
// lookup by number, the type metadata stores numeric attributes under; float64 is only the output cast
|
||||
// fixed gen_ai keys that many traces lack, so a not-found warning means nothing here
|
||||
expr, _, err := querybuilder.ResolveColumn(ctx, q, s.storage, attributeKey(value.key, telemetrytypes.FieldDataTypeNumber), telemetrytypes.FieldDataTypeFloat64, keys)
|
||||
@@ -301,7 +315,7 @@ func (s *traceStore) GetThreadSpans(ctx context.Context, orgID valuer.UUID, trac
|
||||
sb := sqlbuilder.NewSelectBuilder()
|
||||
sb.Select(
|
||||
"DISTINCT ON (span_id) timestamp", "duration_nano", "span_id", "parent_span_id", "has_error", "name", "kind_string",
|
||||
"status_code_string", "status_message", "resources_string",
|
||||
"status_code_string", "status_message", "resource",
|
||||
"attributes", "attributes_string", "attributes_number", "attributes_bool",
|
||||
"events", "links as references",
|
||||
)
|
||||
@@ -392,7 +406,7 @@ func (s *traceStore) GetFlamegraphSpans(ctx context.Context, traceID string, sta
|
||||
"if(notEmpty(attributes), map(), any(attributes_string)) AS attributes_string", // `attributes` below resolves to the aggregated alias
|
||||
"if(notEmpty(attributes), map(), any(attributes_number)) AS attributes_number",
|
||||
"if(notEmpty(attributes), map(), any(attributes_bool)) AS attributes_bool",
|
||||
"any(resources_string) AS resources_string",
|
||||
"any(resource) AS resource",
|
||||
"any(scope) AS scope",
|
||||
)
|
||||
sb.From(fmt.Sprintf("%s.%s", spantypes.TraceDB, spantypes.TraceTable))
|
||||
@@ -533,3 +547,74 @@ func (s *traceStore) anyExistsCondition(ctx context.Context, q qbtypes.QueryInfo
|
||||
}
|
||||
return sb.Or(conds...), nil
|
||||
}
|
||||
|
||||
func (s *traceStore) GetTraceSkeleton(ctx context.Context, orgID valuer.UUID, traceID string, bounds *spantypes.TraceBounds) (*spantypes.TraceSkeleton, error) {
|
||||
names := make([]string, 0, len(genAIUsageValues))
|
||||
for _, value := range genAIUsageValues {
|
||||
names = append(names, value.key)
|
||||
}
|
||||
keys, err := s.genAIFieldKeys(ctx, orgID, names)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
q := querybuilder.NewQueryInfo(ctx, orgID, s.flagger, telemetrytypes.SignalTraces, nil, uint64(bounds.Start.UnixNano()), uint64(bounds.End.UnixNano()))
|
||||
usageColumns, err := s.genAIUsageColumns(ctx, q, keys)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sb := sqlbuilder.NewSelectBuilder()
|
||||
// Empty for the usual value, one reference to the parent, which the tree rebuilds from the two ids.
|
||||
otherReferences := fmt.Sprintf("multiIf(links = concat(%s, trace_id, %s, parent_span_id, %s), '', links = '', '[]', links) AS other_references",
|
||||
sb.Var(`[{"traceId":"`), sb.Var(`","spanId":"`), sb.Var(`","refType":"CHILD_OF"}]`))
|
||||
sb.Select(
|
||||
"DISTINCT ON (span_id) span_id", "parent_span_id", "timestamp", "duration_nano", "has_error",
|
||||
"name", colServiceName, "kind_string", "response_status_code", "status_code_string", "status_message",
|
||||
colHasExceptionEvent, colHasLink, otherReferences,
|
||||
)
|
||||
sb.SelectMore(usageColumns...)
|
||||
sb.From(fmt.Sprintf("%s.%s", spantypes.TraceDB, spantypes.TraceTable))
|
||||
sb.Where(
|
||||
sb.E("trace_id", traceID),
|
||||
sb.GE("ts_bucket_start", bounds.Start.Unix()-1800),
|
||||
sb.LE("ts_bucket_start", bounds.End.Unix()),
|
||||
)
|
||||
sb.OrderByAsc("timestamp")
|
||||
sb.OrderByAsc("name")
|
||||
sb.OrderByAsc("span_id")
|
||||
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
|
||||
|
||||
rows, err := s.telemetryStore.ClickhouseDB().Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error querying trace skeleton")
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
builder := spantypes.NewTraceSkeletonBuilder(traceID, int(bounds.NumSpans))
|
||||
var span spantypes.SkeletonSpan
|
||||
// ScanStruct builds a new list of fields for every row; reusing one halves the time on a large trace.
|
||||
fields := []any{
|
||||
&span.SpanID, &span.ParentSpanID, &span.StartTime, &span.DurationNano, &span.HasError,
|
||||
&span.Name, &span.ServiceName, &span.KindString, &span.ResponseStatusCode, &span.StatusCodeString, &span.StatusMessage,
|
||||
&span.HasExceptionEvent, &span.HasLink, &span.OtherReferences,
|
||||
&span.AIUsage.InputTokens, &span.AIUsage.OutputTokens, &span.AIUsage.CacheReadTokens,
|
||||
&span.AIUsage.CacheWriteTokens, &span.AIUsage.ReasoningTokens, &span.AIUsage.Cost,
|
||||
}
|
||||
spanCount := 0
|
||||
for rows.Next() {
|
||||
// The builder keeps the usage values of a row, so every row gets its own.
|
||||
span.AIUsage = spantypes.AISpanUsage{}
|
||||
if err := rows.Scan(fields...); err != nil {
|
||||
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error scanning trace skeleton")
|
||||
}
|
||||
builder.Add(&span)
|
||||
spanCount++
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error reading trace skeleton")
|
||||
}
|
||||
if spanCount == 0 {
|
||||
return nil, spantypes.ErrTraceNotFound
|
||||
}
|
||||
return builder.Build(), nil
|
||||
}
|
||||
|
||||
@@ -154,7 +154,7 @@ func TestGetSpanCountByField(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestGetTraceSpans(t *testing.T) {
|
||||
expectedSQL := "SELECT DISTINCT ON (span_id) timestamp, duration_nano, span_id, has_error, kind, resource_string_service$$name, name, attributes, resources_string, scope, if(notEmpty(attributes), map(), attributes_string) AS attributes_string, if(notEmpty(attributes), map(), attributes_number) AS attributes_number, if(notEmpty(attributes), map(), attributes_bool) AS attributes_bool, events, status_message, status_code_string, kind_string, parent_span_id, flags, is_remote, trace_state, status_code, db_name, db_operation, http_method, http_url, http_host, external_http_method, external_http_url, response_status_code, links as references FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? ORDER BY timestamp ASC, name ASC"
|
||||
expectedSQL := "SELECT DISTINCT ON (span_id) timestamp, duration_nano, span_id, has_error, kind, resource_string_service$$name, name, attributes, resource, scope, if(notEmpty(attributes), map(), attributes_string) AS attributes_string, if(notEmpty(attributes), map(), attributes_number) AS attributes_number, if(notEmpty(attributes), map(), attributes_bool) AS attributes_bool, events, status_message, status_code_string, kind_string, parent_span_id, flags, is_remote, trace_state, status_code, db_name, db_operation, http_method, http_url, http_host, external_http_method, external_http_url, response_status_code, links as references FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? ORDER BY timestamp ASC, name ASC"
|
||||
|
||||
s := newTestStore(sqlmock.QueryMatcherEqual)
|
||||
s.Mock().ExpectSelect(expectedSQL).
|
||||
@@ -171,12 +171,12 @@ func TestGetFlamegraphSpans(t *testing.T) {
|
||||
}{
|
||||
{
|
||||
name: "NoSpanIDs_GeneratesBaseSQL",
|
||||
sql: "SELECT span_id, any(parent_span_id) AS parent_span_id, any(timestamp) AS timestamp, any(duration_nano) AS duration_nano, any(has_error) AS has_error, any(name) AS name, any(events) AS events, any(attributes) AS attributes, if(notEmpty(attributes), map(), any(attributes_string)) AS attributes_string, if(notEmpty(attributes), map(), any(attributes_number)) AS attributes_number, if(notEmpty(attributes), map(), any(attributes_bool)) AS attributes_bool, any(resources_string) AS resources_string, any(scope) AS scope FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? GROUP BY span_id ORDER BY timestamp ASC, name ASC",
|
||||
sql: "SELECT span_id, any(parent_span_id) AS parent_span_id, any(timestamp) AS timestamp, any(duration_nano) AS duration_nano, any(has_error) AS has_error, any(name) AS name, any(events) AS events, any(attributes) AS attributes, if(notEmpty(attributes), map(), any(attributes_string)) AS attributes_string, if(notEmpty(attributes), map(), any(attributes_number)) AS attributes_number, if(notEmpty(attributes), map(), any(attributes_bool)) AS attributes_bool, any(resource) AS resource, any(scope) AS scope FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? GROUP BY span_id ORDER BY timestamp ASC, name ASC",
|
||||
},
|
||||
{
|
||||
name: "WithSpanIDs_GeneratesInClauseSQL",
|
||||
spanIDs: []string{"span-1", "span-2"},
|
||||
sql: "SELECT span_id, any(parent_span_id) AS parent_span_id, any(timestamp) AS timestamp, any(duration_nano) AS duration_nano, any(has_error) AS has_error, any(name) AS name, any(events) AS events, any(attributes) AS attributes, if(notEmpty(attributes), map(), any(attributes_string)) AS attributes_string, if(notEmpty(attributes), map(), any(attributes_number)) AS attributes_number, if(notEmpty(attributes), map(), any(attributes_bool)) AS attributes_bool, any(resources_string) AS resources_string, any(scope) AS scope FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? AND span_id IN (?, ?) GROUP BY span_id ORDER BY timestamp ASC, name ASC",
|
||||
sql: "SELECT span_id, any(parent_span_id) AS parent_span_id, any(timestamp) AS timestamp, any(duration_nano) AS duration_nano, any(has_error) AS has_error, any(name) AS name, any(events) AS events, any(attributes) AS attributes, if(notEmpty(attributes), map(), any(attributes_string)) AS attributes_string, if(notEmpty(attributes), map(), any(attributes_number)) AS attributes_number, if(notEmpty(attributes), map(), any(attributes_bool)) AS attributes_bool, any(resource) AS resource, any(scope) AS scope FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? AND span_id IN (?, ?) GROUP BY span_id ORDER BY timestamp ASC, name ASC",
|
||||
},
|
||||
}
|
||||
|
||||
@@ -218,7 +218,7 @@ func TestGetSpanDurationByField(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestGetThreadSpans(t *testing.T) {
|
||||
selectSQL := "SELECT DISTINCT ON (span_id) timestamp, duration_nano, span_id, parent_span_id, has_error, name, kind_string, status_code_string, status_message, resources_string, attributes, attributes_string, attributes_number, attributes_bool, events, links as references"
|
||||
selectSQL := "SELECT DISTINCT ON (span_id) timestamp, duration_nano, span_id, parent_span_id, has_error, name, kind_string, status_code_string, status_message, resource, attributes, attributes_string, attributes_number, attributes_bool, events, links as references"
|
||||
fromSQL := " FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? AND "
|
||||
orderSQL := " ORDER BY timestamp ASC, span_id ASC LIMIT ?"
|
||||
jsonInsideTrace := testStart.Add(500 * time.Second)
|
||||
@@ -253,3 +253,39 @@ func TestGetThreadSpans(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetTraceSkeleton(t *testing.T) {
|
||||
jsonInsideTrace := testStart.Add(500 * time.Second)
|
||||
jsonBeforeTrace := testStart.Add(-500 * time.Second)
|
||||
fl := flaggertest.WithBooleanFlags(t, map[string]bool{flagger.FeatureUseTraceAttributesJSON.String(): true})
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
jsonRelease *time.Time
|
||||
expectedSQL string
|
||||
}{
|
||||
{
|
||||
name: "LegacyMaps",
|
||||
expectedSQL: "SELECT DISTINCT ON (span_id) span_id, parent_span_id, timestamp, duration_nano, has_error, name, resource_string_service$$name, kind_string, response_status_code, status_code_string, status_message, (NOT has_error AND arrayExists(e -> position(e, '\"isError\":true') > 0, events)) AS has_exception_event, (position(links, '\"refType\":\"FOLLOWS_FROM\"') > 0) AS has_link, multiIf(links = concat(?, trace_id, ?, parent_span_id, ?), '', links = '', '[]', links) AS other_references, multiIf(mapContains(attributes_number, 'gen_ai.usage.input_tokens'), toFloat64(attributes_number['gen_ai.usage.input_tokens']), NULL) AS input_tokens_value, multiIf(mapContains(attributes_number, 'gen_ai.usage.output_tokens'), toFloat64(attributes_number['gen_ai.usage.output_tokens']), NULL) AS output_tokens_value, multiIf(mapContains(attributes_number, 'gen_ai.usage.cache_read.input_tokens'), toFloat64(attributes_number['gen_ai.usage.cache_read.input_tokens']), NULL) AS cache_read_tokens_value, multiIf(mapContains(attributes_number, 'gen_ai.usage.cache_creation.input_tokens'), toFloat64(attributes_number['gen_ai.usage.cache_creation.input_tokens']), NULL) AS cache_write_tokens_value, multiIf(mapContains(attributes_number, 'gen_ai.usage.reasoning.output_tokens'), toFloat64(attributes_number['gen_ai.usage.reasoning.output_tokens']), NULL) AS reasoning_tokens_value, multiIf(mapContains(attributes_number, 'signoz.gen_ai.usage.tokens.cost'), toFloat64(attributes_number['signoz.gen_ai.usage.tokens.cost']), NULL) AS total_cost_value FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? ORDER BY timestamp ASC, name ASC, span_id ASC",
|
||||
},
|
||||
{
|
||||
name: "JSONEvolutionInsideTrace_ReadsBothColumns",
|
||||
jsonRelease: &jsonInsideTrace,
|
||||
expectedSQL: "SELECT DISTINCT ON (span_id) span_id, parent_span_id, timestamp, duration_nano, has_error, name, resource_string_service$$name, kind_string, response_status_code, status_code_string, status_message, (NOT has_error AND arrayExists(e -> position(e, '\"isError\":true') > 0, events)) AS has_exception_event, (position(links, '\"refType\":\"FOLLOWS_FROM\"') > 0) AS has_link, multiIf(links = concat(?, trace_id, ?, parent_span_id, ?), '', links = '', '[]', links) AS other_references, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.input_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.input_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.input_tokens'), attributes_number['gen_ai.usage.input_tokens'], NULL)) AS input_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.output_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.output_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.output_tokens'), attributes_number['gen_ai.usage.output_tokens'], NULL)) AS output_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.cache_read.input_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.cache_read.input_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.cache_read.input_tokens'), attributes_number['gen_ai.usage.cache_read.input_tokens'], NULL)) AS cache_read_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.cache_creation.input_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.cache_creation.input_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.cache_creation.input_tokens'), attributes_number['gen_ai.usage.cache_creation.input_tokens'], NULL)) AS cache_write_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`gen_ai.usage.reasoning.output_tokens`::String) IS NOT NULL, toFloat64OrNull(attributes.`gen_ai.usage.reasoning.output_tokens`::String), mapContains(attributes_number, 'gen_ai.usage.reasoning.output_tokens'), attributes_number['gen_ai.usage.reasoning.output_tokens'], NULL)) AS reasoning_tokens_value, toFloat64(multiIf(toFloat64OrNull(attributes.`signoz.gen_ai.usage.tokens.cost`::String) IS NOT NULL, toFloat64OrNull(attributes.`signoz.gen_ai.usage.tokens.cost`::String), mapContains(attributes_number, 'signoz.gen_ai.usage.tokens.cost'), attributes_number['signoz.gen_ai.usage.tokens.cost'], NULL)) AS total_cost_value FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? ORDER BY timestamp ASC, name ASC, span_id ASC",
|
||||
},
|
||||
{
|
||||
name: "JSONEvolutionBeforeTrace_ReadsJSONOnly",
|
||||
jsonRelease: &jsonBeforeTrace,
|
||||
expectedSQL: "SELECT DISTINCT ON (span_id) span_id, parent_span_id, timestamp, duration_nano, has_error, name, resource_string_service$$name, kind_string, response_status_code, status_code_string, status_message, (NOT has_error AND arrayExists(e -> position(e, '\"isError\":true') > 0, events)) AS has_exception_event, (position(links, '\"refType\":\"FOLLOWS_FROM\"') > 0) AS has_link, multiIf(links = concat(?, trace_id, ?, parent_span_id, ?), '', links = '', '[]', links) AS other_references, toFloat64OrNull(attributes.`gen_ai.usage.input_tokens`::String) AS input_tokens_value, toFloat64OrNull(attributes.`gen_ai.usage.output_tokens`::String) AS output_tokens_value, toFloat64OrNull(attributes.`gen_ai.usage.cache_read.input_tokens`::String) AS cache_read_tokens_value, toFloat64OrNull(attributes.`gen_ai.usage.cache_creation.input_tokens`::String) AS cache_write_tokens_value, toFloat64OrNull(attributes.`gen_ai.usage.reasoning.output_tokens`::String) AS reasoning_tokens_value, toFloat64OrNull(attributes.`signoz.gen_ai.usage.tokens.cost`::String) AS total_cost_value FROM signoz_traces.distributed_signoz_index_v3 WHERE trace_id = ? AND ts_bucket_start >= ? AND ts_bucket_start <= ? ORDER BY timestamp ASC, name ASC, span_id ASC",
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
s := newTestStoreWithMetadata(sqlmock.QueryMatcherEqual, genAIMetadataStore(testCase.jsonRelease), fl)
|
||||
s.Mock().ExpectQuery(testCase.expectedSQL).WithArgs(`[{"traceId":"`, `","spanId":"`, `","refType":"CHILD_OF"}]`, testTraceID, testStart.Unix()-1800, testEnd.Unix()).WillReturnRows(cmock.NewRows(nil, nil))
|
||||
_, _ = s.Store().GetTraceSkeleton(context.Background(), valuer.GenerateUUID(), testTraceID, testBounds)
|
||||
assert.NoError(t, s.Mock().ExpectationsWereMet())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,4 +31,7 @@ type Module interface {
|
||||
GetTraceAggregations(ctx context.Context, traceID string, req *spantypes.PostableTraceAggregations) (*spantypes.GettableTraceAggregations, error)
|
||||
GetFlamegraph(ctx context.Context, traceID string, selectedSpanID string, selectFields []telemetrytypes.TelemetryFieldKey) (*spantypes.GettableFlamegraphTrace, error)
|
||||
GetThread(ctx context.Context, orgID valuer.UUID, traceID string, query *spantypes.ThreadQuery) (*spantypes.GettableTraceThread, error)
|
||||
GetTraceHighlights(ctx context.Context, orgID valuer.UUID, traceID string, query *spantypes.TraceHighlightsQuery) (*spantypes.TraceHighlights, error)
|
||||
GetTraceSpan(ctx context.Context, traceID string, spanID string) (*spantypes.Span, error)
|
||||
ListTraceSpans(ctx context.Context, orgID valuer.UUID, traceID string, query *spantypes.SpanListQuery) (*spantypes.SpanList, error)
|
||||
}
|
||||
|
||||
@@ -73,11 +73,12 @@ func NewFlamegraphSpanFromStorable(s *StorableSpan, level int64, selectFields []
|
||||
return span
|
||||
}
|
||||
var attributes map[string]any
|
||||
resource := s.Resource()
|
||||
var scopeFields []string
|
||||
for _, field := range selectFields {
|
||||
switch field.FieldContext {
|
||||
case telemetrytypes.FieldContextResource:
|
||||
if v, ok := s.ResourcesString[field.Name]; ok && v != "" {
|
||||
if v, ok := resource[field.Name]; ok && v != "" {
|
||||
span.Resource[field.Name] = v
|
||||
}
|
||||
case telemetrytypes.FieldContextAttribute:
|
||||
|
||||
@@ -45,7 +45,7 @@ func TestNewFlamegraphSpanFromStorable_SelectFields(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "ResourceFields_EmptyValueSkipped",
|
||||
span: StorableSpan{ResourcesString: map[string]string{"service.name": "checkout", "deployment.environment": ""}},
|
||||
span: StorableSpan{ResourceJSON: jsonAttrs(map[string]any{"service.name": "checkout", "deployment.environment": ""})},
|
||||
selectFields: []telemetrytypes.TelemetryFieldKey{
|
||||
{Name: "service.name", FieldContext: telemetrytypes.FieldContextResource},
|
||||
{Name: "deployment.environment", FieldContext: telemetrytypes.FieldContextResource},
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
package spantypes
|
||||
|
||||
import (
|
||||
"maps"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
SpanListViewErrorOrigins SpanListView = "error_origins"
|
||||
SpanListViewUnmarkedFailures SpanListView = "unmarked_failures"
|
||||
@@ -15,6 +21,8 @@ const (
|
||||
UnmarkedFailureExceptionEvent UnmarkedFailureKind = "exception_event"
|
||||
)
|
||||
|
||||
var ErrCodeTraceSpanNotFound = errors.MustNewCode("trace_span_not_found")
|
||||
|
||||
// SpanListView keeps the spans of one kind out of the spans a route covers, in that kind's order.
|
||||
// It is a plain string so that a list of views binds from a repeated query parameter.
|
||||
type SpanListView string
|
||||
@@ -56,12 +64,54 @@ type Span struct {
|
||||
StatusCodeString string `json:"status_code_string" required:"true"`
|
||||
StatusMessage string `json:"status_message" required:"true" description:"Usually the error text."`
|
||||
ResponseStatusCode string `json:"response_status_code" required:"true" description:"HTTP or gRPC status code, for example 404."`
|
||||
HTTPMethod string `json:"http_method,omitempty" description:"Omitted when empty, and in a list unless selected."`
|
||||
HTTPURL string `json:"http_url,omitempty" description:"Omitted when empty, and in a list unless selected."`
|
||||
HTTPHost string `json:"http_host,omitempty" description:"Host or server address. Omitted when empty, and in a list unless selected."`
|
||||
ExternalHTTPMethod string `json:"external_http_method,omitempty" description:"Method of an outgoing HTTP call. Omitted when empty, and in a list unless selected."`
|
||||
ExternalHTTPURL string `json:"external_http_url,omitempty" description:"Host of an outgoing HTTP call. Omitted when empty, and in a list unless selected."`
|
||||
DBName string `json:"db_name,omitempty" description:"Omitted when empty, and in a list unless selected."`
|
||||
DBOperation string `json:"db_operation,omitempty" description:"Omitted when empty, and in a list unless selected."`
|
||||
TraceState string `json:"trace_state,omitempty" description:"W3C trace state. Omitted when empty, and in a list unless selected."`
|
||||
Scope Scope `json:"scope,omitempty" description:"Instrumentation scope. Omitted when empty, and in a list unless selected."`
|
||||
Resource map[string]string `json:"resource" required:"true" nullable:"false" description:"Always has service.name. All of them for a span read by ID; the selected ones in a list."`
|
||||
Attributes map[string]any `json:"attributes" required:"true" nullable:"false" description:"All of them for a span read by ID; the selected ones in a list."`
|
||||
Events []Event `json:"events" required:"true" nullable:"false" description:"All of them for a span read by ID; none in a list."`
|
||||
References []OtelSpanRef `json:"references" required:"true" nullable:"false" description:"The parent as CHILD_OF, and each span link as FOLLOWS_FROM."`
|
||||
}
|
||||
|
||||
// NewSpan returns the span with everything row stores on it: all attributes, resource attributes
|
||||
// and events.
|
||||
func NewSpan(traceID string, row *StorableSpan) *Span {
|
||||
span := &Span{
|
||||
SpanID: row.SpanID,
|
||||
TraceID: traceID,
|
||||
ParentSpanID: row.ParentSpanID,
|
||||
Name: row.Name,
|
||||
KindString: row.SpanKind,
|
||||
TimeUnix: uint64(row.StartTime.UnixMilli()),
|
||||
DurationNano: row.DurationNano,
|
||||
HasError: row.HasError,
|
||||
StatusCodeString: row.StatusCodeString,
|
||||
StatusMessage: row.StatusMessage,
|
||||
ResponseStatusCode: row.ResponseStatusCode,
|
||||
Resource: map[string]string{"service.name": row.ServiceName},
|
||||
Attributes: row.Attributes(),
|
||||
Events: row.UnmarshalledEvents(),
|
||||
References: row.UnmarshalledRefs(),
|
||||
HTTPMethod: row.HTTPMethod,
|
||||
HTTPURL: row.HTTPURL,
|
||||
HTTPHost: row.HTTPHost,
|
||||
ExternalHTTPMethod: row.ExternalHTTPMethod,
|
||||
ExternalHTTPURL: row.ExternalHTTPURL,
|
||||
DBName: row.DBName,
|
||||
DBOperation: row.DBOperation,
|
||||
TraceState: row.TraceState,
|
||||
Scope: NewScope(row.Scope.Flatten()),
|
||||
}
|
||||
maps.Copy(span.Resource, row.Resource())
|
||||
return span
|
||||
}
|
||||
|
||||
type SameNameSiblingStats struct {
|
||||
SpanCount uint64 `json:"spanCount" required:"true" description:"This span included."`
|
||||
OwnTimeNano uint64 `json:"ownTimeNano" required:"true"`
|
||||
|
||||
@@ -40,6 +40,8 @@ type TraceStore interface {
|
||||
GetThreadSpans(ctx context.Context, orgID valuer.UUID, traceID string, bounds *TraceBounds, page ThreadPage) ([]StorableSpan, error)
|
||||
GetThreadCursor(ctx context.Context, traceID string, bounds *TraceBounds, spanID string) (*ThreadCursor, error)
|
||||
|
||||
GetTraceSkeleton(ctx context.Context, orgID valuer.UUID, traceID string, bounds *TraceBounds) (*TraceSkeleton, error)
|
||||
|
||||
GetSpanCountByField(ctx context.Context, traceID string, bounds *TraceBounds, fieldKey telemetrytypes.TelemetryFieldKey) (map[string]uint64, error)
|
||||
GetSpanDurationByField(ctx context.Context, traceID string, bounds *TraceBounds, fieldKey telemetrytypes.TelemetryFieldKey) (map[string]uint64, error)
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package spantypes
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"maps"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/types/aiobservabilitytypes"
|
||||
@@ -174,8 +173,7 @@ func (s *ThreadSpan) cursor() ThreadCursor {
|
||||
}
|
||||
|
||||
func newThreadSpan(traceID string, storable *StorableSpan) *ThreadSpan {
|
||||
resources := make(map[string]string, len(storable.ResourcesString))
|
||||
maps.Copy(resources, storable.ResourcesString)
|
||||
resources := storable.Resource()
|
||||
timeUnixNano := uint64(storable.StartTime.UnixNano())
|
||||
attributes := storable.Attributes()
|
||||
// Spans from before the JSON rollout have an empty document and format to nothing.
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
package spantypes
|
||||
|
||||
import (
|
||||
"slices"
|
||||
)
|
||||
|
||||
const highlightsDefaultLimit = 10
|
||||
|
||||
type GetTraceHighlightsParams struct {
|
||||
Views []SpanListView `query:"views" description:"The lists to return. Default: all."`
|
||||
Limit int `query:"limit" description:"Spans in each list. Default: 10. Maximum: 1000."`
|
||||
@@ -22,3 +28,51 @@ type TraceHighlights struct {
|
||||
AIUsage *SpanList `json:"aiUsage,omitempty" description:"First page of the ai_usage view."`
|
||||
Links *SpanList `json:"links,omitempty" description:"First page of the links view."`
|
||||
}
|
||||
|
||||
type TraceHighlightsQuery struct {
|
||||
Views []SpanListView
|
||||
Limit int
|
||||
}
|
||||
|
||||
func NewTraceHighlightsQuery(params *GetTraceHighlightsParams) (*TraceHighlightsQuery, error) {
|
||||
limit, err := pageLimit("limit", params.Limit, highlightsDefaultLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
query := &TraceHighlightsQuery{Limit: limit}
|
||||
for _, view := range params.Views {
|
||||
if err := validateSpanListView(view); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !slices.Contains(query.Views, view) {
|
||||
query.Views = append(query.Views, view)
|
||||
}
|
||||
}
|
||||
if len(query.Views) == 0 {
|
||||
for _, view := range SpanListView("").Enum() {
|
||||
query.Views = append(query.Views, view.(SpanListView))
|
||||
}
|
||||
}
|
||||
return query, nil
|
||||
}
|
||||
|
||||
// NewTraceHighlights builds the first page of each requested view from the tree.
|
||||
func NewTraceHighlights(skeleton *TraceSkeleton, query *TraceHighlightsQuery) *TraceHighlights {
|
||||
highlights := &TraceHighlights{Services: skeleton.serviceStats()}
|
||||
for _, view := range query.Views {
|
||||
list := NewSpanList(skeleton.page(skeleton.treeOrder, view, 0, query.Limit), nil)
|
||||
switch view {
|
||||
case SpanListViewErrorOrigins:
|
||||
highlights.ErrorOrigins = list
|
||||
case SpanListViewUnmarkedFailures:
|
||||
highlights.UnmarkedFailures = list
|
||||
case SpanListViewTimeSpent:
|
||||
highlights.TimeSpent = list
|
||||
case SpanListViewAIUsage:
|
||||
highlights.AIUsage = list
|
||||
case SpanListViewLinks:
|
||||
highlights.Links = list
|
||||
}
|
||||
}
|
||||
return highlights
|
||||
}
|
||||
|
||||
445
pkg/types/spantypes/trace_skeleton.go
Normal file
445
pkg/types/spantypes/trace_skeleton.go
Normal file
@@ -0,0 +1,445 @@
|
||||
package spantypes
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
noParent int32 = -1
|
||||
|
||||
refTypeChildOf = "CHILD_OF"
|
||||
)
|
||||
|
||||
// SkeletonSpan is one row of the query a TraceSkeleton is built from.
|
||||
type SkeletonSpan struct {
|
||||
Span
|
||||
// StartTime keeps the nanoseconds own time is computed from; TimeUnix is in milliseconds.
|
||||
StartTime time.Time
|
||||
ServiceName string
|
||||
HasExceptionEvent bool
|
||||
HasLink bool
|
||||
// OtherReferences is empty for a span whose only reference is the one to its parent.
|
||||
OtherReferences string
|
||||
// AIUsage is kept when it has a value, pointers included: every row needs its own.
|
||||
AIUsage AISpanUsage
|
||||
}
|
||||
|
||||
// AISpanUsage is the gen_ai token and cost usage of one span; a nil value is absent on the span.
|
||||
type AISpanUsage struct {
|
||||
InputTokens *float64
|
||||
OutputTokens *float64
|
||||
CacheReadTokens *float64
|
||||
CacheWriteTokens *float64
|
||||
ReasoningTokens *float64
|
||||
Cost *float64
|
||||
}
|
||||
|
||||
// TraceSkeleton is the tree of a trace. A span is known by its position, its index in start time
|
||||
// order, and every slice below holds one value per span at that position. It is read-only once built.
|
||||
type TraceSkeleton struct {
|
||||
traceID string
|
||||
|
||||
// spanIDs holds every span id back to back; span i is spanIDs[idOffsets[i]:idOffsets[i+1]].
|
||||
spanIDs string
|
||||
idOffsets []uint32
|
||||
// parents holds the position of each span's parent, or noParent for a root.
|
||||
parents []int32
|
||||
startNano []int64
|
||||
durationNano []uint64
|
||||
hasError []bool
|
||||
hasExceptionEvent []bool
|
||||
hasLink []bool
|
||||
// Each distinct string is stored once in stringTable; these hold its index there.
|
||||
names []uint32
|
||||
services []uint32
|
||||
kinds []uint32
|
||||
responseStatusCodes []uint32
|
||||
statusCodeStrings []uint32
|
||||
statusMessages []uint32
|
||||
stringTable []string
|
||||
// references holds the stored references of a span that has more than the one to its parent.
|
||||
references map[int32]string
|
||||
// storedParentIDs holds the parent id of a root that has one: its parent is missing or on a loop.
|
||||
storedParentIDs map[int32]string
|
||||
// aiUsage holds the usage of the spans that carry any, by span position.
|
||||
aiUsage map[int32]AISpanUsage
|
||||
|
||||
// The children of span i are childList[childStart[i]:childStart[i+1]], in start time order.
|
||||
childStart []int32
|
||||
childList []int32
|
||||
roots []int32
|
||||
// treeOrder lists the spans as a waterfall shows them: a span, then everything below it.
|
||||
treeOrder []int32
|
||||
level []uint32
|
||||
// descendantCount is the number of spans below each span, at any depth.
|
||||
descendantCount []uint32
|
||||
ownTime []uint64
|
||||
// groupOf is the index in groups of the group a span belongs to.
|
||||
groupOf []int32
|
||||
groups []siblingGroup
|
||||
}
|
||||
|
||||
// TraceSkeletonBuilder collects the rows of a trace. They must be added in start time order.
|
||||
type TraceSkeletonBuilder struct {
|
||||
skeleton *TraceSkeleton
|
||||
ids []byte
|
||||
parentIDs []string
|
||||
stringIndex map[string]uint32
|
||||
}
|
||||
|
||||
func NewTraceSkeletonBuilder(traceID string, sizeHint int) *TraceSkeletonBuilder {
|
||||
return &TraceSkeletonBuilder{
|
||||
skeleton: &TraceSkeleton{
|
||||
traceID: traceID,
|
||||
idOffsets: make([]uint32, 1, sizeHint+1),
|
||||
parents: make([]int32, 0, sizeHint),
|
||||
startNano: make([]int64, 0, sizeHint),
|
||||
durationNano: make([]uint64, 0, sizeHint),
|
||||
hasError: make([]bool, 0, sizeHint),
|
||||
hasExceptionEvent: make([]bool, 0, sizeHint),
|
||||
hasLink: make([]bool, 0, sizeHint),
|
||||
names: make([]uint32, 0, sizeHint),
|
||||
services: make([]uint32, 0, sizeHint),
|
||||
kinds: make([]uint32, 0, sizeHint),
|
||||
responseStatusCodes: make([]uint32, 0, sizeHint),
|
||||
statusCodeStrings: make([]uint32, 0, sizeHint),
|
||||
statusMessages: make([]uint32, 0, sizeHint),
|
||||
references: make(map[int32]string),
|
||||
storedParentIDs: make(map[int32]string),
|
||||
aiUsage: make(map[int32]AISpanUsage),
|
||||
},
|
||||
ids: make([]byte, 0, sizeHint*16),
|
||||
parentIDs: make([]string, 0, sizeHint),
|
||||
stringIndex: make(map[string]uint32),
|
||||
}
|
||||
}
|
||||
|
||||
func (builder *TraceSkeletonBuilder) Add(span *SkeletonSpan) {
|
||||
skeleton := builder.skeleton
|
||||
if span.AIUsage.hasValue() {
|
||||
skeleton.aiUsage[int32(len(builder.parentIDs))] = span.AIUsage
|
||||
}
|
||||
if span.OtherReferences != "" {
|
||||
skeleton.references[int32(len(builder.parentIDs))] = span.OtherReferences
|
||||
}
|
||||
builder.ids = append(builder.ids, span.SpanID...)
|
||||
skeleton.idOffsets = append(skeleton.idOffsets, uint32(len(builder.ids)))
|
||||
builder.parentIDs = append(builder.parentIDs, span.ParentSpanID)
|
||||
skeleton.startNano = append(skeleton.startNano, span.StartTime.UnixNano())
|
||||
skeleton.durationNano = append(skeleton.durationNano, span.DurationNano)
|
||||
skeleton.hasError = append(skeleton.hasError, span.HasError)
|
||||
skeleton.hasExceptionEvent = append(skeleton.hasExceptionEvent, span.HasExceptionEvent)
|
||||
skeleton.hasLink = append(skeleton.hasLink, span.HasLink)
|
||||
skeleton.names = append(skeleton.names, builder.intern(span.Name))
|
||||
skeleton.services = append(skeleton.services, builder.intern(span.ServiceName))
|
||||
skeleton.kinds = append(skeleton.kinds, builder.intern(span.KindString))
|
||||
skeleton.responseStatusCodes = append(skeleton.responseStatusCodes, builder.intern(span.ResponseStatusCode))
|
||||
skeleton.statusCodeStrings = append(skeleton.statusCodeStrings, builder.intern(span.StatusCodeString))
|
||||
skeleton.statusMessages = append(skeleton.statusMessages, builder.intern(span.StatusMessage))
|
||||
}
|
||||
|
||||
// Build turns the added rows into the tree. The builder cannot be reused.
|
||||
func (builder *TraceSkeletonBuilder) Build() *TraceSkeleton {
|
||||
skeleton := builder.skeleton
|
||||
skeleton.spanIDs = string(builder.ids)
|
||||
n := len(builder.parentIDs)
|
||||
|
||||
// A span whose parent is not in the trace, or is the span itself, becomes a root.
|
||||
positions := make(map[string]int32, n)
|
||||
for i := range n {
|
||||
positions[skeleton.spanID(int32(i))] = int32(i)
|
||||
}
|
||||
for i, parentID := range builder.parentIDs {
|
||||
parent, ok := positions[parentID]
|
||||
if !ok || parent == int32(i) {
|
||||
parent = noParent
|
||||
if parentID != "" {
|
||||
skeleton.storedParentIDs[int32(i)] = parentID
|
||||
}
|
||||
}
|
||||
skeleton.parents = append(skeleton.parents, parent)
|
||||
}
|
||||
builder.parentIDs, builder.stringIndex, builder.ids = nil, nil, nil
|
||||
|
||||
skeleton.linkChildren()
|
||||
if skeleton.walkFromRoots() < n {
|
||||
skeleton.cutParentLoops()
|
||||
skeleton.linkChildren()
|
||||
skeleton.walkFromRoots()
|
||||
}
|
||||
|
||||
// Walking the tree order backwards reaches every span after all the spans below it.
|
||||
skeleton.descendantCount = make([]uint32, n)
|
||||
for k := n - 1; k >= 0; k-- {
|
||||
i := skeleton.treeOrder[k]
|
||||
if parent := skeleton.parents[i]; parent != noParent {
|
||||
skeleton.descendantCount[parent] += skeleton.descendantCount[i] + 1
|
||||
}
|
||||
}
|
||||
|
||||
skeleton.ownTime = make([]uint64, n)
|
||||
for i := range n {
|
||||
skeleton.ownTime[i] = skeleton.durationNano[i] - skeleton.timeCoveredByChildren(int32(i))
|
||||
}
|
||||
|
||||
skeleton.groupSameNameSiblings()
|
||||
return skeleton
|
||||
}
|
||||
|
||||
// siblingGroup totals the spans that share a name and a parent; a root is a group of its own.
|
||||
type siblingGroup struct {
|
||||
spanCount uint64
|
||||
ownTime uint64
|
||||
errCount uint64
|
||||
}
|
||||
|
||||
func (skeleton *TraceSkeleton) len() int {
|
||||
return len(skeleton.parents)
|
||||
}
|
||||
|
||||
func (skeleton *TraceSkeleton) spanID(i int32) string {
|
||||
return skeleton.spanIDs[skeleton.idOffsets[i]:skeleton.idOffsets[i+1]]
|
||||
}
|
||||
|
||||
func (skeleton *TraceSkeleton) position(spanID string) (int32, bool) {
|
||||
for i := range int32(skeleton.len()) {
|
||||
if skeleton.spanID(i) == spanID {
|
||||
return i, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func (skeleton *TraceSkeleton) children(i int32) []int32 {
|
||||
return skeleton.childList[skeleton.childStart[i]:skeleton.childStart[i+1]]
|
||||
}
|
||||
|
||||
func (skeleton *TraceSkeleton) parentSpanID(i int32) string {
|
||||
if parent := skeleton.parents[i]; parent != noParent {
|
||||
return skeleton.spanID(parent)
|
||||
}
|
||||
return skeleton.storedParentIDs[i]
|
||||
}
|
||||
|
||||
func (skeleton *TraceSkeleton) spanReferences(i int32) []OtelSpanRef {
|
||||
stored, ok := skeleton.references[i]
|
||||
if !ok {
|
||||
return []OtelSpanRef{{TraceId: skeleton.traceID, SpanId: skeleton.parentSpanID(i), RefType: refTypeChildOf}}
|
||||
}
|
||||
refs := []OtelSpanRef{}
|
||||
if err := json.Unmarshal([]byte(stored), &refs); err != nil {
|
||||
return []OtelSpanRef{} // skip malformed values
|
||||
}
|
||||
return refs
|
||||
}
|
||||
|
||||
// unmarkedFailureKind is set for a span that reports a failure without the error flag. The response
|
||||
// status column holds an HTTP status or a gRPC status.
|
||||
func (skeleton *TraceSkeleton) unmarkedFailureKind(i int32) UnmarkedFailureKind {
|
||||
if skeleton.hasError[i] {
|
||||
return ""
|
||||
}
|
||||
if code, err := strconv.Atoi(skeleton.stringTable[skeleton.responseStatusCodes[i]]); err == nil {
|
||||
switch {
|
||||
case code >= 400 && code < 500:
|
||||
return UnmarkedFailureHTTP4xx
|
||||
case code >= 500 && code < 600:
|
||||
return UnmarkedFailureHTTP5xx
|
||||
case code >= 1 && code <= 16:
|
||||
return UnmarkedFailureGRPCStatus
|
||||
}
|
||||
}
|
||||
if skeleton.hasExceptionEvent[i] {
|
||||
return UnmarkedFailureExceptionEvent
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (skeleton *TraceSkeleton) treeStats(i int32) SpanTreeStats {
|
||||
stats := SpanTreeStats{
|
||||
Level: skeleton.level[i],
|
||||
ChildCount: uint32(len(skeleton.children(i))),
|
||||
SubtreeSpanCount: skeleton.descendantCount[i],
|
||||
OwnTimeNano: skeleton.ownTime[i],
|
||||
}
|
||||
for p := skeleton.parents[i]; p != noParent && skeleton.hasError[p]; p = skeleton.parents[p] {
|
||||
stats.ErrorAncestorCount++
|
||||
}
|
||||
if group := skeleton.groups[skeleton.groupOf[i]]; group.spanCount > 1 {
|
||||
stats.SameNameSiblings = &SameNameSiblingStats{SpanCount: group.spanCount, OwnTimeNano: group.ownTime, ErrorSpanCount: group.errCount}
|
||||
}
|
||||
return stats
|
||||
}
|
||||
|
||||
// serviceStats totals the spans of each service, the service with the most own time first.
|
||||
func (skeleton *TraceSkeleton) serviceStats() []TraceServiceStats {
|
||||
services := make([]TraceServiceStats, 0)
|
||||
positionOf := make(map[uint32]int)
|
||||
for i := range int32(skeleton.len()) {
|
||||
position, ok := positionOf[skeleton.services[i]]
|
||||
if !ok {
|
||||
position = len(services)
|
||||
positionOf[skeleton.services[i]] = position
|
||||
services = append(services, TraceServiceStats{ServiceName: skeleton.stringTable[skeleton.services[i]]})
|
||||
}
|
||||
services[position].SpanCount++
|
||||
services[position].OwnTimeNano += skeleton.ownTime[i]
|
||||
if skeleton.hasError[i] {
|
||||
services[position].ErrorSpanCount++
|
||||
}
|
||||
}
|
||||
slices.SortFunc(services, func(a, b TraceServiceStats) int {
|
||||
return cmp.Or(cmp.Compare(b.OwnTimeNano, a.OwnTimeNano), strings.Compare(a.ServiceName, b.ServiceName))
|
||||
})
|
||||
return services
|
||||
}
|
||||
|
||||
func (usage AISpanUsage) hasValue() bool {
|
||||
return usage.InputTokens != nil || usage.OutputTokens != nil || usage.CacheReadTokens != nil ||
|
||||
usage.CacheWriteTokens != nil || usage.ReasoningTokens != nil || usage.Cost != nil
|
||||
}
|
||||
|
||||
// intern returns the index of value in the string table, adding it on first sight.
|
||||
func (builder *TraceSkeletonBuilder) intern(value string) uint32 {
|
||||
if idx, ok := builder.stringIndex[value]; ok {
|
||||
return idx
|
||||
}
|
||||
idx := uint32(len(builder.skeleton.stringTable))
|
||||
builder.skeleton.stringTable = append(builder.skeleton.stringTable, value)
|
||||
builder.stringIndex[value] = idx
|
||||
return idx
|
||||
}
|
||||
|
||||
// linkChildren fills roots, childStart and childList from parents: it counts the children of
|
||||
// every span, turns the counts into start offsets, then places each child.
|
||||
func (skeleton *TraceSkeleton) linkChildren() {
|
||||
n := skeleton.len()
|
||||
skeleton.childStart = make([]int32, n+1)
|
||||
skeleton.roots = skeleton.roots[:0]
|
||||
for i := range n {
|
||||
if parent := skeleton.parents[i]; parent != noParent {
|
||||
skeleton.childStart[parent+1]++
|
||||
} else {
|
||||
skeleton.roots = append(skeleton.roots, int32(i))
|
||||
}
|
||||
}
|
||||
for i := range n {
|
||||
skeleton.childStart[i+1] += skeleton.childStart[i]
|
||||
}
|
||||
skeleton.childList = make([]int32, skeleton.childStart[n])
|
||||
next := slices.Clone(skeleton.childStart[:n])
|
||||
for i := range n {
|
||||
if parent := skeleton.parents[i]; parent != noParent {
|
||||
skeleton.childList[next[parent]] = int32(i)
|
||||
next[parent]++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// walkFromRoots fills treeOrder and level, and returns the number of spans it reached.
|
||||
func (skeleton *TraceSkeleton) walkFromRoots() int {
|
||||
n := skeleton.len()
|
||||
skeleton.treeOrder = make([]int32, 0, n)
|
||||
skeleton.level = make([]uint32, n)
|
||||
// Pushed in reverse, the earliest root and the earliest child are popped first.
|
||||
stack := make([]int32, 0, 64)
|
||||
for r := len(skeleton.roots) - 1; r >= 0; r-- {
|
||||
stack = append(stack, skeleton.roots[r])
|
||||
}
|
||||
for len(stack) > 0 {
|
||||
i := stack[len(stack)-1]
|
||||
stack = stack[:len(stack)-1]
|
||||
skeleton.treeOrder = append(skeleton.treeOrder, i)
|
||||
children := skeleton.children(i)
|
||||
for c := len(children) - 1; c >= 0; c-- {
|
||||
skeleton.level[children[c]] = skeleton.level[i] + 1
|
||||
stack = append(stack, children[c])
|
||||
}
|
||||
}
|
||||
return len(skeleton.treeOrder)
|
||||
}
|
||||
|
||||
// cutParentLoops handles spans no root reaches: they sit on a loop of parents (a under b, b under
|
||||
// a) or below one. The earliest unreached span of each loop becomes a root.
|
||||
func (skeleton *TraceSkeleton) cutParentLoops() {
|
||||
reached := make([]bool, skeleton.len())
|
||||
for _, i := range skeleton.treeOrder {
|
||||
reached[i] = true
|
||||
}
|
||||
for i := range int32(skeleton.len()) {
|
||||
if reached[i] {
|
||||
continue
|
||||
}
|
||||
skeleton.storedParentIDs[i] = skeleton.spanID(skeleton.parents[i])
|
||||
skeleton.parents[i] = noParent
|
||||
stack := []int32{i}
|
||||
for len(stack) > 0 {
|
||||
top := stack[len(stack)-1]
|
||||
stack = stack[:len(stack)-1]
|
||||
if !reached[top] {
|
||||
reached[top] = true
|
||||
stack = append(stack, skeleton.children(top)...)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// timeCoveredByChildren is the time of span i during which a child was running. Overlapping
|
||||
// children count once, and child time outside the span does not count.
|
||||
func (skeleton *TraceSkeleton) timeCoveredByChildren(i int32) uint64 {
|
||||
start := skeleton.startNano[i]
|
||||
end := start + int64(skeleton.durationNano[i])
|
||||
covered, cursor := int64(0), start
|
||||
for _, child := range skeleton.children(i) {
|
||||
childStart := max(skeleton.startNano[child], cursor)
|
||||
childEnd := min(skeleton.startNano[child]+int64(skeleton.durationNano[child]), end)
|
||||
if childEnd <= childStart {
|
||||
continue
|
||||
}
|
||||
covered += childEnd - childStart
|
||||
cursor = childEnd
|
||||
}
|
||||
return uint64(covered)
|
||||
}
|
||||
|
||||
// groupSameNameSiblings fills groups and groupOf: one group per name among the children of a span.
|
||||
func (skeleton *TraceSkeleton) groupSameNameSiblings() {
|
||||
n := skeleton.len()
|
||||
skeleton.groupOf = make([]int32, n)
|
||||
skeleton.groups = make([]siblingGroup, 0, n)
|
||||
addGroup := func(members []int32) {
|
||||
group := siblingGroup{}
|
||||
for _, i := range members {
|
||||
skeleton.groupOf[i] = int32(len(skeleton.groups))
|
||||
group.spanCount++
|
||||
group.ownTime += skeleton.ownTime[i]
|
||||
if skeleton.hasError[i] {
|
||||
group.errCount++
|
||||
}
|
||||
}
|
||||
skeleton.groups = append(skeleton.groups, group)
|
||||
}
|
||||
|
||||
for r := range skeleton.roots {
|
||||
addGroup(skeleton.roots[r : r+1])
|
||||
}
|
||||
var siblings []int32
|
||||
for parent := range int32(n) {
|
||||
// Sorting by name puts same-name siblings side by side; the stable sort keeps their time order.
|
||||
siblings = append(siblings[:0], skeleton.children(parent)...)
|
||||
slices.SortStableFunc(siblings, func(a, b int32) int { return int(skeleton.names[a]) - int(skeleton.names[b]) })
|
||||
for first := 0; first < len(siblings); {
|
||||
end := first + 1
|
||||
for end < len(siblings) && skeleton.names[siblings[end]] == skeleton.names[siblings[first]] {
|
||||
end++
|
||||
}
|
||||
addGroup(siblings[first:end])
|
||||
first = end
|
||||
}
|
||||
}
|
||||
}
|
||||
325
pkg/types/spantypes/trace_skeleton_test.go
Normal file
325
pkg/types/spantypes/trace_skeleton_test.go
Normal file
@@ -0,0 +1,325 @@
|
||||
package spantypes
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type skeletonSpec struct {
|
||||
id, parent, name, service string
|
||||
startMs, durationMs int64
|
||||
hasError, hasException bool
|
||||
hasLink bool
|
||||
usage AISpanUsage
|
||||
statusCode string
|
||||
references string
|
||||
}
|
||||
|
||||
// buildSkeleton adds the spans in the given order, which stands for the store's start time order.
|
||||
func buildSkeleton(specs ...skeletonSpec) *TraceSkeleton {
|
||||
builder := NewTraceSkeletonBuilder("trace", len(specs))
|
||||
for _, spec := range specs {
|
||||
span := &SkeletonSpan{
|
||||
Span: Span{
|
||||
SpanID: spec.id,
|
||||
ParentSpanID: spec.parent,
|
||||
DurationNano: uint64(spec.durationMs) * uint64(time.Millisecond),
|
||||
HasError: spec.hasError,
|
||||
Name: spec.name,
|
||||
KindString: "Internal",
|
||||
ResponseStatusCode: spec.statusCode,
|
||||
},
|
||||
StartTime: time.Unix(100, 0).Add(time.Duration(spec.startMs) * time.Millisecond),
|
||||
ServiceName: spec.service,
|
||||
HasExceptionEvent: spec.hasException,
|
||||
HasLink: spec.hasLink,
|
||||
OtherReferences: spec.references,
|
||||
AIUsage: spec.usage,
|
||||
}
|
||||
builder.Add(span)
|
||||
}
|
||||
return builder.Build()
|
||||
}
|
||||
|
||||
func spanIDsOf(skeleton *TraceSkeleton, positions []int32) []string {
|
||||
spanIDs := make([]string, 0, len(positions))
|
||||
for _, i := range positions {
|
||||
spanIDs = append(spanIDs, skeleton.spanID(i))
|
||||
}
|
||||
return spanIDs
|
||||
}
|
||||
|
||||
func positionOf(t *testing.T, skeleton *TraceSkeleton, spanID string) int32 {
|
||||
t.Helper()
|
||||
for i := range int32(skeleton.len()) {
|
||||
if skeleton.spanID(i) == spanID {
|
||||
return i
|
||||
}
|
||||
}
|
||||
require.FailNow(t, "span not in skeleton", spanID)
|
||||
return noParent
|
||||
}
|
||||
|
||||
func TestTraceSkeletonOwnTime(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
specs []skeletonSpec
|
||||
expected int64
|
||||
}{
|
||||
{
|
||||
// time (ms) 0 10 30 50 80 100
|
||||
// root |-------------------------------------------------| 100 ms
|
||||
// a |---------| 20 ms
|
||||
// b |--------------| 30 ms
|
||||
name: "SequentialChildren_SubtractsEach",
|
||||
specs: []skeletonSpec{
|
||||
{id: "root", startMs: 0, durationMs: 100},
|
||||
{id: "a", parent: "root", startMs: 10, durationMs: 20},
|
||||
{id: "b", parent: "root", startMs: 50, durationMs: 30},
|
||||
},
|
||||
expected: 50,
|
||||
},
|
||||
{
|
||||
// Calls fanned out at once, such as parallel queries. Together they cover 10 to 60.
|
||||
// time (ms) 0 10 20 30 40 50 60 100
|
||||
// root |-------------------------------------------------| 100 ms
|
||||
// a |-------------------| 40 ms
|
||||
// b |-------------------| 40 ms
|
||||
// c |----| 10 ms
|
||||
name: "ParallelChildren_CountsOverlapOnce",
|
||||
specs: []skeletonSpec{
|
||||
{id: "root", startMs: 0, durationMs: 100},
|
||||
{id: "a", parent: "root", startMs: 10, durationMs: 40},
|
||||
{id: "b", parent: "root", startMs: 20, durationMs: 40},
|
||||
{id: "c", parent: "root", startMs: 30, durationMs: 10},
|
||||
},
|
||||
expected: 50,
|
||||
},
|
||||
{
|
||||
// Work the parent starts and does not wait for, such as a background job.
|
||||
// time (ms) 0 80 100
|
||||
// root |-------------------------------------------------| 100 ms
|
||||
// a |--------------> 500 ms, 20 of them inside root
|
||||
name: "ChildOutlivesParent_ClipsToParentEnd",
|
||||
specs: []skeletonSpec{
|
||||
{id: "root", startMs: 0, durationMs: 100},
|
||||
{id: "a", parent: "root", startMs: 80, durationMs: 500},
|
||||
},
|
||||
expected: 80,
|
||||
},
|
||||
{
|
||||
// Clock skew: the child's host clock runs behind the parent's.
|
||||
// time (ms) 0 10 30 110
|
||||
// early |--------------| 30 ms, 20 of them inside root
|
||||
// root |-------------------------------------------------| 100 ms
|
||||
name: "ChildStartsBeforeParent_ClipsToParentStart",
|
||||
specs: []skeletonSpec{
|
||||
{id: "early", parent: "root", startMs: 0, durationMs: 30},
|
||||
{id: "root", startMs: 10, durationMs: 100},
|
||||
},
|
||||
expected: 80,
|
||||
},
|
||||
{
|
||||
// Clock skew again, with a child that also runs past the parent's end.
|
||||
// time (ms) 0 10 110
|
||||
// early |-----------------------------------------------------------> 500 ms
|
||||
// root |-------------------------------------------------| 100 ms
|
||||
name: "ChildCoversParent_LeavesZero",
|
||||
specs: []skeletonSpec{
|
||||
{id: "early", parent: "root", startMs: 0, durationMs: 500},
|
||||
{id: "root", startMs: 10, durationMs: 100},
|
||||
},
|
||||
expected: 0,
|
||||
},
|
||||
{
|
||||
// Only direct children count: a1 is taken from the time of a, not of root.
|
||||
// time (ms) 0 10 30 90 100
|
||||
// root |-------------------------------------------------| 100 ms
|
||||
// a |---------| 20 ms
|
||||
// a1 |------------------------------------| 75 ms, child of a
|
||||
name: "Grandchild_NotSubtracted",
|
||||
specs: []skeletonSpec{
|
||||
{id: "root", startMs: 0, durationMs: 100},
|
||||
{id: "a", parent: "root", startMs: 10, durationMs: 20},
|
||||
{id: "a1", parent: "a", startMs: 15, durationMs: 75},
|
||||
},
|
||||
expected: 80,
|
||||
},
|
||||
{
|
||||
name: "NoChildren_EqualsDuration",
|
||||
specs: []skeletonSpec{
|
||||
{id: "root", startMs: 0, durationMs: 70},
|
||||
},
|
||||
expected: 70,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
skeleton := buildSkeleton(testCase.specs...)
|
||||
assert.Equal(t, uint64(testCase.expected)*uint64(time.Millisecond), skeleton.ownTime[positionOf(t, skeleton, "root")])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTraceSkeletonTree(t *testing.T) {
|
||||
// root 0 to 100
|
||||
// a 10 to 40
|
||||
// a1 15 to 20, error
|
||||
// b 50 to 60
|
||||
// orphan 60 to 70; its parent is not in the trace, so it is a second root
|
||||
skeleton := buildSkeleton(
|
||||
skeletonSpec{id: "root", name: "GET /", service: "web", startMs: 0, durationMs: 100},
|
||||
skeletonSpec{id: "a", parent: "root", name: "a", service: "web", startMs: 10, durationMs: 30},
|
||||
skeletonSpec{id: "a1", parent: "a", name: "a1", service: "db", startMs: 15, durationMs: 5, hasError: true},
|
||||
skeletonSpec{id: "b", parent: "root", name: "b", service: "web", startMs: 50, durationMs: 10},
|
||||
skeletonSpec{id: "orphan", parent: "gone", name: "orphan", service: "worker", startMs: 60, durationMs: 10},
|
||||
)
|
||||
|
||||
assert.Equal(t, []string{"root", "a", "a1", "b", "orphan"}, spanIDsOf(skeleton, skeleton.treeOrder))
|
||||
assert.Equal(t, []string{"root", "orphan"}, spanIDsOf(skeleton, skeleton.roots))
|
||||
// root: two children, three spans below it, and 100 less the 30 of a and the 10 of b.
|
||||
assert.Equal(t, SpanTreeStats{Level: 0, ChildCount: 2, SubtreeSpanCount: 3, OwnTimeNano: uint64(60 * time.Millisecond)}, skeleton.treeStats(positionOf(t, skeleton, "root")))
|
||||
assert.Equal(t, SpanTreeStats{Level: 2, OwnTimeNano: uint64(5 * time.Millisecond)}, skeleton.treeStats(positionOf(t, skeleton, "a1")))
|
||||
assert.Equal(t, SpanTreeStats{Level: 0, OwnTimeNano: uint64(10 * time.Millisecond)}, skeleton.treeStats(positionOf(t, skeleton, "orphan")))
|
||||
}
|
||||
|
||||
func TestTraceSkeletonTreeStats(t *testing.T) {
|
||||
// root error
|
||||
// handler error
|
||||
// q1 SELECT, 10 ms
|
||||
// q2 SELECT, 30 ms, error
|
||||
// cache
|
||||
// evict error
|
||||
// q3 SELECT, 20 ms
|
||||
skeleton := buildSkeleton(
|
||||
skeletonSpec{id: "root", name: "GET /", startMs: 0, durationMs: 100, hasError: true},
|
||||
skeletonSpec{id: "handler", parent: "root", name: "handler", startMs: 0, durationMs: 90, hasError: true},
|
||||
skeletonSpec{id: "q1", parent: "handler", name: "SELECT", startMs: 0, durationMs: 10},
|
||||
skeletonSpec{id: "q2", parent: "handler", name: "SELECT", startMs: 10, durationMs: 30, hasError: true},
|
||||
skeletonSpec{id: "cache", parent: "handler", name: "GET cache", startMs: 40, durationMs: 5},
|
||||
skeletonSpec{id: "evict", parent: "cache", name: "evict", startMs: 41, durationMs: 2, hasError: true},
|
||||
skeletonSpec{id: "q3", parent: "handler", name: "SELECT", startMs: 50, durationMs: 20},
|
||||
)
|
||||
|
||||
// q2 has two error spans above it, and shares its name with q1 and q3.
|
||||
stats := skeleton.treeStats(positionOf(t, skeleton, "q2"))
|
||||
assert.Equal(t, uint32(2), stats.ErrorAncestorCount)
|
||||
require.NotNil(t, stats.SameNameSiblings)
|
||||
assert.Equal(t, SameNameSiblingStats{SpanCount: 3, OwnTimeNano: uint64(60 * time.Millisecond), ErrorSpanCount: 1}, *stats.SameNameSiblings)
|
||||
|
||||
cache := skeleton.treeStats(positionOf(t, skeleton, "cache"))
|
||||
assert.Nil(t, cache.SameNameSiblings)
|
||||
assert.Equal(t, uint32(2), cache.ErrorAncestorCount)
|
||||
|
||||
// The count stops at the first ancestor that is not an error: cache, the parent of evict.
|
||||
assert.Equal(t, uint32(0), skeleton.treeStats(positionOf(t, skeleton, "evict")).ErrorAncestorCount)
|
||||
}
|
||||
|
||||
func TestTraceSkeletonUnmarkedFailureKind(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
spec skeletonSpec
|
||||
expected UnmarkedFailureKind
|
||||
}{
|
||||
{name: "HTTP400_LowestClientError", spec: skeletonSpec{statusCode: "400"}, expected: UnmarkedFailureHTTP4xx},
|
||||
{name: "HTTP499_HighestClientError", spec: skeletonSpec{statusCode: "499"}, expected: UnmarkedFailureHTTP4xx},
|
||||
{name: "HTTP200_NotAFailure", spec: skeletonSpec{statusCode: "200"}},
|
||||
// Instrumentation should flag a 5xx as an error; proxies and hand-written spans often do not.
|
||||
{name: "HTTP500_LowestServerError", spec: skeletonSpec{statusCode: "500"}, expected: UnmarkedFailureHTTP5xx},
|
||||
{name: "HTTP599_HighestServerError", spec: skeletonSpec{statusCode: "599"}, expected: UnmarkedFailureHTTP5xx},
|
||||
{name: "HTTP600_NotAFailure", spec: skeletonSpec{statusCode: "600"}},
|
||||
{name: "GRPC1_LowestFailure", spec: skeletonSpec{statusCode: "1"}, expected: UnmarkedFailureGRPCStatus},
|
||||
{name: "GRPC16_HighestFailure", spec: skeletonSpec{statusCode: "16"}, expected: UnmarkedFailureGRPCStatus},
|
||||
{name: "GRPC0_OK", spec: skeletonSpec{statusCode: "0"}},
|
||||
{name: "ExceptionEvent_WithoutStatusCode", spec: skeletonSpec{hasException: true}, expected: UnmarkedFailureExceptionEvent},
|
||||
{name: "ExceptionEvent_WithSuccessStatusCode", spec: skeletonSpec{statusCode: "200", hasException: true}, expected: UnmarkedFailureExceptionEvent},
|
||||
{name: "StatusCodeAndExceptionEvent_ReportsStatusCode", spec: skeletonSpec{statusCode: "404", hasException: true}, expected: UnmarkedFailureHTTP4xx},
|
||||
{name: "ErrorFlag_NeverUnmarked", spec: skeletonSpec{statusCode: "404", hasException: true, hasError: true}},
|
||||
{name: "NoSignal_NotAFailure", spec: skeletonSpec{}},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
testCase.spec.id = "span"
|
||||
skeleton := buildSkeleton(testCase.spec)
|
||||
assert.Equal(t, testCase.expected, skeleton.unmarkedFailureKind(0))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// No valid trace has a parent loop; it comes from instrumentation that reuses span ids. Every span
|
||||
// must still be listed once.
|
||||
func TestTraceSkeletonParentLoop(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
specs []skeletonSpec
|
||||
expectedRoots []string
|
||||
expectedTreeOrder []string
|
||||
}{
|
||||
{
|
||||
// x is the earliest span of the loop, so it becomes a root; y and under-y stay below it.
|
||||
name: "TwoSpansPointAtEachOther",
|
||||
specs: []skeletonSpec{
|
||||
{id: "root", startMs: 0, durationMs: 10},
|
||||
{id: "x", parent: "y", startMs: 1, durationMs: 5},
|
||||
{id: "y", parent: "x", startMs: 2, durationMs: 5},
|
||||
{id: "under-y", parent: "y", startMs: 3, durationMs: 1},
|
||||
},
|
||||
expectedRoots: []string{"root", "x"},
|
||||
expectedTreeOrder: []string{"root", "x", "y", "under-y"},
|
||||
},
|
||||
{
|
||||
name: "SpanIsItsOwnParent",
|
||||
specs: []skeletonSpec{
|
||||
{id: "self", parent: "self", startMs: 0, durationMs: 10},
|
||||
{id: "child", parent: "self", startMs: 1, durationMs: 5},
|
||||
},
|
||||
expectedRoots: []string{"self"},
|
||||
expectedTreeOrder: []string{"self", "child"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
skeleton := buildSkeleton(testCase.specs...)
|
||||
assert.Equal(t, testCase.expectedRoots, spanIDsOf(skeleton, skeleton.roots))
|
||||
assert.Equal(t, testCase.expectedTreeOrder, spanIDsOf(skeleton, skeleton.treeOrder))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTraceSkeletonSpan_ParentAndReferences(t *testing.T) {
|
||||
skeleton := buildSkeleton(
|
||||
skeletonSpec{id: "root"},
|
||||
skeletonSpec{id: "child", parent: "root"},
|
||||
skeletonSpec{id: "linked", parent: "root", references: `[{"traceId":"trace","spanId":"root","refType":"CHILD_OF"},{"traceId":"other","spanId":"far","refType":"FOLLOWS_FROM"}]`},
|
||||
skeletonSpec{id: "orphan", parent: "gone"},
|
||||
// a and b are each other's parent; a, the earliest, becomes a root.
|
||||
skeletonSpec{id: "a", parent: "b"},
|
||||
skeletonSpec{id: "b", parent: "a"},
|
||||
)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
spanID string
|
||||
parentSpanID string
|
||||
references []OtelSpanRef
|
||||
}{
|
||||
{name: "NoStoredReferences_RebuiltFromTheParent", spanID: "child", parentSpanID: "root", references: []OtelSpanRef{{TraceId: "trace", SpanId: "root", RefType: "CHILD_OF"}}},
|
||||
{name: "StoredReferences_ReturnedAsStored", spanID: "linked", parentSpanID: "root", references: []OtelSpanRef{{TraceId: "trace", SpanId: "root", RefType: "CHILD_OF"}, {TraceId: "other", SpanId: "far", RefType: "FOLLOWS_FROM"}}},
|
||||
{name: "MissingParent_KeepsTheStoredParentID", spanID: "orphan", parentSpanID: "gone", references: []OtelSpanRef{{TraceId: "trace", SpanId: "gone", RefType: "CHILD_OF"}}},
|
||||
{name: "ParentLoop_KeepsTheStoredParentID", spanID: "a", parentSpanID: "b", references: []OtelSpanRef{{TraceId: "trace", SpanId: "b", RefType: "CHILD_OF"}}},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
span := skeleton.span(positionOf(t, skeleton, testCase.spanID))
|
||||
assert.Equal(t, testCase.parentSpanID, span.ParentSpanID)
|
||||
assert.Equal(t, testCase.references, span.References)
|
||||
})
|
||||
}
|
||||
}
|
||||
414
pkg/types/spantypes/trace_span_list.go
Normal file
414
pkg/types/spantypes/trace_span_list.go
Normal file
@@ -0,0 +1,414 @@
|
||||
package spantypes
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/types/aiobservabilitytypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
|
||||
)
|
||||
|
||||
const (
|
||||
SpanScopeTrace SpanScope = "trace"
|
||||
SpanScopeChildren SpanScope = "children"
|
||||
SpanScopeDescendants SpanScope = "descendants"
|
||||
SpanScopeAncestors SpanScope = "ancestors"
|
||||
)
|
||||
|
||||
const (
|
||||
spanListDefaultLimit = 50
|
||||
spanListMaxLimit = 1000
|
||||
)
|
||||
|
||||
var (
|
||||
ErrCodeTraceSpansInvalidLimit = errors.MustNewCode("trace_spans_invalid_limit")
|
||||
ErrCodeTraceSpansInvalidOffset = errors.MustNewCode("trace_spans_invalid_offset")
|
||||
ErrCodeTraceSpansInvalidView = errors.MustNewCode("trace_spans_invalid_view")
|
||||
)
|
||||
|
||||
// SpanScope says which spans of a trace a list route covers: all of them, or the ones related to one span.
|
||||
type SpanScope string
|
||||
|
||||
type SpanListQuery struct {
|
||||
Scope SpanScope
|
||||
// ScopeSpanID is the span the scope is relative to. Empty when the scope is the whole trace.
|
||||
ScopeSpanID string
|
||||
// View is empty when every span the scope covers is wanted.
|
||||
View SpanListView
|
||||
SelectFields []telemetrytypes.TelemetryFieldKey
|
||||
Offset int
|
||||
Limit int
|
||||
}
|
||||
|
||||
// SpanListPage is one page of a span list picked from the tree, before the stored data of its spans is read.
|
||||
type SpanListPage struct {
|
||||
skeleton *TraceSkeleton
|
||||
view SpanListView
|
||||
// total counts the spans the page was cut from.
|
||||
total uint64
|
||||
positions []int32
|
||||
selectFields []telemetrytypes.TelemetryFieldKey
|
||||
}
|
||||
|
||||
func NewSpanListQuery(params *ListTraceSpansParams, scope SpanScope, scopeSpanID string) (*SpanListQuery, error) {
|
||||
query := &SpanListQuery{Scope: scope, ScopeSpanID: scopeSpanID, View: params.View, Offset: params.Offset}
|
||||
if query.View != "" {
|
||||
if err := validateSpanListView(query.View); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(params.Query) != "" {
|
||||
return nil, errors.New(errors.TypeUnsupported, errors.CodeUnsupported, "query is not implemented yet")
|
||||
}
|
||||
if params.Offset < 0 {
|
||||
return nil, errors.NewInvalidInputf(ErrCodeTraceSpansInvalidOffset, "offset cannot be negative, got %d", params.Offset)
|
||||
}
|
||||
limit, err := pageLimit("limit", params.Limit, spanListDefaultLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
query.Limit = limit
|
||||
|
||||
for _, text := range params.SelectFields {
|
||||
if text = strings.TrimSpace(text); text != "" {
|
||||
query.SelectFields = append(query.SelectFields, newSelectField(text))
|
||||
}
|
||||
}
|
||||
return query, nil
|
||||
}
|
||||
|
||||
func NewSpanListPage(skeleton *TraceSkeleton, query *SpanListQuery) (*SpanListPage, error) {
|
||||
scope, err := skeleton.scopePositions(query.Scope, query.ScopeSpanID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
page := skeleton.page(scope, query.View, query.Offset, query.Limit)
|
||||
page.selectFields = query.SelectFields
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (page *SpanListPage) SpanIDs() []string {
|
||||
spanIDs := make([]string, 0, len(page.positions))
|
||||
for _, i := range page.positions {
|
||||
spanIDs = append(spanIDs, page.skeleton.spanID(i))
|
||||
}
|
||||
return spanIDs
|
||||
}
|
||||
|
||||
// NewSpanList builds the page. rows holds the stored data of its spans, read only for the selected
|
||||
// fields. A selected field no span of the page has is reported as a warning.
|
||||
func NewSpanList(page *SpanListPage, rows []StorableSpan) *SpanList {
|
||||
byID := make(map[string]*StorableSpan, len(rows))
|
||||
for i := range rows {
|
||||
byID[rows[i].SpanID] = &rows[i]
|
||||
}
|
||||
|
||||
skeleton := page.skeleton
|
||||
list := &SpanList{Total: page.total, Items: make([]SpanItem, 0, len(page.positions))}
|
||||
found := make([]bool, len(page.selectFields))
|
||||
for _, i := range page.positions {
|
||||
item := SpanItem{Span: skeleton.span(i), TreeStats: skeleton.treeStats(i), UnmarkedFailureKind: skeleton.unmarkedFailureKind(i)}
|
||||
if page.view == SpanListViewAIUsage {
|
||||
skeleton.setUsageAttributes(&item.Span, i)
|
||||
}
|
||||
item.Span.selectFields(byID[skeleton.spanID(i)], page.selectFields, found)
|
||||
list.Items = append(list.Items, item)
|
||||
}
|
||||
for k, field := range page.selectFields {
|
||||
if !found[k] && len(list.Items) > 0 {
|
||||
list.Warnings = append(list.Warnings, fmt.Sprintf("field `%s` was not found on any returned span", telemetrytypes.TelemetryFieldKeyToText(&field)))
|
||||
}
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
func validateSpanListView(view SpanListView) error {
|
||||
if !slices.Contains(SpanListView("").Enum(), any(view)) {
|
||||
return errors.NewInvalidInputf(ErrCodeTraceSpansInvalidView, "invalid view %q, expected one of error_origins, unmarked_failures, time_spent, ai_usage, links", string(view))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// newSelectField reads a name into its context and bare name. The data type is not used.
|
||||
func newSelectField(text string) telemetrytypes.TelemetryFieldKey {
|
||||
key := telemetrytypes.GetFieldKeyFromKeyText(text)
|
||||
key.FieldDataType = telemetrytypes.FieldDataTypeUnspecified
|
||||
return key
|
||||
}
|
||||
|
||||
// selectFields fills span with the selected fields of row and marks in found the ones row has. A
|
||||
// name is read as a trace list query reads it: a field of the span itself first, then an attribute.
|
||||
func (span *Span) selectFields(row *StorableSpan, fields []telemetrytypes.TelemetryFieldKey, found []bool) {
|
||||
if row == nil || len(fields) == 0 {
|
||||
return
|
||||
}
|
||||
resource, attributes := row.Resource(), row.Attributes()
|
||||
for k, field := range fields {
|
||||
onRow, isSpanField := span.selectSpanField(row, &field)
|
||||
if !isSpanField {
|
||||
onRow = span.selectAttribute(resource, attributes, &field)
|
||||
}
|
||||
found[k] = found[k] || onRow
|
||||
}
|
||||
}
|
||||
|
||||
// selectSpanField copies a field of the span itself from row. known is false when field does not
|
||||
// name one, and found is false when the span has no value for it.
|
||||
func (span *Span) selectSpanField(row *StorableSpan, field *telemetrytypes.TelemetryFieldKey) (found, known bool) {
|
||||
name := field.Name
|
||||
switch field.FieldContext {
|
||||
case telemetrytypes.FieldContextUnspecified, telemetrytypes.FieldContextSpan:
|
||||
case telemetrytypes.FieldContextScope:
|
||||
return span.selectScope(row, name), true
|
||||
default:
|
||||
return false, false
|
||||
}
|
||||
|
||||
switch name {
|
||||
case "span_id", "trace_id", "parent_span_id", "name", "kind_string", "timestamp", "duration_nano",
|
||||
"has_error", "status_code_string", "status_message", "response_status_code":
|
||||
// Every span already carries these.
|
||||
return true, true
|
||||
case "http_method":
|
||||
return setString(&span.HTTPMethod, row.HTTPMethod), true
|
||||
case "http_url":
|
||||
return setString(&span.HTTPURL, row.HTTPURL), true
|
||||
case "http_host":
|
||||
return setString(&span.HTTPHost, row.HTTPHost), true
|
||||
case "external_http_method":
|
||||
return setString(&span.ExternalHTTPMethod, row.ExternalHTTPMethod), true
|
||||
case "external_http_url":
|
||||
return setString(&span.ExternalHTTPURL, row.ExternalHTTPURL), true
|
||||
case "db_name":
|
||||
return setString(&span.DBName, row.DBName), true
|
||||
case "db_operation":
|
||||
return setString(&span.DBOperation, row.DBOperation), true
|
||||
case "trace_state":
|
||||
return setString(&span.TraceState, row.TraceState), true
|
||||
}
|
||||
return false, false
|
||||
}
|
||||
|
||||
// selectScope copies the scope's name, version or, for any other name, a scope attribute from row,
|
||||
// keeping the scope attributes already selected.
|
||||
func (span *Span) selectScope(row *StorableSpan, name string) bool {
|
||||
if name == scopeName || name == scopeVersion {
|
||||
name = "scope." + name
|
||||
}
|
||||
selected := NewSelectedScope(row.Scope.Flatten(), []string{name})
|
||||
if len(selected) == 0 {
|
||||
return false
|
||||
}
|
||||
if span.Scope == nil {
|
||||
span.Scope = Scope{}
|
||||
}
|
||||
for key, value := range selected {
|
||||
attributes, isAttributes := value.(map[string]any)
|
||||
if selectedAttributes, ok := span.Scope[key].(map[string]any); isAttributes && ok {
|
||||
maps.Copy(selectedAttributes, attributes)
|
||||
continue
|
||||
}
|
||||
span.Scope[key] = value
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// selectAttribute copies an attribute or a resource attribute, and reports whether the span has it.
|
||||
// A name without a context is looked up in both.
|
||||
func (span *Span) selectAttribute(resource map[string]string, attributes map[string]any, field *telemetrytypes.TelemetryFieldKey) bool {
|
||||
found := false
|
||||
switch field.FieldContext {
|
||||
case telemetrytypes.FieldContextUnspecified, telemetrytypes.FieldContextResource:
|
||||
if value, ok := resource[field.Name]; ok {
|
||||
span.Resource[field.Name], found = value, true
|
||||
}
|
||||
}
|
||||
switch field.FieldContext {
|
||||
case telemetrytypes.FieldContextUnspecified, telemetrytypes.FieldContextAttribute, telemetrytypes.FieldContextSpan:
|
||||
if value, ok := attributes[field.Name]; ok {
|
||||
span.Attributes[field.Name], found = value, true
|
||||
}
|
||||
}
|
||||
// The context word can be part of an attribute name, as in an attribute named resource.type.
|
||||
if text := telemetrytypes.TelemetryFieldKeyToText(field); !found {
|
||||
if value, ok := attributes[text]; ok {
|
||||
span.Attributes[text], found = value, true
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
func setString(target *string, value string) bool {
|
||||
*target = value
|
||||
return value != ""
|
||||
}
|
||||
|
||||
func pageLimit(name string, value, fallback int) (int, error) {
|
||||
switch {
|
||||
case value < 0 || value > spanListMaxLimit:
|
||||
return 0, errors.NewInvalidInputf(ErrCodeTraceSpansInvalidLimit, "%s must be between 1 and %d, got %d", name, spanListMaxLimit, value)
|
||||
case value == 0:
|
||||
return fallback, nil
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
// page cuts one page out of the spans of scope. A view keeps the ones of its kind, in its own order.
|
||||
func (skeleton *TraceSkeleton) page(scope []int32, view SpanListView, offset, limit int) *SpanListPage {
|
||||
positions := scope
|
||||
if view != "" {
|
||||
positions = skeleton.viewPositions(view, scope)
|
||||
}
|
||||
page := &SpanListPage{skeleton: skeleton, view: view, total: uint64(len(positions))}
|
||||
if offset < len(positions) {
|
||||
page.positions = positions[offset:min(offset+limit, len(positions))]
|
||||
}
|
||||
return page
|
||||
}
|
||||
|
||||
// scopePositions lists the spans a scope covers, in the scope's own order.
|
||||
func (skeleton *TraceSkeleton) scopePositions(scope SpanScope, spanID string) ([]int32, error) {
|
||||
if scope == SpanScopeTrace {
|
||||
return skeleton.treeOrder, nil
|
||||
}
|
||||
span, ok := skeleton.position(spanID)
|
||||
if !ok {
|
||||
return nil, errors.NewNotFoundf(ErrCodeTraceSpanNotFound, "span %s not found in trace %s", spanID, skeleton.traceID)
|
||||
}
|
||||
switch scope {
|
||||
case SpanScopeChildren:
|
||||
return skeleton.children(span), nil
|
||||
case SpanScopeDescendants:
|
||||
// The spans below a span follow it directly in tree order.
|
||||
at := slices.Index(skeleton.treeOrder, span)
|
||||
return skeleton.treeOrder[at+1 : at+1+int(skeleton.descendantCount[span])], nil
|
||||
case SpanScopeAncestors:
|
||||
ancestors := make([]int32, 0, skeleton.level[span])
|
||||
for parent := skeleton.parents[span]; parent != noParent; parent = skeleton.parents[parent] {
|
||||
ancestors = append(ancestors, parent)
|
||||
}
|
||||
return ancestors, nil
|
||||
}
|
||||
return nil, errors.NewInternalf(errors.CodeInternal, "unknown span scope %q", string(scope))
|
||||
}
|
||||
|
||||
// viewPositions lists the spans of scope that are in a view, in the order of the view.
|
||||
func (skeleton *TraceSkeleton) viewPositions(view SpanListView, scope []int32) []int32 {
|
||||
switch view {
|
||||
case SpanListViewErrorOrigins:
|
||||
return skeleton.spansWhere(scope, skeleton.errorStartsAt)
|
||||
case SpanListViewUnmarkedFailures:
|
||||
return skeleton.spansWhere(scope, func(i int32) bool { return skeleton.unmarkedFailureKind(i) != "" })
|
||||
case SpanListViewLinks:
|
||||
return skeleton.spansWhere(scope, func(i int32) bool { return skeleton.hasLink[i] })
|
||||
case SpanListViewTimeSpent:
|
||||
return skeleton.timeSpentSpans(scope)
|
||||
case SpanListViewAIUsage:
|
||||
return skeleton.aiUsageSpans(scope)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// errorStartsAt reports whether span i is an error span with no error span among its children.
|
||||
func (skeleton *TraceSkeleton) errorStartsAt(i int32) bool {
|
||||
return skeleton.hasError[i] && !slices.ContainsFunc(skeleton.children(i), func(child int32) bool { return skeleton.hasError[child] })
|
||||
}
|
||||
|
||||
// spansWhere lists the spans of scope that match, in start time order.
|
||||
func (skeleton *TraceSkeleton) spansWhere(scope []int32, match func(i int32) bool) []int32 {
|
||||
spans := make([]int32, 0)
|
||||
for _, i := range scope {
|
||||
if match(i) {
|
||||
spans = append(spans, i)
|
||||
}
|
||||
}
|
||||
slices.Sort(spans)
|
||||
return spans
|
||||
}
|
||||
|
||||
// timeSpentSpans lists one span for each sibling group in scope, its longest there, the group with
|
||||
// the most own time first. Equal groups fall back to span order, so that every page cuts the same ranking.
|
||||
func (skeleton *TraceSkeleton) timeSpentSpans(scope []int32) []int32 {
|
||||
longest := slices.Repeat([]int32{-1}, len(skeleton.groups))
|
||||
for _, i := range scope {
|
||||
group := skeleton.groupOf[i]
|
||||
if longest[group] < 0 || skeleton.durationNano[i] > skeleton.durationNano[longest[group]] {
|
||||
longest[group] = i
|
||||
}
|
||||
}
|
||||
spans := slices.DeleteFunc(longest, func(i int32) bool { return i < 0 })
|
||||
groupOwnTime := func(i int32) uint64 { return skeleton.groups[skeleton.groupOf[i]].ownTime }
|
||||
slices.SortFunc(spans, func(a, b int32) int {
|
||||
return cmp.Or(cmp.Compare(groupOwnTime(b), groupOwnTime(a)), cmp.Compare(a, b))
|
||||
})
|
||||
return spans
|
||||
}
|
||||
|
||||
// aiUsageSpans lists the spans of scope that carry gen_ai usage by cost, or by tokens when none
|
||||
// of them carries a cost; equal spans fall back to span order.
|
||||
func (skeleton *TraceSkeleton) aiUsageSpans(scope []int32) []int32 {
|
||||
spans := skeleton.spansWhere(scope, func(i int32) bool {
|
||||
_, ok := skeleton.aiUsage[i]
|
||||
return ok
|
||||
})
|
||||
hasCost := slices.ContainsFunc(spans, func(i int32) bool { return skeleton.aiUsage[i].Cost != nil })
|
||||
weight := func(i int32) float64 {
|
||||
usage := skeleton.aiUsage[i]
|
||||
if hasCost {
|
||||
return floatValue(usage.Cost)
|
||||
}
|
||||
return floatValue(usage.InputTokens) + floatValue(usage.OutputTokens)
|
||||
}
|
||||
slices.SortFunc(spans, func(a, b int32) int {
|
||||
return cmp.Or(cmp.Compare(weight(b), weight(a)), cmp.Compare(a, b))
|
||||
})
|
||||
return spans
|
||||
}
|
||||
|
||||
// span returns span i with service.name as its only resource attribute.
|
||||
func (skeleton *TraceSkeleton) span(i int32) Span {
|
||||
return Span{
|
||||
SpanID: skeleton.spanID(i),
|
||||
TraceID: skeleton.traceID,
|
||||
ParentSpanID: skeleton.parentSpanID(i),
|
||||
Name: skeleton.stringTable[skeleton.names[i]],
|
||||
KindString: skeleton.stringTable[skeleton.kinds[i]],
|
||||
TimeUnix: uint64(skeleton.startNano[i] / 1_000_000),
|
||||
DurationNano: skeleton.durationNano[i],
|
||||
HasError: skeleton.hasError[i],
|
||||
StatusCodeString: skeleton.stringTable[skeleton.statusCodeStrings[i]],
|
||||
StatusMessage: skeleton.stringTable[skeleton.statusMessages[i]],
|
||||
ResponseStatusCode: skeleton.stringTable[skeleton.responseStatusCodes[i]],
|
||||
Resource: map[string]string{"service.name": skeleton.stringTable[skeleton.services[i]]},
|
||||
Attributes: map[string]any{},
|
||||
Events: []Event{},
|
||||
References: skeleton.spanReferences(i),
|
||||
}
|
||||
}
|
||||
|
||||
func (skeleton *TraceSkeleton) setUsageAttributes(span *Span, i int32) {
|
||||
usage := skeleton.aiUsage[i]
|
||||
for key, value := range map[string]*float64{
|
||||
aiobservabilitytypes.GenAIUsageInputTokens: usage.InputTokens,
|
||||
aiobservabilitytypes.GenAIUsageOutputTokens: usage.OutputTokens,
|
||||
aiobservabilitytypes.GenAIUsageCacheReadInputTokens: usage.CacheReadTokens,
|
||||
aiobservabilitytypes.GenAIUsageCacheCreationInputTokens: usage.CacheWriteTokens,
|
||||
aiobservabilitytypes.GenAIUsageReasoningOutputTokens: usage.ReasoningTokens,
|
||||
aiobservabilitytypes.SignozGenAITotalCost: usage.Cost,
|
||||
} {
|
||||
if value != nil {
|
||||
span.Attributes[key] = *value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func floatValue(value *float64) float64 {
|
||||
if value == nil {
|
||||
return 0
|
||||
}
|
||||
return *value
|
||||
}
|
||||
268
pkg/types/spantypes/trace_span_list_test.go
Normal file
268
pkg/types/spantypes/trace_span_list_test.go
Normal file
@@ -0,0 +1,268 @@
|
||||
package spantypes
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
|
||||
)
|
||||
|
||||
// checkoutSkeleton is one request with a failing payment call, a group of same-name queries and
|
||||
// an orphan. usage sets the gen_ai usage of the named spans.
|
||||
func checkoutSkeleton(usage map[string]AISpanUsage) *TraceSkeleton {
|
||||
return buildSkeleton(
|
||||
skeletonSpec{id: "root", name: "POST /checkout", service: "web", startMs: 0, durationMs: 100, hasError: true},
|
||||
skeletonSpec{id: "pay", parent: "root", name: "charge", service: "payment", startMs: 0, durationMs: 40, hasError: true, hasLink: true},
|
||||
skeletonSpec{id: "grpc", parent: "pay", name: "Charge", service: "payment", startMs: 5, durationMs: 5, statusCode: "14", usage: usage["grpc"]},
|
||||
skeletonSpec{id: "caught", parent: "pay", name: "retry", service: "payment", startMs: 10, durationMs: 5, hasException: true},
|
||||
skeletonSpec{id: "q1", parent: "root", name: "SELECT", service: "db", startMs: 40, durationMs: 10, usage: usage["q1"]},
|
||||
skeletonSpec{id: "q2", parent: "root", name: "SELECT", service: "db", startMs: 50, durationMs: 25, hasLink: true, usage: usage["q2"]},
|
||||
skeletonSpec{id: "auth", parent: "root", name: "GET /auth", service: "auth", startMs: 75, durationMs: 5, statusCode: "404", usage: usage["auth"]},
|
||||
skeletonSpec{id: "orphan", parent: "gone", name: "flush", service: "worker", startMs: 90, durationMs: 60},
|
||||
)
|
||||
}
|
||||
|
||||
func TestTraceSkeletonPage_Ranking(t *testing.T) {
|
||||
value := func(v float64) *float64 { return &v }
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
view SpanListView
|
||||
usage map[string]AISpanUsage
|
||||
expected []string
|
||||
}{
|
||||
{
|
||||
// own time: orphan 60, the two SELECTs 35 together, pay 30, root 20, then the 5s in start order.
|
||||
name: "TimeSpent_GroupsSameNameSiblings",
|
||||
view: SpanListViewTimeSpent,
|
||||
expected: []string{"orphan", "q2", "pay", "root", "grpc", "caught", "auth"},
|
||||
},
|
||||
{
|
||||
// grpc has tokens and no cost, so it ranks last.
|
||||
name: "AIUsage_ByCost",
|
||||
view: SpanListViewAIUsage,
|
||||
usage: map[string]AISpanUsage{"q1": {Cost: value(0.01)}, "auth": {Cost: value(0.5)}, "grpc": {InputTokens: value(900)}},
|
||||
expected: []string{"auth", "q1", "grpc"},
|
||||
},
|
||||
{
|
||||
// auth carries no token or cost value, so it is not listed.
|
||||
name: "AIUsage_ByTokensWhenNoSpanHasACost",
|
||||
view: SpanListViewAIUsage,
|
||||
usage: map[string]AISpanUsage{"q1": {InputTokens: value(10), OutputTokens: value(5)}, "q2": {InputTokens: value(100)}, "auth": {}},
|
||||
expected: []string{"q2", "q1"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
skeleton := checkoutSkeleton(testCase.usage)
|
||||
page := skeleton.page(skeleton.treeOrder, testCase.view, 0, 50)
|
||||
assert.Equal(t, testCase.expected, spanIDsOf(skeleton, page.positions))
|
||||
assert.Equal(t, uint64(len(testCase.expected)), page.total)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTraceSkeletonPage_CutsTheViewOfTheGivenSpans(t *testing.T) {
|
||||
skeleton := checkoutSkeleton(nil)
|
||||
|
||||
// Among the children of root: the two SELECTs as one, then pay, then auth.
|
||||
page := skeleton.page(skeleton.children(positionOf(t, skeleton, "root")), SpanListViewTimeSpent, 1, 5)
|
||||
assert.Equal(t, []string{"pay", "auth"}, spanIDsOf(skeleton, page.positions))
|
||||
assert.Equal(t, uint64(3), page.total)
|
||||
}
|
||||
|
||||
func TestNewSpanList_OnlyAIUsageCarriesUsageAttributes(t *testing.T) {
|
||||
value := func(v float64) *float64 { return &v }
|
||||
skeleton := checkoutSkeleton(map[string]AISpanUsage{"q1": {InputTokens: value(120), OutputTokens: value(30), Cost: value(0.02)}})
|
||||
|
||||
usage := NewSpanList(skeleton.page(skeleton.treeOrder, SpanListViewAIUsage, 0, 50), nil)
|
||||
require.Len(t, usage.Items, 1)
|
||||
assert.Equal(t, map[string]any{"gen_ai.usage.input_tokens": 120.0, "gen_ai.usage.output_tokens": 30.0, "signoz.gen_ai.usage.tokens.cost": 0.02}, usage.Items[0].Span.Attributes)
|
||||
|
||||
// The same span in any other list carries no attributes.
|
||||
for _, item := range NewSpanList(skeleton.page(skeleton.treeOrder, "", 0, 50), nil).Items {
|
||||
assert.Empty(t, item.Span.Attributes, item.Span.SpanID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewSpanListPage(t *testing.T) {
|
||||
// root ─┬─ pay ─┬─ grpc
|
||||
// │ └─ caught
|
||||
// ├─ q1
|
||||
// ├─ q2
|
||||
// └─ auth
|
||||
// orphan (its parent was never received)
|
||||
testCases := []struct {
|
||||
name string
|
||||
query SpanListQuery
|
||||
expected []string
|
||||
expectedTotal uint64
|
||||
}{
|
||||
{
|
||||
name: "Trace_TreeOrder",
|
||||
query: SpanListQuery{Scope: SpanScopeTrace, Limit: 50},
|
||||
expected: []string{"root", "pay", "grpc", "caught", "q1", "q2", "auth", "orphan"},
|
||||
expectedTotal: 8,
|
||||
},
|
||||
{
|
||||
name: "Trace_OffsetAndLimit_KeepsTotal",
|
||||
query: SpanListQuery{Scope: SpanScopeTrace, Offset: 6, Limit: 5},
|
||||
expected: []string{"auth", "orphan"},
|
||||
expectedTotal: 8,
|
||||
},
|
||||
{
|
||||
name: "Children_OneLevel_StartOrder",
|
||||
query: SpanListQuery{Scope: SpanScopeChildren, ScopeSpanID: "root", Limit: 50},
|
||||
expected: []string{"pay", "q1", "q2", "auth"},
|
||||
expectedTotal: 4,
|
||||
},
|
||||
{
|
||||
name: "Descendants_TreeOrder",
|
||||
query: SpanListQuery{Scope: SpanScopeDescendants, ScopeSpanID: "pay", Limit: 50},
|
||||
expected: []string{"grpc", "caught"},
|
||||
expectedTotal: 2,
|
||||
},
|
||||
{
|
||||
name: "Ancestors_ParentFirst",
|
||||
query: SpanListQuery{Scope: SpanScopeAncestors, ScopeSpanID: "grpc", Limit: 50},
|
||||
expected: []string{"pay", "root"},
|
||||
expectedTotal: 2,
|
||||
},
|
||||
{
|
||||
name: "Ancestors_StopAtMissingParent",
|
||||
query: SpanListQuery{Scope: SpanScopeAncestors, ScopeSpanID: "orphan", Limit: 50},
|
||||
expected: []string{},
|
||||
},
|
||||
{
|
||||
// root carries the error up from pay, so it is not where the error starts.
|
||||
name: "Ancestors_View_OnlySpansOfTheView",
|
||||
query: SpanListQuery{Scope: SpanScopeAncestors, ScopeSpanID: "grpc", View: SpanListViewErrorOrigins, Limit: 50},
|
||||
expected: []string{"pay"},
|
||||
expectedTotal: 1,
|
||||
},
|
||||
{
|
||||
// orphan and root rank in the view too, but are not below root.
|
||||
name: "Descendants_View_OnlySpansInScope",
|
||||
query: SpanListQuery{Scope: SpanScopeDescendants, ScopeSpanID: "root", View: SpanListViewTimeSpent, Limit: 50},
|
||||
expected: []string{"q2", "pay", "grpc", "caught", "auth"},
|
||||
expectedTotal: 5,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
page, err := NewSpanListPage(checkoutSkeleton(nil), &testCase.query)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testCase.expected, page.SpanIDs())
|
||||
assert.Equal(t, testCase.expectedTotal, page.total)
|
||||
})
|
||||
}
|
||||
|
||||
_, err := NewSpanListPage(checkoutSkeleton(nil), &SpanListQuery{Scope: SpanScopeChildren, ScopeSpanID: "missing", Limit: 50})
|
||||
assert.True(t, errors.Ast(err, errors.TypeNotFound))
|
||||
}
|
||||
|
||||
func TestNewSpanListPage_TimeSpent_ShowsTheGroupByItsLongestSpanInScope(t *testing.T) {
|
||||
// root ─┬─ q1 (SELECT, 10 ms) ── row
|
||||
// └─ q2 (SELECT, 25 ms)
|
||||
// q2 is the longest SELECT, but only q1 is an ancestor of row.
|
||||
skeleton := buildSkeleton(
|
||||
skeletonSpec{id: "root", name: "GET /orders", service: "web", startMs: 0, durationMs: 100},
|
||||
skeletonSpec{id: "q1", parent: "root", name: "SELECT", service: "db", startMs: 10, durationMs: 10},
|
||||
skeletonSpec{id: "row", parent: "q1", name: "decode", service: "db", startMs: 12, durationMs: 2},
|
||||
skeletonSpec{id: "q2", parent: "root", name: "SELECT", service: "db", startMs: 30, durationMs: 25},
|
||||
)
|
||||
|
||||
page, err := NewSpanListPage(skeleton, &SpanListQuery{Scope: SpanScopeAncestors, ScopeSpanID: "row", View: SpanListViewTimeSpent, Limit: 50})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"root", "q1"}, page.SpanIDs())
|
||||
|
||||
page, err = NewSpanListPage(skeleton, &SpanListQuery{Scope: SpanScopeTrace, View: SpanListViewTimeSpent, Limit: 50})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"root", "q2", "row"}, page.SpanIDs())
|
||||
}
|
||||
|
||||
func TestNewSpanListPage_AIUsage_RanksByTokensWhenNoListedSpanHasACost(t *testing.T) {
|
||||
value := func(v float64) *float64 { return &v }
|
||||
// agent ─┬─ plan (cost)
|
||||
// └─ tools ─┬─ search (10 tokens)
|
||||
// └─ fetch (100 tokens)
|
||||
skeleton := buildSkeleton(
|
||||
skeletonSpec{id: "agent"},
|
||||
skeletonSpec{id: "plan", parent: "agent", usage: AISpanUsage{Cost: value(0.5)}},
|
||||
skeletonSpec{id: "tools", parent: "agent"},
|
||||
skeletonSpec{id: "search", parent: "tools", usage: AISpanUsage{InputTokens: value(10)}},
|
||||
skeletonSpec{id: "fetch", parent: "tools", usage: AISpanUsage{InputTokens: value(100)}},
|
||||
)
|
||||
|
||||
page, err := NewSpanListPage(skeleton, &SpanListQuery{Scope: SpanScopeChildren, ScopeSpanID: "tools", View: SpanListViewAIUsage, Limit: 50})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"fetch", "search"}, page.SpanIDs())
|
||||
}
|
||||
|
||||
// A name is read the way the query builder reads a select field of a trace list.
|
||||
func TestNewSpanList_SelectFields(t *testing.T) {
|
||||
skeleton := buildSkeleton(skeletonSpec{id: "root", name: "POST /checkout", service: "web"})
|
||||
rows := []StorableSpan{{
|
||||
SpanID: "root",
|
||||
AttributesString: map[string]string{"http.route": "/checkout", "env": "span-env", "name": "an attribute", "resource.type": "db"},
|
||||
ResourceJSON: jsonAttrs(map[string]any{"env": "resource-env"}),
|
||||
HTTPMethod: "POST",
|
||||
Scope: scopeColumn("", "", map[string]any{"lib.lang": "go", "team": "payments"}),
|
||||
}}
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
field string
|
||||
attributes map[string]any
|
||||
resource map[string]string
|
||||
httpMethod string
|
||||
scope Scope
|
||||
warnings []string
|
||||
}{
|
||||
{name: "NoContext_BothSides", field: "env", attributes: map[string]any{"env": "span-env"}, resource: map[string]string{"service.name": "web", "env": "resource-env"}},
|
||||
{name: "ResourceContext_OneSide", field: "resource.env", attributes: map[string]any{}, resource: map[string]string{"service.name": "web", "env": "resource-env"}},
|
||||
{name: "AttributeContext_OneSide", field: "attribute.env", attributes: map[string]any{"env": "span-env"}, resource: map[string]string{"service.name": "web"}},
|
||||
{name: "SpanContext_ReadsTheAttribute", field: "span.http.route", attributes: map[string]any{"http.route": "/checkout"}, resource: map[string]string{"service.name": "web"}},
|
||||
{name: "ContextWord_PartOfTheAttributeName", field: "resource.type", attributes: map[string]any{"resource.type": "db"}, resource: map[string]string{"service.name": "web"}},
|
||||
// The span already carries its name, and the attribute called name needs attribute.name.
|
||||
{name: "SpanField_Returned_NotReadAsAnAttribute", field: "name", attributes: map[string]any{}, resource: map[string]string{"service.name": "web"}},
|
||||
{name: "SpanField_Selected", field: "http_method", attributes: map[string]any{}, resource: map[string]string{"service.name": "web"}, httpMethod: "POST"},
|
||||
{name: "SpanField_EmptyOnTheSpan_Warns", field: "db_name", attributes: map[string]any{}, resource: map[string]string{"service.name": "web"}, warnings: []string{"field `db_name` was not found on any returned span"}},
|
||||
{name: "ScopeField_EmptyOnTheSpan_Warns", field: "scope.name", attributes: map[string]any{}, resource: map[string]string{"service.name": "web"}, warnings: []string{"field `scope.name` was not found on any returned span"}},
|
||||
{name: "ScopeAttribute_Selected", field: "scope.lib.lang", attributes: map[string]any{}, resource: map[string]string{"service.name": "web"}, scope: Scope{"attributes": map[string]any{"lib.lang": "go"}}},
|
||||
{name: "ScopeAttribute_Missing_Warns", field: "scope.nope", attributes: map[string]any{}, resource: map[string]string{"service.name": "web"}, warnings: []string{"field `scope.nope` was not found on any returned span"}},
|
||||
{name: "Unknown_Warns", field: "nope", attributes: map[string]any{}, resource: map[string]string{"service.name": "web"}, warnings: []string{"field `nope` was not found on any returned span"}},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
page := skeleton.page(skeleton.treeOrder, "", 0, 50)
|
||||
page.selectFields = []telemetrytypes.TelemetryFieldKey{newSelectField(testCase.field)}
|
||||
|
||||
list := NewSpanList(page, rows)
|
||||
require.Len(t, list.Items, 1)
|
||||
assert.Equal(t, testCase.attributes, list.Items[0].Span.Attributes)
|
||||
assert.Equal(t, testCase.resource, list.Items[0].Span.Resource)
|
||||
assert.Equal(t, testCase.httpMethod, list.Items[0].Span.HTTPMethod)
|
||||
assert.Equal(t, testCase.scope, list.Items[0].Span.Scope)
|
||||
assert.Equal(t, testCase.warnings, list.Warnings)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewSpanList_SelectScopeFields_KeepsEachAttribute(t *testing.T) {
|
||||
skeleton := buildSkeleton(skeletonSpec{id: "root", name: "GET /cart", service: "cart"})
|
||||
rows := []StorableSpan{{SpanID: "root", Scope: scopeColumn("io.opentelemetry.http", "1.2.0", map[string]any{"lib.lang": "go", "team": "payments"})}}
|
||||
page := skeleton.page(skeleton.treeOrder, "", 0, 50)
|
||||
page.selectFields = []telemetrytypes.TelemetryFieldKey{newSelectField("scope.lib.lang"), newSelectField("scope.name"), newSelectField("scope.team")}
|
||||
|
||||
list := NewSpanList(page, rows)
|
||||
require.Len(t, list.Items, 1)
|
||||
assert.Equal(t, Scope{"name": "io.opentelemetry.http", "attributes": map[string]any{"lib.lang": "go", "team": "payments"}}, list.Items[0].Span.Scope)
|
||||
assert.Empty(t, list.Warnings)
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package spantypes
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"maps"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
@@ -113,7 +112,7 @@ type StorableSpan struct {
|
||||
AttributesNumber map[string]float64 `ch:"attributes_number"`
|
||||
AttributesBool map[string]bool `ch:"attributes_bool"`
|
||||
AttributesJSON telemetrystoretypes.JSONValue `ch:"attributes"`
|
||||
ResourcesString map[string]string `ch:"resources_string"`
|
||||
ResourceJSON telemetrystoretypes.JSONValue `ch:"resource"`
|
||||
Scope telemetrystoretypes.JSONValue `ch:"scope"`
|
||||
Events []string `ch:"events"`
|
||||
StatusMessage string `ch:"status_message"`
|
||||
@@ -296,6 +295,16 @@ func (item *StorableSpan) Attributes() map[string]any {
|
||||
return attributes
|
||||
}
|
||||
|
||||
// Resource flattens the JSON column into dotted keys, rendering non-string values as text.
|
||||
func (item *StorableSpan) Resource() map[string]string {
|
||||
flat := item.ResourceJSON.Flatten()
|
||||
resource := make(map[string]string, len(flat))
|
||||
for key, value := range flat {
|
||||
resource[key] = fmt.Sprint(value)
|
||||
}
|
||||
return resource
|
||||
}
|
||||
|
||||
func (item *StorableSpan) UnmarshalledEvents() []Event {
|
||||
events := make([]Event, 0, len(item.Events))
|
||||
for _, eventStr := range item.Events {
|
||||
@@ -317,9 +326,6 @@ func (item *StorableSpan) UnmarshalledRefs() []OtelSpanRef {
|
||||
}
|
||||
|
||||
func (item *StorableSpan) ToWaterfallSpan(traceID string) *WaterfallSpan {
|
||||
resources := make(map[string]string)
|
||||
maps.Copy(resources, item.ResourcesString)
|
||||
|
||||
formatted := aiobservabilitytypes.FormatMessages(item.AttributesJSON.Nest())
|
||||
return &WaterfallSpan{
|
||||
Attributes: item.Attributes(),
|
||||
@@ -339,7 +345,7 @@ func (item *StorableSpan) ToWaterfallSpan(traceID string) *WaterfallSpan {
|
||||
KindString: item.SpanKind,
|
||||
Name: item.Name,
|
||||
ParentSpanID: item.ParentSpanID,
|
||||
Resource: resources,
|
||||
Resource: item.Resource(),
|
||||
Scope: NewScope(item.Scope.Flatten()),
|
||||
ResponseStatusCode: item.ResponseStatusCode,
|
||||
SpanID: item.SpanID,
|
||||
|
||||
11
tests/e2e/drivers/meter.ts
generated
11
tests/e2e/drivers/meter.ts
generated
@@ -26,6 +26,14 @@ export const METER_EXPLORER_PATH = '/meter/explorer';
|
||||
|
||||
export type MeterSection = 'total' | 'logs' | 'traces' | 'metrics';
|
||||
|
||||
// Section ids derive from the first panel id in frontend/src/container/MeterExplorer/Breakdown/dashboard.ts.
|
||||
const SECTION_FIRST_PANEL: Record<MeterSection, string> = {
|
||||
total: 'total-log-size',
|
||||
logs: 'log-count',
|
||||
traces: 'span-count',
|
||||
metrics: 'metric-datapoints',
|
||||
};
|
||||
|
||||
export interface MeterBreakdown {
|
||||
/** Open `/meter` and return the `query_range` responses its widgets fire. */
|
||||
goto(): Promise<Response[]>;
|
||||
@@ -58,7 +66,8 @@ export function meterDriver(page: Page): Meter {
|
||||
page.off('response', collect);
|
||||
return responses;
|
||||
},
|
||||
section: (name) => page.getByTestId(`meter-breakdown-section-${name}`),
|
||||
section: (name) =>
|
||||
page.getByTestId(`dashboard-section-sec-${SECTION_FIRST_PANEL[name]}`),
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
7
tests/fixtures/traces.py
vendored
7
tests/fixtures/traces.py
vendored
@@ -184,16 +184,19 @@ class TracesEvent(ABC):
|
||||
name: str
|
||||
time_unix_nano: np.uint64
|
||||
attribute_map: dict[str, str]
|
||||
is_error: bool
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
timestamp: datetime.datetime,
|
||||
attribute_map: dict[str, str] = {},
|
||||
is_error: bool = False,
|
||||
) -> None:
|
||||
self.name = name
|
||||
self.time_unix_nano = np.uint64(int(timestamp.timestamp() * 1e9))
|
||||
self.attribute_map = attribute_map
|
||||
self.is_error = is_error
|
||||
|
||||
def np_arr(self) -> np.array:
|
||||
return np.array([self.name, self.time_unix_nano, json.dumps(self.attribute_map)])
|
||||
@@ -598,13 +601,15 @@ class Traces(ABC):
|
||||
)
|
||||
# DB shape per event: {"name", "timeUnixNano", "attributeMap"}. Must match
|
||||
# what the consume-layer parser in pkg/types/spantypes expects.
|
||||
# The collector writes isError only when it is set.
|
||||
self._events_db = [
|
||||
json.dumps(
|
||||
{
|
||||
"name": event.name,
|
||||
"timeUnixNano": int(event.time_unix_nano),
|
||||
"attributeMap": dict(event.attribute_map),
|
||||
},
|
||||
}
|
||||
| ({"isError": True} if event.is_error else {}),
|
||||
separators=(",", ":"),
|
||||
)
|
||||
for event in events
|
||||
|
||||
194
tests/integration/tests/tracedetail/05_highlights.py
Normal file
194
tests/integration/tests/tracedetail/05_highlights.py
Normal file
@@ -0,0 +1,194 @@
|
||||
from collections.abc import Callable
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from http import HTTPStatus
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from fixtures import types
|
||||
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
|
||||
from fixtures.querier import get_attribute_backend_now
|
||||
from fixtures.traces import TraceIdGenerator, Traces, TracesEvent, TracesKind, TracesLink, TracesRefType, TracesStatusCode
|
||||
|
||||
SPAN_LISTS = ("errorOrigins", "unmarkedFailures", "timeSpent", "aiUsage", "links")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("attribute_backend", ["map", "json"])
|
||||
def test_trace_highlights(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
attribute_backend: str,
|
||||
) -> None:
|
||||
"""Attributes are written to one layout only, so a read from the wrong column loses them."""
|
||||
now = get_attribute_backend_now(signoz, attribute_backend).replace(second=0, microsecond=0)
|
||||
write_mode = "json_only" if attribute_backend == "json" else "legacy_only"
|
||||
trace_id = TraceIdGenerator.trace_id()
|
||||
other_trace_id = TraceIdGenerator.trace_id()
|
||||
names = ("root", "place_order", "charge_card", "inventory_http", "inventory_grpc", "render", "notify", "consume", "model", "tool")
|
||||
ids = {name: TraceIdGenerator.span_id() for name in names}
|
||||
gateway, orders, agent = (f"td-highlights-{service}-{attribute_backend}" for service in ("gateway", "orders", "agent"))
|
||||
start = now - timedelta(seconds=10)
|
||||
|
||||
def span(key: str, parent: str, name: str, service: str, offset_ms: int, duration_ms: int, **kwargs) -> Traces:
|
||||
return Traces(
|
||||
timestamp=start + timedelta(milliseconds=offset_ms),
|
||||
duration=timedelta(milliseconds=duration_ms),
|
||||
trace_id=trace_id,
|
||||
span_id=ids[key],
|
||||
parent_span_id=ids[parent] if parent else "",
|
||||
name=name,
|
||||
resources={"service.name": service, "k8s.pod.name": f"{service}-0"},
|
||||
attribute_write_mode=write_mode,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
insert_traces(
|
||||
[
|
||||
span("root", "", "POST /checkout", gateway, 0, 1000, kind=TracesKind.SPAN_KIND_SERVER, status_code=TracesStatusCode.STATUS_CODE_ERROR, attributes={"http.response.status_code": 500}),
|
||||
# the error is carried up from charge_card through place_order to the root
|
||||
span("place_order", "root", "place_order", orders, 10, 600, status_code=TracesStatusCode.STATUS_CODE_ERROR),
|
||||
span("charge_card", "place_order", "charge_card", orders, 20, 300, kind=TracesKind.SPAN_KIND_CLIENT, status_code=TracesStatusCode.STATUS_CODE_ERROR, status_message="card declined", attributes={"payment.provider": "worldpay"}),
|
||||
# four failures that do not carry the error flag
|
||||
span("inventory_http", "place_order", "GET /inventory", orders, 330, 40, kind=TracesKind.SPAN_KIND_CLIENT, attributes={"http.response.status_code": 404}),
|
||||
span("inventory_grpc", "place_order", "inventory.Check", orders, 380, 40, kind=TracesKind.SPAN_KIND_CLIENT, attributes={"rpc.grpc.status_code": 5}),
|
||||
span("render", "root", "render_receipt", gateway, 700, 50, events=[TracesEvent("exception", now, {"exception.message": "template missing, fell back"}, is_error=True)]),
|
||||
span("notify", "root", "POST /notify", gateway, 752, 5, kind=TracesKind.SPAN_KIND_CLIENT, attributes={"http.response.status_code": 503}),
|
||||
# a link out to another trace
|
||||
span("consume", "root", "consume order.created", orders, 760, 20, kind=TracesKind.SPAN_KIND_CONSUMER, links=[TracesLink(trace_id=other_trace_id, span_id="aaaaaaaaaaaaaaaa", ref_type=TracesRefType.REF_TYPE_FOLLOWS_FROM)]),
|
||||
span("model", "root", "chat gpt-4o-mini", agent, 800, 100, kind=TracesKind.SPAN_KIND_CLIENT, attributes={"gen_ai.request.model": "gpt-4o-mini", "gen_ai.usage.input_tokens": 100, "gen_ai.usage.output_tokens": 20, "signoz.gen_ai.usage.tokens.cost": 0.01}),
|
||||
span("tool", "root", "execute_tool", agent, 910, 30, attributes={"gen_ai.tool.name": "get_weather"}),
|
||||
]
|
||||
)
|
||||
|
||||
headers = {"authorization": f"Bearer {get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)}"}
|
||||
response = requests.get(signoz.self.host_configs["8080"].get(f"/api/v1/traces/{trace_id}/highlights"), headers=headers, timeout=10)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
highlights = response.json()["data"]
|
||||
|
||||
# own time is the duration minus what the children cover
|
||||
assert [(service["serviceName"], service["spanCount"], service["errorSpanCount"], service["ownTimeNano"]) for service in highlights["services"]] == [
|
||||
(orders, 5, 2, 620_000_000),
|
||||
(gateway, 3, 1, 250_000_000),
|
||||
(agent, 2, 0, 130_000_000),
|
||||
]
|
||||
|
||||
# one entry for the error, at the span that threw it
|
||||
errors = highlights["errorOrigins"]
|
||||
assert errors["total"] == 1
|
||||
error = errors["items"][0]
|
||||
assert error["span"] == {
|
||||
"span_id": ids["charge_card"],
|
||||
"trace_id": trace_id,
|
||||
"parent_span_id": ids["place_order"],
|
||||
"name": "charge_card",
|
||||
"kind_string": "Client",
|
||||
"time_unix": int(start.timestamp()) * 1_000 + 20,
|
||||
"duration_nano": 300_000_000,
|
||||
"has_error": True,
|
||||
"status_code_string": "STATUS_CODE_ERROR",
|
||||
"status_message": "card declined",
|
||||
"response_status_code": "",
|
||||
"resource": {"service.name": orders},
|
||||
"attributes": {},
|
||||
"events": [],
|
||||
"references": [{"traceId": trace_id, "spanId": ids["place_order"], "refType": "CHILD_OF"}],
|
||||
}
|
||||
assert error["treeStats"] == {"level": 2, "childCount": 0, "subtreeSpanCount": 0, "ownTimeNano": 300_000_000, "errorAncestorCount": 2}
|
||||
assert "unmarkedFailureKind" not in error
|
||||
assert "matches" not in error
|
||||
|
||||
unmarked = highlights["unmarkedFailures"]
|
||||
assert unmarked["total"] == 4
|
||||
assert [(item["span"]["span_id"], item["unmarkedFailureKind"]) for item in unmarked["items"]] == [(ids["inventory_http"], "http_4xx"), (ids["inventory_grpc"], "grpc_status"), (ids["render"], "exception_event"), (ids["notify"], "http_5xx")]
|
||||
assert unmarked["items"][0]["span"]["response_status_code"] == "404"
|
||||
|
||||
links = highlights["links"]
|
||||
assert links["total"] == 1
|
||||
assert links["items"][0]["span"]["span_id"] == ids["consume"]
|
||||
assert {"traceId": other_trace_id, "spanId": "aaaaaaaaaaaaaaaa", "refType": "FOLLOWS_FROM"} in links["items"][0]["span"]["references"]
|
||||
|
||||
# no other list carries attributes
|
||||
ai_usage = highlights["aiUsage"]
|
||||
# the tool span carries no token or cost value, so it is not listed
|
||||
assert ai_usage["total"] == 1
|
||||
assert ai_usage["items"][0]["span"]["span_id"] == ids["model"]
|
||||
assert ai_usage["items"][0]["span"]["attributes"] == {"gen_ai.usage.input_tokens": 100, "gen_ai.usage.output_tokens": 20, "signoz.gen_ai.usage.tokens.cost": pytest.approx(0.01)}
|
||||
|
||||
# every span is its own entry here, most own time first
|
||||
time_spent = highlights["timeSpent"]
|
||||
assert time_spent["total"] == 10
|
||||
assert [item["span"]["span_id"] for item in time_spent["items"][:3]] == [ids["charge_card"], ids["place_order"], ids["root"]]
|
||||
assert time_spent["items"][0]["treeStats"]["ownTimeNano"] == 300_000_000
|
||||
assert "sameNameSiblings" not in time_spent["items"][0]["treeStats"]
|
||||
assert time_spent["items"][1]["treeStats"] == {"level": 1, "childCount": 3, "subtreeSpanCount": 3, "ownTimeNano": 220_000_000, "errorAncestorCount": 1}
|
||||
|
||||
# the totals of the trace are not here: they come from the summary route
|
||||
assert set(highlights) == {"services", *SPAN_LISTS}
|
||||
for name in SPAN_LISTS:
|
||||
for item in highlights[name]["items"]:
|
||||
assert item["span"]["events"] == [], name
|
||||
assert list(item["span"]["resource"]) == ["service.name"], name
|
||||
|
||||
|
||||
def test_trace_highlights_limits(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
) -> None:
|
||||
now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
|
||||
trace_id = TraceIdGenerator.trace_id()
|
||||
root_id = TraceIdGenerator.span_id()
|
||||
resources = {"service.name": "td-highlights-limits"}
|
||||
start = now - timedelta(seconds=30)
|
||||
spans = [Traces(timestamp=start, duration=timedelta(seconds=20), trace_id=trace_id, span_id=root_id, name="POST /import", kind=TracesKind.SPAN_KIND_SERVER, resources=resources)]
|
||||
for i in range(150):
|
||||
failed = {"status_code": TracesStatusCode.STATUS_CODE_ERROR, "status_message": f"failure {i:03d}"} if i < 12 else {}
|
||||
spans.append(Traces(timestamp=start + timedelta(seconds=1, milliseconds=i * 10), duration=timedelta(milliseconds=5), trace_id=trace_id, span_id=TraceIdGenerator.span_id(), parent_span_id=root_id, name="write_item", resources=resources, **failed))
|
||||
insert_traces(spans)
|
||||
|
||||
url = signoz.self.host_configs["8080"].get(f"/api/v1/traces/{trace_id}/highlights")
|
||||
headers = {"authorization": f"Bearer {get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)}"}
|
||||
response = requests.get(url, headers=headers, timeout=10)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
highlights = response.json()["data"]
|
||||
|
||||
# the default: 10 spans of a list, with the total behind it
|
||||
assert highlights["errorOrigins"]["total"] == 12
|
||||
assert [item["span"]["status_message"] for item in highlights["errorOrigins"]["items"]] == [f"failure {i:03d}" for i in range(10)]
|
||||
assert highlights["aiUsage"] == {"total": 0, "items": []}
|
||||
|
||||
# the 150 same-name children are one entry of the timeSpent list, shown by one of them
|
||||
time_spent = highlights["timeSpent"]
|
||||
assert time_spent["total"] == 2
|
||||
group = next(item for item in time_spent["items"] if item["span"]["name"] == "write_item")
|
||||
assert group["treeStats"]["sameNameSiblings"] == {"spanCount": 150, "ownTimeNano": 150 * 5_000_000, "errorSpanCount": 12}
|
||||
assert group["span"]["parent_span_id"] == root_id
|
||||
root = next(item for item in time_spent["items"] if item["span"]["span_id"] == root_id)
|
||||
assert root["treeStats"]["childCount"] == 150
|
||||
assert root["treeStats"]["subtreeSpanCount"] == 150
|
||||
|
||||
sized = requests.get(url, params={"limit": 3}, headers=headers, timeout=10).json()["data"]
|
||||
assert len(sized["errorOrigins"]["items"]) == 3
|
||||
assert sized["errorOrigins"]["total"] == 12
|
||||
|
||||
# the highest value accepted returns everything
|
||||
largest = requests.get(url, params={"limit": 1000}, headers=headers, timeout=10)
|
||||
assert largest.status_code == HTTPStatus.OK, largest.text
|
||||
assert len(largest.json()["data"]["errorOrigins"]["items"]) == 12
|
||||
|
||||
# views names the lists to return; the others are left out
|
||||
picked = requests.get(url, params={"views": ["error_origins", "time_spent"]}, headers=headers, timeout=10)
|
||||
assert picked.status_code == HTTPStatus.OK, picked.text
|
||||
assert set(picked.json()["data"]) == {"services", "errorOrigins", "timeSpent"}
|
||||
assert picked.json()["data"]["errorOrigins"]["total"] == 12
|
||||
assert picked.json()["data"]["timeSpent"]["total"] == 2
|
||||
|
||||
for params in ({"limit": 1001}, {"limit": -1}, {"views": "fastest"}, {"views": "all"}):
|
||||
response = requests.get(url, params=params, headers=headers, timeout=10)
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST, f"{params}: {response.text}"
|
||||
|
||||
unknown = requests.get(signoz.self.host_configs["8080"].get(f"/api/v1/traces/{TraceIdGenerator.trace_id()}/highlights"), headers=headers, timeout=10)
|
||||
assert unknown.status_code == HTTPStatus.NOT_FOUND, unknown.text
|
||||
111
tests/integration/tests/tracedetail/06_span.py
Normal file
111
tests/integration/tests/tracedetail/06_span.py
Normal file
@@ -0,0 +1,111 @@
|
||||
from collections.abc import Callable
|
||||
from datetime import timedelta
|
||||
from http import HTTPStatus
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from fixtures import types
|
||||
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
|
||||
from fixtures.querier import get_attribute_backend_now
|
||||
from fixtures.traces import TraceIdGenerator, Traces, TracesEvent, TracesKind, TracesLink, TracesRefType, TracesStatusCode
|
||||
|
||||
|
||||
@pytest.mark.parametrize("attribute_backend", ["map", "json"])
|
||||
def test_get_trace_span(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_traces: Callable[[list[Traces]], None],
|
||||
attribute_backend: str,
|
||||
) -> None:
|
||||
"""Attributes are written to one layout only, so a read from the wrong column loses them."""
|
||||
now = get_attribute_backend_now(signoz, attribute_backend).replace(second=0, microsecond=0)
|
||||
write_mode = "json_only" if attribute_backend == "json" else "legacy_only"
|
||||
trace_id = TraceIdGenerator.trace_id()
|
||||
other_trace_id = TraceIdGenerator.trace_id()
|
||||
resources = {"service.name": f"td-span-{attribute_backend}", "k8s.pod.name": "orders-0"}
|
||||
root_id, target_id, plain_id, orphan_id, gone_id = (TraceIdGenerator.span_id() for _ in range(5))
|
||||
long_statement = "SELECT * FROM orders WHERE id IN (" + ", ".join(str(i) for i in range(2000)) + ")"
|
||||
start = now - timedelta(seconds=10)
|
||||
|
||||
def span(span_id: str, parent_id: str, name: str, offset_ms: int, duration_ms: int, **kwargs) -> Traces:
|
||||
return Traces(timestamp=start + timedelta(milliseconds=offset_ms), duration=timedelta(milliseconds=duration_ms), trace_id=trace_id, span_id=span_id, parent_span_id=parent_id, name=name, resources=resources, attribute_write_mode=write_mode, **kwargs)
|
||||
|
||||
# POST /orders root, error, attribute http.route
|
||||
# ├─ query_orders error "deadlock detected", 4 attributes (one is 12 KB), a scope, 1 event, a link to another trace
|
||||
# └─ fetch_page no attributes, no events
|
||||
#
|
||||
# flush_metrics its parent was never received; status 404
|
||||
insert_traces(
|
||||
[
|
||||
span(root_id, "", "POST /orders", 0, 2000, kind=TracesKind.SPAN_KIND_SERVER, status_code=TracesStatusCode.STATUS_CODE_ERROR, attributes={"http.route": "/orders"}),
|
||||
span(
|
||||
target_id,
|
||||
root_id,
|
||||
"query_orders",
|
||||
30,
|
||||
1000,
|
||||
kind=TracesKind.SPAN_KIND_CLIENT,
|
||||
status_code=TracesStatusCode.STATUS_CODE_ERROR,
|
||||
status_message="deadlock detected",
|
||||
attributes={"db.system": "postgresql", "db.name": "orders", "db.statement": long_statement, "db.rows": 42},
|
||||
scope={"name": "orders-db", "version": "1.2.0"},
|
||||
events=[TracesEvent("retry", start, {"attempt": "2"})],
|
||||
links=[TracesLink(trace_id=other_trace_id, span_id="bbbbbbbbbbbbbbbb", ref_type=TracesRefType.REF_TYPE_FOLLOWS_FROM)],
|
||||
),
|
||||
span(plain_id, root_id, "fetch_page", 1100, 8),
|
||||
span(orphan_id, gone_id, "flush_metrics", 1500, 100, attributes={"http.response.status_code": 404}),
|
||||
]
|
||||
)
|
||||
|
||||
spans_url = signoz.self.host_configs["8080"].get(f"/api/v1/traces/{trace_id}/spans")
|
||||
headers = {"authorization": f"Bearer {get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)}"}
|
||||
response = requests.get(f"{spans_url}/{target_id}", headers=headers, timeout=10)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
|
||||
# the response is the span itself: everything it stores, with no value cut
|
||||
assert response.json()["data"] == {
|
||||
"span_id": target_id,
|
||||
"trace_id": trace_id,
|
||||
"parent_span_id": root_id,
|
||||
"name": "query_orders",
|
||||
"kind_string": "Client",
|
||||
"time_unix": int(start.timestamp()) * 1_000 + 30,
|
||||
"duration_nano": 1_000_000_000,
|
||||
"has_error": True,
|
||||
"status_code_string": "STATUS_CODE_ERROR",
|
||||
"status_message": "deadlock detected",
|
||||
"response_status_code": "",
|
||||
"db_name": "orders",
|
||||
"scope": {"name": "orders-db", "version": "1.2.0"},
|
||||
"resource": resources,
|
||||
"attributes": {"db.system": "postgresql", "db.name": "orders", "db.statement": long_statement, "db.rows": 42},
|
||||
"events": [{"name": "retry", "timeUnixNano": int(start.timestamp()) * 1_000_000_000, "attributeMap": {"attempt": "2"}}],
|
||||
"references": [{"traceId": trace_id, "spanId": root_id, "refType": "CHILD_OF"}, {"traceId": other_trace_id, "spanId": "bbbbbbbbbbbbbbbb", "refType": "FOLLOWS_FROM"}],
|
||||
}
|
||||
|
||||
root = requests.get(f"{spans_url}/{root_id}", headers=headers, timeout=10).json()["data"]
|
||||
assert root["parent_span_id"] == ""
|
||||
assert root["kind_string"] == "Server"
|
||||
assert root["attributes"] == {"http.route": "/orders"}
|
||||
|
||||
# a span that stores no attributes and no events returns them empty, not null
|
||||
plain = requests.get(f"{spans_url}/{plain_id}", headers=headers, timeout=10).json()["data"]
|
||||
assert plain["attributes"] == {}
|
||||
assert plain["events"] == []
|
||||
assert plain["resource"] == resources
|
||||
assert "db_name" not in plain
|
||||
assert "scope" not in plain
|
||||
|
||||
# a span whose parent was never received keeps the parent's id
|
||||
orphan = requests.get(f"{spans_url}/{orphan_id}", headers=headers, timeout=10).json()["data"]
|
||||
assert orphan["parent_span_id"] == gone_id
|
||||
assert orphan["response_status_code"] == "404"
|
||||
assert orphan["has_error"] is False
|
||||
|
||||
unknown_span = requests.get(f"{spans_url}/{TraceIdGenerator.span_id()}", headers=headers, timeout=10)
|
||||
assert unknown_span.status_code == HTTPStatus.NOT_FOUND, unknown_span.text
|
||||
|
||||
unknown_trace = requests.get(signoz.self.host_configs["8080"].get(f"/api/v1/traces/{TraceIdGenerator.trace_id()}/spans/{target_id}"), headers=headers, timeout=10)
|
||||
assert unknown_trace.status_code == HTTPStatus.NOT_FOUND, unknown_trace.text
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user