mirror of
https://github.com/SigNoz/signoz.git
synced 2026-12-02 05:00:41 +00:00
Compare commits
9 Commits
split/2-au
...
perf/web-i
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f0c1f4bbf9 | ||
|
|
8fad61a8b5 | ||
|
|
ed69006a2a | ||
|
|
659d3fc204 | ||
|
|
30f6175903 | ||
|
|
98dee29f1f | ||
|
|
bcb6e708ab | ||
|
|
649c3a250c | ||
|
|
f7b1383427 |
@@ -165,6 +165,7 @@ apiserver:
|
||||
- /api/v1/health
|
||||
- /api/v1/version
|
||||
- /
|
||||
- /assets/
|
||||
|
||||
##################### Querier #####################
|
||||
querier:
|
||||
|
||||
3
frontend/.gitignore
vendored
3
frontend/.gitignore
vendored
@@ -1,4 +1,7 @@
|
||||
|
||||
# Vite copies public/ unhashed, and the Go server caches /assets/ as immutable
|
||||
/public/assets/
|
||||
|
||||
# Sentry Config File
|
||||
.env.sentry-build-plugin
|
||||
.qodo
|
||||
|
||||
@@ -298,6 +298,8 @@
|
||||
// Steers call sites to the src/lib/router facade (allowlisted in overrides below)
|
||||
"signoz/no-builder-ai-query-access": "error",
|
||||
// Steers AI slot access to lib/query/builderSlot (allowlisted in overrides below)
|
||||
"signoz/no-monaco-stripped-features": "error",
|
||||
// Bans Monaco features the production build strips, and monaco-editor value imports outside src/lib/monaco/setup.ts (allowlisted in overrides below)
|
||||
"no-restricted-globals": [
|
||||
"error",
|
||||
{
|
||||
@@ -644,6 +646,13 @@
|
||||
"rules": {
|
||||
"signoz/no-builder-ai-query-access": "off"
|
||||
}
|
||||
},
|
||||
{
|
||||
// setup.ts owns the monaco-editor imports that pick the languages and workers
|
||||
"files": ["src/lib/monaco/setup.ts"],
|
||||
"rules": {
|
||||
"signoz/no-monaco-stripped-features": "off"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
132
frontend/plugins/__tests__/no-monaco-stripped-features.test.mjs
Normal file
132
frontend/plugins/__tests__/no-monaco-stripped-features.test.mjs
Normal file
@@ -0,0 +1,132 @@
|
||||
import { ruleTester } from './rule-tester.mjs';
|
||||
|
||||
const IMPORT = 'Import Monaco from lib/monaco/setup';
|
||||
const STRIPPED = 'which the production build strips';
|
||||
|
||||
await ruleTester({
|
||||
rule: 'no-monaco-stripped-features',
|
||||
valid: [
|
||||
{
|
||||
name: 'setup import',
|
||||
code: "import { monaco } from 'lib/monaco/setup';",
|
||||
},
|
||||
{
|
||||
name: 'type-only import',
|
||||
code: "import type { editor } from 'monaco-editor';",
|
||||
},
|
||||
{
|
||||
name: 'inline type specifiers only',
|
||||
code: "import { type editor, type languages } from 'monaco-editor';",
|
||||
},
|
||||
{
|
||||
name: 'type-only re-export',
|
||||
code: "export type { editor } from 'monaco-editor';",
|
||||
},
|
||||
{
|
||||
name: 'inline type re-export specifiers only',
|
||||
code: "export { type editor, type languages } from 'monaco-editor';",
|
||||
},
|
||||
{
|
||||
name: 'react wrapper',
|
||||
code: "import Editor from '@monaco-editor/react';",
|
||||
},
|
||||
{
|
||||
name: 'kept provider',
|
||||
code: "monaco.languages.registerCompletionItemProvider('json', {});",
|
||||
},
|
||||
{
|
||||
name: 'stripped option turned off',
|
||||
code:
|
||||
"const o = { experimentalGpuAcceleration: 'off', minimap: { showMarkSectionHeaders: false } };",
|
||||
},
|
||||
],
|
||||
invalid: [
|
||||
{
|
||||
name: 'package entry import',
|
||||
code: "import * as monaco from 'monaco-editor';",
|
||||
errors: [{ message: IMPORT, line: 1, column: 25 }],
|
||||
},
|
||||
{
|
||||
name: 'deep import',
|
||||
code:
|
||||
"import 'monaco-editor/esm/vs/basic-languages/python/python.contribution.js';",
|
||||
errors: [{ message: IMPORT }],
|
||||
},
|
||||
{
|
||||
name: 'mixed value and type specifiers',
|
||||
code: "import { editor, type languages } from 'monaco-editor';",
|
||||
errors: [{ message: IMPORT }],
|
||||
},
|
||||
{
|
||||
name: 'dynamic import',
|
||||
code: "const m = await import('monaco-editor');",
|
||||
errors: [{ message: IMPORT }],
|
||||
},
|
||||
{
|
||||
name: 'require',
|
||||
code: "const m = require('monaco-editor');",
|
||||
errors: [{ message: IMPORT }],
|
||||
},
|
||||
{
|
||||
name: 're-export',
|
||||
code: "export { editor } from 'monaco-editor';",
|
||||
errors: [{ message: IMPORT }],
|
||||
},
|
||||
{
|
||||
name: 'mixed value and type re-export specifiers',
|
||||
code: "export { editor, type languages } from 'monaco-editor';",
|
||||
errors: [{ message: IMPORT }],
|
||||
},
|
||||
{
|
||||
name: 'export all',
|
||||
code: "export * from 'monaco-editor';",
|
||||
errors: [{ message: IMPORT }],
|
||||
},
|
||||
{
|
||||
name: 'stripped provider on monaco.languages',
|
||||
code: "monaco.languages.registerInlayHintsProvider('sql', {});",
|
||||
errors: [
|
||||
{
|
||||
message: 'needs the Monaco `inlayHints` contribution',
|
||||
line: 1,
|
||||
column: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'stripped provider on a destructured languages',
|
||||
code: "languages.registerSignatureHelpProvider('sql', {});",
|
||||
errors: [{ message: '`parameterHints`' }],
|
||||
},
|
||||
{
|
||||
name: 'stripped provider called bare',
|
||||
code: "registerRenameProvider('json', {});",
|
||||
errors: [{ message: '`rename`' }],
|
||||
},
|
||||
{
|
||||
name: 'stripped provider through a string key',
|
||||
code: "monaco.languages['registerRenameProvider']('json', {});",
|
||||
errors: [{ message: '`rename`' }],
|
||||
},
|
||||
{
|
||||
name: 'semantic tokens provider',
|
||||
code: "monaco.languages.registerDocumentSemanticTokensProvider('json', {});",
|
||||
errors: [{ message: '`semanticTokens`' }],
|
||||
},
|
||||
{
|
||||
name: 'stripped option turned on',
|
||||
code: "const o = { experimentalGpuAcceleration: 'on' };",
|
||||
errors: [{ message: '`gpu`', line: 1, column: 13 }],
|
||||
},
|
||||
{
|
||||
name: 'stripped option with a variable value',
|
||||
code: 'const o = { minimap: { showRegionSectionHeaders: enabled } };',
|
||||
errors: [{ message: STRIPPED }],
|
||||
},
|
||||
{
|
||||
name: 'quoted option key',
|
||||
code: "const o = { 'showMarkSectionHeaders': true };",
|
||||
errors: [{ message: '`sectionHeaders`' }],
|
||||
},
|
||||
],
|
||||
});
|
||||
147
frontend/plugins/rules/no-monaco-stripped-features.mjs
Normal file
147
frontend/plugins/rules/no-monaco-stripped-features.mjs
Normal file
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* Rule: no-monaco-stripped-features
|
||||
*
|
||||
* The production build drops the Monaco contributions listed in
|
||||
* plugins/rules/shared/monaco-stripped-features.mjs. Dev and Storybook still carry them,
|
||||
* so a provider or option for one of them works there and silently does nothing
|
||||
* in production. This rule reports them, plus value imports of `monaco-editor`
|
||||
* outside src/lib/monaco/setup.ts: the package entry registers every language and
|
||||
* worker.
|
||||
*
|
||||
* src/lib/monaco/setup.ts is allowlisted via overrides in .oxlintrc.json.
|
||||
*/
|
||||
|
||||
import { MONACO_STRIPPED_FEATURES } from './shared/monaco-stripped-features.mjs';
|
||||
|
||||
const featureByProvider = new Map();
|
||||
const featureByOption = new Map();
|
||||
for (const [feature, { providers = [], options = [] }] of Object.entries(
|
||||
MONACO_STRIPPED_FEATURES,
|
||||
)) {
|
||||
providers.forEach((name) => featureByProvider.set(name, feature));
|
||||
options.forEach((name) => featureByOption.set(name, feature));
|
||||
}
|
||||
|
||||
function isMonacoSource(value) {
|
||||
return value === 'monaco-editor' || value.startsWith('monaco-editor/');
|
||||
}
|
||||
|
||||
function isTypeOnlyImport(node) {
|
||||
return (
|
||||
node.importKind === 'type' ||
|
||||
(node.specifiers.length > 0 &&
|
||||
node.specifiers.every((s) => s.importKind === 'type'))
|
||||
);
|
||||
}
|
||||
|
||||
function isTypeOnlyExport(node) {
|
||||
return (
|
||||
node.exportKind === 'type' ||
|
||||
(node.specifiers.length > 0 &&
|
||||
node.specifiers.every((s) => s.exportKind === 'type'))
|
||||
);
|
||||
}
|
||||
|
||||
function propertyName(node) {
|
||||
if (node.type === 'Identifier') {
|
||||
return node.name;
|
||||
}
|
||||
if (node.type === 'Literal' && typeof node.value === 'string') {
|
||||
return node.value;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function isDisabledValue(node) {
|
||||
return (
|
||||
node.type === 'Literal' && (node.value === false || node.value === 'off')
|
||||
);
|
||||
}
|
||||
|
||||
export default {
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description:
|
||||
'Disallow Monaco features the production build strips, and value imports of monaco-editor outside src/lib/monaco/setup.ts',
|
||||
category: 'Monaco',
|
||||
},
|
||||
schema: [],
|
||||
messages: {
|
||||
provider:
|
||||
'{{name}} needs the Monaco `{{feature}}` contribution, which the production build strips, so it works in dev and does nothing in production. Remove `{{feature}}` from plugins/rules/shared/monaco-stripped-features.mjs to use it.',
|
||||
option:
|
||||
'`{{name}}` needs the Monaco `{{feature}}` contribution, which the production build strips, so it works in dev and does nothing in production. Remove `{{feature}}` from plugins/rules/shared/monaco-stripped-features.mjs to use it.',
|
||||
import:
|
||||
'Import Monaco from lib/monaco/setup, not monaco-editor: the package entry registers every language and worker. Type-only imports are fine.',
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const reportSource = (source) => {
|
||||
if (
|
||||
source?.type === 'Literal' &&
|
||||
typeof source.value === 'string' &&
|
||||
isMonacoSource(source.value)
|
||||
) {
|
||||
context.report({ node: source, messageId: 'import' });
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
ImportDeclaration(node) {
|
||||
if (!isTypeOnlyImport(node)) {
|
||||
reportSource(node.source);
|
||||
}
|
||||
},
|
||||
ImportExpression: (node) => reportSource(node.source),
|
||||
ExportAllDeclaration(node) {
|
||||
if (node.exportKind !== 'type') {
|
||||
reportSource(node.source);
|
||||
}
|
||||
},
|
||||
ExportNamedDeclaration(node) {
|
||||
if (!isTypeOnlyExport(node)) {
|
||||
reportSource(node.source);
|
||||
}
|
||||
},
|
||||
CallExpression(node) {
|
||||
const { callee } = node;
|
||||
if (callee.type === 'Identifier' && callee.name === 'require') {
|
||||
reportSource(node.arguments[0]);
|
||||
return;
|
||||
}
|
||||
const name =
|
||||
callee.type === 'MemberExpression'
|
||||
? propertyName(callee.property)
|
||||
: callee.type === 'Identifier'
|
||||
? callee.name
|
||||
: null;
|
||||
if (name !== null && featureByProvider.has(name)) {
|
||||
context.report({
|
||||
node: callee,
|
||||
messageId: 'provider',
|
||||
data: { name, feature: featureByProvider.get(name) },
|
||||
});
|
||||
}
|
||||
},
|
||||
Property(node) {
|
||||
if (node.computed) {
|
||||
return;
|
||||
}
|
||||
const name = propertyName(node.key);
|
||||
if (
|
||||
name !== null &&
|
||||
featureByOption.has(name) &&
|
||||
!isDisabledValue(node.value)
|
||||
) {
|
||||
context.report({
|
||||
node: node.key,
|
||||
messageId: 'option',
|
||||
data: { name, feature: featureByOption.get(name) },
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
29
frontend/plugins/rules/shared/monaco-stripped-features.mjs
Normal file
29
frontend/plugins/rules/shared/monaco-stripped-features.mjs
Normal file
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Monaco editor contributions the production build drops (vite.config.ts marks
|
||||
* them side-effect free), with the API that would need them at runtime.
|
||||
* `signoz/no-monaco-stripped-features` reports those APIs, since the build
|
||||
* leaves them without an error and without an effect.
|
||||
*
|
||||
* To use one, delete its entry here.
|
||||
*/
|
||||
export const MONACO_STRIPPED_FEATURES = {
|
||||
codelens: { providers: ['registerCodeLensProvider'] },
|
||||
dropOrPasteInto: {},
|
||||
gpu: { options: ['experimentalGpuAcceleration'] },
|
||||
inlayHints: { providers: ['registerInlayHintsProvider'] },
|
||||
inlineCompletions: { providers: ['registerInlineCompletionsProvider'] },
|
||||
linkedEditing: { providers: ['registerLinkedEditingRangeProvider'] },
|
||||
parameterHints: { providers: ['registerSignatureHelpProvider'] },
|
||||
rename: {
|
||||
providers: ['registerRenameProvider', 'registerNewSymbolNameProvider'],
|
||||
},
|
||||
sectionHeaders: {
|
||||
options: ['showRegionSectionHeaders', 'showMarkSectionHeaders'],
|
||||
},
|
||||
semanticTokens: {
|
||||
providers: [
|
||||
'registerDocumentSemanticTokensProvider',
|
||||
'registerDocumentRangeSemanticTokensProvider',
|
||||
],
|
||||
},
|
||||
};
|
||||
@@ -21,6 +21,7 @@ import noTextCss from './rules/no-text-css.mjs';
|
||||
import requireDisableReason from './rules/require-disable-reason.mjs';
|
||||
import noDomNodeAccess from './rules/no-dom-node-access.mjs';
|
||||
import noBuilderAiQueryAccess from './rules/no-builder-ai-query-access.mjs';
|
||||
import noMonacoStrippedFeatures from './rules/no-monaco-stripped-features.mjs';
|
||||
|
||||
export default {
|
||||
meta: {
|
||||
@@ -43,5 +44,6 @@ export default {
|
||||
'require-disable-reason': requireDisableReason,
|
||||
'no-dom-node-access': noDomNodeAccess,
|
||||
'no-builder-ai-query-access': noBuilderAiQueryAccess,
|
||||
'no-monaco-stripped-features': noMonacoStrippedFeatures,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
MetricAggregateOperator,
|
||||
QueryBuilderData,
|
||||
} from 'types/common/queryBuilder';
|
||||
import { DataSource, 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 = [MetricAggregateOperator.RATE];
|
||||
const spaceAggregateOperators = [MetricAggregateOperator.SUM];
|
||||
const timeAggregateOperators = [MetrictypesTimeAggregationDTO.rate];
|
||||
const spaceAggregateOperators = [MetrictypesSpaceAggregationDTO.sum];
|
||||
|
||||
return getQueryBuilderQueries({
|
||||
autocompleteData,
|
||||
@@ -113,12 +113,12 @@ export const databaseCallsAvgDuration = ({
|
||||
const legendFormulas = ['Average Duration'];
|
||||
const expressions = [FORMULA.DATABASE_CALLS_AVG_DURATION];
|
||||
const timeAggregateOperators = [
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.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,
|
||||
MetricAggregateOperator,
|
||||
QueryBuilderData,
|
||||
} from 'types/common/queryBuilder';
|
||||
import { DataSource, 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 = [
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.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 = [
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
];
|
||||
const dataSource = DataSource.METRICS;
|
||||
|
||||
@@ -202,8 +202,8 @@ export const externalCallRpsByAddress = ({
|
||||
const legends = [legend];
|
||||
const dataSource = DataSource.METRICS;
|
||||
|
||||
const timeAggregateOperators = [MetricAggregateOperator.RATE];
|
||||
const spaceAggregateOperators = [MetricAggregateOperator.SUM];
|
||||
const timeAggregateOperators = [MetrictypesTimeAggregationDTO.rate];
|
||||
const spaceAggregateOperators = [MetrictypesSpaceAggregationDTO.sum];
|
||||
|
||||
return getQueryBuilderQueries({
|
||||
autocompleteData,
|
||||
@@ -252,12 +252,12 @@ export const externalCallDurationByAddress = ({
|
||||
const additionalItems = [additionalItemsA, additionalItemsA];
|
||||
const legends = [legend, legend];
|
||||
const timeAggregateOperators = [
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
];
|
||||
const dataSource = DataSource.METRICS;
|
||||
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { MetrictypesComparisonSpaceAggregationParamDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
MetrictypesComparisonSpaceAggregationParamDTO,
|
||||
MetrictypesSpaceAggregationDTO,
|
||||
MetrictypesTimeAggregationDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
alphabet,
|
||||
initialFormulaBuilderFormValues,
|
||||
@@ -7,7 +11,6 @@ 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,
|
||||
@@ -34,8 +37,8 @@ const getAggregations = ({
|
||||
dataSource: DataSource;
|
||||
key: string;
|
||||
aggregateOperator: string;
|
||||
timeAggregation: MetricAggregateOperator;
|
||||
spaceAggregation: MetricAggregateOperator;
|
||||
timeAggregation: MetrictypesTimeAggregationDTO;
|
||||
spaceAggregation: MetrictypesSpaceAggregationDTO;
|
||||
comparisonSpaceAggregationParam?: MetrictypesComparisonSpaceAggregationParamDTO;
|
||||
}): IBuilderQuery['aggregations'] =>
|
||||
dataSource === DataSource.TRACES
|
||||
@@ -44,8 +47,8 @@ const getAggregations = ({
|
||||
{
|
||||
metricName: key,
|
||||
temporality: '',
|
||||
timeAggregation: timeAggregation as TimeAggregation,
|
||||
spaceAggregation: spaceAggregation as SpaceAggregation,
|
||||
timeAggregation,
|
||||
spaceAggregation,
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
...(comparisonSpaceAggregationParam && {
|
||||
comparisonSpaceAggregationParam,
|
||||
@@ -124,7 +127,6 @@ export const getQueryBuilderQuerieswithFormula = ({
|
||||
timeAggregateOperators,
|
||||
spaceAggregateOperators,
|
||||
comparisonSpaceAggregationParams = [],
|
||||
stepInterval,
|
||||
dataSource,
|
||||
}: BuilderQuerieswithFormulaProps): QueryBuilderData => ({
|
||||
queryFormulas: expressions.map((expression, index) => ({
|
||||
@@ -156,7 +158,7 @@ export const getQueryBuilderQuerieswithFormula = ({
|
||||
items: additionalItems[index],
|
||||
op: 'AND',
|
||||
},
|
||||
stepInterval: stepInterval ?? null,
|
||||
stepInterval: null,
|
||||
dataSource,
|
||||
})),
|
||||
queryTraceOperator: [],
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import { MetrictypesComparisonSpaceAggregationParamDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
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,
|
||||
MetricAggregateOperator,
|
||||
QueryBuilderData,
|
||||
} from 'types/common/queryBuilder';
|
||||
import { DataSource, QueryBuilderData } from 'types/common/queryBuilder';
|
||||
|
||||
import {
|
||||
FORMULA,
|
||||
@@ -26,11 +25,11 @@ import {
|
||||
LatencyProps,
|
||||
OperationPerSecProps,
|
||||
} from '../Tabs/types';
|
||||
import { getNearestHighestBucketValue } from '../utils';
|
||||
import {
|
||||
getQueryBuilderQueries,
|
||||
getQueryBuilderQuerieswithFormula,
|
||||
} from './MetricsPageQueriesFactory';
|
||||
import { getLatencyAtOrBelowAggregation } from './utils';
|
||||
|
||||
export const latency = ({
|
||||
servicename,
|
||||
@@ -43,7 +42,7 @@ export const latency = ({
|
||||
const newAutoCompleteData: BaseAutocompleteData = {
|
||||
key: isSpanMetricEnable
|
||||
? signozLatencyBucketMetrics
|
||||
: WidgetKeys.SpanDurationNano,
|
||||
: WidgetKeys.DurationNano,
|
||||
dataType: DataTypes.Float64,
|
||||
type: isSpanMetricEnable ? '' : MetricsType.Tag,
|
||||
};
|
||||
@@ -83,14 +82,14 @@ export const latency = ({
|
||||
const queryNameAndExpression = QUERYNAME_AND_EXPRESSION;
|
||||
|
||||
const timeAggregateOperators = [
|
||||
MetricAggregateOperator.EMPTY,
|
||||
MetricAggregateOperator.EMPTY,
|
||||
MetricAggregateOperator.EMPTY,
|
||||
MetrictypesTimeAggregationDTO[''],
|
||||
MetrictypesTimeAggregationDTO[''],
|
||||
MetrictypesTimeAggregationDTO[''],
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetricAggregateOperator.P50,
|
||||
MetricAggregateOperator.P90,
|
||||
MetricAggregateOperator.P99,
|
||||
MetrictypesSpaceAggregationDTO.p50,
|
||||
MetrictypesSpaceAggregationDTO.p90,
|
||||
MetrictypesSpaceAggregationDTO.p99,
|
||||
];
|
||||
|
||||
return getQueryBuilderQueries({
|
||||
@@ -109,33 +108,17 @@ export const apDexMetricsQueryBuilderQueries = ({
|
||||
servicename,
|
||||
tagFilterItems,
|
||||
topLevelOperationsRoute,
|
||||
threashold,
|
||||
delta,
|
||||
threshold,
|
||||
metricsBuckets,
|
||||
}: ApDexMetricsQueryBuilderQueriesProps): QueryBuilderData => {
|
||||
// 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 satisfied = getLatencyAtOrBelowAggregation(
|
||||
threshold * 1000,
|
||||
metricsBuckets,
|
||||
);
|
||||
const tolerating = getLatencyAtOrBelowAggregation(
|
||||
threshold * 1000 * 4,
|
||||
metricsBuckets,
|
||||
);
|
||||
|
||||
const autoCompleteDataA: BaseAutocompleteData = {
|
||||
key: WidgetKeys.SignozLatencyCount,
|
||||
@@ -213,63 +196,27 @@ 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, filterItemC];
|
||||
const additionalItems = [filterItemA, filterItemB, filterItemB];
|
||||
const legends = [GraphTitle.APDEX];
|
||||
const disabled = Array(3).fill(true);
|
||||
const expressions = delta
|
||||
? [FORMULA.APDEX_DELTA_SPAN_METRICS]
|
||||
: [FORMULA.APDEX_CUMULATIVE_SPAN_METRICS];
|
||||
const expressions = [FORMULA.APDEX];
|
||||
const legendFormulas = [GraphTitle.APDEX];
|
||||
// v5 forces increase on histograms, so the total matches it
|
||||
const timeAggregateOperators = [
|
||||
MetricAggregateOperator.INCREASE,
|
||||
MetricAggregateOperator.INCREASE,
|
||||
MetricAggregateOperator.INCREASE,
|
||||
MetrictypesTimeAggregationDTO.increase,
|
||||
MetrictypesTimeAggregationDTO.increase,
|
||||
MetrictypesTimeAggregationDTO.increase,
|
||||
];
|
||||
|
||||
// a plain sum keeps the le label on B and C, and the formula then cannot join them
|
||||
const spaceAggregateOperators = [
|
||||
MetricAggregateOperator.SUM,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
satisfied.spaceAggregation,
|
||||
tolerating.spaceAggregation,
|
||||
];
|
||||
@@ -336,8 +283,8 @@ export const operationPerSec = ({
|
||||
const legends = OPERATION_LEGENDS;
|
||||
const dataSource = DataSource.METRICS;
|
||||
|
||||
const timeAggregateOperators = [MetricAggregateOperator.RATE];
|
||||
const spaceAggregateOperators = [MetricAggregateOperator.SUM];
|
||||
const timeAggregateOperators = [MetrictypesTimeAggregationDTO.rate];
|
||||
const spaceAggregateOperators = [MetrictypesSpaceAggregationDTO.sum];
|
||||
|
||||
return getQueryBuilderQueries({
|
||||
autocompleteData,
|
||||
@@ -431,12 +378,12 @@ export const errorPercentage = ({
|
||||
const expressions = [FORMULA.ERROR_PERCENTAGE];
|
||||
const legendFormulas = [GraphTitle.ERROR_PERCENTAGE];
|
||||
const timeAggregateOperators = [
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.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,
|
||||
MetricAggregateOperator,
|
||||
QueryBuilderData,
|
||||
} from 'types/common/queryBuilder';
|
||||
import { DataSource, QueryBuilderData } from 'types/common/queryBuilder';
|
||||
|
||||
import {
|
||||
GraphTitle,
|
||||
@@ -112,20 +112,20 @@ export const topOperationQueries = ({
|
||||
KeyOperationTableHeader.NUM_OF_CALLS,
|
||||
];
|
||||
const timeAggregateOperators = [
|
||||
MetricAggregateOperator.EMPTY,
|
||||
MetricAggregateOperator.EMPTY,
|
||||
MetricAggregateOperator.EMPTY,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetrictypesTimeAggregationDTO[''],
|
||||
MetrictypesTimeAggregationDTO[''],
|
||||
MetrictypesTimeAggregationDTO[''],
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetricAggregateOperator.P50,
|
||||
MetricAggregateOperator.P90,
|
||||
MetricAggregateOperator.P99,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetrictypesSpaceAggregationDTO.p50,
|
||||
MetrictypesSpaceAggregationDTO.p90,
|
||||
MetrictypesSpaceAggregationDTO.p99,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.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 { QueryEnvelope } from 'types/api/v5/queryRange';
|
||||
import { QueryBuilderFormula, QueryEnvelope } from 'types/api/v5/queryRange';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
|
||||
import {
|
||||
@@ -102,8 +102,7 @@ describe('service details queries on v5', () => {
|
||||
servicename: 'frontend',
|
||||
tagFilterItems: [],
|
||||
topLevelOperationsRoute: ['GET /'],
|
||||
threashold: 0.5,
|
||||
delta: true,
|
||||
threshold: 0.5,
|
||||
metricsBuckets: [100, 250, 500, 1000, 2000, 5000],
|
||||
}),
|
||||
);
|
||||
@@ -139,6 +138,11 @@ 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', () => {
|
||||
@@ -147,8 +151,7 @@ describe('service details queries on v5', () => {
|
||||
servicename: 'frontend',
|
||||
tagFilterItems: [],
|
||||
topLevelOperationsRoute: ['GET /'],
|
||||
threashold: 0.5,
|
||||
delta: true,
|
||||
threshold: 0.5,
|
||||
metricsBuckets: [100, 250, 500, 1000],
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
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,7 +24,6 @@ import { v4 as uuid } from 'uuid';
|
||||
import { ApDexMetricsProps } from './types';
|
||||
|
||||
function ApDexMetrics({
|
||||
delta,
|
||||
metricsBuckets,
|
||||
thresholdValue,
|
||||
onDragSelect,
|
||||
@@ -44,9 +43,8 @@ function ApDexMetrics({
|
||||
servicename,
|
||||
tagFilterItems,
|
||||
topLevelOperationsRoute,
|
||||
threashold: thresholdValue || 0,
|
||||
delta: delta || false,
|
||||
metricsBuckets: metricsBuckets || [],
|
||||
threshold: thresholdValue || 0,
|
||||
metricsBuckets,
|
||||
}),
|
||||
clickhouse_sql: [],
|
||||
id: uuid(),
|
||||
@@ -75,7 +73,6 @@ function ApDexMetrics({
|
||||
id: SERVICE_CHART_ID.apdex,
|
||||
}),
|
||||
[
|
||||
delta,
|
||||
metricsBuckets,
|
||||
servicename,
|
||||
tagFilterItems,
|
||||
@@ -92,10 +89,7 @@ function ApDexMetrics({
|
||||
}, [thresholdValue]);
|
||||
|
||||
const isQueryEnabled =
|
||||
topLevelOperationsRoute.length > 0 &&
|
||||
!!metricsBuckets &&
|
||||
metricsBuckets?.length > 0 &&
|
||||
delta !== undefined;
|
||||
topLevelOperationsRoute.length > 0 && metricsBuckets.length > 0;
|
||||
|
||||
return (
|
||||
<Graph
|
||||
@@ -110,9 +104,4 @@ function ApDexMetrics({
|
||||
);
|
||||
}
|
||||
|
||||
ApDexMetrics.defaultProps = {
|
||||
delta: undefined,
|
||||
le: undefined,
|
||||
};
|
||||
|
||||
export default ApDexMetrics;
|
||||
|
||||
@@ -31,7 +31,6 @@ function ApDexMetricsApplication({
|
||||
<ApDexMetrics
|
||||
topLevelOperationsRoute={topLevelOperationsRoute}
|
||||
handleGraphClick={handleGraphClick}
|
||||
delta={data?.data.delta}
|
||||
metricsBuckets={data?.data.le || []}
|
||||
onDragSelect={onDragSelect}
|
||||
tagFilterItems={tagFilterItems}
|
||||
|
||||
@@ -13,6 +13,5 @@ export interface ApDexDataSwitcherProps extends ApDexApplicationProps {
|
||||
}
|
||||
|
||||
export interface ApDexMetricsProps extends ApDexDataSwitcherProps {
|
||||
delta?: boolean;
|
||||
metricsBuckets?: number[];
|
||||
metricsBuckets: number[];
|
||||
}
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import { ReactNode } from 'react';
|
||||
import { MetrictypesComparisonSpaceAggregationParamDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
MetrictypesComparisonSpaceAggregationParamDTO,
|
||||
MetrictypesSpaceAggregationDTO,
|
||||
MetrictypesTimeAggregationDTO,
|
||||
} 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, MetricAggregateOperator } from 'types/common/queryBuilder';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import type { WidgetKeys } from '../constant';
|
||||
|
||||
export interface IServiceName {
|
||||
servicename: string;
|
||||
@@ -30,8 +36,8 @@ export interface BuilderQueriesProps {
|
||||
aggregateOperator?: string[];
|
||||
dataSource: DataSource;
|
||||
queryNameAndExpression?: string[];
|
||||
timeAggregateOperators: MetricAggregateOperator[];
|
||||
spaceAggregateOperators: MetricAggregateOperator[];
|
||||
timeAggregateOperators: MetrictypesTimeAggregationDTO[];
|
||||
spaceAggregateOperators: MetrictypesSpaceAggregationDTO[];
|
||||
}
|
||||
|
||||
export interface BuilderQuerieswithFormulaProps {
|
||||
@@ -42,14 +48,12 @@ export interface BuilderQuerieswithFormulaProps {
|
||||
expressions: string[];
|
||||
legendFormulas: string[];
|
||||
additionalItems: TagFilterItem[][];
|
||||
timeAggregateOperators: MetricAggregateOperator[];
|
||||
spaceAggregateOperators: MetricAggregateOperator[];
|
||||
timeAggregateOperators: MetrictypesTimeAggregationDTO[];
|
||||
spaceAggregateOperators: MetrictypesSpaceAggregationDTO[];
|
||||
comparisonSpaceAggregationParams?: (
|
||||
| MetrictypesComparisonSpaceAggregationParamDTO
|
||||
| undefined
|
||||
)[];
|
||||
// v5 picks its own step when none is sent; v4 needs one
|
||||
stepInterval?: number;
|
||||
dataSource: DataSource;
|
||||
}
|
||||
|
||||
@@ -70,7 +74,7 @@ export interface ApDexProps {
|
||||
servicename: IServiceName['servicename'];
|
||||
tagFilterItems: TagFilterItem[];
|
||||
topLevelOperationsRoute: string[];
|
||||
threashold: number;
|
||||
threshold: number;
|
||||
}
|
||||
|
||||
export interface TableRendererProps {
|
||||
@@ -78,7 +82,12 @@ 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,23 +30,10 @@ export const SERVICE_DETAIL_DRILLDOWN_ENABLED = true;
|
||||
export enum FORMULA {
|
||||
ERROR_PERCENTAGE = 'A*100/B',
|
||||
DATABASE_CALLS_AVG_DURATION = 'A/B',
|
||||
// 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',
|
||||
// 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',
|
||||
}
|
||||
|
||||
export const TOP_LEVEL_OPERATIONS = ['{{.top_level_operations}}'];
|
||||
@@ -80,17 +67,13 @@ export enum MetricsType {
|
||||
}
|
||||
|
||||
export enum WidgetKeys {
|
||||
Le = 'le',
|
||||
Name = 'name',
|
||||
HasError = 'hasError',
|
||||
Address = 'address',
|
||||
DurationNano = 'durationNano',
|
||||
SpanDurationNano = 'duration_nano',
|
||||
DurationNano = '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,17 +29,24 @@ 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 +Inf for value higher than any bucket', () => {
|
||||
expect(getNearestHighestBucketValue(80, [10, 20, 30, 40, 60, 70])).toBe(
|
||||
'+Inf',
|
||||
);
|
||||
it('should return undefined for value higher than any bucket', () => {
|
||||
expect(
|
||||
getNearestHighestBucketValue(80, [10, 20, 30, 40, 60, 70]),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should return the first bucket for value lower than all buckets', () => {
|
||||
expect(getNearestHighestBucketValue(5, [10, 20, 30, 40, 60, 70])).toBe('10');
|
||||
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]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -47,11 +47,9 @@ export const navigateToTrace = ({
|
||||
export const getNearestHighestBucketValue = (
|
||||
value: number,
|
||||
buckets: number[],
|
||||
): string => {
|
||||
// sort the buckets
|
||||
buckets.sort((a, b) => a - b);
|
||||
const nearestBucket = buckets.find((bucket) => bucket >= value);
|
||||
return nearestBucket?.toString() || '+Inf';
|
||||
): number | undefined => {
|
||||
// buckets are cached query data; never mutate
|
||||
return [...buckets].sort((a, b) => a - b).find((bucket) => bucket >= value);
|
||||
};
|
||||
|
||||
export const convertedTracesToDownloadData = (
|
||||
|
||||
@@ -3,8 +3,3 @@
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-3);
|
||||
}
|
||||
|
||||
.label {
|
||||
font-size: var(--label-small-400-font-size);
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
|
||||
@@ -32,8 +32,3 @@
|
||||
gap: var(--spacing-6);
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.titleText {
|
||||
color: inherit;
|
||||
font-size: var(--label-base-400-font-size);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
MetrictypesSpaceAggregationDTO,
|
||||
MetrictypesTimeAggregationDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { ServiceDataProps } from 'api/metrics/getTopLevelOperations';
|
||||
import { OPERATORS } from 'constants/queryBuilder';
|
||||
import {
|
||||
@@ -11,11 +15,7 @@ import {
|
||||
DataTypes,
|
||||
} from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import {
|
||||
DataSource,
|
||||
MetricAggregateOperator,
|
||||
QueryBuilderData,
|
||||
} from 'types/common/queryBuilder';
|
||||
import { DataSource, QueryBuilderData } from 'types/common/queryBuilder';
|
||||
|
||||
export const serviceMetricsQuery = (
|
||||
topLevelOperation: [keyof ServiceDataProps, string[]],
|
||||
@@ -155,16 +155,16 @@ export const serviceMetricsQuery = (
|
||||
];
|
||||
|
||||
const timeAggregateOperators = [
|
||||
MetricAggregateOperator.EMPTY,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetrictypesTimeAggregationDTO[''],
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
MetrictypesTimeAggregationDTO.rate,
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetricAggregateOperator.P99,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetrictypesSpaceAggregationDTO.p99,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
MetrictypesSpaceAggregationDTO.sum,
|
||||
];
|
||||
|
||||
const disabled = [false, true, true, false];
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import * as monaco from 'monaco-editor';
|
||||
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js';
|
||||
import * as jsonContribution from 'monaco-editor/esm/vs/language/json/monaco.contribution.js';
|
||||
import 'monaco-editor/esm/vs/basic-languages/sql/sql.contribution.js';
|
||||
import 'monaco-editor/esm/vs/basic-languages/yaml/yaml.contribution.js';
|
||||
import EditorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';
|
||||
import JsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker';
|
||||
|
||||
@@ -11,10 +14,13 @@ self.MonacoEnvironment = {
|
||||
if (label === 'json') {
|
||||
return new JsonWorker(); // JSON language service
|
||||
}
|
||||
// SigNoz editors use JSON + a hand-registered ClickHouse tokenizer (no worker),
|
||||
// so the base editor worker covers everything else.
|
||||
return new EditorWorker(); // base worker — sql, yaml, plaintext etc.
|
||||
// SigNoz editors use JSON, SQL and YAML. Their tokenizers run on the main thread,
|
||||
// so the base editor worker covers the rest (word suggestions, links).
|
||||
return new EditorWorker(); // base worker: sql, yaml, plaintext etc.
|
||||
},
|
||||
};
|
||||
|
||||
// The `monaco-editor` entry exposes JSON this way; the role editor reads `languages.json`.
|
||||
Object.assign(monaco.languages, { json: jsonContribution });
|
||||
|
||||
export { monaco };
|
||||
|
||||
@@ -41,6 +41,12 @@ 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 {
|
||||
@@ -167,6 +173,41 @@ 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,14 +53,16 @@ function AllAlertList(): JSX.Element {
|
||||
|
||||
const tab = urlQuery.get('tab');
|
||||
const subTab = urlQuery.get('subTab');
|
||||
const isAlertHistory = location.pathname === ROUTES.ALERT_HISTORY;
|
||||
const isAlertOverview = location.pathname === ROUTES.ALERT_OVERVIEW;
|
||||
const isRuleDetails =
|
||||
location.pathname === ROUTES.ALERT_HISTORY ||
|
||||
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 (isAlertHistory || isAlertOverview) {
|
||||
if (isRuleDetails) {
|
||||
return AlertListTabs.ALERT_RULES;
|
||||
}
|
||||
if (isChannelDetails) {
|
||||
@@ -74,7 +76,7 @@ function AllAlertList(): JSX.Element {
|
||||
return AlertListTabs.CONFIGURATION;
|
||||
}
|
||||
return tab || AlertListTabs.ALERT_RULES;
|
||||
}, [isAlertHistory, isAlertOverview, isChannelDetails, tab]);
|
||||
}, [isRuleDetails, isChannelDetails, tab]);
|
||||
|
||||
const getActiveSubTab = useCallback((): AlertListSubTabs => {
|
||||
if (isChannelDetails) {
|
||||
@@ -114,6 +116,18 @@ 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();
|
||||
@@ -201,7 +215,7 @@ function AllAlertList(): JSX.Element {
|
||||
key: AlertListTabs.ALERT_RULES,
|
||||
children: (
|
||||
<div className="alert-rules-container">
|
||||
{isAlertHistory || isAlertOverview ? <AlertDetails /> : <AllAlertRules />}
|
||||
{isRuleDetails ? <AlertDetails /> : <AllAlertRules />}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
@@ -222,12 +236,8 @@ function AllAlertList(): JSX.Element {
|
||||
destroyInactiveTabPane
|
||||
items={items}
|
||||
activeKey={getActiveTab()}
|
||||
onChange={handleTopTabChange}
|
||||
className={`alerts-container ${
|
||||
isAlertHistory || isAlertOverview || isChannelDetails
|
||||
? 'alert-details-tabs'
|
||||
: ''
|
||||
}`}
|
||||
onTabClick={handleTopTabClick}
|
||||
className={`alerts-container ${isDetailsView ? 'alert-details-tabs' : ''}`}
|
||||
tabBarExtraContent={
|
||||
<HeaderRightSection
|
||||
enableAnnouncements={false}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { ComponentType } from 'react';
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import * as monaco from 'monaco-editor';
|
||||
import { monaco } from 'lib/monaco/setup';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { renderAtRoute } from '@/storybook/renderAtRoute';
|
||||
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
|
||||
|
||||
@@ -6,6 +6,7 @@ import type { Plugin, TransformResult, UserConfig } from 'vite';
|
||||
import { defineConfig, loadEnv } from 'vite';
|
||||
import vitePluginChecker from 'vite-plugin-checker';
|
||||
import viteCompression from 'vite-plugin-compression';
|
||||
import { MONACO_STRIPPED_FEATURES } from './plugins/rules/shared/monaco-stripped-features.mjs';
|
||||
import type {
|
||||
Appcues,
|
||||
Posthog,
|
||||
@@ -74,6 +75,10 @@ function rawMarkdownPlugin(): Plugin {
|
||||
};
|
||||
}
|
||||
|
||||
// Monaco contributions that need a provider SigNoz never registers. monaco-editor
|
||||
// declares no `sideEffects`, so its bare imports keep all of them.
|
||||
const MONACO_STRIPPED_FEATURE_NAMES = Object.keys(MONACO_STRIPPED_FEATURES);
|
||||
|
||||
export default defineConfig(({ mode }): UserConfig => {
|
||||
const env = loadEnv(mode, process.cwd(), '') as ImportMetaEnv;
|
||||
// Base path for serving the app (e.g., '/signoz/'). Defaults to '/'.
|
||||
@@ -180,8 +185,23 @@ export default defineConfig(({ mode }): UserConfig => {
|
||||
sourcemap: true,
|
||||
outDir: 'build',
|
||||
cssMinify: 'esbuild',
|
||||
// The Go server caches /assets/ as immutable, so every file there must carry a content hash.
|
||||
assetsDir: 'assets',
|
||||
rolldownOptions: {
|
||||
treeshake: {
|
||||
moduleSideEffects: [
|
||||
{
|
||||
test: new RegExp(
|
||||
`monaco-editor/esm/vs/editor/contrib/(${MONACO_STRIPPED_FEATURE_NAMES.join('|')})/`,
|
||||
),
|
||||
sideEffects: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
output: {
|
||||
entryFileNames: 'assets/[name]-[hash].js',
|
||||
chunkFileNames: 'assets/[name]-[hash].js',
|
||||
assetFileNames: 'assets/[name]-[hash].[ext]',
|
||||
// Without this group Rolldown splits the entry's static graph into ~300
|
||||
// chunks, 324 requests on first load.
|
||||
codeSplitting: {
|
||||
|
||||
@@ -53,6 +53,7 @@ func newConfig() factory.Config {
|
||||
"/api/v1/health",
|
||||
"/api/v1/version",
|
||||
"/",
|
||||
"/assets/",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -8,25 +8,38 @@ import (
|
||||
)
|
||||
|
||||
type Cache struct {
|
||||
maxAge time.Duration
|
||||
cacheControl string
|
||||
}
|
||||
|
||||
func NewCache(maxAge time.Duration) *Cache {
|
||||
// Cache-Control: no-cache is equivalent to Cache-Control: max-age=0, must-revalidate as most HTTP/1.0 caches don't support no-cache directives
|
||||
directives := []string{
|
||||
"max-age=" + strconv.Itoa(int(maxAge.Seconds())),
|
||||
"no-cache", // Note that no-cache does not mean "don't cache". no-cache allows caches to store a response but requires them to revalidate it before reuse.
|
||||
"private", //If you forget to add private to a response with personalized content, then that response can be stored in a shared cache and end up being reused for multiple users, which can cause personal information to leak.
|
||||
"must-revalidate", // HTTP allows caches to reuse stale responses when they are disconnected from the origin server. must-revalidate is a way to prevent this from happening - either the stored response is revalidated with the origin server or a 504 (Gateway Timeout) response is generated.
|
||||
}
|
||||
|
||||
return &Cache{
|
||||
maxAge: maxAge,
|
||||
cacheControl: strings.Join(directives, ","),
|
||||
}
|
||||
}
|
||||
|
||||
func NewImmutableCache(maxAge time.Duration) *Cache {
|
||||
directives := []string{
|
||||
"public",
|
||||
"max-age=" + strconv.Itoa(int(maxAge.Seconds())),
|
||||
"immutable",
|
||||
}
|
||||
|
||||
return &Cache{
|
||||
cacheControl: strings.Join(directives, ","),
|
||||
}
|
||||
}
|
||||
|
||||
func (middleware *Cache) Wrap(next http.Handler) http.Handler {
|
||||
// Cache-Control: no-cache is equivalent to Cache-Control: max-age=0, must-revalidate as most HTTP/1.0 caches don't support no-cache directives
|
||||
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
|
||||
directives := []string{
|
||||
"max-age=" + strconv.Itoa(int(middleware.maxAge.Seconds())),
|
||||
"no-cache", // Note that no-cache does not mean "don't cache". no-cache allows caches to store a response but requires them to revalidate it before reuse.
|
||||
"private", //If you forget to add private to a response with personalized content, then that response can be stored in a shared cache and end up being reused for multiple users, which can cause personal information to leak.
|
||||
"must-revalidate", // HTTP allows caches to reuse stale responses when they are disconnected from the origin server. must-revalidate is a way to prevent this from happening - either the stored response is revalidated with the origin server or a 504 (Gateway Timeout) response is generated.
|
||||
}
|
||||
rw.Header().Set("Cache-Control", strings.Join(directives, ","))
|
||||
rw.Header().Set("Cache-Control", middleware.cacheControl)
|
||||
next.ServeHTTP(rw, req)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package middleware
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -44,8 +45,8 @@ func TestCache(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
req, err := http.NewRequest("GET", "http://"+listener.Addr().String(), nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -62,3 +63,25 @@ func TestCache(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCacheControl(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
cache *Cache
|
||||
expected string
|
||||
}{
|
||||
{name: "NoCache", cache: NewCache(0), expected: "max-age=0,no-cache,private,must-revalidate"},
|
||||
{name: "Immutable", cache: NewImmutableCache(365 * 24 * time.Hour), expected: "public,max-age=31536000,immutable"},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
rw := httptest.NewRecorder()
|
||||
testCase.cache.Wrap(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})).ServeHTTP(rw, httptest.NewRequest(http.MethodGet, "/", nil))
|
||||
|
||||
assert.Equal(t, testCase.expected, rw.Header().Get("Cache-Control"))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,10 @@ import (
|
||||
"html/template"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/factory"
|
||||
@@ -16,6 +19,11 @@ import (
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
const (
|
||||
assetsPathPrefix = "/assets/"
|
||||
assetsMaxAge = 365 * 24 * time.Hour
|
||||
)
|
||||
|
||||
type provider struct {
|
||||
config web.Config
|
||||
indexContents []byte
|
||||
@@ -64,8 +72,18 @@ func New(ctx context.Context, settings factory.ProviderSettings, config web.Conf
|
||||
}
|
||||
|
||||
func (provider *provider) AddToRouter(router *mux.Router) error {
|
||||
assetsCache := middleware.NewImmutableCache(assetsMaxAge)
|
||||
err := router.PathPrefix(assetsPathPrefix).
|
||||
MatcherFunc(provider.matchAsset).
|
||||
Handler(
|
||||
assetsCache.Wrap(http.HandlerFunc(provider.ServeHTTP)),
|
||||
).GetError()
|
||||
if err != nil {
|
||||
return errors.WrapInternalf(err, errors.CodeInternal, "unable to add web assets to router")
|
||||
}
|
||||
|
||||
cache := middleware.NewCache(0)
|
||||
err := router.PathPrefix("/").
|
||||
err = router.PathPrefix("/").
|
||||
Handler(
|
||||
cache.Wrap(http.HandlerFunc(provider.ServeHTTP)),
|
||||
).GetError()
|
||||
@@ -78,10 +96,10 @@ func (provider *provider) AddToRouter(router *mux.Router) error {
|
||||
|
||||
func (provider *provider) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||
// Join internally call path.Clean to prevent directory traversal
|
||||
path := filepath.Join(provider.config.Directory, req.URL.Path)
|
||||
filePath := filepath.Join(provider.config.Directory, req.URL.Path)
|
||||
|
||||
// check whether a file exists or is a directory at the given path
|
||||
fi, err := os.Stat(path)
|
||||
fi, err := os.Stat(filePath)
|
||||
if err != nil {
|
||||
// if the file doesn't exist, serve index.html
|
||||
if os.IsNotExist(err) {
|
||||
@@ -105,6 +123,28 @@ func (provider *provider) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||
provider.fileHandler.ServeHTTP(rw, req)
|
||||
}
|
||||
|
||||
// matchAsset matches files under /assets/, which are content-hashed, so their URL changes with their content.
|
||||
func (provider *provider) matchAsset(req *http.Request, _ *mux.RouteMatch) bool {
|
||||
// a non-canonical URL can name a file outside /assets/ or get a redirect
|
||||
if req.URL.Path != path.Clean(req.URL.Path) {
|
||||
return false
|
||||
}
|
||||
|
||||
if !strings.HasPrefix(req.URL.Path, assetsPathPrefix) {
|
||||
return false
|
||||
}
|
||||
|
||||
filePath := filepath.Join(provider.config.Directory, req.URL.Path)
|
||||
|
||||
// a missing file or a directory serves index.html
|
||||
fi, err := os.Stat(filePath)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return !fi.IsDir()
|
||||
}
|
||||
|
||||
func (provider *provider) serveIndex(rw http.ResponseWriter) {
|
||||
rw.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = rw.Write(provider.indexContents)
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -251,3 +252,87 @@ func TestServeStaticFilesUnchanged(t *testing.T) {
|
||||
|
||||
assert.Equal(t, string(expected), httpGet(t, base+"/assets/style.css"))
|
||||
}
|
||||
|
||||
func TestServeCacheControl(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
directory := t.TempDir()
|
||||
files := map[string]string{
|
||||
"index.html": "<html>index</html>",
|
||||
"assets/x.js": "console.log('x')",
|
||||
"assets/nested/y.css": "body{}",
|
||||
"assets-legacy/z.js": "console.log('z')",
|
||||
"favicon.ico": "icon",
|
||||
"css/uPlot.min.css": ".uplot{}",
|
||||
"locales/en/main.json": "{}",
|
||||
}
|
||||
for name, content := range files {
|
||||
require.NoError(t, os.MkdirAll(filepath.Join(directory, filepath.Dir(name)), 0o755))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(directory, name), []byte(content), 0o644))
|
||||
}
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
basePath string
|
||||
path string
|
||||
expectedStatus int
|
||||
expectedBody string
|
||||
expectedCC string
|
||||
}{
|
||||
{name: "ExistingAsset_Immutable", path: "/assets/x.js", expectedBody: files["assets/x.js"], expectedCC: "public,max-age=31536000,immutable"},
|
||||
{name: "ExistingNestedAsset_Immutable", path: "/assets/nested/y.css", expectedBody: files["assets/nested/y.css"], expectedCC: "public,max-age=31536000,immutable"},
|
||||
{name: "MissingAsset_ServesIndex_NoCache", path: "/assets/missing-AAAA.js", expectedBody: files["index.html"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
|
||||
{name: "AssetsDirectory_ServesIndex_NoCache", path: "/assets/nested/", expectedBody: files["index.html"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
|
||||
{name: "Root_ServesIndex_NoCache", path: "/", expectedBody: files["index.html"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
|
||||
{name: "UnknownRoute_ServesIndex_NoCache", path: "/does-not-exist", expectedBody: files["index.html"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
|
||||
{name: "NonAssetFile_NoCache", path: "/favicon.ico", expectedBody: files["favicon.ico"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
|
||||
{name: "NonAssetNestedFile_NoCache", path: "/css/uPlot.min.css", expectedBody: files["css/uPlot.min.css"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
|
||||
{name: "LocaleFile_NoCache", path: "/locales/en/main.json", expectedBody: files["locales/en/main.json"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
|
||||
{name: "AssetsPrefixLookalike_NoCache", path: "/assets-legacy/z.js", expectedBody: files["assets-legacy/z.js"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
|
||||
{name: "BasePath_ExistingAsset_Immutable", basePath: "/signoz", path: "/assets/x.js", expectedBody: files["assets/x.js"], expectedCC: "public,max-age=31536000,immutable"},
|
||||
{name: "BasePath_MissingAsset_ServesIndex_NoCache", basePath: "/signoz", path: "/assets/missing-AAAA.js", expectedBody: files["index.html"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
|
||||
{name: "BasePath_NonAssetFile_NoCache", basePath: "/signoz", path: "/favicon.ico", expectedBody: files["favicon.ico"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
|
||||
{name: "AssetTrailingSlash_Redirects_NoCache", path: "/assets/x.js/", expectedStatus: http.StatusMovedPermanently, expectedCC: "max-age=0,no-cache,private,must-revalidate"},
|
||||
{name: "EncodedDotDotOutOfAssets_NoCache", path: "/assets/%2e%2e/locales/en/main.json", expectedBody: files["locales/en/main.json"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
|
||||
{name: "BasePath_Root_ServesIndex_NoCache", basePath: "/signoz", path: "/", expectedBody: files["index.html"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
routerWeb, err := New(
|
||||
context.Background(),
|
||||
factorytest.NewSettings(),
|
||||
web.Config{Index: "index.html", Directory: directory},
|
||||
global.Config{ExternalURL: &url.URL{Path: testCase.basePath}},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
router := mux.NewRouter().UseEncodedPath()
|
||||
require.NoError(t, routerWeb.AddToRouter(router))
|
||||
|
||||
var handler http.Handler = router
|
||||
if testCase.basePath != "" {
|
||||
handler = http.StripPrefix(testCase.basePath, router)
|
||||
}
|
||||
|
||||
server := httptest.NewServer(handler)
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
res, err := client.Get(server.URL + testCase.basePath + testCase.path)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = res.Body.Close() }()
|
||||
|
||||
body, err := io.ReadAll(res.Body)
|
||||
require.NoError(t, err)
|
||||
|
||||
expectedStatus := testCase.expectedStatus
|
||||
if expectedStatus == 0 {
|
||||
expectedStatus = http.StatusOK
|
||||
}
|
||||
assert.Equal(t, expectedStatus, res.StatusCode)
|
||||
assert.Equal(t, testCase.expectedCC, res.Header.Get("Cache-Control"))
|
||||
assert.Equal(t, testCase.expectedBody, string(body))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user