mirror of
https://github.com/SigNoz/signoz.git
synced 2026-12-02 21:20:58 +00:00
Compare commits
79 Commits
tvats-tele
...
split/4-e2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d6a2141217 | ||
|
|
5bb52df642 | ||
|
|
43d9a5e535 | ||
|
|
8e26feea44 | ||
|
|
4c20dafc34 | ||
|
|
16248a93a1 | ||
|
|
2307f02d0c | ||
|
|
0e4b7996e3 | ||
|
|
fcaf591cde | ||
|
|
c37b197ef6 | ||
|
|
559bdc773e | ||
|
|
c363f7a150 | ||
|
|
777150a0f5 | ||
|
|
23bbddfad4 | ||
|
|
56ad40cf38 | ||
|
|
c439308d7e | ||
|
|
cabac4739e | ||
|
|
afa60e6a37 | ||
|
|
0c2690903d | ||
|
|
7f01315612 | ||
|
|
d769be317d | ||
|
|
a72a8d0063 | ||
|
|
189ebaad72 | ||
|
|
62201a6289 | ||
|
|
7700246e4a | ||
|
|
11df5721c9 | ||
|
|
7b92439d93 | ||
|
|
565440ed21 | ||
|
|
60b35b8222 | ||
|
|
b910ccc618 | ||
|
|
a1e8febab5 | ||
|
|
0eda2c3080 | ||
|
|
62099763dc | ||
|
|
0a15b0f9be | ||
|
|
ca6045a462 | ||
|
|
f80c6be217 | ||
|
|
d0ee0d913b | ||
|
|
f057d5894e | ||
|
|
c6b1e8ea0e | ||
|
|
c31870110a | ||
|
|
8f201eeb76 | ||
|
|
b1261610b0 | ||
|
|
ac1a12c390 | ||
|
|
f7ad5f2f47 | ||
|
|
1ecb2ea954 | ||
|
|
e75768f981 | ||
|
|
e10731fb7c | ||
|
|
d28421004e | ||
|
|
136d98311e | ||
|
|
083f70c70f | ||
|
|
1cdf7e82ee | ||
|
|
79f49f56fc | ||
|
|
e395459783 | ||
|
|
59a23fbc2d | ||
|
|
8f5450df7c | ||
|
|
d7ecc1034d | ||
|
|
245cca1cb5 | ||
|
|
4f4a793558 | ||
|
|
7413f3f427 | ||
|
|
89f1c7cc72 | ||
|
|
8b068c827f | ||
|
|
cc389a3d73 | ||
|
|
322b288daf | ||
|
|
c017fc7436 | ||
|
|
18aab1a293 | ||
|
|
7ee8e18863 | ||
|
|
5ff867a5af | ||
|
|
e0fa2ef8c4 | ||
|
|
66ab2b4a5f | ||
|
|
a38b24c357 | ||
|
|
80adedb0db | ||
|
|
31160581bc | ||
|
|
606f8e80d3 | ||
|
|
7bd71304bb | ||
|
|
dc64cea7b9 | ||
|
|
01790cd6dc | ||
|
|
4f20848baa | ||
|
|
bd8000d0c5 | ||
|
|
a1662e453e |
@@ -88,7 +88,7 @@ Say the numbers plainly: how many screens changed, how many are new, how many ar
|
||||
- A full capture is hundreds of shots. Scope with `--title "Pages/Alerts"` or `--stories "a,b,c"` (substring match on id or Title/Name, repeatable).
|
||||
- **On macOS a capture can pin itself to one story at a time.** sbshot picks how many to shoot at once by sampling free memory, and off Linux it reads `os.freemem()`, which counts only truly free pages. macOS parks almost everything in "inactive" instead, which is reclaimable on demand, so the sampler can read ~100 MB on a 25 GB machine and shrink to one forever. `--jobs` does not help: it is only an upper cap. Check `parallelism` in `<run>/events.ndjson`; if it sits at 1 while `vm_stat` shows gigabytes inactive, that is this. A 124-shot run takes about 90 minutes pinned and about 6 minutes at four at a time, so it is worth spotting before a long capture.
|
||||
- A fresh worktree cannot build Storybook: `i18n-translations-hash.json` is gitignored and generated. Run `node ./i18-generate-hash.cjs` in `<worktree>/frontend`, and symlink `node_modules` from the main checkout.
|
||||
- `pnpm test:storybook` starts its own server on 6006 and hangs silently if something already holds that port. Free it first.
|
||||
- `pnpm test:storybook` builds Storybook and serves the build on 6006, and refuses to start if something already holds that port. Free it first.
|
||||
- ImageMagick on macOS may have no default font, so `--mode green-parallel` fails with ``unable to read font `' ``. Map Helvetica to a real file in `~/.config/ImageMagick/type.xml`.
|
||||
- `sbshot link <dir> <name>` adds a run from elsewhere into the workspace, but it symlinks. Keep the source directory alive until you have exported.
|
||||
- The export directory is build output. Delete it when done, or gitignore it.
|
||||
|
||||
@@ -137,6 +137,7 @@ func runGenerateAuthz(_ context.Context) error {
|
||||
coretypes.NewResourceRef(coretypes.ResourceOrganization).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceMetaResourceRule).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceMetaResourceRoutePolicy).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceMetaResourcePlannedMaintenance).String(): true,
|
||||
}
|
||||
|
||||
allowedTypes := map[string]bool{}
|
||||
|
||||
@@ -11469,6 +11469,7 @@ components:
|
||||
- exceptions
|
||||
- meter
|
||||
- ai_observability
|
||||
- audit
|
||||
type: string
|
||||
QuickfiltertypesSourceFilters:
|
||||
properties:
|
||||
@@ -16033,15 +16034,15 @@ paths:
|
||||
- $ref: '#/components/schemas/TelemetrytypesSignal'
|
||||
description: 'The signal to look up keys in: traces, logs or metrics. Empty
|
||||
searches every signal.'
|
||||
- description: The data source within the signal. Use meter for Cost Meter metrics;
|
||||
empty means the default source.
|
||||
- description: The data source within the signal. Use audit for audit logs or
|
||||
meter for Cost Meter metrics; empty means the default source.
|
||||
in: query
|
||||
name: source
|
||||
schema:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/TelemetrytypesSource'
|
||||
description: The data source within the signal. Use meter for Cost Meter
|
||||
metrics; empty means the default source.
|
||||
description: The data source within the signal. Use audit for audit logs
|
||||
or meter for Cost Meter metrics; empty means the default source.
|
||||
- description: Maximum number of results per signal. Defaults to 1000 for keys
|
||||
and 50 for values. For keys, intrinsic and materialized fields are added
|
||||
on top, and an empty signal applies the limit to traces, logs and metrics
|
||||
@@ -16055,27 +16056,31 @@ paths:
|
||||
metrics separately, so the response can exceed it.
|
||||
type: integer
|
||||
- description: Start of the lookup window in Unix milliseconds, rounded down
|
||||
to a 6 hour boundary. Ignored for key lookups and meter lookups; trace and
|
||||
log values apply it at calendar-day granularity; metric attribute values
|
||||
and relatedValues apply it. Omit for no lower bound.
|
||||
to a 6 hour boundary. Ignored for key lookups, audit lookups (fixed 30 day
|
||||
lookback) and meter lookups; trace and log values apply it at calendar-day
|
||||
granularity; metric attribute values and relatedValues apply it. Omit for
|
||||
no lower bound.
|
||||
in: query
|
||||
name: startUnixMilli
|
||||
schema:
|
||||
description: Start of the lookup window in Unix milliseconds, rounded down
|
||||
to a 6 hour boundary. Ignored for key lookups and meter lookups; trace
|
||||
and log values apply it at calendar-day granularity; metric attribute
|
||||
values and relatedValues apply it. Omit for no lower bound.
|
||||
to a 6 hour boundary. Ignored for key lookups, audit lookups (fixed 30
|
||||
day lookback) and meter lookups; trace and log values apply it at calendar-day
|
||||
granularity; metric attribute values and relatedValues apply it. Omit
|
||||
for no lower bound.
|
||||
format: int64
|
||||
type: integer
|
||||
- description: End of the lookup window in Unix milliseconds. Ignored for key
|
||||
lookups, trace and log value lookups and meter lookups; applied to metric
|
||||
attribute values and relatedValues. Omit for no upper bound.
|
||||
lookups, trace and log value lookups, audit lookups (fixed 30 day lookback)
|
||||
and meter lookups; applied to metric attribute values and relatedValues.
|
||||
Omit for no upper bound.
|
||||
in: query
|
||||
name: endUnixMilli
|
||||
schema:
|
||||
description: End of the lookup window in Unix milliseconds. Ignored for
|
||||
key lookups, trace and log value lookups and meter lookups; applied to
|
||||
metric attribute values and relatedValues. Omit for no upper bound.
|
||||
key lookups, trace and log value lookups, audit lookups (fixed 30 day
|
||||
lookback) and meter lookups; applied to metric attribute values and relatedValues.
|
||||
Omit for no upper bound.
|
||||
format: int64
|
||||
type: integer
|
||||
- description: 'Restricts keys to one context: resource, attribute, scope, span,
|
||||
@@ -16183,15 +16188,15 @@ paths:
|
||||
- $ref: '#/components/schemas/TelemetrytypesSignal'
|
||||
description: 'The signal to look up keys in: traces, logs or metrics. Empty
|
||||
searches every signal.'
|
||||
- description: The data source within the signal. Use meter for Cost Meter metrics;
|
||||
empty means the default source.
|
||||
- description: The data source within the signal. Use audit for audit logs or
|
||||
meter for Cost Meter metrics; empty means the default source.
|
||||
in: query
|
||||
name: source
|
||||
schema:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/TelemetrytypesSource'
|
||||
description: The data source within the signal. Use meter for Cost Meter
|
||||
metrics; empty means the default source.
|
||||
description: The data source within the signal. Use audit for audit logs
|
||||
or meter for Cost Meter metrics; empty means the default source.
|
||||
- description: Maximum number of results per signal. Defaults to 1000 for keys
|
||||
and 50 for values. For keys, intrinsic and materialized fields are added
|
||||
on top, and an empty signal applies the limit to traces, logs and metrics
|
||||
@@ -16205,27 +16210,31 @@ paths:
|
||||
metrics separately, so the response can exceed it.
|
||||
type: integer
|
||||
- description: Start of the lookup window in Unix milliseconds, rounded down
|
||||
to a 6 hour boundary. Ignored for key lookups and meter lookups; trace and
|
||||
log values apply it at calendar-day granularity; metric attribute values
|
||||
and relatedValues apply it. Omit for no lower bound.
|
||||
to a 6 hour boundary. Ignored for key lookups, audit lookups (fixed 30 day
|
||||
lookback) and meter lookups; trace and log values apply it at calendar-day
|
||||
granularity; metric attribute values and relatedValues apply it. Omit for
|
||||
no lower bound.
|
||||
in: query
|
||||
name: startUnixMilli
|
||||
schema:
|
||||
description: Start of the lookup window in Unix milliseconds, rounded down
|
||||
to a 6 hour boundary. Ignored for key lookups and meter lookups; trace
|
||||
and log values apply it at calendar-day granularity; metric attribute
|
||||
values and relatedValues apply it. Omit for no lower bound.
|
||||
to a 6 hour boundary. Ignored for key lookups, audit lookups (fixed 30
|
||||
day lookback) and meter lookups; trace and log values apply it at calendar-day
|
||||
granularity; metric attribute values and relatedValues apply it. Omit
|
||||
for no lower bound.
|
||||
format: int64
|
||||
type: integer
|
||||
- description: End of the lookup window in Unix milliseconds. Ignored for key
|
||||
lookups, trace and log value lookups and meter lookups; applied to metric
|
||||
attribute values and relatedValues. Omit for no upper bound.
|
||||
lookups, trace and log value lookups, audit lookups (fixed 30 day lookback)
|
||||
and meter lookups; applied to metric attribute values and relatedValues.
|
||||
Omit for no upper bound.
|
||||
in: query
|
||||
name: endUnixMilli
|
||||
schema:
|
||||
description: End of the lookup window in Unix milliseconds. Ignored for
|
||||
key lookups, trace and log value lookups and meter lookups; applied to
|
||||
metric attribute values and relatedValues. Omit for no upper bound.
|
||||
key lookups, trace and log value lookups, audit lookups (fixed 30 day
|
||||
lookback) and meter lookups; applied to metric attribute values and relatedValues.
|
||||
Omit for no upper bound.
|
||||
format: int64
|
||||
type: integer
|
||||
- description: 'Restricts keys to one context: resource, attribute, scope, span,
|
||||
@@ -28671,15 +28680,15 @@ paths:
|
||||
- $ref: '#/components/schemas/TelemetrytypesSignal'
|
||||
description: 'The signal to look up keys in: traces, logs or metrics. Empty
|
||||
searches every signal.'
|
||||
- description: The data source within the signal. Use meter for Cost Meter metrics;
|
||||
empty means the default source.
|
||||
- description: The data source within the signal. Use audit for audit logs or
|
||||
meter for Cost Meter metrics; empty means the default source.
|
||||
in: query
|
||||
name: source
|
||||
schema:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/TelemetrytypesSource'
|
||||
description: The data source within the signal. Use meter for Cost Meter
|
||||
metrics; empty means the default source.
|
||||
description: The data source within the signal. Use audit for audit logs
|
||||
or meter for Cost Meter metrics; empty means the default source.
|
||||
- description: Maximum number of results per signal. Defaults to 1000 for keys
|
||||
and 50 for values. For keys, intrinsic and materialized fields are added
|
||||
on top, and an empty signal applies the limit to traces, logs and metrics
|
||||
@@ -28693,27 +28702,31 @@ paths:
|
||||
metrics separately, so the response can exceed it.
|
||||
type: integer
|
||||
- description: Start of the lookup window in Unix milliseconds, rounded down
|
||||
to a 6 hour boundary. Ignored for key lookups and meter lookups; trace and
|
||||
log values apply it at calendar-day granularity; metric attribute values
|
||||
and relatedValues apply it. Omit for no lower bound.
|
||||
to a 6 hour boundary. Ignored for key lookups, audit lookups (fixed 30 day
|
||||
lookback) and meter lookups; trace and log values apply it at calendar-day
|
||||
granularity; metric attribute values and relatedValues apply it. Omit for
|
||||
no lower bound.
|
||||
in: query
|
||||
name: startUnixMilli
|
||||
schema:
|
||||
description: Start of the lookup window in Unix milliseconds, rounded down
|
||||
to a 6 hour boundary. Ignored for key lookups and meter lookups; trace
|
||||
and log values apply it at calendar-day granularity; metric attribute
|
||||
values and relatedValues apply it. Omit for no lower bound.
|
||||
to a 6 hour boundary. Ignored for key lookups, audit lookups (fixed 30
|
||||
day lookback) and meter lookups; trace and log values apply it at calendar-day
|
||||
granularity; metric attribute values and relatedValues apply it. Omit
|
||||
for no lower bound.
|
||||
format: int64
|
||||
type: integer
|
||||
- description: End of the lookup window in Unix milliseconds. Ignored for key
|
||||
lookups, trace and log value lookups and meter lookups; applied to metric
|
||||
attribute values and relatedValues. Omit for no upper bound.
|
||||
lookups, trace and log value lookups, audit lookups (fixed 30 day lookback)
|
||||
and meter lookups; applied to metric attribute values and relatedValues.
|
||||
Omit for no upper bound.
|
||||
in: query
|
||||
name: endUnixMilli
|
||||
schema:
|
||||
description: End of the lookup window in Unix milliseconds. Ignored for
|
||||
key lookups, trace and log value lookups and meter lookups; applied to
|
||||
metric attribute values and relatedValues. Omit for no upper bound.
|
||||
key lookups, trace and log value lookups, audit lookups (fixed 30 day
|
||||
lookback) and meter lookups; applied to metric attribute values and relatedValues.
|
||||
Omit for no upper bound.
|
||||
format: int64
|
||||
type: integer
|
||||
- description: 'Restricts keys to one context: resource, attribute, scope, span,
|
||||
@@ -28845,15 +28858,15 @@ paths:
|
||||
- $ref: '#/components/schemas/TelemetrytypesSignal'
|
||||
description: 'The signal to look up keys in: traces, logs or metrics. Empty
|
||||
searches every signal.'
|
||||
- description: The data source within the signal. Use meter for Cost Meter metrics;
|
||||
empty means the default source.
|
||||
- description: The data source within the signal. Use audit for audit logs or
|
||||
meter for Cost Meter metrics; empty means the default source.
|
||||
in: query
|
||||
name: source
|
||||
schema:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/TelemetrytypesSource'
|
||||
description: The data source within the signal. Use meter for Cost Meter
|
||||
metrics; empty means the default source.
|
||||
description: The data source within the signal. Use audit for audit logs
|
||||
or meter for Cost Meter metrics; empty means the default source.
|
||||
- description: Maximum number of results per signal. Defaults to 1000 for keys
|
||||
and 50 for values. For keys, intrinsic and materialized fields are added
|
||||
on top, and an empty signal applies the limit to traces, logs and metrics
|
||||
@@ -28867,27 +28880,31 @@ paths:
|
||||
metrics separately, so the response can exceed it.
|
||||
type: integer
|
||||
- description: Start of the lookup window in Unix milliseconds, rounded down
|
||||
to a 6 hour boundary. Ignored for key lookups and meter lookups; trace and
|
||||
log values apply it at calendar-day granularity; metric attribute values
|
||||
and relatedValues apply it. Omit for no lower bound.
|
||||
to a 6 hour boundary. Ignored for key lookups, audit lookups (fixed 30 day
|
||||
lookback) and meter lookups; trace and log values apply it at calendar-day
|
||||
granularity; metric attribute values and relatedValues apply it. Omit for
|
||||
no lower bound.
|
||||
in: query
|
||||
name: startUnixMilli
|
||||
schema:
|
||||
description: Start of the lookup window in Unix milliseconds, rounded down
|
||||
to a 6 hour boundary. Ignored for key lookups and meter lookups; trace
|
||||
and log values apply it at calendar-day granularity; metric attribute
|
||||
values and relatedValues apply it. Omit for no lower bound.
|
||||
to a 6 hour boundary. Ignored for key lookups, audit lookups (fixed 30
|
||||
day lookback) and meter lookups; trace and log values apply it at calendar-day
|
||||
granularity; metric attribute values and relatedValues apply it. Omit
|
||||
for no lower bound.
|
||||
format: int64
|
||||
type: integer
|
||||
- description: End of the lookup window in Unix milliseconds. Ignored for key
|
||||
lookups, trace and log value lookups and meter lookups; applied to metric
|
||||
attribute values and relatedValues. Omit for no upper bound.
|
||||
lookups, trace and log value lookups, audit lookups (fixed 30 day lookback)
|
||||
and meter lookups; applied to metric attribute values and relatedValues.
|
||||
Omit for no upper bound.
|
||||
in: query
|
||||
name: endUnixMilli
|
||||
schema:
|
||||
description: End of the lookup window in Unix milliseconds. Ignored for
|
||||
key lookups, trace and log value lookups and meter lookups; applied to
|
||||
metric attribute values and relatedValues. Omit for no upper bound.
|
||||
key lookups, trace and log value lookups, audit lookups (fixed 30 day
|
||||
lookback) and meter lookups; applied to metric attribute values and relatedValues.
|
||||
Omit for no upper bound.
|
||||
format: int64
|
||||
type: integer
|
||||
- description: 'Restricts keys to one context: resource, attribute, scope, span,
|
||||
|
||||
@@ -112,12 +112,17 @@ const preview: Preview = {
|
||||
'Alerts',
|
||||
[
|
||||
'Rules',
|
||||
['Overview', 'Authz'],
|
||||
'Triggered',
|
||||
'Overview',
|
||||
['Overview', 'Authz'],
|
||||
'History',
|
||||
['Overview', 'Authz'],
|
||||
'Create',
|
||||
['Overview', 'Authz'],
|
||||
'Edit',
|
||||
'Planned Downtime',
|
||||
['Overview', 'Authz'],
|
||||
'Routing Policies',
|
||||
['Overview', 'Authz'],
|
||||
'Channels',
|
||||
@@ -185,6 +190,7 @@ const preview: Preview = {
|
||||
['Overview', 'Kafka', 'Kafka Detail', 'Celery'],
|
||||
'Onboarding',
|
||||
['Questionnaire', 'Add Data Source'],
|
||||
'Audit Logs',
|
||||
'Settings',
|
||||
[
|
||||
'Workspace',
|
||||
|
||||
@@ -1,17 +1,12 @@
|
||||
import { getStoryContext } from '@storybook/test-runner';
|
||||
import type { TestRunnerConfig } from '@storybook/test-runner';
|
||||
import type { Page } from 'playwright';
|
||||
import type { Page, Request } from 'playwright';
|
||||
|
||||
const IGNORED_MESSAGES = [
|
||||
// `preview-head.html` swaps a local stylesheet in for Google Fonts, but the
|
||||
// browser still warns on the real cross-origin one it briefly requests
|
||||
// before msw starts (no CORS headers), regardless of story content.
|
||||
/Can't access cssRules/,
|
||||
// Pre-existing dev-server noise, unrelated to any story.
|
||||
/Couldn't load preload assets/,
|
||||
// Fires because a Jest-driven browser sets a global testing flag React
|
||||
// checks for; unrelated to anything a story does.
|
||||
/current testing environment is not configured to support act/,
|
||||
// React and antd route dev-only warnings (missing keys, DOM nesting, API
|
||||
// deprecations) through `console.error` under this prefix; app-wide and
|
||||
// tracked separately from story regressions.
|
||||
@@ -37,10 +32,35 @@ interface CapturedMessage {
|
||||
text: string;
|
||||
}
|
||||
|
||||
const PREPARE_TIMEOUT_MS = 180_000;
|
||||
|
||||
const messagesByPage = new WeakMap<Page, CapturedMessage[]>();
|
||||
|
||||
const SETTLE_TIMEOUT_MS = 1_000;
|
||||
|
||||
const SETTLE_POLL_MS = 25;
|
||||
|
||||
const requestsByPage = new WeakMap<Page, Set<Request>>();
|
||||
|
||||
/**
|
||||
* The runner opens the next story in this page as soon as the previous one has
|
||||
* rendered, so what that one still has in flight answers into state both share:
|
||||
* the Noz store holds a single thread id. Requests held open on purpose never
|
||||
* end, so the wait gives up and forgets them.
|
||||
*/
|
||||
const settleRequests = async (page: Page): Promise<void> => {
|
||||
const pending = requestsByPage.get(page);
|
||||
if (!pending) {
|
||||
return;
|
||||
}
|
||||
|
||||
const deadline = Date.now() + SETTLE_TIMEOUT_MS;
|
||||
while (pending.size > 0 && Date.now() < deadline) {
|
||||
await new Promise((resolve) => {
|
||||
setTimeout(resolve, SETTLE_POLL_MS);
|
||||
});
|
||||
}
|
||||
pending.clear();
|
||||
};
|
||||
|
||||
/**
|
||||
* When the story under test started rendering, stamped by the preview's
|
||||
* `beforeEach`. Messages captured before it belong to the previous story: the
|
||||
@@ -61,16 +81,9 @@ const config: TestRunnerConfig = {
|
||||
// msw logs every mocked request at `log`; keep it out of the failure dump
|
||||
// unless the job is re-run with debug logging (GitHub sets RUNNER_DEBUG=1).
|
||||
logLevel: process.env.RUNNER_DEBUG === '1' ? 'info' : 'warn',
|
||||
// The runner's default prepare, minus Playwright's 30s navigation timeout: on
|
||||
// a cold dev server the first load compiles the whole preview, which outlasts
|
||||
// it on a shared CI runner.
|
||||
async prepare({ page }): Promise<void> {
|
||||
await page.goto(new URL('iframe.html', process.env.TARGET_URL).toString(), {
|
||||
waitUntil: 'load',
|
||||
timeout: PREPARE_TIMEOUT_MS,
|
||||
});
|
||||
},
|
||||
async preVisit(page): Promise<void> {
|
||||
await settleRequests(page);
|
||||
|
||||
const existing = messagesByPage.get(page);
|
||||
if (existing) {
|
||||
existing.length = 0;
|
||||
@@ -79,6 +92,11 @@ const config: TestRunnerConfig = {
|
||||
|
||||
const messages: CapturedMessage[] = [];
|
||||
messagesByPage.set(page, messages);
|
||||
const pending = new Set<Request>();
|
||||
requestsByPage.set(page, pending);
|
||||
page.on('request', (request) => pending.add(request));
|
||||
page.on('requestfinished', (request) => pending.delete(request));
|
||||
page.on('requestfailed', (request) => pending.delete(request));
|
||||
page.on('console', (message) => {
|
||||
if (
|
||||
message.type() === 'error' &&
|
||||
|
||||
@@ -61,5 +61,6 @@
|
||||
"AI_OBSERVABILITY_OVERVIEW": "SigNoz | AI Observability Overview",
|
||||
"AI_OBSERVABILITY_EXPLORER": "SigNoz | AI Observability Explorer",
|
||||
"AI_OBSERVABILITY_CONFIGURATION": "SigNoz | AI Observability Configuration",
|
||||
"AI_OBSERVABILITY_ATTRIBUTE_MAPPING": "SigNoz | AI Observability Attribute Mapping"
|
||||
"AI_OBSERVABILITY_ATTRIBUTE_MAPPING": "SigNoz | AI Observability Attribute Mapping",
|
||||
"AUDIT_LOGS": "SigNoz | Audit Logs"
|
||||
}
|
||||
@@ -82,5 +82,6 @@
|
||||
"AI_OBSERVABILITY_OVERVIEW": "SigNoz | AI Observability Overview",
|
||||
"AI_OBSERVABILITY_EXPLORER": "SigNoz | AI Observability Explorer",
|
||||
"AI_OBSERVABILITY_CONFIGURATION": "SigNoz | AI Observability Configuration",
|
||||
"AI_OBSERVABILITY_ATTRIBUTE_MAPPING": "SigNoz | AI Observability Attribute Mapping"
|
||||
"AI_OBSERVABILITY_ATTRIBUTE_MAPPING": "SigNoz | AI Observability Attribute Mapping",
|
||||
"AUDIT_LOGS": "SigNoz | Audit Logs"
|
||||
}
|
||||
@@ -1,33 +1,34 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
story_count=$(find src -name '*.stories.tsx' | wc -l)
|
||||
if [ "$story_count" -eq 0 ]; then
|
||||
echo "No *.stories.tsx found under src/" >&2
|
||||
port=6006
|
||||
static_dir=${STORYBOOK_STATIC_DIR:-}
|
||||
if [ -z "$static_dir" ]; then
|
||||
static_dir=storybook-static
|
||||
pnpm storybook:build --quiet
|
||||
fi
|
||||
if [ ! -f "$static_dir/index.json" ]; then
|
||||
echo "No Storybook build in $static_dir/" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# jest splits the sorted story files into contiguous shards and exits 1 when a
|
||||
# shard is empty, which happens on every shard above the file count. The runner
|
||||
# rejects jest's own `--passWithNoTests`, so skip those shards here.
|
||||
for arg in "$@"; do
|
||||
if [[ $arg == --shard=* ]]; then
|
||||
shard_index=${arg#--shard=}
|
||||
if [ "${shard_index%%/*}" -gt "$story_count" ]; then
|
||||
echo "Skipping ${arg#--shard=}: only ${story_count} story files"
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
done
|
||||
if curl -s -o /dev/null "http://127.0.0.1:$port/"; then
|
||||
echo "Port $port is taken; stop whatever serves it first." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
pnpm storybook --ci --quiet &
|
||||
SB_PID=$!
|
||||
trap 'kill "$SB_PID" 2>/dev/null || true' EXIT
|
||||
node_modules/.bin/vite preview --outDir "$static_dir" --host 127.0.0.1 --port "$port" --strictPort --no-open >/dev/null &
|
||||
SERVER_PID=$!
|
||||
trap 'kill "$SERVER_PID" 2>/dev/null || true' EXIT
|
||||
|
||||
until curl -sf http://127.0.0.1:6006/index.json >/dev/null 2>&1; do
|
||||
until curl -sf "http://127.0.0.1:$port/index.json" >/dev/null 2>&1; do
|
||||
kill -0 "$SERVER_PID" 2>/dev/null || {
|
||||
echo "Static server exited" >&2
|
||||
exit 1
|
||||
}
|
||||
sleep 1
|
||||
done
|
||||
|
||||
# The first story of a heavy page compiles it on the cold dev server inside its
|
||||
# own test, which outlasts 30s on a loaded runner.
|
||||
pnpm exec test-storybook --ci --maxWorkers=2 --testTimeout 60000 "$@"
|
||||
# Index-json mode names its tests after story titles, so story file arguments
|
||||
# would match nothing.
|
||||
pnpm exec test-storybook --ci --no-index-json --url "http://127.0.0.1:$port" --maxWorkers=2 --testTimeout 30000 "$@"
|
||||
|
||||
@@ -449,9 +449,9 @@ describe('PrivateRoute', () => {
|
||||
assertStaysOnRoute(ROUTES.HOME);
|
||||
});
|
||||
|
||||
it('should redirect to unauthorized when VIEWER tries to access admin-only route /alerts/new', async () => {
|
||||
it('should redirect to unauthorized when VIEWER tries to access admin-only route /licenses', async () => {
|
||||
renderPrivateRoute({
|
||||
initialRoute: ROUTES.ALERTS_NEW,
|
||||
initialRoute: ROUTES.LIST_LICENSES,
|
||||
appContext: {
|
||||
isLoggedIn: true,
|
||||
user: createMockUser({ role: USER_ROLES.VIEWER as ROLES }),
|
||||
@@ -1688,6 +1688,9 @@ describe('PrivateRoute', () => {
|
||||
AuthzRouteCase
|
||||
> = {
|
||||
LIST_ALL_ALERT: { path: ROUTES.LIST_ALL_ALERT, deniedRoles: DENIED_ROLES },
|
||||
ALERTS_NEW: { path: ROUTES.ALERTS_NEW, deniedRoles: DENIED_ROLES },
|
||||
ALERT_OVERVIEW: { path: ROUTES.ALERT_OVERVIEW, deniedRoles: DENIED_ROLES },
|
||||
ALERT_HISTORY: { path: ROUTES.ALERT_HISTORY, deniedRoles: DENIED_ROLES },
|
||||
CHANNELS_NEW: { path: ROUTES.CHANNELS_NEW, deniedRoles: DENIED_ROLES },
|
||||
CHANNELS_EDIT: {
|
||||
path: ROUTES.CHANNELS_EDIT.replace(':channelId', 'channel-id-1'),
|
||||
@@ -1775,7 +1778,6 @@ describe('PrivateRoute', () => {
|
||||
|
||||
// Routes with no authz check - legacy role check still applies
|
||||
const NON_AUTHZ_ROUTE_CASES: [string, string, ROLES][] = [
|
||||
['ALERTS_NEW', ROUTES.ALERTS_NEW, USER_ROLES.VIEWER as ROLES],
|
||||
['LIST_LICENSES', ROUTES.LIST_LICENSES, USER_ROLES.EDITOR as ROLES],
|
||||
['ONBOARDING', ROUTES.ONBOARDING, USER_ROLES.VIEWER as ROLES],
|
||||
['APPLICATION', ROUTES.APPLICATION, USER_ROLES.ANONYMOUS as ROLES],
|
||||
|
||||
@@ -292,3 +292,10 @@ export const LLMObservabilityPage = Loadable(
|
||||
/* webpackChunkName: "LLM Observability Page" */ 'pages/LLMObservability'
|
||||
),
|
||||
);
|
||||
|
||||
export const AuditLogsPage = Loadable(
|
||||
() =>
|
||||
import(
|
||||
/* webpackChunkName: "Audit Logs Page" */ 'pages/AuditLogsModule/AuditLogsModule'
|
||||
),
|
||||
);
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
AlertOverview,
|
||||
AllErrors,
|
||||
ApiMonitoring,
|
||||
AuditLogsPage,
|
||||
ChannelsEdit,
|
||||
ChannelsNew,
|
||||
CreateNewAlerts,
|
||||
@@ -408,6 +409,12 @@ const routes: AppRoutes[] = [
|
||||
key: 'AI_OBSERVABILITY_CONFIGURATION',
|
||||
isPrivate: true,
|
||||
},
|
||||
{
|
||||
path: ROUTES.AUDIT_LOGS,
|
||||
component: AuditLogsPage,
|
||||
key: 'AUDIT_LOGS',
|
||||
isPrivate: true,
|
||||
},
|
||||
];
|
||||
|
||||
export const SUPPORT_ROUTE: AppRoutes = {
|
||||
|
||||
@@ -12587,6 +12587,7 @@ export enum QuickfiltertypesSourceDTO {
|
||||
exceptions = 'exceptions',
|
||||
meter = 'meter',
|
||||
ai_observability = 'ai_observability',
|
||||
audit = 'audit',
|
||||
}
|
||||
export interface QuickfiltertypesSourceFiltersDTO {
|
||||
/**
|
||||
@@ -15516,7 +15517,7 @@ export type GetFieldsKeysParams = {
|
||||
*/
|
||||
signal?: TelemetrytypesSignalDTO;
|
||||
/**
|
||||
* @description The data source within the signal. Use meter for Cost Meter metrics; empty means the default source.
|
||||
* @description The data source within the signal. Use audit for audit logs or meter for Cost Meter metrics; empty means the default source.
|
||||
*/
|
||||
source?: TelemetrytypesSourceDTO;
|
||||
/**
|
||||
@@ -15527,13 +15528,13 @@ export type GetFieldsKeysParams = {
|
||||
/**
|
||||
* @type integer
|
||||
* @format int64
|
||||
* @description Start of the lookup window in Unix milliseconds, rounded down to a 6 hour boundary. Ignored for key lookups and meter lookups; trace and log values apply it at calendar-day granularity; metric attribute values and relatedValues apply it. Omit for no lower bound.
|
||||
* @description Start of the lookup window in Unix milliseconds, rounded down to a 6 hour boundary. Ignored for key lookups, audit lookups (fixed 30 day lookback) and meter lookups; trace and log values apply it at calendar-day granularity; metric attribute values and relatedValues apply it. Omit for no lower bound.
|
||||
*/
|
||||
startUnixMilli?: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @format int64
|
||||
* @description End of the lookup window in Unix milliseconds. Ignored for key lookups, trace and log value lookups and meter lookups; applied to metric attribute values and relatedValues. Omit for no upper bound.
|
||||
* @description End of the lookup window in Unix milliseconds. Ignored for key lookups, trace and log value lookups, audit lookups (fixed 30 day lookback) and meter lookups; applied to metric attribute values and relatedValues. Omit for no upper bound.
|
||||
*/
|
||||
endUnixMilli?: number;
|
||||
/**
|
||||
@@ -15575,7 +15576,7 @@ export type GetFieldsValuesParams = {
|
||||
*/
|
||||
signal?: TelemetrytypesSignalDTO;
|
||||
/**
|
||||
* @description The data source within the signal. Use meter for Cost Meter metrics; empty means the default source.
|
||||
* @description The data source within the signal. Use audit for audit logs or meter for Cost Meter metrics; empty means the default source.
|
||||
*/
|
||||
source?: TelemetrytypesSourceDTO;
|
||||
/**
|
||||
@@ -15586,13 +15587,13 @@ export type GetFieldsValuesParams = {
|
||||
/**
|
||||
* @type integer
|
||||
* @format int64
|
||||
* @description Start of the lookup window in Unix milliseconds, rounded down to a 6 hour boundary. Ignored for key lookups and meter lookups; trace and log values apply it at calendar-day granularity; metric attribute values and relatedValues apply it. Omit for no lower bound.
|
||||
* @description Start of the lookup window in Unix milliseconds, rounded down to a 6 hour boundary. Ignored for key lookups, audit lookups (fixed 30 day lookback) and meter lookups; trace and log values apply it at calendar-day granularity; metric attribute values and relatedValues apply it. Omit for no lower bound.
|
||||
*/
|
||||
startUnixMilli?: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @format int64
|
||||
* @description End of the lookup window in Unix milliseconds. Ignored for key lookups, trace and log value lookups and meter lookups; applied to metric attribute values and relatedValues. Omit for no upper bound.
|
||||
* @description End of the lookup window in Unix milliseconds. Ignored for key lookups, trace and log value lookups, audit lookups (fixed 30 day lookback) and meter lookups; applied to metric attribute values and relatedValues. Omit for no upper bound.
|
||||
*/
|
||||
endUnixMilli?: number;
|
||||
/**
|
||||
@@ -17130,7 +17131,7 @@ export type GetRuleHistoryFilterKeysParams = {
|
||||
*/
|
||||
signal?: TelemetrytypesSignalDTO;
|
||||
/**
|
||||
* @description The data source within the signal. Use meter for Cost Meter metrics; empty means the default source.
|
||||
* @description The data source within the signal. Use audit for audit logs or meter for Cost Meter metrics; empty means the default source.
|
||||
*/
|
||||
source?: TelemetrytypesSourceDTO;
|
||||
/**
|
||||
@@ -17141,13 +17142,13 @@ export type GetRuleHistoryFilterKeysParams = {
|
||||
/**
|
||||
* @type integer
|
||||
* @format int64
|
||||
* @description Start of the lookup window in Unix milliseconds, rounded down to a 6 hour boundary. Ignored for key lookups and meter lookups; trace and log values apply it at calendar-day granularity; metric attribute values and relatedValues apply it. Omit for no lower bound.
|
||||
* @description Start of the lookup window in Unix milliseconds, rounded down to a 6 hour boundary. Ignored for key lookups, audit lookups (fixed 30 day lookback) and meter lookups; trace and log values apply it at calendar-day granularity; metric attribute values and relatedValues apply it. Omit for no lower bound.
|
||||
*/
|
||||
startUnixMilli?: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @format int64
|
||||
* @description End of the lookup window in Unix milliseconds. Ignored for key lookups, trace and log value lookups and meter lookups; applied to metric attribute values and relatedValues. Omit for no upper bound.
|
||||
* @description End of the lookup window in Unix milliseconds. Ignored for key lookups, trace and log value lookups, audit lookups (fixed 30 day lookback) and meter lookups; applied to metric attribute values and relatedValues. Omit for no upper bound.
|
||||
*/
|
||||
endUnixMilli?: number;
|
||||
/**
|
||||
@@ -17192,7 +17193,7 @@ export type GetRuleHistoryFilterValuesParams = {
|
||||
*/
|
||||
signal?: TelemetrytypesSignalDTO;
|
||||
/**
|
||||
* @description The data source within the signal. Use meter for Cost Meter metrics; empty means the default source.
|
||||
* @description The data source within the signal. Use audit for audit logs or meter for Cost Meter metrics; empty means the default source.
|
||||
*/
|
||||
source?: TelemetrytypesSourceDTO;
|
||||
/**
|
||||
@@ -17203,13 +17204,13 @@ export type GetRuleHistoryFilterValuesParams = {
|
||||
/**
|
||||
* @type integer
|
||||
* @format int64
|
||||
* @description Start of the lookup window in Unix milliseconds, rounded down to a 6 hour boundary. Ignored for key lookups and meter lookups; trace and log values apply it at calendar-day granularity; metric attribute values and relatedValues apply it. Omit for no lower bound.
|
||||
* @description Start of the lookup window in Unix milliseconds, rounded down to a 6 hour boundary. Ignored for key lookups, audit lookups (fixed 30 day lookback) and meter lookups; trace and log values apply it at calendar-day granularity; metric attribute values and relatedValues apply it. Omit for no lower bound.
|
||||
*/
|
||||
startUnixMilli?: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @format int64
|
||||
* @description End of the lookup window in Unix milliseconds. Ignored for key lookups, trace and log value lookups and meter lookups; applied to metric attribute values and relatedValues. Omit for no upper bound.
|
||||
* @description End of the lookup window in Unix milliseconds. Ignored for key lookups, trace and log value lookups, audit lookups (fixed 30 day lookback) and meter lookups; applied to metric attribute values and relatedValues. Omit for no upper bound.
|
||||
*/
|
||||
endUnixMilli?: number;
|
||||
/**
|
||||
|
||||
@@ -15,7 +15,7 @@ import { getBasePath } from 'utils/basePath';
|
||||
import { eventEmitter } from 'utils/getEventEmitter';
|
||||
import { getIsNoAuthMode } from 'utils/noAuthMode';
|
||||
|
||||
import apiV1, { apiAlertManager, apiV2, apiV3, apiV4, apiV5 } from './apiV1';
|
||||
import apiV1, { apiAlertManager, apiV2, apiV4, apiV5 } from './apiV1';
|
||||
import { Logout } from './utils';
|
||||
|
||||
const RESPONSE_TIMEOUT_THRESHOLD = 5000; // 5 seconds
|
||||
@@ -193,19 +193,6 @@ ApiV2Instance.interceptors.response.use(
|
||||
ApiV2Instance.interceptors.request.use(interceptorsRequestResponse);
|
||||
ApiV2Instance.interceptors.request.use(interceptorsRequestBasePath);
|
||||
|
||||
// axios V3
|
||||
export const ApiV3Instance = axios.create({
|
||||
baseURL: `${ENVIRONMENT.baseURL}${apiV3}`,
|
||||
});
|
||||
|
||||
ApiV3Instance.interceptors.response.use(
|
||||
interceptorsResponse,
|
||||
interceptorRejected,
|
||||
);
|
||||
ApiV3Instance.interceptors.request.use(interceptorsRequestResponse);
|
||||
ApiV3Instance.interceptors.request.use(interceptorsRequestBasePath);
|
||||
//
|
||||
|
||||
// axios V4
|
||||
export const ApiV4Instance = axios.create({
|
||||
baseURL: `${ENVIRONMENT.baseURL}${apiV4}`,
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
import { ApiV3Instance, ApiV4Instance } from 'api';
|
||||
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
|
||||
import { AxiosError } from 'axios';
|
||||
import { ENTITY_VERSION_V4 } from 'constants/app';
|
||||
import { ErrorResponse, SuccessResponse, Warning } from 'types/api';
|
||||
import {
|
||||
MetricRangePayloadV3,
|
||||
QueryRangePayload,
|
||||
} from 'types/api/metrics/getQueryRange';
|
||||
|
||||
export const getMetricsQueryRange = async (
|
||||
props: QueryRangePayload,
|
||||
version: string,
|
||||
signal: AbortSignal,
|
||||
headers?: Record<string, string>,
|
||||
): Promise<
|
||||
(SuccessResponse<MetricRangePayloadV3> & { warning?: Warning }) | ErrorResponse
|
||||
> => {
|
||||
try {
|
||||
if (version && version === ENTITY_VERSION_V4) {
|
||||
const response = await ApiV4Instance.post('/query_range', props, {
|
||||
signal,
|
||||
});
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
message: response.data.status,
|
||||
payload: response.data,
|
||||
params: props,
|
||||
};
|
||||
}
|
||||
|
||||
const response = await ApiV3Instance.post('/query_range', props, {
|
||||
signal,
|
||||
headers,
|
||||
});
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
message: response.data.status,
|
||||
payload: response.data,
|
||||
params: props,
|
||||
};
|
||||
} catch (error) {
|
||||
return ErrorResponseHandler(error as AxiosError);
|
||||
}
|
||||
};
|
||||
@@ -1,50 +0,0 @@
|
||||
import { ApiV3Instance } from 'api';
|
||||
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
|
||||
import { AxiosError, AxiosResponse } from 'axios';
|
||||
import { baseAutoCompleteIdKeysOrder } from 'constants/queryBuilder';
|
||||
import { createIdFromObjectFields } from 'lib/createIdFromObjectFields';
|
||||
import createQueryParams from 'lib/createQueryParams';
|
||||
// ** Helpers
|
||||
import { ErrorResponse, SuccessResponse } from 'types/api';
|
||||
// ** Types
|
||||
import { IGetAggregateAttributePayload } from 'types/api/queryBuilder/getAggregatorAttribute';
|
||||
import {
|
||||
BaseAutocompleteData,
|
||||
IQueryAutocompleteResponse,
|
||||
} from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
|
||||
export const getAggregateAttribute = async ({
|
||||
aggregateOperator,
|
||||
searchText,
|
||||
dataSource,
|
||||
source,
|
||||
}: IGetAggregateAttributePayload): Promise<
|
||||
SuccessResponse<IQueryAutocompleteResponse> | ErrorResponse
|
||||
> => {
|
||||
try {
|
||||
const response: AxiosResponse<{
|
||||
data: IQueryAutocompleteResponse;
|
||||
}> = await ApiV3Instance.get(
|
||||
`/autocomplete/aggregate_attributes?${createQueryParams({
|
||||
aggregateOperator,
|
||||
searchText,
|
||||
dataSource: source === 'meter' ? 'meter' : dataSource,
|
||||
})}`,
|
||||
);
|
||||
|
||||
const payload: BaseAutocompleteData[] =
|
||||
response.data.data.attributeKeys?.map(({ id: _, ...item }) => ({
|
||||
...item,
|
||||
id: createIdFromObjectFields(item, baseAutoCompleteIdKeysOrder),
|
||||
})) || [];
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
message: response.statusText,
|
||||
payload: { attributeKeys: payload },
|
||||
};
|
||||
} catch (e) {
|
||||
return ErrorResponseHandler(e as AxiosError);
|
||||
}
|
||||
};
|
||||
@@ -1,50 +0,0 @@
|
||||
import { ApiV3Instance } from 'api';
|
||||
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
|
||||
import { AxiosError, AxiosResponse } from 'axios';
|
||||
import { baseAutoCompleteIdKeysOrder } from 'constants/queryBuilder';
|
||||
import { createIdFromObjectFields } from 'lib/createIdFromObjectFields';
|
||||
import createQueryParams from 'lib/createQueryParams';
|
||||
import { ErrorResponse, SuccessResponse } from 'types/api';
|
||||
import { IGetAttributeKeysPayload } from 'types/api/queryBuilder/getAttributeKeys';
|
||||
import {
|
||||
BaseAutocompleteData,
|
||||
IQueryAutocompleteResponse,
|
||||
} from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
|
||||
export const getAggregateKeys = async ({
|
||||
aggregateOperator,
|
||||
searchText,
|
||||
dataSource,
|
||||
aggregateAttribute,
|
||||
tagType,
|
||||
}: IGetAttributeKeysPayload): Promise<
|
||||
SuccessResponse<IQueryAutocompleteResponse> | ErrorResponse
|
||||
> => {
|
||||
try {
|
||||
const response: AxiosResponse<{
|
||||
data: IQueryAutocompleteResponse;
|
||||
}> = await ApiV3Instance.get(
|
||||
`/autocomplete/attribute_keys?${createQueryParams({
|
||||
aggregateOperator,
|
||||
searchText,
|
||||
dataSource,
|
||||
aggregateAttribute,
|
||||
})}&tagType=${tagType}`,
|
||||
);
|
||||
|
||||
const payload: BaseAutocompleteData[] =
|
||||
response.data.data.attributeKeys?.map(({ id: _, ...item }) => ({
|
||||
...item,
|
||||
id: createIdFromObjectFields(item, baseAutoCompleteIdKeysOrder),
|
||||
})) || [];
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
message: response.statusText,
|
||||
payload: { attributeKeys: payload },
|
||||
};
|
||||
} catch (e) {
|
||||
return ErrorResponseHandler(e as AxiosError);
|
||||
}
|
||||
};
|
||||
@@ -1,63 +0,0 @@
|
||||
import { ApiV3Instance } from 'api';
|
||||
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
|
||||
import { AxiosError, AxiosResponse } from 'axios';
|
||||
import { baseAutoCompleteIdKeysOrder } from 'constants/queryBuilder';
|
||||
import { encode } from 'js-base64';
|
||||
import { createIdFromObjectFields } from 'lib/createIdFromObjectFields';
|
||||
import createQueryParams from 'lib/createQueryParams';
|
||||
import { ErrorResponse, SuccessResponse } from 'types/api';
|
||||
import {
|
||||
IGetAttributeSuggestionsPayload,
|
||||
IGetAttributeSuggestionsSuccessResponse,
|
||||
} from 'types/api/queryBuilder/getAttributeSuggestions';
|
||||
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
|
||||
export const getAttributeSuggestions = async ({
|
||||
searchText,
|
||||
dataSource,
|
||||
filters,
|
||||
}: IGetAttributeSuggestionsPayload): Promise<
|
||||
SuccessResponse<IGetAttributeSuggestionsSuccessResponse> | ErrorResponse
|
||||
> => {
|
||||
try {
|
||||
let base64EncodedFiltersString;
|
||||
try {
|
||||
// the replace function is to remove the padding at the end of base64 encoded string which is auto added to make it a multiple of 4
|
||||
// why ? because the current working of qs doesn't work well with padding
|
||||
base64EncodedFiltersString = encode(JSON.stringify(filters)).replace(
|
||||
/=+$/,
|
||||
'',
|
||||
);
|
||||
} catch {
|
||||
// default base64 encoded string for empty filters object
|
||||
base64EncodedFiltersString = 'eyJpdGVtcyI6W10sIm9wIjoiQU5EIn0';
|
||||
}
|
||||
const response: AxiosResponse<{
|
||||
data: IGetAttributeSuggestionsSuccessResponse;
|
||||
}> = await ApiV3Instance.get(
|
||||
`/filter_suggestions?${createQueryParams({
|
||||
searchText,
|
||||
dataSource,
|
||||
existingFilter: base64EncodedFiltersString,
|
||||
})}`,
|
||||
);
|
||||
|
||||
const payload: BaseAutocompleteData[] =
|
||||
response.data.data.attributes?.map(({ id: _, ...item }) => ({
|
||||
...item,
|
||||
id: createIdFromObjectFields(item, baseAutoCompleteIdKeysOrder),
|
||||
})) || [];
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
message: response.statusText,
|
||||
payload: {
|
||||
attributes: payload,
|
||||
example_queries: response.data.data.example_queries,
|
||||
},
|
||||
};
|
||||
} catch (e) {
|
||||
return ErrorResponseHandler(e as AxiosError);
|
||||
}
|
||||
};
|
||||
@@ -1,42 +0,0 @@
|
||||
import { ApiV3Instance } from 'api';
|
||||
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
|
||||
import { AxiosError } from 'axios';
|
||||
import createQueryParams from 'lib/createQueryParams';
|
||||
import { ErrorResponse, SuccessResponse } from 'types/api';
|
||||
import {
|
||||
IAttributeValuesResponse,
|
||||
IGetAttributeValuesPayload,
|
||||
} from 'types/api/queryBuilder/getAttributesValues';
|
||||
|
||||
export const getAttributesValues = async ({
|
||||
aggregateOperator,
|
||||
dataSource,
|
||||
aggregateAttribute,
|
||||
attributeKey,
|
||||
filterAttributeKeyDataType,
|
||||
tagType,
|
||||
searchText,
|
||||
}: IGetAttributeValuesPayload): Promise<
|
||||
SuccessResponse<IAttributeValuesResponse> | ErrorResponse
|
||||
> => {
|
||||
try {
|
||||
const response = await ApiV3Instance.get(
|
||||
`/autocomplete/attribute_values?${createQueryParams({
|
||||
aggregateOperator,
|
||||
dataSource,
|
||||
aggregateAttribute,
|
||||
attributeKey,
|
||||
searchText,
|
||||
})}&filterAttributeKeyDataType=${filterAttributeKeyDataType}&tagType=${tagType}`,
|
||||
);
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
message: response.data.status,
|
||||
payload: response.data.data,
|
||||
};
|
||||
} catch (error) {
|
||||
return ErrorResponseHandler(error as AxiosError);
|
||||
}
|
||||
};
|
||||
@@ -396,16 +396,20 @@ describe('convertV5ResponseToLegacy', () => {
|
||||
meta: { rowsScanned: 0, bytesScanned: 0, durationMs: 0, stepIntervals: {} },
|
||||
} as unknown as QueryRangeResponseV5;
|
||||
|
||||
const baseSpec = {
|
||||
name: 'A',
|
||||
stepInterval: 60,
|
||||
disabled: false,
|
||||
aggregations: [],
|
||||
};
|
||||
|
||||
const params = makeBaseParams(type as RequestType, [
|
||||
{
|
||||
type: 'builder_query',
|
||||
spec: {
|
||||
name: 'A',
|
||||
signal: type === 'trace' ? 'traces' : 'logs',
|
||||
stepInterval: 60,
|
||||
disabled: false,
|
||||
aggregations: [],
|
||||
},
|
||||
spec:
|
||||
type === 'trace'
|
||||
? { ...baseSpec, signal: 'traces' }
|
||||
: { ...baseSpec, signal: 'logs' },
|
||||
},
|
||||
]);
|
||||
|
||||
@@ -467,5 +471,34 @@ describe('convertV5ResponseToLegacy', () => {
|
||||
const data = (result.payload.data.result[0].list?.[0] as any)?.data ?? {};
|
||||
expect('body' in data).toBe(false);
|
||||
});
|
||||
|
||||
const getRowData = (
|
||||
result: ReturnType<typeof convertV5ResponseToLegacy>,
|
||||
): Record<string, unknown> =>
|
||||
(result.payload.data.result[0].list?.[0] as any)?.data ?? {};
|
||||
|
||||
it('lifts resource.attributes onto resource', () => {
|
||||
const result = makeRawResult([
|
||||
{
|
||||
timestamp: '2026-07-21T00:00:00Z',
|
||||
data: {
|
||||
resource: { attributes: { 'signoz.resource.kind': 'dashboard' } },
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
expect(getRowData(result).resource).toStrictEqual({
|
||||
'signoz.resource.kind': 'dashboard',
|
||||
});
|
||||
});
|
||||
|
||||
it('leaves a flat resource unchanged', () => {
|
||||
const resource = { 'service.name': 'signoz' };
|
||||
const result = makeRawResult([
|
||||
{ timestamp: '2026-07-21T00:00:00Z', data: { resource } },
|
||||
]);
|
||||
|
||||
expect(getRowData(result).resource).toStrictEqual(resource);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { extractOnlyMessageBody } from 'lib/logs/logBody';
|
||||
import { cloneDeep, isEmpty } from 'lodash-es';
|
||||
import { cloneDeep, get, isEmpty, isPlainObject } from 'lodash-es';
|
||||
import { SuccessResponse, Warning } from 'types/api';
|
||||
import { MetricRangePayloadV3 } from 'types/api/metrics/getQueryRange';
|
||||
import {
|
||||
@@ -305,6 +305,12 @@ function convertRawData(
|
||||
data.body = extractOnlyMessageBody(row.data.body);
|
||||
}
|
||||
|
||||
// Audit rows nest resource keys under resource.attributes; lift them so resource is flat and FlatLogData flattens it.
|
||||
const resourceAttributes = get(row.data, ['resource', 'attributes']);
|
||||
if (isPlainObject(resourceAttributes)) {
|
||||
data.resource = resourceAttributes;
|
||||
}
|
||||
|
||||
return {
|
||||
timestamp: row.timestamp,
|
||||
data,
|
||||
|
||||
@@ -643,6 +643,28 @@ describe('prepareQueryRangePayloadV5', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('sends source audit on a logs query that targets audit', () => {
|
||||
const [envelope] = convertBuilderQueriesToV5(
|
||||
{
|
||||
A: baseBuilderQuery({ dataSource: DataSource.LOGS, source: 'audit' }),
|
||||
},
|
||||
'raw',
|
||||
);
|
||||
|
||||
expect(envelope.spec).toMatchObject({ signal: 'logs', source: 'audit' });
|
||||
});
|
||||
|
||||
it('sends no source on a plain logs query', () => {
|
||||
const [envelope] = convertBuilderQueriesToV5(
|
||||
{
|
||||
A: baseBuilderQuery({ dataSource: DataSource.LOGS, source: '' }),
|
||||
},
|
||||
'raw',
|
||||
);
|
||||
|
||||
expect(envelope.spec).not.toHaveProperty('source');
|
||||
});
|
||||
|
||||
it('builds payload for builder queries with filters array but no filter expression', () => {
|
||||
const props: GetQueryResultsProps = {
|
||||
query: {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
/* eslint-disable sonarjs/cognitive-complexity */
|
||||
/* eslint-disable sonarjs/no-identical-functions */
|
||||
import { TelemetrytypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { convertFiltersToExpression } from 'components/QueryBuilderV2/utils';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
|
||||
@@ -341,6 +342,9 @@ export function convertBuilderQueriesToV5(
|
||||
spec = {
|
||||
name: queryName,
|
||||
signal: 'logs' as const,
|
||||
...(queryData.source === TelemetrytypesSourceDTO.audit && {
|
||||
source: TelemetrytypesSourceDTO.audit,
|
||||
}),
|
||||
...baseSpec,
|
||||
aggregations: aggregations as LogAggregation[],
|
||||
};
|
||||
|
||||
@@ -29,33 +29,6 @@
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.overflowTrigger {
|
||||
all: unset;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.labelPopover {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
padding: 8px;
|
||||
max-height: 300px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.labelTooltip {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
max-height: 300px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.labelValue {
|
||||
text-overflow: ellipsis;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.tooltipContent {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -1,29 +1,5 @@
|
||||
import type { BadgeColorType } from '@signozhq/ui/badge';
|
||||
|
||||
export const STATE_ORDER = ['firing', 'pending', 'inactive', 'disabled'];
|
||||
export const SEVERITY_ORDER = ['critical', 'error', 'warning', 'info'];
|
||||
|
||||
export const STATE_LABELS: Record<string, string> = {
|
||||
firing: 'Firing',
|
||||
pending: 'Pending',
|
||||
inactive: 'OK',
|
||||
disabled: 'Disabled',
|
||||
};
|
||||
|
||||
export const STATE_COLORS: Record<string, string> = {
|
||||
firing: 'var(--bg-cherry-500)',
|
||||
pending: 'var(--bg-amber-500)',
|
||||
inactive: 'var(--bg-forest-500)',
|
||||
disabled: 'var(--l2-foreground)',
|
||||
};
|
||||
|
||||
export const SEVERITY_COLORS: Record<string, string> = {
|
||||
critical: 'var(--bg-cherry-500)',
|
||||
error: 'var(--bg-cherry-400)',
|
||||
warning: 'var(--bg-amber-500)',
|
||||
info: 'var(--bg-robin-500)',
|
||||
};
|
||||
|
||||
export const SEVERITY_BADGE_COLORS: Record<string, BadgeColorType> = {
|
||||
critical: 'danger',
|
||||
error: 'danger',
|
||||
|
||||
@@ -24,11 +24,6 @@
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.filtersLabel {
|
||||
color: var(--l2-foreground);
|
||||
margin-right: 2px;
|
||||
}
|
||||
|
||||
.filterControls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -8,8 +8,3 @@
|
||||
border-top: 1px solid var(--l2-border);
|
||||
background: var(--l1-background);
|
||||
}
|
||||
|
||||
.count {
|
||||
font-size: var(--label-small-400-font-size);
|
||||
color: var(--l3-foreground);
|
||||
}
|
||||
|
||||
@@ -74,10 +74,6 @@
|
||||
padding: 1px 6px;
|
||||
}
|
||||
|
||||
.deleteName {
|
||||
color: var(--danger-background);
|
||||
}
|
||||
|
||||
.row {
|
||||
position: relative;
|
||||
display: flex;
|
||||
|
||||
@@ -1,19 +1,32 @@
|
||||
import type { ReactElement } from 'react';
|
||||
import { AuthZGuardContent } from 'lib/authz/components/AuthZGuard/AuthZGuardContent';
|
||||
import PermissionDeniedCallout from 'lib/authz/components/PermissionDeniedCallout/PermissionDeniedCallout';
|
||||
import { LIST_CHECKS } from 'pages/DashboardsListPage/constants/permissions';
|
||||
import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';
|
||||
|
||||
import styles from './ViewsRailGuard.module.scss';
|
||||
|
||||
interface Props {
|
||||
/** What reading the list's saved views needs. */
|
||||
checks: BrandedPermission[];
|
||||
/**
|
||||
* Show the rail until the check denies it: while it runs, and when the check
|
||||
* itself fails, leaving the API to decide. For a list that renders before its
|
||||
* own check does.
|
||||
*/
|
||||
shouldRenderUntilDenied?: boolean;
|
||||
children: ReactElement;
|
||||
}
|
||||
|
||||
function ViewsRailGuard({ children }: Props): JSX.Element {
|
||||
function ViewsRailGuard({
|
||||
checks,
|
||||
shouldRenderUntilDenied = false,
|
||||
children,
|
||||
}: Props): JSX.Element {
|
||||
return (
|
||||
<AuthZGuardContent
|
||||
checks={LIST_CHECKS}
|
||||
onFailRenderContent={false}
|
||||
checks={checks}
|
||||
onFailRenderContent={shouldRenderUntilDenied}
|
||||
fallbackOnLoading={shouldRenderUntilDenied ? children : undefined}
|
||||
fallback={({ deniedPermissions }): ReactElement => (
|
||||
<div className={styles.denied} data-testid="views-rail-denied">
|
||||
<PermissionDeniedCallout deniedPermissions={deniedPermissions} />
|
||||
@@ -4,10 +4,9 @@ import { render, screen } from 'tests/test-utils';
|
||||
import { setupAuthzAllow } from 'lib/authz/utils/authz-test-utils';
|
||||
import { DashboardListPermission } from 'lib/authz/hooks/useAuthZ/permissions/dashboard.permissions';
|
||||
|
||||
import ViewsRailGuard from 'pages/DashboardsListPage/components/DashboardsList/ViewsRailGuard';
|
||||
|
||||
import type { BuiltinListView } from '../../types';
|
||||
import ViewsRail from '../ViewsRail';
|
||||
import ViewsRailGuard from '../ViewsRailGuard';
|
||||
|
||||
const BUILTIN_VIEWS: BuiltinListView[] = [
|
||||
{
|
||||
@@ -38,7 +37,11 @@ function renderRail(
|
||||
onDelete={jest.fn()}
|
||||
onRename={jest.fn()}
|
||||
testIdPrefix="dashboards"
|
||||
guard={(content): JSX.Element => <ViewsRailGuard>{content}</ViewsRailGuard>}
|
||||
guard={(content): JSX.Element => (
|
||||
<ViewsRailGuard checks={[DashboardListPermission]}>
|
||||
{content}
|
||||
</ViewsRailGuard>
|
||||
)}
|
||||
{...props}
|
||||
/>,
|
||||
);
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { ToggleGroup } from '@signozhq/ui/toggle-group';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { Tooltip } from 'antd';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import LogStateIndicator from 'components/Logs/LogStateIndicator/LogStateIndicator';
|
||||
@@ -20,22 +19,17 @@ import useInitialQuery from 'container/LogsExplorerContext/useInitialQuery';
|
||||
import { useOptionsMenu } from 'container/OptionsMenu';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
import { useArrowKeyNavigation } from 'container/TracesExplorer/SpanDrawer/useArrowKeyNavigation';
|
||||
import { useCloseOnOutsideClick } from 'hooks/logs/useCloseOnOutsideClick';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { getBodyMessage } from 'lib/logs/logBody';
|
||||
import { cloneDeep } from 'lodash-es';
|
||||
import {
|
||||
ArrowDown,
|
||||
ArrowUp,
|
||||
Filter,
|
||||
Histogram,
|
||||
Table,
|
||||
TextSelect,
|
||||
} from '@signozhq/icons';
|
||||
import { Filter, Histogram, Table, TextSelect } from '@signozhq/icons';
|
||||
import { Query, TagFilter } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { DataSource, StringOperators } from 'types/common/queryBuilder';
|
||||
|
||||
import { RESOURCE_KEYS, VIEW_TYPES, VIEWS } from './constants';
|
||||
import { LogDetailBodyProps } from './LogDetail.interfaces';
|
||||
import { LogNavigationHint } from './LogNavigationHint/LogNavigationHint';
|
||||
import LogHighlights from './LogHighlights/LogHighlights';
|
||||
|
||||
/* eslint-disable-next-line sonarjs/cognitive-complexity */
|
||||
@@ -61,33 +55,7 @@ function LogDetailBody({
|
||||
const [isEdit, setIsEdit] = useState<boolean>(false);
|
||||
const { stagedQuery } = useQueryBuilder();
|
||||
|
||||
// Handle clicks outside to close drawer, except on explicitly ignored regions
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (e: MouseEvent): void => {
|
||||
const target = e.target as HTMLElement;
|
||||
|
||||
// Don't close if clicking on drawer content, overlays, or portal elements
|
||||
if (
|
||||
target.closest('[data-log-detail-ignore="true"]') ||
|
||||
target.closest('.cm-tooltip-autocomplete') ||
|
||||
target.closest('.drawer-popover') ||
|
||||
target.closest('.query-status-popover') ||
|
||||
target.closest('[data-radix-popper-content-wrapper]') ||
|
||||
target.closest('[data-base-ui-portal]')
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Close the drawer for any other outside click
|
||||
onClose();
|
||||
};
|
||||
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
|
||||
return (): void => {
|
||||
document.removeEventListener('mousedown', handleClickOutside);
|
||||
};
|
||||
}, [onClose]);
|
||||
useCloseOnOutsideClick(true, onClose);
|
||||
|
||||
// Only listen in the OVERVIEW tab so we don't hijack arrow keys from the
|
||||
// JSON editor / context view.
|
||||
@@ -329,31 +297,7 @@ function LogDetailBody({
|
||||
|
||||
{selectedView === VIEW_TYPES.OVERVIEW && (
|
||||
<div className="log-detail-drawer__footer-hint">
|
||||
<div className="log-detail-drawer__footer-hint-content">
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="secondary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Use
|
||||
</Typography>
|
||||
<ArrowUp size={14} className="log-detail-drawer__footer-hint-icon" />
|
||||
<span>/</span>
|
||||
<ArrowDown size={14} className="log-detail-drawer__footer-hint-icon" />
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="secondary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
to view previous/next log
|
||||
</Typography>
|
||||
</div>
|
||||
<LogNavigationHint />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -110,17 +110,5 @@
|
||||
color: var(--l3-foreground);
|
||||
background: var(--drawer-background);
|
||||
z-index: 10;
|
||||
|
||||
.log-detail-drawer__footer-hint-content {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.log-detail-drawer__footer-hint-icon {
|
||||
display: inline;
|
||||
vertical-align: middle;
|
||||
color: var(--l3-foreground);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { act, renderHook } from 'tests/test-utils';
|
||||
|
||||
import { useLogNavigation } from '../useLogNavigation';
|
||||
|
||||
interface TestLog {
|
||||
id: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
const logs: TestLog[] = [
|
||||
{ id: 'a', label: 'first' },
|
||||
{ id: 'b', label: 'second' },
|
||||
{ id: 'c', label: 'third' },
|
||||
];
|
||||
|
||||
const onNavigateLog = jest.fn() as jest.MockedFunction<(log: TestLog) => void>;
|
||||
const onScrollToLog = jest.fn() as jest.MockedFunction<(id: string) => void>;
|
||||
|
||||
function renderNavigation(
|
||||
activeLogId: string,
|
||||
list: TestLog[] | undefined = logs,
|
||||
) {
|
||||
return renderHook(() =>
|
||||
useLogNavigation<TestLog>({
|
||||
logs: list,
|
||||
activeLogId,
|
||||
onNavigateLog,
|
||||
onScrollToLog,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('useLogNavigation', () => {
|
||||
it('disables previous on the first log', () => {
|
||||
const { result } = renderNavigation('a');
|
||||
|
||||
expect(result.current.isPrevDisabled).toBe(true);
|
||||
expect(result.current.isNextDisabled).toBe(false);
|
||||
});
|
||||
|
||||
it('disables next on the last log', () => {
|
||||
const { result } = renderNavigation('c');
|
||||
|
||||
expect(result.current.isPrevDisabled).toBe(false);
|
||||
expect(result.current.isNextDisabled).toBe(true);
|
||||
});
|
||||
|
||||
it('enables both in the middle', () => {
|
||||
const { result } = renderNavigation('b');
|
||||
|
||||
expect(result.current.isPrevDisabled).toBe(false);
|
||||
expect(result.current.isNextDisabled).toBe(false);
|
||||
});
|
||||
|
||||
it('moves to the next log and scrolls to it', () => {
|
||||
const { result } = renderNavigation('b');
|
||||
|
||||
act(() => result.current.goToNext());
|
||||
|
||||
expect(onNavigateLog).toHaveBeenCalledWith(logs[2]);
|
||||
expect(onScrollToLog).toHaveBeenCalledWith('c');
|
||||
});
|
||||
|
||||
it('moves to the previous log and scrolls to it', () => {
|
||||
const { result } = renderNavigation('b');
|
||||
|
||||
act(() => result.current.goToPrev());
|
||||
|
||||
expect(onNavigateLog).toHaveBeenCalledWith(logs[0]);
|
||||
expect(onScrollToLog).toHaveBeenCalledWith('a');
|
||||
});
|
||||
|
||||
it('does nothing past the ends', () => {
|
||||
const { result } = renderNavigation('a');
|
||||
|
||||
act(() => result.current.goToPrev());
|
||||
|
||||
expect(onNavigateLog).not.toHaveBeenCalled();
|
||||
expect(onScrollToLog).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('disables both when the active log is not in the list', () => {
|
||||
const { result } = renderNavigation('missing');
|
||||
|
||||
expect(result.current.isPrevDisabled).toBe(true);
|
||||
expect(result.current.isNextDisabled).toBe(true);
|
||||
});
|
||||
|
||||
it('disables both without logs', () => {
|
||||
const { result } = renderNavigation('a', []);
|
||||
|
||||
expect(result.current.isPrevDisabled).toBe(true);
|
||||
expect(result.current.isNextDisabled).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,10 @@
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { ILog } from 'types/api/logs/log';
|
||||
import { LogWithId } from 'hooks/logs/types';
|
||||
|
||||
interface UseLogNavigationParams {
|
||||
logs?: ILog[];
|
||||
interface UseLogNavigationParams<T extends LogWithId> {
|
||||
logs?: T[];
|
||||
activeLogId: string;
|
||||
onNavigateLog?: (log: ILog) => void;
|
||||
onNavigateLog?: (log: T) => void;
|
||||
onScrollToLog?: (id: string) => void;
|
||||
}
|
||||
|
||||
@@ -15,12 +15,12 @@ interface UseLogNavigationReturn {
|
||||
isNextDisabled: boolean;
|
||||
}
|
||||
|
||||
export function useLogNavigation({
|
||||
export function useLogNavigation<T extends LogWithId>({
|
||||
logs,
|
||||
activeLogId,
|
||||
onNavigateLog,
|
||||
onScrollToLog,
|
||||
}: UseLogNavigationParams): UseLogNavigationReturn {
|
||||
}: UseLogNavigationParams<T>): UseLogNavigationReturn {
|
||||
const currentIndex = useMemo(
|
||||
() => logs?.findIndex((l) => l.id === activeLogId) ?? -1,
|
||||
[logs, activeLogId],
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
.content {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-2);
|
||||
}
|
||||
|
||||
.icon {
|
||||
display: inline;
|
||||
vertical-align: middle;
|
||||
color: var(--l3-foreground);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { ArrowDown, ArrowUp } from '@signozhq/icons';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
|
||||
import styles from './LogNavigationHint.module.scss';
|
||||
|
||||
export function LogNavigationHint(): JSX.Element {
|
||||
return (
|
||||
<div className={styles.content}>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="secondary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Use
|
||||
</Typography>
|
||||
<ArrowUp size={14} className={styles.icon} />
|
||||
<span>/</span>
|
||||
<ArrowDown size={14} className={styles.icon} />
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="secondary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
to view previous/next log
|
||||
</Typography>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import Spinner from 'components/Spinner';
|
||||
|
||||
export function LogsLoadingFooter(): JSX.Element {
|
||||
return <Spinner height={20} tip="Getting Logs" testId="logs-loading-footer" />;
|
||||
}
|
||||
@@ -191,6 +191,7 @@ function OptionsMenu({
|
||||
type="button"
|
||||
className="periscope-btn"
|
||||
aria-label="Fewer lines per row"
|
||||
data-testid="max-lines-fewer"
|
||||
onClick={(): void => handleLinesPerRowChange(maxLinesPerRow - 1)}
|
||||
>
|
||||
<Minus size={12} />
|
||||
@@ -211,6 +212,7 @@ function OptionsMenu({
|
||||
type="button"
|
||||
className="periscope-btn"
|
||||
aria-label="More lines per row"
|
||||
data-testid="max-lines-more"
|
||||
onClick={(): void => handleLinesPerRowChange(maxLinesPerRow + 1)}
|
||||
>
|
||||
<Plus size={12} />
|
||||
|
||||
@@ -3,6 +3,7 @@ import { screen, userEvent } from 'storybook/test';
|
||||
|
||||
import { withCanvas } from '@/storybook/decorators/withCanvas';
|
||||
import type { GlobalMockArgs } from '@/storybook/globals';
|
||||
import { hoverTruncated } from '@/storybook/play/truncatedText';
|
||||
|
||||
import { CustomMultiSelect, CustomSelect } from '../index';
|
||||
|
||||
@@ -142,7 +143,7 @@ export const TruncatedOption: Story = {
|
||||
await userEvent.click(
|
||||
await screen.findByRole('combobox', { name: 'Service' }),
|
||||
);
|
||||
await userEvent.hover(
|
||||
await hoverTruncated(
|
||||
await screen.findByRole('option', { name: LONG_LABEL_OPTION.label }),
|
||||
);
|
||||
await screen.findByRole('tooltip', { name: LONG_LABEL_OPTION.label });
|
||||
@@ -156,7 +157,7 @@ export const TruncatedValue: Story = {
|
||||
value: LONG_LABEL_OPTION.value,
|
||||
},
|
||||
play: async (): Promise<void> => {
|
||||
await userEvent.hover(await screen.findByText(LONG_LABEL_OPTION.label));
|
||||
await hoverTruncated(await screen.findByText(LONG_LABEL_OPTION.label));
|
||||
await screen.findByRole('tooltip', { name: LONG_LABEL_OPTION.label });
|
||||
},
|
||||
};
|
||||
@@ -173,7 +174,7 @@ export const MultiTruncatedOption: Story = {
|
||||
await userEvent.click(
|
||||
await screen.findByRole('combobox', { name: 'Services' }),
|
||||
);
|
||||
await userEvent.hover(
|
||||
await hoverTruncated(
|
||||
await screen.findByRole('option', { name: LONG_LABEL_OPTION.label }),
|
||||
);
|
||||
await screen.findByRole('tooltip', { name: LONG_LABEL_OPTION.label });
|
||||
|
||||
@@ -62,16 +62,6 @@ $custom-border-color: #2c3044;
|
||||
}
|
||||
}
|
||||
|
||||
.all-selected-text {
|
||||
position: absolute;
|
||||
left: 12px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
color: var(--l2-foreground);
|
||||
z-index: 1;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.ant-select-selector {
|
||||
max-height: 200px;
|
||||
overflow: auto;
|
||||
@@ -450,8 +440,7 @@ $custom-border-color: #2c3044;
|
||||
width: 100%;
|
||||
background-color: var(--l2-background);
|
||||
|
||||
.select-all-option,
|
||||
.custom-value-option {
|
||||
.select-all-option {
|
||||
padding: 8px 12px;
|
||||
border-bottom: 1px solid $custom-border-color;
|
||||
margin-bottom: 8px;
|
||||
@@ -461,16 +450,6 @@ $custom-border-color: #2c3044;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.selected-values-section {
|
||||
padding: 0 0 8px 0;
|
||||
border-bottom: 1px solid $custom-border-color;
|
||||
margin-bottom: 8px;
|
||||
|
||||
.selected-option {
|
||||
padding: 4px 12px;
|
||||
}
|
||||
}
|
||||
|
||||
.select-group {
|
||||
margin-bottom: 12px;
|
||||
overflow: hidden;
|
||||
@@ -656,14 +635,6 @@ $custom-border-color: #2c3044;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
// Custom option styles for keyboard navigation
|
||||
.custom-option {
|
||||
&.focused,
|
||||
&.ant-select-item-option-active {
|
||||
background-color: var(--l1-border) !important;
|
||||
}
|
||||
}
|
||||
|
||||
// Improve the sticky headers appearance
|
||||
.custom-select-dropdown-container {
|
||||
.group-label,
|
||||
@@ -744,12 +715,6 @@ $custom-border-color: #2c3044;
|
||||
.custom-multiselect-dropdown {
|
||||
@include custom-scrollbar;
|
||||
|
||||
// Main content area
|
||||
.options-container {
|
||||
@include custom-scrollbar;
|
||||
padding-right: 2px; // Add slight padding to prevent content touching scrollbar
|
||||
}
|
||||
|
||||
// Non-sectioned options
|
||||
.no-section-options {
|
||||
@include nested-scrollbar;
|
||||
@@ -762,11 +727,6 @@ $custom-border-color: #2c3044;
|
||||
.custom-select-dropdown-container,
|
||||
.custom-multiselect-dropdown-container {
|
||||
@include custom-scrollbar;
|
||||
|
||||
// Add subtle shadow inside to indicate scrollable area
|
||||
&.has-overflow {
|
||||
box-shadow: inset 0 -10px 10px -10px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
}
|
||||
|
||||
// Light Mode Overrides
|
||||
@@ -958,16 +918,11 @@ $custom-border-color: #2c3044;
|
||||
}
|
||||
|
||||
.custom-multiselect-dropdown {
|
||||
.select-all-option,
|
||||
.custom-value-option {
|
||||
.select-all-option {
|
||||
border-bottom: 1px solid #f0f0f0;
|
||||
background-color: #fafafa;
|
||||
}
|
||||
|
||||
.selected-values-section {
|
||||
border-bottom: 1px solid #f0f0f0;
|
||||
}
|
||||
|
||||
.status-message {
|
||||
color: rgba(0, 0, 0, 0.65);
|
||||
border-top: 1px dashed #f0f0f0;
|
||||
@@ -984,13 +939,6 @@ $custom-border-color: #2c3044;
|
||||
background-color: rgba(24, 144, 255, 0.2);
|
||||
}
|
||||
|
||||
.custom-option {
|
||||
&.focused,
|
||||
&.ant-select-item-option-active {
|
||||
background-color: #f5f5f5 !important;
|
||||
}
|
||||
}
|
||||
|
||||
.custom-select-dropdown-container {
|
||||
.group-label,
|
||||
.ant-select-item-group {
|
||||
|
||||
@@ -35,7 +35,6 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
|
||||
isRawQuery = false,
|
||||
showOnlyWhereClause = false,
|
||||
showTraceOperator = false,
|
||||
version,
|
||||
onSignalSourceChange,
|
||||
signalSourceChangeEnabled = false,
|
||||
savePreviousQuery = false,
|
||||
@@ -235,12 +234,11 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
|
||||
isMultiQueryAllowed={isMultiQueryAllowed}
|
||||
showTraceOperator={canShowTraceOperator}
|
||||
hasTraceOperator={hasTraceOperator}
|
||||
version={version}
|
||||
isAvailableToDisable={false}
|
||||
queryVariant={config?.queryVariant || 'dropdown'}
|
||||
showOnlyWhereClause={showOnlyWhereClause}
|
||||
isRawQuery={isRawQuery}
|
||||
signalSource={activeBuilder.queryData[0].source as 'meter' | ''}
|
||||
signalSource={activeBuilder.queryData[0].source}
|
||||
onSignalSourceChange={onSignalSourceChange || ((): void => {})}
|
||||
signalSourceChangeEnabled={signalSourceChangeEnabled}
|
||||
queriesCount={1}
|
||||
@@ -255,7 +253,6 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
|
||||
query={query}
|
||||
fieldsConfig={fieldsConfig}
|
||||
allowedDataSources={queryDataSources}
|
||||
version={version}
|
||||
isMultiQueryAllowed={isMultiQueryAllowed}
|
||||
isAvailableToDisable={false}
|
||||
showTraceOperator={canShowTraceOperator}
|
||||
@@ -263,7 +260,7 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
|
||||
queryVariant={config?.queryVariant || 'dropdown'}
|
||||
showOnlyWhereClause={showOnlyWhereClause}
|
||||
isRawQuery={isRawQuery}
|
||||
signalSource={query.source as 'meter' | ''}
|
||||
signalSource={query.source}
|
||||
onSignalSourceChange={onSignalSourceChange || ((): void => {})}
|
||||
signalSourceChangeEnabled={signalSourceChangeEnabled}
|
||||
queriesCount={activeBuilder.queryData.length}
|
||||
|
||||
@@ -23,13 +23,11 @@ import './MetricsAggregateSection.styles.scss';
|
||||
const MetricsAggregateSection = memo(function MetricsAggregateSection({
|
||||
query,
|
||||
index,
|
||||
version,
|
||||
panelType,
|
||||
fieldsConfig,
|
||||
}: {
|
||||
query: IBuilderQuery;
|
||||
index: number;
|
||||
version: string;
|
||||
panelType: PANEL_TYPES | null;
|
||||
fieldsConfig?: QueryBuilderFieldsConfig;
|
||||
}): JSX.Element {
|
||||
@@ -46,7 +44,6 @@ const MetricsAggregateSection = memo(function MetricsAggregateSection({
|
||||
} = useQueryOperations({
|
||||
index,
|
||||
query,
|
||||
entityVersion: version,
|
||||
});
|
||||
|
||||
// this function is only relevant for metrics and now operators are part of aggregations
|
||||
|
||||
@@ -29,7 +29,6 @@ export const SOURCE_OPTIONS: SelectOption<string, string>[] = [
|
||||
export const MetricsSelect = memo(function MetricsSelect({
|
||||
query,
|
||||
index,
|
||||
version,
|
||||
signalSource,
|
||||
onSignalSourceChange,
|
||||
signalSourceChangeEnabled = false,
|
||||
@@ -37,7 +36,6 @@ export const MetricsSelect = memo(function MetricsSelect({
|
||||
}: {
|
||||
query: IBuilderQuery;
|
||||
index: number;
|
||||
version: string;
|
||||
signalSource: 'meter' | '';
|
||||
onSignalSourceChange: (value: string) => void;
|
||||
signalSourceChangeEnabled: boolean;
|
||||
@@ -46,7 +44,6 @@ export const MetricsSelect = memo(function MetricsSelect({
|
||||
const { handleChangeAggregatorAttribute } = useQueryOperations({
|
||||
index,
|
||||
query,
|
||||
entityVersion: version,
|
||||
});
|
||||
|
||||
const { updateAllQueriesOperators, handleSetQueryData, panelType } =
|
||||
|
||||
@@ -53,7 +53,6 @@ import './QueryAddOns.styles.scss';
|
||||
|
||||
function QueryAddOns({
|
||||
query,
|
||||
version,
|
||||
isRawQuery,
|
||||
showReduceTo,
|
||||
panelType,
|
||||
@@ -62,7 +61,6 @@ function QueryAddOns({
|
||||
isForTraceOperator = false,
|
||||
}: {
|
||||
query: IBuilderQuery;
|
||||
version: string;
|
||||
isRawQuery: boolean;
|
||||
showReduceTo: boolean;
|
||||
panelType: PANEL_TYPES | null;
|
||||
@@ -78,7 +76,6 @@ function QueryAddOns({
|
||||
const { handleChangeQueryData } = useQueryOperations({
|
||||
index,
|
||||
query,
|
||||
entityVersion: '',
|
||||
isForTraceOperator,
|
||||
});
|
||||
|
||||
@@ -433,7 +430,6 @@ function QueryAddOns({
|
||||
</Tooltip>
|
||||
<div className="input">
|
||||
<OrderByFilter
|
||||
entityVersion={version}
|
||||
query={query}
|
||||
onChange={handleChangeOrderByKeys}
|
||||
isRawQuery={isRawQuery}
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
} from 'react';
|
||||
import { Dropdown, type DropdownItemType } from '@signozhq/ui/dropdown';
|
||||
import cx from 'classnames';
|
||||
import { ENTITY_VERSION_V4, ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import QBEntityOptions from 'container/QueryBuilder/components/QBEntityOptions/QBEntityOptions';
|
||||
import { QueryProps } from 'container/QueryBuilder/type';
|
||||
import SpanScopeSelector from 'container/QueryBuilder/filters/QueryBuilderSearchV2/SpanScopeSelector';
|
||||
@@ -42,7 +41,6 @@ export const QueryV2 = forwardRef(function QueryV2(
|
||||
isRawQuery = false,
|
||||
showTraceOperator = false,
|
||||
hasTraceOperator = false,
|
||||
version,
|
||||
showOnlyWhereClause = false,
|
||||
signalSource = '',
|
||||
isMultiQueryAllowed = false,
|
||||
@@ -77,7 +75,6 @@ export const QueryV2 = forwardRef(function QueryV2(
|
||||
index,
|
||||
query,
|
||||
isRawQuery,
|
||||
entityVersion: version,
|
||||
savePreviousQuery,
|
||||
});
|
||||
|
||||
@@ -193,8 +190,7 @@ export const QueryV2 = forwardRef(function QueryV2(
|
||||
isMetricsDataSource={dataSource === DataSource.METRICS}
|
||||
showFunctions={
|
||||
!functions.hidden &&
|
||||
((version && version === ENTITY_VERSION_V4) ||
|
||||
query.dataSource === DataSource.LOGS ||
|
||||
(query.dataSource === DataSource.LOGS ||
|
||||
query.dataSource === DataSource.METRICS ||
|
||||
hasQueryFunctions ||
|
||||
false)
|
||||
@@ -265,7 +261,6 @@ export const QueryV2 = forwardRef(function QueryV2(
|
||||
<MetricsSelect
|
||||
query={query}
|
||||
index={index}
|
||||
version={ENTITY_VERSION_V5}
|
||||
signalSource={signalSource as 'meter' | ''}
|
||||
onSignalSourceChange={onSignalSourceChange}
|
||||
signalSourceChangeEnabled={signalSourceChangeEnabled}
|
||||
@@ -317,7 +312,6 @@ export const QueryV2 = forwardRef(function QueryV2(
|
||||
query={query}
|
||||
index={index}
|
||||
key={`metrics-aggregate-section-${query.queryName}-${query.dataSource}-${signalSource}`}
|
||||
version="v4"
|
||||
fieldsConfig={fieldsConfig}
|
||||
/>
|
||||
)}
|
||||
@@ -327,7 +321,6 @@ export const QueryV2 = forwardRef(function QueryV2(
|
||||
<QueryAddOns
|
||||
index={index}
|
||||
query={query}
|
||||
version="v3"
|
||||
isRawQuery={isRawQuery}
|
||||
showReduceTo={showReduceTo}
|
||||
panelType={panelType}
|
||||
|
||||
@@ -31,7 +31,6 @@ export default function TraceOperator({
|
||||
const { handleChangeQueryData } = useQueryOperations({
|
||||
index: 0,
|
||||
query: traceOperator,
|
||||
entityVersion: '',
|
||||
isForTraceOperator: true,
|
||||
});
|
||||
|
||||
@@ -116,7 +115,6 @@ export default function TraceOperator({
|
||||
<QueryAddOns
|
||||
index={0}
|
||||
query={traceOperator}
|
||||
version="v3"
|
||||
isForTraceOperator
|
||||
isRawQuery={false}
|
||||
showReduceTo={false}
|
||||
|
||||
@@ -177,7 +177,6 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
<QueryV2
|
||||
index={0}
|
||||
query={queryA}
|
||||
version="v4"
|
||||
isAvailableToDisable={false}
|
||||
isMultiQueryAllowed
|
||||
queriesCount={queriesCount}
|
||||
@@ -190,7 +189,7 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
};
|
||||
|
||||
it('renders limit input when dataSource is logs', () => {
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} />);
|
||||
|
||||
// Ensure the Limit add-on input is present and is of type number
|
||||
const limitInput = screen.getByPlaceholderText(
|
||||
@@ -204,7 +203,7 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
|
||||
it('Cmd+Enter on the limit input triggers handleRunQuery via container handler', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} />);
|
||||
|
||||
screen.getByTestId('input-Limit-field').focus();
|
||||
await user.keyboard('{Meta>}{Enter}{/Meta}');
|
||||
@@ -214,7 +213,7 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
|
||||
it('Cmd+Enter on the legend input triggers handleRunQuery via container handler', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} />);
|
||||
|
||||
screen.getByPlaceholderText('Write legend format').focus();
|
||||
await user.keyboard('{Meta>}{Enter}{/Meta}');
|
||||
@@ -224,7 +223,7 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
|
||||
it('Cmd+Enter in the where clause editor triggers handleRunQuery via container handler', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} />);
|
||||
|
||||
const editorWrapper = await screen.findByTestId('query-where-clause-editor');
|
||||
within(editorWrapper).getByRole('textbox').focus();
|
||||
@@ -249,7 +248,7 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
});
|
||||
|
||||
expect(() =>
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />),
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} />),
|
||||
).not.toThrow();
|
||||
|
||||
// query list still renders from queryData, formulas block is skipped
|
||||
@@ -342,7 +341,7 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
},
|
||||
});
|
||||
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} />);
|
||||
|
||||
const fxButton = screen.getByTestId('query-functions-fx-btn');
|
||||
expect(fxButton).toBeInTheDocument();
|
||||
|
||||
@@ -103,7 +103,6 @@ describe('QueryAddOns', () => {
|
||||
render(
|
||||
<QueryAddOns
|
||||
query={baseQuery()}
|
||||
version="v5"
|
||||
isRawQuery={false}
|
||||
showReduceTo
|
||||
panelType={PANEL_TYPES.VALUE}
|
||||
@@ -127,7 +126,6 @@ describe('QueryAddOns', () => {
|
||||
dataSource: DataSource.METRICS,
|
||||
groupBy: ['service.name'],
|
||||
})}
|
||||
version="v5"
|
||||
isRawQuery={false}
|
||||
showReduceTo={false}
|
||||
panelType={PANEL_TYPES.TIME_SERIES}
|
||||
@@ -143,7 +141,6 @@ describe('QueryAddOns', () => {
|
||||
render(
|
||||
<QueryAddOns
|
||||
query={baseQuery()}
|
||||
version="v5"
|
||||
isRawQuery
|
||||
showReduceTo={false}
|
||||
panelType={PANEL_TYPES.LIST}
|
||||
@@ -159,7 +156,6 @@ describe('QueryAddOns', () => {
|
||||
render(
|
||||
<QueryAddOns
|
||||
query={baseQuery({ limit: 5 })}
|
||||
version="v5"
|
||||
isRawQuery={false}
|
||||
showReduceTo={false}
|
||||
panelType={PANEL_TYPES.TIME_SERIES}
|
||||
@@ -193,7 +189,6 @@ describe('QueryAddOns', () => {
|
||||
render(
|
||||
<QueryAddOns
|
||||
query={baseQuery()}
|
||||
version="v5"
|
||||
isRawQuery={false}
|
||||
showReduceTo={false}
|
||||
panelType={PANEL_TYPES.TIME_SERIES}
|
||||
@@ -215,7 +210,6 @@ describe('QueryAddOns', () => {
|
||||
render(
|
||||
<QueryAddOns
|
||||
query={baseQuery()}
|
||||
version="v5"
|
||||
isRawQuery={false}
|
||||
showReduceTo={false}
|
||||
panelType={PANEL_TYPES.TIME_SERIES}
|
||||
@@ -237,7 +231,6 @@ describe('QueryAddOns', () => {
|
||||
render(
|
||||
<QueryAddOns
|
||||
query={baseQuery()}
|
||||
version="v5"
|
||||
isRawQuery={false}
|
||||
showReduceTo={false}
|
||||
panelType={PANEL_TYPES.TOP_LIST}
|
||||
@@ -311,7 +304,6 @@ describe('QueryAddOns', () => {
|
||||
render(
|
||||
<QueryAddOns
|
||||
query={query}
|
||||
version="v5"
|
||||
isRawQuery={false}
|
||||
showReduceTo={false}
|
||||
panelType={PANEL_TYPES.TIME_SERIES}
|
||||
@@ -332,7 +324,6 @@ describe('QueryAddOns', () => {
|
||||
render(
|
||||
<QueryAddOns
|
||||
query={baseQuery()}
|
||||
version="v5"
|
||||
isRawQuery={false}
|
||||
showReduceTo
|
||||
panelType={PANEL_TYPES.TIME_SERIES}
|
||||
@@ -348,7 +339,6 @@ describe('QueryAddOns', () => {
|
||||
render(
|
||||
<QueryAddOns
|
||||
query={baseQuery({ reduceTo: ReduceOperators.SUM })}
|
||||
version="v5"
|
||||
isRawQuery={false}
|
||||
showReduceTo
|
||||
panelType={PANEL_TYPES.TIME_SERIES}
|
||||
@@ -371,7 +361,6 @@ describe('QueryAddOns', () => {
|
||||
render(
|
||||
<QueryAddOns
|
||||
query={query}
|
||||
version="v5"
|
||||
isRawQuery={false}
|
||||
showReduceTo
|
||||
panelType={PANEL_TYPES.TIME_SERIES}
|
||||
@@ -423,7 +412,6 @@ describe('QueryAddOns', () => {
|
||||
render(
|
||||
<QueryAddOns
|
||||
query={query}
|
||||
version="v5"
|
||||
isRawQuery={false}
|
||||
showReduceTo={false}
|
||||
panelType={PANEL_TYPES.TIME_SERIES}
|
||||
@@ -447,7 +435,6 @@ describe('QueryAddOns', () => {
|
||||
render(
|
||||
<QueryAddOns
|
||||
query={baseQuery()}
|
||||
version="v5"
|
||||
isRawQuery={false}
|
||||
showReduceTo={false}
|
||||
panelType={PANEL_TYPES.TIME_SERIES}
|
||||
@@ -474,7 +461,6 @@ describe('QueryAddOns', () => {
|
||||
render(
|
||||
<QueryAddOns
|
||||
query={query}
|
||||
version="v5"
|
||||
isRawQuery={false}
|
||||
showReduceTo={false}
|
||||
panelType={PANEL_TYPES.TIME_SERIES}
|
||||
@@ -496,7 +482,6 @@ describe('QueryAddOns', () => {
|
||||
render(
|
||||
<QueryAddOns
|
||||
query={baseQuery({ dataSource: DataSource.METRICS, ...overrides })}
|
||||
version="v5"
|
||||
isRawQuery={false}
|
||||
showReduceTo={false}
|
||||
panelType={PANEL_TYPES.HEATMAP}
|
||||
@@ -518,7 +503,6 @@ describe('QueryAddOns', () => {
|
||||
render(
|
||||
<QueryAddOns
|
||||
query={baseQuery({ dataSource: DataSource.METRICS })}
|
||||
version="v5"
|
||||
isRawQuery={false}
|
||||
showReduceTo={false}
|
||||
panelType={PANEL_TYPES.TIME_SERIES}
|
||||
|
||||
@@ -42,7 +42,6 @@ jest.mock(
|
||||
},
|
||||
);
|
||||
jest.mock('container/QueryBuilder/filters', () => ({
|
||||
AggregatorFilter: (): JSX.Element => <div />,
|
||||
MetricNameSelector: (): JSX.Element => <div />,
|
||||
}));
|
||||
// Mock hooks
|
||||
@@ -150,7 +149,6 @@ describe('MetricsSelect - signal source switching (standalone)', () => {
|
||||
render(
|
||||
<QueryBuilderV2
|
||||
panelType={PANEL_TYPES.TABLE}
|
||||
version="v5"
|
||||
signalSourceChangeEnabled
|
||||
savePreviousQuery
|
||||
/>,
|
||||
@@ -185,11 +183,7 @@ describe('MetricsSelect - signal source switching (standalone)', () => {
|
||||
const user = userEvent.setup();
|
||||
// render WITHOUT savePreviousQuery enabled
|
||||
render(
|
||||
<QueryBuilderV2
|
||||
panelType={PANEL_TYPES.TABLE}
|
||||
version="v5"
|
||||
signalSourceChangeEnabled
|
||||
/>,
|
||||
<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} signalSourceChangeEnabled />,
|
||||
);
|
||||
|
||||
// open Source and choose Meter
|
||||
@@ -307,7 +301,6 @@ describe('DataSource change - Logs to Traces', () => {
|
||||
render(
|
||||
<QueryBuilderV2
|
||||
panelType={PANEL_TYPES.TABLE}
|
||||
version="v5"
|
||||
signalSourceChangeEnabled
|
||||
savePreviousQuery
|
||||
/>,
|
||||
@@ -333,11 +326,7 @@ describe('DataSource change - Logs to Traces', () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<QueryBuilderV2
|
||||
panelType={PANEL_TYPES.TABLE}
|
||||
version="v5"
|
||||
signalSourceChangeEnabled
|
||||
/>,
|
||||
<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} signalSourceChangeEnabled />,
|
||||
);
|
||||
|
||||
const logsTrigger = within(
|
||||
|
||||
@@ -21,22 +21,18 @@ jest.mock('../QueryV2/QueryV2', () => ({
|
||||
jest.mock('../QueryV2/QueryFooter/QueryFooter', () => (): null => null);
|
||||
|
||||
function renderWith(currentQuery: Query): void {
|
||||
render(
|
||||
<QueryBuilderV2 panelType={PANEL_TYPES.TIME_SERIES} version="v3" />,
|
||||
undefined,
|
||||
{
|
||||
queryBuilderOverrides: {
|
||||
currentQuery,
|
||||
panelType: PANEL_TYPES.TIME_SERIES,
|
||||
initialDataSource: null,
|
||||
handleSetConfig: jest.fn(),
|
||||
addNewBuilderQuery: jest.fn(),
|
||||
addNewFormula: jest.fn(),
|
||||
addTraceOperator: jest.fn(),
|
||||
handleRunQuery: jest.fn(),
|
||||
},
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TIME_SERIES} />, undefined, {
|
||||
queryBuilderOverrides: {
|
||||
currentQuery,
|
||||
panelType: PANEL_TYPES.TIME_SERIES,
|
||||
initialDataSource: null,
|
||||
handleSetConfig: jest.fn(),
|
||||
addNewBuilderQuery: jest.fn(),
|
||||
addNewFormula: jest.fn(),
|
||||
addTraceOperator: jest.fn(),
|
||||
handleRunQuery: jest.fn(),
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const builderWithQuery = (
|
||||
|
||||
@@ -51,7 +51,7 @@ describe('QueryBuilderV2 provider config sync', () => {
|
||||
it('leaves the data source unset for a bar panel without a static config', () => {
|
||||
const handleSetConfig = mockContext({});
|
||||
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.BAR} version="v3" />);
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.BAR} />);
|
||||
|
||||
expect(handleSetConfig).toHaveBeenCalledWith(PANEL_TYPES.BAR, null);
|
||||
});
|
||||
@@ -61,7 +61,6 @@ describe('QueryBuilderV2 provider config sync', () => {
|
||||
|
||||
render(
|
||||
<QueryBuilderV2
|
||||
version="v3"
|
||||
panelType={PANEL_TYPES.BAR}
|
||||
config={{ initialDataSource: DataSource.LOGS, queryVariant: 'static' }}
|
||||
/>,
|
||||
@@ -78,7 +77,6 @@ describe('QueryBuilderV2 provider config sync', () => {
|
||||
|
||||
render(
|
||||
<QueryBuilderV2
|
||||
version="v3"
|
||||
panelType={PANEL_TYPES.BAR}
|
||||
config={{ initialDataSource: DataSource.TRACES, queryVariant: 'static' }}
|
||||
/>,
|
||||
@@ -98,7 +96,6 @@ describe('QueryBuilderV2 provider config sync', () => {
|
||||
|
||||
render(
|
||||
<QueryBuilderV2
|
||||
version="v3"
|
||||
panelType={PANEL_TYPES.TIME_SERIES}
|
||||
config={{ initialDataSource: DataSource.TRACES, queryVariant: 'static' }}
|
||||
/>,
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
import { negateOperator, OPERATORS } from 'constants/antlrQueryConstants';
|
||||
import { initialQueryBuilderFormValuesMap } from 'constants/queryBuilder';
|
||||
import {
|
||||
BaseAutocompleteData,
|
||||
DataTypes,
|
||||
} from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { Query, TagFilter } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
|
||||
import { extractQueryPairs } from 'utils/queryContextUtils';
|
||||
|
||||
import {
|
||||
adjustQueryForV5,
|
||||
convertAggregationToExpression,
|
||||
convertExpressionToFilters,
|
||||
convertFiltersToExpression,
|
||||
@@ -1687,31 +1684,3 @@ describe('formatValueForExpression', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('adjustQueryForV5', () => {
|
||||
it('adjusts the AI builder slot for AI query builder queries', () => {
|
||||
const emptyBuilder = {
|
||||
queryData: [],
|
||||
queryFormulas: [],
|
||||
queryTraceOperator: [],
|
||||
};
|
||||
const query: Query = {
|
||||
id: 'q',
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
promql: [],
|
||||
clickhouse_sql: [],
|
||||
builder: emptyBuilder,
|
||||
builder_ai_query: {
|
||||
...emptyBuilder,
|
||||
queryData: [initialQueryBuilderFormValuesMap.logs],
|
||||
},
|
||||
};
|
||||
|
||||
const result = adjustQueryForV5(query);
|
||||
|
||||
expect(result.builder).toBe(emptyBuilder);
|
||||
expect(result.builder_ai_query?.queryData[0]).not.toHaveProperty(
|
||||
'aggregateOperator',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { expect, waitFor } from 'storybook/test';
|
||||
|
||||
import { withCanvas } from '@/storybook/decorators/withCanvas';
|
||||
|
||||
@@ -9,15 +8,18 @@ import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { QueryBuilderV2 } from '../QueryBuilderV2';
|
||||
import {
|
||||
addOnToggles,
|
||||
appendToAggregation,
|
||||
expectGaugeDefaults,
|
||||
expectHistogramDefaults,
|
||||
expectSingleAggregation,
|
||||
expectTablePanelAddOns,
|
||||
expectTimeSeriesAddOns,
|
||||
expectValuePanelAddOns,
|
||||
} from './__story_mockdata__/queryBuilder.play';
|
||||
import {
|
||||
DEFAULT_ARGS,
|
||||
expectFirstQuery,
|
||||
PANEL_EDITOR_ARGS,
|
||||
PANEL_EDITOR_PATH,
|
||||
payloadIn,
|
||||
routeWith,
|
||||
selectMetric,
|
||||
} from './QueryBuilderV2.stories.mocks';
|
||||
import QueryProbe from './QueryProbe';
|
||||
|
||||
@@ -60,11 +62,7 @@ export const LogsOnValuePanel: Story = {
|
||||
parameters: {
|
||||
signoz: { route: routeWith(PANEL_EDITOR_PATH, initialQueriesMap.logs) },
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
await waitFor(() =>
|
||||
expect(addOnToggles(canvasElement)).toStrictEqual(['legend_format']),
|
||||
);
|
||||
},
|
||||
play: expectValuePanelAddOns,
|
||||
};
|
||||
|
||||
/** Metrics on a Table: reduce-to is offered; group by lives in the aggregation row. */
|
||||
@@ -73,17 +71,7 @@ export const MetricsOnTablePanel: Story = {
|
||||
parameters: {
|
||||
signoz: { route: routeWith(PANEL_EDITOR_PATH, initialQueriesMap.metrics) },
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
await waitFor(() =>
|
||||
expect(addOnToggles(canvasElement)).toStrictEqual([
|
||||
'having',
|
||||
'order_by',
|
||||
'limit',
|
||||
'legend_format',
|
||||
'reduce_to',
|
||||
]),
|
||||
);
|
||||
},
|
||||
play: expectTablePanelAddOns,
|
||||
};
|
||||
|
||||
/** Traces on a time series: every add-on, with group by as a toggle. */
|
||||
@@ -92,54 +80,21 @@ export const TracesOnTimeSeriesPanel: Story = {
|
||||
parameters: {
|
||||
signoz: { route: routeWith(PANEL_EDITOR_PATH, initialQueriesMap.traces) },
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
await waitFor(() =>
|
||||
expect(addOnToggles(canvasElement)).toStrictEqual([
|
||||
'group_by',
|
||||
'having',
|
||||
'order_by',
|
||||
'limit',
|
||||
'legend_format',
|
||||
]),
|
||||
);
|
||||
},
|
||||
play: expectTimeSeriesAddOns,
|
||||
};
|
||||
|
||||
/** Picking a gauge defaults to avg over time and avg across series. */
|
||||
export const GaugeMetricDefaults: Story = {
|
||||
args: METRICS_EXPLORER_ARGS,
|
||||
parameters: { signoz: { route: metricsExplorerRoute } },
|
||||
play: async ({ canvasElement }) => {
|
||||
await selectMetric(canvasElement, 'container_cpu_utilization');
|
||||
|
||||
await expectFirstQuery(canvasElement, {
|
||||
aggregations: [
|
||||
expect.objectContaining({
|
||||
metricName: 'container_cpu_utilization',
|
||||
timeAggregation: 'avg',
|
||||
spaceAggregation: 'avg',
|
||||
}),
|
||||
],
|
||||
});
|
||||
},
|
||||
play: expectGaugeDefaults,
|
||||
};
|
||||
|
||||
/** Picking a histogram defaults to the p90 across series. */
|
||||
export const HistogramMetricDefaults: Story = {
|
||||
args: METRICS_EXPLORER_ARGS,
|
||||
parameters: { signoz: { route: metricsExplorerRoute } },
|
||||
play: async ({ canvasElement }) => {
|
||||
await selectMetric(canvasElement, 'signoz_latency_bucket');
|
||||
|
||||
await expectFirstQuery(canvasElement, {
|
||||
aggregations: [
|
||||
expect.objectContaining({
|
||||
metricName: 'signoz_latency_bucket',
|
||||
spaceAggregation: 'p90',
|
||||
}),
|
||||
],
|
||||
});
|
||||
},
|
||||
play: expectHistogramDefaults,
|
||||
};
|
||||
|
||||
/** A Value panel takes a single aggregation: a second one is not accepted. */
|
||||
@@ -148,22 +103,5 @@ export const ValuePanelTakesOneAggregation: Story = {
|
||||
parameters: {
|
||||
signoz: { route: routeWith(PANEL_EDITOR_PATH, initialQueriesMap.logs) },
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
await expectFirstQuery(canvasElement, {
|
||||
aggregations: [{ expression: 'count()' }],
|
||||
});
|
||||
|
||||
const { before, after } = appendToAggregation(
|
||||
canvasElement,
|
||||
', count_distinct(service.name)',
|
||||
);
|
||||
await expect(after).toBe(before);
|
||||
|
||||
await expectFirstQuery(canvasElement, {
|
||||
aggregations: [{ expression: 'count()' }],
|
||||
});
|
||||
await expect(
|
||||
payloadIn(canvasElement).queries[0].spec.aggregations,
|
||||
).toHaveLength(1);
|
||||
},
|
||||
play: expectSingleAggregation,
|
||||
};
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
* Do not hand-edit: regenerate instead.
|
||||
*/
|
||||
|
||||
import type { TransactionSpec } from '@codemirror/state';
|
||||
import { EditorView } from '@codemirror/view';
|
||||
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
|
||||
|
||||
@@ -134,6 +135,40 @@ export const selectMetric = async (
|
||||
await waitFor(() => expect(screen.queryByRole('listbox')).toBeNull());
|
||||
};
|
||||
|
||||
const aggregationEditor = (canvasElement: HTMLElement): EditorView => {
|
||||
const content = within(canvasElement)
|
||||
.getByTestId('query-aggregation-editor')
|
||||
.querySelector<HTMLElement>('.cm-content');
|
||||
const view = content ? EditorView.findFromDOM(content) : null;
|
||||
if (!view) {
|
||||
throw new Error('aggregation editor not mounted');
|
||||
}
|
||||
return view;
|
||||
};
|
||||
|
||||
const appendTo = (view: EditorView, text: string): TransactionSpec => ({
|
||||
changes: { from: view.state.doc.length, insert: text },
|
||||
selection: { anchor: view.state.doc.length + text.length },
|
||||
userEvent: 'input.type',
|
||||
});
|
||||
|
||||
/**
|
||||
* Waits until query `A`'s aggregation editor refuses `text`. The builder
|
||||
* applies a panel's limits one commit after mounting, which a fast static
|
||||
* build can beat. `state.update` runs the editor's filters without changing
|
||||
* the document.
|
||||
*/
|
||||
export const waitForAggregationLimit = async (
|
||||
canvasElement: HTMLElement,
|
||||
text: string,
|
||||
): Promise<void> => {
|
||||
await waitFor(() => {
|
||||
const view = aggregationEditor(canvasElement);
|
||||
const attempt = view.state.update(appendTo(view, text));
|
||||
return expect(attempt.newDoc.toString()).toBe(view.state.doc.toString());
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Appends `text` to query `A`'s aggregation editor and returns its document
|
||||
* before and after. Dispatched as a CodeMirror transaction: `userEvent.type`
|
||||
@@ -144,19 +179,9 @@ export const appendToAggregation = (
|
||||
canvasElement: HTMLElement,
|
||||
text: string,
|
||||
): { before: string; after: string } => {
|
||||
const content = within(canvasElement)
|
||||
.getByTestId('query-aggregation-editor')
|
||||
.querySelector<HTMLElement>('.cm-content');
|
||||
const view = content ? EditorView.findFromDOM(content) : null;
|
||||
if (!view) {
|
||||
throw new Error('aggregation editor not mounted');
|
||||
}
|
||||
const view = aggregationEditor(canvasElement);
|
||||
const before = view.state.doc.toString();
|
||||
view.dispatch({
|
||||
changes: { from: before.length, insert: text },
|
||||
selection: { anchor: before.length + text.length },
|
||||
userEvent: 'input.type',
|
||||
});
|
||||
view.dispatch(appendTo(view, text));
|
||||
// Read synchronously: the document is the editor's own verdict, before
|
||||
// React state catches up.
|
||||
return { before, after: view.state.doc.toString() };
|
||||
@@ -164,7 +189,6 @@ export const appendToAggregation = (
|
||||
|
||||
export const DEFAULT_ARGS: Partial<QueryBuilderProps> = {
|
||||
panelType: PANEL_TYPES.TIME_SERIES,
|
||||
version: 'v3',
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -15,7 +15,14 @@ import {
|
||||
ResolvedQueryBuilderField,
|
||||
resolveQueryBuilderField,
|
||||
} from '../../queryBuilderFields.utils';
|
||||
import { expectFirstQuery, payloadIn } from '../QueryBuilderV2.stories.mocks';
|
||||
import {
|
||||
addOnToggles,
|
||||
appendToAggregation,
|
||||
expectFirstQuery,
|
||||
payloadIn,
|
||||
selectMetric,
|
||||
waitForAggregationLimit,
|
||||
} from '../QueryBuilderV2.stories.mocks';
|
||||
|
||||
interface PlayContext {
|
||||
canvasElement: HTMLElement;
|
||||
@@ -197,3 +204,95 @@ export const hoverAddFunction = async ({
|
||||
|
||||
await hoverForLearnMore(button, 'Add new function');
|
||||
};
|
||||
|
||||
export const expectValuePanelAddOns = async ({
|
||||
canvasElement,
|
||||
}: PlayContext): Promise<void> => {
|
||||
await waitFor(() =>
|
||||
expect(addOnToggles(canvasElement)).toStrictEqual(['legend_format']),
|
||||
);
|
||||
};
|
||||
|
||||
export const expectTablePanelAddOns = async ({
|
||||
canvasElement,
|
||||
}: PlayContext): Promise<void> => {
|
||||
await waitFor(() =>
|
||||
expect(addOnToggles(canvasElement)).toStrictEqual([
|
||||
'having',
|
||||
'order_by',
|
||||
'limit',
|
||||
'legend_format',
|
||||
'reduce_to',
|
||||
]),
|
||||
);
|
||||
};
|
||||
|
||||
export const expectTimeSeriesAddOns = async ({
|
||||
canvasElement,
|
||||
}: PlayContext): Promise<void> => {
|
||||
await waitFor(() =>
|
||||
expect(addOnToggles(canvasElement)).toStrictEqual([
|
||||
'group_by',
|
||||
'having',
|
||||
'order_by',
|
||||
'limit',
|
||||
'legend_format',
|
||||
]),
|
||||
);
|
||||
};
|
||||
|
||||
export const expectGaugeDefaults = async ({
|
||||
canvasElement,
|
||||
}: PlayContext): Promise<void> => {
|
||||
await selectMetric(canvasElement, 'container_cpu_utilization');
|
||||
|
||||
await expectFirstQuery(canvasElement, {
|
||||
aggregations: [
|
||||
expect.objectContaining({
|
||||
metricName: 'container_cpu_utilization',
|
||||
timeAggregation: 'avg',
|
||||
spaceAggregation: 'avg',
|
||||
}),
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
export const expectHistogramDefaults = async ({
|
||||
canvasElement,
|
||||
}: PlayContext): Promise<void> => {
|
||||
await selectMetric(canvasElement, 'signoz_latency_bucket');
|
||||
|
||||
await expectFirstQuery(canvasElement, {
|
||||
aggregations: [
|
||||
expect.objectContaining({
|
||||
metricName: 'signoz_latency_bucket',
|
||||
spaceAggregation: 'p90',
|
||||
}),
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
const SECOND_AGGREGATION = ', count_distinct(service.name)';
|
||||
|
||||
export const expectSingleAggregation = async ({
|
||||
canvasElement,
|
||||
}: PlayContext): Promise<void> => {
|
||||
await expectFirstQuery(canvasElement, {
|
||||
aggregations: [{ expression: 'count()' }],
|
||||
});
|
||||
|
||||
await waitForAggregationLimit(canvasElement, SECOND_AGGREGATION);
|
||||
|
||||
const { before, after } = appendToAggregation(
|
||||
canvasElement,
|
||||
SECOND_AGGREGATION,
|
||||
);
|
||||
await expect(after).toBe(before);
|
||||
|
||||
await expectFirstQuery(canvasElement, {
|
||||
aggregations: [{ expression: 'count()' }],
|
||||
});
|
||||
await expect(
|
||||
payloadIn(canvasElement).queries[0].spec.aggregations,
|
||||
).toHaveLength(1);
|
||||
};
|
||||
|
||||
@@ -9,11 +9,6 @@ import {
|
||||
QUERY_BUILDER_FUNCTIONS,
|
||||
} from 'constants/antlrQueryConstants';
|
||||
import { getOperatorValue } from 'container/QueryBuilder/filters/QueryBuilderSearchV2/utils';
|
||||
import {
|
||||
getActiveBuilder,
|
||||
getBuilderSlotKeyForQueryType,
|
||||
isBuilderQueryType,
|
||||
} from 'lib/query/builderSlot';
|
||||
import FilterQueryLexer from 'parser/FilterQueryLexer';
|
||||
import FilterQueryParser, {
|
||||
AndExpressionContext,
|
||||
@@ -29,7 +24,6 @@ import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteRe
|
||||
import {
|
||||
Having,
|
||||
IBuilderQuery,
|
||||
Query,
|
||||
TagFilter,
|
||||
TagFilterItem,
|
||||
} from 'types/api/queryBuilder/queryBuilderData';
|
||||
@@ -1032,57 +1026,3 @@ export function getQueryLabelWithAggregation(
|
||||
|
||||
return labels;
|
||||
}
|
||||
|
||||
export const adjustQueryForV5 = (currentQuery: Query): Query => {
|
||||
if (isBuilderQueryType(currentQuery.queryType)) {
|
||||
const activeBuilder = getActiveBuilder(currentQuery);
|
||||
const newQueryData = activeBuilder.queryData.map((query) => {
|
||||
const aggregations = query.aggregations?.map((aggregation) => {
|
||||
if (query.dataSource === DataSource.METRICS) {
|
||||
const metricAggregation = aggregation as MetricAggregation;
|
||||
return {
|
||||
...aggregation,
|
||||
metricName:
|
||||
metricAggregation.metricName || query.aggregateAttribute?.key || '',
|
||||
timeAggregation:
|
||||
metricAggregation.timeAggregation || query.timeAggregation || '',
|
||||
spaceAggregation:
|
||||
metricAggregation.spaceAggregation || query.spaceAggregation || '',
|
||||
reduceTo: metricAggregation.reduceTo || query.reduceTo || 'avg',
|
||||
};
|
||||
}
|
||||
return aggregation;
|
||||
});
|
||||
|
||||
const {
|
||||
aggregateAttribute: _aggregateAttribute,
|
||||
aggregateOperator: _aggregateOperator,
|
||||
timeAggregation: _timeAggregation,
|
||||
spaceAggregation: _spaceAggregation,
|
||||
reduceTo: _reduceTo,
|
||||
filters: _filters,
|
||||
...retainedQuery
|
||||
} = query;
|
||||
|
||||
const newAggregations =
|
||||
query.dataSource === DataSource.METRICS
|
||||
? (aggregations as MetricAggregation[])
|
||||
: (aggregations as (TraceAggregation | LogAggregation)[]);
|
||||
|
||||
return {
|
||||
...retainedQuery,
|
||||
aggregations: newAggregations,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
...currentQuery,
|
||||
[getBuilderSlotKeyForQueryType(currentQuery.queryType)]: {
|
||||
...activeBuilder,
|
||||
queryData: newQueryData,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return currentQuery;
|
||||
};
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { useMemo } from 'react';
|
||||
import { TelemetrytypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { FieldValuesConfig } from 'api/querySuggestions/types';
|
||||
import { QUICK_FILTER_SOURCE_TO_SIGNAL } from 'components/QuickFilters/constants';
|
||||
import {
|
||||
QUICK_FILTER_SOURCE_TO_SIGNAL,
|
||||
QUICK_FILTER_SOURCE_TO_SOURCE,
|
||||
} from 'components/QuickFilters/constants';
|
||||
import {
|
||||
IQuickFiltersConfig,
|
||||
QuickFiltersSource,
|
||||
@@ -27,12 +29,6 @@ interface UseFieldValuesReturn {
|
||||
isFetching: boolean;
|
||||
}
|
||||
|
||||
const QUICK_FILTERS_SOURCE_TO_SOURCE: Partial<
|
||||
Record<QuickFiltersSource, TelemetrytypesSourceDTO>
|
||||
> = {
|
||||
[QuickFiltersSource.METER_EXPLORER]: TelemetrytypesSourceDTO.meter,
|
||||
};
|
||||
|
||||
export function useFieldValues({
|
||||
filter,
|
||||
searchText,
|
||||
@@ -65,7 +61,7 @@ export function useFieldValues({
|
||||
searchText,
|
||||
existingQuery,
|
||||
metricNamespace,
|
||||
source: QUICK_FILTERS_SOURCE_TO_SOURCE[quickFilterSource],
|
||||
source: QUICK_FILTER_SOURCE_TO_SOURCE[quickFilterSource],
|
||||
startUnixMilli,
|
||||
// This field does not affect the backend but I wanted to keep it here
|
||||
// in case we add the support in the future
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useMemo } from 'react';
|
||||
import { Button, Skeleton } from 'antd';
|
||||
import {
|
||||
QuickfiltertypesSourceDTO,
|
||||
TelemetrytypesSourceDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { QuickfiltertypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { FieldKeysConfig } from 'api/querySuggestions/types';
|
||||
import OverlayScrollbar from 'components/OverlayScrollbar/OverlayScrollbar';
|
||||
import { QUICK_FILTER_SOURCE_TO_SIGNAL } from 'components/QuickFilters/constants';
|
||||
import {
|
||||
QUICK_FILTER_SOURCE_TO_SIGNAL,
|
||||
QUICK_FILTER_SOURCE_TO_SOURCE,
|
||||
} from 'components/QuickFilters/constants';
|
||||
import { buildCompositeKey } from 'container/OptionsMenu/utils';
|
||||
import { useFieldKeysSuggestion } from 'hooks/querySuggestions/useFieldKeysSuggestion';
|
||||
import {
|
||||
@@ -43,8 +43,6 @@ function OtherFilters({
|
||||
addedFilters: TelemetryFieldKey[];
|
||||
setAddedFilters: React.Dispatch<React.SetStateAction<TelemetryFieldKey[]>>;
|
||||
}): JSX.Element {
|
||||
const isMeterDataSource =
|
||||
savedFiltersSource === QuickfiltertypesSourceDTO.meter;
|
||||
const isAIObservability =
|
||||
savedFiltersSource === QuickfiltertypesSourceDTO.ai_observability;
|
||||
|
||||
@@ -57,7 +55,7 @@ function OtherFilters({
|
||||
: {
|
||||
searchText: inputValue,
|
||||
signal: QUICK_FILTER_SOURCE_TO_SIGNAL[savedFiltersSource],
|
||||
source: isMeterDataSource ? TelemetrytypesSourceDTO.meter : undefined,
|
||||
source: QUICK_FILTER_SOURCE_TO_SOURCE[savedFiltersSource],
|
||||
};
|
||||
|
||||
const { data: fetchedKeys, isFetching } = useFieldKeysSuggestion(
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { TelemetrytypesSignalDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
TelemetrytypesSignalDTO,
|
||||
TelemetrytypesSourceDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import { QuickFiltersSource } from './types';
|
||||
|
||||
@@ -13,4 +16,19 @@ export const QUICK_FILTER_SOURCE_TO_SIGNAL: Record<
|
||||
[QuickFiltersSource.AI_OBSERVABILITY]: TelemetrytypesSignalDTO.traces,
|
||||
[QuickFiltersSource.METER_EXPLORER]: TelemetrytypesSignalDTO.metrics,
|
||||
[QuickFiltersSource.INFRA_MONITORING]: TelemetrytypesSignalDTO.metrics,
|
||||
[QuickFiltersSource.AUDIT_LOGS]: TelemetrytypesSignalDTO.logs,
|
||||
};
|
||||
|
||||
export const QUICK_FILTER_SOURCE_TO_SOURCE: Record<
|
||||
QuickFiltersSource,
|
||||
TelemetrytypesSourceDTO | undefined
|
||||
> = {
|
||||
[QuickFiltersSource.LOGS_EXPLORER]: undefined,
|
||||
[QuickFiltersSource.TRACES_EXPLORER]: undefined,
|
||||
[QuickFiltersSource.EXCEPTIONS]: undefined,
|
||||
[QuickFiltersSource.API_MONITORING]: undefined,
|
||||
[QuickFiltersSource.AI_OBSERVABILITY]: undefined,
|
||||
[QuickFiltersSource.METER_EXPLORER]: TelemetrytypesSourceDTO.meter,
|
||||
[QuickFiltersSource.INFRA_MONITORING]: undefined,
|
||||
[QuickFiltersSource.AUDIT_LOGS]: TelemetrytypesSourceDTO.audit,
|
||||
};
|
||||
|
||||
@@ -60,6 +60,7 @@ export const QuickFiltersSource = {
|
||||
API_MONITORING: QuickfiltertypesSourceDTO.api_monitoring,
|
||||
METER_EXPLORER: QuickfiltertypesSourceDTO.meter,
|
||||
AI_OBSERVABILITY: QuickfiltertypesSourceDTO.ai_observability,
|
||||
AUDIT_LOGS: QuickfiltertypesSourceDTO.audit,
|
||||
/** No saved filter list: renders `config` as given. */
|
||||
INFRA_MONITORING: 'infra-monitoring',
|
||||
} as const;
|
||||
|
||||
@@ -48,10 +48,8 @@ export const getFilterConfig = (
|
||||
({
|
||||
type: getFilterType(att),
|
||||
title: getFilterName(att.name),
|
||||
// The type mapping below exists only for the old v3 attribute-values fetch
|
||||
// (useCheckboxFilterValues), the sole reader of attributeKey.dataType/type.
|
||||
// Once the values fetch moves to fields/values, remove this and reduce
|
||||
// attributeKey to { id, key }.
|
||||
// TODO: nothing reads dataType/type; reduce attributeKey to { id, key }
|
||||
// once the TagFilterItem.key readers are checked.
|
||||
attributeKey: {
|
||||
id: att.name,
|
||||
key: att.name,
|
||||
|
||||
@@ -12,8 +12,6 @@ export const INVITE_MEMBERS_HASH = '#invite-team-members';
|
||||
|
||||
export const DASHBOARD_TIME_IN_DURATION = 'refreshInterval';
|
||||
|
||||
export const DEFAULT_ENTITY_VERSION = 'v3';
|
||||
export const ENTITY_VERSION_V4 = 'v4';
|
||||
export const ENTITY_VERSION_V5 = 'v5';
|
||||
|
||||
export const SIGNOZ_ADMIN_EMAIL = 'admin@signoz.cloud';
|
||||
|
||||
@@ -48,4 +48,5 @@ export enum LOCALSTORAGE {
|
||||
ALERT_RULES_LIST_VIEWS = 'ALERT_RULES_LIST_VIEWS',
|
||||
DASHBOARD_V2_PANEL_COLUMN_WIDTHS = 'DASHBOARD_V2_PANEL_COLUMN_WIDTHS',
|
||||
LLM_ATTRIBUTE_MAPPING_TEST_SPAN = 'LLM_ATTRIBUTE_MAPPING_TEST_SPAN',
|
||||
AUDIT_LOGS_OPTIONS = 'AUDIT_LOGS_OPTIONS',
|
||||
}
|
||||
|
||||
@@ -5,15 +5,12 @@ import {
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { createIdFromObjectFields } from 'lib/createIdFromObjectFields';
|
||||
import { createNewBuilderItemName } from 'lib/newQueryBuilder/createNewBuilderItemName';
|
||||
import { IAttributeValuesResponse } from 'types/api/queryBuilder/getAttributesValues';
|
||||
import {
|
||||
AutocompleteType,
|
||||
BaseAutocompleteData,
|
||||
DataTypes,
|
||||
LocalDataType,
|
||||
} from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import {
|
||||
HavingForm,
|
||||
IBuilderFormula,
|
||||
IBuilderQuery,
|
||||
IBuilderTraceOperator,
|
||||
@@ -57,19 +54,11 @@ export const MAX_QUERIES = 26;
|
||||
export const TRACE_OPERATOR_QUERY_NAME = 'Trace Operator';
|
||||
|
||||
export const idDivider = '--';
|
||||
export const selectValueDivider = '__';
|
||||
|
||||
export const baseAutoCompleteIdKeysOrder: (keyof Omit<
|
||||
BaseAutocompleteData,
|
||||
'id' | 'isIndexed'
|
||||
>)[] = ['key', 'dataType', 'type'];
|
||||
|
||||
export const autocompleteType: Record<AutocompleteType, AutocompleteType> = {
|
||||
resource: 'resource',
|
||||
tag: 'tag',
|
||||
'': '',
|
||||
};
|
||||
|
||||
export const formulasNames: string[] = Array.from(
|
||||
Array(MAX_FORMULAS),
|
||||
(_, i) => `F${i + 1}`,
|
||||
@@ -77,12 +66,6 @@ export const formulasNames: string[] = Array.from(
|
||||
const alpha: number[] = Array.from(Array(MAX_QUERIES), (_, i) => i + 65);
|
||||
export const alphabet: string[] = alpha.map((str) => String.fromCharCode(str));
|
||||
|
||||
export enum QueryBuilderKeys {
|
||||
GET_AGGREGATE_ATTRIBUTE = 'GET_AGGREGATE_ATTRIBUTE',
|
||||
GET_AGGREGATE_KEYS = 'GET_AGGREGATE_KEYS',
|
||||
GET_ATTRIBUTE_SUGGESTIONS = 'GET_ATTRIBUTE_SUGGESTIONS',
|
||||
}
|
||||
|
||||
export const mapOfOperators = {
|
||||
metrics: metricAggregateOperatorOptions,
|
||||
logs: logsAggregateOperatorOptions,
|
||||
@@ -110,12 +93,6 @@ export const REDUCE_TO_VALUES: SelectOption<ReduceOperators, string>[] = [
|
||||
{ value: ReduceOperators.MIN, label: 'Min of values in timeframe' },
|
||||
];
|
||||
|
||||
export const initialHavingValues: HavingForm = {
|
||||
columnName: '',
|
||||
op: '',
|
||||
value: [],
|
||||
};
|
||||
|
||||
export const initialAutocompleteData: BaseAutocompleteData = {
|
||||
id: createIdFromObjectFields(
|
||||
{ dataType: null, key: '', type: null },
|
||||
@@ -525,17 +502,6 @@ export const OPERATORS_CONFIG = {
|
||||
],
|
||||
};
|
||||
|
||||
export const HAVING_OPERATORS: string[] = [
|
||||
OPERATORS['='],
|
||||
OPERATORS['!='],
|
||||
OPERATORS.IN,
|
||||
OPERATORS.NIN,
|
||||
OPERATORS['>='],
|
||||
OPERATORS['>'],
|
||||
OPERATORS['<='],
|
||||
OPERATORS['<'],
|
||||
];
|
||||
|
||||
export enum PanelDisplay {
|
||||
TIME_SERIES = 'Time Series',
|
||||
VALUE = 'Number',
|
||||
@@ -546,21 +512,6 @@ export enum PanelDisplay {
|
||||
HISTOGRAM = 'Histogram',
|
||||
}
|
||||
|
||||
export const DATA_TYPE_VS_ATTRIBUTE_VALUES_KEY: Record<
|
||||
DataTypes,
|
||||
keyof IAttributeValuesResponse
|
||||
> = {
|
||||
[DataTypes.String]: 'stringAttributeValues',
|
||||
[DataTypes.Float64]: 'numberAttributeValues',
|
||||
[DataTypes.Int64]: 'numberAttributeValues',
|
||||
[DataTypes.bool]: 'boolAttributeValues',
|
||||
[DataTypes.ArrayFloat64]: 'numberAttributeValues',
|
||||
[DataTypes.ArrayInt64]: 'numberAttributeValues',
|
||||
[DataTypes.ArrayString]: 'stringAttributeValues',
|
||||
[DataTypes.ArrayBool]: 'boolAttributeValues',
|
||||
[DataTypes.EMPTY]: 'stringAttributeValues',
|
||||
};
|
||||
|
||||
export const listViewInitialLogQuery: Query = {
|
||||
...initialQueriesMap.logs,
|
||||
builder: {
|
||||
|
||||
@@ -12,6 +12,7 @@ export const REACT_QUERY_KEY = {
|
||||
GET_PUBLIC_DASHBOARD_WIDGET_DATA: 'GET_PUBLIC_DASHBOARD_WIDGET_DATA',
|
||||
GET_ALL_LICENCES: 'GET_ALL_LICENCES',
|
||||
GET_QUERY_RANGE: 'GET_QUERY_RANGE',
|
||||
GET_AUDIT_LOGS: 'GET_AUDIT_LOGS',
|
||||
GET_ALL_DASHBOARDS: 'GET_ALL_DASHBOARDS',
|
||||
GET_TRIGGERED_ALERTS: 'GET_TRIGGERED_ALERTS',
|
||||
DASHBOARD_BY_ID: 'DASHBOARD_BY_ID',
|
||||
|
||||
@@ -2,10 +2,4 @@ import { TRACE_OPERATOR_QUERY_NAME } from './queryBuilder';
|
||||
|
||||
export const FORMULA_REGEXP = /F\d+/;
|
||||
|
||||
export const HAVING_FILTER_REGEXP = /^[-\d.,\s]+$/;
|
||||
|
||||
export const TYPE_ADDON_REGEXP = /_(.+)/;
|
||||
|
||||
export const SPLIT_FIRST_UNDERSCORE = /(?<!^)_/;
|
||||
|
||||
export const TRACE_OPERATOR_REGEXP = new RegExp(TRACE_OPERATOR_QUERY_NAME);
|
||||
|
||||
@@ -41,6 +41,7 @@ const ROUTES = {
|
||||
LOGS_PIPELINES: '/logs/pipelines',
|
||||
PASSWORD_RESET: '/password-reset',
|
||||
LIST_LICENSES: '/licenses',
|
||||
AUDIT_LOGS: '/audit-logs',
|
||||
LOGS_INDEX_FIELDS: '/logs-explorer/index-fields',
|
||||
TRACE_EXPLORER: '/trace-explorer',
|
||||
BILLING: '/settings/billing',
|
||||
|
||||
@@ -94,21 +94,9 @@
|
||||
&__text {
|
||||
color: var(--l2-foreground);
|
||||
line-height: 18px;
|
||||
.bold-text {
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
}
|
||||
&__button-wrapper {
|
||||
margin-top: 12px;
|
||||
.configure-alert-rule-button {
|
||||
padding: 8px 16px;
|
||||
border-radius: 2px;
|
||||
background: var(--l3-background);
|
||||
border-width: 0;
|
||||
color: var(--l1-foreground);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { useMemo } from 'react';
|
||||
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
|
||||
import ErrorContent from 'components/ErrorModal/components/ErrorContent';
|
||||
import { useGetAlertRuleDetailsTopContributors } from 'pages/AlertDetails/hooks';
|
||||
import { labelsArrayToObject } from 'container/AlertHistory/utils/labelAdapters';
|
||||
import DataStateRenderer from 'periscope/components/DataStateRenderer/DataStateRenderer';
|
||||
@@ -13,8 +15,9 @@ type TopContributorsRendererProps = {
|
||||
function TopContributorsRenderer({
|
||||
totalCurrentTriggers,
|
||||
}: TopContributorsRendererProps): JSX.Element {
|
||||
const { isLoading, isRefetching, isError, data, isValidRuleId, ruleId } =
|
||||
const { isLoading, isRefetching, data, error, isValidRuleId, ruleId } =
|
||||
useGetAlertRuleDetailsTopContributors();
|
||||
const apiError = useMemo(() => convertToApiError(error), [error]);
|
||||
|
||||
// TODO(shaheer): render the DataStateRenderer inside the TopContributorsCard, it should display the title and view all
|
||||
const adaptedData = useMemo((): AlertRuleTopContributors[] | null => {
|
||||
@@ -31,11 +34,19 @@ function TopContributorsRenderer({
|
||||
}));
|
||||
}, [data?.data]);
|
||||
|
||||
if (apiError) {
|
||||
return (
|
||||
<div data-testid="top-contributors-error">
|
||||
<ErrorContent error={apiError} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<DataStateRenderer
|
||||
isLoading={isLoading}
|
||||
isRefetching={isRefetching}
|
||||
isError={isError || !isValidRuleId || !ruleId}
|
||||
isError={!isValidRuleId || !ruleId}
|
||||
data={adaptedData}
|
||||
>
|
||||
{(topContributorsData): JSX.Element => (
|
||||
|
||||
@@ -19,14 +19,4 @@
|
||||
line-height: 18px;
|
||||
letter-spacing: -0.06px;
|
||||
}
|
||||
&__chart {
|
||||
.chart-placeholder {
|
||||
width: 100%;
|
||||
height: 52px;
|
||||
background: color-mix(in srgb, var(--l1-foreground) 12%, transparent);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import ROUTES from 'constants/routes';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { render, screen, within } from 'tests/test-utils';
|
||||
|
||||
import TopContributorsRenderer from '../Statistics/TopContributorsRenderer/TopContributorsRenderer';
|
||||
|
||||
const RULE_ID = 'rule-1';
|
||||
const route = `${ROUTES.ALERT_HISTORY}?ruleId=${RULE_ID}&relativeTime=6h`;
|
||||
|
||||
const failWith = (status: number, code: string): ReturnType<typeof rest.get> =>
|
||||
rest.get(
|
||||
`http://localhost/api/v2/rules/${RULE_ID}/history/top_contributors`,
|
||||
(_req, res, ctx) =>
|
||||
res(
|
||||
ctx.status(status),
|
||||
ctx.json({ status: 'error', error: { code, message: 'refused' } }),
|
||||
),
|
||||
);
|
||||
|
||||
describe('TopContributorsRenderer', () => {
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[500, 'internal'],
|
||||
[403, 'authz_forbidden'],
|
||||
])('shows the generic error for a %i', async (status, code) => {
|
||||
server.use(failWith(status, code));
|
||||
render(<TopContributorsRenderer totalCurrentTriggers={0} />, undefined, {
|
||||
initialRoute: route,
|
||||
});
|
||||
|
||||
const error = await screen.findByTestId('top-contributors-error');
|
||||
expect(within(error).getByText(code)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -62,7 +62,6 @@ function DomainList(): JSX.Element {
|
||||
const { handleChangeQueryData } = useQueryOperations({
|
||||
index: 0,
|
||||
query,
|
||||
entityVersion: '',
|
||||
});
|
||||
|
||||
const compositeData = useGetCompositeQueryParam();
|
||||
|
||||
@@ -100,33 +100,6 @@ describe('TopErrors', () => {
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// Mock V4 API endpoint for dropdown data
|
||||
server.use(
|
||||
rest.post('*/api/v1/query_range', (_req, res, ctx) =>
|
||||
res(
|
||||
ctx.status(200),
|
||||
ctx.json({
|
||||
payload: {
|
||||
data: {
|
||||
result: [
|
||||
{
|
||||
table: {
|
||||
rows: [
|
||||
{
|
||||
http_url: '/api/test',
|
||||
A: 100,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('renders component correctly', async () => {
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Input } from '@signozhq/ui/input';
|
||||
import { Button, Select, Tooltip } from 'antd';
|
||||
import AuthZSelect from 'lib/authz/components/AuthZSelect/AuthZSelect';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { CircleX, Trash } from '@signozhq/icons';
|
||||
import { useAppContext } from 'providers/App/App';
|
||||
import NotificationChannelsNotFound from 'components/NotificationChannelsNotFound/NotificationChannelsNotFound';
|
||||
|
||||
import { useCreateAlertState } from '../context';
|
||||
import { AlertThresholdOperator } from '../context/types';
|
||||
import { normalizeOperator } from '../utils';
|
||||
import { ThresholdItemProps } from './types';
|
||||
import { NotificationChannelsNotFoundContent } from './utils';
|
||||
import { useAlertRuleChannelAccess } from './useAlertRuleChannelAccess';
|
||||
|
||||
function ThresholdItem({
|
||||
threshold,
|
||||
@@ -23,8 +24,13 @@ function ThresholdItem({
|
||||
isLoadingChannels,
|
||||
isAnomaly = false,
|
||||
}: ThresholdItemProps): JSX.Element {
|
||||
const { user } = useAppContext();
|
||||
const { thresholdState, notificationSettings } = useCreateAlertState();
|
||||
const { options: channelOptions, onPickerVisibleChange } =
|
||||
useAlertRuleChannelAccess(
|
||||
threshold,
|
||||
channels,
|
||||
`threshold-${threshold.label}-channel-option`,
|
||||
);
|
||||
const [showRecoveryThreshold, setShowRecoveryThreshold] = useState(false);
|
||||
|
||||
const yAxisUnitSelect = useMemo(() => {
|
||||
@@ -179,19 +185,16 @@ function ThresholdItem({
|
||||
>
|
||||
send to
|
||||
</Typography>
|
||||
<Select
|
||||
<AuthZSelect
|
||||
value={threshold.channels}
|
||||
onChange={(value): void =>
|
||||
updateThreshold(threshold.id, 'channels', value)
|
||||
}
|
||||
data-testid="threshold-notification-channel-select"
|
||||
popupMatchSelectWidth={false}
|
||||
style={{ width: 350 }}
|
||||
options={channels.map((channel) => ({
|
||||
value: channel.name,
|
||||
label: channel.name,
|
||||
'data-testid': `threshold-notification-channel-option-${threshold.label}`,
|
||||
}))}
|
||||
mode="multiple"
|
||||
options={channelOptions}
|
||||
onDropdownVisibleChange={onPickerVisibleChange}
|
||||
placeholder="Select notification channels"
|
||||
showSearch
|
||||
maxTagCount={2}
|
||||
@@ -199,16 +202,10 @@ function ThresholdItem({
|
||||
`+${omittedValues.length} more`
|
||||
}
|
||||
maxTagTextLength={10}
|
||||
filterOption={(input, option): boolean =>
|
||||
option?.label?.toLowerCase().includes(input.toLowerCase()) || false
|
||||
}
|
||||
status={isErrorChannels ? 'error' : undefined}
|
||||
disabled={isLoadingChannels}
|
||||
notFoundContent={
|
||||
<NotificationChannelsNotFoundContent
|
||||
user={user}
|
||||
refreshChannels={refreshChannels}
|
||||
/>
|
||||
<NotificationChannelsNotFound onRefresh={refreshChannels} />
|
||||
}
|
||||
/>
|
||||
</>
|
||||
|
||||
@@ -102,15 +102,6 @@ jest.mock('hooks/notificationChannels/useChannelOptions', () => ({
|
||||
})),
|
||||
}));
|
||||
|
||||
// Mock alert format categories
|
||||
jest.mock('constants/formats/alertFormatCategories', () => ({
|
||||
getCategoryByOptionId: jest.fn(() => ({ name: 'bytes' })),
|
||||
getCategorySelectOptionByName: jest.fn(() => [
|
||||
{ label: 'Bytes', value: 'bytes' },
|
||||
{ label: 'KB', value: 'kb' },
|
||||
]),
|
||||
}));
|
||||
|
||||
jest.mock('container/CreateAlert/utils', () => ({
|
||||
...jest.requireActual('container/CreateAlert/utils'),
|
||||
}));
|
||||
|
||||
@@ -1,15 +1,33 @@
|
||||
import { fireEvent, render, screen } from 'tests/test-utils';
|
||||
import { fireEvent, render, screen, userEvent, within } from 'tests/test-utils';
|
||||
import type { DefaultOptionType } from 'antd/es/select';
|
||||
import { INITIAL_ALERT_THRESHOLD_STATE } from 'container/CreateAlert/context/constants';
|
||||
import type { Threshold } from 'container/CreateAlert/context/types';
|
||||
import { createMockAlertContextState } from 'container/CreateAlert/EvaluationSettings/__tests__/testUtils';
|
||||
import { getAppContextMockState } from 'container/RoutingPolicies/__tests__/testUtils';
|
||||
import * as appHooks from 'providers/App/App';
|
||||
import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
|
||||
|
||||
import {
|
||||
buildNotificationChannelAttachPermission,
|
||||
buildNotificationChannelDetachPermission,
|
||||
NotificationChannelCreatePermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/notification-channel.permissions';
|
||||
import { buildRuleDetachPermission } from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
|
||||
import type { UseAuthZResult } from 'lib/authz/hooks/useAuthZ/types';
|
||||
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
|
||||
import { formatPermission } from 'lib/authz/hooks/useAuthZ/utils';
|
||||
import {
|
||||
denyPermissions,
|
||||
mockUseAuthZDeny,
|
||||
} from 'lib/authz/utils/authz-test-utils';
|
||||
|
||||
import * as context from '../../context';
|
||||
import ThresholdItem from '../ThresholdItem';
|
||||
import { ThresholdItemProps } from '../types';
|
||||
|
||||
jest.spyOn(appHooks, 'useAppContext').mockReturnValue(getAppContextMockState());
|
||||
jest.mock('lib/authz/hooks/useAuthZ/useAuthZ');
|
||||
|
||||
beforeEach(() => {
|
||||
denyPermissions();
|
||||
});
|
||||
|
||||
jest.mock('uplot', () => {
|
||||
const paths = {
|
||||
@@ -372,4 +390,177 @@ describe('ThresholdItem', () => {
|
||||
const channelSelectors = screen.getAllByRole('combobox');
|
||||
expect(channelSelectors).toHaveLength(2); // Should have both unit and channel selectors
|
||||
});
|
||||
|
||||
describe('authz', () => {
|
||||
const RULE_ID = 'rule-1';
|
||||
const option = (
|
||||
channelId: string,
|
||||
label: string = TEST_CONSTANTS.CRITICAL_LABEL,
|
||||
): Promise<HTMLElement> =>
|
||||
screen.findByTestId(`threshold-${label}-channel-option-${channelId}`);
|
||||
const openPicker = async (): Promise<void> => {
|
||||
await userEvent
|
||||
.setup()
|
||||
.click(
|
||||
within(
|
||||
screen.getByTestId('threshold-notification-channel-select'),
|
||||
).getByRole('combobox'),
|
||||
);
|
||||
};
|
||||
const withChannels = (
|
||||
channels: string[],
|
||||
overrides: Partial<Threshold> = {},
|
||||
): Threshold => ({ ...mockThreshold, channels, ...overrides });
|
||||
const editing = (
|
||||
savedChannelNames: string[],
|
||||
thresholds: Threshold[] = [mockThreshold],
|
||||
): void => {
|
||||
jest.spyOn(context, 'useCreateAlertState').mockReturnValue(
|
||||
createMockAlertContextState({
|
||||
isEditMode: true,
|
||||
ruleId: RULE_ID,
|
||||
savedChannelNames,
|
||||
thresholdState: { ...INITIAL_ALERT_THRESHOLD_STATE, thresholds },
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
jest.spyOn(context, 'useCreateAlertState').mockReturnValue(
|
||||
createMockAlertContextState({
|
||||
setThresholdState: mockSetThresholdState,
|
||||
setAlertState: mockSetAlertState,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('disables a channel the user cannot attach, naming the permission', async () => {
|
||||
const attach = buildNotificationChannelAttachPermission(
|
||||
TEST_CONSTANTS.CHANNEL_2,
|
||||
);
|
||||
denyPermissions(attach);
|
||||
renderThresholdItem();
|
||||
await openPicker();
|
||||
|
||||
const denied = await option(TEST_CONSTANTS.CHANNEL_2);
|
||||
expect(denied).toHaveAttribute('aria-disabled', 'true');
|
||||
expect(denied).toHaveAttribute(
|
||||
'aria-description',
|
||||
expect.stringContaining(formatPermission(attach)),
|
||||
);
|
||||
await expect(option(TEST_CONSTANTS.CHANNEL_3)).resolves.toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'false',
|
||||
);
|
||||
});
|
||||
|
||||
it('locks a saved channel the user cannot detach', async () => {
|
||||
const detach = buildNotificationChannelDetachPermission(
|
||||
TEST_CONSTANTS.CHANNEL_1,
|
||||
);
|
||||
denyPermissions(detach);
|
||||
const critical = withChannels([TEST_CONSTANTS.EMAIL_CHANNEL_NAME]);
|
||||
editing([TEST_CONSTANTS.EMAIL_CHANNEL_NAME], [critical]);
|
||||
renderThresholdItem({ threshold: critical });
|
||||
await openPicker();
|
||||
|
||||
const saved = await option(TEST_CONSTANTS.CHANNEL_1);
|
||||
expect(saved).toHaveAttribute('aria-disabled', 'true');
|
||||
expect(saved).toHaveAttribute(
|
||||
'aria-description',
|
||||
expect.stringContaining(formatPermission(detach)),
|
||||
);
|
||||
});
|
||||
|
||||
describe('with several thresholds', () => {
|
||||
const EMAIL = TEST_CONSTANTS.EMAIL_CHANNEL_NAME;
|
||||
const warningId = 'test-threshold-2';
|
||||
|
||||
beforeEach(() => {
|
||||
denyPermissions(
|
||||
buildNotificationChannelDetachPermission(TEST_CONSTANTS.CHANNEL_1),
|
||||
buildRuleDetachPermission(RULE_ID),
|
||||
);
|
||||
});
|
||||
|
||||
it('lets a saved channel be removed while another threshold still has it', async () => {
|
||||
const critical = withChannels([EMAIL]);
|
||||
const warning = withChannels([EMAIL], {
|
||||
id: warningId,
|
||||
label: TEST_CONSTANTS.WARNING_LABEL,
|
||||
});
|
||||
editing([EMAIL], [critical, warning]);
|
||||
renderThresholdItem({ threshold: critical });
|
||||
await openPicker();
|
||||
|
||||
await expect(option(TEST_CONSTANTS.CHANNEL_1)).resolves.toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'false',
|
||||
);
|
||||
});
|
||||
|
||||
it('lets a channel saved on one threshold be added to another', async () => {
|
||||
const critical = withChannels([EMAIL]);
|
||||
const warning = withChannels([], {
|
||||
id: warningId,
|
||||
label: TEST_CONSTANTS.WARNING_LABEL,
|
||||
});
|
||||
editing([EMAIL], [critical, warning]);
|
||||
renderThresholdItem({ threshold: warning });
|
||||
await openPicker();
|
||||
|
||||
await expect(
|
||||
option(TEST_CONSTANTS.CHANNEL_1, TEST_CONSTANTS.WARNING_LABEL),
|
||||
).resolves.toHaveAttribute('aria-disabled', 'false');
|
||||
});
|
||||
|
||||
it('lets a saved channel that no threshold has anymore be added back', async () => {
|
||||
const critical = withChannels([]);
|
||||
editing([EMAIL], [critical]);
|
||||
renderThresholdItem({ threshold: critical });
|
||||
await openPicker();
|
||||
|
||||
await expect(option(TEST_CONSTANTS.CHANNEL_1)).resolves.toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'false',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps channels disabled while their check is pending', async () => {
|
||||
jest.mocked(useAuthZ).mockReturnValue({
|
||||
...mockUseAuthZDeny()([]),
|
||||
isLoading: true,
|
||||
permissions: null,
|
||||
} as UseAuthZResult);
|
||||
renderThresholdItem();
|
||||
await openPicker();
|
||||
|
||||
const pending = await option(TEST_CONSTANTS.CHANNEL_2);
|
||||
expect(pending).toHaveAttribute('aria-disabled', 'true');
|
||||
expect(pending).toHaveAttribute('aria-description', 'Checking permissions');
|
||||
});
|
||||
|
||||
it('offers to create a channel with notification-channel:create', async () => {
|
||||
renderThresholdItem({ channels: [] });
|
||||
await openPicker();
|
||||
|
||||
await expect(
|
||||
screen.findByTestId('channels-not-found-create'),
|
||||
).resolves.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('asks for an admin without notification-channel:create', async () => {
|
||||
denyPermissions(NotificationChannelCreatePermission);
|
||||
renderThresholdItem({ channels: [] });
|
||||
await openPicker();
|
||||
|
||||
await expect(
|
||||
screen.findByText('Please ask your admin to create one.'),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('channels-not-found-create'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -205,46 +205,6 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.recovery-threshold-input-group {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0;
|
||||
margin-left: 28px;
|
||||
|
||||
.recovery-threshold-label {
|
||||
pointer-events: none;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.recovery-threshold-btn {
|
||||
pointer-events: none;
|
||||
cursor: default;
|
||||
color: var(--muted-foreground);
|
||||
background-color: var(--surface-2) !important;
|
||||
border: 1px solid var(--l1-border);
|
||||
border-radius: 4px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.ant-input {
|
||||
background-color: var(--surface-2);
|
||||
border: 1px solid var(--l1-border);
|
||||
color: var(--l1-foreground);
|
||||
height: 32px;
|
||||
|
||||
&:hover {
|
||||
border-color: var(--l1-border);
|
||||
}
|
||||
|
||||
&:focus {
|
||||
border-color: var(--l1-border);
|
||||
box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -275,15 +235,10 @@
|
||||
gap: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
.ant-typography {
|
||||
color: var(--accent-primary);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.condensed-alert-threshold-container,
|
||||
.condensed-anomaly-threshold-container {
|
||||
.condensed-alert-threshold-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { useMemo } from 'react';
|
||||
import type { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
|
||||
import {
|
||||
type UseChannelPickerAccessReturn,
|
||||
useChannelPickerAccess,
|
||||
} from 'hooks/notificationChannels/useChannelPickerAccess';
|
||||
import {
|
||||
buildRuleAttachPermission,
|
||||
buildRuleDetachPermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
|
||||
|
||||
import { useCreateAlertState } from '../context';
|
||||
import type { Threshold } from '../context/types';
|
||||
|
||||
/**
|
||||
* One threshold's channel picker. An edit checks `attach`/`detach` on the rule
|
||||
* and each channel; a new rule has no id, so its own `attach` is checked on
|
||||
* Save, as for a new routing policy. The backend diffs the rule's channels as
|
||||
* one set, so a channel another threshold holds, or a saved one this threshold
|
||||
* no longer holds, needs no check.
|
||||
*/
|
||||
export function useAlertRuleChannelAccess(
|
||||
threshold: Threshold,
|
||||
channels: ChannelOption[],
|
||||
testIdPrefix: string,
|
||||
): Pick<UseChannelPickerAccessReturn, 'options' | 'onPickerVisibleChange'> {
|
||||
const { isEditMode, ruleId, savedChannelNames, thresholdState } =
|
||||
useCreateAlertState();
|
||||
const editedRuleId = isEditMode && ruleId ? ruleId : undefined;
|
||||
|
||||
const owner = useMemo(
|
||||
() =>
|
||||
editedRuleId
|
||||
? {
|
||||
attach: buildRuleAttachPermission(editedRuleId),
|
||||
detach: buildRuleDetachPermission(editedRuleId),
|
||||
}
|
||||
: undefined,
|
||||
[editedRuleId],
|
||||
);
|
||||
|
||||
const exemptChannelNames = useMemo(() => {
|
||||
const own = new Set(threshold.channels);
|
||||
return [
|
||||
...thresholdState.thresholds
|
||||
.filter((other) => other.id !== threshold.id)
|
||||
.flatMap((other) => other.channels),
|
||||
...savedChannelNames.filter((name) => !own.has(name)),
|
||||
];
|
||||
}, [
|
||||
threshold.id,
|
||||
threshold.channels,
|
||||
thresholdState.thresholds,
|
||||
savedChannelNames,
|
||||
]);
|
||||
|
||||
const { options, onPickerVisibleChange } = useChannelPickerAccess({
|
||||
owner,
|
||||
savedChannelNames,
|
||||
exemptChannelNames,
|
||||
channels,
|
||||
testIdPrefix,
|
||||
});
|
||||
|
||||
return { options, onPickerVisibleChange };
|
||||
}
|
||||
@@ -1,12 +1,10 @@
|
||||
import { Button, SelectProps } from 'antd';
|
||||
import Flex from 'periscope/components/Flex/Flex';
|
||||
import { Switch } from '@signozhq/ui/switch';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import type { BaseOptionType, DefaultOptionType } from 'antd/es/select';
|
||||
import { getInvolvedQueriesInTraceOperator } from 'components/QueryBuilderV2/QueryV2/TraceOperator/utils/utils';
|
||||
import { YAxisSource } from 'components/YAxisUnitSelector/types';
|
||||
import { getYAxisCategories } from 'components/YAxisUnitSelector/utils';
|
||||
import ROUTES from 'constants/routes';
|
||||
import {
|
||||
AlertThresholdMatchType,
|
||||
AlertThresholdOperator,
|
||||
@@ -15,12 +13,9 @@ import { getSelectedQueryOptions } from 'container/FormAlertRules/utils';
|
||||
import { useSafeNavigate } from 'hooks/useSafeNavigate';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { ArrowRight } from '@signozhq/icons';
|
||||
import { IUser } from 'providers/App/types';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { QueryFunction } from 'types/api/v5/queryRange';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { USER_ROLES } from 'types/roles';
|
||||
import { openInNewTab } from 'utils/navigation';
|
||||
|
||||
import { ROUTING_POLICIES_ROUTE } from './constants';
|
||||
import { Threshold } from '../context/types';
|
||||
@@ -427,66 +422,6 @@ export const getMatchTypeTooltip = (
|
||||
}
|
||||
};
|
||||
|
||||
export function NotificationChannelsNotFoundContent({
|
||||
user,
|
||||
refreshChannels,
|
||||
}: {
|
||||
user: IUser;
|
||||
refreshChannels: () => void;
|
||||
}): JSX.Element {
|
||||
return (
|
||||
<Flex justify="space-between">
|
||||
<Flex gap={4} align="center">
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
No channels yet.
|
||||
</Typography>
|
||||
{user?.role === USER_ROLES.ADMIN ? (
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Create one
|
||||
<Button
|
||||
style={{ padding: '0 4px' }}
|
||||
type="link"
|
||||
onClick={(): void => {
|
||||
openInNewTab(ROUTES.CHANNELS_NEW);
|
||||
}}
|
||||
>
|
||||
here.
|
||||
</Button>
|
||||
</Typography>
|
||||
) : (
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Please ask your admin to create one.
|
||||
</Typography>
|
||||
)}
|
||||
</Flex>
|
||||
<Button type="text" onClick={refreshChannels}>
|
||||
Refresh
|
||||
</Button>
|
||||
</Flex>
|
||||
);
|
||||
}
|
||||
|
||||
export function RoutingPolicyBanner({
|
||||
notificationSettings,
|
||||
setNotificationSettings,
|
||||
|
||||
@@ -2,6 +2,8 @@ import { useCallback, useMemo } from 'react';
|
||||
import { Input } from '@signozhq/ui/input';
|
||||
import classNames from 'classnames';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { buildRuleUpdatePermission } from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
|
||||
import { useAuthZDisabled } from 'lib/authz/hooks/useAuthZDisabled/useAuthZDisabled';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { useAlertRuleOptional } from 'providers/Alert';
|
||||
import { Labels } from 'types/api/alerts/def';
|
||||
@@ -12,7 +14,15 @@ import LabelsInput from './LabelsInput';
|
||||
import './styles.scss';
|
||||
|
||||
function CreateAlertHeader(): JSX.Element {
|
||||
const { alertState, setAlertState, isEditMode } = useCreateAlertState();
|
||||
const { alertState, setAlertState, isEditMode, ruleId } =
|
||||
useCreateAlertState();
|
||||
// Renaming or relabelling a saved rule is an update; a new rule is gated on
|
||||
// its Save.
|
||||
const updateChecks = useMemo(
|
||||
() => (isEditMode && ruleId ? [buildRuleUpdatePermission(ruleId)] : []),
|
||||
[isEditMode, ruleId],
|
||||
);
|
||||
const updateLock = useAuthZDisabled(updateChecks);
|
||||
const alertRuleContext = useAlertRuleOptional();
|
||||
|
||||
const { currentQuery } = useQueryBuilder();
|
||||
@@ -60,6 +70,8 @@ function CreateAlertHeader(): JSX.Element {
|
||||
}
|
||||
}}
|
||||
placeholder="Enter alert rule name"
|
||||
disabled={updateLock.disabled}
|
||||
disabledTooltip={updateLock.disabledTooltip}
|
||||
testId="alert-name-input"
|
||||
/>
|
||||
</div>
|
||||
@@ -69,6 +81,8 @@ function CreateAlertHeader(): JSX.Element {
|
||||
setAlertState({ type: 'SET_ALERT_LABELS', payload: labels })
|
||||
}
|
||||
validateLabelsKey={validateLabelsKey}
|
||||
disabled={updateLock.disabled}
|
||||
disabledTooltip={updateLock.disabledTooltip}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import React, { useCallback, useState } from 'react';
|
||||
import { X } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { useNotifications } from 'hooks/useNotifications';
|
||||
|
||||
import { LabelInputState, LabelsInputProps } from './types';
|
||||
@@ -8,6 +9,8 @@ function LabelsInput({
|
||||
labels,
|
||||
onLabelsChange,
|
||||
validateLabelsKey,
|
||||
disabled = false,
|
||||
disabledTooltip,
|
||||
}: LabelsInputProps): JSX.Element {
|
||||
const { notifications } = useNotifications();
|
||||
const [inputState, setInputState] = useState<LabelInputState>({
|
||||
@@ -134,6 +137,8 @@ function LabelsInput({
|
||||
type="button"
|
||||
className="labels-input__remove-button"
|
||||
aria-label={`Remove label ${key}`}
|
||||
data-testid={`label-remove-${key}`}
|
||||
disabled={disabled}
|
||||
onClick={(): void => handleRemoveLabel(key)}
|
||||
>
|
||||
<X size="md" />
|
||||
@@ -144,14 +149,19 @@ function LabelsInput({
|
||||
)}
|
||||
|
||||
{!isAdding ? (
|
||||
<button
|
||||
className="labels-input__add-button"
|
||||
type="button"
|
||||
onClick={handleAddLabelsClick}
|
||||
data-testid="alert-add-label-button"
|
||||
>
|
||||
+ Add labels
|
||||
</button>
|
||||
<div className="labels-input__add">
|
||||
<Button
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
disabled={disabled}
|
||||
disabledTooltip={disabledTooltip}
|
||||
onClick={handleAddLabelsClick}
|
||||
testId="alert-add-label-button"
|
||||
>
|
||||
+ Add labels
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="labels-input__input-container">
|
||||
<input
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { initialQueryAIWithType } from 'constants/queryBuilder';
|
||||
import { buildRuleUpdatePermission } from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
|
||||
import { denyPermissions } from 'lib/authz/utils/authz-test-utils';
|
||||
import { defaultPostableAlertRuleV2 } from 'container/CreateAlert/constants';
|
||||
import { getCreateAlertLocalStateFromAlertDef } from 'container/CreateAlert/utils';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
@@ -43,6 +45,12 @@ jest.mock('uplot', () => {
|
||||
|
||||
mockAppLocation({ search: '' });
|
||||
|
||||
jest.mock('lib/authz/hooks/useAuthZ/useAuthZ');
|
||||
|
||||
beforeEach(() => {
|
||||
denyPermissions();
|
||||
});
|
||||
|
||||
const ENTER_ALERT_RULE_NAME_PLACEHOLDER = 'Enter alert rule name';
|
||||
|
||||
const renderCreateAlertHeader = (): ReturnType<typeof render> =>
|
||||
@@ -142,4 +150,54 @@ describe('CreateAlertHeader', () => {
|
||||
|
||||
alertStateSpy.mockRestore();
|
||||
});
|
||||
|
||||
describe('authz', () => {
|
||||
const RULE_ID = 'rule-1';
|
||||
const renderEdit = (): void => {
|
||||
render(
|
||||
<CreateAlertProvider
|
||||
isEditMode
|
||||
ruleId={RULE_ID}
|
||||
initialAlertType={AlertTypes.METRICS_BASED_ALERT}
|
||||
initialAlertState={getCreateAlertLocalStateFromAlertDef(
|
||||
defaultPostableAlertRuleV2,
|
||||
)}
|
||||
>
|
||||
<CreateAlertHeader />
|
||||
</CreateAlertProvider>,
|
||||
);
|
||||
};
|
||||
const nameField = (): HTMLElement =>
|
||||
screen.getByPlaceholderText(ENTER_ALERT_RULE_NAME_PLACEHOLDER);
|
||||
|
||||
it('locks renaming and relabelling a saved rule without update', () => {
|
||||
denyPermissions(buildRuleUpdatePermission(RULE_ID));
|
||||
renderEdit();
|
||||
|
||||
expect(nameField()).toBeDisabled();
|
||||
expect(screen.getByTestId('alert-add-label-button')).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
expect(screen.getByTestId('label-remove-severity')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('lets a saved rule be renamed and relabelled with update', () => {
|
||||
renderEdit();
|
||||
|
||||
expect(nameField()).toBeEnabled();
|
||||
expect(screen.getByTestId('alert-add-label-button')).not.toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
expect(screen.getByTestId('label-remove-severity')).toBeEnabled();
|
||||
});
|
||||
|
||||
it('never locks naming a new rule', () => {
|
||||
denyPermissions(buildRuleUpdatePermission(RULE_ID));
|
||||
renderCreateAlertHeader();
|
||||
|
||||
expect(nameField()).toBeEnabled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -60,20 +60,8 @@
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
|
||||
&__add-button {
|
||||
width: fit-content;
|
||||
font-size: 13px;
|
||||
color: var(--l2-foreground);
|
||||
border: 1px solid var(--l1-border);
|
||||
background-color: transparent;
|
||||
cursor: pointer;
|
||||
padding: 4px 8px;
|
||||
border-radius: 4px;
|
||||
|
||||
&:hover {
|
||||
border-color: var(--l1-border);
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
&__add {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
&__existing-labels {
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { Labels } from 'types/api/alerts/def';
|
||||
|
||||
export interface LabelsInputProps {
|
||||
labels: Labels;
|
||||
onLabelsChange: (labels: Labels) => void;
|
||||
validateLabelsKey: (key: string) => string | null;
|
||||
disabled?: boolean;
|
||||
/** Shown on Add labels while disabled. */
|
||||
disabledTooltip?: ReactNode;
|
||||
}
|
||||
|
||||
export interface LabelInputState {
|
||||
|
||||
@@ -11,11 +11,6 @@
|
||||
gap: 16px;
|
||||
padding: 16px;
|
||||
|
||||
.ant-typography {
|
||||
color: var(--l1-foreground);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.ant-btn-group {
|
||||
.ant-btn {
|
||||
border: 1px solid var(--l1-border);
|
||||
@@ -133,12 +128,6 @@
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
|
||||
.ant-typography {
|
||||
color: var(--l1-foreground);
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.ant-select {
|
||||
border: 1px solid var(--l1-border);
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ export const createMockAlertContextState = (
|
||||
updateAlertRule: jest.fn(),
|
||||
isEditMode: false,
|
||||
ruleId: '',
|
||||
savedChannelNames: [],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
|
||||
@@ -1,53 +1,3 @@
|
||||
.evaluation-settings-container {
|
||||
margin: 16px;
|
||||
|
||||
.evaluate-alert-conditions-container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
background-color: var(--l2-background);
|
||||
padding: 16px;
|
||||
border-radius: 4px;
|
||||
border: 1px solid var(--l1-border);
|
||||
margin-bottom: 16px;
|
||||
|
||||
.ant-typography {
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.evaluate-alert-conditions-separator {
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
border-top: 1px dashed var(--l1-border);
|
||||
}
|
||||
|
||||
.ant-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
background-color: var(--l2-background);
|
||||
border: 1px solid var(--l1-border);
|
||||
|
||||
.evaluate-alert-conditions-button-left {
|
||||
color: var(--l2-foreground);
|
||||
padding-right: 16px;
|
||||
}
|
||||
|
||||
.evaluate-alert-conditions-button-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
color: var(--muted-foreground);
|
||||
gap: 8px;
|
||||
|
||||
.evaluate-alert-conditions-button-right-text {
|
||||
background-color: var(--l2-background);
|
||||
padding: 1px 4px;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.advanced-options-container {
|
||||
.ant-collapse {
|
||||
.ant-collapse-item {
|
||||
@@ -118,18 +68,9 @@
|
||||
margin: 0 -16px;
|
||||
padding: 4px 16px;
|
||||
|
||||
.ant-typography {
|
||||
color: var(--muted-foreground);
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
&.active {
|
||||
background-color: var(--l1-background);
|
||||
border-left: 2px solid var(--bg-robin-500);
|
||||
.ant-typography {
|
||||
font-weight: 500;
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
}
|
||||
|
||||
&:hover {
|
||||
@@ -147,25 +88,12 @@
|
||||
gap: 16px;
|
||||
width: 400px;
|
||||
|
||||
.ant-typography {
|
||||
color: var(--muted-foreground);
|
||||
}
|
||||
|
||||
.ant-btn {
|
||||
width: fit-content;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.evaluation-window-footer {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
background-color: var(--l2-background);
|
||||
border-top: 1px solid var(--l1-border);
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.ant-btn {
|
||||
background-color: var(--l3-background);
|
||||
border: 1px solid var(--l1-border);
|
||||
@@ -188,13 +116,6 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
|
||||
.ant-typography {
|
||||
color: var(--l3-foreground);
|
||||
font-size: 11px;
|
||||
line-height: 18px;
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
|
||||
.time-select-group {
|
||||
@@ -218,12 +139,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
.ant-typography {
|
||||
color: var(--l2-foreground);
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.ant-select {
|
||||
width: 60%;
|
||||
background-color: var(--l2-background);
|
||||
|
||||
@@ -57,14 +57,6 @@ export interface IEvaluationCadencePreviewProps {
|
||||
setIsOpen: Dispatch<SetStateAction<boolean>>;
|
||||
}
|
||||
|
||||
export interface TimeInputProps {
|
||||
value?: string; // Format: "HH:MM:SS"
|
||||
onChange?: (value: string) => void;
|
||||
placeholder?: string;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export interface IEditCustomScheduleProps {
|
||||
setIsEvaluationCadenceDetailsVisible: (isOpen: boolean) => void;
|
||||
setIsPreviewVisible: (isOpen: boolean) => void;
|
||||
|
||||
@@ -7,12 +7,16 @@ import { AxiosError } from 'axios';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useSafeNavigate } from 'hooks/useSafeNavigate';
|
||||
import { Check, Send, X } from '@signozhq/icons';
|
||||
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
|
||||
import { AUTHZ_LOADING_TOOLTIP } from 'lib/authz/components/constants';
|
||||
import { useErrorModal } from 'providers/ErrorModalProvider';
|
||||
import { toPostableRuleDTO } from 'types/api/alerts/convert';
|
||||
import APIError from 'types/api/error';
|
||||
import { isModifierKeyPressed } from 'utils/app';
|
||||
|
||||
import { useCreateAlertState } from '../context';
|
||||
import { WAIT_FOR_SAVE, WAIT_FOR_TEST_NOTIFICATION } from './constants';
|
||||
import { useAlertRuleSaveChecks } from './useAlertRuleSaveChecks';
|
||||
import { buildCreateAlertRulePayload, validateCreateAlertState } from './utils';
|
||||
|
||||
import './styles.scss';
|
||||
@@ -42,13 +46,13 @@ function Footer(): JSX.Element {
|
||||
} = useCreateAlertState();
|
||||
const { currentQuery } = useQueryBuilder();
|
||||
const { safeNavigate } = useSafeNavigate();
|
||||
const { saveChecks, testChecks, isResolvingChannels } =
|
||||
useAlertRuleSaveChecks();
|
||||
const { showErrorModal } = useErrorModal();
|
||||
|
||||
const handleApiError = useCallback(
|
||||
(error: unknown): void => {
|
||||
showErrorModal(
|
||||
convertToApiError(error as AxiosError<RenderErrorResponseDTO>) as APIError,
|
||||
);
|
||||
(error: AxiosError<RenderErrorResponseDTO>): void => {
|
||||
showErrorModal(convertToApiError(error) as APIError);
|
||||
},
|
||||
[showErrorModal],
|
||||
);
|
||||
@@ -178,65 +182,64 @@ function Footer(): JSX.Element {
|
||||
const isSavingAlertRule = isCreatingAlertRule || isUpdatingAlertRule;
|
||||
const disableButtons = isSavingAlertRule || isTestingAlertRule;
|
||||
|
||||
const saveBlockedReason =
|
||||
alertValidationMessage ||
|
||||
(isTestingAlertRule
|
||||
? WAIT_FOR_TEST_NOTIFICATION
|
||||
: isResolvingChannels
|
||||
? AUTHZ_LOADING_TOOLTIP
|
||||
: undefined);
|
||||
const testBlockedReason =
|
||||
alertValidationMessage ||
|
||||
(isSavingAlertRule
|
||||
? WAIT_FOR_SAVE
|
||||
: isResolvingChannels
|
||||
? AUTHZ_LOADING_TOOLTIP
|
||||
: undefined);
|
||||
|
||||
const saveAlertButton = useMemo(
|
||||
() => (
|
||||
<Button
|
||||
disabledTooltip={
|
||||
alertValidationMessage || 'Wait for the test notification to finish'
|
||||
}
|
||||
<AuthZButton
|
||||
checks={saveChecks}
|
||||
disabledTooltip={saveBlockedReason}
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
onClick={handleSaveAlert}
|
||||
disabled={isTestingAlertRule || Boolean(alertValidationMessage)}
|
||||
loading={isSavingAlertRule}
|
||||
prefix={<Check data-testid="save-alert-rule-check-icon" size={14} />}
|
||||
testId="save-alert-rule-button"
|
||||
>
|
||||
Save Alert Rule
|
||||
</Button>
|
||||
</AuthZButton>
|
||||
),
|
||||
[
|
||||
alertValidationMessage,
|
||||
handleSaveAlert,
|
||||
isSavingAlertRule,
|
||||
isTestingAlertRule,
|
||||
],
|
||||
[saveChecks, saveBlockedReason, handleSaveAlert, isSavingAlertRule],
|
||||
);
|
||||
|
||||
const testAlertButton = useMemo(
|
||||
() => (
|
||||
<Button
|
||||
disabledTooltip={
|
||||
alertValidationMessage || 'Wait for the alert rule to finish saving'
|
||||
}
|
||||
<AuthZButton
|
||||
checks={testChecks}
|
||||
disabledTooltip={testBlockedReason}
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
onClick={handleTestNotification}
|
||||
disabled={isSavingAlertRule || Boolean(alertValidationMessage)}
|
||||
loading={isTestingAlertRule}
|
||||
prefix={<Send data-testid="test-notification-send-icon" size={14} />}
|
||||
testId="test-notification-button"
|
||||
>
|
||||
Test Notification
|
||||
</Button>
|
||||
</AuthZButton>
|
||||
),
|
||||
[
|
||||
alertValidationMessage,
|
||||
handleTestNotification,
|
||||
isSavingAlertRule,
|
||||
isTestingAlertRule,
|
||||
],
|
||||
[testChecks, testBlockedReason, handleTestNotification, isTestingAlertRule],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="create-alert-v2-footer">
|
||||
<Button
|
||||
disabledTooltip={
|
||||
isTestingAlertRule
|
||||
? 'Wait for the test notification to finish'
|
||||
: 'Wait for the alert rule to finish saving'
|
||||
isTestingAlertRule ? WAIT_FOR_TEST_NOTIFICATION : WAIT_FOR_SAVE
|
||||
}
|
||||
size="md"
|
||||
variant="solid"
|
||||
|
||||
@@ -1,39 +1,56 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import type { AxiosError } from 'axios';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import type { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
AlertThresholdMatchType,
|
||||
AlertThresholdOperator,
|
||||
} from 'container/CreateAlert/context/types';
|
||||
import { createMockAlertContextState } from 'container/CreateAlert/EvaluationSettings/__tests__/testUtils';
|
||||
import { useChannelOptions } from 'hooks/notificationChannels/useChannelOptions';
|
||||
import { buildNotificationChannelAttachPermission } from 'lib/authz/hooks/useAuthZ/permissions/notification-channel.permissions';
|
||||
import {
|
||||
buildRuleUpdatePermission,
|
||||
RuleCreatePermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
|
||||
import { denyPermissions } from 'lib/authz/utils/authz-test-utils';
|
||||
|
||||
import type { ICreateAlertContextProps } from '../../context/types';
|
||||
import * as createAlertState from '../../context';
|
||||
import Footer from '../Footer';
|
||||
import MockQueryClientProvider from 'providers/test/MockQueryClientProvider';
|
||||
|
||||
// Mock the hooks used by Footer component
|
||||
jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
|
||||
useQueryBuilder: jest.fn(),
|
||||
}));
|
||||
const mockShowErrorModal = jest.fn();
|
||||
jest.mock('providers/ErrorModalProvider', () => ({
|
||||
...jest.requireActual('providers/ErrorModalProvider'),
|
||||
useErrorModal: (): { showErrorModal: jest.Mock } => ({
|
||||
showErrorModal: jest.fn(),
|
||||
showErrorModal: mockShowErrorModal,
|
||||
}),
|
||||
}));
|
||||
jest.mock('lib/authz/hooks/useAuthZ/useAuthZ');
|
||||
|
||||
jest.mock('hooks/useSafeNavigate', () => ({
|
||||
useSafeNavigate: jest.fn(),
|
||||
}));
|
||||
const { useQueryBuilder } = jest.requireMock(
|
||||
'hooks/queryBuilder/useQueryBuilder',
|
||||
);
|
||||
|
||||
const CHANNELS_URL = 'http://localhost/api/v2/notification_channels';
|
||||
const CHANNELS = [
|
||||
{ id: 'ch-test', displayName: 'test-channel' },
|
||||
{ id: 'ch-other', displayName: 'other-channel' },
|
||||
];
|
||||
|
||||
const SAVE = 'save-alert-rule-button';
|
||||
const TEST = 'test-notification-button';
|
||||
const DISCARD = 'discard-alert-rule-button';
|
||||
|
||||
const mockCreateAlertRule = jest.fn();
|
||||
const mockTestAlertRule = jest.fn();
|
||||
const mockUpdateAlertRule = jest.fn();
|
||||
const mockDiscardAlertRule = jest.fn();
|
||||
|
||||
// Import the mocked hooks
|
||||
const { useQueryBuilder } = jest.requireMock(
|
||||
'hooks/queryBuilder/useQueryBuilder',
|
||||
);
|
||||
const { useSafeNavigate } = jest.requireMock('hooks/useSafeNavigate');
|
||||
|
||||
const mockAlertContextState = createMockAlertContextState({
|
||||
createAlertRule: mockCreateAlertRule,
|
||||
testAlertRule: mockTestAlertRule,
|
||||
@@ -64,19 +81,52 @@ const mockAlertContextState = createMockAlertContextState({
|
||||
},
|
||||
});
|
||||
|
||||
const WrappedFooter = (): JSX.Element => (
|
||||
<MockQueryClientProvider>
|
||||
<Footer />
|
||||
</MockQueryClientProvider>
|
||||
);
|
||||
const withState = (overrides: Partial<ICreateAlertContextProps>): void => {
|
||||
jest
|
||||
.spyOn(createAlertState, 'useCreateAlertState')
|
||||
.mockReturnValue({ ...mockAlertContextState, ...overrides });
|
||||
};
|
||||
|
||||
jest
|
||||
.spyOn(createAlertState, 'useCreateAlertState')
|
||||
.mockReturnValue(mockAlertContextState);
|
||||
const withoutChannels = (
|
||||
routingPolicies: boolean,
|
||||
): Partial<ICreateAlertContextProps> => ({
|
||||
notificationSettings: {
|
||||
...mockAlertContextState.notificationSettings,
|
||||
routingPolicies,
|
||||
},
|
||||
thresholdState: {
|
||||
...mockAlertContextState.thresholdState,
|
||||
thresholds: [
|
||||
{ ...mockAlertContextState.thresholdState.thresholds[0], channels: [] },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const SAVE_ALERT_RULE_TEXT = 'Save Alert Rule';
|
||||
const TEST_NOTIFICATION_TEXT = 'Test Notification';
|
||||
const DISCARD_TEXT = 'Discard';
|
||||
/** Reads the channel list the footer reads, so a test knows it has loaded. */
|
||||
function ChannelsProbe(): JSX.Element {
|
||||
const { data } = useChannelOptions();
|
||||
return <output data-testid="channels-probe">{data.length}</output>;
|
||||
}
|
||||
|
||||
const renderFooter = async (): Promise<void> => {
|
||||
render(
|
||||
<>
|
||||
<ChannelsProbe />
|
||||
<Footer />
|
||||
</>,
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('channels-probe')).toHaveTextContent(
|
||||
String(CHANNELS.length),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const user = (): ReturnType<typeof userEvent.setup> =>
|
||||
userEvent.setup({ pointerEventsCheck: 0 });
|
||||
|
||||
const lockOf = (testId: string): string | null =>
|
||||
screen.getByTestId(testId).getAttribute('aria-disabled');
|
||||
|
||||
describe('Footer', () => {
|
||||
beforeEach(() => {
|
||||
@@ -91,217 +141,219 @@ describe('Footer', () => {
|
||||
queryType: 'builder',
|
||||
},
|
||||
});
|
||||
|
||||
useSafeNavigate.mockReturnValue({
|
||||
safeNavigate: jest.fn(),
|
||||
});
|
||||
denyPermissions();
|
||||
withState({});
|
||||
server.use(
|
||||
rest.get(CHANNELS_URL, (_req, res, ctx) =>
|
||||
res(
|
||||
ctx.json({
|
||||
status: 'success',
|
||||
data: { channels: CHANNELS, total: CHANNELS.length },
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('should render the component with 3 buttons', () => {
|
||||
render(<WrappedFooter />);
|
||||
expect(screen.getByText(SAVE_ALERT_RULE_TEXT)).toBeInTheDocument();
|
||||
expect(screen.getByText(TEST_NOTIFICATION_TEXT)).toBeInTheDocument();
|
||||
expect(screen.getByText(DISCARD_TEXT)).toBeInTheDocument();
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
it('discard action works correctly', () => {
|
||||
render(<WrappedFooter />);
|
||||
fireEvent.click(screen.getByText(DISCARD_TEXT));
|
||||
it('should render the component with 3 buttons', async () => {
|
||||
await renderFooter();
|
||||
expect(screen.getByTestId(SAVE)).toBeInTheDocument();
|
||||
expect(screen.getByTestId(TEST)).toBeInTheDocument();
|
||||
expect(screen.getByTestId(DISCARD)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('discard action works correctly', async () => {
|
||||
await renderFooter();
|
||||
await user().click(screen.getByTestId(DISCARD));
|
||||
expect(mockDiscardAlertRule).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('save alert rule action works correctly', () => {
|
||||
render(<WrappedFooter />);
|
||||
fireEvent.click(screen.getByText(SAVE_ALERT_RULE_TEXT));
|
||||
it('save alert rule action works correctly', async () => {
|
||||
await renderFooter();
|
||||
await user().click(screen.getByTestId(SAVE));
|
||||
expect(mockCreateAlertRule).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('update alert rule action works correctly', () => {
|
||||
jest.spyOn(createAlertState, 'useCreateAlertState').mockReturnValueOnce({
|
||||
...mockAlertContextState,
|
||||
isEditMode: true,
|
||||
});
|
||||
render(<WrappedFooter />);
|
||||
fireEvent.click(screen.getByText(SAVE_ALERT_RULE_TEXT));
|
||||
it('update alert rule action works correctly', async () => {
|
||||
withState({ isEditMode: true });
|
||||
await renderFooter();
|
||||
await user().click(screen.getByTestId(SAVE));
|
||||
expect(mockUpdateAlertRule).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('test notification action works correctly', () => {
|
||||
render(<WrappedFooter />);
|
||||
fireEvent.click(screen.getByText(TEST_NOTIFICATION_TEXT));
|
||||
it('test notification action works correctly', async () => {
|
||||
await renderFooter();
|
||||
await user().click(screen.getByTestId(TEST));
|
||||
expect(mockTestAlertRule).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('all buttons are disabled when creating alert rule', () => {
|
||||
jest.spyOn(createAlertState, 'useCreateAlertState').mockReturnValueOnce({
|
||||
...mockAlertContextState,
|
||||
isCreatingAlertRule: true,
|
||||
});
|
||||
render(<WrappedFooter />);
|
||||
it.each([
|
||||
['creating', { isCreatingAlertRule: true }],
|
||||
['updating', { isUpdatingAlertRule: true }],
|
||||
['testing', { isTestingAlertRule: true }],
|
||||
])('all buttons are disabled when %s alert rule', async (_label, state) => {
|
||||
withState(state);
|
||||
await renderFooter();
|
||||
|
||||
expect(
|
||||
screen.getByRole('button', { name: /save alert rule/i }),
|
||||
).toHaveAttribute('aria-disabled', 'true');
|
||||
expect(
|
||||
screen.getByRole('button', { name: /test notification/i }),
|
||||
).toHaveAttribute('aria-disabled', 'true');
|
||||
expect(screen.getByRole('button', { name: /discard/i })).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
expect(lockOf(SAVE)).toBe('true');
|
||||
expect(lockOf(TEST)).toBe('true');
|
||||
expect(lockOf(DISCARD)).toBe('true');
|
||||
});
|
||||
|
||||
it('all buttons are disabled when updating alert rule', () => {
|
||||
jest.spyOn(createAlertState, 'useCreateAlertState').mockReturnValueOnce({
|
||||
...mockAlertContextState,
|
||||
isUpdatingAlertRule: true,
|
||||
it('create and test buttons are disabled when alert name is missing', async () => {
|
||||
withState({
|
||||
alertState: { ...mockAlertContextState.alertState, name: '' },
|
||||
});
|
||||
render(<WrappedFooter />);
|
||||
await renderFooter();
|
||||
|
||||
// Target the button elements directly instead of the text spans inside them
|
||||
expect(
|
||||
screen.getByRole('button', { name: /save alert rule/i }),
|
||||
).toHaveAttribute('aria-disabled', 'true');
|
||||
expect(
|
||||
screen.getByRole('button', { name: /test notification/i }),
|
||||
).toHaveAttribute('aria-disabled', 'true');
|
||||
expect(screen.getByRole('button', { name: /discard/i })).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
expect(lockOf(SAVE)).toBe('true');
|
||||
expect(lockOf(TEST)).toBe('true');
|
||||
});
|
||||
|
||||
it('all buttons are disabled when testing alert rule', () => {
|
||||
jest.spyOn(createAlertState, 'useCreateAlertState').mockReturnValueOnce({
|
||||
...mockAlertContextState,
|
||||
isTestingAlertRule: true,
|
||||
});
|
||||
render(<WrappedFooter />);
|
||||
it('create and test buttons are disabled when notifcation channels are missing and routing policies are disabled', async () => {
|
||||
withState(withoutChannels(false));
|
||||
await renderFooter();
|
||||
|
||||
// Target the button elements directly instead of the text spans inside them
|
||||
expect(
|
||||
screen.getByRole('button', { name: /save alert rule/i }),
|
||||
).toHaveAttribute('aria-disabled', 'true');
|
||||
expect(
|
||||
screen.getByRole('button', { name: /test notification/i }),
|
||||
).toHaveAttribute('aria-disabled', 'true');
|
||||
expect(screen.getByRole('button', { name: /discard/i })).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
expect(lockOf(SAVE)).toBe('true');
|
||||
expect(lockOf(TEST)).toBe('true');
|
||||
});
|
||||
|
||||
it('create and test buttons are disabled when alert name is missing', () => {
|
||||
jest.spyOn(createAlertState, 'useCreateAlertState').mockReturnValueOnce({
|
||||
...mockAlertContextState,
|
||||
alertState: {
|
||||
...mockAlertContextState.alertState,
|
||||
name: '',
|
||||
},
|
||||
});
|
||||
render(<WrappedFooter />);
|
||||
it('buttons are enabled even with no notification channels when routing policies are enabled', async () => {
|
||||
withState(withoutChannels(true));
|
||||
await renderFooter();
|
||||
|
||||
expect(
|
||||
screen.getByRole('button', { name: /save alert rule/i }),
|
||||
).toHaveAttribute('aria-disabled', 'true');
|
||||
expect(
|
||||
screen.getByRole('button', { name: /test notification/i }),
|
||||
).toHaveAttribute('aria-disabled', 'true');
|
||||
expect(lockOf(SAVE)).toBe('false');
|
||||
expect(lockOf(TEST)).toBe('false');
|
||||
expect(lockOf(DISCARD)).toBe('false');
|
||||
});
|
||||
|
||||
it('create and test buttons are disabled when notifcation channels are missing and routing policies are disabled', () => {
|
||||
jest.spyOn(createAlertState, 'useCreateAlertState').mockReturnValueOnce({
|
||||
...mockAlertContextState,
|
||||
notificationSettings: {
|
||||
...mockAlertContextState.notificationSettings,
|
||||
routingPolicies: false,
|
||||
},
|
||||
thresholdState: {
|
||||
...mockAlertContextState.thresholdState,
|
||||
thresholds: [
|
||||
{
|
||||
...mockAlertContextState.thresholdState.thresholds[0],
|
||||
channels: [],
|
||||
it('should show loading state on test notification button when testing alert rule', async () => {
|
||||
withState({ isTestingAlertRule: true });
|
||||
await renderFooter();
|
||||
|
||||
expect(screen.getByTestId(TEST)).toHaveAttribute('aria-busy', 'true');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['updating', { isUpdatingAlertRule: true }],
|
||||
['creating', { isCreatingAlertRule: true }],
|
||||
])(
|
||||
'should show loading state on save alert rule button when %s alert rule',
|
||||
async (_label, state) => {
|
||||
withState(state);
|
||||
await renderFooter();
|
||||
|
||||
expect(screen.getByTestId(SAVE)).toHaveAttribute('aria-busy', 'true');
|
||||
},
|
||||
);
|
||||
|
||||
describe('authz', () => {
|
||||
const RULE_ID = 'rule-1';
|
||||
|
||||
const editing = (savedChannelNames: string[]): void => {
|
||||
withState({ isEditMode: true, ruleId: RULE_ID, savedChannelNames });
|
||||
};
|
||||
|
||||
it('locks Save and Test without create, naming it', async () => {
|
||||
denyPermissions(RuleCreatePermission);
|
||||
await renderFooter();
|
||||
|
||||
for (const testId of [SAVE, TEST]) {
|
||||
expect(lockOf(testId)).toBe('true');
|
||||
expect(screen.getByTestId(testId)).toHaveAttribute(
|
||||
'data-denied-permissions',
|
||||
expect.stringContaining(RuleCreatePermission),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('locks Save without attach on a picked channel', async () => {
|
||||
const attach = buildNotificationChannelAttachPermission('ch-test');
|
||||
denyPermissions(attach);
|
||||
await renderFooter();
|
||||
|
||||
expect(screen.getByTestId(SAVE)).toHaveAttribute(
|
||||
'data-denied-permissions',
|
||||
attach,
|
||||
);
|
||||
});
|
||||
|
||||
it('saves an edit with update alone when the channels are unchanged', async () => {
|
||||
denyPermissions(buildNotificationChannelAttachPermission('ch-test'));
|
||||
editing(['test-channel']);
|
||||
await renderFooter();
|
||||
|
||||
expect(lockOf(SAVE)).toBe('false');
|
||||
});
|
||||
|
||||
it('locks Save on an edit without update, leaving Test open', async () => {
|
||||
const update = buildRuleUpdatePermission(RULE_ID);
|
||||
denyPermissions(update);
|
||||
editing(['test-channel']);
|
||||
await renderFooter();
|
||||
|
||||
expect(screen.getByTestId(SAVE)).toHaveAttribute(
|
||||
'data-denied-permissions',
|
||||
update,
|
||||
);
|
||||
expect(lockOf(TEST)).toBe('false');
|
||||
});
|
||||
|
||||
it('needs attach on a channel the edit adds', async () => {
|
||||
const attach = buildNotificationChannelAttachPermission('ch-test');
|
||||
denyPermissions(attach);
|
||||
editing(['other-channel']);
|
||||
await renderFooter();
|
||||
|
||||
expect(screen.getByTestId(SAVE)).toHaveAttribute(
|
||||
'data-denied-permissions',
|
||||
expect.stringContaining(attach),
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps Save and Test locked while the channel list loads', () => {
|
||||
server.use(
|
||||
rest.get(CHANNELS_URL, (_req, res, ctx) => res(ctx.delay('infinite'))),
|
||||
);
|
||||
render(<Footer />);
|
||||
|
||||
for (const testId of [SAVE, TEST]) {
|
||||
expect(lockOf(testId)).toBe('true');
|
||||
expect(screen.getByTestId(testId)).not.toHaveAttribute(
|
||||
'data-denied-permissions',
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('shows a server 403 in the error modal like any other failure', async () => {
|
||||
const forbidden = {
|
||||
isAxiosError: true,
|
||||
response: {
|
||||
status: 403,
|
||||
data: {
|
||||
status: 'error',
|
||||
error: {
|
||||
code: 'authz_forbidden',
|
||||
message: 'user/u-1 is not authorized to perform metric:read',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
} as AxiosError<RenderErrorResponseDTO>;
|
||||
mockShowErrorModal.mockClear();
|
||||
await renderFooter();
|
||||
await user().click(screen.getByTestId(SAVE));
|
||||
|
||||
const [, { onError }] = mockCreateAlertRule.mock.calls.at(-1);
|
||||
await act(async () => {
|
||||
onError(forbidden);
|
||||
});
|
||||
|
||||
render(<WrappedFooter />);
|
||||
|
||||
expect(
|
||||
screen.getByRole('button', { name: /save alert rule/i }),
|
||||
).toHaveAttribute('aria-disabled', 'true');
|
||||
expect(
|
||||
screen.getByRole('button', { name: /test notification/i }),
|
||||
).toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
|
||||
it('buttons are enabled even with no notification channels when routing policies are enabled', () => {
|
||||
jest.spyOn(createAlertState, 'useCreateAlertState').mockReturnValueOnce({
|
||||
...mockAlertContextState,
|
||||
notificationSettings: {
|
||||
...mockAlertContextState.notificationSettings,
|
||||
routingPolicies: true,
|
||||
},
|
||||
thresholdState: {
|
||||
...mockAlertContextState.thresholdState,
|
||||
thresholds: [
|
||||
{
|
||||
...mockAlertContextState.thresholdState.thresholds[0],
|
||||
channels: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
render(<WrappedFooter />);
|
||||
|
||||
expect(
|
||||
screen.getByRole('button', { name: /save alert rule/i }),
|
||||
).not.toHaveAttribute('aria-disabled', 'true');
|
||||
expect(
|
||||
screen.getByRole('button', { name: /test notification/i }),
|
||||
).not.toHaveAttribute('aria-disabled', 'true');
|
||||
expect(screen.getByRole('button', { name: /discard/i })).not.toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
});
|
||||
|
||||
it('should show loading state on test notification button when testing alert rule', () => {
|
||||
jest.spyOn(createAlertState, 'useCreateAlertState').mockReturnValueOnce({
|
||||
...mockAlertContextState,
|
||||
isTestingAlertRule: true,
|
||||
});
|
||||
render(<WrappedFooter />);
|
||||
|
||||
expect(
|
||||
screen.getByRole('button', { name: /test notification/i }),
|
||||
).toHaveAttribute('aria-busy', 'true');
|
||||
});
|
||||
|
||||
it('should show loading state on save alert rule button when updating alert rule', () => {
|
||||
jest.spyOn(createAlertState, 'useCreateAlertState').mockReturnValueOnce({
|
||||
...mockAlertContextState,
|
||||
isUpdatingAlertRule: true,
|
||||
});
|
||||
render(<WrappedFooter />);
|
||||
|
||||
expect(
|
||||
screen.getByRole('button', { name: /save alert rule/i }),
|
||||
).toHaveAttribute('aria-busy', 'true');
|
||||
});
|
||||
|
||||
it('should show loading state on save alert rule button when creating alert rule', () => {
|
||||
jest.spyOn(createAlertState, 'useCreateAlertState').mockReturnValueOnce({
|
||||
...mockAlertContextState,
|
||||
isCreatingAlertRule: true,
|
||||
});
|
||||
render(<WrappedFooter />);
|
||||
|
||||
expect(
|
||||
screen.getByRole('button', { name: /save alert rule/i }),
|
||||
).toHaveAttribute('aria-busy', 'true');
|
||||
expect(mockShowErrorModal).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
3
frontend/src/container/CreateAlert/Footer/constants.ts
Normal file
3
frontend/src/container/CreateAlert/Footer/constants.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export const WAIT_FOR_TEST_NOTIFICATION =
|
||||
'Wait for the test notification to finish';
|
||||
export const WAIT_FOR_SAVE = 'Wait for the alert rule to finish saving';
|
||||
@@ -32,3 +32,8 @@
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
}
|
||||
|
||||
// A pinned side nav is 240px wide, not the collapsed one the left offset clears.
|
||||
.app-layout.side-nav-pinned .create-alert-v2-footer {
|
||||
left: 240px;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useChannelOptions } from 'hooks/notificationChannels/useChannelOptions';
|
||||
import { getChannelIds } from 'hooks/notificationChannels/utils';
|
||||
import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';
|
||||
|
||||
import { useCreateAlertState } from '../context';
|
||||
import { getRuleCreateChecks, getRuleSaveChecks } from '../ruleSaveChecks';
|
||||
|
||||
export interface UseAlertRuleSaveChecksReturn {
|
||||
saveChecks: BrandedPermission[];
|
||||
testChecks: BrandedPermission[];
|
||||
/** The channel list is still loading, so the channel checks are not known yet. */
|
||||
isResolvingChannels: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save and Test notification checks for the rule form. The channel ids come
|
||||
* from the channel list the form already loads.
|
||||
*/
|
||||
export function useAlertRuleSaveChecks(): UseAlertRuleSaveChecksReturn {
|
||||
const { thresholdState, savedChannelNames, isEditMode, ruleId } =
|
||||
useCreateAlertState();
|
||||
const { data: channels, isLoading } = useChannelOptions();
|
||||
|
||||
const selectedChannels = useMemo(
|
||||
() => thresholdState.thresholds.flatMap((threshold) => threshold.channels),
|
||||
[thresholdState.thresholds],
|
||||
);
|
||||
|
||||
return useMemo(() => {
|
||||
const selectedChannelIds = getChannelIds(channels, selectedChannels);
|
||||
|
||||
return {
|
||||
saveChecks: getRuleSaveChecks({
|
||||
ruleId: isEditMode ? ruleId : undefined,
|
||||
savedChannelIds: getChannelIds(channels, savedChannelNames),
|
||||
selectedChannelIds,
|
||||
}),
|
||||
testChecks: getRuleCreateChecks(selectedChannelIds),
|
||||
isResolvingChannels:
|
||||
isLoading && (selectedChannels.length > 0 || savedChannelNames.length > 0),
|
||||
};
|
||||
}, [
|
||||
channels,
|
||||
selectedChannels,
|
||||
savedChannelNames,
|
||||
isEditMode,
|
||||
ruleId,
|
||||
isLoading,
|
||||
]);
|
||||
}
|
||||
@@ -101,84 +101,12 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
|
||||
.ant-typography {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
|
||||
.ant-select {
|
||||
width: 300px;
|
||||
}
|
||||
}
|
||||
|
||||
.re-notification-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
background-color: var(--l2-background);
|
||||
border: 1px solid var(--l1-border);
|
||||
padding: 16px;
|
||||
margin-top: 16px;
|
||||
|
||||
.advanced-option-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
gap: 16px;
|
||||
|
||||
.advanced-option-item-left-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
}
|
||||
|
||||
.border-bottom {
|
||||
border-bottom: 1px solid var(--l1-border);
|
||||
width: 100%;
|
||||
margin-left: -16px;
|
||||
margin-right: -32px;
|
||||
}
|
||||
|
||||
.re-notification-condition {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: nowrap;
|
||||
|
||||
.ant-typography {
|
||||
color: var(--l2-foreground);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.ant-select {
|
||||
width: 200px;
|
||||
height: 32px;
|
||||
flex-shrink: 0;
|
||||
.ant-select-selector {
|
||||
border: 1px solid var(--l1-border);
|
||||
|
||||
&:hover {
|
||||
border-color: var(--l1-border);
|
||||
}
|
||||
|
||||
&:focus {
|
||||
border-color: var(--l1-border);
|
||||
box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.ant-input {
|
||||
width: 200px;
|
||||
flex-shrink: 0;
|
||||
border: 1px solid var(--l1-border);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,11 +15,6 @@
|
||||
border-bottom: none;
|
||||
margin-bottom: -1px;
|
||||
|
||||
.prom-ql-icon {
|
||||
height: 13px;
|
||||
width: 13px;
|
||||
}
|
||||
|
||||
.explorer-view-option {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import {
|
||||
buildNotificationChannelAttachPermission,
|
||||
buildNotificationChannelDetachPermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/notification-channel.permissions';
|
||||
import {
|
||||
buildRuleAttachPermission,
|
||||
buildRuleDetachPermission,
|
||||
buildRuleUpdatePermission,
|
||||
RuleAttachPermission,
|
||||
RuleCreatePermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
|
||||
|
||||
import { getRuleCreateChecks, getRuleSaveChecks } from '../ruleSaveChecks';
|
||||
|
||||
const ID = 'rule-1';
|
||||
const UPDATE = buildRuleUpdatePermission(ID);
|
||||
|
||||
describe('getRuleCreateChecks', () => {
|
||||
it('needs only create without channels', () => {
|
||||
expect(getRuleCreateChecks([])).toStrictEqual([RuleCreatePermission]);
|
||||
});
|
||||
|
||||
it('attaches the rule and each channel once', () => {
|
||||
expect(getRuleCreateChecks(['a', 'b', 'a'])).toStrictEqual([
|
||||
RuleCreatePermission,
|
||||
RuleAttachPermission,
|
||||
buildNotificationChannelAttachPermission('a'),
|
||||
buildNotificationChannelAttachPermission('b'),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getRuleSaveChecks', () => {
|
||||
it('creates a new rule with its channels', () => {
|
||||
expect(
|
||||
getRuleSaveChecks({ savedChannelIds: [], selectedChannelIds: ['a'] }),
|
||||
).toStrictEqual(getRuleCreateChecks(['a']));
|
||||
});
|
||||
|
||||
it('needs only update when the channels are unchanged', () => {
|
||||
expect(
|
||||
getRuleSaveChecks({
|
||||
ruleId: ID,
|
||||
savedChannelIds: ['a', 'b'],
|
||||
selectedChannelIds: ['b', 'a'],
|
||||
}),
|
||||
).toStrictEqual([UPDATE]);
|
||||
});
|
||||
|
||||
it('attaches added channels and detaches removed ones', () => {
|
||||
expect(
|
||||
getRuleSaveChecks({
|
||||
ruleId: ID,
|
||||
savedChannelIds: ['a', 'b'],
|
||||
selectedChannelIds: ['b', 'c'],
|
||||
}),
|
||||
).toStrictEqual([
|
||||
UPDATE,
|
||||
buildRuleAttachPermission(ID),
|
||||
buildNotificationChannelAttachPermission('c'),
|
||||
buildRuleDetachPermission(ID),
|
||||
buildNotificationChannelDetachPermission('a'),
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -319,6 +319,20 @@ export function CreateAlertProvider(
|
||||
handleAlertTypeChange(AlertTypes.METRICS_BASED_ALERT);
|
||||
}, [handleAlertTypeChange]);
|
||||
|
||||
const savedChannelNames = useMemo(
|
||||
() =>
|
||||
isEditMode && initialAlertState
|
||||
? [
|
||||
...new Set(
|
||||
initialAlertState.threshold.thresholds.flatMap(
|
||||
(threshold) => threshold.channels,
|
||||
),
|
||||
),
|
||||
]
|
||||
: [],
|
||||
[isEditMode, initialAlertState],
|
||||
);
|
||||
|
||||
const { mutate: createAlertRule, isLoading: isCreatingAlertRule } =
|
||||
useCreateRule();
|
||||
|
||||
@@ -350,6 +364,7 @@ export function CreateAlertProvider(
|
||||
isUpdatingAlertRule,
|
||||
isEditMode: isEditMode || false,
|
||||
ruleId: ruleId || '',
|
||||
savedChannelNames,
|
||||
}),
|
||||
[
|
||||
createAlertState,
|
||||
@@ -369,6 +384,7 @@ export function CreateAlertProvider(
|
||||
isUpdatingAlertRule,
|
||||
isEditMode,
|
||||
ruleId,
|
||||
savedChannelNames,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -54,6 +54,7 @@ export interface ICreateAlertContextProps {
|
||||
>;
|
||||
isEditMode: boolean;
|
||||
ruleId: string;
|
||||
savedChannelNames: string[];
|
||||
}
|
||||
|
||||
export interface ICreateAlertProviderProps {
|
||||
@@ -64,13 +65,6 @@ export interface ICreateAlertProviderProps {
|
||||
ruleId?: string;
|
||||
}
|
||||
|
||||
export enum AlertCreationStep {
|
||||
ALERT_DEFINITION = 0,
|
||||
ALERT_CONDITION = 1,
|
||||
EVALUATION_SETTINGS = 2,
|
||||
NOTIFICATION_SETTINGS = 3,
|
||||
}
|
||||
|
||||
export interface AlertState {
|
||||
name: string;
|
||||
labels: Labels;
|
||||
|
||||
55
frontend/src/container/CreateAlert/ruleSaveChecks.ts
Normal file
55
frontend/src/container/CreateAlert/ruleSaveChecks.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { buildNotificationChannelLinkPermissions } from 'lib/authz/hooks/useAuthZ/permissions/notification-channel.permissions';
|
||||
import {
|
||||
buildRuleAttachPermission,
|
||||
buildRuleDetachPermission,
|
||||
buildRuleUpdatePermission,
|
||||
RuleAttachPermission,
|
||||
RuleCreatePermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
|
||||
import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';
|
||||
import { getLinkSaveChecks } from 'lib/authz/utils/getLinkSaveChecks';
|
||||
|
||||
/**
|
||||
* What creating a rule, or sending a test notification, needs: `create`, and
|
||||
* `attach` on the rule and on every channel it notifies.
|
||||
*/
|
||||
export function getRuleCreateChecks(channelIds: string[]): BrandedPermission[] {
|
||||
return getLinkSaveChecks({
|
||||
ownerChecks: [RuleCreatePermission],
|
||||
owner: {
|
||||
attach: RuleAttachPermission,
|
||||
detach: buildRuleDetachPermission('*'),
|
||||
},
|
||||
buildItemPermissions: buildNotificationChannelLinkPermissions,
|
||||
savedIds: [],
|
||||
incomingIds: channelIds,
|
||||
});
|
||||
}
|
||||
|
||||
interface RuleSaveChecksInput {
|
||||
/** Absent for a new rule. */
|
||||
ruleId?: string;
|
||||
savedChannelIds: string[];
|
||||
selectedChannelIds: string[];
|
||||
}
|
||||
|
||||
/** What saving a rule needs, as the rule routes check it. */
|
||||
export function getRuleSaveChecks({
|
||||
ruleId,
|
||||
savedChannelIds,
|
||||
selectedChannelIds,
|
||||
}: RuleSaveChecksInput): BrandedPermission[] {
|
||||
if (!ruleId) {
|
||||
return getRuleCreateChecks(selectedChannelIds);
|
||||
}
|
||||
return getLinkSaveChecks({
|
||||
ownerChecks: [buildRuleUpdatePermission(ruleId)],
|
||||
owner: {
|
||||
attach: buildRuleAttachPermission(ruleId),
|
||||
detach: buildRuleDetachPermission(ruleId),
|
||||
},
|
||||
buildItemPermissions: buildNotificationChannelLinkPermissions,
|
||||
savedIds: savedChannelIds,
|
||||
incomingIds: selectedChannelIds,
|
||||
});
|
||||
}
|
||||
@@ -1,21 +1,5 @@
|
||||
import { AlertTypes } from 'types/api/alerts/alertTypes';
|
||||
|
||||
import {
|
||||
AdvancedOptionsState,
|
||||
AlertState,
|
||||
AlertThresholdState,
|
||||
EvaluationWindowState,
|
||||
NotificationSettingsState,
|
||||
} from './context/types';
|
||||
|
||||
export interface CreateAlertProps {
|
||||
alertType: AlertTypes;
|
||||
}
|
||||
|
||||
export interface GetCreateAlertLocalStateFromAlertDefReturn {
|
||||
basicAlertState: AlertState;
|
||||
thresholdState: AlertThresholdState;
|
||||
advancedOptionsState: AdvancedOptionsState;
|
||||
evaluationWindowState: EvaluationWindowState;
|
||||
notificationSettingsState: NotificationSettingsState;
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user