mirror of
https://github.com/SigNoz/signoz.git
synced 2026-12-01 12:40:48 +00:00
Compare commits
10 Commits
main
...
split/2-au
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d7ecc1034d | ||
|
|
245cca1cb5 | ||
|
|
cc389a3d73 | ||
|
|
322b288daf | ||
|
|
c017fc7436 | ||
|
|
18aab1a293 | ||
|
|
01790cd6dc | ||
|
|
4f20848baa | ||
|
|
bd8000d0c5 | ||
|
|
a1662e453e |
@@ -16034,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
|
||||
@@ -16056,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,
|
||||
@@ -16184,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
|
||||
@@ -16206,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,
|
||||
@@ -28672,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
|
||||
@@ -28694,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,
|
||||
@@ -28846,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
|
||||
@@ -28868,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,
|
||||
|
||||
@@ -15517,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;
|
||||
/**
|
||||
@@ -15528,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;
|
||||
/**
|
||||
@@ -15576,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;
|
||||
/**
|
||||
@@ -15587,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;
|
||||
/**
|
||||
@@ -17131,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;
|
||||
/**
|
||||
@@ -17142,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;
|
||||
/**
|
||||
@@ -17193,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;
|
||||
/**
|
||||
@@ -17204,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;
|
||||
/**
|
||||
|
||||
@@ -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' },
|
||||
},
|
||||
]);
|
||||
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -341,6 +341,7 @@ export function convertBuilderQueriesToV5(
|
||||
spec = {
|
||||
name: queryName,
|
||||
signal: 'logs' as const,
|
||||
...(queryData.source === 'audit' && { source: 'audit' as const }),
|
||||
...baseSpec,
|
||||
aggregations: aggregations as LogAggregation[],
|
||||
};
|
||||
|
||||
@@ -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();
|
||||
const onScrollToLog = jest.fn();
|
||||
|
||||
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,13 @@
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { ILog } from 'types/api/logs/log';
|
||||
|
||||
interface UseLogNavigationParams {
|
||||
logs?: ILog[];
|
||||
interface LogWithId {
|
||||
id: string;
|
||||
}
|
||||
|
||||
interface UseLogNavigationParams<T extends LogWithId> {
|
||||
logs?: T[];
|
||||
activeLogId: string;
|
||||
onNavigateLog?: (log: ILog) => void;
|
||||
onNavigateLog?: (log: T) => void;
|
||||
onScrollToLog?: (id: string) => void;
|
||||
}
|
||||
|
||||
@@ -15,12 +18,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,137 @@
|
||||
import ROUTES from 'constants/routes';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
import {
|
||||
NO_DELAY_USER_EVENT,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
} from 'tests/test-utils';
|
||||
import { IField } from 'types/api/logs/fields';
|
||||
import { ILog } from 'types/api/logs/log';
|
||||
|
||||
import { buildLog } from '../../__tests__/buildLog';
|
||||
import ListLogView from '..';
|
||||
|
||||
jest.mock('react-use', () => ({
|
||||
...jest.requireActual('react-use'),
|
||||
useCopyToClipboard: (): [unknown, jest.Mock] => [null, jest.fn()],
|
||||
}));
|
||||
|
||||
const field = (name: string): IField => ({ name, type: '', dataType: '' });
|
||||
|
||||
function renderRow(
|
||||
props: Partial<React.ComponentProps<typeof ListLogView<ILog>>> = {},
|
||||
route: string = ROUTES.LOGS_EXPLORER,
|
||||
): void {
|
||||
render(
|
||||
<ListLogView
|
||||
logData={buildLog()}
|
||||
linesPerRow={1}
|
||||
fontSize={FontSize.SMALL}
|
||||
selectedFields={[field('body')]}
|
||||
onSetActiveLog={jest.fn()}
|
||||
{...props}
|
||||
/>,
|
||||
undefined,
|
||||
{ initialRoute: route },
|
||||
);
|
||||
}
|
||||
|
||||
describe('ListLogView action buttons', () => {
|
||||
it('shows copy link and context on the Logs Explorer route', () => {
|
||||
renderRow();
|
||||
|
||||
expect(screen.getByTestId('log-line-copy-link')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('log-line-show-context')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides the buttons off the Logs Explorer route', () => {
|
||||
renderRow({}, ROUTES.AUDIT_LOGS);
|
||||
|
||||
expect(screen.queryByTestId('log-line-copy-link')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('log-line-show-context')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows only copy link off the Logs Explorer route when showActions is set', () => {
|
||||
renderRow({ showActions: true }, ROUTES.AUDIT_LOGS);
|
||||
|
||||
expect(screen.getByTestId('log-line-copy-link')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('log-line-show-context')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ListLogView content', () => {
|
||||
it('renders the body', () => {
|
||||
renderRow({ logData: buildLog({ body: 'created dashboard' }) });
|
||||
|
||||
expect(screen.getByTestId('logs-list-row-log-1')).toHaveTextContent(
|
||||
'created dashboard',
|
||||
);
|
||||
});
|
||||
|
||||
it('reads selected fields from the log by default', () => {
|
||||
renderRow({
|
||||
logData: buildLog({ severity_text: 'NOTICE' }),
|
||||
selectedFields: [field('severity_text')],
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('logs-list-row-log-1')).toHaveTextContent('NOTICE');
|
||||
});
|
||||
|
||||
it('reads selected fields through getFieldValue when it is given', () => {
|
||||
renderRow({
|
||||
selectedFields: [field('custom.field')],
|
||||
getFieldValue: (_, fieldName) => `resolved:${fieldName}`,
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('logs-list-row-log-1')).toHaveTextContent(
|
||||
'resolved:custom.field',
|
||||
);
|
||||
});
|
||||
|
||||
it('skips a field the resolver returns nothing for', () => {
|
||||
renderRow({
|
||||
selectedFields: [field('missing')],
|
||||
getFieldValue: () => undefined,
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('logs-list-row-log-1')).not.toHaveTextContent(
|
||||
'missing',
|
||||
);
|
||||
});
|
||||
|
||||
it('renders without an add to query handler', () => {
|
||||
renderRow({
|
||||
selectedFields: [field('custom.field')],
|
||||
getFieldValue: () => 'value',
|
||||
onAddToQuery: undefined,
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('logs-list-row-log-1')).toHaveTextContent('value');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ListLogView row click', () => {
|
||||
it('opens the log on click', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const onSetActiveLog = jest.fn();
|
||||
const logData = buildLog();
|
||||
renderRow({ logData, onSetActiveLog });
|
||||
|
||||
await user.click(screen.getByTestId('logs-list-row-log-1'));
|
||||
|
||||
expect(onSetActiveLog).toHaveBeenCalledWith(logData);
|
||||
});
|
||||
|
||||
it('clears the active log when the active row is clicked', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const onClearActiveLog = jest.fn();
|
||||
const onSetActiveLog = jest.fn();
|
||||
renderRow({ isActiveLog: true, onClearActiveLog, onSetActiveLog });
|
||||
|
||||
await user.click(screen.getByTestId('logs-list-row-log-1'));
|
||||
|
||||
expect(onClearActiveLog).toHaveBeenCalledTimes(1);
|
||||
expect(onSetActiveLog).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -16,12 +16,12 @@ import { getBodyDisplay } from 'lib/logs/logBody';
|
||||
import { useTimezone } from 'providers/Timezone';
|
||||
// interfaces
|
||||
import { IField } from 'types/api/logs/fields';
|
||||
import { ILog } from 'types/api/logs/log';
|
||||
import { coerceToString, isScalarFieldValue } from 'utils/stringUtils';
|
||||
|
||||
// components
|
||||
import AddToQueryHOC, { AddToQueryHOCProps } from '../AddToQueryHOC';
|
||||
import LogLinesActionButtons from '../LogLinesActionButtons/LogLinesActionButtons';
|
||||
import { LogRowData } from '../RawLogView/types';
|
||||
import LogStateIndicator from '../LogStateIndicator/LogStateIndicator';
|
||||
import { getLogIndicatorType } from '../LogStateIndicator/utils';
|
||||
// styles
|
||||
@@ -127,40 +127,44 @@ function LogSelectedField({
|
||||
);
|
||||
}
|
||||
|
||||
type ListLogViewProps = {
|
||||
logData: ILog;
|
||||
type ListLogViewProps<T extends LogRowData> = {
|
||||
logData: T;
|
||||
selectedFields: IField[];
|
||||
onSetActiveLog: (
|
||||
log: ILog,
|
||||
log: T,
|
||||
selectedTab?: (typeof VIEW_TYPES)[keyof typeof VIEW_TYPES],
|
||||
) => void;
|
||||
onAddToQuery: AddToQueryHOCProps['onAddToQuery'];
|
||||
activeLog?: ILog | null;
|
||||
onAddToQuery?: AddToQueryHOCProps['onAddToQuery'];
|
||||
activeLog?: T | null;
|
||||
linesPerRow: number;
|
||||
fontSize: FontSize;
|
||||
handleChangeSelectedView?: ChangeViewFunctionType;
|
||||
isActiveLog?: boolean;
|
||||
onClearActiveLog?: () => void;
|
||||
showActions?: boolean;
|
||||
getFieldValue?: (log: T, fieldName: string) => unknown;
|
||||
};
|
||||
|
||||
function ListLogView({
|
||||
function ListLogView<T extends LogRowData>({
|
||||
logData,
|
||||
selectedFields,
|
||||
onSetActiveLog,
|
||||
onAddToQuery,
|
||||
activeLog,
|
||||
activeLog = null,
|
||||
linesPerRow,
|
||||
fontSize,
|
||||
isActiveLog,
|
||||
onClearActiveLog,
|
||||
}: ListLogViewProps): JSX.Element {
|
||||
showActions = false,
|
||||
getFieldValue,
|
||||
}: ListLogViewProps<T>): JSX.Element {
|
||||
const flattenLogData = useMemo(() => FlatLogData(logData), [logData]);
|
||||
const isBodyJsonEnabled = useIsBodyJsonEnabled();
|
||||
|
||||
const { isHighlighted, isLogsExplorerPage, onLogCopy } = useCopyLogLink(
|
||||
logData.id,
|
||||
);
|
||||
const isReadOnlyLog = !isLogsExplorerPage;
|
||||
const showActionButtons = isLogsExplorerPage || showActions;
|
||||
|
||||
const isDarkMode = useIsDarkMode();
|
||||
|
||||
@@ -249,7 +253,9 @@ function ListLogView({
|
||||
{updatedSelecedFields
|
||||
.filter((field) => !['timestamp', 'body'].includes(field.name))
|
||||
.map((field) => {
|
||||
const value = getLogFieldValue(logData, field.name, isBodyJsonEnabled);
|
||||
const value = getFieldValue
|
||||
? getFieldValue(logData, field.name)
|
||||
: getLogFieldValue(logData, field.name, isBodyJsonEnabled);
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
@@ -268,9 +274,9 @@ function ListLogView({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!isReadOnlyLog && (
|
||||
{showActionButtons && (
|
||||
<LogLinesActionButtons
|
||||
handleShowContext={handleShowContext}
|
||||
handleShowContext={isLogsExplorerPage ? handleShowContext : undefined}
|
||||
onLogCopy={onLogCopy}
|
||||
/>
|
||||
)}
|
||||
@@ -279,13 +285,8 @@ function ListLogView({
|
||||
);
|
||||
}
|
||||
|
||||
ListLogView.defaultProps = {
|
||||
activeLog: null,
|
||||
handleChangeSelectedView: undefined,
|
||||
};
|
||||
|
||||
LogGeneralField.defaultProps = {
|
||||
linesPerRow: 1,
|
||||
};
|
||||
|
||||
export default memo(ListLogView);
|
||||
export default memo(ListLogView) as typeof ListLogView;
|
||||
|
||||
@@ -5,7 +5,7 @@ import { Button, Tooltip } from 'antd';
|
||||
import './LogLinesActionButtons.styles.scss';
|
||||
|
||||
export interface LogLinesActionButtonsProps {
|
||||
handleShowContext: MouseEventHandler<HTMLElement>;
|
||||
handleShowContext?: MouseEventHandler<HTMLElement>;
|
||||
onLogCopy: MouseEventHandler<HTMLElement>;
|
||||
customClassName?: string;
|
||||
}
|
||||
@@ -17,15 +17,17 @@ function LogLinesActionButtons({
|
||||
}: LogLinesActionButtonsProps): JSX.Element {
|
||||
return (
|
||||
<div className={`log-line-action-buttons ${customClassName}`}>
|
||||
<Tooltip title="Show in Context">
|
||||
<Button
|
||||
size="small"
|
||||
icon={<TextSelect size={14} />}
|
||||
className="show-context-btn"
|
||||
onClick={handleShowContext}
|
||||
data-testid="log-line-show-context"
|
||||
/>
|
||||
</Tooltip>
|
||||
{handleShowContext && (
|
||||
<Tooltip title="Show in Context">
|
||||
<Button
|
||||
size="small"
|
||||
icon={<TextSelect size={14} />}
|
||||
className="show-context-btn"
|
||||
onClick={handleShowContext}
|
||||
data-testid="log-line-show-context"
|
||||
/>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tooltip title="Copy Link">
|
||||
<Button
|
||||
size="small"
|
||||
@@ -40,6 +42,7 @@ function LogLinesActionButtons({
|
||||
}
|
||||
|
||||
LogLinesActionButtons.defaultProps = {
|
||||
handleShowContext: undefined,
|
||||
customClassName: '',
|
||||
};
|
||||
|
||||
|
||||
@@ -6,6 +6,10 @@
|
||||
width: 3px;
|
||||
border-radius: 50px;
|
||||
|
||||
&.flush {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
&.small {
|
||||
min-height: 16px;
|
||||
}
|
||||
|
||||
@@ -36,4 +36,20 @@ describe('LogStateIndicator', () => {
|
||||
'severity-error-0',
|
||||
);
|
||||
});
|
||||
|
||||
it('drops its margin when flush', () => {
|
||||
render(
|
||||
<LogStateIndicator severityText="INFO" fontSize={FontSize.MEDIUM} flush />,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('log-state-indicator-line')).toHaveClass('flush');
|
||||
});
|
||||
|
||||
it('keeps its margin by default', () => {
|
||||
render(<LogStateIndicator severityText="INFO" fontSize={FontSize.MEDIUM} />);
|
||||
|
||||
expect(screen.getByTestId('log-state-indicator-line')).not.toHaveClass(
|
||||
'flush',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -130,17 +130,19 @@ function LogStateIndicator({
|
||||
fontSize,
|
||||
severityText,
|
||||
severityNumber,
|
||||
flush = false,
|
||||
}: {
|
||||
fontSize: FontSize;
|
||||
severityText?: string;
|
||||
severityNumber?: number;
|
||||
flush?: boolean;
|
||||
}): JSX.Element {
|
||||
const severityClass = getSeverityClass(severityText, severityNumber);
|
||||
|
||||
return (
|
||||
<div className="log-state-indicator" data-testid="log-state-indicator">
|
||||
<div
|
||||
className={cx('line', fontSize, severityClass)}
|
||||
className={cx('line', fontSize, severityClass, { flush })}
|
||||
data-testid="log-state-indicator-line"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -90,7 +90,10 @@ const getLogType = (
|
||||
return defaultType;
|
||||
};
|
||||
|
||||
export const getLogIndicatorType = (logData: ILog): string => {
|
||||
export type LogIndicatorData = Pick<ILog, 'severity_text' | 'severity_number'> &
|
||||
Partial<Pick<ILog, 'attributes_string'>>;
|
||||
|
||||
export const getLogIndicatorType = (logData: LogIndicatorData): string => {
|
||||
const defaultType = logData.attributes_string?.log_level || LogType.INFO;
|
||||
// convert the severity_text to upper case for the comparison to support case insensitive values
|
||||
return getLogType(
|
||||
|
||||
@@ -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" />;
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import ROUTES from 'constants/routes';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
import {
|
||||
NO_DELAY_USER_EVENT,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
} from 'tests/test-utils';
|
||||
import { IField } from 'types/api/logs/fields';
|
||||
import { ILog } from 'types/api/logs/log';
|
||||
|
||||
import { buildLog } from '../../__tests__/buildLog';
|
||||
import RawLogView from '..';
|
||||
|
||||
jest.mock('react-use', () => ({
|
||||
...jest.requireActual('react-use'),
|
||||
useCopyToClipboard: (): [unknown, jest.Mock] => [null, jest.fn()],
|
||||
}));
|
||||
|
||||
const field = (name: string): IField => ({ name, type: '', dataType: '' });
|
||||
const bodyField = [field('body')];
|
||||
|
||||
function renderRow(
|
||||
props: Partial<React.ComponentProps<typeof RawLogView<ILog>>> = {},
|
||||
route: string = ROUTES.LOGS_EXPLORER,
|
||||
): void {
|
||||
render(
|
||||
<RawLogView
|
||||
data={buildLog()}
|
||||
linesPerRow={1}
|
||||
fontSize={FontSize.SMALL}
|
||||
selectedFields={bodyField}
|
||||
{...props}
|
||||
/>,
|
||||
undefined,
|
||||
{ initialRoute: route },
|
||||
);
|
||||
}
|
||||
|
||||
describe('RawLogView action buttons', () => {
|
||||
it('shows copy link and context on the Logs Explorer route', () => {
|
||||
renderRow();
|
||||
|
||||
expect(screen.getByTestId('log-line-copy-link')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('log-line-show-context')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides the buttons off the Logs Explorer route', () => {
|
||||
renderRow({}, ROUTES.AUDIT_LOGS);
|
||||
|
||||
expect(screen.queryByTestId('log-line-copy-link')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('log-line-show-context')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows only copy link off the Logs Explorer route when showActions is set', () => {
|
||||
renderRow({ showActions: true }, ROUTES.AUDIT_LOGS);
|
||||
|
||||
expect(screen.getByTestId('log-line-copy-link')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('log-line-show-context')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides the buttons for a read-only row even with showActions', () => {
|
||||
renderRow({ showActions: true, isReadOnly: true }, ROUTES.AUDIT_LOGS);
|
||||
|
||||
expect(screen.queryByTestId('log-line-copy-link')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('RawLogView content', () => {
|
||||
it('renders the body', () => {
|
||||
renderRow({ data: buildLog({ body: 'created dashboard' }) });
|
||||
|
||||
expect(screen.getByTestId('logs-raw-row-log-1')).toHaveTextContent(
|
||||
'created dashboard',
|
||||
);
|
||||
});
|
||||
|
||||
it('reads selected fields from the log by default', () => {
|
||||
renderRow({
|
||||
data: buildLog({ severity_text: 'NOTICE' }),
|
||||
selectedFields: [field('severity_text'), field('body')],
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('logs-raw-row-log-1')).toHaveTextContent('NOTICE');
|
||||
});
|
||||
|
||||
it('reads selected fields through getFieldValue when it is given', () => {
|
||||
renderRow({
|
||||
selectedFields: [field('custom.field'), field('body')],
|
||||
getFieldValue: (_, fieldName) => `resolved:${fieldName}`,
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('logs-raw-row-log-1')).toHaveTextContent(
|
||||
'resolved:custom.field',
|
||||
);
|
||||
});
|
||||
|
||||
it('skips a field the resolver returns nothing for', () => {
|
||||
renderRow({
|
||||
selectedFields: [field('missing'), field('body')],
|
||||
getFieldValue: () => undefined,
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('logs-raw-row-log-1')).toHaveTextContent(
|
||||
/^a log body$/,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('RawLogView row click', () => {
|
||||
it('opens the log on click', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const onSetActiveLog = jest.fn();
|
||||
const data = buildLog();
|
||||
renderRow({ data, onSetActiveLog });
|
||||
|
||||
await user.click(screen.getByTestId('logs-raw-row-log-1'));
|
||||
|
||||
expect(onSetActiveLog).toHaveBeenCalledWith(data);
|
||||
});
|
||||
|
||||
it('clears the active log when the active row is clicked', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const onClearActiveLog = jest.fn();
|
||||
const onSetActiveLog = jest.fn();
|
||||
renderRow({ isActiveLog: true, onClearActiveLog, onSetActiveLog });
|
||||
|
||||
await user.click(screen.getByTestId('logs-raw-row-log-1'));
|
||||
|
||||
expect(onClearActiveLog).toHaveBeenCalledTimes(1);
|
||||
expect(onSetActiveLog).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -25,22 +25,24 @@ import LogStateIndicator from '../LogStateIndicator/LogStateIndicator';
|
||||
import { getLogIndicatorType } from '../LogStateIndicator/utils';
|
||||
// styles
|
||||
import { InfoIconWrapper, RawLogContent, RawLogViewContainer } from './styles';
|
||||
import { RawLogViewProps } from './types';
|
||||
import { LogRowData, RawLogViewProps } from './types';
|
||||
|
||||
function RawLogView({
|
||||
isActiveLog,
|
||||
isReadOnly,
|
||||
function RawLogView<T extends LogRowData>({
|
||||
isActiveLog = false,
|
||||
isReadOnly = false,
|
||||
data,
|
||||
linesPerRow,
|
||||
isTextOverflowEllipsisDisabled,
|
||||
isHighlighted,
|
||||
isTextOverflowEllipsisDisabled = false,
|
||||
isHighlighted = false,
|
||||
helpTooltip,
|
||||
showActions = false,
|
||||
selectedFields = [],
|
||||
getFieldValue,
|
||||
fontSize,
|
||||
onLogClick,
|
||||
onSetActiveLog,
|
||||
onClearActiveLog,
|
||||
}: RawLogViewProps): JSX.Element {
|
||||
}: RawLogViewProps<T>): JSX.Element {
|
||||
const {
|
||||
isHighlighted: isUrlHighlighted,
|
||||
isLogsExplorerPage,
|
||||
@@ -49,7 +51,7 @@ function RawLogView({
|
||||
const isBodyJsonEnabled = useIsBodyJsonEnabled();
|
||||
|
||||
const isDarkMode = useIsDarkMode();
|
||||
const isReadOnlyLog = !isLogsExplorerPage || isReadOnly;
|
||||
const showActionButtons = !isReadOnly && (isLogsExplorerPage || showActions);
|
||||
|
||||
const logType = getLogIndicatorType(data);
|
||||
|
||||
@@ -60,7 +62,11 @@ function RawLogView({
|
||||
|
||||
const attributesValues = updatedSelecedFields
|
||||
.filter((field) => !['timestamp', 'body'].includes(field.name))
|
||||
.map((field) => getLogFieldValue(data, field.name, isBodyJsonEnabled))
|
||||
.map((field) =>
|
||||
getFieldValue
|
||||
? getFieldValue(data, field.name)
|
||||
: getLogFieldValue(data, field.name, isBodyJsonEnabled),
|
||||
)
|
||||
.filter((attribute) => {
|
||||
// loadash isEmpty doesnot work with numbers
|
||||
if (isNumber(attribute) || isBoolean(attribute)) {
|
||||
@@ -196,20 +202,13 @@ function RawLogView({
|
||||
dangerouslySetInnerHTML={html}
|
||||
/>
|
||||
|
||||
{!isReadOnlyLog && (
|
||||
{showActionButtons && (
|
||||
<LogLinesActionButtons
|
||||
handleShowContext={handleShowContext}
|
||||
handleShowContext={isLogsExplorerPage ? handleShowContext : undefined}
|
||||
onLogCopy={onLogCopy}
|
||||
/>
|
||||
)}
|
||||
</RawLogViewContainer>
|
||||
);
|
||||
}
|
||||
RawLogView.defaultProps = {
|
||||
isActiveLog: false,
|
||||
isReadOnly: false,
|
||||
isTextOverflowEllipsisDisabled: false,
|
||||
isHighlighted: false,
|
||||
};
|
||||
|
||||
export default memo(RawLogView);
|
||||
export default memo(RawLogView) as typeof RawLogView;
|
||||
|
||||
@@ -4,21 +4,27 @@ import { ChangeViewFunctionType } from 'hooks/useHandleExplorerTabChange';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
import { IField } from 'types/api/logs/fields';
|
||||
import { ILog } from 'types/api/logs/log';
|
||||
import { LogIndicatorData } from '../LogStateIndicator/utils';
|
||||
|
||||
export interface RawLogViewProps {
|
||||
export type LogRowData = Pick<ILog, 'id' | 'timestamp' | 'body'> &
|
||||
LogIndicatorData;
|
||||
|
||||
export interface RawLogViewProps<T extends LogRowData = ILog> {
|
||||
isActiveLog?: boolean;
|
||||
isReadOnly?: boolean;
|
||||
isTextOverflowEllipsisDisabled?: boolean;
|
||||
isHighlighted?: boolean;
|
||||
helpTooltip?: string;
|
||||
data: ILog;
|
||||
showActions?: boolean;
|
||||
data: T;
|
||||
linesPerRow: number;
|
||||
fontSize: FontSize;
|
||||
selectedFields?: IField[];
|
||||
onLogClick?: (log: ILog, event: MouseEvent) => void;
|
||||
getFieldValue?: (log: T, fieldName: string) => unknown;
|
||||
onLogClick?: (log: T, event: MouseEvent) => void;
|
||||
handleChangeSelectedView?: ChangeViewFunctionType;
|
||||
onSetActiveLog?: (
|
||||
log: ILog,
|
||||
log: T,
|
||||
selectedTab?: (typeof VIEW_TYPES)[keyof typeof VIEW_TYPES],
|
||||
) => void;
|
||||
onClearActiveLog?: () => void;
|
||||
|
||||
24
frontend/src/components/Logs/__tests__/buildLog.ts
Normal file
24
frontend/src/components/Logs/__tests__/buildLog.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { ILog } from 'types/api/logs/log';
|
||||
|
||||
export function buildLog(overrides: Partial<ILog> = {}): ILog {
|
||||
return {
|
||||
id: 'log-1',
|
||||
timestamp: '2024-01-01T10:00:00.000Z',
|
||||
date: '2024-01-01T10:00:00.000Z',
|
||||
body: 'a log body',
|
||||
severityText: 'INFO',
|
||||
severityNumber: 9,
|
||||
severity_text: 'INFO',
|
||||
severity_number: 9,
|
||||
traceFlags: 0,
|
||||
traceId: '',
|
||||
spanID: '',
|
||||
attributesString: {},
|
||||
attributesInt: {},
|
||||
attributesFloat: {},
|
||||
attributes_string: {},
|
||||
resources_string: {},
|
||||
scope_string: {},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
@@ -238,7 +238,7 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
|
||||
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}
|
||||
@@ -260,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}
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -15,3 +18,10 @@ export const QUICK_FILTER_SOURCE_TO_SIGNAL: Record<
|
||||
[QuickFiltersSource.INFRA_MONITORING]: TelemetrytypesSignalDTO.metrics,
|
||||
[QuickFiltersSource.AUDIT_LOGS]: TelemetrytypesSignalDTO.logs,
|
||||
};
|
||||
|
||||
export const QUICK_FILTER_SOURCE_TO_SOURCE: Partial<
|
||||
Record<QuickFiltersSource, TelemetrytypesSourceDTO>
|
||||
> = {
|
||||
[QuickFiltersSource.METER_EXPLORER]: TelemetrytypesSourceDTO.meter,
|
||||
[QuickFiltersSource.AUDIT_LOGS]: TelemetrytypesSourceDTO.audit,
|
||||
};
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -16,7 +16,7 @@ import { getLogIndicatorType } from 'components/Logs/LogStateIndicator/utils';
|
||||
import RawLogView from 'components/Logs/RawLogView';
|
||||
import { useLogsTableColumns } from 'components/Logs/TableView/useLogsTableColumns';
|
||||
import OverlayScrollbar from 'components/OverlayScrollbar/OverlayScrollbar';
|
||||
import Spinner from 'components/Spinner';
|
||||
import { LogsLoadingFooter } from 'components/Logs/LogsLoadingFooter/LogsLoadingFooter';
|
||||
import type { TanStackTableHandle } from 'components/TanStackTableView';
|
||||
import TanStackTable from 'components/TanStackTableView';
|
||||
import type { TableColumnDef } from 'components/TanStackTableView/types';
|
||||
@@ -51,9 +51,6 @@ import {
|
||||
import styles from './LogsExplorerList.module.scss';
|
||||
import './LogsExplorerList.style.scss';
|
||||
|
||||
function Footer(): JSX.Element {
|
||||
return <Spinner height={20} tip="Getting Logs" />;
|
||||
}
|
||||
function LogsExplorerList({
|
||||
isLoading,
|
||||
isFetching,
|
||||
@@ -195,7 +192,7 @@ function LogsExplorerList({
|
||||
const renderContent = useMemo(() => {
|
||||
const components = isLoading
|
||||
? {
|
||||
Footer,
|
||||
Footer: LogsLoadingFooter,
|
||||
}
|
||||
: {};
|
||||
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import {
|
||||
MetrictypesSpaceAggregationDTO,
|
||||
MetrictypesTimeAggregationDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { OPERATORS } from 'constants/queryBuilder';
|
||||
import {
|
||||
BaseAutocompleteData,
|
||||
DataTypes,
|
||||
} from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { DataSource, QueryBuilderData } from 'types/common/queryBuilder';
|
||||
import {
|
||||
DataSource,
|
||||
MetricAggregateOperator,
|
||||
QueryBuilderData,
|
||||
} from 'types/common/queryBuilder';
|
||||
|
||||
import { FORMULA, MetricsType, WidgetKeys } from '../constant';
|
||||
import { DatabaseCallProps, DatabaseCallsRPSProps } from '../types';
|
||||
@@ -55,8 +55,8 @@ export const databaseCallsRPS = ({
|
||||
const legends = [legend];
|
||||
const dataSource = DataSource.METRICS;
|
||||
|
||||
const timeAggregateOperators = [MetrictypesTimeAggregationDTO.rate];
|
||||
const spaceAggregateOperators = [MetrictypesSpaceAggregationDTO.sum];
|
||||
const timeAggregateOperators = [MetricAggregateOperator.RATE];
|
||||
const spaceAggregateOperators = [MetricAggregateOperator.SUM];
|
||||
|
||||
return getQueryBuilderQueries({
|
||||
autocompleteData,
|
||||
@@ -113,12 +113,12 @@ export const databaseCallsAvgDuration = ({
|
||||
const legendFormulas = ['Average Duration'];
|
||||
const expressions = [FORMULA.DATABASE_CALLS_AVG_DURATION];
|
||||
const timeAggregateOperators = [
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
];
|
||||
const dataSource = DataSource.METRICS;
|
||||
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import {
|
||||
MetrictypesSpaceAggregationDTO,
|
||||
MetrictypesTimeAggregationDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { OPERATORS } from 'constants/queryBuilder';
|
||||
import {
|
||||
BaseAutocompleteData,
|
||||
DataTypes,
|
||||
} from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { DataSource, QueryBuilderData } from 'types/common/queryBuilder';
|
||||
import {
|
||||
DataSource,
|
||||
MetricAggregateOperator,
|
||||
QueryBuilderData,
|
||||
} from 'types/common/queryBuilder';
|
||||
|
||||
import { FORMULA, MetricsType, WidgetKeys } from '../constant';
|
||||
import {
|
||||
@@ -88,12 +88,12 @@ export const externalCallErrorPercent = ({
|
||||
const additionalItems = [additionalItemsA, additionalItemsB];
|
||||
|
||||
const timeAggregateOperators = [
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
];
|
||||
const legends = [legend, legend];
|
||||
const dataSource = DataSource.METRICS;
|
||||
@@ -149,12 +149,12 @@ export const externalCallDuration = ({
|
||||
const additionalItems = [additionalItemsA, additionalItemsA];
|
||||
const legends = [legend, legend];
|
||||
const timeAggregateOperators = [
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
];
|
||||
const dataSource = DataSource.METRICS;
|
||||
|
||||
@@ -202,8 +202,8 @@ export const externalCallRpsByAddress = ({
|
||||
const legends = [legend];
|
||||
const dataSource = DataSource.METRICS;
|
||||
|
||||
const timeAggregateOperators = [MetrictypesTimeAggregationDTO.rate];
|
||||
const spaceAggregateOperators = [MetrictypesSpaceAggregationDTO.sum];
|
||||
const timeAggregateOperators = [MetricAggregateOperator.RATE];
|
||||
const spaceAggregateOperators = [MetricAggregateOperator.SUM];
|
||||
|
||||
return getQueryBuilderQueries({
|
||||
autocompleteData,
|
||||
@@ -252,12 +252,12 @@ export const externalCallDurationByAddress = ({
|
||||
const additionalItems = [additionalItemsA, additionalItemsA];
|
||||
const legends = [legend, legend];
|
||||
const timeAggregateOperators = [
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
];
|
||||
const dataSource = DataSource.METRICS;
|
||||
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import {
|
||||
MetrictypesComparisonSpaceAggregationParamDTO,
|
||||
MetrictypesSpaceAggregationDTO,
|
||||
MetrictypesTimeAggregationDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { MetrictypesComparisonSpaceAggregationParamDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
alphabet,
|
||||
initialFormulaBuilderFormValues,
|
||||
@@ -11,6 +7,7 @@ import {
|
||||
import getStep from 'lib/getStep';
|
||||
import store from 'store';
|
||||
import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { SpaceAggregation, TimeAggregation } from 'types/api/v5/queryRange';
|
||||
import {
|
||||
DataSource,
|
||||
MetricAggregateOperator,
|
||||
@@ -37,8 +34,8 @@ const getAggregations = ({
|
||||
dataSource: DataSource;
|
||||
key: string;
|
||||
aggregateOperator: string;
|
||||
timeAggregation: MetrictypesTimeAggregationDTO;
|
||||
spaceAggregation: MetrictypesSpaceAggregationDTO;
|
||||
timeAggregation: MetricAggregateOperator;
|
||||
spaceAggregation: MetricAggregateOperator;
|
||||
comparisonSpaceAggregationParam?: MetrictypesComparisonSpaceAggregationParamDTO;
|
||||
}): IBuilderQuery['aggregations'] =>
|
||||
dataSource === DataSource.TRACES
|
||||
@@ -47,8 +44,8 @@ const getAggregations = ({
|
||||
{
|
||||
metricName: key,
|
||||
temporality: '',
|
||||
timeAggregation,
|
||||
spaceAggregation,
|
||||
timeAggregation: timeAggregation as TimeAggregation,
|
||||
spaceAggregation: spaceAggregation as SpaceAggregation,
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
...(comparisonSpaceAggregationParam && {
|
||||
comparisonSpaceAggregationParam,
|
||||
@@ -127,6 +124,7 @@ export const getQueryBuilderQuerieswithFormula = ({
|
||||
timeAggregateOperators,
|
||||
spaceAggregateOperators,
|
||||
comparisonSpaceAggregationParams = [],
|
||||
stepInterval,
|
||||
dataSource,
|
||||
}: BuilderQuerieswithFormulaProps): QueryBuilderData => ({
|
||||
queryFormulas: expressions.map((expression, index) => ({
|
||||
@@ -158,7 +156,7 @@ export const getQueryBuilderQuerieswithFormula = ({
|
||||
items: additionalItems[index],
|
||||
op: 'AND',
|
||||
},
|
||||
stepInterval: null,
|
||||
stepInterval: stepInterval ?? null,
|
||||
dataSource,
|
||||
})),
|
||||
queryTraceOperator: [],
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import {
|
||||
MetrictypesSpaceAggregationDTO,
|
||||
MetrictypesTimeAggregationDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { MetrictypesComparisonSpaceAggregationParamDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { OPERATORS } from 'constants/queryBuilder';
|
||||
import {
|
||||
BaseAutocompleteData,
|
||||
DataTypes,
|
||||
} from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { DataSource, QueryBuilderData } from 'types/common/queryBuilder';
|
||||
import {
|
||||
DataSource,
|
||||
MetricAggregateOperator,
|
||||
QueryBuilderData,
|
||||
} from 'types/common/queryBuilder';
|
||||
|
||||
import {
|
||||
FORMULA,
|
||||
@@ -25,11 +26,11 @@ import {
|
||||
LatencyProps,
|
||||
OperationPerSecProps,
|
||||
} from '../Tabs/types';
|
||||
import { getNearestHighestBucketValue } from '../utils';
|
||||
import {
|
||||
getQueryBuilderQueries,
|
||||
getQueryBuilderQuerieswithFormula,
|
||||
} from './MetricsPageQueriesFactory';
|
||||
import { getLatencyAtOrBelowAggregation } from './utils';
|
||||
|
||||
export const latency = ({
|
||||
servicename,
|
||||
@@ -42,7 +43,7 @@ export const latency = ({
|
||||
const newAutoCompleteData: BaseAutocompleteData = {
|
||||
key: isSpanMetricEnable
|
||||
? signozLatencyBucketMetrics
|
||||
: WidgetKeys.DurationNano,
|
||||
: WidgetKeys.SpanDurationNano,
|
||||
dataType: DataTypes.Float64,
|
||||
type: isSpanMetricEnable ? '' : MetricsType.Tag,
|
||||
};
|
||||
@@ -82,14 +83,14 @@ export const latency = ({
|
||||
const queryNameAndExpression = QUERYNAME_AND_EXPRESSION;
|
||||
|
||||
const timeAggregateOperators = [
|
||||
MetrictypesTimeAggregationDTO[''],
|
||||
MetrictypesTimeAggregationDTO[''],
|
||||
MetrictypesTimeAggregationDTO[''],
|
||||
MetricAggregateOperator.EMPTY,
|
||||
MetricAggregateOperator.EMPTY,
|
||||
MetricAggregateOperator.EMPTY,
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetrictypesSpaceAggregationDTO.p50,
|
||||
MetrictypesSpaceAggregationDTO.p90,
|
||||
MetrictypesSpaceAggregationDTO.p99,
|
||||
MetricAggregateOperator.P50,
|
||||
MetricAggregateOperator.P90,
|
||||
MetricAggregateOperator.P99,
|
||||
];
|
||||
|
||||
return getQueryBuilderQueries({
|
||||
@@ -108,17 +109,33 @@ export const apDexMetricsQueryBuilderQueries = ({
|
||||
servicename,
|
||||
tagFilterItems,
|
||||
topLevelOperationsRoute,
|
||||
threshold,
|
||||
threashold,
|
||||
delta,
|
||||
metricsBuckets,
|
||||
}: ApDexMetricsQueryBuilderQueriesProps): QueryBuilderData => {
|
||||
const satisfied = getLatencyAtOrBelowAggregation(
|
||||
threshold * 1000,
|
||||
metricsBuckets,
|
||||
);
|
||||
const tolerating = getLatencyAtOrBelowAggregation(
|
||||
threshold * 1000 * 4,
|
||||
metricsBuckets,
|
||||
);
|
||||
// the comparison count stops at the largest finite bucket, so a threshold past it
|
||||
// reads the count metric, which is the +Inf bucket
|
||||
const countAtOrBelow = (
|
||||
ms: number,
|
||||
): {
|
||||
key: string;
|
||||
spaceAggregation: MetricAggregateOperator;
|
||||
param?: MetrictypesComparisonSpaceAggregationParamDTO;
|
||||
} => {
|
||||
const bucket = getNearestHighestBucketValue(ms, metricsBuckets);
|
||||
return bucket === '+Inf'
|
||||
? {
|
||||
key: WidgetKeys.SignozLatencyCount,
|
||||
spaceAggregation: MetricAggregateOperator.SUM,
|
||||
}
|
||||
: {
|
||||
key: WidgetKeys.SignozLatencyBucket,
|
||||
spaceAggregation: MetricAggregateOperator.COUNT,
|
||||
param: { operator: '<=', threshold: Number(bucket) },
|
||||
};
|
||||
};
|
||||
const satisfied = countAtOrBelow(threashold * 1000);
|
||||
const tolerating = countAtOrBelow(threashold * 1000 * 4);
|
||||
|
||||
const autoCompleteDataA: BaseAutocompleteData = {
|
||||
key: WidgetKeys.SignozLatencyCount,
|
||||
@@ -196,27 +213,63 @@ export const apDexMetricsQueryBuilderQueries = ({
|
||||
...tagFilterItems,
|
||||
];
|
||||
|
||||
const filterItemC: TagFilterItem[] = [
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.StatusCode,
|
||||
dataType: DataTypes.String,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS['!='],
|
||||
value: 'STATUS_CODE_ERROR',
|
||||
},
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.OTelServiceName,
|
||||
dataType: DataTypes.String,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS['='],
|
||||
value: servicename,
|
||||
},
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.Operation,
|
||||
dataType: DataTypes.String,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS.IN,
|
||||
value: [...topLevelOperationsRoute],
|
||||
},
|
||||
...tagFilterItems,
|
||||
];
|
||||
|
||||
const autocompleteData = [
|
||||
autoCompleteDataA,
|
||||
autoCompleteDataB,
|
||||
autoCompleteDataC,
|
||||
];
|
||||
|
||||
const additionalItems = [filterItemA, filterItemB, filterItemB];
|
||||
const additionalItems = [filterItemA, filterItemB, filterItemC];
|
||||
const legends = [GraphTitle.APDEX];
|
||||
const disabled = Array(3).fill(true);
|
||||
const expressions = [FORMULA.APDEX];
|
||||
const expressions = delta
|
||||
? [FORMULA.APDEX_DELTA_SPAN_METRICS]
|
||||
: [FORMULA.APDEX_CUMULATIVE_SPAN_METRICS];
|
||||
const legendFormulas = [GraphTitle.APDEX];
|
||||
// v5 forces increase on histograms, so the total matches it
|
||||
const timeAggregateOperators = [
|
||||
MetrictypesTimeAggregationDTO.increase,
|
||||
MetrictypesTimeAggregationDTO.increase,
|
||||
MetrictypesTimeAggregationDTO.increase,
|
||||
MetricAggregateOperator.INCREASE,
|
||||
MetricAggregateOperator.INCREASE,
|
||||
MetricAggregateOperator.INCREASE,
|
||||
];
|
||||
|
||||
// a plain sum keeps the le label on B and C, and the formula then cannot join them
|
||||
const spaceAggregateOperators = [
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetricAggregateOperator.SUM,
|
||||
satisfied.spaceAggregation,
|
||||
tolerating.spaceAggregation,
|
||||
];
|
||||
@@ -283,8 +336,8 @@ export const operationPerSec = ({
|
||||
const legends = OPERATION_LEGENDS;
|
||||
const dataSource = DataSource.METRICS;
|
||||
|
||||
const timeAggregateOperators = [MetrictypesTimeAggregationDTO.rate];
|
||||
const spaceAggregateOperators = [MetrictypesSpaceAggregationDTO.sum];
|
||||
const timeAggregateOperators = [MetricAggregateOperator.RATE];
|
||||
const spaceAggregateOperators = [MetricAggregateOperator.SUM];
|
||||
|
||||
return getQueryBuilderQueries({
|
||||
autocompleteData,
|
||||
@@ -378,12 +431,12 @@ export const errorPercentage = ({
|
||||
const expressions = [FORMULA.ERROR_PERCENTAGE];
|
||||
const legendFormulas = [GraphTitle.ERROR_PERCENTAGE];
|
||||
const timeAggregateOperators = [
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
];
|
||||
const dataSource = DataSource.METRICS;
|
||||
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import {
|
||||
MetrictypesSpaceAggregationDTO,
|
||||
MetrictypesTimeAggregationDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { OPERATORS } from 'constants/queryBuilder';
|
||||
import {
|
||||
BaseAutocompleteData,
|
||||
DataTypes,
|
||||
} from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { DataSource, QueryBuilderData } from 'types/common/queryBuilder';
|
||||
import {
|
||||
DataSource,
|
||||
MetricAggregateOperator,
|
||||
QueryBuilderData,
|
||||
} from 'types/common/queryBuilder';
|
||||
|
||||
import {
|
||||
GraphTitle,
|
||||
@@ -112,20 +112,20 @@ export const topOperationQueries = ({
|
||||
KeyOperationTableHeader.NUM_OF_CALLS,
|
||||
];
|
||||
const timeAggregateOperators = [
|
||||
MetrictypesTimeAggregationDTO[''],
|
||||
MetrictypesTimeAggregationDTO[''],
|
||||
MetrictypesTimeAggregationDTO[''],
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetricAggregateOperator.EMPTY,
|
||||
MetricAggregateOperator.EMPTY,
|
||||
MetricAggregateOperator.EMPTY,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetrictypesSpaceAggregationDTO.p50,
|
||||
MetrictypesSpaceAggregationDTO.p90,
|
||||
MetrictypesSpaceAggregationDTO.p99,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetricAggregateOperator.P50,
|
||||
MetricAggregateOperator.P90,
|
||||
MetricAggregateOperator.P99,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
];
|
||||
const expressions = ['D*100/E'];
|
||||
const legendFormulas = [GraphTitle.ERROR_PERCENTAGE];
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { prepareQueryRangePayloadV5 } from 'api/v5/queryRange/prepareQueryRangePayloadV5';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { QueryBuilderData } from 'types/common/queryBuilder';
|
||||
import { QueryBuilderFormula, QueryEnvelope } from 'types/api/v5/queryRange';
|
||||
import { QueryEnvelope } from 'types/api/v5/queryRange';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
|
||||
import {
|
||||
@@ -102,7 +102,8 @@ describe('service details queries on v5', () => {
|
||||
servicename: 'frontend',
|
||||
tagFilterItems: [],
|
||||
topLevelOperationsRoute: ['GET /'],
|
||||
threshold: 0.5,
|
||||
threashold: 0.5,
|
||||
delta: true,
|
||||
metricsBuckets: [100, 250, 500, 1000, 2000, 5000],
|
||||
}),
|
||||
);
|
||||
@@ -138,11 +139,6 @@ describe('service details queries on v5', () => {
|
||||
"status.code != 'STATUS_CODE_ERROR' AND service.name = 'frontend' AND operation in ['GET /']",
|
||||
},
|
||||
]);
|
||||
expect(
|
||||
queries
|
||||
.filter((query) => query.type === 'builder_formula')
|
||||
.map((query) => (query.spec as QueryBuilderFormula).expression),
|
||||
).toStrictEqual(['((B + C)/2)/A']);
|
||||
});
|
||||
|
||||
it('reads the count metric when the apdex threshold is past the largest bucket', () => {
|
||||
@@ -151,7 +147,8 @@ describe('service details queries on v5', () => {
|
||||
servicename: 'frontend',
|
||||
tagFilterItems: [],
|
||||
topLevelOperationsRoute: ['GET /'],
|
||||
threshold: 0.5,
|
||||
threashold: 0.5,
|
||||
delta: true,
|
||||
metricsBuckets: [100, 250, 500, 1000],
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
import { MetrictypesSpaceAggregationDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { WidgetKeys } from '../constant';
|
||||
import { LatencyAtOrBelowAggregation } from '../Tabs/types';
|
||||
import { getNearestHighestBucketValue } from '../utils';
|
||||
|
||||
// the comparison count stops at the largest finite bucket, so a threshold past it
|
||||
// reads the count metric, which is the +Inf bucket
|
||||
export const getLatencyAtOrBelowAggregation = (
|
||||
thresholdMs: number,
|
||||
buckets: number[],
|
||||
): LatencyAtOrBelowAggregation => {
|
||||
const bucket = getNearestHighestBucketValue(thresholdMs, buckets);
|
||||
return bucket === undefined
|
||||
? {
|
||||
key: WidgetKeys.SignozLatencyCount,
|
||||
spaceAggregation: MetrictypesSpaceAggregationDTO.sum,
|
||||
}
|
||||
: {
|
||||
key: WidgetKeys.SignozLatencyBucket,
|
||||
spaceAggregation: MetrictypesSpaceAggregationDTO.count,
|
||||
param: { operator: '<=', threshold: bucket },
|
||||
};
|
||||
};
|
||||
@@ -24,6 +24,7 @@ import { v4 as uuid } from 'uuid';
|
||||
import { ApDexMetricsProps } from './types';
|
||||
|
||||
function ApDexMetrics({
|
||||
delta,
|
||||
metricsBuckets,
|
||||
thresholdValue,
|
||||
onDragSelect,
|
||||
@@ -43,8 +44,9 @@ function ApDexMetrics({
|
||||
servicename,
|
||||
tagFilterItems,
|
||||
topLevelOperationsRoute,
|
||||
threshold: thresholdValue || 0,
|
||||
metricsBuckets,
|
||||
threashold: thresholdValue || 0,
|
||||
delta: delta || false,
|
||||
metricsBuckets: metricsBuckets || [],
|
||||
}),
|
||||
clickhouse_sql: [],
|
||||
id: uuid(),
|
||||
@@ -73,6 +75,7 @@ function ApDexMetrics({
|
||||
id: SERVICE_CHART_ID.apdex,
|
||||
}),
|
||||
[
|
||||
delta,
|
||||
metricsBuckets,
|
||||
servicename,
|
||||
tagFilterItems,
|
||||
@@ -89,7 +92,10 @@ function ApDexMetrics({
|
||||
}, [thresholdValue]);
|
||||
|
||||
const isQueryEnabled =
|
||||
topLevelOperationsRoute.length > 0 && metricsBuckets.length > 0;
|
||||
topLevelOperationsRoute.length > 0 &&
|
||||
!!metricsBuckets &&
|
||||
metricsBuckets?.length > 0 &&
|
||||
delta !== undefined;
|
||||
|
||||
return (
|
||||
<Graph
|
||||
@@ -104,4 +110,9 @@ function ApDexMetrics({
|
||||
);
|
||||
}
|
||||
|
||||
ApDexMetrics.defaultProps = {
|
||||
delta: undefined,
|
||||
le: undefined,
|
||||
};
|
||||
|
||||
export default ApDexMetrics;
|
||||
|
||||
@@ -31,6 +31,7 @@ function ApDexMetricsApplication({
|
||||
<ApDexMetrics
|
||||
topLevelOperationsRoute={topLevelOperationsRoute}
|
||||
handleGraphClick={handleGraphClick}
|
||||
delta={data?.data.delta}
|
||||
metricsBuckets={data?.data.le || []}
|
||||
onDragSelect={onDragSelect}
|
||||
tagFilterItems={tagFilterItems}
|
||||
|
||||
@@ -13,5 +13,6 @@ export interface ApDexDataSwitcherProps extends ApDexApplicationProps {
|
||||
}
|
||||
|
||||
export interface ApDexMetricsProps extends ApDexDataSwitcherProps {
|
||||
metricsBuckets: number[];
|
||||
delta?: boolean;
|
||||
metricsBuckets?: number[];
|
||||
}
|
||||
|
||||
@@ -1,15 +1,9 @@
|
||||
import { ReactNode } from 'react';
|
||||
import {
|
||||
MetrictypesComparisonSpaceAggregationParamDTO,
|
||||
MetrictypesSpaceAggregationDTO,
|
||||
MetrictypesTimeAggregationDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { MetrictypesComparisonSpaceAggregationParamDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { RowData } from 'lib/query/createTableColumnsFromQuery';
|
||||
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import type { WidgetKeys } from '../constant';
|
||||
import { DataSource, MetricAggregateOperator } from 'types/common/queryBuilder';
|
||||
|
||||
export interface IServiceName {
|
||||
servicename: string;
|
||||
@@ -36,8 +30,8 @@ export interface BuilderQueriesProps {
|
||||
aggregateOperator?: string[];
|
||||
dataSource: DataSource;
|
||||
queryNameAndExpression?: string[];
|
||||
timeAggregateOperators: MetrictypesTimeAggregationDTO[];
|
||||
spaceAggregateOperators: MetrictypesSpaceAggregationDTO[];
|
||||
timeAggregateOperators: MetricAggregateOperator[];
|
||||
spaceAggregateOperators: MetricAggregateOperator[];
|
||||
}
|
||||
|
||||
export interface BuilderQuerieswithFormulaProps {
|
||||
@@ -48,12 +42,14 @@ export interface BuilderQuerieswithFormulaProps {
|
||||
expressions: string[];
|
||||
legendFormulas: string[];
|
||||
additionalItems: TagFilterItem[][];
|
||||
timeAggregateOperators: MetrictypesTimeAggregationDTO[];
|
||||
spaceAggregateOperators: MetrictypesSpaceAggregationDTO[];
|
||||
timeAggregateOperators: MetricAggregateOperator[];
|
||||
spaceAggregateOperators: MetricAggregateOperator[];
|
||||
comparisonSpaceAggregationParams?: (
|
||||
| MetrictypesComparisonSpaceAggregationParamDTO
|
||||
| undefined
|
||||
)[];
|
||||
// v5 picks its own step when none is sent; v4 needs one
|
||||
stepInterval?: number;
|
||||
dataSource: DataSource;
|
||||
}
|
||||
|
||||
@@ -74,7 +70,7 @@ export interface ApDexProps {
|
||||
servicename: IServiceName['servicename'];
|
||||
tagFilterItems: TagFilterItem[];
|
||||
topLevelOperationsRoute: string[];
|
||||
threshold: number;
|
||||
threashold: number;
|
||||
}
|
||||
|
||||
export interface TableRendererProps {
|
||||
@@ -82,12 +78,7 @@ export interface TableRendererProps {
|
||||
renderFunction: (record: RowData) => ReactNode;
|
||||
}
|
||||
|
||||
export interface LatencyAtOrBelowAggregation {
|
||||
key: WidgetKeys;
|
||||
spaceAggregation: MetrictypesSpaceAggregationDTO;
|
||||
param?: MetrictypesComparisonSpaceAggregationParamDTO;
|
||||
}
|
||||
|
||||
export interface ApDexMetricsQueryBuilderQueriesProps extends ApDexProps {
|
||||
delta: boolean;
|
||||
metricsBuckets: number[];
|
||||
}
|
||||
|
||||
@@ -30,10 +30,23 @@ export const SERVICE_DETAIL_DRILLDOWN_ENABLED = true;
|
||||
export enum FORMULA {
|
||||
ERROR_PERCENTAGE = 'A*100/B',
|
||||
DATABASE_CALLS_AVG_DURATION = 'A/B',
|
||||
// Apdex is (satisfied + tolerating / 2) / total, with satisfied B, tolerating C and total A.
|
||||
// C counts requests up to the bucket covering 4x the threshold, so it includes B:
|
||||
// B + (C - B) / 2 = (B + C) / 2
|
||||
APDEX = '((B + C)/2)/A',
|
||||
// The apdex formula is (satisfied_count + 0.5 * tolerating_count + 0 * frustating_count) / total_count
|
||||
// The satisfied_count is B, tolerating_count is C, total_count is A
|
||||
// But why do we have (B+C)/2 instead of B + C/2?
|
||||
// The way we issue the query is latency <= threshold, which means we over count i.e
|
||||
// query B => durationNano <= 500ms
|
||||
// query C => durationNano <= 2000ms
|
||||
// Since <= 2000ms includes <= 500ms, we over count, to correct we subtract B/2
|
||||
// so the full expression would be (B + C/2) - B/2 = (B+C)/2
|
||||
// However, if you add a filter on durationNano > 500ms, (filterItemC in overviewQueries) the query would be
|
||||
// B + C/2
|
||||
APDEX_TRACES = '((B + C)/2)/A',
|
||||
// The delta span metrics store delta compared to previous reporting interval
|
||||
// but not the counts for the current interval. The bucket counts are cumulative
|
||||
APDEX_DELTA_SPAN_METRICS = '((B + C)/2)/A',
|
||||
// Cumulative span metrics store the counts for all buckets
|
||||
// so we need to subtract B/2 to correct the over counting
|
||||
APDEX_CUMULATIVE_SPAN_METRICS = '((B + C)/2)/A',
|
||||
}
|
||||
|
||||
export const TOP_LEVEL_OPERATIONS = ['{{.top_level_operations}}'];
|
||||
@@ -67,13 +80,17 @@ export enum MetricsType {
|
||||
}
|
||||
|
||||
export enum WidgetKeys {
|
||||
Le = 'le',
|
||||
Name = 'name',
|
||||
HasError = 'hasError',
|
||||
Address = 'address',
|
||||
DurationNano = 'duration_nano',
|
||||
DurationNano = 'durationNano',
|
||||
SpanDurationNano = 'duration_nano',
|
||||
StatusCode = 'status.code',
|
||||
Operation = 'operation',
|
||||
OperationName = 'operationName',
|
||||
OTelServiceName = 'service.name',
|
||||
ServiceName = 'serviceName',
|
||||
SignozLatencyCount = 'signoz_latency.count',
|
||||
SignozDBLatencyCount = 'signoz_db_latency_count',
|
||||
DatabaseCallCount = 'signoz_database_call_count',
|
||||
|
||||
@@ -29,24 +29,17 @@ describe('Error Rate', () => {
|
||||
|
||||
describe('getNearestHighestBucketValue', () => {
|
||||
it('should return nearest higher bucket value', () => {
|
||||
expect(getNearestHighestBucketValue(50, [10, 20, 30, 40, 60, 70])).toBe(60);
|
||||
expect(getNearestHighestBucketValue(50, [10, 20, 30, 40, 60, 70])).toBe('60');
|
||||
});
|
||||
|
||||
it('should return undefined for value higher than any bucket', () => {
|
||||
expect(
|
||||
getNearestHighestBucketValue(80, [10, 20, 30, 40, 60, 70]),
|
||||
).toBeUndefined();
|
||||
it('should return +Inf for value higher than any bucket', () => {
|
||||
expect(getNearestHighestBucketValue(80, [10, 20, 30, 40, 60, 70])).toBe(
|
||||
'+Inf',
|
||||
);
|
||||
});
|
||||
|
||||
it('should return the first bucket for value lower than all buckets', () => {
|
||||
expect(getNearestHighestBucketValue(5, [10, 20, 30, 40, 60, 70])).toBe(10);
|
||||
});
|
||||
|
||||
it('should not reorder the buckets it is given', () => {
|
||||
const buckets = [60, 10, 30];
|
||||
|
||||
expect(getNearestHighestBucketValue(20, buckets)).toBe(30);
|
||||
expect(buckets).toStrictEqual([60, 10, 30]);
|
||||
expect(getNearestHighestBucketValue(5, [10, 20, 30, 40, 60, 70])).toBe('10');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -47,9 +47,11 @@ export const navigateToTrace = ({
|
||||
export const getNearestHighestBucketValue = (
|
||||
value: number,
|
||||
buckets: number[],
|
||||
): number | undefined => {
|
||||
// buckets are cached query data; never mutate
|
||||
return [...buckets].sort((a, b) => a - b).find((bucket) => bucket >= value);
|
||||
): string => {
|
||||
// sort the buckets
|
||||
buckets.sort((a, b) => a - b);
|
||||
const nearestBucket = buckets.find((bucket) => bucket >= value);
|
||||
return nearestBucket?.toString() || '+Inf';
|
||||
};
|
||||
|
||||
export const convertedTracesToDownloadData = (
|
||||
|
||||
@@ -3,3 +3,8 @@
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-3);
|
||||
}
|
||||
|
||||
.label {
|
||||
font-size: var(--label-small-400-font-size);
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
|
||||
@@ -32,3 +32,8 @@
|
||||
gap: var(--spacing-6);
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.titleText {
|
||||
color: inherit;
|
||||
font-size: var(--label-base-400-font-size);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
import {
|
||||
MetrictypesSpaceAggregationDTO,
|
||||
MetrictypesTimeAggregationDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { ServiceDataProps } from 'api/metrics/getTopLevelOperations';
|
||||
import { OPERATORS } from 'constants/queryBuilder';
|
||||
import {
|
||||
@@ -15,7 +11,11 @@ import {
|
||||
DataTypes,
|
||||
} from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { DataSource, QueryBuilderData } from 'types/common/queryBuilder';
|
||||
import {
|
||||
DataSource,
|
||||
MetricAggregateOperator,
|
||||
QueryBuilderData,
|
||||
} from 'types/common/queryBuilder';
|
||||
|
||||
export const serviceMetricsQuery = (
|
||||
topLevelOperation: [keyof ServiceDataProps, string[]],
|
||||
@@ -155,16 +155,16 @@ export const serviceMetricsQuery = (
|
||||
];
|
||||
|
||||
const timeAggregateOperators = [
|
||||
MetrictypesTimeAggregationDTO[''],
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetricAggregateOperator.EMPTY,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetrictypesSpaceAggregationDTO.p99,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetricAggregateOperator.P99,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
];
|
||||
|
||||
const disabled = [false, true, true, false];
|
||||
|
||||
104
frontend/src/hooks/logs/__tests__/useAddToQuery.test.ts
Normal file
104
frontend/src/hooks/logs/__tests__/useAddToQuery.test.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
import { renderHook } from 'tests/test-utils';
|
||||
import { initialQueriesMap, OPERATORS } from 'constants/queryBuilder';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
import { useAddToQuery } from '../useAddToQuery';
|
||||
|
||||
jest.mock('hooks/queryBuilder/useQueryBuilder');
|
||||
|
||||
type QueryBuilder = ReturnType<typeof useQueryBuilder>;
|
||||
|
||||
const redirectWithQueryBuilderData = jest.fn() as jest.MockedFunction<
|
||||
QueryBuilder['redirectWithQueryBuilderData']
|
||||
>;
|
||||
|
||||
function mockQueryBuilder(builder: Partial<QueryBuilder>): void {
|
||||
jest.mocked(useQueryBuilder).mockReturnValue(builder as QueryBuilder);
|
||||
}
|
||||
|
||||
const currentQuery: Query = {
|
||||
...initialQueriesMap.logs,
|
||||
builder: {
|
||||
...initialQueriesMap.logs.builder,
|
||||
queryData: [
|
||||
{
|
||||
...initialQueriesMap.logs.builder.queryData[0],
|
||||
source: 'audit',
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockQueryBuilder({ currentQuery, redirectWithQueryBuilderData });
|
||||
});
|
||||
|
||||
describe('useAddToQuery', () => {
|
||||
it('appends a filter on the clicked field and redirects with the query', () => {
|
||||
const { result } = renderHook(() => useAddToQuery());
|
||||
|
||||
result.current('signoz.principal.email', 'alice@acme.com', OPERATORS['=']);
|
||||
|
||||
expect(redirectWithQueryBuilderData).toHaveBeenCalledTimes(1);
|
||||
const [nextQuery] = redirectWithQueryBuilderData.mock.calls[0] as [Query];
|
||||
const { filters } = nextQuery.builder.queryData[0];
|
||||
expect(filters?.items).toHaveLength(1);
|
||||
expect(filters?.items[0]).toStrictEqual(
|
||||
expect.objectContaining({
|
||||
key: expect.objectContaining({ key: 'signoz.principal.email' }),
|
||||
op: '=',
|
||||
value: 'alice@acme.com',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps the filters already on the query', () => {
|
||||
const withFilter: Query = {
|
||||
...currentQuery,
|
||||
builder: {
|
||||
...currentQuery.builder,
|
||||
queryData: [
|
||||
{
|
||||
...currentQuery.builder.queryData[0],
|
||||
filters: {
|
||||
op: 'AND',
|
||||
items: [
|
||||
{
|
||||
id: 'existing',
|
||||
key: { key: 'event_name', type: '', dataType: 'string' },
|
||||
op: '=',
|
||||
value: 'signoz.audit.create',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
} as Query;
|
||||
mockQueryBuilder({
|
||||
currentQuery: withFilter,
|
||||
redirectWithQueryBuilderData,
|
||||
});
|
||||
const { result } = renderHook(() => useAddToQuery());
|
||||
|
||||
result.current('signoz.resource.kind', 'dashboard', OPERATORS['=']);
|
||||
|
||||
const [nextQuery] = redirectWithQueryBuilderData.mock.calls[0] as [Query];
|
||||
const items = nextQuery.builder.queryData[0].filters?.items ?? [];
|
||||
expect(items.map((item) => item.key?.key)).toStrictEqual([
|
||||
'event_name',
|
||||
'signoz.resource.kind',
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps the audit source on the query', () => {
|
||||
const { result } = renderHook(() => useAddToQuery());
|
||||
|
||||
result.current('signoz.audit.outcome', 'failure', OPERATORS['=']);
|
||||
|
||||
const [nextQuery] = redirectWithQueryBuilderData.mock.calls[0] as [Query];
|
||||
expect(nextQuery.builder.queryData[0].source).toBe('audit');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import {
|
||||
NO_DELAY_USER_EVENT,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import { useCloseOnOutsideClick } from '../useCloseOnOutsideClick';
|
||||
|
||||
function Harness({
|
||||
enabled,
|
||||
onClose,
|
||||
}: {
|
||||
enabled: boolean;
|
||||
onClose: () => void;
|
||||
}): JSX.Element {
|
||||
useCloseOnOutsideClick(enabled, onClose);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<button type="button" data-testid="outside">
|
||||
outside
|
||||
</button>
|
||||
<div data-log-detail-ignore="true">
|
||||
<button type="button" data-testid="ignored-list">
|
||||
list
|
||||
</button>
|
||||
</div>
|
||||
<div className="drawer-popover">
|
||||
<button type="button" data-testid="ignored-popover">
|
||||
popover
|
||||
</button>
|
||||
</div>
|
||||
<div data-base-ui-portal>
|
||||
<button type="button" data-testid="ignored-portal">
|
||||
portal
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
describe('useCloseOnOutsideClick', () => {
|
||||
it('closes on a click outside', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const onClose = jest.fn();
|
||||
render(<Harness enabled onClose={onClose} />);
|
||||
|
||||
await user.click(screen.getByTestId('outside'));
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each(['ignored-list', 'ignored-popover', 'ignored-portal'])(
|
||||
'does not close on a click inside %s',
|
||||
async (testId) => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const onClose = jest.fn();
|
||||
render(<Harness enabled onClose={onClose} />);
|
||||
|
||||
await user.click(screen.getByTestId(testId));
|
||||
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('does nothing while disabled', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const onClose = jest.fn();
|
||||
render(<Harness enabled={false} onClose={onClose} />);
|
||||
|
||||
await user.click(screen.getByTestId('outside'));
|
||||
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('stops listening after it is disabled', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const onClose = jest.fn();
|
||||
const { rerender } = render(<Harness enabled onClose={onClose} />);
|
||||
rerender(<Harness enabled={false} onClose={onClose} />);
|
||||
|
||||
await user.click(screen.getByTestId('outside'));
|
||||
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
75
frontend/src/hooks/logs/__tests__/useCopyLogLink.test.tsx
Normal file
75
frontend/src/hooks/logs/__tests__/useCopyLogLink.test.tsx
Normal file
@@ -0,0 +1,75 @@
|
||||
import { ReactNode } from 'react';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { act, AllTheProviders, renderHook } from 'tests/test-utils';
|
||||
|
||||
import { useCopyLogLink } from '../useCopyLogLink';
|
||||
|
||||
const mockCopy = jest.fn();
|
||||
|
||||
jest.mock('react-use', () => ({
|
||||
...jest.requireActual('react-use'),
|
||||
useCopyToClipboard: (): [unknown, jest.Mock] => [null, mockCopy],
|
||||
}));
|
||||
|
||||
function wrapperAt(initialRoute: string) {
|
||||
return function Wrapper({ children }: { children: ReactNode }): JSX.Element {
|
||||
return (
|
||||
<AllTheProviders initialRoute={initialRoute}>{children}</AllTheProviders>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
function copiedLink(): URL {
|
||||
return new URL(mockCopy.mock.calls[0][0] as string);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mockCopy.mockClear();
|
||||
});
|
||||
|
||||
describe('useCopyLogLink', () => {
|
||||
it('copies a link to the current page that carries the log id', () => {
|
||||
const { result } = renderHook(() => useCopyLogLink('log-1'), {
|
||||
wrapper: wrapperAt(ROUTES.AUDIT_LOGS),
|
||||
});
|
||||
|
||||
act(() => result.current.onLogCopy());
|
||||
|
||||
expect(mockCopy).toHaveBeenCalledTimes(1);
|
||||
expect(copiedLink().pathname).toBe(ROUTES.AUDIT_LOGS);
|
||||
expect(copiedLink().searchParams.get('activeLogId')).toBe('"log-1"');
|
||||
});
|
||||
|
||||
it('drops the relative time and pins the time range', () => {
|
||||
const { result } = renderHook(() => useCopyLogLink('log-1'), {
|
||||
wrapper: wrapperAt(`${ROUTES.AUDIT_LOGS}?relativeTime=30m`),
|
||||
});
|
||||
|
||||
act(() => result.current.onLogCopy());
|
||||
|
||||
const { searchParams } = copiedLink();
|
||||
expect(searchParams.has('relativeTime')).toBe(false);
|
||||
expect(searchParams.has('startTime')).toBe(true);
|
||||
expect(searchParams.has('endTime')).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps the other params of the page', () => {
|
||||
const { result } = renderHook(() => useCopyLogLink('log-1'), {
|
||||
wrapper: wrapperAt(`${ROUTES.AUDIT_LOGS}?compositeQuery=abc`),
|
||||
});
|
||||
|
||||
act(() => result.current.onLogCopy());
|
||||
|
||||
expect(copiedLink().searchParams.get('compositeQuery')).toBe('abc');
|
||||
});
|
||||
|
||||
it('copies nothing without a log id', () => {
|
||||
const { result } = renderHook(() => useCopyLogLink(), {
|
||||
wrapper: wrapperAt(ROUTES.AUDIT_LOGS),
|
||||
});
|
||||
|
||||
act(() => result.current.onLogCopy());
|
||||
|
||||
expect(mockCopy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -16,9 +16,9 @@ export type UseCopyLogLink = {
|
||||
onClearActiveLog: () => void;
|
||||
};
|
||||
|
||||
export type UseActiveLog = {
|
||||
activeLog: ILog | null;
|
||||
onSetActiveLog: (log: ILog) => void;
|
||||
export type UseActiveLog<T extends { id: string } = ILog> = {
|
||||
activeLog: T | null;
|
||||
onSetActiveLog: (log: T) => void;
|
||||
onClearActiveLog: () => void;
|
||||
onAddToQuery: (
|
||||
fieldKey: string,
|
||||
|
||||
@@ -1,19 +1,15 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { ScalarFieldValue } from 'utils/stringUtils';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { getFilterQueryData } from 'container/LogDetailedView/logAttributeActions.utils';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import { ILog } from 'types/api/logs/log';
|
||||
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
import { UseActiveLog } from './types';
|
||||
import { useAddToQuery } from './useAddToQuery';
|
||||
|
||||
export const useActiveLog = (): UseActiveLog => {
|
||||
const { currentQuery, redirectWithQueryBuilderData } = useQueryBuilder();
|
||||
|
||||
const [activeLog, setActiveLog] = useState<ILog | null>(null);
|
||||
export const useActiveLog = <
|
||||
T extends { id: string } = ILog,
|
||||
>(): UseActiveLog<T> => {
|
||||
const [activeLog, setActiveLog] = useState<T | null>(null);
|
||||
|
||||
// Close drawer/clear active log when query in URL changes
|
||||
const urlQuery = useUrlQuery();
|
||||
@@ -29,33 +25,13 @@ export const useActiveLog = (): UseActiveLog => {
|
||||
prevQueryRef.current = compositeQuery;
|
||||
}, [compositeQuery]);
|
||||
|
||||
const onSetActiveLog = useCallback((nextActiveLog: ILog): void => {
|
||||
const onSetActiveLog = useCallback((nextActiveLog: T): void => {
|
||||
setActiveLog(nextActiveLog);
|
||||
}, []);
|
||||
|
||||
const onClearActiveLog = useCallback((): void => setActiveLog(null), []);
|
||||
|
||||
const onAddToQuery = useCallback(
|
||||
(
|
||||
fieldKey: string,
|
||||
fieldValue: ScalarFieldValue,
|
||||
operator: string,
|
||||
dataType?: DataTypes,
|
||||
): void => {
|
||||
const nextQuery: Query = {
|
||||
...currentQuery,
|
||||
builder: {
|
||||
...currentQuery.builder,
|
||||
queryData: currentQuery.builder.queryData.map((item) =>
|
||||
getFilterQueryData(item, { fieldKey, dataType }, fieldValue, operator),
|
||||
),
|
||||
},
|
||||
};
|
||||
|
||||
redirectWithQueryBuilderData(nextQuery);
|
||||
},
|
||||
[currentQuery, redirectWithQueryBuilderData],
|
||||
);
|
||||
const onAddToQuery = useAddToQuery();
|
||||
|
||||
return {
|
||||
activeLog,
|
||||
|
||||
34
frontend/src/hooks/logs/useAddToQuery.ts
Normal file
34
frontend/src/hooks/logs/useAddToQuery.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { useCallback } from 'react';
|
||||
import { getFilterQueryData } from 'container/LogDetailedView/logAttributeActions.utils';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { ScalarFieldValue } from 'utils/stringUtils';
|
||||
|
||||
import { UseActiveLog } from './types';
|
||||
|
||||
export const useAddToQuery = (): UseActiveLog['onAddToQuery'] => {
|
||||
const { currentQuery, redirectWithQueryBuilderData } = useQueryBuilder();
|
||||
|
||||
return useCallback(
|
||||
(
|
||||
fieldKey: string,
|
||||
fieldValue: ScalarFieldValue,
|
||||
operator: string,
|
||||
dataType?: DataTypes,
|
||||
): void => {
|
||||
const nextQuery: Query = {
|
||||
...currentQuery,
|
||||
builder: {
|
||||
...currentQuery.builder,
|
||||
queryData: currentQuery.builder.queryData.map((item) =>
|
||||
getFilterQueryData(item, { fieldKey, dataType }, fieldValue, operator),
|
||||
),
|
||||
},
|
||||
};
|
||||
|
||||
redirectWithQueryBuilderData(nextQuery);
|
||||
},
|
||||
[currentQuery, redirectWithQueryBuilderData],
|
||||
);
|
||||
};
|
||||
33
frontend/src/hooks/logs/useCloseOnOutsideClick.ts
Normal file
33
frontend/src/hooks/logs/useCloseOnOutsideClick.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { useEffect } from 'react';
|
||||
|
||||
const IGNORED_TARGETS = [
|
||||
'[data-log-detail-ignore="true"]',
|
||||
'.cm-tooltip-autocomplete',
|
||||
'.drawer-popover',
|
||||
'.query-status-popover',
|
||||
'[data-radix-popper-content-wrapper]',
|
||||
'[data-base-ui-portal]',
|
||||
].join(',');
|
||||
|
||||
export function useCloseOnOutsideClick(
|
||||
enabled: boolean,
|
||||
onClose: () => void,
|
||||
): void {
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const handleMouseDown = (e: MouseEvent): void => {
|
||||
if (e.target instanceof Element && e.target.closest(IGNORED_TARGETS)) {
|
||||
return;
|
||||
}
|
||||
onClose();
|
||||
};
|
||||
|
||||
document.addEventListener('mousedown', handleMouseDown);
|
||||
return (): void => {
|
||||
document.removeEventListener('mousedown', handleMouseDown);
|
||||
};
|
||||
}, [enabled, onClose]);
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { BuilderQuerySource, DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
export type ExplorerQueryRules = {
|
||||
dataSource: DataSource;
|
||||
/** `meter` on the meter explorer, which shares the metrics signal; '' elsewhere. */
|
||||
/** `meter` on the meter explorer, which shares the metrics signal; `audit` on the audit logs page, which shares the logs signal; '' elsewhere. */
|
||||
source: BuilderQuerySource;
|
||||
/** AI_QUERY_BUILDER on the AI explorer, whose queries live in the AI slot. */
|
||||
queryType: EQueryType.QUERY_BUILDER | EQueryType.AI_QUERY_BUILDER;
|
||||
@@ -43,6 +43,12 @@ const EXPLORER_QUERY_RULES: Partial<Record<string, ExplorerQueryRules>> = {
|
||||
queryType: EQueryType.QUERY_BUILDER,
|
||||
allowsTraceOperator: false,
|
||||
},
|
||||
[ROUTES.AUDIT_LOGS]: {
|
||||
dataSource: DataSource.LOGS,
|
||||
source: TelemetrytypesSourceDTO.audit,
|
||||
queryType: EQueryType.QUERY_BUILDER,
|
||||
allowsTraceOperator: false,
|
||||
},
|
||||
};
|
||||
|
||||
export function getExplorerQueryRules(
|
||||
|
||||
@@ -268,6 +268,16 @@ describe('normalizeCompositeQuery', () => {
|
||||
normalizeCompositeQuery(initialQueriesMap.metrics, ROUTES.METER_EXPLORER)
|
||||
.query.builder.queryData[0].source,
|
||||
).toBe(TelemetrytypesSourceDTO.meter);
|
||||
expect(
|
||||
firstBuilderQuery(
|
||||
initialQueriesMap.logs,
|
||||
[{ ...without(logsQuery, 'source'), filter: { expression: "x='y'" } }],
|
||||
ROUTES.AUDIT_LOGS,
|
||||
),
|
||||
).toMatchObject({
|
||||
source: TelemetrytypesSourceDTO.audit,
|
||||
filter: { expression: "x='y'" },
|
||||
});
|
||||
expect(
|
||||
firstBuilderQuery(traces, [{ ...tracesQuery, ...llmFilter }], ai),
|
||||
).toStrictEqual({ ...tracesQuery, ...llmFilter });
|
||||
|
||||
@@ -166,10 +166,11 @@ function fillMissingSignal(
|
||||
builderQuery.dataSource = rules.dataSource;
|
||||
}
|
||||
|
||||
// A missing `source` already means '', so only meter needs it written.
|
||||
// A missing `source` already means '', so only meter and audit need it written.
|
||||
if (
|
||||
builderQuery.source === undefined &&
|
||||
rules.source === TelemetrytypesSourceDTO.meter
|
||||
(rules.source === TelemetrytypesSourceDTO.meter ||
|
||||
rules.source === TelemetrytypesSourceDTO.audit)
|
||||
) {
|
||||
builderQuery.source = rules.source;
|
||||
}
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
import { defaultTo } from 'lodash-es';
|
||||
import { ILog, ILogBody } from 'types/api/logs/log';
|
||||
|
||||
export function FlatLogData(log: ILog): Record<string, string> {
|
||||
export function FlatLogData<T extends object>(
|
||||
logData: T,
|
||||
): Record<string, string> {
|
||||
const log = logData as Record<string, never>;
|
||||
const flattenLogObject: Record<string, string> = {};
|
||||
|
||||
Object.keys(log).forEach((key: string): void => {
|
||||
if (typeof log[key as never] !== 'object') {
|
||||
flattenLogObject[key] = log[key as never];
|
||||
if (typeof log[key] !== 'object') {
|
||||
flattenLogObject[key] = log[key];
|
||||
} else {
|
||||
Object.keys(defaultTo(log[key as never], {})).forEach((childKey) => {
|
||||
flattenLogObject[childKey] = log[key as never][childKey];
|
||||
Object.keys(defaultTo(log[key], {})).forEach((childKey) => {
|
||||
flattenLogObject[childKey] = log[key][childKey];
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -29,7 +32,7 @@ function getBodyFieldValue(body: ILogBody, key: string): unknown {
|
||||
// only), splitting the key on `.`; otherwise fall back to FlatLogData
|
||||
// (attributes/resources/scope/top-level).
|
||||
export function getLogFieldValue(
|
||||
log: ILog,
|
||||
log: Pick<ILog, 'body'>,
|
||||
fieldName: string,
|
||||
isBodyJsonEnabled: boolean,
|
||||
): unknown {
|
||||
|
||||
@@ -41,12 +41,6 @@ jest.mock('pages/AlertDetails', () => ({
|
||||
return <div>Alert Details Component</div>;
|
||||
},
|
||||
}));
|
||||
jest.mock('pages/ChannelsNew', () => ({
|
||||
__esModule: true,
|
||||
default: function MockChannelsNew(): JSX.Element {
|
||||
return <div>Channels New Component</div>;
|
||||
},
|
||||
}));
|
||||
jest.mock('../NotificationChannels/NotificationChannels', () => ({
|
||||
__esModule: true,
|
||||
default: function MockNotificationChannels(): JSX.Element {
|
||||
@@ -173,41 +167,6 @@ describe('AlertList', () => {
|
||||
`/alerts?tab=Configuration&subTab=${CHANNELS_SUB_TAB}`,
|
||||
);
|
||||
});
|
||||
|
||||
it('navigates to the alert rules list when Alert Rules is clicked on a rule details page', async () => {
|
||||
mockQueryParams({ ruleId: 'rule-1' });
|
||||
mockLocation('/alerts/overview');
|
||||
|
||||
render(<AlertList />);
|
||||
|
||||
await clickTab(ALERT_RULES_TEXT);
|
||||
|
||||
expect(mockSafeNavigate).toHaveBeenCalledWith('/alerts?tab=AlertRules');
|
||||
});
|
||||
|
||||
it('navigates to the channels list when Configuration is clicked on a channel page', async () => {
|
||||
mockQueryParams({});
|
||||
mockLocation('/alerts/channels/new');
|
||||
|
||||
render(<AlertList />);
|
||||
|
||||
await clickTab(CONFIGURATION_TEXT);
|
||||
|
||||
expect(mockSafeNavigate).toHaveBeenCalledWith(
|
||||
`/alerts?tab=Configuration&subTab=${CHANNELS_SUB_TAB}`,
|
||||
);
|
||||
});
|
||||
|
||||
it('does not navigate when the active list tab is clicked again', async () => {
|
||||
mockQueryParams({ tab: 'AlertRules' });
|
||||
mockLocation(ALERTS_PATH);
|
||||
|
||||
render(<AlertList />);
|
||||
|
||||
await clickTab(ALERT_RULES_TEXT);
|
||||
|
||||
expect(mockSafeNavigate).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Configuration Tab with Secondary Sidebar', () => {
|
||||
|
||||
@@ -53,16 +53,14 @@ function AllAlertList(): JSX.Element {
|
||||
|
||||
const tab = urlQuery.get('tab');
|
||||
const subTab = urlQuery.get('subTab');
|
||||
const isRuleDetails =
|
||||
location.pathname === ROUTES.ALERT_HISTORY ||
|
||||
location.pathname === ROUTES.ALERT_OVERVIEW;
|
||||
const isAlertHistory = location.pathname === ROUTES.ALERT_HISTORY;
|
||||
const isAlertOverview = location.pathname === ROUTES.ALERT_OVERVIEW;
|
||||
const isChannelsNew = location.pathname === ROUTES.CHANNELS_NEW;
|
||||
const isChannelsEdit = location.pathname.startsWith('/alerts/channels/edit/');
|
||||
const isChannelDetails = isChannelsNew || isChannelsEdit;
|
||||
const isDetailsView = isRuleDetails || isChannelDetails;
|
||||
|
||||
const getActiveTab = useCallback((): string => {
|
||||
if (isRuleDetails) {
|
||||
if (isAlertHistory || isAlertOverview) {
|
||||
return AlertListTabs.ALERT_RULES;
|
||||
}
|
||||
if (isChannelDetails) {
|
||||
@@ -76,7 +74,7 @@ function AllAlertList(): JSX.Element {
|
||||
return AlertListTabs.CONFIGURATION;
|
||||
}
|
||||
return tab || AlertListTabs.ALERT_RULES;
|
||||
}, [isRuleDetails, isChannelDetails, tab]);
|
||||
}, [isAlertHistory, isAlertOverview, isChannelDetails, tab]);
|
||||
|
||||
const getActiveSubTab = useCallback((): AlertListSubTabs => {
|
||||
if (isChannelDetails) {
|
||||
@@ -116,18 +114,6 @@ function AllAlertList(): JSX.Element {
|
||||
[getActiveSubTab, safeNavigate],
|
||||
);
|
||||
|
||||
// A details page shows its parent tab as active, so a click on that tab must
|
||||
// still navigate back to the list; antd only fires onChange for a new key.
|
||||
const handleTopTabClick = useCallback(
|
||||
(clickedTab: string): void => {
|
||||
if (clickedTab === getActiveTab() && !isDetailsView) {
|
||||
return;
|
||||
}
|
||||
handleTopTabChange(clickedTab);
|
||||
},
|
||||
[getActiveTab, handleTopTabChange, isDetailsView],
|
||||
);
|
||||
|
||||
const handleSubTabChange = useCallback(
|
||||
(newSubTab: AlertListSubTabs): void => {
|
||||
const queryParams = new URLSearchParams();
|
||||
@@ -215,7 +201,7 @@ function AllAlertList(): JSX.Element {
|
||||
key: AlertListTabs.ALERT_RULES,
|
||||
children: (
|
||||
<div className="alert-rules-container">
|
||||
{isRuleDetails ? <AlertDetails /> : <AllAlertRules />}
|
||||
{isAlertHistory || isAlertOverview ? <AlertDetails /> : <AllAlertRules />}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
@@ -236,8 +222,12 @@ function AllAlertList(): JSX.Element {
|
||||
destroyInactiveTabPane
|
||||
items={items}
|
||||
activeKey={getActiveTab()}
|
||||
onTabClick={handleTopTabClick}
|
||||
className={`alerts-container ${isDetailsView ? 'alert-details-tabs' : ''}`}
|
||||
onChange={handleTopTabChange}
|
||||
className={`alerts-container ${
|
||||
isAlertHistory || isAlertOverview || isChannelDetails
|
||||
? 'alert-details-tabs'
|
||||
: ''
|
||||
}`}
|
||||
tabBarExtraContent={
|
||||
<HeaderRightSection
|
||||
enableAnnouncements={false}
|
||||
|
||||
@@ -59,6 +59,7 @@ import {
|
||||
} from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import {
|
||||
BuilderQuerySource,
|
||||
DataSource,
|
||||
IsDefaultQueryProps,
|
||||
QueryBuilderContextType,
|
||||
@@ -293,7 +294,7 @@ export function QueryBuilderProvider({
|
||||
query: Query,
|
||||
panelType: PANEL_TYPES,
|
||||
dataSource: DataSource,
|
||||
signalSource?: 'meter' | '',
|
||||
signalSource?: BuilderQuerySource,
|
||||
): Query => {
|
||||
const slotKey = getBuilderSlotKeyForQueryType(query.queryType);
|
||||
const builder = getBuilderBySlotKey(query, slotKey);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { FieldDataType } from 'types/api/v5/queryRange';
|
||||
import { BuilderQuerySource } from 'types/common/queryBuilder';
|
||||
|
||||
export interface QueryKeyDataSuggestionsProps {
|
||||
label: string;
|
||||
@@ -34,7 +35,7 @@ export interface QueryKeyRequestProps {
|
||||
fieldDataType?: FieldDataType;
|
||||
metricName?: string;
|
||||
metricNamespace?: string;
|
||||
signalSource?: 'meter' | '';
|
||||
signalSource?: BuilderQuerySource;
|
||||
}
|
||||
|
||||
export type SignalType = 'traces' | 'logs' | 'metrics';
|
||||
|
||||
@@ -250,6 +250,12 @@ export interface LogBuilderQuery extends BaseBuilderQuery {
|
||||
aggregations?: LogAggregation[];
|
||||
}
|
||||
|
||||
export interface AuditBuilderQuery extends BaseBuilderQuery {
|
||||
signal: 'logs';
|
||||
source: 'audit';
|
||||
aggregations?: LogAggregation[];
|
||||
}
|
||||
|
||||
export interface MetricBuilderQuery extends BaseBuilderQuery {
|
||||
signal: 'metrics';
|
||||
aggregations?: MetricAggregation[];
|
||||
@@ -264,6 +270,7 @@ export interface MeterBuilderQuery extends BaseBuilderQuery {
|
||||
export type BuilderQuery =
|
||||
| TraceBuilderQuery
|
||||
| LogBuilderQuery
|
||||
| AuditBuilderQuery
|
||||
| MetricBuilderQuery
|
||||
| MeterBuilderQuery;
|
||||
|
||||
|
||||
@@ -322,7 +322,7 @@ export type QueryBuilderContextType = {
|
||||
queryData: Query,
|
||||
panelType: PANEL_TYPES,
|
||||
dataSource: DataSource,
|
||||
signalSource?: 'meter' | '',
|
||||
signalSource?: BuilderQuerySource,
|
||||
) => Query;
|
||||
updateQueriesData: <T extends keyof QueryBuilderData>(
|
||||
query: Query,
|
||||
|
||||
@@ -137,6 +137,7 @@ export const routePermission: Record<keyof typeof ROUTES, ROLES[]> = {
|
||||
AI_OBSERVABILITY_OVERVIEW: ['ADMIN', 'EDITOR', 'VIEWER'],
|
||||
AI_OBSERVABILITY_EXPLORER: ['ADMIN', 'EDITOR', 'VIEWER'],
|
||||
AI_OBSERVABILITY_CONFIGURATION: ['ADMIN', 'EDITOR', 'VIEWER'],
|
||||
AUDIT_LOGS: ['ADMIN'],
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -370,9 +370,15 @@ func TestStatementBuilder_WithoutMetadata(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestStatementBuilder_KnownResourceFields(t *testing.T) {
|
||||
keysMap := map[string][]*telemetrytypes.TelemetryFieldKey{}
|
||||
for name, field := range audittelemetryschema.ResourceFields {
|
||||
keysMap[name] = []*telemetrytypes.TelemetryFieldKey{&field}
|
||||
keysMap := map[string][]*telemetrytypes.TelemetryFieldKey{
|
||||
"signoz.resource.kind": {
|
||||
{
|
||||
Name: "signoz.resource.kind",
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
FieldContext: telemetrytypes.FieldContextResource,
|
||||
FieldDataType: telemetrytypes.FieldDataTypeString,
|
||||
},
|
||||
},
|
||||
}
|
||||
statementBuilder := newTestAuditStatementBuilder(t, keysMap)
|
||||
ctx := context.Background()
|
||||
|
||||
688
pkg/telemetrymetadata/audit.go
Normal file
688
pkg/telemetrymetadata/audit.go
Normal file
@@ -0,0 +1,688 @@
|
||||
package telemetrymetadata
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/huandu/go-sqlbuilder"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/clickhousesql"
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/querybuilder"
|
||||
"github.com/SigNoz/signoz/pkg/telemetryschema/audittelemetryschema"
|
||||
"github.com/SigNoz/signoz/pkg/types/ctxtypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/instrumentationtypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
|
||||
)
|
||||
|
||||
const auditLookbackWindow = 30 * 24 * time.Hour
|
||||
|
||||
func (t *telemetryMetaStore) getAuditKeys(ctx context.Context, fieldKeySelectors []*telemetrytypes.FieldKeySelector) ([]*telemetrytypes.TelemetryFieldKey, bool, error) {
|
||||
ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{
|
||||
instrumentationtypes.TelemetrySignal: telemetrytypes.SignalLogs.StringValue(),
|
||||
instrumentationtypes.CodeNamespace: "metadata",
|
||||
instrumentationtypes.CodeFunctionName: "getAuditKeys",
|
||||
})
|
||||
|
||||
if len(fieldKeySelectors) == 0 {
|
||||
return nil, true, nil
|
||||
}
|
||||
|
||||
var queryAttributes, queryScope, queryResource bool
|
||||
var limit int
|
||||
for _, sel := range fieldKeySelectors {
|
||||
switch sel.FieldContext {
|
||||
case telemetrytypes.FieldContextUnspecified:
|
||||
queryAttributes = true
|
||||
queryScope = true
|
||||
queryResource = true
|
||||
case telemetrytypes.FieldContextAttribute:
|
||||
queryAttributes = true
|
||||
case telemetrytypes.FieldContextScope:
|
||||
queryScope = true
|
||||
case telemetrytypes.FieldContextResource:
|
||||
queryResource = true
|
||||
}
|
||||
limit += sel.Limit
|
||||
}
|
||||
if limit == 0 {
|
||||
limit = 1000
|
||||
}
|
||||
|
||||
jsonKeys, err := t.getAuditJSONPathKeys(ctx, queryAttributes, queryScope)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
|
||||
var resourceKeys []*telemetrytypes.TelemetryFieldKey
|
||||
resourceComplete := true
|
||||
if queryResource {
|
||||
resourceKeys, resourceComplete, err = t.getAuditResourceKeys(ctx, fieldKeySelectors, limit)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
}
|
||||
|
||||
seen := make(map[string]struct{}, len(jsonKeys)+len(resourceKeys))
|
||||
discovered := make([]*telemetrytypes.TelemetryFieldKey, 0, len(jsonKeys)+len(resourceKeys))
|
||||
for _, key := range append(jsonKeys, resourceKeys...) {
|
||||
if !staticFieldMatchesAny(*key, fieldKeySelectors) {
|
||||
continue
|
||||
}
|
||||
id := key.Name + ";" + key.FieldContext.StringValue() + ";" + key.FieldDataType.StringValue()
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
discovered = append(discovered, key)
|
||||
}
|
||||
|
||||
slices.SortFunc(discovered, func(a, b *telemetrytypes.TelemetryFieldKey) int {
|
||||
if c := cmp.Compare(getPriorityForContext(a.FieldContext), getPriorityForContext(b.FieldContext)); c != 0 {
|
||||
return c
|
||||
}
|
||||
if c := cmp.Compare(a.Name, b.Name); c != 0 {
|
||||
return c
|
||||
}
|
||||
return cmp.Compare(a.FieldDataType.StringValue(), b.FieldDataType.StringValue())
|
||||
})
|
||||
|
||||
complete := resourceComplete && len(discovered) <= limit
|
||||
if len(discovered) > limit {
|
||||
discovered = discovered[:limit]
|
||||
}
|
||||
|
||||
kept := make(map[string]*telemetrytypes.TelemetryFieldKey, len(discovered))
|
||||
for _, key := range discovered {
|
||||
kept[key.Name+";"+key.FieldContext.StringValue()+";"+key.FieldDataType.StringValue()] = key
|
||||
}
|
||||
|
||||
return appendStaticAuditKeys(discovered, kept, fieldKeySelectors), complete, nil
|
||||
}
|
||||
|
||||
func (t *telemetryMetaStore) getAuditJSONPathKeys(ctx context.Context, queryAttributes, queryScope bool) ([]*telemetrytypes.TelemetryFieldKey, error) {
|
||||
if !queryAttributes && !queryScope {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
var selectExprs []string
|
||||
var contexts []telemetrytypes.FieldContext
|
||||
if queryAttributes {
|
||||
selectExprs = append(selectExprs, fmt.Sprintf("distinctJSONPathsAndTypes(%s)", audittelemetryschema.AttributesColumn))
|
||||
contexts = append(contexts, telemetrytypes.FieldContextAttribute)
|
||||
}
|
||||
if queryScope {
|
||||
selectExprs = append(selectExprs, fmt.Sprintf("distinctJSONPathsAndTypes(%s.attributes)", audittelemetryschema.ScopeColumn))
|
||||
contexts = append(contexts, telemetrytypes.FieldContextScope)
|
||||
}
|
||||
|
||||
sb := sqlbuilder.Select(selectExprs...).From(t.auditDBName + "." + t.auditLogsTblName)
|
||||
t.applyAuditLogLookback(sb)
|
||||
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
|
||||
|
||||
rows, err := t.telemetrystore.ClickhouseDB().Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditKeys.Error())
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
if !rows.Next() {
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditKeys.Error())
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
pathMaps := make([]map[string][]string, len(contexts))
|
||||
dests := make([]any, len(contexts))
|
||||
for i := range pathMaps {
|
||||
dests[i] = &pathMaps[i]
|
||||
}
|
||||
if err := rows.Scan(dests...); err != nil {
|
||||
return nil, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditKeys.Error())
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditKeys.Error())
|
||||
}
|
||||
|
||||
var keys []*telemetrytypes.TelemetryFieldKey
|
||||
for i, fieldContext := range contexts {
|
||||
for path, chTypes := range pathMaps[i] {
|
||||
seenTypes := make(map[telemetrytypes.FieldDataType]struct{}, len(chTypes))
|
||||
for _, chType := range chTypes {
|
||||
dataType := clickhouseJSONTypeToFieldDataType(chType)
|
||||
if _, seen := seenTypes[dataType]; seen {
|
||||
continue
|
||||
}
|
||||
seenTypes[dataType] = struct{}{}
|
||||
keys = append(keys, &telemetrytypes.TelemetryFieldKey{
|
||||
Name: path,
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
FieldContext: fieldContext,
|
||||
FieldDataType: dataType,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
func (t *telemetryMetaStore) getAuditResourceKeys(ctx context.Context, fieldKeySelectors []*telemetrytypes.FieldKeySelector, limit int) ([]*telemetrytypes.TelemetryFieldKey, bool, error) {
|
||||
sb := sqlbuilder.Select("DISTINCT arrayJoin(JSONExtractKeys(labels)) AS tag_key").
|
||||
From(t.auditDBName + "." + t.auditLogsResourceTblName)
|
||||
|
||||
var conds []string
|
||||
matchAll := false
|
||||
matchedAnySelector := false
|
||||
for _, sel := range fieldKeySelectors {
|
||||
if sel.FieldContext != telemetrytypes.FieldContextUnspecified && sel.FieldContext != telemetrytypes.FieldContextResource {
|
||||
continue
|
||||
}
|
||||
if sel.FieldDataType != telemetrytypes.FieldDataTypeUnspecified && sel.FieldDataType != telemetrytypes.FieldDataTypeString {
|
||||
continue
|
||||
}
|
||||
matchedAnySelector = true
|
||||
if sel.SelectorMatchType == telemetrytypes.FieldSelectorMatchTypeExact {
|
||||
conds = append(conds, sb.E("tag_key", sel.Name))
|
||||
} else if sel.Name == "" {
|
||||
matchAll = true
|
||||
} else {
|
||||
conds = append(conds, sb.ILike("tag_key", "%"+clickhousesql.LikePattern(sel.Name)+"%"))
|
||||
}
|
||||
}
|
||||
if !matchedAnySelector {
|
||||
return nil, true, nil
|
||||
}
|
||||
if !matchAll && len(conds) > 0 {
|
||||
sb.Where(sb.Or(conds...))
|
||||
}
|
||||
t.applyAuditResourceLookback(sb)
|
||||
sb.Limit(limit + 1)
|
||||
|
||||
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
|
||||
rows, err := t.telemetrystore.ClickhouseDB().Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, false, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditKeys.Error())
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var keys []*telemetrytypes.TelemetryFieldKey
|
||||
rowCount := 0
|
||||
for rows.Next() {
|
||||
rowCount++
|
||||
if rowCount > limit {
|
||||
break
|
||||
}
|
||||
var name string
|
||||
if err := rows.Scan(&name); err != nil {
|
||||
return nil, false, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditKeys.Error())
|
||||
}
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
keys = append(keys, &telemetrytypes.TelemetryFieldKey{
|
||||
Name: name,
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
FieldContext: telemetrytypes.FieldContextResource,
|
||||
FieldDataType: telemetrytypes.FieldDataTypeString,
|
||||
})
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, false, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditKeys.Error())
|
||||
}
|
||||
|
||||
return keys, rowCount <= limit, nil
|
||||
}
|
||||
|
||||
func clickhouseJSONTypeToFieldDataType(chType string) telemetrytypes.FieldDataType {
|
||||
for {
|
||||
switch {
|
||||
case strings.HasPrefix(chType, "Nullable(") && strings.HasSuffix(chType, ")"):
|
||||
chType = chType[len("Nullable(") : len(chType)-1]
|
||||
case strings.HasPrefix(chType, "LowCardinality(") && strings.HasSuffix(chType, ")"):
|
||||
chType = chType[len("LowCardinality(") : len(chType)-1]
|
||||
default:
|
||||
switch chType {
|
||||
case "String":
|
||||
return telemetrytypes.FieldDataTypeString
|
||||
case "Bool":
|
||||
return telemetrytypes.FieldDataTypeBool
|
||||
case "Int8", "Int16", "Int32", "Int64",
|
||||
"UInt8", "UInt16", "UInt32", "UInt64",
|
||||
"Float32", "Float64":
|
||||
return telemetrytypes.FieldDataTypeNumber
|
||||
default:
|
||||
return telemetrytypes.FieldDataTypeString
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// appendStaticAuditKeys adds the matching intrinsic audit fields.
|
||||
func appendStaticAuditKeys(keys []*telemetrytypes.TelemetryFieldKey, mapOfKeys map[string]*telemetrytypes.TelemetryFieldKey, fieldKeySelectors []*telemetrytypes.FieldKeySelector) []*telemetrytypes.TelemetryFieldKey {
|
||||
for _, field := range audittelemetryschema.IntrinsicFields {
|
||||
if !staticFieldMatchesAny(field, fieldKeySelectors) {
|
||||
continue
|
||||
}
|
||||
if _, added := mapOfKeys[field.Name+";"+field.FieldContext.StringValue()+";"+field.FieldDataType.StringValue()]; added {
|
||||
continue
|
||||
}
|
||||
keys = append(keys, &field)
|
||||
}
|
||||
|
||||
return keys
|
||||
}
|
||||
|
||||
func (t *telemetryMetaStore) getAuditFieldValues(ctx context.Context, fieldValueSelector *telemetrytypes.FieldValueSelector) (*telemetrytypes.TelemetryFieldValues, bool, error) {
|
||||
ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{
|
||||
instrumentationtypes.TelemetrySignal: telemetrytypes.SignalLogs.StringValue(),
|
||||
instrumentationtypes.CodeNamespace: "metadata",
|
||||
instrumentationtypes.CodeFunctionName: "getAuditFieldValues",
|
||||
})
|
||||
|
||||
if fieldValueSelector.Name == "" {
|
||||
return &telemetrytypes.TelemetryFieldValues{}, true, nil
|
||||
}
|
||||
|
||||
limit := fieldValueSelector.Limit
|
||||
if limit == 0 {
|
||||
limit = 50
|
||||
}
|
||||
|
||||
switch fieldValueSelector.FieldContext {
|
||||
case telemetrytypes.FieldContextLog:
|
||||
field, ok := audittelemetryschema.IntrinsicFields[fieldValueSelector.Name]
|
||||
if !ok || field.FieldContext != telemetrytypes.FieldContextLog {
|
||||
return &telemetrytypes.TelemetryFieldValues{}, true, nil
|
||||
}
|
||||
return t.getAuditIntrinsicFieldValues(ctx, fieldValueSelector, field, limit)
|
||||
case telemetrytypes.FieldContextScope:
|
||||
return t.getAuditScopeFieldValues(ctx, fieldValueSelector, limit)
|
||||
case telemetrytypes.FieldContextResource:
|
||||
return t.getAuditResourceFieldValues(ctx, fieldValueSelector, limit)
|
||||
case telemetrytypes.FieldContextAttribute:
|
||||
return t.getAuditAttributeFieldValues(ctx, fieldValueSelector, limit)
|
||||
case telemetrytypes.FieldContextUnspecified:
|
||||
if field, ok := audittelemetryschema.IntrinsicFields[fieldValueSelector.Name]; ok {
|
||||
if field.FieldContext == telemetrytypes.FieldContextScope {
|
||||
return t.getAuditScopeFieldValues(ctx, fieldValueSelector, limit)
|
||||
}
|
||||
return t.getAuditIntrinsicFieldValues(ctx, fieldValueSelector, field, limit)
|
||||
}
|
||||
|
||||
resourceValues, resourceComplete, err := t.getAuditResourceFieldValues(ctx, fieldValueSelector, limit)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
attrValues, attrComplete, err := t.getAuditAttributeFieldValues(ctx, fieldValueSelector, limit)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
merged, mergeComplete := mergeFieldValues(limit, resourceValues, attrValues)
|
||||
return merged, resourceComplete && attrComplete && mergeComplete, nil
|
||||
default:
|
||||
return &telemetrytypes.TelemetryFieldValues{}, true, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (t *telemetryMetaStore) getAuditIntrinsicFieldValues(ctx context.Context, fieldValueSelector *telemetrytypes.FieldValueSelector, field telemetrytypes.TelemetryFieldKey, limit int) (*telemetrytypes.TelemetryFieldValues, bool, error) {
|
||||
isNumeric := isAuditNumericFieldDataType(field.FieldDataType)
|
||||
if fieldValueSelector.FieldDataType != telemetrytypes.FieldDataTypeUnspecified {
|
||||
if isNumeric && !isAuditNumericFieldDataType(fieldValueSelector.FieldDataType) {
|
||||
return &telemetrytypes.TelemetryFieldValues{}, true, nil
|
||||
}
|
||||
if !isNumeric && fieldValueSelector.FieldDataType != field.FieldDataType {
|
||||
return &telemetrytypes.TelemetryFieldValues{}, true, nil
|
||||
}
|
||||
}
|
||||
|
||||
colExpr := field.Name
|
||||
if field.Name == audittelemetryschema.BodyColumn {
|
||||
colExpr = audittelemetryschema.BodyColumn + ".message"
|
||||
}
|
||||
|
||||
if isNumeric {
|
||||
sb := sqlbuilder.Select(fmt.Sprintf("DISTINCT toFloat64(%s)", colExpr)).
|
||||
From(t.auditDBName + "." + t.auditLogsTblName)
|
||||
if fieldValueSelector.Value != "" {
|
||||
sb.Where(sb.ILike(fmt.Sprintf("toString(%s)", colExpr), "%"+clickhousesql.LikePattern(fieldValueSelector.Value)+"%"))
|
||||
}
|
||||
t.applyAuditLogLookback(sb)
|
||||
sb.Limit(limit + 1)
|
||||
return t.queryAuditNumberValues(ctx, sb, limit)
|
||||
}
|
||||
|
||||
sb := sqlbuilder.Select("DISTINCT " + colExpr).
|
||||
From(t.auditDBName + "." + t.auditLogsTblName)
|
||||
sb.Where(sb.NE(colExpr, ""))
|
||||
if fieldValueSelector.Value != "" {
|
||||
sb.Where(sb.ILike(colExpr, "%"+clickhousesql.LikePattern(fieldValueSelector.Value)+"%"))
|
||||
}
|
||||
t.applyAuditLogLookback(sb)
|
||||
sb.Limit(limit + 1)
|
||||
return t.queryAuditStringValues(ctx, sb, limit)
|
||||
}
|
||||
|
||||
func (t *telemetryMetaStore) getAuditScopeFieldValues(ctx context.Context, fieldValueSelector *telemetrytypes.FieldValueSelector, limit int) (*telemetrytypes.TelemetryFieldValues, bool, error) {
|
||||
if fieldValueSelector.FieldDataType != telemetrytypes.FieldDataTypeUnspecified && fieldValueSelector.FieldDataType != telemetrytypes.FieldDataTypeString {
|
||||
return &telemetrytypes.TelemetryFieldValues{}, true, nil
|
||||
}
|
||||
|
||||
var rawPath, expr string
|
||||
isDynamic := false
|
||||
switch fieldValueSelector.Name {
|
||||
case "name", "scope.name":
|
||||
expr = audittelemetryschema.ScopeColumn + ".name"
|
||||
case "version", "scope.version":
|
||||
expr = audittelemetryschema.ScopeColumn + ".version"
|
||||
default:
|
||||
rawPath = fmt.Sprintf("%s.attributes.%s", audittelemetryschema.ScopeColumn, clickhousesql.Identifier(fieldValueSelector.Name))
|
||||
expr = rawPath + "::String"
|
||||
isDynamic = true
|
||||
}
|
||||
|
||||
escapedExpr := sqlbuilder.Escape(expr)
|
||||
sb := sqlbuilder.Select("DISTINCT " + escapedExpr).From(t.auditDBName + "." + t.auditLogsTblName)
|
||||
if isDynamic {
|
||||
sb.Where(sqlbuilder.Escape(rawPath) + " IS NOT NULL")
|
||||
}
|
||||
sb.Where(escapedExpr + " <> ''")
|
||||
if fieldValueSelector.Value != "" {
|
||||
sb.Where(sb.ILike(expr, "%"+clickhousesql.LikePattern(fieldValueSelector.Value)+"%"))
|
||||
}
|
||||
t.applyAuditLogLookback(sb)
|
||||
sb.Limit(limit + 1)
|
||||
|
||||
return t.queryAuditStringValues(ctx, sb, limit)
|
||||
}
|
||||
|
||||
func (t *telemetryMetaStore) getAuditResourceFieldValues(ctx context.Context, fieldValueSelector *telemetrytypes.FieldValueSelector, limit int) (*telemetrytypes.TelemetryFieldValues, bool, error) {
|
||||
if fieldValueSelector.FieldDataType != telemetrytypes.FieldDataTypeUnspecified && fieldValueSelector.FieldDataType != telemetrytypes.FieldDataTypeString {
|
||||
return &telemetrytypes.TelemetryFieldValues{}, true, nil
|
||||
}
|
||||
|
||||
sb := sqlbuilder.NewSelectBuilder()
|
||||
extractExpr := func() string {
|
||||
return fmt.Sprintf("JSONExtractString(labels, %s)", sb.Var(fieldValueSelector.Name))
|
||||
}
|
||||
sb.Select("DISTINCT " + extractExpr() + " AS val").
|
||||
From(t.auditDBName + "." + t.auditLogsResourceTblName).
|
||||
Where(extractExpr() + " <> ''")
|
||||
|
||||
if fieldValueSelector.Value != "" {
|
||||
sb.Where(fmt.Sprintf("LOWER(%s) LIKE LOWER(%s)", extractExpr(), sb.Var("%"+clickhousesql.LikePattern(fieldValueSelector.Value)+"%")))
|
||||
}
|
||||
t.applyAuditResourceLookback(sb)
|
||||
sb.Limit(limit + 1)
|
||||
|
||||
return t.queryAuditStringValues(ctx, sb, limit)
|
||||
}
|
||||
|
||||
func (t *telemetryMetaStore) getAuditAttributeFieldValues(ctx context.Context, fieldValueSelector *telemetrytypes.FieldValueSelector, limit int) (*telemetrytypes.TelemetryFieldValues, bool, error) {
|
||||
rawPath := fmt.Sprintf("%s.%s", audittelemetryschema.AttributesColumn, clickhousesql.Identifier(fieldValueSelector.Name))
|
||||
escapedPath := sqlbuilder.Escape(rawPath)
|
||||
|
||||
switch fieldValueSelector.FieldDataType {
|
||||
case telemetrytypes.FieldDataTypeString:
|
||||
return t.getAuditStringAttributeFieldValues(ctx, rawPath, escapedPath, fieldValueSelector.Value, limit)
|
||||
case telemetrytypes.FieldDataTypeNumber, telemetrytypes.FieldDataTypeInt64, telemetrytypes.FieldDataTypeFloat64:
|
||||
return t.getAuditNumberAttributeFieldValues(ctx, rawPath, escapedPath, fieldValueSelector.Value, limit)
|
||||
case telemetrytypes.FieldDataTypeBool:
|
||||
return t.getAuditBoolAttributeFieldValues(ctx, rawPath, escapedPath, fieldValueSelector.Value, limit)
|
||||
case telemetrytypes.FieldDataTypeUnspecified:
|
||||
return t.getAuditUnspecifiedAttributeFieldValues(ctx, rawPath, escapedPath, fieldValueSelector.Value, limit)
|
||||
default:
|
||||
return &telemetrytypes.TelemetryFieldValues{}, true, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (t *telemetryMetaStore) getAuditStringAttributeFieldValues(ctx context.Context, rawPath, escapedPath, searchValue string, limit int) (*telemetrytypes.TelemetryFieldValues, bool, error) {
|
||||
rawStrExpr := rawPath + "::String"
|
||||
strExpr := escapedPath + "::String"
|
||||
|
||||
sb := sqlbuilder.Select("DISTINCT " + strExpr).From(t.auditDBName + "." + t.auditLogsTblName)
|
||||
sb.Where(escapedPath+" IS NOT NULL", strExpr+" <> ''")
|
||||
if searchValue != "" {
|
||||
sb.Where(sb.ILike(rawStrExpr, "%"+clickhousesql.LikePattern(searchValue)+"%"))
|
||||
}
|
||||
t.applyAuditLogLookback(sb)
|
||||
sb.Limit(limit + 1)
|
||||
|
||||
return t.queryAuditStringValues(ctx, sb, limit)
|
||||
}
|
||||
|
||||
func (t *telemetryMetaStore) getAuditNumberAttributeFieldValues(ctx context.Context, rawPath, escapedPath, searchValue string, limit int) (*telemetrytypes.TelemetryFieldValues, bool, error) {
|
||||
rawNumExpr := fmt.Sprintf("toFloat64OrNull(%s::String)", rawPath)
|
||||
numExpr := fmt.Sprintf("toFloat64OrNull(%s::String)", escapedPath)
|
||||
|
||||
sb := sqlbuilder.Select(fmt.Sprintf("DISTINCT assumeNotNull(%s)", numExpr)).From(t.auditDBName + "." + t.auditLogsTblName)
|
||||
sb.Where(numExpr + " IS NOT NULL")
|
||||
if searchValue != "" {
|
||||
sb.Where(sb.ILike(fmt.Sprintf("toString(%s)", rawNumExpr), "%"+clickhousesql.LikePattern(searchValue)+"%"))
|
||||
}
|
||||
t.applyAuditLogLookback(sb)
|
||||
sb.Limit(limit + 1)
|
||||
|
||||
return t.queryAuditNumberValues(ctx, sb, limit)
|
||||
}
|
||||
|
||||
func (t *telemetryMetaStore) getAuditBoolAttributeFieldValues(ctx context.Context, rawPath, escapedPath, searchValue string, limit int) (*telemetrytypes.TelemetryFieldValues, bool, error) {
|
||||
rawStrExpr := rawPath + "::String"
|
||||
strExpr := escapedPath + "::String"
|
||||
|
||||
sb := sqlbuilder.Select("DISTINCT " + strExpr).From(t.auditDBName + "." + t.auditLogsTblName)
|
||||
sb.Where(fmt.Sprintf("dynamicType(%s) = 'Bool'", escapedPath))
|
||||
if searchValue != "" {
|
||||
sb.Where(sb.ILike(rawStrExpr, "%"+clickhousesql.LikePattern(searchValue)+"%"))
|
||||
}
|
||||
t.applyAuditLogLookback(sb)
|
||||
sb.Limit(limit + 1)
|
||||
|
||||
return t.queryAuditBoolValues(ctx, sb, limit)
|
||||
}
|
||||
|
||||
func (t *telemetryMetaStore) getAuditUnspecifiedAttributeFieldValues(ctx context.Context, rawPath, escapedPath, searchValue string, limit int) (*telemetrytypes.TelemetryFieldValues, bool, error) {
|
||||
rawStrExpr := rawPath + "::String"
|
||||
strExpr := escapedPath + "::String"
|
||||
|
||||
sb := sqlbuilder.Select(fmt.Sprintf("DISTINCT dynamicType(%s)", escapedPath), strExpr).
|
||||
From(t.auditDBName + "." + t.auditLogsTblName)
|
||||
sb.Where(escapedPath+" IS NOT NULL", strExpr+" <> ''")
|
||||
if searchValue != "" {
|
||||
sb.Where(sb.ILike(rawStrExpr, "%"+clickhousesql.LikePattern(searchValue)+"%"))
|
||||
}
|
||||
t.applyAuditLogLookback(sb)
|
||||
sb.Limit(limit + 1)
|
||||
|
||||
return t.queryAuditDynamicValues(ctx, sb, limit)
|
||||
}
|
||||
|
||||
func (t *telemetryMetaStore) queryAuditStringValues(ctx context.Context, sb *sqlbuilder.SelectBuilder, limit int) (*telemetrytypes.TelemetryFieldValues, bool, error) {
|
||||
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
|
||||
rows, err := t.telemetrystore.ClickhouseDB().Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, false, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditValues.Error())
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
values := &telemetrytypes.TelemetryFieldValues{}
|
||||
rowCount := 0
|
||||
for rows.Next() {
|
||||
rowCount++
|
||||
if rowCount > limit {
|
||||
break
|
||||
}
|
||||
var strVal string
|
||||
if err := rows.Scan(&strVal); err != nil {
|
||||
return nil, false, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditValues.Error())
|
||||
}
|
||||
if strVal != "" {
|
||||
values.StringValues = append(values.StringValues, strVal)
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, false, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditValues.Error())
|
||||
}
|
||||
|
||||
return values, rowCount <= limit, nil
|
||||
}
|
||||
|
||||
func (t *telemetryMetaStore) queryAuditNumberValues(ctx context.Context, sb *sqlbuilder.SelectBuilder, limit int) (*telemetrytypes.TelemetryFieldValues, bool, error) {
|
||||
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
|
||||
rows, err := t.telemetrystore.ClickhouseDB().Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, false, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditValues.Error())
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
values := &telemetrytypes.TelemetryFieldValues{}
|
||||
rowCount := 0
|
||||
for rows.Next() {
|
||||
rowCount++
|
||||
if rowCount > limit {
|
||||
break
|
||||
}
|
||||
var numVal float64
|
||||
if err := rows.Scan(&numVal); err != nil {
|
||||
return nil, false, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditValues.Error())
|
||||
}
|
||||
values.NumberValues = append(values.NumberValues, numVal)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, false, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditValues.Error())
|
||||
}
|
||||
|
||||
return values, rowCount <= limit, nil
|
||||
}
|
||||
|
||||
func (t *telemetryMetaStore) queryAuditBoolValues(ctx context.Context, sb *sqlbuilder.SelectBuilder, limit int) (*telemetrytypes.TelemetryFieldValues, bool, error) {
|
||||
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
|
||||
rows, err := t.telemetrystore.ClickhouseDB().Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, false, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditValues.Error())
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
values := &telemetrytypes.TelemetryFieldValues{}
|
||||
seenBool := make(map[bool]struct{})
|
||||
rowCount := 0
|
||||
for rows.Next() {
|
||||
rowCount++
|
||||
if rowCount > limit {
|
||||
break
|
||||
}
|
||||
var strVal string
|
||||
if err := rows.Scan(&strVal); err != nil {
|
||||
return nil, false, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditValues.Error())
|
||||
}
|
||||
boolVal, err := strconv.ParseBool(strVal)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if _, ok := seenBool[boolVal]; !ok {
|
||||
seenBool[boolVal] = struct{}{}
|
||||
values.BoolValues = append(values.BoolValues, boolVal)
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, false, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditValues.Error())
|
||||
}
|
||||
|
||||
return values, rowCount <= limit, nil
|
||||
}
|
||||
|
||||
func (t *telemetryMetaStore) queryAuditDynamicValues(ctx context.Context, sb *sqlbuilder.SelectBuilder, limit int) (*telemetrytypes.TelemetryFieldValues, bool, error) {
|
||||
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
|
||||
rows, err := t.telemetrystore.ClickhouseDB().Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, false, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditValues.Error())
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
values := &telemetrytypes.TelemetryFieldValues{}
|
||||
seenStr := make(map[string]struct{})
|
||||
seenNum := make(map[float64]struct{})
|
||||
seenBool := make(map[bool]struct{})
|
||||
rowCount := 0
|
||||
for rows.Next() {
|
||||
rowCount++
|
||||
if rowCount > limit {
|
||||
break
|
||||
}
|
||||
var dynamicType, strVal string
|
||||
if err := rows.Scan(&dynamicType, &strVal); err != nil {
|
||||
return nil, false, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditValues.Error())
|
||||
}
|
||||
if strVal == "" {
|
||||
continue
|
||||
}
|
||||
switch clickhouseJSONTypeToFieldDataType(dynamicType) {
|
||||
case telemetrytypes.FieldDataTypeBool:
|
||||
if boolVal, err := strconv.ParseBool(strVal); err == nil {
|
||||
if _, seen := seenBool[boolVal]; !seen {
|
||||
seenBool[boolVal] = struct{}{}
|
||||
values.BoolValues = append(values.BoolValues, boolVal)
|
||||
}
|
||||
}
|
||||
case telemetrytypes.FieldDataTypeNumber:
|
||||
if numVal, err := strconv.ParseFloat(strVal, 64); err == nil {
|
||||
if _, seen := seenNum[numVal]; !seen {
|
||||
seenNum[numVal] = struct{}{}
|
||||
values.NumberValues = append(values.NumberValues, numVal)
|
||||
}
|
||||
}
|
||||
default:
|
||||
if _, seen := seenStr[strVal]; !seen {
|
||||
seenStr[strVal] = struct{}{}
|
||||
values.StringValues = append(values.StringValues, strVal)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, false, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditValues.Error())
|
||||
}
|
||||
|
||||
return values, rowCount <= limit, nil
|
||||
}
|
||||
|
||||
func (t *telemetryMetaStore) auditLookbackBounds() (startNs uint64, startBucket uint64) {
|
||||
nowFn := t.now
|
||||
if nowFn == nil {
|
||||
nowFn = time.Now
|
||||
}
|
||||
cutoff := nowFn().Add(-auditLookbackWindow)
|
||||
startNs = uint64(cutoff.UnixNano())
|
||||
startSec := uint64(cutoff.Unix())
|
||||
if startSec > querybuilder.BucketAdjustment {
|
||||
startBucket = startSec - querybuilder.BucketAdjustment
|
||||
}
|
||||
return startNs, startBucket
|
||||
}
|
||||
|
||||
func (t *telemetryMetaStore) applyAuditLogLookback(sb *sqlbuilder.SelectBuilder) {
|
||||
startNs, startBucket := t.auditLookbackBounds()
|
||||
sb.Where(
|
||||
sb.GE(audittelemetryschema.TimestampColumn, startNs),
|
||||
sb.GE(audittelemetryschema.TimestampBucketStartColumn, startBucket),
|
||||
)
|
||||
}
|
||||
|
||||
func (t *telemetryMetaStore) applyAuditResourceLookback(sb *sqlbuilder.SelectBuilder) {
|
||||
_, startBucket := t.auditLookbackBounds()
|
||||
sb.Where(sb.GE("seen_at_ts_bucket_start", startBucket))
|
||||
}
|
||||
|
||||
func isAuditNumericFieldDataType(dataType telemetrytypes.FieldDataType) bool {
|
||||
switch dataType {
|
||||
case telemetrytypes.FieldDataTypeNumber, telemetrytypes.FieldDataTypeInt64, telemetrytypes.FieldDataTypeFloat64:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
530
pkg/telemetrymetadata/audit_test.go
Normal file
530
pkg/telemetrymetadata/audit_test.go
Normal file
@@ -0,0 +1,530 @@
|
||||
package telemetrymetadata
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
cmock "github.com/SigNoz/clickhouse-go-mock"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/flagger/flaggertest"
|
||||
"github.com/SigNoz/signoz/pkg/instrumentation/instrumentationtest"
|
||||
"github.com/SigNoz/signoz/pkg/querybuilder"
|
||||
"github.com/SigNoz/signoz/pkg/telemetrystore"
|
||||
"github.com/SigNoz/signoz/pkg/telemetrystore/telemetrystoretest"
|
||||
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
)
|
||||
|
||||
func newAuditTestMetaStore(t *testing.T) (*telemetryMetaStore, cmock.ClickConnMockCommon, uint64, uint64) {
|
||||
t.Helper()
|
||||
|
||||
mockTelemetryStore := telemetrystoretest.New(telemetrystore.Config{}, ®exMatcher{})
|
||||
store := NewTelemetryMetaStore(instrumentationtest.New().ToProviderSettings(), mockTelemetryStore, flaggertest.New(t)).(*telemetryMetaStore)
|
||||
fixedNow := time.Unix(1730000000, 0).UTC()
|
||||
store.now = func() time.Time { return fixedNow }
|
||||
|
||||
cutoff := fixedNow.Add(-auditLookbackWindow)
|
||||
startNs := uint64(cutoff.UnixNano())
|
||||
startBucket := uint64(cutoff.Unix()) - querybuilder.BucketAdjustment
|
||||
return store, mockTelemetryStore.Mock(), startNs, startBucket
|
||||
}
|
||||
|
||||
func TestGetAuditKeys_UnspecifiedContextDiscoversAllAndMergesIntrinsics(t *testing.T) {
|
||||
metadata, mock, startNs, startBucket := newAuditTestMetaStore(t)
|
||||
|
||||
mock.ExpectQuery(`SELECT distinctJSONPathsAndTypes\(attributes\), distinctJSONPathsAndTypes\(scope\.attributes\) FROM signoz_audit\.distributed_logs WHERE timestamp >= \? AND ts_bucket_start >= \?$`).
|
||||
WithArgs(startNs, startBucket).
|
||||
WillReturnRows(cmock.NewRows(
|
||||
[]cmock.ColumnType{
|
||||
{Name: "attr_paths", Type: "Map(String, Array(String))"},
|
||||
{Name: "scope_paths", Type: "Map(String, Array(String))"},
|
||||
},
|
||||
[][]any{{
|
||||
map[string][]string{
|
||||
"signoz.audit.verb": {"LowCardinality(String)"},
|
||||
"http.response.status_code": {"Int64", "Float64"},
|
||||
"signoz.audit.dry_run": {"Nullable(Bool)"},
|
||||
},
|
||||
map[string][]string{
|
||||
"scope.custom": {"String"},
|
||||
},
|
||||
}},
|
||||
))
|
||||
|
||||
mock.ExpectQuery(`SELECT DISTINCT arrayJoin\(JSONExtractKeys\(labels\)\) AS tag_key FROM signoz_audit\.distributed_logs_resource WHERE seen_at_ts_bucket_start >= \? LIMIT \?`).
|
||||
WithArgs(startBucket, 1001).
|
||||
WillReturnRows(cmock.NewRows(
|
||||
[]cmock.ColumnType{{Name: "tag_key", Type: "String"}},
|
||||
[][]any{{"signoz.resource.kind"}, {"service.name"}},
|
||||
))
|
||||
|
||||
selector := telemetrytypes.NewFieldKeySelectorFromPostableFieldKeysParams(telemetrytypes.PostableFieldKeysParams{
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
Source: telemetrytypes.SourceAudit,
|
||||
StartUnixMilli: 1700000000000,
|
||||
EndUnixMilli: 1700003600000,
|
||||
})
|
||||
|
||||
keys, complete, err := metadata.GetKeys(context.Background(), valuer.GenerateUUID(), selector)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, complete)
|
||||
|
||||
require.Len(t, keys["signoz.audit.verb"], 1)
|
||||
assert.Equal(t, telemetrytypes.FieldContextAttribute, keys["signoz.audit.verb"][0].FieldContext)
|
||||
assert.Equal(t, telemetrytypes.FieldDataTypeString, keys["signoz.audit.verb"][0].FieldDataType)
|
||||
|
||||
require.Len(t, keys["http.response.status_code"], 1)
|
||||
assert.Equal(t, telemetrytypes.FieldContextAttribute, keys["http.response.status_code"][0].FieldContext)
|
||||
assert.Equal(t, telemetrytypes.FieldDataTypeNumber, keys["http.response.status_code"][0].FieldDataType)
|
||||
|
||||
require.Len(t, keys["signoz.audit.dry_run"], 1)
|
||||
assert.Equal(t, telemetrytypes.FieldContextAttribute, keys["signoz.audit.dry_run"][0].FieldContext)
|
||||
assert.Equal(t, telemetrytypes.FieldDataTypeBool, keys["signoz.audit.dry_run"][0].FieldDataType)
|
||||
|
||||
require.Len(t, keys["scope.custom"], 1)
|
||||
assert.Equal(t, telemetrytypes.FieldContextScope, keys["scope.custom"][0].FieldContext)
|
||||
|
||||
require.Len(t, keys["signoz.resource.kind"], 1)
|
||||
assert.Equal(t, telemetrytypes.FieldContextResource, keys["signoz.resource.kind"][0].FieldContext)
|
||||
|
||||
require.Len(t, keys["event_name"], 1)
|
||||
assert.Equal(t, telemetrytypes.FieldContextLog, keys["event_name"][0].FieldContext)
|
||||
|
||||
require.Len(t, keys["scope.name"], 1)
|
||||
assert.Equal(t, telemetrytypes.FieldContextScope, keys["scope.name"][0].FieldContext)
|
||||
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestGetAuditKeys_ContextAndDataTypeFiltering(t *testing.T) {
|
||||
t.Run("LogContextSkipsClickHouse", func(t *testing.T) {
|
||||
metadata, mock, _, _ := newAuditTestMetaStore(t)
|
||||
|
||||
selector := telemetrytypes.NewFieldKeySelectorFromPostableFieldKeysParams(telemetrytypes.PostableFieldKeysParams{
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
Source: telemetrytypes.SourceAudit,
|
||||
FieldContext: telemetrytypes.FieldContextLog,
|
||||
})
|
||||
|
||||
keys, complete, err := metadata.GetKeys(context.Background(), valuer.GenerateUUID(), selector)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, complete)
|
||||
assert.Contains(t, keys, "body")
|
||||
assert.Contains(t, keys, "event_name")
|
||||
assert.Contains(t, keys, "severity_number")
|
||||
assert.NotContains(t, keys, "scope.name")
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
})
|
||||
|
||||
t.Run("NumberDataTypeSkipsResourceTable", func(t *testing.T) {
|
||||
metadata, mock, startNs, startBucket := newAuditTestMetaStore(t)
|
||||
|
||||
mock.ExpectQuery(`SELECT distinctJSONPathsAndTypes\(attributes\), distinctJSONPathsAndTypes\(scope\.attributes\) FROM signoz_audit\.distributed_logs WHERE timestamp >= \? AND ts_bucket_start >= \?$`).
|
||||
WithArgs(startNs, startBucket).
|
||||
WillReturnRows(cmock.NewRows(
|
||||
[]cmock.ColumnType{
|
||||
{Name: "attr_paths", Type: "Map(String, Array(String))"},
|
||||
{Name: "scope_paths", Type: "Map(String, Array(String))"},
|
||||
},
|
||||
[][]any{{
|
||||
map[string][]string{
|
||||
"signoz.audit.verb": {"String"},
|
||||
"http.response.status_code": {"Int64"},
|
||||
},
|
||||
map[string][]string{},
|
||||
}},
|
||||
))
|
||||
|
||||
selector := telemetrytypes.NewFieldKeySelectorFromPostableFieldKeysParams(telemetrytypes.PostableFieldKeysParams{
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
Source: telemetrytypes.SourceAudit,
|
||||
FieldDataType: telemetrytypes.FieldDataTypeNumber,
|
||||
})
|
||||
|
||||
keys, complete, err := metadata.GetKeys(context.Background(), valuer.GenerateUUID(), selector)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, complete)
|
||||
assert.Contains(t, keys, "http.response.status_code")
|
||||
assert.Contains(t, keys, "severity_number")
|
||||
assert.Contains(t, keys, "trace_flags")
|
||||
assert.NotContains(t, keys, "signoz.audit.verb")
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
})
|
||||
|
||||
t.Run("LimitTruncationMarksIncompleteAndKeepsIntrinsics", func(t *testing.T) {
|
||||
metadata, mock, startNs, startBucket := newAuditTestMetaStore(t)
|
||||
|
||||
mock.ExpectQuery(`SELECT distinctJSONPathsAndTypes\(attributes\) FROM signoz_audit\.distributed_logs WHERE timestamp >= \? AND ts_bucket_start >= \?$`).
|
||||
WithArgs(startNs, startBucket).
|
||||
WillReturnRows(cmock.NewRows(
|
||||
[]cmock.ColumnType{{Name: "attr_paths", Type: "Map(String, Array(String))"}},
|
||||
[][]any{{
|
||||
map[string][]string{
|
||||
"attr.a": {"String"},
|
||||
"attr.b": {"String"},
|
||||
"attr.c": {"String"},
|
||||
},
|
||||
}},
|
||||
))
|
||||
|
||||
selector := telemetrytypes.NewFieldKeySelectorFromPostableFieldKeysParams(telemetrytypes.PostableFieldKeysParams{
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
Source: telemetrytypes.SourceAudit,
|
||||
FieldContext: telemetrytypes.FieldContextAttribute,
|
||||
Limit: 2,
|
||||
})
|
||||
|
||||
keys, complete, err := metadata.GetKeys(context.Background(), valuer.GenerateUUID(), selector)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, complete)
|
||||
assert.Len(t, keys, 2)
|
||||
assert.Contains(t, keys, "attr.a")
|
||||
assert.Contains(t, keys, "attr.b")
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
})
|
||||
|
||||
t.Run("EmptyTableStillReturnsIntrinsics", func(t *testing.T) {
|
||||
metadata, mock, startNs, startBucket := newAuditTestMetaStore(t)
|
||||
|
||||
mock.ExpectQuery(`SELECT distinctJSONPathsAndTypes\(attributes\), distinctJSONPathsAndTypes\(scope\.attributes\) FROM signoz_audit\.distributed_logs WHERE timestamp >= \? AND ts_bucket_start >= \?$`).
|
||||
WithArgs(startNs, startBucket).
|
||||
WillReturnRows(cmock.NewRows(
|
||||
[]cmock.ColumnType{
|
||||
{Name: "attr_paths", Type: "Map(String, Array(String))"},
|
||||
{Name: "scope_paths", Type: "Map(String, Array(String))"},
|
||||
},
|
||||
[][]any{},
|
||||
))
|
||||
mock.ExpectQuery(`SELECT DISTINCT arrayJoin\(JSONExtractKeys\(labels\)\) AS tag_key FROM signoz_audit\.distributed_logs_resource WHERE seen_at_ts_bucket_start >= \? LIMIT \?`).
|
||||
WithArgs(startBucket, 1001).
|
||||
WillReturnRows(cmock.NewRows([]cmock.ColumnType{{Name: "tag_key", Type: "String"}}, [][]any{}))
|
||||
|
||||
selector := telemetrytypes.NewFieldKeySelectorFromPostableFieldKeysParams(telemetrytypes.PostableFieldKeysParams{
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
Source: telemetrytypes.SourceAudit,
|
||||
})
|
||||
|
||||
keys, complete, err := metadata.GetKeys(context.Background(), valuer.GenerateUUID(), selector)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, complete)
|
||||
assert.Contains(t, keys, "event_name")
|
||||
assert.Contains(t, keys, "body")
|
||||
assert.Contains(t, keys, "scope.name")
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
})
|
||||
|
||||
t.Run("GetKeysMultiExactMatch", func(t *testing.T) {
|
||||
metadata, mock, startNs, startBucket := newAuditTestMetaStore(t)
|
||||
|
||||
mock.ExpectQuery(`SELECT distinctJSONPathsAndTypes\(attributes\), distinctJSONPathsAndTypes\(scope\.attributes\) FROM signoz_audit\.distributed_logs WHERE timestamp >= \? AND ts_bucket_start >= \?$`).
|
||||
WithArgs(startNs, startBucket).
|
||||
WillReturnRows(cmock.NewRows(
|
||||
[]cmock.ColumnType{
|
||||
{Name: "attr_paths", Type: "Map(String, Array(String))"},
|
||||
{Name: "scope_paths", Type: "Map(String, Array(String))"},
|
||||
},
|
||||
[][]any{{
|
||||
map[string][]string{"signoz.audit.verb": {"String"}, "other": {"String"}},
|
||||
map[string][]string{},
|
||||
}},
|
||||
))
|
||||
mock.ExpectQuery(`SELECT DISTINCT arrayJoin\(JSONExtractKeys\(labels\)\) AS tag_key FROM signoz_audit\.distributed_logs_resource WHERE \(tag_key = \? OR tag_key = \?\) AND seen_at_ts_bucket_start >= \? LIMIT \?`).
|
||||
WithArgs("signoz.resource.kind", "signoz.audit.verb", startBucket, 1001).
|
||||
WillReturnRows(cmock.NewRows(
|
||||
[]cmock.ColumnType{{Name: "tag_key", Type: "String"}},
|
||||
[][]any{{"signoz.resource.kind"}},
|
||||
))
|
||||
|
||||
keys, complete, err := metadata.GetKeysMulti(context.Background(), valuer.GenerateUUID(), []*telemetrytypes.FieldKeySelector{
|
||||
{Name: "signoz.resource.kind", Signal: telemetrytypes.SignalLogs, Source: telemetrytypes.SourceAudit, SelectorMatchType: telemetrytypes.FieldSelectorMatchTypeExact},
|
||||
{Name: "signoz.audit.verb", Signal: telemetrytypes.SignalLogs, Source: telemetrytypes.SourceAudit, SelectorMatchType: telemetrytypes.FieldSelectorMatchTypeExact},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.True(t, complete)
|
||||
assert.Contains(t, keys, "signoz.resource.kind")
|
||||
assert.Contains(t, keys, "signoz.audit.verb")
|
||||
assert.NotContains(t, keys, "other")
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
})
|
||||
}
|
||||
|
||||
func TestGetAuditFieldValues(t *testing.T) {
|
||||
t.Run("LogIntrinsicBodyAndNumericPreservesZero", func(t *testing.T) {
|
||||
metadata, mock, startNs, startBucket := newAuditTestMetaStore(t)
|
||||
|
||||
mock.ExpectQuery(`SELECT DISTINCT body\.message FROM signoz_audit\.distributed_logs WHERE body\.message <> \? AND LOWER\(body\.message\) LIKE LOWER\(\?\) AND timestamp >= \? AND ts_bucket_start >= \? LIMIT \?`).
|
||||
WithArgs("", "%created%", startNs, startBucket, 51).
|
||||
WillReturnRows(cmock.NewRows(
|
||||
[]cmock.ColumnType{{Name: "body.message", Type: "String"}},
|
||||
[][]any{{"alice created dashboard"}},
|
||||
))
|
||||
|
||||
bodySel := telemetrytypes.NewFieldValueSelectorFromPostableFieldValueParams(telemetrytypes.PostableFieldValueParams{
|
||||
Name: "body",
|
||||
PostableFieldKeysParams: telemetrytypes.PostableFieldKeysParams{
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
Source: telemetrytypes.SourceAudit,
|
||||
SearchText: "created",
|
||||
},
|
||||
})
|
||||
bodyVals, complete, err := metadata.GetAllValues(context.Background(), valuer.GenerateUUID(), bodySel)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, complete)
|
||||
assert.Equal(t, []string{"alice created dashboard"}, bodyVals.StringValues)
|
||||
|
||||
mock.ExpectQuery(`SELECT DISTINCT toFloat64\(severity_number\) FROM signoz_audit\.distributed_logs WHERE timestamp >= \? AND ts_bucket_start >= \? LIMIT \?`).
|
||||
WithArgs(startNs, startBucket, 51).
|
||||
WillReturnRows(cmock.NewRows(
|
||||
[]cmock.ColumnType{{Name: "severity_number", Type: "Float64"}},
|
||||
[][]any{{float64(0)}, {float64(9)}},
|
||||
))
|
||||
|
||||
sevSel := telemetrytypes.NewFieldValueSelectorFromPostableFieldValueParams(telemetrytypes.PostableFieldValueParams{
|
||||
Name: "severity_number",
|
||||
PostableFieldKeysParams: telemetrytypes.PostableFieldKeysParams{
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
Source: telemetrytypes.SourceAudit,
|
||||
},
|
||||
})
|
||||
sevVals, complete, err := metadata.GetAllValues(context.Background(), valuer.GenerateUUID(), sevSel)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, complete)
|
||||
assert.Equal(t, []float64{0, 9}, sevVals.NumberValues)
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
})
|
||||
|
||||
t.Run("ScopeNameViaPrefix", func(t *testing.T) {
|
||||
metadata, mock, startNs, startBucket := newAuditTestMetaStore(t)
|
||||
|
||||
// NameMatchSelectors tries both the literal key ("scope.name") and stripped ("name" with FieldContextScope).
|
||||
for range 2 {
|
||||
mock.ExpectQuery(`SELECT DISTINCT scope\.name FROM signoz_audit\.distributed_logs WHERE scope\.name <> '' AND timestamp >= \? AND ts_bucket_start >= \? LIMIT \?`).
|
||||
WithArgs(startNs, startBucket, 51).
|
||||
WillReturnRows(cmock.NewRows(
|
||||
[]cmock.ColumnType{{Name: "scope.name", Type: "String"}},
|
||||
[][]any{{"signoz.audit"}},
|
||||
))
|
||||
}
|
||||
|
||||
sel := telemetrytypes.NewFieldValueSelectorFromPostableFieldValueParams(telemetrytypes.PostableFieldValueParams{
|
||||
Name: "scope.name",
|
||||
PostableFieldKeysParams: telemetrytypes.PostableFieldKeysParams{
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
Source: telemetrytypes.SourceAudit,
|
||||
},
|
||||
})
|
||||
vals, complete, err := metadata.GetAllValues(context.Background(), valuer.GenerateUUID(), sel)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, complete)
|
||||
assert.Equal(t, []string{"signoz.audit"}, vals.StringValues)
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
})
|
||||
|
||||
t.Run("ResourceIgnoresCallerTimeBoundsAndAppliesLookback", func(t *testing.T) {
|
||||
metadata, mock, _, startBucket := newAuditTestMetaStore(t)
|
||||
|
||||
mock.ExpectQuery(`SELECT DISTINCT JSONExtractString\(labels, \?\) AS val FROM signoz_audit\.distributed_logs_resource WHERE JSONExtractString\(labels, \?\) <> '' AND LOWER\(JSONExtractString\(labels, \?\)\) LIKE LOWER\(\?\) AND seen_at_ts_bucket_start >= \? LIMIT \?`).
|
||||
WithArgs("signoz.resource.kind", "signoz.resource.kind", "signoz.resource.kind", "%dash%", startBucket, 51).
|
||||
WillReturnRows(cmock.NewRows(
|
||||
[]cmock.ColumnType{{Name: "val", Type: "String"}},
|
||||
[][]any{{"dashboard"}},
|
||||
))
|
||||
|
||||
sel := telemetrytypes.NewFieldValueSelectorFromPostableFieldValueParams(telemetrytypes.PostableFieldValueParams{
|
||||
Name: "signoz.resource.kind",
|
||||
PostableFieldKeysParams: telemetrytypes.PostableFieldKeysParams{
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
Source: telemetrytypes.SourceAudit,
|
||||
FieldContext: telemetrytypes.FieldContextResource,
|
||||
SearchText: "dash",
|
||||
StartUnixMilli: 1700000000000,
|
||||
EndUnixMilli: 1700003600000,
|
||||
},
|
||||
})
|
||||
vals, complete, err := metadata.GetAllValues(context.Background(), valuer.GenerateUUID(), sel)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, complete)
|
||||
assert.Equal(t, []string{"dashboard"}, vals.StringValues)
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
})
|
||||
|
||||
t.Run("AttributeUnspecifiedDynamicTypeRoutesAndDedupes", func(t *testing.T) {
|
||||
metadata, mock, startNs, startBucket := newAuditTestMetaStore(t)
|
||||
|
||||
mock.ExpectQuery(`SELECT DISTINCT dynamicType\(attributes\.`+"`mixed.field`"+`\), attributes\.`+"`mixed.field`"+`::String FROM signoz_audit\.distributed_logs WHERE attributes\.`+"`mixed.field`"+` IS NOT NULL AND attributes\.`+"`mixed.field`"+`::String <> '' AND timestamp >= \? AND ts_bucket_start >= \? LIMIT \?`).
|
||||
WithArgs(startNs, startBucket, 51).
|
||||
WillReturnRows(cmock.NewRows(
|
||||
[]cmock.ColumnType{{Name: "dt", Type: "String"}, {Name: "val", Type: "String"}},
|
||||
[][]any{
|
||||
{"Int64", "200"},
|
||||
{"Float64", "200"},
|
||||
{"String", "ok"},
|
||||
{"Bool", "true"},
|
||||
},
|
||||
))
|
||||
|
||||
sel := telemetrytypes.NewFieldValueSelectorFromPostableFieldValueParams(telemetrytypes.PostableFieldValueParams{
|
||||
Name: "mixed.field",
|
||||
PostableFieldKeysParams: telemetrytypes.PostableFieldKeysParams{
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
Source: telemetrytypes.SourceAudit,
|
||||
FieldContext: telemetrytypes.FieldContextAttribute,
|
||||
},
|
||||
})
|
||||
vals, complete, err := metadata.GetAllValues(context.Background(), valuer.GenerateUUID(), sel)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, complete)
|
||||
assert.Equal(t, []float64{200}, vals.NumberValues)
|
||||
assert.Equal(t, []string{"ok"}, vals.StringValues)
|
||||
assert.Equal(t, []bool{true}, vals.BoolValues)
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
})
|
||||
|
||||
t.Run("AttributeExplicitNumberAndBool", func(t *testing.T) {
|
||||
metadata, mock, startNs, startBucket := newAuditTestMetaStore(t)
|
||||
|
||||
mock.ExpectQuery(`SELECT DISTINCT assumeNotNull\(toFloat64OrNull\(attributes\.`+"`http.response.status_code`"+`::String\)\) FROM signoz_audit\.distributed_logs WHERE toFloat64OrNull\(attributes\.`+"`http.response.status_code`"+`::String\) IS NOT NULL AND timestamp >= \? AND ts_bucket_start >= \? LIMIT \?`).
|
||||
WithArgs(startNs, startBucket, 2).
|
||||
WillReturnRows(cmock.NewRows(
|
||||
[]cmock.ColumnType{{Name: "val", Type: "Float64"}},
|
||||
[][]any{{float64(200)}, {float64(403)}},
|
||||
))
|
||||
|
||||
numSel := telemetrytypes.NewFieldValueSelectorFromPostableFieldValueParams(telemetrytypes.PostableFieldValueParams{
|
||||
Name: "http.response.status_code",
|
||||
PostableFieldKeysParams: telemetrytypes.PostableFieldKeysParams{
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
Source: telemetrytypes.SourceAudit,
|
||||
FieldContext: telemetrytypes.FieldContextAttribute,
|
||||
FieldDataType: telemetrytypes.FieldDataTypeNumber,
|
||||
Limit: 1,
|
||||
},
|
||||
})
|
||||
numVals, complete, err := metadata.GetAllValues(context.Background(), valuer.GenerateUUID(), numSel)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, complete)
|
||||
assert.Equal(t, []float64{200}, numVals.NumberValues)
|
||||
|
||||
mock.ExpectQuery(`SELECT DISTINCT attributes\.`+"`dry_run`"+`::String FROM signoz_audit\.distributed_logs WHERE dynamicType\(attributes\.`+"`dry_run`"+`\) = 'Bool' AND timestamp >= \? AND ts_bucket_start >= \? LIMIT \?`).
|
||||
WithArgs(startNs, startBucket, 51).
|
||||
WillReturnRows(cmock.NewRows(
|
||||
[]cmock.ColumnType{{Name: "val", Type: "String"}},
|
||||
[][]any{{"true"}, {"false"}},
|
||||
))
|
||||
|
||||
boolSel := telemetrytypes.NewFieldValueSelectorFromPostableFieldValueParams(telemetrytypes.PostableFieldValueParams{
|
||||
Name: "dry_run",
|
||||
PostableFieldKeysParams: telemetrytypes.PostableFieldKeysParams{
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
Source: telemetrytypes.SourceAudit,
|
||||
FieldContext: telemetrytypes.FieldContextAttribute,
|
||||
FieldDataType: telemetrytypes.FieldDataTypeBool,
|
||||
},
|
||||
})
|
||||
boolVals, complete, err := metadata.GetAllValues(context.Background(), valuer.GenerateUUID(), boolSel)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, complete)
|
||||
assert.Equal(t, []bool{true, false}, boolVals.BoolValues)
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
})
|
||||
|
||||
t.Run("BareKeyQueriesResourceAndAttributesAndMerges", func(t *testing.T) {
|
||||
metadata, mock, startNs, startBucket := newAuditTestMetaStore(t)
|
||||
|
||||
mock.ExpectQuery(`SELECT DISTINCT JSONExtractString\(labels, \?\) AS val FROM signoz_audit\.distributed_logs_resource WHERE JSONExtractString\(labels, \?\) <> '' AND seen_at_ts_bucket_start >= \? LIMIT \?`).
|
||||
WithArgs("signoz.resource.kind", "signoz.resource.kind", startBucket, 51).
|
||||
WillReturnRows(cmock.NewRows(
|
||||
[]cmock.ColumnType{{Name: "val", Type: "String"}},
|
||||
[][]any{{"dashboard"}},
|
||||
))
|
||||
mock.ExpectQuery(`SELECT DISTINCT dynamicType\(attributes\.`+"`signoz.resource.kind`"+`\), attributes\.`+"`signoz.resource.kind`"+`::String FROM signoz_audit\.distributed_logs WHERE attributes\.`+"`signoz.resource.kind`"+` IS NOT NULL AND attributes\.`+"`signoz.resource.kind`"+`::String <> '' AND timestamp >= \? AND ts_bucket_start >= \? LIMIT \?`).
|
||||
WithArgs(startNs, startBucket, 51).
|
||||
WillReturnRows(cmock.NewRows(
|
||||
[]cmock.ColumnType{{Name: "dt", Type: "String"}, {Name: "val", Type: "String"}},
|
||||
[][]any{},
|
||||
))
|
||||
|
||||
sel := telemetrytypes.NewFieldValueSelectorFromPostableFieldValueParams(telemetrytypes.PostableFieldValueParams{
|
||||
Name: "signoz.resource.kind",
|
||||
PostableFieldKeysParams: telemetrytypes.PostableFieldKeysParams{
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
Source: telemetrytypes.SourceAudit,
|
||||
},
|
||||
})
|
||||
vals, complete, err := metadata.GetAllValues(context.Background(), valuer.GenerateUUID(), sel)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, complete)
|
||||
assert.Equal(t, []string{"dashboard"}, vals.StringValues)
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
})
|
||||
|
||||
t.Run("AttributeAndScopeSearchPreservesDoubleDollarKey", func(t *testing.T) {
|
||||
metadata, mock, startNs, startBucket := newAuditTestMetaStore(t)
|
||||
|
||||
mock.ExpectQuery(`SELECT DISTINCT attributes\.`+"`foo\\$\\$bar`"+`::String FROM signoz_audit\.distributed_logs WHERE attributes\.`+"`foo\\$\\$bar`"+` IS NOT NULL AND attributes\.`+"`foo\\$\\$bar`"+`::String <> '' AND LOWER\(attributes\.`+"`foo\\$\\$bar`"+`::String\) LIKE LOWER\(\?\) AND timestamp >= \? AND ts_bucket_start >= \? LIMIT \?`).
|
||||
WithArgs("%val%", startNs, startBucket, 51).
|
||||
WillReturnRows(cmock.NewRows(
|
||||
[]cmock.ColumnType{{Name: "val", Type: "String"}},
|
||||
[][]any{{"val1"}},
|
||||
))
|
||||
|
||||
attrSel := telemetrytypes.NewFieldValueSelectorFromPostableFieldValueParams(telemetrytypes.PostableFieldValueParams{
|
||||
Name: "foo$$bar",
|
||||
PostableFieldKeysParams: telemetrytypes.PostableFieldKeysParams{
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
Source: telemetrytypes.SourceAudit,
|
||||
FieldContext: telemetrytypes.FieldContextAttribute,
|
||||
FieldDataType: telemetrytypes.FieldDataTypeString,
|
||||
SearchText: "val",
|
||||
},
|
||||
})
|
||||
attrVals, complete, err := metadata.GetAllValues(context.Background(), valuer.GenerateUUID(), attrSel)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, complete)
|
||||
assert.Equal(t, []string{"val1"}, attrVals.StringValues)
|
||||
|
||||
mock.ExpectQuery(`SELECT DISTINCT scope\.attributes\.`+"`foo\\$\\$bar`"+`::String FROM signoz_audit\.distributed_logs WHERE scope\.attributes\.`+"`foo\\$\\$bar`"+` IS NOT NULL AND scope\.attributes\.`+"`foo\\$\\$bar`"+`::String <> '' AND LOWER\(scope\.attributes\.`+"`foo\\$\\$bar`"+`::String\) LIKE LOWER\(\?\) AND timestamp >= \? AND ts_bucket_start >= \? LIMIT \?`).
|
||||
WithArgs("%val%", startNs, startBucket, 51).
|
||||
WillReturnRows(cmock.NewRows(
|
||||
[]cmock.ColumnType{{Name: "val", Type: "String"}},
|
||||
[][]any{{"val2"}},
|
||||
))
|
||||
|
||||
scopeSel := telemetrytypes.NewFieldValueSelectorFromPostableFieldValueParams(telemetrytypes.PostableFieldValueParams{
|
||||
Name: "foo$$bar",
|
||||
PostableFieldKeysParams: telemetrytypes.PostableFieldKeysParams{
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
Source: telemetrytypes.SourceAudit,
|
||||
FieldContext: telemetrytypes.FieldContextScope,
|
||||
SearchText: "val",
|
||||
},
|
||||
})
|
||||
scopeVals, complete, err := metadata.GetAllValues(context.Background(), valuer.GenerateUUID(), scopeSel)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, complete)
|
||||
assert.Equal(t, []string{"val2"}, scopeVals.StringValues)
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
})
|
||||
}
|
||||
|
||||
func TestGetRelatedValues_AuditShortCircuitsWithoutQuery(t *testing.T) {
|
||||
metadata, mock, _, _ := newAuditTestMetaStore(t)
|
||||
|
||||
sel := telemetrytypes.NewFieldValueSelectorFromPostableFieldValueParams(telemetrytypes.PostableFieldValueParams{
|
||||
Name: "signoz.principal.email",
|
||||
ExistingQuery: "signoz.audit.outcome = 'failure'",
|
||||
PostableFieldKeysParams: telemetrytypes.PostableFieldKeysParams{
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
Source: telemetrytypes.SourceAudit,
|
||||
},
|
||||
})
|
||||
|
||||
values, complete, err := metadata.GetRelatedValues(context.Background(), valuer.GenerateUUID(), sel)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, complete)
|
||||
assert.Empty(t, values)
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
@@ -35,6 +35,7 @@ var (
|
||||
ErrFailedToGetTracesKeys = errors.Newf(errors.TypeInternal, errors.CodeInternal, "failed to get traces keys")
|
||||
ErrFailedToGetLogsKeys = errors.Newf(errors.TypeInternal, errors.CodeInternal, "failed to get logs keys")
|
||||
ErrFailedToGetAuditKeys = errors.Newf(errors.TypeInternal, errors.CodeInternal, "failed to get audit keys")
|
||||
ErrFailedToGetAuditValues = errors.Newf(errors.TypeInternal, errors.CodeInternal, "failed to get audit values")
|
||||
ErrFailedToGetTblStatement = errors.Newf(errors.TypeInternal, errors.CodeInternal, "failed to get tbl statement")
|
||||
ErrFailedToGetMetricsKeys = errors.Newf(errors.TypeInternal, errors.CodeInternal, "failed to get metrics keys")
|
||||
ErrFailedToGetMeterKeys = errors.Newf(errors.TypeInternal, errors.CodeInternal, "failed to get meter keys")
|
||||
@@ -60,9 +61,7 @@ type telemetryMetaStore struct {
|
||||
logsV2TblName string
|
||||
auditDBName string
|
||||
auditLogsTblName string
|
||||
auditFieldsTblName string
|
||||
auditAttributeKeysTblName string
|
||||
auditResourceKeysTblName string
|
||||
auditLogsResourceTblName string
|
||||
relatedMetadataDBName string
|
||||
relatedMetadataTblName string
|
||||
columnEvolutionMetadataTblName string
|
||||
@@ -70,6 +69,7 @@ type telemetryMetaStore struct {
|
||||
storage qbtypes.Storage
|
||||
fl flagger.Flagger
|
||||
jsonColumnMetadata map[telemetrytypes.Signal]map[telemetrytypes.FieldContext]telemetrytypes.JSONColumnMetadata
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewTelemetryMetaStore(
|
||||
@@ -97,9 +97,7 @@ func NewTelemetryMetaStore(
|
||||
logResourceKeysTblName: logstelemetryschema.LogResourceKeysTblName,
|
||||
auditDBName: audittelemetryschema.DBName,
|
||||
auditLogsTblName: audittelemetryschema.AuditLogsTableName,
|
||||
auditFieldsTblName: audittelemetryschema.TagAttributesTableName,
|
||||
auditAttributeKeysTblName: audittelemetryschema.LogAttributeKeysTblName,
|
||||
auditResourceKeysTblName: audittelemetryschema.LogResourceKeysTblName,
|
||||
auditLogsResourceTblName: audittelemetryschema.LogsResourceTableName,
|
||||
relatedMetadataDBName: DBName,
|
||||
relatedMetadataTblName: AttributesMetadataTableName,
|
||||
columnEvolutionMetadataTblName: ColumnEvolutionMetadataTableName,
|
||||
@@ -113,6 +111,7 @@ func NewTelemetryMetaStore(
|
||||
},
|
||||
fl: fl,
|
||||
storage: NewStorage(),
|
||||
now: time.Now,
|
||||
}
|
||||
|
||||
return t
|
||||
@@ -691,222 +690,6 @@ func (t *telemetryMetaStore) getLogsKeys(ctx context.Context, orgID valuer.UUID,
|
||||
return keys, complete, nil
|
||||
}
|
||||
|
||||
//nolint:unused // not called until audit keys are recorded in signoz_metadata
|
||||
func (t *telemetryMetaStore) auditTblStatementToFieldKeys(ctx context.Context) ([]*telemetrytypes.TelemetryFieldKey, error) {
|
||||
ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{
|
||||
instrumentationtypes.TelemetrySignal: telemetrytypes.SignalLogs.StringValue(),
|
||||
instrumentationtypes.CodeNamespace: "metadata",
|
||||
instrumentationtypes.CodeFunctionName: "auditTblStatementToFieldKeys",
|
||||
})
|
||||
|
||||
query := fmt.Sprintf("SHOW CREATE TABLE %s.%s", t.auditDBName, t.auditLogsTblName)
|
||||
statements := []telemetrytypes.ShowCreateTableStatement{}
|
||||
err := t.telemetrystore.ClickhouseDB().Select(ctx, &statements, query)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetTblStatement.Error())
|
||||
}
|
||||
|
||||
materialisedKeys, err := ExtractFieldKeysFromTblStatement(statements[0].Statement)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditKeys.Error())
|
||||
}
|
||||
|
||||
for idx := range materialisedKeys {
|
||||
materialisedKeys[idx].Signal = telemetrytypes.SignalLogs
|
||||
}
|
||||
|
||||
return materialisedKeys, nil
|
||||
}
|
||||
|
||||
//nolint:unused // not called until audit keys are recorded in signoz_metadata
|
||||
func (t *telemetryMetaStore) getAuditKeys(ctx context.Context, fieldKeySelectors []*telemetrytypes.FieldKeySelector) ([]*telemetrytypes.TelemetryFieldKey, bool, error) {
|
||||
ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{
|
||||
instrumentationtypes.TelemetrySignal: telemetrytypes.SignalLogs.StringValue(),
|
||||
instrumentationtypes.CodeNamespace: "metadata",
|
||||
instrumentationtypes.CodeFunctionName: "getAuditKeys",
|
||||
})
|
||||
|
||||
if len(fieldKeySelectors) == 0 {
|
||||
return nil, true, nil
|
||||
}
|
||||
|
||||
matKeys, err := t.auditTblStatementToFieldKeys(ctx)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
mapOfKeys := make(map[string]*telemetrytypes.TelemetryFieldKey)
|
||||
for _, key := range matKeys {
|
||||
mapOfKeys[key.Name+";"+key.FieldContext.StringValue()+";"+key.FieldDataType.StringValue()] = key
|
||||
}
|
||||
|
||||
var queries []string
|
||||
var allArgs []any
|
||||
|
||||
queryAttributeTable := false
|
||||
queryResourceTable := false
|
||||
|
||||
for _, selector := range fieldKeySelectors {
|
||||
if selector.FieldContext == telemetrytypes.FieldContextUnspecified {
|
||||
queryAttributeTable = true
|
||||
queryResourceTable = true
|
||||
break
|
||||
} else if selector.FieldContext == telemetrytypes.FieldContextAttribute {
|
||||
queryAttributeTable = true
|
||||
} else if selector.FieldContext == telemetrytypes.FieldContextResource {
|
||||
queryResourceTable = true
|
||||
}
|
||||
}
|
||||
|
||||
tablesToQuery := []struct {
|
||||
fieldContext telemetrytypes.FieldContext
|
||||
shouldQuery bool
|
||||
tblName string
|
||||
}{
|
||||
{telemetrytypes.FieldContextAttribute, queryAttributeTable, t.auditDBName + "." + t.auditAttributeKeysTblName},
|
||||
{telemetrytypes.FieldContextResource, queryResourceTable, t.auditDBName + "." + t.auditResourceKeysTblName},
|
||||
}
|
||||
|
||||
for _, table := range tablesToQuery {
|
||||
if !table.shouldQuery {
|
||||
continue
|
||||
}
|
||||
|
||||
fieldContext := table.fieldContext
|
||||
tblName := table.tblName
|
||||
|
||||
sb := sqlbuilder.Select(
|
||||
"name AS tag_key",
|
||||
fmt.Sprintf("'%s' AS tag_type", fieldContext.TagType()),
|
||||
"lower(datatype) AS tag_data_type",
|
||||
fmt.Sprintf("%d AS priority", getPriorityForContext(fieldContext)),
|
||||
).From(tblName)
|
||||
|
||||
var limit int
|
||||
conds := []string{}
|
||||
|
||||
for _, fieldKeySelector := range fieldKeySelectors {
|
||||
if fieldKeySelector.FieldContext != telemetrytypes.FieldContextUnspecified && fieldKeySelector.FieldContext != fieldContext {
|
||||
continue
|
||||
}
|
||||
|
||||
fieldKeyConds := []string{}
|
||||
if fieldKeySelector.SelectorMatchType == telemetrytypes.FieldSelectorMatchTypeExact {
|
||||
fieldKeyConds = append(fieldKeyConds, sb.E("name", fieldKeySelector.Name))
|
||||
} else {
|
||||
fieldKeyConds = append(fieldKeyConds, sb.ILike("name", "%"+clickhousesql.LikePattern(fieldKeySelector.Name)+"%"))
|
||||
}
|
||||
|
||||
if fieldKeySelector.FieldDataType != telemetrytypes.FieldDataTypeUnspecified {
|
||||
fieldKeyConds = append(fieldKeyConds, sb.E("datatype", fieldKeySelector.FieldDataType.TagDataType()))
|
||||
}
|
||||
|
||||
if len(fieldKeyConds) > 0 {
|
||||
conds = append(conds, sb.And(fieldKeyConds...))
|
||||
}
|
||||
limit += fieldKeySelector.Limit
|
||||
}
|
||||
|
||||
if len(conds) > 0 {
|
||||
sb.Where(sb.Or(conds...))
|
||||
}
|
||||
|
||||
sb.GroupBy("name", "datatype")
|
||||
if limit == 0 {
|
||||
limit = 1000
|
||||
}
|
||||
|
||||
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
|
||||
queries = append(queries, query)
|
||||
allArgs = append(allArgs, args...)
|
||||
}
|
||||
|
||||
var limit int
|
||||
for _, fieldKeySelector := range fieldKeySelectors {
|
||||
limit += fieldKeySelector.Limit
|
||||
}
|
||||
if limit == 0 {
|
||||
limit = 1000
|
||||
}
|
||||
|
||||
keys := []*telemetrytypes.TelemetryFieldKey{}
|
||||
rowCount := 0
|
||||
|
||||
// the log and scope contexts have no keys table; they are served by the
|
||||
// static fields appended below
|
||||
if len(queries) > 0 {
|
||||
mainQuery := fmt.Sprintf(`
|
||||
SELECT tag_key, tag_type, tag_data_type, max(priority) as priority
|
||||
FROM (
|
||||
%s
|
||||
) AS combined_results
|
||||
GROUP BY tag_key, tag_type, tag_data_type
|
||||
ORDER BY priority
|
||||
LIMIT %d
|
||||
`, strings.Join(queries, " UNION ALL "), limit+1)
|
||||
|
||||
rows, err := t.telemetrystore.ClickhouseDB().Query(ctx, mainQuery, allArgs...)
|
||||
if err != nil {
|
||||
return nil, false, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditKeys.Error())
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
for rows.Next() {
|
||||
rowCount++
|
||||
if rowCount > limit {
|
||||
break
|
||||
}
|
||||
|
||||
var name string
|
||||
var fieldContext telemetrytypes.FieldContext
|
||||
var fieldDataType telemetrytypes.FieldDataType
|
||||
var priority uint8
|
||||
err = rows.Scan(&name, &fieldContext, &fieldDataType, &priority)
|
||||
if err != nil {
|
||||
return nil, false, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditKeys.Error())
|
||||
}
|
||||
key, ok := mapOfKeys[name+";"+fieldContext.StringValue()+";"+fieldDataType.StringValue()]
|
||||
|
||||
if !ok {
|
||||
key = &telemetrytypes.TelemetryFieldKey{
|
||||
Name: name,
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
FieldContext: fieldContext,
|
||||
FieldDataType: fieldDataType,
|
||||
}
|
||||
}
|
||||
|
||||
keys = append(keys, key)
|
||||
mapOfKeys[name+";"+fieldContext.StringValue()+";"+fieldDataType.StringValue()] = key
|
||||
}
|
||||
|
||||
if rows.Err() != nil {
|
||||
return nil, false, errors.Wrap(rows.Err(), errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditKeys.Error())
|
||||
}
|
||||
}
|
||||
|
||||
complete := rowCount <= limit
|
||||
|
||||
return appendStaticAuditKeys(keys, mapOfKeys, fieldKeySelectors), complete, nil
|
||||
}
|
||||
|
||||
// appendStaticAuditKeys adds the matching intrinsic audit fields (same as logs intrinsics: body, severity_text, etc.)
|
||||
// and the known resource fields.
|
||||
func appendStaticAuditKeys(keys []*telemetrytypes.TelemetryFieldKey, mapOfKeys map[string]*telemetrytypes.TelemetryFieldKey, fieldKeySelectors []*telemetrytypes.FieldKeySelector) []*telemetrytypes.TelemetryFieldKey {
|
||||
for _, fields := range []map[string]telemetrytypes.TelemetryFieldKey{audittelemetryschema.IntrinsicFields, audittelemetryschema.ResourceFields} {
|
||||
for _, field := range fields {
|
||||
if !staticFieldMatchesAny(field, fieldKeySelectors) {
|
||||
continue
|
||||
}
|
||||
if _, added := mapOfKeys[field.Name+";"+field.FieldContext.StringValue()+";"+field.FieldDataType.StringValue()]; added {
|
||||
continue
|
||||
}
|
||||
keys = append(keys, &field)
|
||||
}
|
||||
}
|
||||
|
||||
return keys
|
||||
}
|
||||
|
||||
func getPriorityForContext(ctx telemetrytypes.FieldContext) int {
|
||||
switch ctx {
|
||||
case telemetrytypes.FieldContextLog:
|
||||
@@ -1218,7 +1001,7 @@ func (t *telemetryMetaStore) GetKeys(ctx context.Context, orgID valuer.UUID, fie
|
||||
keys, complete, err = t.getTracesKeys(ctx, selectors)
|
||||
case telemetrytypes.SignalLogs:
|
||||
if fieldKeySelector.Source == telemetrytypes.SourceAudit {
|
||||
keys = appendStaticAuditKeys(nil, map[string]*telemetrytypes.TelemetryFieldKey{}, selectors)
|
||||
keys, complete, err = t.getAuditKeys(ctx, selectors)
|
||||
} else {
|
||||
keys, complete, err = t.getLogsKeys(ctx, orgID, selectors)
|
||||
}
|
||||
@@ -1302,7 +1085,10 @@ func (t *telemetryMetaStore) GetKeysMulti(ctx context.Context, orgID valuer.UUID
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
auditKeys := appendStaticAuditKeys(nil, map[string]*telemetrytypes.TelemetryFieldKey{}, auditSelectors)
|
||||
auditKeys, auditComplete, err := t.getAuditKeys(ctx, auditSelectors)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
tracesKeys, tracesComplete, err := t.getTracesKeys(ctx, tracesSelectors)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
@@ -1317,7 +1103,7 @@ func (t *telemetryMetaStore) GetKeysMulti(ctx context.Context, orgID valuer.UUID
|
||||
return nil, false, err
|
||||
}
|
||||
// Complete only if all queries are complete
|
||||
complete := logsComplete && tracesComplete && metricsComplete
|
||||
complete := logsComplete && auditComplete && tracesComplete && metricsComplete
|
||||
|
||||
mapOfKeys := make(map[string][]*telemetrytypes.TelemetryFieldKey)
|
||||
for _, key := range logsKeys {
|
||||
@@ -1362,6 +1148,11 @@ func (t *telemetryMetaStore) getRelatedValues(ctx context.Context, orgID valuer.
|
||||
return nil, true, nil
|
||||
}
|
||||
|
||||
// audit logs do not write to signoz_metadata.distributed_attributes_metadata
|
||||
if fieldValueSelector.Signal == telemetrytypes.SignalLogs && fieldValueSelector.Source == telemetrytypes.SourceAudit {
|
||||
return nil, true, nil
|
||||
}
|
||||
|
||||
key := &telemetrytypes.TelemetryFieldKey{
|
||||
Name: fieldValueSelector.Name,
|
||||
Signal: fieldValueSelector.Signal,
|
||||
@@ -1718,98 +1509,6 @@ func (t *telemetryMetaStore) getTagTableValues(ctx context.Context, table string
|
||||
return values, complete, nil
|
||||
}
|
||||
|
||||
//nolint:unused // not called until audit values are recorded in signoz_metadata
|
||||
func (t *telemetryMetaStore) getAuditFieldValues(ctx context.Context, fieldValueSelector *telemetrytypes.FieldValueSelector) (*telemetrytypes.TelemetryFieldValues, bool, error) {
|
||||
ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{
|
||||
instrumentationtypes.TelemetrySignal: telemetrytypes.SignalLogs.StringValue(),
|
||||
instrumentationtypes.CodeNamespace: "metadata",
|
||||
instrumentationtypes.CodeFunctionName: "getAuditFieldValues",
|
||||
})
|
||||
|
||||
limit := fieldValueSelector.Limit
|
||||
if limit == 0 {
|
||||
limit = 50
|
||||
}
|
||||
|
||||
sb := sqlbuilder.Select("DISTINCT string_value, number_value").From(t.auditDBName + "." + t.auditFieldsTblName)
|
||||
|
||||
if fieldValueSelector.Name != "" {
|
||||
sb.Where(sb.E("tag_key", fieldValueSelector.Name))
|
||||
}
|
||||
|
||||
if fieldValueSelector.FieldContext != telemetrytypes.FieldContextUnspecified {
|
||||
sb.Where(sb.E("tag_type", fieldValueSelector.FieldContext.TagType()))
|
||||
}
|
||||
|
||||
if fieldValueSelector.FieldDataType != telemetrytypes.FieldDataTypeUnspecified {
|
||||
sb.Where(sb.E("tag_data_type", fieldValueSelector.FieldDataType.TagDataType()))
|
||||
}
|
||||
|
||||
if fieldValueSelector.Value != "" {
|
||||
switch fieldValueSelector.FieldDataType {
|
||||
case telemetrytypes.FieldDataTypeString:
|
||||
sb.Where(sb.ILike("string_value", "%"+clickhousesql.LikePattern(fieldValueSelector.Value)+"%"))
|
||||
case telemetrytypes.FieldDataTypeNumber, telemetrytypes.FieldDataTypeInt64, telemetrytypes.FieldDataTypeFloat64:
|
||||
sb.Where(sb.IsNotNull("number_value"))
|
||||
sb.Where(sb.ILike("toString(number_value)", "%"+clickhousesql.LikePattern(fieldValueSelector.Value)+"%"))
|
||||
case telemetrytypes.FieldDataTypeUnspecified:
|
||||
sb.Where(sb.Or(
|
||||
sb.ILike("string_value", "%"+clickhousesql.LikePattern(fieldValueSelector.Value)+"%"),
|
||||
sb.ILike("toString(number_value)", "%"+clickhousesql.LikePattern(fieldValueSelector.Value)+"%"),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
// fetch one extra row to detect whether the result set is complete
|
||||
sb.Limit(limit + 1)
|
||||
|
||||
query, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
|
||||
|
||||
rows, err := t.telemetrystore.ClickhouseDB().Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, false, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditKeys.Error())
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
values := &telemetrytypes.TelemetryFieldValues{}
|
||||
seen := make(map[string]bool)
|
||||
rowCount := 0
|
||||
totalCount := 0
|
||||
|
||||
for rows.Next() {
|
||||
rowCount++
|
||||
|
||||
var stringValue string
|
||||
var numberValue float64
|
||||
err = rows.Scan(&stringValue, &numberValue)
|
||||
if err != nil {
|
||||
return nil, false, errors.Wrap(err, errors.TypeInternal, errors.CodeInternal, ErrFailedToGetAuditKeys.Error())
|
||||
}
|
||||
if stringValue != "" && !seen[stringValue] {
|
||||
if totalCount >= limit {
|
||||
break
|
||||
}
|
||||
values.StringValues = append(values.StringValues, stringValue)
|
||||
seen[stringValue] = true
|
||||
totalCount++
|
||||
}
|
||||
if numberValue != 0 {
|
||||
if totalCount >= limit {
|
||||
break
|
||||
}
|
||||
if !seen[fmt.Sprintf("%f", numberValue)] {
|
||||
values.NumberValues = append(values.NumberValues, numberValue)
|
||||
seen[fmt.Sprintf("%f", numberValue)] = true
|
||||
totalCount++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
complete := rowCount <= limit
|
||||
|
||||
return values, complete, nil
|
||||
}
|
||||
|
||||
// getMetricFieldValues returns field values and whether the result is complete.
|
||||
func (t *telemetryMetaStore) getMetricFieldValues(ctx context.Context, orgID valuer.UUID, fieldValueSelector *telemetrytypes.FieldValueSelector) (*telemetrytypes.TelemetryFieldValues, bool, error) {
|
||||
ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{
|
||||
@@ -2260,7 +1959,7 @@ func (t *telemetryMetaStore) getAllValues(ctx context.Context, orgID valuer.UUID
|
||||
values, complete, err = t.getSpanFieldValues(ctx, orgID, fieldValueSelector)
|
||||
case telemetrytypes.SignalLogs:
|
||||
if fieldValueSelector.Source == telemetrytypes.SourceAudit {
|
||||
values = &telemetrytypes.TelemetryFieldValues{}
|
||||
values, complete, err = t.getAuditFieldValues(ctx, fieldValueSelector)
|
||||
} else {
|
||||
values, complete, err = t.getLogFieldValues(ctx, orgID, fieldValueSelector)
|
||||
}
|
||||
|
||||
@@ -2,11 +2,8 @@ package audittelemetryschema
|
||||
|
||||
import (
|
||||
schema "github.com/SigNoz/signoz-otel-collector/cmd/signozschemamigrator/schema_migrator"
|
||||
"github.com/SigNoz/signoz-semantic-conventions/gen/go/sigsemconv"
|
||||
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
|
||||
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -83,17 +80,22 @@ var (
|
||||
FieldContext: telemetrytypes.FieldContextLog,
|
||||
FieldDataType: telemetrytypes.FieldDataTypeString,
|
||||
},
|
||||
"scope.name": {
|
||||
Name: "scope.name",
|
||||
Description: "Instrumentation scope name",
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
FieldContext: telemetrytypes.FieldContextScope,
|
||||
FieldDataType: telemetrytypes.FieldDataTypeString,
|
||||
},
|
||||
"scope.version": {
|
||||
Name: "scope.version",
|
||||
Description: "Instrumentation scope version",
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
FieldContext: telemetrytypes.FieldContextScope,
|
||||
FieldDataType: telemetrytypes.FieldDataTypeString,
|
||||
},
|
||||
}
|
||||
|
||||
// ResourceFields are the resource keys the audit writer emits, so a bare name resolves to resource.
|
||||
ResourceFields = newResourceFields(
|
||||
semconv.ServiceNameKey,
|
||||
semconv.ServiceVersionKey,
|
||||
sigsemconv.SigNozResourceKindKey,
|
||||
sigsemconv.SigNozResourceIDKey,
|
||||
sigsemconv.SigNozResourceObjectKey,
|
||||
)
|
||||
|
||||
DefaultSortingOrder = []qbtypes.OrderBy{
|
||||
{
|
||||
Key: qbtypes.OrderByKey{
|
||||
@@ -133,25 +135,8 @@ var auditLogColumns = map[string]*schema.Column{
|
||||
}
|
||||
|
||||
const (
|
||||
DBName = "signoz_audit"
|
||||
AuditLogsTableName = "distributed_logs"
|
||||
AuditLogsLocalTableName = "logs"
|
||||
TagAttributesTableName = "distributed_tag_attributes"
|
||||
TagAttributesLocalTableName = "tag_attributes"
|
||||
LogAttributeKeysTblName = "distributed_logs_attribute_keys"
|
||||
LogResourceKeysTblName = "distributed_logs_resource_keys"
|
||||
LogsResourceTableName = "distributed_logs_resource"
|
||||
DBName = "signoz_audit"
|
||||
AuditLogsTableName = "distributed_logs"
|
||||
AuditLogsLocalTableName = "logs"
|
||||
LogsResourceTableName = "distributed_logs_resource"
|
||||
)
|
||||
|
||||
func newResourceFields(keys ...attribute.Key) map[string]telemetrytypes.TelemetryFieldKey {
|
||||
fields := make(map[string]telemetrytypes.TelemetryFieldKey, len(keys))
|
||||
for _, key := range keys {
|
||||
fields[string(key)] = telemetrytypes.TelemetryFieldKey{
|
||||
Name: string(key),
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
FieldContext: telemetrytypes.FieldContextResource,
|
||||
FieldDataType: telemetrytypes.FieldDataTypeString,
|
||||
}
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
@@ -213,10 +213,10 @@ type MetricContext struct {
|
||||
}
|
||||
|
||||
type FieldKeySelector struct {
|
||||
StartUnixMilli int64 `json:"startUnixMilli" 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. Zero means no lower bound."`
|
||||
EndUnixMilli int64 `json:"endUnixMilli" 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. Zero means no upper bound."`
|
||||
StartUnixMilli int64 `json:"startUnixMilli" 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. Zero means no lower bound."`
|
||||
EndUnixMilli int64 `json:"endUnixMilli" 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. Zero means no upper bound."`
|
||||
Signal Signal `json:"signal" description:"The signal to look up keys in: traces, logs or metrics. Empty means every signal."`
|
||||
Source Source `json:"source" description:"The data source within the signal. Use meter for Cost Meter metrics; empty means the default source."`
|
||||
Source Source `json:"source" description:"The data source within the signal. Use audit for audit logs or meter for Cost Meter metrics; empty means the default source."`
|
||||
FieldContext FieldContext `json:"fieldContext" description:"Restricts keys to one context such as resource or attribute. Applied to trace and log keys; metric attribute keys ignore it. Empty means any context."`
|
||||
FieldDataType FieldDataType `json:"fieldDataType" description:"Restricts keys to one data type such as string or float64. Applied to trace and log keys; metric attribute keys ignore it. Empty means any type."`
|
||||
Name string `json:"name" description:"Key name to match; empty matches every key. Matched according to selectorMatchType."`
|
||||
@@ -272,10 +272,10 @@ type GettableFieldKeys struct {
|
||||
|
||||
type PostableFieldKeysParams struct {
|
||||
Signal Signal `query:"signal" description:"The signal to look up keys in: traces, logs or metrics. Empty searches every signal."`
|
||||
Source Source `query:"source" description:"The data source within the signal. Use meter for Cost Meter metrics; empty means the default source."`
|
||||
Source Source `query:"source" description:"The data source within the signal. Use audit for audit logs or meter for Cost Meter metrics; empty means the default source."`
|
||||
Limit int `query:"limit" 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 separately, so the response can exceed it."`
|
||||
StartUnixMilli int64 `query:"startUnixMilli" 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."`
|
||||
EndUnixMilli int64 `query:"endUnixMilli" 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."`
|
||||
StartUnixMilli int64 `query:"startUnixMilli" 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."`
|
||||
EndUnixMilli int64 `query:"endUnixMilli" 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."`
|
||||
FieldContext FieldContext `query:"fieldContext" description:"Restricts keys to one context: resource, attribute, scope, span, trace, log, body or metric. Applied to trace and log keys; metric attribute keys ignore it. Empty means any context."`
|
||||
FieldDataType FieldDataType `query:"fieldDataType" description:"Restricts keys to one data type: string, bool, int64, float64 or number. Applied to trace and log keys; metric attribute keys ignore it. Empty means any type."`
|
||||
MetricName string `query:"metricName" description:"Restricts keys to those seen on this metric. Metrics signal only."`
|
||||
|
||||
315
tests/integration/tests/querieraudit/08_fields.py
Normal file
315
tests/integration/tests/querieraudit/08_fields.py
Normal file
@@ -0,0 +1,315 @@
|
||||
from collections.abc import Callable
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from http import HTTPStatus
|
||||
|
||||
from fixtures import types
|
||||
from fixtures.audit import (
|
||||
ALICE_CREATED_DASHBOARD,
|
||||
AuditLog,
|
||||
sample_audit_logs,
|
||||
)
|
||||
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
|
||||
from fixtures.metadata import get_field_keys, get_field_values
|
||||
|
||||
|
||||
def test_audit_fields_keys_discovery_and_filters(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_audit_logs: Callable[[list[AuditLog]], None],
|
||||
) -> None:
|
||||
now = datetime.now(tz=UTC)
|
||||
insert_audit_logs(sample_audit_logs(now))
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
response = get_field_keys(signoz, token, {"signal": "logs", "source": "audit"})
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
data = response.json()["data"]
|
||||
assert data["complete"] is True
|
||||
keys = data["keys"]
|
||||
|
||||
assert any(k["fieldContext"] == "attribute" and k["fieldDataType"] == "string" for k in keys["signoz.principal.email"])
|
||||
assert any(k["fieldContext"] == "attribute" and k["fieldDataType"] == "number" for k in keys["signoz.audit.fields_changed"])
|
||||
assert any(k["fieldContext"] == "resource" and k["fieldDataType"] == "string" for k in keys["signoz.resource.kind"])
|
||||
assert any(k["fieldContext"] == "resource" and k["fieldDataType"] == "string" for k in keys["service.name"])
|
||||
assert any(k["fieldContext"] == "log" for k in keys["event_name"])
|
||||
assert any(k["fieldContext"] == "log" for k in keys["body"])
|
||||
assert any(k["fieldContext"] == "scope" for k in keys["scope.name"])
|
||||
assert any(k["fieldContext"] == "scope" for k in keys["scope.version"])
|
||||
|
||||
response = get_field_keys(
|
||||
signoz,
|
||||
token,
|
||||
{
|
||||
"signal": "logs",
|
||||
"source": "audit",
|
||||
"fieldContext": "resource",
|
||||
"searchText": "resource.kind",
|
||||
},
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
filtered = response.json()["data"]
|
||||
assert filtered["complete"] is True
|
||||
assert list(filtered["keys"].keys()) == ["signoz.resource.kind"]
|
||||
|
||||
response = get_field_keys(
|
||||
signoz,
|
||||
token,
|
||||
{"signal": "logs", "source": "audit", "fieldDataType": "number"},
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
numeric = response.json()["data"]
|
||||
assert "signoz.audit.fields_changed" in numeric["keys"]
|
||||
assert "severity_number" in numeric["keys"]
|
||||
assert "signoz.principal.email" not in numeric["keys"]
|
||||
|
||||
response = get_field_keys(
|
||||
signoz,
|
||||
token,
|
||||
{
|
||||
"signal": "logs",
|
||||
"source": "audit",
|
||||
"fieldContext": "attribute",
|
||||
"limit": 2,
|
||||
},
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
limited = response.json()["data"]
|
||||
assert limited["complete"] is False
|
||||
assert len(limited["keys"]) == 2
|
||||
|
||||
|
||||
def test_audit_fields_keys_empty_table_returns_intrinsics(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_audit_logs: Callable[[list[AuditLog]], None], # pylint: disable=unused-argument
|
||||
) -> None:
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
response = get_field_keys(signoz, token, {"signal": "logs", "source": "audit"})
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
data = response.json()["data"]
|
||||
assert data["complete"] is True
|
||||
assert "event_name" in data["keys"]
|
||||
assert "body" in data["keys"]
|
||||
assert "scope.name" in data["keys"]
|
||||
assert "signoz.principal.email" not in data["keys"]
|
||||
|
||||
|
||||
def test_audit_fields_values_across_contexts_and_types(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_audit_logs: Callable[[list[AuditLog]], None],
|
||||
) -> None:
|
||||
now = datetime.now(tz=UTC)
|
||||
insert_audit_logs(sample_audit_logs(now))
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
response = get_field_values(
|
||||
signoz,
|
||||
token,
|
||||
{"signal": "logs", "source": "audit", "name": "signoz.resource.kind"},
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
bare_res = response.json()["data"]
|
||||
assert bare_res["complete"] is True
|
||||
assert set(bare_res["values"]["stringValues"]) == {"dashboard", "alert-rule", "user"}
|
||||
|
||||
response = get_field_values(
|
||||
signoz,
|
||||
token,
|
||||
{"signal": "logs", "source": "audit", "name": "resource.signoz.resource.kind"},
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
prefixed_res = response.json()["data"]
|
||||
assert set(prefixed_res["values"]["stringValues"]) == {"dashboard", "alert-rule", "user"}
|
||||
|
||||
response = get_field_values(
|
||||
signoz,
|
||||
token,
|
||||
{
|
||||
"signal": "logs",
|
||||
"source": "audit",
|
||||
"name": "signoz.principal.email",
|
||||
"searchText": "alice",
|
||||
"existingQuery": "signoz.audit.outcome = 'failure'",
|
||||
},
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
emails = response.json()["data"]
|
||||
assert emails["complete"] is True
|
||||
assert emails["values"]["stringValues"] == ["alice@acme.com"]
|
||||
assert not emails["values"].get("relatedValues")
|
||||
|
||||
response = get_field_values(
|
||||
signoz,
|
||||
token,
|
||||
{"signal": "logs", "source": "audit", "name": "signoz.audit.fields_changed"},
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
changed = response.json()["data"]
|
||||
assert changed["complete"] is True
|
||||
assert set(changed["values"]["numberValues"]) == {3, 8, 12}
|
||||
|
||||
response = get_field_values(
|
||||
signoz,
|
||||
token,
|
||||
{"signal": "logs", "source": "audit", "name": "event_name"},
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
events = response.json()["data"]
|
||||
assert set(events["values"]["stringValues"]) == {
|
||||
"signoz.audit.create",
|
||||
"signoz.audit.update",
|
||||
"signoz.audit.delete",
|
||||
}
|
||||
|
||||
response = get_field_values(
|
||||
signoz,
|
||||
token,
|
||||
{"signal": "logs", "source": "audit", "name": "severity_number"},
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
sev_nums = response.json()["data"]
|
||||
assert set(sev_nums["values"]["numberValues"]) == {9, 17}
|
||||
|
||||
response = get_field_values(
|
||||
signoz,
|
||||
token,
|
||||
{
|
||||
"signal": "logs",
|
||||
"source": "audit",
|
||||
"name": "body",
|
||||
"searchText": "created dashboard",
|
||||
},
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
bodies = response.json()["data"]
|
||||
assert bodies["values"]["stringValues"] == [ALICE_CREATED_DASHBOARD]
|
||||
|
||||
response = get_field_values(
|
||||
signoz,
|
||||
token,
|
||||
{"signal": "logs", "source": "audit", "name": "scope.version"},
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
scope_versions = response.json()["data"]
|
||||
assert set(scope_versions["values"]["stringValues"]) == {"1.0.0", "2.0.0"}
|
||||
|
||||
response = get_field_values(
|
||||
signoz,
|
||||
token,
|
||||
{"signal": "logs", "source": "audit", "name": "signoz.audit.verb", "limit": 2},
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
limited_verbs = response.json()["data"]
|
||||
assert limited_verbs["complete"] is False
|
||||
assert len(limited_verbs["values"]["stringValues"]) == 2
|
||||
|
||||
|
||||
def test_audit_fields_fixed_lookback_window(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_audit_logs: Callable[[list[AuditLog]], None],
|
||||
) -> None:
|
||||
now = datetime.now(tz=UTC)
|
||||
expired_ts = now - timedelta(days=35)
|
||||
recent_ts = now - timedelta(days=25)
|
||||
insert_audit_logs(
|
||||
[
|
||||
AuditLog(
|
||||
timestamp=expired_ts,
|
||||
resources={
|
||||
"service.name": "signoz",
|
||||
"signoz.resource.kind": "expired-resource",
|
||||
"signoz.resource.expired_only_key": "old",
|
||||
},
|
||||
attributes={
|
||||
"signoz.principal.email": "expired@acme.com",
|
||||
"signoz.audit.expired_only_key": "old",
|
||||
},
|
||||
event_name="signoz.audit.create",
|
||||
),
|
||||
AuditLog(
|
||||
timestamp=recent_ts,
|
||||
resources={
|
||||
"service.name": "signoz",
|
||||
"signoz.resource.kind": "dashboard",
|
||||
"signoz.resource.recent_only_key": "recent",
|
||||
},
|
||||
attributes={"signoz.principal.email": "recent@acme.com", "signoz.audit.verb": "update"},
|
||||
event_name="signoz.audit.update",
|
||||
),
|
||||
]
|
||||
)
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
wide_start_ms = int((now - timedelta(days=40)).timestamp() * 1000)
|
||||
narrow_start_ms = int((now - timedelta(hours=1)).timestamp() * 1000)
|
||||
end_ms = int((now + timedelta(minutes=1)).timestamp() * 1000)
|
||||
|
||||
response = get_field_keys(
|
||||
signoz,
|
||||
token,
|
||||
{
|
||||
"signal": "logs",
|
||||
"source": "audit",
|
||||
"startUnixMilli": wide_start_ms,
|
||||
"endUnixMilli": end_ms,
|
||||
},
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
wide_keys = response.json()["data"]["keys"]
|
||||
assert "signoz.audit.verb" in wide_keys
|
||||
assert "signoz.resource.recent_only_key" in wide_keys
|
||||
assert "signoz.audit.expired_only_key" not in wide_keys
|
||||
assert "signoz.resource.expired_only_key" not in wide_keys
|
||||
|
||||
response = get_field_keys(
|
||||
signoz,
|
||||
token,
|
||||
{
|
||||
"signal": "logs",
|
||||
"source": "audit",
|
||||
"startUnixMilli": narrow_start_ms,
|
||||
"endUnixMilli": end_ms,
|
||||
},
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
narrow_keys = response.json()["data"]["keys"]
|
||||
assert "signoz.audit.verb" in narrow_keys
|
||||
assert "signoz.resource.recent_only_key" in narrow_keys
|
||||
assert "signoz.audit.expired_only_key" not in narrow_keys
|
||||
assert "signoz.resource.expired_only_key" not in narrow_keys
|
||||
|
||||
response = get_field_values(
|
||||
signoz,
|
||||
token,
|
||||
{
|
||||
"signal": "logs",
|
||||
"source": "audit",
|
||||
"name": "signoz.principal.email",
|
||||
"startUnixMilli": narrow_start_ms,
|
||||
"endUnixMilli": end_ms,
|
||||
},
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
assert response.json()["data"]["values"]["stringValues"] == ["recent@acme.com"]
|
||||
|
||||
response = get_field_values(
|
||||
signoz,
|
||||
token,
|
||||
{
|
||||
"signal": "logs",
|
||||
"source": "audit",
|
||||
"name": "signoz.resource.kind",
|
||||
"fieldContext": "resource",
|
||||
"startUnixMilli": narrow_start_ms,
|
||||
"endUnixMilli": end_ms,
|
||||
},
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
assert response.json()["data"]["values"]["stringValues"] == ["dashboard"]
|
||||
Reference in New Issue
Block a user