mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-30 20:20:43 +00:00
Compare commits
9 Commits
chore/dead
...
perf/chunk
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
faed0e0a84 | ||
|
|
fa58650fb1 | ||
|
|
a070019305 | ||
|
|
b2becedf1c | ||
|
|
69617a2d65 | ||
|
|
c7420f716e | ||
|
|
bddaef374f | ||
|
|
05a0beaf81 | ||
|
|
3fec9f4b83 |
@@ -135,6 +135,7 @@ func runGenerateAuthz(_ context.Context) error {
|
||||
coretypes.NewResourceRef(coretypes.ResourceMetaResourceIngestionLimit).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceMetaResourceAuthDomain).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceOrganization).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceMetaResourceRule).String(): true,
|
||||
}
|
||||
|
||||
allowedTypes := map[string]bool{}
|
||||
|
||||
@@ -674,11 +674,11 @@ components:
|
||||
nullable: true
|
||||
type: boolean
|
||||
text:
|
||||
description: Alertmanager template for the card body; defaults to the Alertmanager
|
||||
Teams default.
|
||||
description: Alertmanager template for the card body, rendered as Teams
|
||||
markdown; defaults to the SigNoz Teams default.
|
||||
type: string
|
||||
title:
|
||||
description: Alertmanager template for the card title; defaults to the Alertmanager
|
||||
description: Alertmanager template for the card title; defaults to the SigNoz
|
||||
Teams default.
|
||||
type: string
|
||||
webhookUrl:
|
||||
@@ -4152,7 +4152,7 @@ components:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/TelemetrytypesSource'
|
||||
description: The data source within the signal. Set to meter for Cost Meter
|
||||
metrics; leave empty for regular telemetry.
|
||||
metrics or audit for audit logs; leave empty for regular telemetry.
|
||||
stepInterval:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/Querybuildertypesv5Step'
|
||||
@@ -10663,7 +10663,7 @@ components:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/TelemetrytypesSource'
|
||||
description: The data source within the signal. Set to meter for Cost Meter
|
||||
metrics; leave empty for regular telemetry.
|
||||
metrics or audit for audit logs; leave empty for regular telemetry.
|
||||
stepInterval:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/Querybuildertypesv5Step'
|
||||
@@ -10784,7 +10784,7 @@ components:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/TelemetrytypesSource'
|
||||
description: The data source within the signal. Set to meter for Cost Meter
|
||||
metrics; leave empty for regular telemetry.
|
||||
metrics or audit for audit logs; leave empty for regular telemetry.
|
||||
stepInterval:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/Querybuildertypesv5Step'
|
||||
@@ -10905,7 +10905,7 @@ components:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/TelemetrytypesSource'
|
||||
description: The data source within the signal. Set to meter for Cost Meter
|
||||
metrics; leave empty for regular telemetry.
|
||||
metrics or audit for audit logs; leave empty for regular telemetry.
|
||||
stepInterval:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/Querybuildertypesv5Step'
|
||||
@@ -12398,8 +12398,9 @@ components:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/SavedviewtypesSource'
|
||||
description: 'The explorer page the view belongs to: traces, logs, metrics,
|
||||
meter or ai_observability. Builder queries inside spec must use the matching
|
||||
signal; meter views use signal metrics with source meter.'
|
||||
meter, ai_observability or audit. Builder queries inside spec must use
|
||||
the matching signal; meter views use signal metrics with source meter,
|
||||
and audit views use signal logs with source audit.'
|
||||
spec:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/SavedviewtypesSavedViewSpec'
|
||||
@@ -12431,7 +12432,7 @@ components:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/SavedviewtypesSource'
|
||||
description: 'The explorer page the view belongs to: traces, logs, metrics,
|
||||
meter or ai_observability.'
|
||||
meter, ai_observability or audit.'
|
||||
spec:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/SavedviewtypesSavedViewSpec'
|
||||
@@ -12500,6 +12501,7 @@ components:
|
||||
- metrics
|
||||
- meter
|
||||
- ai_observability
|
||||
- audit
|
||||
type: string
|
||||
SavedviewtypesUpdatableSavedView:
|
||||
properties:
|
||||
@@ -12511,8 +12513,8 @@ components:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/SavedviewtypesSource'
|
||||
description: 'The explorer page the view belongs to: traces, logs, metrics,
|
||||
meter or ai_observability. The machine name cannot be changed; it is identified
|
||||
by the id in the path.'
|
||||
meter, ai_observability or audit. The machine name cannot be changed;
|
||||
it is identified by the id in the path.'
|
||||
spec:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/SavedviewtypesSavedViewSpec'
|
||||
@@ -30238,14 +30240,14 @@ paths:
|
||||
operationId: ListSavedViews
|
||||
parameters:
|
||||
- description: 'Returns only the views of this explorer page: traces, logs,
|
||||
metrics, meter or ai_observability. Defaults to every source.'
|
||||
metrics, meter, ai_observability or audit. Defaults to every source.'
|
||||
in: query
|
||||
name: source
|
||||
schema:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/SavedviewtypesSource'
|
||||
description: 'Returns only the views of this explorer page: traces, logs,
|
||||
metrics, meter or ai_observability. Defaults to every source.'
|
||||
metrics, meter, ai_observability or audit. Defaults to every source.'
|
||||
- description: Returns only the view with this exact machine name.
|
||||
in: query
|
||||
name: name
|
||||
@@ -30312,6 +30314,44 @@ paths:
|
||||
content:
|
||||
application/json:
|
||||
examples:
|
||||
audit_list:
|
||||
description: A list panel over audit logs for dashboard mutations.
|
||||
Audit views are queried as logs with the builder spec source set
|
||||
to audit.
|
||||
summary: Audit logs list view
|
||||
value:
|
||||
name: dashboard-audit-events
|
||||
schemaVersion: v2
|
||||
source: audit
|
||||
spec:
|
||||
displayName: Dashboard audit events
|
||||
panelType: list
|
||||
queries:
|
||||
- spec:
|
||||
filter:
|
||||
expression: signoz.resource.kind = 'dashboard'
|
||||
limit: 100
|
||||
name: A
|
||||
order:
|
||||
- direction: desc
|
||||
key:
|
||||
name: timestamp
|
||||
- direction: desc
|
||||
key:
|
||||
name: id
|
||||
signal: logs
|
||||
source: audit
|
||||
type: builder_query
|
||||
requestType: raw
|
||||
selectedFields:
|
||||
- fieldContext: log
|
||||
fieldDataType: string
|
||||
name: event_name
|
||||
signal: logs
|
||||
- fieldContext: resource
|
||||
fieldDataType: string
|
||||
name: signoz.resource.kind
|
||||
signal: logs
|
||||
logs_list_generated_name:
|
||||
description: A list panel over error logs of one service. generateName
|
||||
lets the server derive the machine name from displayName; the display
|
||||
|
||||
@@ -90,7 +90,7 @@ const config: StorybookConfig = {
|
||||
build: {
|
||||
...viteConfig.build,
|
||||
// `vite.config.ts` sets this for the app; Storybook's builder replaces
|
||||
// `build` wholesale, which leaves rolldown-vite on its default
|
||||
// `build` wholesale, which leaves Vite on its default
|
||||
// lightningcss. That one rejects `:global()` in a plain stylesheet, which
|
||||
// the app has, and the static build dies in CSS minification.
|
||||
cssMinify: 'esbuild',
|
||||
|
||||
@@ -15,8 +15,6 @@
|
||||
content="frame-src 'self' blob: data:"
|
||||
/>
|
||||
|
||||
<link rel="stylesheet" href="css/uPlot.min.css" />
|
||||
|
||||
<script>
|
||||
// i18n's language detector would pick the browser locale (e.g. `en-US`), which
|
||||
// /public/locales does not ship; pin it to the bundled language instead.
|
||||
|
||||
@@ -22,6 +22,7 @@ import i18n from '../src/ReactI18';
|
||||
// to its loader default and pulls Monaco from cdn.jsdelivr.net, which msw does
|
||||
// not report because the requests look like static assets.
|
||||
import '../src/lib/monaco/loader';
|
||||
import '../src/lib/uPlotStylesheet';
|
||||
|
||||
import '../src/styles.scss';
|
||||
|
||||
|
||||
46
frontend/boot-guard/bootGuard.css
Normal file
46
frontend/boot-guard/bootGuard.css
Normal file
@@ -0,0 +1,46 @@
|
||||
#signoz-boot-error {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
z-index: 2147483647;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
box-sizing: border-box;
|
||||
text-align: center;
|
||||
font:
|
||||
16px/1.5 system-ui,
|
||||
sans-serif;
|
||||
background: #0b0c0e;
|
||||
color: #e6e6e6;
|
||||
}
|
||||
|
||||
body.lightMode #signoz-boot-error {
|
||||
background: #fff;
|
||||
color: #1a1a1a;
|
||||
}
|
||||
|
||||
#signoz-boot-error h1 {
|
||||
margin: 0 0 8px;
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
#signoz-boot-error p {
|
||||
margin: 0 0 16px;
|
||||
max-width: 520px;
|
||||
}
|
||||
|
||||
#signoz-boot-error button {
|
||||
padding: 8px 20px;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
border: 1px solid currentColor;
|
||||
border-radius: 4px;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
}
|
||||
79
frontend/boot-guard/bootGuard.js
Normal file
79
frontend/boot-guard/bootGuard.js
Normal file
@@ -0,0 +1,79 @@
|
||||
// Inlined into index.html by vite-plugins/inlineBootGuard.ts, not bundled or
|
||||
// transpiled. Keep to ES2015, so a browser too old for the app can still show
|
||||
// the message.
|
||||
(function () {
|
||||
const MESSAGES = {
|
||||
unsupported: {
|
||||
title: 'Your browser is not supported',
|
||||
text:
|
||||
'SigNoz needs a newer browser. Update Chrome, Edge, Firefox or Safari, then reload this page.',
|
||||
},
|
||||
load: {
|
||||
title: 'SigNoz failed to load',
|
||||
text:
|
||||
'Part of the app could not be downloaded. Check your connection and reload the page. If it keeps happening, contact your administrator.',
|
||||
},
|
||||
};
|
||||
|
||||
function createElement(tag, text) {
|
||||
const element = document.createElement(tag);
|
||||
element.textContent = text;
|
||||
return element;
|
||||
}
|
||||
|
||||
function render(kind) {
|
||||
if (document.getElementById('signoz-boot-error')) {
|
||||
return;
|
||||
}
|
||||
const message = MESSAGES[kind];
|
||||
const box = document.createElement('div');
|
||||
box.id = 'signoz-boot-error';
|
||||
box.setAttribute('role', 'alert');
|
||||
box.setAttribute('data-testid', 'boot-error');
|
||||
box.appendChild(createElement('h1', message.title));
|
||||
box.appendChild(createElement('p', message.text));
|
||||
if (kind === 'load') {
|
||||
const reload = createElement('button', 'Reload');
|
||||
reload.type = 'button';
|
||||
reload.setAttribute('data-testid', 'boot-error-reload');
|
||||
reload.onclick = function () {
|
||||
window.location.reload();
|
||||
};
|
||||
box.appendChild(reload);
|
||||
}
|
||||
document.body.appendChild(box);
|
||||
}
|
||||
|
||||
function renderWhenReady(kind) {
|
||||
if (document.body) {
|
||||
render(kind);
|
||||
} else {
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
render(kind);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const supportsImportMap = !!(
|
||||
window.HTMLScriptElement &&
|
||||
HTMLScriptElement.supports &&
|
||||
HTMLScriptElement.supports('importmap')
|
||||
);
|
||||
|
||||
if (!supportsImportMap) {
|
||||
renderWhenReady('unsupported');
|
||||
}
|
||||
|
||||
// A module script fires `error` when any file of its static import graph
|
||||
// fails to download. Without import maps, every chunk key is a 404.
|
||||
window.addEventListener(
|
||||
'error',
|
||||
function (event) {
|
||||
const target = event.target;
|
||||
if (target && target.tagName === 'SCRIPT' && target.type === 'module') {
|
||||
renderWhenReady(supportsImportMap ? 'load' : 'unsupported');
|
||||
}
|
||||
},
|
||||
true,
|
||||
);
|
||||
})();
|
||||
@@ -157,7 +157,6 @@
|
||||
})(document, 'script');
|
||||
}
|
||||
</script>
|
||||
<link rel="stylesheet" href="css/uPlot.min.css" />
|
||||
<script type="module" src="./src/index.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -42,7 +42,10 @@ const config: Config.InitialOptions = {
|
||||
'<rootDir>/node_modules/@signozhq/$1/dist/$1.js',
|
||||
},
|
||||
extensionsToTreatAsEsm: ['.ts'],
|
||||
testMatch: ['<rootDir>/src/**/*?(*.)(test).(ts|js)?(x)'],
|
||||
testMatch: [
|
||||
'<rootDir>/src/**/*?(*.)(test).(ts|js)?(x)',
|
||||
'<rootDir>/vite-plugins/**/*.test.ts',
|
||||
],
|
||||
preset: 'ts-jest/presets/js-with-ts-esm',
|
||||
transform: {
|
||||
'^.+\\.(ts|tsx)?$': [
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
"build:geo-outlines": "node scripts/geo-outlines/build.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.0.0",
|
||||
"node": ">=22.12.0",
|
||||
"pnpm": ">=10.0.0 <11.0.0"
|
||||
},
|
||||
"author": "",
|
||||
@@ -67,7 +67,7 @@
|
||||
"@visx/hierarchy": "3.12.0",
|
||||
"@visx/shape": "3.5.0",
|
||||
"@visx/tooltip": "3.3.0",
|
||||
"@vitejs/plugin-react": "5.1.4",
|
||||
"@vitejs/plugin-react": "6.3.0",
|
||||
"ansi-to-html": "0.7.2",
|
||||
"antd": "5.11.0",
|
||||
"antd-table-saveas-excel": "2.2.1",
|
||||
@@ -137,7 +137,7 @@
|
||||
"typescript": "5.9.3",
|
||||
"uplot": "1.6.31",
|
||||
"uuid": "14.0.1",
|
||||
"vite": "npm:rolldown-vite@7.3.1",
|
||||
"vite": "8.3.8",
|
||||
"zod": "4.6.7",
|
||||
"zustand": "5.0.11"
|
||||
},
|
||||
@@ -194,6 +194,7 @@
|
||||
"@types/topojson-client": "3.1.5",
|
||||
"@types/topojson-specification": "1.0.5",
|
||||
"@typescript/native-preview": "7.0.0-dev.20260430.1",
|
||||
"esbuild": "0.28.1",
|
||||
"eslint-plugin-sonarjs": "4.0.2",
|
||||
"husky": "^9.1.7",
|
||||
"jest-environment-jsdom": "29.7.0",
|
||||
@@ -221,8 +222,7 @@
|
||||
"use-sync-external-store": "1.6.0",
|
||||
"vite-plugin-checker": "0.12.0",
|
||||
"vite-plugin-compression": "0.5.1",
|
||||
"vite-plugin-image-optimizer": "2.0.3",
|
||||
"vite-tsconfig-paths": "6.1.1"
|
||||
"vite-plugin-image-optimizer": "2.0.3"
|
||||
},
|
||||
"lint-staged": {
|
||||
"*.(js|jsx|ts|tsx)": [
|
||||
|
||||
597
frontend/pnpm-lock.yaml
generated
597
frontend/pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -40,9 +40,9 @@ overrides:
|
||||
# remove: blocked. The direct dep is already on 3.4.17, but @grafana/data
|
||||
# (latest 13.1.0) and monaco-editor (latest 0.55.1) still pin vulnerable versions
|
||||
dompurify@<=3.4.16: '>=3.4.17 <4'
|
||||
# via: rolldown-vite@7.3.1 (esbuild ^0.27.0); ts-jest@29.4.9 (~0.27.4)
|
||||
# remove: blocked on rolldown-vite (7.3.1 is latest, still ^0.27.0);
|
||||
# orval >=8.20.0 and ts-jest >=29.4.11 already fixed on their side
|
||||
# via: ts-jest@29.4.9 (~0.27.4)
|
||||
# remove: blocked on ts-jest; orval >=8.20.0 and ts-jest >=29.4.11 already
|
||||
# fixed on their side
|
||||
esbuild@>=0.27.3 <0.28.1: '>=0.28.1 <0.29.0'
|
||||
# via: @commitlint/cli > @commitlint/config-validator > ajv@8 (fast-uri ^3.0.1)
|
||||
# remove: blocked — ajv@8 caps fast-uri at ^3, and only 3.1.9 carries the fix
|
||||
|
||||
1
frontend/public/css/uPlot.min.css
vendored
1
frontend/public/css/uPlot.min.css
vendored
@@ -1 +0,0 @@
|
||||
.uplot, .uplot *, .uplot *::before, .uplot *::after {box-sizing: border-box;}.uplot {font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";line-height: 1.5;width: min-content;}.u-title {text-align: center;font-size: 18px;font-weight: bold;}.u-wrap {position: relative;user-select: none;}.u-over, .u-under {position: absolute;}.u-under {overflow: hidden;}.uplot canvas {display: block;position: relative;width: 100%;height: 100%;}.u-axis {position: absolute;}.u-legend {font-size: 14px;margin: auto;text-align: center;}.u-inline {display: block;}.u-inline * {display: inline-block;}.u-inline tr {margin-right: 16px;}.u-legend th {font-weight: 600;}.u-legend th > * {vertical-align: middle;display: inline-block;}.u-legend .u-marker {width: 1em;height: 1em;margin-right: 4px;background-clip: padding-box !important;}.u-inline.u-live th::after {content: ":";vertical-align: middle;}.u-inline:not(.u-live) .u-value {display: none;}.u-series > * {padding: 4px;}.u-series th {cursor: pointer;}.u-legend .u-off > * {opacity: 0.3;}.u-select {background: rgba(0,0,0,0.07);position: absolute;pointer-events: none;}.u-cursor-x, .u-cursor-y {position: absolute;left: 0;top: 0;pointer-events: none;will-change: transform;}.u-hz .u-cursor-x, .u-vt .u-cursor-y {height: 100%;border-right: 1px dashed #607D8B;}.u-hz .u-cursor-y, .u-vt .u-cursor-x {width: 100%;border-bottom: 1px dashed #607D8B;}.u-cursor-pt {position: absolute;top: 0;left: 0;border-radius: 50%;border: 0 solid;pointer-events: none;will-change: transform;/*this has to be !important since we set inline "background" shorthand */background-clip: padding-box !important;}.u-axis.u-off, .u-select.u-off, .u-cursor-x.u-off, .u-cursor-y.u-off, .u-cursor-pt.u-off {display: none;}
|
||||
@@ -751,12 +751,12 @@ export interface AlertmanagertypesChannelMSTeamsConfigDTO {
|
||||
sendResolved?: boolean | null;
|
||||
/**
|
||||
* @type string
|
||||
* @description Alertmanager template for the card body; defaults to the Alertmanager Teams default.
|
||||
* @description Alertmanager template for the card body, rendered as Teams markdown; defaults to the SigNoz Teams default.
|
||||
*/
|
||||
text?: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description Alertmanager template for the card title; defaults to the Alertmanager Teams default.
|
||||
* @description Alertmanager template for the card title; defaults to the SigNoz Teams default.
|
||||
*/
|
||||
title?: string;
|
||||
/**
|
||||
@@ -5372,7 +5372,7 @@ export interface DashboardtypesAIBuilderQuerySpecDTO {
|
||||
*/
|
||||
signal: DashboardtypesAIBuilderQuerySpecDTOSignal;
|
||||
/**
|
||||
* @description The data source within the signal. Set to meter for Cost Meter metrics; leave empty for regular telemetry.
|
||||
* @description The data source within the signal. Set to meter for Cost Meter metrics or audit for audit logs; leave empty for regular telemetry.
|
||||
*/
|
||||
source?: TelemetrytypesSourceDTO;
|
||||
/**
|
||||
@@ -5771,7 +5771,7 @@ export interface Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTyp
|
||||
*/
|
||||
signal: Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5LogAggregationDTOSignal;
|
||||
/**
|
||||
* @description The data source within the signal. Set to meter for Cost Meter metrics; leave empty for regular telemetry.
|
||||
* @description The data source within the signal. Set to meter for Cost Meter metrics or audit for audit logs; leave empty for regular telemetry.
|
||||
*/
|
||||
source?: TelemetrytypesSourceDTO;
|
||||
/**
|
||||
@@ -5951,7 +5951,7 @@ export interface Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTyp
|
||||
*/
|
||||
signal: Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTOSignal;
|
||||
/**
|
||||
* @description The data source within the signal. Set to meter for Cost Meter metrics; leave empty for regular telemetry.
|
||||
* @description The data source within the signal. Set to meter for Cost Meter metrics or audit for audit logs; leave empty for regular telemetry.
|
||||
*/
|
||||
source?: TelemetrytypesSourceDTO;
|
||||
/**
|
||||
@@ -6050,7 +6050,7 @@ export interface Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTyp
|
||||
*/
|
||||
signal: Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregationDTOSignal;
|
||||
/**
|
||||
* @description The data source within the signal. Set to meter for Cost Meter metrics; leave empty for regular telemetry.
|
||||
* @description The data source within the signal. Set to meter for Cost Meter metrics or audit for audit logs; leave empty for regular telemetry.
|
||||
*/
|
||||
source?: TelemetrytypesSourceDTO;
|
||||
/**
|
||||
@@ -13504,6 +13504,7 @@ export enum SavedviewtypesSourceDTO {
|
||||
metrics = 'metrics',
|
||||
meter = 'meter',
|
||||
ai_observability = 'ai_observability',
|
||||
audit = 'audit',
|
||||
}
|
||||
export interface SavedviewtypesSavedViewSpecDTO {
|
||||
/**
|
||||
@@ -13551,7 +13552,7 @@ export interface SavedviewtypesPostableSavedViewDTO {
|
||||
*/
|
||||
schemaVersion: SavedviewtypesSchemaVersionDTO;
|
||||
/**
|
||||
* @description The explorer page the view belongs to: traces, logs, metrics, meter or ai_observability. Builder queries inside spec must use the matching signal; meter views use signal metrics with source meter.
|
||||
* @description The explorer page the view belongs to: traces, logs, metrics, meter, ai_observability or audit. Builder queries inside spec must use the matching signal; meter views use signal metrics with source meter, and audit views use signal logs with source audit.
|
||||
*/
|
||||
source: SavedviewtypesSourceDTO;
|
||||
/**
|
||||
@@ -13584,7 +13585,7 @@ export interface SavedviewtypesSavedViewDTO {
|
||||
*/
|
||||
schemaVersion: SavedviewtypesSchemaVersionDTO;
|
||||
/**
|
||||
* @description The explorer page the view belongs to: traces, logs, metrics, meter or ai_observability.
|
||||
* @description The explorer page the view belongs to: traces, logs, metrics, meter, ai_observability or audit.
|
||||
*/
|
||||
source?: SavedviewtypesSourceDTO;
|
||||
/**
|
||||
@@ -13608,7 +13609,7 @@ export interface SavedviewtypesUpdatableSavedViewDTO {
|
||||
*/
|
||||
schemaVersion: SavedviewtypesSchemaVersionDTO;
|
||||
/**
|
||||
* @description The explorer page the view belongs to: traces, logs, metrics, meter or ai_observability. The machine name cannot be changed; it is identified by the id in the path.
|
||||
* @description The explorer page the view belongs to: traces, logs, metrics, meter, ai_observability or audit. The machine name cannot be changed; it is identified by the id in the path.
|
||||
*/
|
||||
source: SavedviewtypesSourceDTO;
|
||||
/**
|
||||
@@ -17398,7 +17399,7 @@ export type TestRule200 = {
|
||||
|
||||
export type ListSavedViewsParams = {
|
||||
/**
|
||||
* @description Returns only the views of this explorer page: traces, logs, metrics, meter or ai_observability. Defaults to every source.
|
||||
* @description Returns only the views of this explorer page: traces, logs, metrics, meter, ai_observability or audit. Defaults to every source.
|
||||
*/
|
||||
source?: SavedviewtypesSourceDTO;
|
||||
/**
|
||||
|
||||
@@ -14,7 +14,6 @@ import uPlot from 'uplot';
|
||||
|
||||
import tooltipPlugin from './tooltipPlugin';
|
||||
|
||||
import 'uplot/dist/uPlot.min.css';
|
||||
import './AnomalyAlertEvaluationView.styles.scss';
|
||||
|
||||
const { Search } = Input;
|
||||
|
||||
@@ -51,7 +51,7 @@
|
||||
flex: 1;
|
||||
min-width: 0; // allow shrinking below natural width when AI panel is open
|
||||
z-index: 0;
|
||||
background: var(--l1-background);
|
||||
background: var(--surface-1);
|
||||
|
||||
// Column so the bottom strip sits under the scrolling content, not inside it.
|
||||
display: flex;
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
.create-alert-v2-container {
|
||||
background-color: var(--l1-background);
|
||||
padding-bottom: 100px;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
AlertmanagertypesChannelIncidentIOConfigDTO,
|
||||
AlertmanagertypesChannelJiraConfigDTO,
|
||||
AlertmanagertypesChannelJSMOpsConfigDTO,
|
||||
AlertmanagertypesChannelMSTeamsConfigDTO,
|
||||
AlertmanagertypesChannelOpsgenieConfigDTO,
|
||||
AlertmanagertypesChannelPagerdutyConfigDTO,
|
||||
AlertmanagertypesChannelSlackConfigDTO,
|
||||
@@ -12,7 +13,6 @@ import {
|
||||
|
||||
import { ChannelKind, ChannelSpecFormValues, JiraDeployment } from './types';
|
||||
|
||||
// shared by slack and ms teams, both render the same title / description boxes
|
||||
export const SlackInitialConfig: Partial<AlertmanagertypesChannelSlackConfigDTO> =
|
||||
{
|
||||
text: `{{ range .Alerts -}}
|
||||
@@ -39,6 +39,26 @@ export const SlackInitialConfig: Partial<AlertmanagertypesChannelSlackConfigDTO>
|
||||
{{- end }}`,
|
||||
};
|
||||
|
||||
// mirrors DefaultMSTeamsTitleTemplate / DefaultMSTeamsTextTemplate in
|
||||
// pkg/types/alertmanagertypes/channel_msteams.go, which the backend applies
|
||||
// when title / text are left empty
|
||||
export const MsTeamsInitialConfig: Partial<AlertmanagertypesChannelMSTeamsConfigDTO> =
|
||||
{
|
||||
title: `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}`,
|
||||
text: `{{ range .Alerts -}}
|
||||
**Alert:** {{ .Labels.alertname }}{{ if .Labels.severity }} ({{ .Labels.severity }}){{ end }} - {{ .Status }}
|
||||
|
||||
{{ if .Annotations.summary }}**Summary:** {{ .Annotations.summary }}
|
||||
|
||||
{{ end }}{{ if .Annotations.description }}**Description:** {{ .Annotations.description }}
|
||||
|
||||
{{ end }}{{ template "signoz.relatedLinks.markdown" . }}{{ with (.Labels.Remove (stringSlice "alertname" "severity" "ruleId" "ruleSource")).SortedPairs }}**Details:**
|
||||
|
||||
{{ range . }}- **{{ .Name }}:** {{ .Value }}
|
||||
{{ end }}
|
||||
{{ end }}{{ end }}`,
|
||||
};
|
||||
|
||||
// mirrors DefaultGoogleChatReceiverConfig in pkg/types/alertmanagertypes/googlechat.go,
|
||||
// which the backend applies when title / text are left empty
|
||||
export const GoogleChatInitialConfig: Partial<AlertmanagertypesChannelGoogleChatConfigDTO> =
|
||||
@@ -577,7 +597,7 @@ export const DEFAULT_CHANNEL_KIND = ChannelKind.slack;
|
||||
export const ChannelInitialConfig: Record<ChannelKind, ChannelSpecFormValues> =
|
||||
{
|
||||
[ChannelKind.slack]: SlackInitialConfig,
|
||||
[ChannelKind.msteams]: SlackInitialConfig,
|
||||
[ChannelKind.msteams]: MsTeamsInitialConfig,
|
||||
[ChannelKind.googlechat]: GoogleChatInitialConfig,
|
||||
[ChannelKind.jira]: JiraInitialConfig,
|
||||
[ChannelKind.jsmops]: JsmOpsInitialConfig,
|
||||
|
||||
@@ -5,8 +5,6 @@
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
|
||||
background: color-mix(in srgb, var(--l1-background) 90%, transparent);
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 0.3rem;
|
||||
height: 0.3rem;
|
||||
|
||||
@@ -65,7 +65,6 @@
|
||||
|
||||
.trace-explorer-page {
|
||||
.trace-explorer {
|
||||
background: var(--l1-background);
|
||||
border-color: var(--l1-border);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
|
||||
.jsonEditorError {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: var(--spacing-2);
|
||||
padding: var(--spacing-4) var(--spacing-6);
|
||||
|
||||
@@ -329,8 +329,9 @@ describe('transformTransactionGroupsToResourcePermissions', () => {
|
||||
it('returns all resources from RESOURCE_ORDER even with empty transaction groups', () => {
|
||||
const result = transformTransactionGroupsToResourcePermissions([]);
|
||||
|
||||
expect(result).toHaveLength(19);
|
||||
expect(result).toHaveLength(20);
|
||||
expect(result.map((r) => r.resourceKind)).toStrictEqual([
|
||||
'rule',
|
||||
'factor-api-key',
|
||||
'auth-domain',
|
||||
'dashboard',
|
||||
@@ -430,8 +431,9 @@ describe('createEmptyRolePermissions', () => {
|
||||
it('creates permissions for all resources in RESOURCE_ORDER', () => {
|
||||
const result = createEmptyRolePermissions();
|
||||
|
||||
expect(result).toHaveLength(19);
|
||||
expect(result).toHaveLength(20);
|
||||
expect(result.map((r) => r.resourceKind)).toStrictEqual([
|
||||
'rule',
|
||||
'factor-api-key',
|
||||
'auth-domain',
|
||||
'dashboard',
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
BellDot,
|
||||
Bot,
|
||||
Building,
|
||||
Cable,
|
||||
@@ -116,6 +117,15 @@ export const RESOURCE_PANELS: Record<AuthZResource, ResourcePanelConfig> = {
|
||||
'Type notification channel ID, separate multiple with comma or space',
|
||||
docsAnchor: 'notification-channel',
|
||||
},
|
||||
rule: {
|
||||
label: 'Alert Rules',
|
||||
description:
|
||||
'Alert rules, the conditions they evaluate and the channels they notify.',
|
||||
icon: BellDot,
|
||||
selectorPlaceholder:
|
||||
'Type alert rule ID, separate multiple with comma or space',
|
||||
docsAnchor: 'rule',
|
||||
},
|
||||
logs: {
|
||||
label: 'Logs',
|
||||
description: 'Log data collected across the workspace.',
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
max-width: 54px;
|
||||
min-width: 54px;
|
||||
width: 54px;
|
||||
border-right: 1px solid var(--l1-border);
|
||||
background: var(--l2-background);
|
||||
border-right: 1px solid var(--l2-border);
|
||||
background: var(--surface-1);
|
||||
|
||||
padding-bottom: 48px;
|
||||
transition:
|
||||
@@ -466,7 +466,7 @@
|
||||
background: linear-gradient(
|
||||
180deg,
|
||||
transparent 0%,
|
||||
var(--l2-background) 27.11%
|
||||
var(--surface-1) 27.11%
|
||||
);
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
@@ -631,7 +631,7 @@
|
||||
position: absolute;
|
||||
height: 100%;
|
||||
z-index: 10;
|
||||
background: var(--l1-background);
|
||||
box-shadow: var(--shadow-sidebar);
|
||||
|
||||
.brand-container {
|
||||
padding: 8px 15px;
|
||||
@@ -813,6 +813,7 @@
|
||||
position: absolute;
|
||||
height: 100%;
|
||||
z-index: 10;
|
||||
box-shadow: none;
|
||||
|
||||
.brand-container {
|
||||
padding: 8px 15px;
|
||||
|
||||
@@ -18,6 +18,7 @@ import 'lib/monaco/loader';
|
||||
import './ReactI18';
|
||||
|
||||
import 'styles.scss';
|
||||
import 'lib/uPlotStylesheet';
|
||||
|
||||
installTranslationResilience();
|
||||
configureOverlayScrollbars();
|
||||
|
||||
@@ -1,2 +1,4 @@
|
||||
export const SINGLE_FLIGHT_WAIT_TIME_MS = 50;
|
||||
export const AUTHZ_CACHE_TIME = 20_000;
|
||||
// OpenFGA's default max_checks_per_batch_check; a larger request fails whole.
|
||||
export const AUTHZ_MAX_CHECKS_PER_REQUEST = 50;
|
||||
|
||||
@@ -72,6 +72,19 @@ export default {
|
||||
type: 'metaresource',
|
||||
allowedVerbs: ['list', 'read', 'update'],
|
||||
},
|
||||
{
|
||||
kind: 'rule',
|
||||
type: 'metaresource',
|
||||
allowedVerbs: [
|
||||
'attach',
|
||||
'create',
|
||||
'delete',
|
||||
'detach',
|
||||
'list',
|
||||
'read',
|
||||
'update',
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: 'saved-view',
|
||||
type: 'metaresource',
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { buildPermission } from '../utils';
|
||||
import type { BrandedPermission } from '../types';
|
||||
|
||||
// Collection-level. Wildcard selector required for correct response key matching.
|
||||
// `list` also covers rule views, which the backend gates on it.
|
||||
export const RuleListPermission = buildPermission('list', 'rule:*');
|
||||
export const RuleCreatePermission = buildPermission('create', 'rule:*');
|
||||
|
||||
// Resource-level. Requires a specific rule id.
|
||||
export const buildRuleReadPermission = (id: string): BrandedPermission =>
|
||||
buildPermission('read', `rule:${id}`);
|
||||
export const buildRuleUpdatePermission = (id: string): BrandedPermission =>
|
||||
buildPermission('update', `rule:${id}`);
|
||||
export const buildRuleDeletePermission = (id: string): BrandedPermission =>
|
||||
buildPermission('delete', `rule:${id}`);
|
||||
export const buildRuleAttachPermission = (id: string): BrandedPermission =>
|
||||
buildPermission('attach', `rule:${id}`);
|
||||
export const buildRuleDetachPermission = (id: string): BrandedPermission =>
|
||||
buildPermission('detach', `rule:${id}`);
|
||||
@@ -392,6 +392,40 @@ describe('useAuthZ', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('should split a single flight into requests the backend accepts', async () => {
|
||||
const permissions = Array.from({ length: 120 }, (_, i) =>
|
||||
buildPermission('read', `role:${i}`),
|
||||
);
|
||||
const payloadSizes: number[] = [];
|
||||
|
||||
server.use(
|
||||
rest.post(AUTHZ_CHECK_URL, async (req, res, ctx) => {
|
||||
const payload = await req.json();
|
||||
payloadSizes.push(payload.length);
|
||||
if (payload.length > 50) {
|
||||
return res(ctx.status(400));
|
||||
}
|
||||
return res(
|
||||
ctx.status(200),
|
||||
ctx.json(
|
||||
authzMockResponse(
|
||||
payload,
|
||||
payload.map(() => true),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useAuthZ(permissions), { wrapper });
|
||||
|
||||
await waitFor(() => expect(result.current.isLoading).toBe(false));
|
||||
|
||||
expect(result.current.error).toBeNull();
|
||||
expect(result.current.allowed).toBe(true);
|
||||
expect(payloadSizes.sort((a, b) => b - a)).toStrictEqual([50, 50, 20]);
|
||||
});
|
||||
|
||||
it('should create separate batches for calls after single flight window', async () => {
|
||||
const permission1 = buildPermission('read', 'role:*');
|
||||
const permission2 = buildPermission('update', 'role:123');
|
||||
|
||||
@@ -8,7 +8,11 @@ import type {
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { IS_DEV, MODE } from 'lib/env';
|
||||
|
||||
import { AUTHZ_CACHE_TIME, SINGLE_FLIGHT_WAIT_TIME_MS } from './constants';
|
||||
import {
|
||||
AUTHZ_CACHE_TIME,
|
||||
AUTHZ_MAX_CHECKS_PER_REQUEST,
|
||||
SINGLE_FLIGHT_WAIT_TIME_MS,
|
||||
} from './constants';
|
||||
import type {
|
||||
AuthZCheckResponse,
|
||||
BrandedPermission,
|
||||
@@ -105,6 +109,18 @@ function dispatchPermission(
|
||||
|
||||
async function fetchManyPermissions(
|
||||
permissions: BrandedPermission[],
|
||||
): Promise<AuthZCheckResponse> {
|
||||
const chunks: BrandedPermission[][] = [];
|
||||
for (let i = 0; i < permissions.length; i += AUTHZ_MAX_CHECKS_PER_REQUEST) {
|
||||
chunks.push(permissions.slice(i, i + AUTHZ_MAX_CHECKS_PER_REQUEST));
|
||||
}
|
||||
|
||||
const responses = await Promise.all(chunks.map(fetchPermissionChunk));
|
||||
return Object.assign({}, ...responses);
|
||||
}
|
||||
|
||||
async function fetchPermissionChunk(
|
||||
permissions: BrandedPermission[],
|
||||
): Promise<AuthZCheckResponse> {
|
||||
const payload: AuthtypesTransactionDTO[] = permissions.map((permission) => {
|
||||
const dto = permissionToTransactionDto(permission);
|
||||
|
||||
31
frontend/src/lib/monaco/__tests__/workerBundle.test.ts
Normal file
31
frontend/src/lib/monaco/__tests__/workerBundle.test.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { execFileSync } from 'child_process';
|
||||
import { resolve } from 'path';
|
||||
|
||||
const READ_WORKER_FORMAT = `
|
||||
(async () => {
|
||||
const { resolveConfig } = await import('vite');
|
||||
const config = await resolveConfig(
|
||||
{ configFile: process.argv[1], mode: 'production' },
|
||||
'build',
|
||||
);
|
||||
process.stdout.write(JSON.stringify(config.worker.format));
|
||||
})();
|
||||
`;
|
||||
|
||||
describe('Monaco worker bundle', () => {
|
||||
// An iife worker runs as a sloppy script: the minifier renames on the
|
||||
// assumption of strict mode, and Annex B hoisting then lets the JSON worker's
|
||||
// block-level `hasDuplicates` replace the schema collector, so validating any
|
||||
// non-empty array threw `Cannot read properties of undefined (reading 'include')`.
|
||||
it('ships workers as ES modules, which always run in strict mode', () => {
|
||||
const output = execFileSync(
|
||||
process.execPath,
|
||||
['--eval', READ_WORKER_FORMAT, resolve(process.cwd(), 'vite.config.ts')],
|
||||
{ cwd: process.cwd(), encoding: 'utf8' },
|
||||
);
|
||||
|
||||
const format: unknown = JSON.parse(output);
|
||||
|
||||
expect(format).toBe('es');
|
||||
}, 60_000);
|
||||
});
|
||||
7
frontend/src/lib/uPlotStylesheet.ts
Normal file
7
frontend/src/lib/uPlotStylesheet.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import href from 'uplot/dist/uPlot.min.css?url';
|
||||
|
||||
// Appended to the end of <body> so uPlot's rules win ties over the app's stylesheets.
|
||||
const link = document.createElement('link');
|
||||
link.rel = 'stylesheet';
|
||||
link.href = href;
|
||||
document.body.appendChild(link);
|
||||
@@ -4,7 +4,6 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
background: var(--l1-background);
|
||||
@include selection;
|
||||
}
|
||||
|
||||
@@ -15,7 +14,6 @@
|
||||
padding: 12px;
|
||||
border-bottom: 1px solid var(--l1-border);
|
||||
flex-shrink: 0;
|
||||
background: var(--l1-background);
|
||||
}
|
||||
|
||||
.title {
|
||||
|
||||
@@ -706,6 +706,71 @@ describe('ChannelForm save', () => {
|
||||
TEST_TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
'prefills microsoft teams with its own templates instead of the slack ones',
|
||||
async () => {
|
||||
let body: Record<string, unknown> | undefined;
|
||||
server.use(
|
||||
rest.post(
|
||||
'http://localhost/api/v2/notification_channels',
|
||||
async (req, res, ctx) => {
|
||||
body = await req.json();
|
||||
return res(ctx.status(201), ctx.json({ status: 'success', data: {} }));
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
render(<ChannelForm onDone={jest.fn()} />);
|
||||
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
await pickChannelType(user, ChannelKind.msteams);
|
||||
|
||||
const teamsTitle =
|
||||
'[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}';
|
||||
expect(screen.getByTestId('title-textarea')).toHaveValue(teamsTitle);
|
||||
const description = screen.getByTestId(
|
||||
'description-textarea',
|
||||
) as HTMLTextAreaElement;
|
||||
expect(description.value).toContain(
|
||||
'**Alert:** {{ .Labels.alertname }}{{ if .Labels.severity }} ({{ .Labels.severity }}){{ end }} - {{ .Status }}',
|
||||
);
|
||||
expect(description.value).toContain(
|
||||
'{{ template "signoz.relatedLinks.markdown" . }}',
|
||||
);
|
||||
expect(description.value).not.toContain('*Alert:* ');
|
||||
expect(description.value).not.toContain('signoz.relatedLinks.slack');
|
||||
|
||||
await user.type(
|
||||
screen.getByTestId('channel-name-textbox-field'),
|
||||
'teams alerts',
|
||||
);
|
||||
await user.type(
|
||||
screen.getByTestId('webhook-url-textbox-field'),
|
||||
'https://teams.example.com/workflows/hook',
|
||||
);
|
||||
|
||||
const save = screen.getByTestId('save-channel-button');
|
||||
await waitFor(
|
||||
() => expect(save).toHaveAttribute('aria-disabled', 'false'),
|
||||
FIND,
|
||||
);
|
||||
await user.click(save);
|
||||
|
||||
await waitFor(() => expect(body).toBeDefined(), FIND);
|
||||
expect(body).toMatchObject({
|
||||
config: {
|
||||
kind: 'msteams',
|
||||
spec: {
|
||||
webhookUrl: 'https://teams.example.com/workflows/hook',
|
||||
title: teamsTitle,
|
||||
text: description.value,
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
TEST_TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
'leaves the pagerduty client url empty so the backend links to this instance',
|
||||
async () => {
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
background: var(--l1-background);
|
||||
}
|
||||
|
||||
.right {
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
background: var(--l0-background);
|
||||
}
|
||||
|
||||
.header {
|
||||
|
||||
@@ -40,7 +40,6 @@
|
||||
|
||||
.trace-explorer-page {
|
||||
.trace-explorer {
|
||||
background: var(--l1-background);
|
||||
border-color: var(--l1-border);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ body {
|
||||
text-rendering: optimizeLegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
background: var(--l1-background) !important;
|
||||
background: var(--surface-1) !important;
|
||||
color: var(--l1-foreground) !important;
|
||||
|
||||
// compatibility changes, to reduce amount of drift
|
||||
|
||||
@@ -83,6 +83,7 @@
|
||||
"./jest.config.ts",
|
||||
"./jest.setup.ts",
|
||||
"./vite.config.ts",
|
||||
"./vite-plugins",
|
||||
"./commitlint.config.ts"
|
||||
]
|
||||
}
|
||||
|
||||
84
frontend/vite-plugins/__tests__/bootGuard.test.ts
Normal file
84
frontend/vite-plugins/__tests__/bootGuard.test.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
import { readFileSync } from 'fs';
|
||||
import { resolve } from 'path';
|
||||
import { screen } from '@testing-library/react';
|
||||
|
||||
const guard = readFileSync(
|
||||
resolve(__dirname, '../../boot-guard/bootGuard.js'),
|
||||
'utf8',
|
||||
);
|
||||
|
||||
function runGuard(supportsImportMap: boolean): void {
|
||||
document.head.innerHTML = '';
|
||||
document.body.innerHTML = '';
|
||||
Object.assign(HTMLScriptElement, {
|
||||
supports: (type: string) => supportsImportMap && type === 'importmap',
|
||||
});
|
||||
|
||||
const script = document.createElement('script');
|
||||
script.textContent = guard;
|
||||
document.body.appendChild(script);
|
||||
}
|
||||
|
||||
function addScript(type: string): HTMLScriptElement {
|
||||
const script = document.createElement('script');
|
||||
script.type = type;
|
||||
document.head.appendChild(script);
|
||||
return script;
|
||||
}
|
||||
|
||||
describe('boot guard', () => {
|
||||
let removeListeners: () => void = () => {};
|
||||
|
||||
beforeEach(() => {
|
||||
const added: Parameters<typeof window.addEventListener>[] = [];
|
||||
const addEventListener = window.addEventListener.bind(window);
|
||||
jest
|
||||
.spyOn(window, 'addEventListener')
|
||||
.mockImplementation((...args: Parameters<typeof addEventListener>) => {
|
||||
added.push(args);
|
||||
addEventListener(...args);
|
||||
});
|
||||
removeListeners = (): void => {
|
||||
added.forEach((args) => window.removeEventListener(...args));
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
removeListeners();
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('shows nothing while the app loads', () => {
|
||||
runGuard(true);
|
||||
|
||||
expect(screen.queryByTestId('boot-error')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the load error when the entry module fails', () => {
|
||||
runGuard(true);
|
||||
|
||||
addScript('module').dispatchEvent(new Event('error'));
|
||||
|
||||
expect(screen.getByTestId('boot-error')).toHaveTextContent(
|
||||
'SigNoz failed to load',
|
||||
);
|
||||
expect(screen.getByTestId('boot-error-reload')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('ignores errors from classic scripts', () => {
|
||||
runGuard(true);
|
||||
|
||||
addScript('text/javascript').dispatchEvent(new Event('error'));
|
||||
|
||||
expect(screen.queryByTestId('boot-error')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('asks for a newer browser when import maps are not supported', () => {
|
||||
runGuard(false);
|
||||
|
||||
expect(screen.getByTestId('boot-error')).toHaveTextContent(
|
||||
'Your browser is not supported',
|
||||
);
|
||||
expect(screen.queryByTestId('boot-error-reload')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
29
frontend/vite-plugins/__tests__/inlineBootGuard.test.ts
Normal file
29
frontend/vite-plugins/__tests__/inlineBootGuard.test.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { readFileSync } from 'fs';
|
||||
import { resolve } from 'path';
|
||||
import type { HtmlTagDescriptor } from 'vite';
|
||||
|
||||
import { inlineBootGuard } from '../inlineBootGuard';
|
||||
|
||||
function readBootGuardFile(name: string): string {
|
||||
return readFileSync(resolve(__dirname, '../../boot-guard', name), 'utf8');
|
||||
}
|
||||
|
||||
describe('inlineBootGuard', () => {
|
||||
it('inlines the boot guard style and script into the head', () => {
|
||||
const transform = inlineBootGuard()
|
||||
.transformIndexHtml as () => HtmlTagDescriptor[];
|
||||
|
||||
expect(transform()).toStrictEqual([
|
||||
{
|
||||
tag: 'style',
|
||||
children: readBootGuardFile('bootGuard.css'),
|
||||
injectTo: 'head',
|
||||
},
|
||||
{
|
||||
tag: 'script',
|
||||
children: readBootGuardFile('bootGuard.js'),
|
||||
injectTo: 'head',
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
36
frontend/vite-plugins/__tests__/vendorChunkName.test.ts
Normal file
36
frontend/vite-plugins/__tests__/vendorChunkName.test.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { vendorChunkName } from '../vendorChunkName';
|
||||
|
||||
describe('vendorChunkName', () => {
|
||||
it('names an unscoped package after its folder', () => {
|
||||
expect(
|
||||
vendorChunkName('/repo/node_modules/react-dom/cjs/react-dom.production.js'),
|
||||
).toBe('v-react-dom');
|
||||
});
|
||||
|
||||
it('joins the scope and the name of a scoped package', () => {
|
||||
expect(
|
||||
vendorChunkName(
|
||||
'/repo/node_modules/@tanstack/react-table/build/lib/index.mjs',
|
||||
),
|
||||
).toBe('v--tanstack-react-table');
|
||||
});
|
||||
|
||||
it('uses the innermost node_modules of a pnpm path', () => {
|
||||
expect(
|
||||
vendorChunkName(
|
||||
'/repo/node_modules/.pnpm/antd@5.0.0_react@18/node_modules/antd/es/index.js',
|
||||
),
|
||||
).toBe('v-antd');
|
||||
});
|
||||
|
||||
it('returns null for app code and virtual modules', () => {
|
||||
expect(vendorChunkName('/repo/src/pages/Home/index.tsx')).toBeNull();
|
||||
expect(vendorChunkName('\0vite/preload-helper.js')).toBeNull();
|
||||
});
|
||||
|
||||
it('replaces characters that are not safe in a file name', () => {
|
||||
expect(vendorChunkName('/repo/node_modules/@scope/a+b/index.js')).toBe(
|
||||
'v--scope-a-b',
|
||||
);
|
||||
});
|
||||
});
|
||||
29
frontend/vite-plugins/inlineBootGuard.ts
Normal file
29
frontend/vite-plugins/inlineBootGuard.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { readFileSync } from 'fs';
|
||||
import { resolve } from 'path';
|
||||
import type { HtmlTagDescriptor, Plugin } from 'vite';
|
||||
|
||||
const BOOT_GUARD_DIR = resolve(__dirname, '../boot-guard');
|
||||
|
||||
function readBootGuardFile(name: string): string {
|
||||
return readFileSync(resolve(BOOT_GUARD_DIR, name), 'utf8');
|
||||
}
|
||||
|
||||
export function inlineBootGuard(): Plugin {
|
||||
return {
|
||||
name: 'signoz:inline-boot-guard',
|
||||
transformIndexHtml(): HtmlTagDescriptor[] {
|
||||
return [
|
||||
{
|
||||
tag: 'style',
|
||||
children: readBootGuardFile('bootGuard.css'),
|
||||
injectTo: 'head',
|
||||
},
|
||||
{
|
||||
tag: 'script',
|
||||
children: readBootGuardFile('bootGuard.js'),
|
||||
injectTo: 'head',
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
}
|
||||
13
frontend/vite-plugins/vendorChunkName.ts
Normal file
13
frontend/vite-plugins/vendorChunkName.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
const NODE_MODULES = 'node_modules/';
|
||||
|
||||
export function vendorChunkName(moduleId: string): string | null {
|
||||
const start = moduleId.lastIndexOf(NODE_MODULES);
|
||||
if (start < 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [first, second] = moduleId.slice(start + NODE_MODULES.length).split('/');
|
||||
const packageName = first.startsWith('@') ? `${first}-${second}` : first;
|
||||
|
||||
return `v-${packageName.replace(/[^A-Za-z0-9_.-]/g, '-')}`;
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import { defineConfig, loadEnv } from 'vite';
|
||||
import vitePluginChecker from 'vite-plugin-checker';
|
||||
import viteCompression from 'vite-plugin-compression';
|
||||
import { ViteImageOptimizer } from 'vite-plugin-image-optimizer';
|
||||
import tsconfigPaths from 'vite-tsconfig-paths';
|
||||
import type {
|
||||
Appcues,
|
||||
Posthog,
|
||||
@@ -15,6 +14,8 @@ import type {
|
||||
Sentry,
|
||||
WebSettings,
|
||||
} from 'types/generated/webSettings';
|
||||
import { inlineBootGuard } from './vite-plugins/inlineBootGuard';
|
||||
import { vendorChunkName } from './vite-plugins/vendorChunkName';
|
||||
|
||||
// In dev the Go backend is not involved, so replace the [[.BaseHref]] placeholder
|
||||
// with the configured base path so relative assets resolve correctly from the Vite dev server.
|
||||
@@ -82,10 +83,10 @@ export default defineConfig(({ mode }): UserConfig => {
|
||||
const basePath = env.VITE_BASE_PATH || '/';
|
||||
|
||||
const plugins = [
|
||||
tsconfigPaths(),
|
||||
rawMarkdownPlugin(),
|
||||
devBasePathPlugin(basePath),
|
||||
devBootDataPlugin(env),
|
||||
inlineBootGuard(),
|
||||
react(),
|
||||
vitePluginChecker({
|
||||
typescript: true,
|
||||
@@ -114,7 +115,13 @@ export default defineConfig(({ mode }): UserConfig => {
|
||||
project: env.VITE_SENTRY_PROJECT_ID,
|
||||
// Pin the sourcemap-upload release to the same value injected as
|
||||
// process.env.VERSION so uploaded sourcemaps resolve. Ref: platform-pod#2393
|
||||
release: { name: env.VITE_VERSION, setCommits: { auto: true } },
|
||||
// `inject: false`: the release string would otherwise land in every chunk
|
||||
// and change all their hashes on each release. Sentry.init sets it.
|
||||
release: {
|
||||
name: env.VITE_VERSION,
|
||||
inject: false,
|
||||
setCommits: { auto: true },
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -142,6 +149,7 @@ export default defineConfig(({ mode }): UserConfig => {
|
||||
return {
|
||||
plugins,
|
||||
resolve: {
|
||||
tsconfigPaths: true,
|
||||
alias: {
|
||||
// @grafana/data imports bare CJS `lodash`, whose UMD footer checks for an
|
||||
// AMD loader before assigning module.exports. Any third-party script that
|
||||
@@ -149,13 +157,13 @@ export default defineConfig(({ mode }): UserConfig => {
|
||||
// every lodash method reached through it is undefined at runtime. lodash-es
|
||||
// is the same version, real ESM, and tree-shakes.
|
||||
lodash: 'lodash-es',
|
||||
'@': resolve(__dirname, './src'),
|
||||
utils: resolve(__dirname, './src/utils'),
|
||||
types: resolve(__dirname, './src/types'),
|
||||
constants: resolve(__dirname, './src/constants'),
|
||||
parser: resolve(__dirname, './src/parser'),
|
||||
providers: resolve(__dirname, './src/providers'),
|
||||
lib: resolve(__dirname, './src/lib'),
|
||||
'@': resolve(import.meta.dirname, './src'),
|
||||
utils: resolve(import.meta.dirname, './src/utils'),
|
||||
types: resolve(import.meta.dirname, './src/types'),
|
||||
constants: resolve(import.meta.dirname, './src/constants'),
|
||||
parser: resolve(import.meta.dirname, './src/parser'),
|
||||
providers: resolve(import.meta.dirname, './src/providers'),
|
||||
lib: resolve(import.meta.dirname, './src/lib'),
|
||||
},
|
||||
},
|
||||
css: {
|
||||
@@ -188,6 +196,42 @@ export default defineConfig(({ mode }): UserConfig => {
|
||||
sourcemap: true,
|
||||
outDir: 'build',
|
||||
cssMinify: 'esbuild',
|
||||
chunkImportMap: true,
|
||||
rolldownOptions: {
|
||||
output: {
|
||||
// Export aliases are renumbered whenever a chunk's exports change, which
|
||||
// re-hashes every importer.
|
||||
minifyInternalExports: false,
|
||||
// Without these groups Rolldown splits the entry's static graph into ~300
|
||||
// chunks, 324 requests on first load. `initial` keeps the app code of that
|
||||
// graph in one chunk, so the packages around it can keep their hashes.
|
||||
codeSplitting: {
|
||||
groups: [
|
||||
{
|
||||
name: vendorChunkName,
|
||||
debugName: 'per-package',
|
||||
test: 'node_modules',
|
||||
tags: ['$initial'],
|
||||
minSize: 100 * 1024,
|
||||
priority: 5,
|
||||
},
|
||||
{
|
||||
name: 'v-misc',
|
||||
test: 'node_modules',
|
||||
tags: ['$initial'],
|
||||
priority: 1,
|
||||
},
|
||||
{ name: 'initial', tags: ['$initial'] },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
// An iife worker runs as a sloppy script, where a function declared in a
|
||||
// block is hoisted as a `var` over the minifier's renamed outer names (the
|
||||
// JSON worker's validation then throws on every non-empty array).
|
||||
worker: {
|
||||
format: 'es',
|
||||
},
|
||||
server: {
|
||||
open: true,
|
||||
|
||||
@@ -14,10 +14,12 @@ import (
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagertemplate"
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/types/alertmanagertypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/ruletypes"
|
||||
commoncfg "github.com/prometheus/common/config"
|
||||
"github.com/prometheus/common/model"
|
||||
|
||||
@@ -35,6 +37,10 @@ const (
|
||||
|
||||
const (
|
||||
Integration = "msteamsv2"
|
||||
|
||||
// Teams rejects messages over 28 KB; the margin covers the workflow's own envelope.
|
||||
// https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/add-incoming-webhook
|
||||
maxMessageBytes = 25 * 1024
|
||||
)
|
||||
|
||||
type Notifier struct {
|
||||
@@ -67,7 +73,6 @@ type Body struct {
|
||||
Wrap bool `json:"wrap,omitempty"`
|
||||
Style string `json:"style,omitempty"`
|
||||
Color string `json:"color,omitempty"`
|
||||
Facts []Fact `json:"facts,omitempty"`
|
||||
}
|
||||
|
||||
type Action struct {
|
||||
@@ -76,11 +81,6 @@ type Action struct {
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
type Fact struct {
|
||||
Title string `json:"title"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
type Msteams struct {
|
||||
Width string `json:"width"`
|
||||
}
|
||||
@@ -154,8 +154,177 @@ func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error)
|
||||
return false, err
|
||||
}
|
||||
|
||||
// A message as referenced in https://learn.microsoft.com/en-us/connectors/teams/?tabs=text1%2Cdotnet#request-body-schema
|
||||
t := teamsMessage{
|
||||
payload, err := encodeMessage(bodyBlocks, titleLink)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
originalBytes := payload.Len()
|
||||
for payload.Len() > maxMessageBytes {
|
||||
longest := indexLongestText(bodyBlocks)
|
||||
if longest < 0 {
|
||||
break
|
||||
}
|
||||
text := truncateToEncodedBytes(bodyBlocks[longest].Text, payload.Len()-maxMessageBytes)
|
||||
if text == "" && longest > 0 {
|
||||
bodyBlocks = slices.Delete(bodyBlocks, longest, longest+1)
|
||||
} else {
|
||||
bodyBlocks[longest].Text = text
|
||||
}
|
||||
if payload, err = encodeMessage(bodyBlocks, titleLink); err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
if payload.Len() < originalBytes {
|
||||
n.logger.WarnContext(ctx, "truncated message text to fit the size limit", slog.Int("original_bytes", originalBytes), slog.Int("final_bytes", payload.Len()), slog.Int("max_bytes", maxMessageBytes))
|
||||
}
|
||||
|
||||
resp, err := n.postJSONFunc(ctx, n.client, url, payload) //nolint:bodyclose
|
||||
if err != nil {
|
||||
return true, notify.RedactURL(err)
|
||||
}
|
||||
defer notify.Drain(resp) //drain is used to close the body of the response hence the nolint directive
|
||||
|
||||
// https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/connectors-using?tabs=cURL#rate-limiting-for-connectors
|
||||
shouldRetry, err := n.retrier.Check(resp.StatusCode, resp.Body)
|
||||
if err != nil {
|
||||
return shouldRetry, notify.NewErrorWithReason(notify.GetFailureReasonFromStatusCode(resp.StatusCode), err)
|
||||
}
|
||||
return shouldRetry, err
|
||||
}
|
||||
|
||||
// prepareContent builds the Adaptive Card body blocks for the notification.
|
||||
// The first block is always the title; the remainder is the channel text, or
|
||||
// one block per alert when the alerts carried a custom body template.
|
||||
func (n *Notifier) prepareContent(ctx context.Context, alerts []*types.Alert) ([]Body, error) {
|
||||
if groupLabels, ok := notify.GroupLabels(ctx); ok {
|
||||
ctx = notify.WithGroupLabels(ctx, escapeLabels(groupLabels))
|
||||
}
|
||||
|
||||
customTitle, customBody := alertmanagertemplate.ExtractTemplatesFromAnnotations(alerts)
|
||||
result, err := n.templater.Expand(ctx, alertmanagertypes.ExpandRequest{
|
||||
TitleTemplate: customTitle,
|
||||
BodyTemplate: customBody,
|
||||
DefaultTitleTemplate: n.conf.Title,
|
||||
DefaultBodyTemplate: n.conf.Text,
|
||||
}, escapeLabelValues(alerts))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
color := colorGrey
|
||||
switch types.Alerts(alerts...).Status() {
|
||||
case model.AlertFiring:
|
||||
color = colorRed
|
||||
case model.AlertResolved:
|
||||
color = colorGreen
|
||||
}
|
||||
|
||||
blocks := []Body{{
|
||||
Type: "TextBlock",
|
||||
Text: result.Title,
|
||||
Weight: "Bolder",
|
||||
Size: "Medium",
|
||||
Wrap: true,
|
||||
Style: "heading",
|
||||
Color: color,
|
||||
}}
|
||||
|
||||
if result.IsDefaultBody {
|
||||
for _, body := range result.Body {
|
||||
if body = strings.TrimSpace(body); body != "" {
|
||||
blocks = append(blocks, Body{Type: "TextBlock", Text: body, Wrap: true})
|
||||
}
|
||||
}
|
||||
return blocks, nil
|
||||
}
|
||||
|
||||
// Custom body path: result.Body is positionally aligned with alerts;
|
||||
// entries for alerts whose template rendered empty are kept as "" so we
|
||||
// can skip them here without shifting the per-alert color index.
|
||||
for i, body := range result.Body {
|
||||
if body == "" || i >= len(alerts) {
|
||||
continue
|
||||
}
|
||||
perAlertColor := colorRed
|
||||
if alerts[i].Resolved() {
|
||||
perAlertColor = colorGreen
|
||||
}
|
||||
blocks = append(blocks, Body{
|
||||
Type: "TextBlock",
|
||||
Text: body,
|
||||
Wrap: true,
|
||||
Color: perAlertColor,
|
||||
})
|
||||
}
|
||||
return blocks, nil
|
||||
}
|
||||
|
||||
// escapeLabelValues copies the alerts so a label value shows on the card as written instead of being read as markdown.
|
||||
func escapeLabelValues(alerts []*types.Alert) []*types.Alert {
|
||||
escaped := make([]*types.Alert, 0, len(alerts))
|
||||
|
||||
for _, alert := range alerts {
|
||||
escaped = append(escaped, &types.Alert{
|
||||
Alert: model.Alert{
|
||||
Labels: escapeLabels(alert.Labels),
|
||||
Annotations: alert.Annotations.Clone(),
|
||||
StartsAt: alert.StartsAt,
|
||||
EndsAt: alert.EndsAt,
|
||||
GeneratorURL: alert.GeneratorURL,
|
||||
},
|
||||
UpdatedAt: alert.UpdatedAt,
|
||||
Timeout: alert.Timeout,
|
||||
})
|
||||
}
|
||||
|
||||
return escaped
|
||||
}
|
||||
|
||||
func escapeLabels(labels model.LabelSet) model.LabelSet {
|
||||
escaped := make(model.LabelSet, len(labels))
|
||||
for name, value := range labels {
|
||||
if name == ruletypes.LabelRuleSource {
|
||||
escaped[name] = value
|
||||
continue
|
||||
}
|
||||
escaped[name] = model.LabelValue(escapeMarkdown(string(value)))
|
||||
}
|
||||
|
||||
return escaped
|
||||
}
|
||||
|
||||
// escapeMarkdown leaves an underscore inside a word and a lone tilde alone, since Teams reads neither as markup.
|
||||
func escapeMarkdown(value string) string {
|
||||
runes := []rune(value)
|
||||
pairedTildes := strings.Count(value, "~") > 1
|
||||
|
||||
var escaped strings.Builder
|
||||
for i, r := range runes {
|
||||
switch r {
|
||||
case '\\', '*', '[', ']', '`':
|
||||
escaped.WriteRune('\\')
|
||||
case '~':
|
||||
if pairedTildes {
|
||||
escaped.WriteRune('\\')
|
||||
}
|
||||
case '_':
|
||||
if i == 0 || i == len(runes)-1 || !isWordRune(runes[i-1]) || !isWordRune(runes[i+1]) {
|
||||
escaped.WriteRune('\\')
|
||||
}
|
||||
}
|
||||
escaped.WriteRune(r)
|
||||
}
|
||||
|
||||
return escaped.String()
|
||||
}
|
||||
|
||||
func isWordRune(r rune) bool {
|
||||
return unicode.IsLetter(r) || unicode.IsDigit(r)
|
||||
}
|
||||
|
||||
// A message as referenced in https://learn.microsoft.com/en-us/connectors/teams/?tabs=text1%2Cdotnet#request-body-schema
|
||||
func encodeMessage(bodyBlocks []Body, titleLink string) (*bytes.Buffer, error) {
|
||||
message := teamsMessage{
|
||||
Type: "message",
|
||||
Attachments: []Attachment{
|
||||
{
|
||||
@@ -182,134 +351,49 @@ func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error)
|
||||
}
|
||||
|
||||
var payload bytes.Buffer
|
||||
if err = json.NewEncoder(&payload).Encode(t); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
resp, err := n.postJSONFunc(ctx, n.client, url, &payload) //nolint:bodyclose
|
||||
if err != nil {
|
||||
return true, notify.RedactURL(err)
|
||||
}
|
||||
defer notify.Drain(resp) //drain is used to close the body of the response hence the nolint directive
|
||||
|
||||
// https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/connectors-using?tabs=cURL#rate-limiting-for-connectors
|
||||
shouldRetry, err := n.retrier.Check(resp.StatusCode, resp.Body)
|
||||
if err != nil {
|
||||
return shouldRetry, notify.NewErrorWithReason(notify.GetFailureReasonFromStatusCode(resp.StatusCode), err)
|
||||
}
|
||||
return shouldRetry, err
|
||||
}
|
||||
|
||||
// prepareContent builds the Adaptive Card body blocks for the notification.
|
||||
// The first block is always the title; the remainder depends on whether the
|
||||
// alerts carried a custom body template.
|
||||
func (n *Notifier) prepareContent(ctx context.Context, alerts []*types.Alert) ([]Body, error) {
|
||||
customTitle, customBody := alertmanagertemplate.ExtractTemplatesFromAnnotations(alerts)
|
||||
result, err := n.templater.Expand(ctx, alertmanagertypes.ExpandRequest{
|
||||
TitleTemplate: customTitle,
|
||||
BodyTemplate: customBody,
|
||||
DefaultTitleTemplate: n.conf.Title,
|
||||
DefaultBodyTemplate: n.conf.Text,
|
||||
}, alerts)
|
||||
if err != nil {
|
||||
if err := json.NewEncoder(&payload).Encode(message); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
color := colorGrey
|
||||
switch types.Alerts(alerts...).Status() {
|
||||
case model.AlertFiring:
|
||||
color = colorRed
|
||||
case model.AlertResolved:
|
||||
color = colorGreen
|
||||
}
|
||||
|
||||
blocks := []Body{{
|
||||
Type: "TextBlock",
|
||||
Text: result.Title,
|
||||
Weight: "Bolder",
|
||||
Size: "Medium",
|
||||
Wrap: true,
|
||||
Style: "heading",
|
||||
Color: color,
|
||||
}}
|
||||
|
||||
if result.IsDefaultBody {
|
||||
for _, alert := range alerts {
|
||||
blocks = append(blocks, Body{
|
||||
Type: "TextBlock",
|
||||
Text: "Alerts",
|
||||
Weight: "Bolder",
|
||||
Size: "Medium",
|
||||
Wrap: true,
|
||||
Color: color,
|
||||
})
|
||||
blocks = append(blocks, n.createLabelsAndAnnotationsBody(alert)...)
|
||||
}
|
||||
return blocks, nil
|
||||
}
|
||||
|
||||
// Custom body path: result.Body is positionally aligned with alerts;
|
||||
// entries for alerts whose template rendered empty are kept as "" so we
|
||||
// can skip them here without shifting the per-alert color index.
|
||||
for i, body := range result.Body {
|
||||
if body == "" || i >= len(alerts) {
|
||||
continue
|
||||
}
|
||||
perAlertColor := colorRed
|
||||
if alerts[i].Resolved() {
|
||||
perAlertColor = colorGreen
|
||||
}
|
||||
blocks = append(blocks, Body{
|
||||
Type: "TextBlock",
|
||||
Text: body,
|
||||
Wrap: true,
|
||||
Color: perAlertColor,
|
||||
})
|
||||
}
|
||||
return blocks, nil
|
||||
return &payload, nil
|
||||
}
|
||||
|
||||
func (*Notifier) createLabelsAndAnnotationsBody(alert *types.Alert) []Body {
|
||||
bodies := []Body{}
|
||||
bodies = append(bodies, Body{
|
||||
Type: "TextBlock",
|
||||
Text: "Labels",
|
||||
Weight: "Bolder",
|
||||
Size: "Medium",
|
||||
})
|
||||
// truncateToEncodedBytes cuts text until its JSON encoding is overflow bytes shorter, since escaping makes some characters longer than their raw bytes.
|
||||
func truncateToEncodedBytes(text string, overflow int) string {
|
||||
budget := encodedLen(text) - overflow
|
||||
|
||||
facts := []Fact{}
|
||||
for k, v := range alert.Labels {
|
||||
if slices.Contains([]string{"alertname", "severity", "ruleId", "ruleSource"}, string(k)) {
|
||||
continue
|
||||
low, high := 0, len(text)
|
||||
for low < high {
|
||||
mid := (low + high + 1) / 2
|
||||
truncated, _ := notify.TruncateInBytes(text, mid)
|
||||
if encodedLen(truncated) <= budget {
|
||||
low = mid
|
||||
} else {
|
||||
high = mid - 1
|
||||
}
|
||||
facts = append(facts, Fact{Title: string(k), Value: string(v)})
|
||||
}
|
||||
bodies = append(bodies, Body{
|
||||
Type: "FactSet",
|
||||
Facts: facts,
|
||||
})
|
||||
truncated, _ := notify.TruncateInBytes(text, low)
|
||||
|
||||
bodies = append(bodies, Body{
|
||||
Type: "TextBlock",
|
||||
Text: "Annotations",
|
||||
Weight: "Bolder",
|
||||
Size: "Medium",
|
||||
})
|
||||
|
||||
annotationsFacts := []Fact{}
|
||||
for k, v := range alert.Annotations {
|
||||
if slices.Contains([]string{"summary", "related_logs", "related_traces"}, string(k)) ||
|
||||
alertmanagertypes.IsPrivateAnnotation(string(k)) {
|
||||
continue
|
||||
}
|
||||
annotationsFacts = append(annotationsFacts, Fact{Title: string(k), Value: string(v)})
|
||||
}
|
||||
|
||||
bodies = append(bodies, Body{
|
||||
Type: "FactSet",
|
||||
Facts: annotationsFacts,
|
||||
})
|
||||
|
||||
return bodies
|
||||
return truncated
|
||||
}
|
||||
|
||||
func encodedLen(text string) int {
|
||||
encoded, _ := json.Marshal(text)
|
||||
|
||||
return len(encoded)
|
||||
}
|
||||
|
||||
// indexLongestText returns -1 once no block has text left to trim; the title at index 0 goes last.
|
||||
func indexLongestText(blocks []Body) int {
|
||||
longest := -1
|
||||
for i := 1; i < len(blocks); i++ {
|
||||
if len(blocks[i].Text) > 0 && (longest < 0 || len(blocks[i].Text) > len(blocks[longest].Text)) {
|
||||
longest = i
|
||||
}
|
||||
}
|
||||
if longest < 0 && len(blocks) > 0 && len(blocks[0].Text) > 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
return longest
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
package msteamsv2
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
@@ -13,6 +14,7 @@ import (
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -340,3 +342,399 @@ func TestMSTeamsV2ReadingURLFromFile(t *testing.T) {
|
||||
|
||||
test.AssertNotifyLeaksNoSecret(ctx, t, notifier, u.String())
|
||||
}
|
||||
|
||||
func TestPrepareContentChannelText(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
title string
|
||||
text string
|
||||
annotations model.LabelSet
|
||||
expectedTitle string
|
||||
expectedBody []Body
|
||||
}{
|
||||
{
|
||||
name: "CustomChannelText_Rendered",
|
||||
title: "Team alert: {{ .CommonLabels.alertname }}",
|
||||
text: "Service {{ range .Alerts }}{{ .Labels.service }}{{ end }} needs attention",
|
||||
expectedTitle: "Team alert: checkout errors",
|
||||
expectedBody: []Body{{Type: "TextBlock", Text: "Service checkout needs attention", Wrap: true}},
|
||||
},
|
||||
{
|
||||
name: "DefaultMarkers_RenderTeamsDefault",
|
||||
title: `{{ template "msteamsv2.default.title" . }}`,
|
||||
text: `{{ template "msteamsv2.default.text" . }}`,
|
||||
annotations: model.LabelSet{"description": "error rate crossed 5%"},
|
||||
expectedTitle: "[FIRING:1] checkout errors",
|
||||
expectedBody: []Body{{
|
||||
Type: "TextBlock",
|
||||
Text: "**Alert:** checkout errors (critical) - firing\n\n**Description:** error rate crossed 5%\n\n**Details:**\n\n- **service:** checkout",
|
||||
Wrap: true,
|
||||
}},
|
||||
},
|
||||
{
|
||||
name: "RuleBodyTemplate_OverridesChannelText",
|
||||
title: "Rule wins: {{ .CommonLabels.alertname }}",
|
||||
text: "channel text that must not appear",
|
||||
annotations: model.LabelSet{ruletypes.AnnotationBodyTemplate: "rule body for $alertname"},
|
||||
expectedTitle: "Rule wins: checkout errors",
|
||||
expectedBody: []Body{{Type: "TextBlock", Text: "rule body for checkout errors", Wrap: true, Color: colorRed}},
|
||||
},
|
||||
{
|
||||
name: "EmptyText_TitleOnly",
|
||||
title: "Only a title",
|
||||
text: "",
|
||||
expectedTitle: "Only a title",
|
||||
expectedBody: []Body{},
|
||||
},
|
||||
{
|
||||
name: "WhitespaceText_TitleOnly",
|
||||
title: "Still only a title",
|
||||
text: "{{ if false }}never{{ end }}\n ",
|
||||
expectedTitle: "Still only a title",
|
||||
expectedBody: []Body{},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
tmpl, err := alertmanagertypes.FromGlobs([]string{})
|
||||
require.NoError(t, err)
|
||||
tmpl.ExternalURL = &url.URL{Scheme: "http", Host: "signoz.test"}
|
||||
|
||||
notifier, err := New(
|
||||
&config.MSTeamsV2Config{
|
||||
WebhookURL: &config.SecretURL{URL: testWebhookURL},
|
||||
HTTPConfig: &commoncfg.HTTPClientConfig{},
|
||||
Title: testCase.title,
|
||||
Text: testCase.text,
|
||||
},
|
||||
tmpl,
|
||||
`{{ template "msteamsv2.default.titleLink" . }}`,
|
||||
promslog.NewNopLogger(),
|
||||
newTestTemplater(tmpl),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
alerts := []*types.Alert{{
|
||||
Alert: model.Alert{
|
||||
Labels: model.LabelSet{"alertname": "checkout errors", "severity": "critical", "service": "checkout", "ruleId": "0199051c-f374-71f7-a340-ec79ad81e70f"},
|
||||
Annotations: testCase.annotations,
|
||||
StartsAt: time.Now(),
|
||||
EndsAt: time.Now().Add(time.Hour),
|
||||
},
|
||||
}}
|
||||
|
||||
blocks, err := notifier.prepareContent(notify.WithGroupKey(context.Background(), "1"), alerts)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, blocks)
|
||||
assert.Equal(t, testCase.expectedTitle, blocks[0].Text)
|
||||
assert.Equal(t, colorRed, blocks[0].Color)
|
||||
assert.Equal(t, testCase.expectedBody, blocks[1:])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotifyMessageSize(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
text string
|
||||
ruleBody string
|
||||
alertCount int
|
||||
expectedTruncated bool
|
||||
expectedWarnLogs int
|
||||
}{
|
||||
{
|
||||
name: "UnderLimit_TextUntouched",
|
||||
text: strings.Repeat("short body ", 100),
|
||||
expectedTruncated: false,
|
||||
expectedWarnLogs: 0,
|
||||
},
|
||||
{
|
||||
name: "OverLimit_TextTrimmedToFit",
|
||||
text: strings.Repeat("a very long body line\n\n", 4000),
|
||||
expectedTruncated: true,
|
||||
expectedWarnLogs: 1,
|
||||
},
|
||||
{
|
||||
name: "OverLimit_EscapedCharacters_StillFits",
|
||||
text: strings.Repeat("request to \"checkout\" failed with a timeout after several retries\n", 4000),
|
||||
expectedTruncated: true,
|
||||
expectedWarnLogs: 1,
|
||||
},
|
||||
{
|
||||
name: "OverLimit_HTMLCharacters_KeepsFittingPrefix",
|
||||
text: strings.Repeat("&", 6000),
|
||||
expectedTruncated: true,
|
||||
expectedWarnLogs: 1,
|
||||
},
|
||||
{
|
||||
name: "OverLimit_Backslashes_KeepsFittingPrefix",
|
||||
text: strings.Repeat(`C:\\Users\\x `, 4000),
|
||||
expectedTruncated: true,
|
||||
expectedWarnLogs: 1,
|
||||
},
|
||||
{
|
||||
name: "OverLimit_ManyRuleBodies_BlocksDropped",
|
||||
text: "unused channel text",
|
||||
ruleBody: "rule body for $alertname",
|
||||
alertCount: 600,
|
||||
expectedTruncated: true,
|
||||
expectedWarnLogs: 1,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
var received []byte
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
received, _ = io.ReadAll(r.Body)
|
||||
}))
|
||||
defer srv.Close()
|
||||
u, err := url.Parse(srv.URL)
|
||||
require.NoError(t, err)
|
||||
|
||||
var logs bytes.Buffer
|
||||
tmpl := test.CreateTmpl(t)
|
||||
notifier, err := New(
|
||||
&config.MSTeamsV2Config{
|
||||
WebhookURL: &config.SecretURL{URL: u},
|
||||
HTTPConfig: &commoncfg.HTTPClientConfig{},
|
||||
Title: "size check",
|
||||
Text: testCase.text,
|
||||
},
|
||||
tmpl,
|
||||
`{{ template "msteamsv2.default.titleLink" . }}`,
|
||||
slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelWarn})),
|
||||
newTestTemplater(tmpl),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
alerts := make([]*types.Alert, 0, max(testCase.alertCount, 1))
|
||||
for range max(testCase.alertCount, 1) {
|
||||
alert := &types.Alert{Alert: model.Alert{Labels: model.LabelSet{"alertname": "size"}, StartsAt: time.Now(), EndsAt: time.Now().Add(time.Hour)}}
|
||||
if testCase.ruleBody != "" {
|
||||
alert.Annotations = model.LabelSet{ruletypes.AnnotationBodyTemplate: model.LabelValue(testCase.ruleBody)}
|
||||
}
|
||||
alerts = append(alerts, alert)
|
||||
}
|
||||
|
||||
_, err = notifier.Notify(notify.WithGroupKey(context.Background(), "1"), alerts...)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, received)
|
||||
assert.LessOrEqual(t, len(received), maxMessageBytes)
|
||||
assert.Equal(t, testCase.expectedWarnLogs, strings.Count(logs.String(), "level=WARN"))
|
||||
|
||||
var message teamsMessage
|
||||
require.NoError(t, json.Unmarshal(received, &message))
|
||||
require.Len(t, message.Attachments, 1)
|
||||
body := message.Attachments[0].Content.Body
|
||||
require.NotEmpty(t, body)
|
||||
assert.Equal(t, "size check", body[0].Text)
|
||||
if testCase.alertCount > 1 {
|
||||
assert.Greater(t, len(body), 1)
|
||||
assert.Less(t, len(body), testCase.alertCount+1)
|
||||
for _, block := range body {
|
||||
assert.NotEmpty(t, block.Text)
|
||||
}
|
||||
return
|
||||
}
|
||||
require.Len(t, body, 2)
|
||||
assert.NotEmpty(t, body[1].Text)
|
||||
assert.Equal(t, testCase.expectedTruncated, len(body[1].Text) < len(strings.TrimSpace(testCase.text)))
|
||||
if testCase.expectedTruncated {
|
||||
assert.Greater(t, len(received), maxMessageBytes-32)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEscapeMarkdown(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
value string
|
||||
expected string
|
||||
}{
|
||||
{name: "AsteriskPair_Escaped", value: "a*b*c", expected: `a\*b\*c`},
|
||||
{name: "LinkSyntax_BracketsEscaped", value: "[runbook](https://wiki.test)", expected: `\[runbook\](https://wiki.test)`},
|
||||
{name: "UnderscoreAtWordEdges_Escaped", value: "_internal_ value", expected: `\_internal\_ value`},
|
||||
{name: "DoubleUnderscore_AllEscaped", value: "__init__", expected: `\_\_init\_\_`},
|
||||
{name: "UnderscoreInsideWord_Untouched", value: "k8s_namespace_name", expected: "k8s_namespace_name"},
|
||||
{name: "UnderscoreAfterSymbol_Escaped", value: "/api/v1/*_bulk", expected: `/api/v1/\*\_bulk`},
|
||||
{name: "TrailingUnderscore_Escaped", value: "tmp_", expected: `tmp\_`},
|
||||
{name: "NonASCIIWord_UnderscoreUntouched", value: "größe_wert", expected: "größe_wert"},
|
||||
{name: "WindowsPath_BackslashesEscaped", value: `C:\Users\x`, expected: `C:\\Users\\x`},
|
||||
{name: "UNCPath_BackslashesEscaped", value: `\\server\share`, expected: `\\\\server\\share`},
|
||||
{name: "EscapedAsterisk_BackslashAndAsteriskEscaped", value: `x\*y*`, expected: `x\\\*y\*`},
|
||||
{name: "BacktickPair_Escaped", value: "run `cmd` now", expected: "run \\`cmd\\` now"},
|
||||
{name: "TildePair_Escaped", value: "a~b~c", expected: `a\~b\~c`},
|
||||
{name: "DoubleTildePair_Escaped", value: "a~~b~~c", expected: `a\~\~b\~\~c`},
|
||||
{name: "LoneTilde_Untouched", value: "https://host.test/~user/logs", expected: "https://host.test/~user/logs"},
|
||||
{name: "HTMLAndHash_Untouched", value: "<b>tag</b> # not a heading", expected: "<b>tag</b> # not a heading"},
|
||||
{name: "Empty_Untouched", value: "", expected: ""},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
assert.Equal(t, testCase.expected, escapeMarkdown(testCase.value))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEscapeLabelValues(t *testing.T) {
|
||||
startsAt := time.Unix(1700000000, 0)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
alert *types.Alert
|
||||
expectedLabels model.LabelSet
|
||||
expectedAnnotations model.LabelSet
|
||||
}{
|
||||
{
|
||||
name: "MarkdownInLabels_CopyEscaped_OriginalUntouched",
|
||||
alert: &types.Alert{
|
||||
Alert: model.Alert{
|
||||
Labels: model.LabelSet{"alertname": "a*b*c"},
|
||||
Annotations: model.LabelSet{"summary": "**bold**"},
|
||||
StartsAt: startsAt,
|
||||
EndsAt: startsAt.Add(time.Minute),
|
||||
GeneratorURL: "https://signoz.test/alerts",
|
||||
},
|
||||
UpdatedAt: startsAt,
|
||||
Timeout: true,
|
||||
},
|
||||
expectedLabels: model.LabelSet{"alertname": `a\*b\*c`},
|
||||
expectedAnnotations: model.LabelSet{"summary": "**bold**"},
|
||||
},
|
||||
{
|
||||
name: "PlainLabels_CopyUnchanged_OriginalUntouched",
|
||||
alert: &types.Alert{Alert: model.Alert{Labels: model.LabelSet{"service": "checkout"}, Annotations: model.LabelSet{}, StartsAt: startsAt}},
|
||||
expectedLabels: model.LabelSet{"service": "checkout"},
|
||||
expectedAnnotations: model.LabelSet{},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
originalLabels := testCase.alert.Labels.Clone()
|
||||
originalAnnotations := testCase.alert.Annotations.Clone()
|
||||
|
||||
escaped := escapeLabelValues([]*types.Alert{testCase.alert})
|
||||
require.Len(t, escaped, 1)
|
||||
|
||||
assert.Equal(t, testCase.expectedLabels, escaped[0].Labels)
|
||||
assert.Equal(t, testCase.expectedAnnotations, escaped[0].Annotations)
|
||||
assert.Equal(t, testCase.alert.StartsAt, escaped[0].StartsAt)
|
||||
assert.Equal(t, testCase.alert.EndsAt, escaped[0].EndsAt)
|
||||
assert.Equal(t, testCase.alert.GeneratorURL, escaped[0].GeneratorURL)
|
||||
assert.Equal(t, testCase.alert.UpdatedAt, escaped[0].UpdatedAt)
|
||||
assert.Equal(t, testCase.alert.Timeout, escaped[0].Timeout)
|
||||
|
||||
escaped[0].Annotations["added"] = "x"
|
||||
escaped[0].Labels["added"] = "x"
|
||||
assert.Equal(t, originalLabels, testCase.alert.Labels)
|
||||
assert.Equal(t, originalAnnotations, testCase.alert.Annotations)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepareContentEscapesLabelValues(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
title string
|
||||
text string
|
||||
annotations model.LabelSet
|
||||
expectedTitle string
|
||||
expectedBody string
|
||||
}{
|
||||
{
|
||||
name: "DefaultTemplates_AlertNameAndDetailsEscaped",
|
||||
title: `{{ template "msteamsv2.default.title" . }}`,
|
||||
text: `{{ template "msteamsv2.default.text" . }}`,
|
||||
expectedTitle: `[FIRING:1] CPU \*high\* \[prod\]`,
|
||||
expectedBody: "**Alert:** CPU \\*high\\* \\[prod\\] (critical) - firing\n\n**Details:**\n\n- **expr:** rate(a\\[5m\\]) \\* 2\n- **k8s_pod_name:** api_server_1",
|
||||
},
|
||||
{
|
||||
name: "CustomChannelTemplates_LabelValuesEscaped",
|
||||
title: "Custom: {{ .CommonLabels.alertname }}",
|
||||
text: "{{ range .Alerts }}expr={{ .Labels.expr }} pod={{ .Labels.k8s_pod_name }}{{ end }}",
|
||||
expectedTitle: `Custom: CPU \*high\* \[prod\]`,
|
||||
expectedBody: `expr=rate(a\[5m\]) \* 2 pod=api_server_1`,
|
||||
},
|
||||
{
|
||||
name: "CustomChannelTemplates_GroupLabelValuesEscaped",
|
||||
title: "Group: {{ .GroupLabels.alertname }}",
|
||||
text: "{{ .GroupLabels.alertname }} from {{ .GroupLabels.ruleSource }}",
|
||||
expectedTitle: `Group: CPU \*high\* \[prod\]`,
|
||||
expectedBody: `CPU \*high\* \[prod\] from https://signoz.test/alerts/overview?ruleId=[x]_`,
|
||||
},
|
||||
{
|
||||
name: "RuleBodyTemplate_LabelValuesEscaped",
|
||||
title: "Rule: {{ .CommonLabels.alertname }}",
|
||||
text: "unused channel text",
|
||||
annotations: model.LabelSet{ruletypes.AnnotationBodyTemplate: "expr is $expr"},
|
||||
expectedTitle: `Rule: CPU \*high\* \[prod\]`,
|
||||
expectedBody: `expr is rate(a\[5m\]) \* 2`,
|
||||
},
|
||||
{
|
||||
name: "AnnotationValues_LeftAsWritten",
|
||||
title: "Annotations: {{ .CommonLabels.severity }}",
|
||||
text: "{{ range .Alerts }}{{ .Annotations.summary }}{{ end }}",
|
||||
annotations: model.LabelSet{"summary": "see **the** [runbook](https://wiki.test) for a*b"},
|
||||
expectedTitle: "Annotations: critical",
|
||||
expectedBody: "see **the** [runbook](https://wiki.test) for a*b",
|
||||
},
|
||||
{
|
||||
name: "RuleSourceLabel_LeftAsWritten",
|
||||
title: "Source: {{ .CommonLabels.severity }}",
|
||||
text: "{{ range .Alerts }}[open]({{ .Labels.ruleSource }}){{ end }}",
|
||||
expectedTitle: "Source: critical",
|
||||
expectedBody: "[open](https://signoz.test/alerts/overview?ruleId=[x]_)",
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
tmpl, err := alertmanagertypes.FromGlobs([]string{})
|
||||
require.NoError(t, err)
|
||||
tmpl.ExternalURL = &url.URL{Scheme: "http", Host: "signoz.test"}
|
||||
|
||||
notifier, err := New(
|
||||
&config.MSTeamsV2Config{
|
||||
WebhookURL: &config.SecretURL{URL: testWebhookURL},
|
||||
HTTPConfig: &commoncfg.HTTPClientConfig{},
|
||||
Title: testCase.title,
|
||||
Text: testCase.text,
|
||||
},
|
||||
tmpl,
|
||||
`{{ template "msteamsv2.default.titleLink" . }}`,
|
||||
promslog.NewNopLogger(),
|
||||
newTestTemplater(tmpl),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
alerts := []*types.Alert{{
|
||||
Alert: model.Alert{
|
||||
Labels: model.LabelSet{
|
||||
"alertname": "CPU *high* [prod]", "severity": "critical", "expr": "rate(a[5m]) * 2", "k8s_pod_name": "api_server_1",
|
||||
"ruleSource": "https://signoz.test/alerts/overview?ruleId=[x]_",
|
||||
},
|
||||
Annotations: testCase.annotations,
|
||||
StartsAt: time.Now(),
|
||||
EndsAt: time.Now().Add(time.Hour),
|
||||
},
|
||||
}}
|
||||
|
||||
groupLabels := model.LabelSet{"alertname": "CPU *high* [prod]", "ruleSource": "https://signoz.test/alerts/overview?ruleId=[x]_"}
|
||||
ctx := notify.WithGroupLabels(notify.WithGroupKey(context.Background(), "1"), groupLabels)
|
||||
|
||||
blocks, err := notifier.prepareContent(ctx, alerts)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, blocks, 2)
|
||||
assert.Equal(t, testCase.expectedTitle, blocks[0].Text)
|
||||
assert.Equal(t, testCase.expectedBody, blocks[1].Text)
|
||||
assert.Equal(t, model.LabelValue("CPU *high* [prod]"), groupLabels["alertname"])
|
||||
assert.Equal(t, model.LabelValue("CPU *high* [prod]"), alerts[0].Labels["alertname"])
|
||||
assert.Equal(t, model.LabelValue("rate(a[5m]) * 2"), alerts[0].Labels["expr"])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,6 +133,41 @@ func postableSavedViewExamples() []handler.OpenAPIExample {
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "audit_list",
|
||||
Summary: "Audit logs list view",
|
||||
Description: "A list panel over audit logs for dashboard mutations. Audit views are queried as logs with the builder spec source set to audit.",
|
||||
Value: map[string]any{
|
||||
"name": "dashboard-audit-events",
|
||||
"source": "audit",
|
||||
"schemaVersion": "v2",
|
||||
"spec": map[string]any{
|
||||
"displayName": "Dashboard audit events",
|
||||
"panelType": "list",
|
||||
"requestType": "raw",
|
||||
"queries": []any{
|
||||
map[string]any{
|
||||
"type": "builder_query",
|
||||
"spec": map[string]any{
|
||||
"name": "A",
|
||||
"signal": "logs",
|
||||
"source": "audit",
|
||||
"filter": map[string]any{"expression": "signoz.resource.kind = 'dashboard'"},
|
||||
"order": []any{
|
||||
map[string]any{"key": map[string]any{"name": "timestamp"}, "direction": "desc"},
|
||||
map[string]any{"key": map[string]any{"name": "id"}, "direction": "desc"},
|
||||
},
|
||||
"limit": 100,
|
||||
},
|
||||
},
|
||||
},
|
||||
"selectedFields": []any{
|
||||
map[string]any{"name": "event_name", "signal": "logs", "fieldContext": "log", "fieldDataType": "string"},
|
||||
map[string]any{"name": "signoz.resource.kind", "signal": "logs", "fieldContext": "resource", "fieldDataType": "string"},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -278,6 +278,7 @@ func NewSQLMigrationProviderFactories(
|
||||
sqlmigration.NewMigrateRelatedLinksTemplateFactory(),
|
||||
sqlmigration.NewAddOrganizationTuplesFactory(sqlstore),
|
||||
sqlmigration.NewAddOrgPreferenceTuplesFactory(sqlstore),
|
||||
sqlmigration.NewMigrateMSTeamsDefaultTemplatesFactory(),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
699
pkg/sqlmigration/151_migrate_msteams_default_templates.go
Normal file
699
pkg/sqlmigration/151_migrate_msteams_default_templates.go
Normal file
@@ -0,0 +1,699 @@
|
||||
package sqlmigration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"text/template/parse"
|
||||
|
||||
"github.com/uptrace/bun"
|
||||
"github.com/uptrace/bun/migrate"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/factory"
|
||||
)
|
||||
|
||||
const (
|
||||
msteamsConfigsKey = "msteamsv2_configs"
|
||||
msteamsTitleField = "title"
|
||||
msteamsTextField = "text"
|
||||
|
||||
msteamsDefaultTitle = `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}`
|
||||
|
||||
msteamsDefaultText = `{{ range .Alerts -}}
|
||||
**Alert:** {{ .Labels.alertname }}{{ if .Labels.severity }} ({{ .Labels.severity }}){{ end }} - {{ .Status }}
|
||||
|
||||
{{ if .Annotations.summary }}**Summary:** {{ .Annotations.summary }}
|
||||
|
||||
{{ end }}{{ if .Annotations.description }}**Description:** {{ .Annotations.description }}
|
||||
|
||||
{{ end }}{{ template "signoz.relatedLinks.markdown" . }}{{ with (.Labels.Remove (stringSlice "alertname" "severity" "ruleId" "ruleSource")).SortedPairs }}**Details:**
|
||||
|
||||
{{ range . }}- **{{ .Name }}:** {{ .Value }}
|
||||
{{ end }}
|
||||
{{ end }}{{ end }}`
|
||||
|
||||
msteamsSlackSeedTitle = `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }} for {{ .CommonLabels.job }}
|
||||
{{- if gt (len .CommonLabels) (len .GroupLabels) -}}
|
||||
{{" "}}(
|
||||
{{- with .CommonLabels.Remove .GroupLabels.Names }}
|
||||
{{- range $index, $label := .SortedPairs -}}
|
||||
{{ if $index }}, {{ end }}
|
||||
{{- $label.Name }}="{{ $label.Value -}}"
|
||||
{{- end }}
|
||||
{{- end -}}
|
||||
)
|
||||
{{- end }}`
|
||||
|
||||
msteamsSlackRelatedLinksName = `"signoz.relatedLinks.slack"`
|
||||
msteamsMarkdownRelatedLinksName = `"signoz.relatedLinks.markdown"`
|
||||
|
||||
msteamsMaskOpen = ""
|
||||
msteamsMaskClose = ""
|
||||
|
||||
// A description counts as derived from the Slack seed once it still bolds this many of the seed's labels the Slack way.
|
||||
msteamsSlackSeedLabelThreshold = 2
|
||||
)
|
||||
|
||||
const (
|
||||
msteamsTemplateUnchanged msteamsTemplateOutcome = iota
|
||||
msteamsTemplateReplaced
|
||||
msteamsTemplateConverted
|
||||
msteamsTemplateCustom
|
||||
)
|
||||
|
||||
var (
|
||||
// Every description the channel form prefilled for Microsoft Teams; they differ only in the related links lines.
|
||||
msteamsSlackSeedTexts = []string{
|
||||
`{{ range .Alerts -}}
|
||||
*Alert:* {{ .Labels.alertname }}{{ if .Labels.severity }} - {{ .Labels.severity }}{{ end }}
|
||||
|
||||
*Summary:* {{ .Annotations.summary }}
|
||||
*Description:* {{ .Annotations.description }}
|
||||
|
||||
*Details:*
|
||||
{{ range .Labels.SortedPairs }} • *{{ .Name }}:* {{ .Value }}
|
||||
{{ end }}
|
||||
{{ end }}`,
|
||||
`{{ range .Alerts -}}
|
||||
*Alert:* {{ .Labels.alertname }}{{ if .Labels.severity }} - {{ .Labels.severity }}{{ end }}
|
||||
|
||||
*Summary:* {{ .Annotations.summary }}
|
||||
*Description:* {{ .Annotations.description }}
|
||||
*RelatedLogs:* {{ .Annotations.related_logs }}
|
||||
*RelatedTraces:* {{ .Annotations.related_traces }}
|
||||
|
||||
*Details:*
|
||||
{{ range .Labels.SortedPairs }} • *{{ .Name }}:* {{ .Value }}
|
||||
{{ end }}
|
||||
{{ end }}`,
|
||||
`{{ range .Alerts -}}
|
||||
*Alert:* {{ .Labels.alertname }}{{ if .Labels.severity }} - {{ .Labels.severity }}{{ end }}
|
||||
|
||||
*Summary:* {{ .Annotations.summary }}
|
||||
*Description:* {{ .Annotations.description }}
|
||||
*RelatedLogs:* {{ if gt (len .Annotations.related_logs) 0 -}} View in <{{ .Annotations.related_logs }}|logs explorer> {{- end}}
|
||||
*RelatedTraces:* {{ if gt (len .Annotations.related_traces) 0 -}} View in <{{ .Annotations.related_traces }}|traces explorer> {{- end}}
|
||||
|
||||
*Details:*
|
||||
{{ range .Labels.SortedPairs }} • *{{ .Name }}:* {{ .Value }}
|
||||
{{ end }}
|
||||
{{ end }}`,
|
||||
`{{ range .Alerts -}}
|
||||
*Alert:* {{ .Labels.alertname }}{{ if .Labels.severity }} - {{ .Labels.severity }}{{ end }}
|
||||
|
||||
*Summary:* {{ .Annotations.summary }}
|
||||
*Description:* {{ .Annotations.description }}
|
||||
{{ template "signoz.relatedLinks.slack" . }}
|
||||
|
||||
*Details:*
|
||||
{{ range .Labels.SortedPairs }} • *{{ .Name }}:* {{ .Value }}
|
||||
{{ end }}
|
||||
{{ end }}`,
|
||||
}
|
||||
|
||||
msteamsSlackSeedLabels = []string{"Alert:", "Summary:", "Description:", "Details:"}
|
||||
|
||||
msteamsControlKeywords = []string{"if", "else", "end", "range", "with", "define", "block", "break", "continue"}
|
||||
|
||||
msteamsActionPattern = regexp.MustCompile(`(?s)\{\{.*?\}\}`)
|
||||
msteamsMaskPattern = regexp.MustCompile(msteamsMaskOpen + `(\d+)` + msteamsMaskClose)
|
||||
msteamsSlackBoldPattern = regexp.MustCompile(`\*([^\s*][^*\n]*)\*`)
|
||||
msteamsSlackLinkPattern = regexp.MustCompile(`<([^<>|\s]+)\|([^<>\n]+)>`)
|
||||
msteamsSlackBulletPattern = regexp.MustCompile(`[ \t]*•[ \t]*`)
|
||||
msteamsIndentPattern = regexp.MustCompile(`(?m)^[ \t]+`)
|
||||
)
|
||||
|
||||
type msteamsTemplateOutcome int
|
||||
|
||||
type migrateMSTeamsDefaultTemplates struct {
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
type msteamsConfigRow struct {
|
||||
bun.BaseModel `bun:"table:alertmanager_config"`
|
||||
|
||||
ID string `bun:"id"`
|
||||
OrgID string `bun:"org_id"`
|
||||
Config string `bun:"config"`
|
||||
}
|
||||
|
||||
type msteamsChannelRow struct {
|
||||
bun.BaseModel `bun:"table:notification_channel"`
|
||||
|
||||
ID string `bun:"id"`
|
||||
OrgID string `bun:"org_id"`
|
||||
Data string `bun:"data"`
|
||||
Spec string `bun:"spec,nullzero"`
|
||||
}
|
||||
|
||||
type msteamsMigrationCounts struct {
|
||||
replaced int
|
||||
converted int
|
||||
custom int
|
||||
failed int
|
||||
}
|
||||
|
||||
func NewMigrateMSTeamsDefaultTemplatesFactory() factory.ProviderFactory[SQLMigration, Config] {
|
||||
return factory.NewProviderFactory(
|
||||
factory.MustNewName("migrate_msteams_templates"),
|
||||
func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {
|
||||
return &migrateMSTeamsDefaultTemplates{logger: ps.Logger}, nil
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func (migration *migrateMSTeamsDefaultTemplates) Register(migrations *migrate.Migrations) error {
|
||||
return migrations.Register(migration.Up, migration.Down)
|
||||
}
|
||||
|
||||
func (migration *migrateMSTeamsDefaultTemplates) Up(ctx context.Context, db *bun.DB) error {
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_ = tx.Rollback()
|
||||
}()
|
||||
|
||||
if err := migration.migrateConfigs(ctx, tx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := migration.migrateChannels(ctx, tx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (migration *migrateMSTeamsDefaultTemplates) Down(context.Context, *bun.DB) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (migration *migrateMSTeamsDefaultTemplates) migrateConfigs(ctx context.Context, tx bun.Tx) error {
|
||||
rows := make([]*msteamsConfigRow, 0)
|
||||
if err := tx.NewSelect().Model(&rows).Scan(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
counts := msteamsMigrationCounts{}
|
||||
for _, row := range rows {
|
||||
cfg := make(map[string]json.RawMessage)
|
||||
if err := json.Unmarshal([]byte(row.Config), &cfg); err != nil {
|
||||
migration.logger.WarnContext(ctx, "skipping alertmanager config with unreadable config", slog.String("config_id", row.ID), errors.Attr(err))
|
||||
counts.failed++
|
||||
continue
|
||||
}
|
||||
|
||||
receiversRaw, ok := cfg["receivers"]
|
||||
if !ok || string(receiversRaw) == "null" {
|
||||
continue
|
||||
}
|
||||
|
||||
receivers := make([]map[string]json.RawMessage, 0)
|
||||
if err := json.Unmarshal(receiversRaw, &receivers); err != nil {
|
||||
migration.logger.WarnContext(ctx, "skipping alertmanager config with unreadable receivers", slog.String("config_id", row.ID), errors.Attr(err))
|
||||
counts.failed++
|
||||
continue
|
||||
}
|
||||
|
||||
changed := false
|
||||
for _, receiver := range receivers {
|
||||
var receiverName string
|
||||
_ = json.Unmarshal(receiver["name"], &receiverName)
|
||||
|
||||
outcomes, receiverChanged, err := migrateMSTeamsReceiver(receiver)
|
||||
if err != nil {
|
||||
migration.logger.WarnContext(ctx, "leaving msteams receiver templates as is", slog.String("config_id", row.ID), slog.String("org_id", row.OrgID), slog.String("receiver", receiverName), errors.Attr(err))
|
||||
counts.failed++
|
||||
continue
|
||||
}
|
||||
for field, outcome := range outcomes {
|
||||
if counts.add(outcome) {
|
||||
migration.logger.InfoContext(ctx, "migrated msteams receiver template", slog.String("config_id", row.ID), slog.String("org_id", row.OrgID), slog.String("receiver", receiverName), slog.String("field", field), slog.String("outcome", outcome.String()))
|
||||
}
|
||||
}
|
||||
changed = changed || receiverChanged
|
||||
}
|
||||
if !changed {
|
||||
continue
|
||||
}
|
||||
|
||||
newReceivers, err := json.Marshal(receivers)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg["receivers"] = newReceivers
|
||||
|
||||
newConfig, err := json.Marshal(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := tx.NewUpdate().
|
||||
Model((*msteamsConfigRow)(nil)).
|
||||
Set("config = ?", string(newConfig)).
|
||||
Set("hash = ?", fmt.Sprintf("%x", md5.Sum(newConfig))).
|
||||
Where("id = ?", row.ID).
|
||||
Exec(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
migration.logger.InfoContext(ctx, "migrated msteams templates on alertmanager configs", slog.Int("total", len(rows)), slog.Int("replaced", counts.replaced), slog.Int("converted", counts.converted), slog.Int("custom", counts.custom), slog.Int("failed", counts.failed))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (migration *migrateMSTeamsDefaultTemplates) migrateChannels(ctx context.Context, tx bun.Tx) error {
|
||||
rows := make([]*msteamsChannelRow, 0)
|
||||
if err := tx.NewSelect().Model(&rows).Where("type = ?", "msteams").Scan(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
counts := msteamsMigrationCounts{}
|
||||
for _, row := range rows {
|
||||
query := tx.NewUpdate().Model((*msteamsChannelRow)(nil)).Where("id = ?", row.ID)
|
||||
|
||||
receiver := make(map[string]json.RawMessage)
|
||||
if err := json.Unmarshal([]byte(row.Data), &receiver); err != nil {
|
||||
migration.logger.WarnContext(ctx, "skipping notification channel with unreadable data", slog.String("org_id", row.OrgID), slog.String("channel_id", row.ID), errors.Attr(err))
|
||||
counts.failed++
|
||||
continue
|
||||
}
|
||||
|
||||
outcomes, changed, err := migrateMSTeamsReceiver(receiver)
|
||||
if err != nil {
|
||||
migration.logger.WarnContext(ctx, "leaving notification channel templates as is", slog.String("org_id", row.OrgID), slog.String("channel_id", row.ID), errors.Attr(err))
|
||||
counts.failed++
|
||||
continue
|
||||
}
|
||||
for field, outcome := range outcomes {
|
||||
if counts.add(outcome) {
|
||||
migration.logger.InfoContext(ctx, "migrated msteams notification channel template", slog.String("org_id", row.OrgID), slog.String("channel_id", row.ID), slog.String("field", field), slog.String("outcome", outcome.String()))
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
newData, err := json.Marshal(receiver)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
query = query.Set("data = ?", string(newData))
|
||||
}
|
||||
|
||||
if row.Spec != "" {
|
||||
spec := make(map[string]json.RawMessage)
|
||||
if err := json.Unmarshal([]byte(row.Spec), &spec); err != nil {
|
||||
migration.logger.WarnContext(ctx, "skipping notification channel spec with unreadable json", slog.String("org_id", row.OrgID), slog.String("channel_id", row.ID), errors.Attr(err))
|
||||
} else {
|
||||
specOutcomes, err := migrateMSTeamsFields(spec)
|
||||
if err != nil {
|
||||
migration.logger.WarnContext(ctx, "leaving notification channel spec templates as is", slog.String("org_id", row.OrgID), slog.String("channel_id", row.ID), errors.Attr(err))
|
||||
}
|
||||
specChanged := false
|
||||
for _, outcome := range specOutcomes {
|
||||
specChanged = specChanged || outcome.rewrites()
|
||||
}
|
||||
if err == nil && specChanged {
|
||||
newSpec, err := json.Marshal(spec)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
query = query.Set("spec = ?", string(newSpec))
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !changed {
|
||||
continue
|
||||
}
|
||||
if _, err := query.Exec(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
migration.logger.InfoContext(ctx, "migrated msteams templates on notification channels", slog.Int("total", len(rows)), slog.Int("replaced", counts.replaced), slog.Int("converted", counts.converted), slog.Int("custom", counts.custom), slog.Int("failed", counts.failed))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (outcome msteamsTemplateOutcome) String() string {
|
||||
switch outcome {
|
||||
case msteamsTemplateReplaced:
|
||||
return "replaced"
|
||||
case msteamsTemplateConverted:
|
||||
return "converted"
|
||||
case msteamsTemplateCustom:
|
||||
return "custom"
|
||||
default:
|
||||
return "unchanged"
|
||||
}
|
||||
}
|
||||
|
||||
func (outcome msteamsTemplateOutcome) rewrites() bool {
|
||||
return outcome == msteamsTemplateReplaced || outcome == msteamsTemplateConverted
|
||||
}
|
||||
|
||||
// add reports whether the outcome is worth a log line of its own.
|
||||
func (counts *msteamsMigrationCounts) add(outcome msteamsTemplateOutcome) bool {
|
||||
switch outcome {
|
||||
case msteamsTemplateReplaced:
|
||||
counts.replaced++
|
||||
case msteamsTemplateConverted:
|
||||
counts.converted++
|
||||
case msteamsTemplateCustom:
|
||||
counts.custom++
|
||||
default:
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// migrateMSTeamsReceiver reports the outcome of the receiver's first msteams notifier, the only one a channel carries, and whether any notifier was rewritten.
|
||||
func migrateMSTeamsReceiver(receiver map[string]json.RawMessage) (map[string]msteamsTemplateOutcome, bool, error) {
|
||||
configsRaw, ok := receiver[msteamsConfigsKey]
|
||||
outcomes := make(map[string]msteamsTemplateOutcome)
|
||||
|
||||
if !ok || string(configsRaw) == "null" {
|
||||
return outcomes, false, nil
|
||||
}
|
||||
|
||||
configs := make([]map[string]json.RawMessage, 0)
|
||||
if err := json.Unmarshal(configsRaw, &configs); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
|
||||
changed := false
|
||||
for i, config := range configs {
|
||||
configOutcomes, err := migrateMSTeamsFields(config)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if i == 0 {
|
||||
outcomes = configOutcomes
|
||||
}
|
||||
for _, outcome := range configOutcomes {
|
||||
changed = changed || outcome.rewrites()
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return outcomes, false, nil
|
||||
}
|
||||
|
||||
newConfigs, err := json.Marshal(configs)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
receiver[msteamsConfigsKey] = newConfigs
|
||||
|
||||
return outcomes, true, nil
|
||||
}
|
||||
|
||||
func migrateMSTeamsFields(object map[string]json.RawMessage) (map[string]msteamsTemplateOutcome, error) {
|
||||
outcomes := make(map[string]msteamsTemplateOutcome, 2)
|
||||
|
||||
for _, field := range []string{msteamsTitleField, msteamsTextField} {
|
||||
raw, ok := object[field]
|
||||
if !ok || string(raw) == "null" {
|
||||
continue
|
||||
}
|
||||
|
||||
var tmpl string
|
||||
if err := json.Unmarshal(raw, &tmpl); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var (
|
||||
migrated string
|
||||
outcome msteamsTemplateOutcome
|
||||
err error
|
||||
)
|
||||
if field == msteamsTitleField {
|
||||
migrated, outcome, err = migrateMSTeamsTitle(tmpl)
|
||||
} else {
|
||||
migrated, outcome, err = migrateMSTeamsText(tmpl)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
outcomes[field] = outcome
|
||||
if !outcome.rewrites() {
|
||||
continue
|
||||
}
|
||||
|
||||
newRaw, err := json.Marshal(migrated)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
object[field] = newRaw
|
||||
}
|
||||
|
||||
return outcomes, nil
|
||||
}
|
||||
|
||||
func migrateMSTeamsTitle(title string) (string, msteamsTemplateOutcome, error) {
|
||||
if isMSTeamsDefaultOrEmpty(title, msteamsDefaultTitle) {
|
||||
return title, msteamsTemplateUnchanged, nil
|
||||
}
|
||||
|
||||
matches, err := matchesAnyMSTeamsTemplate(title, []string{msteamsSlackSeedTitle})
|
||||
if err != nil {
|
||||
return title, msteamsTemplateUnchanged, err
|
||||
}
|
||||
if matches {
|
||||
return msteamsDefaultTitle, msteamsTemplateReplaced, nil
|
||||
}
|
||||
|
||||
return title, msteamsTemplateCustom, nil
|
||||
}
|
||||
|
||||
func migrateMSTeamsText(text string) (string, msteamsTemplateOutcome, error) {
|
||||
if isMSTeamsDefaultOrEmpty(text, msteamsDefaultText) {
|
||||
return text, msteamsTemplateUnchanged, nil
|
||||
}
|
||||
|
||||
matches, err := matchesAnyMSTeamsTemplate(text, msteamsSlackSeedTexts)
|
||||
if err != nil {
|
||||
return text, msteamsTemplateUnchanged, err
|
||||
}
|
||||
if matches {
|
||||
return msteamsDefaultText, msteamsTemplateReplaced, nil
|
||||
}
|
||||
|
||||
// Text already holding a placeholder character cannot be masked safely.
|
||||
if strings.Contains(text, msteamsMaskOpen) || strings.Contains(text, msteamsMaskClose) || !isMSTeamsSlackSeedDerived(text) {
|
||||
return text, msteamsTemplateCustom, nil
|
||||
}
|
||||
|
||||
converted := convertMSTeamsSlackSeed(text)
|
||||
if _, err := normalizeMSTeamsTemplate(converted); err != nil {
|
||||
return text, msteamsTemplateUnchanged, err
|
||||
}
|
||||
|
||||
return converted, msteamsTemplateConverted, nil
|
||||
}
|
||||
|
||||
// isMSTeamsDefaultOrEmpty covers what needs no migration: nothing stored, an upstream marker or the new default itself.
|
||||
func isMSTeamsDefaultOrEmpty(tmpl string, newDefault string) bool {
|
||||
trimmed := strings.TrimSpace(tmpl)
|
||||
|
||||
return trimmed == "" || trimmed == newDefault || strings.HasPrefix(trimmed, `{{ template "msteamsv2.default.`) || strings.HasPrefix(trimmed, `{{ template "msteams.default.`)
|
||||
}
|
||||
|
||||
func matchesAnyMSTeamsTemplate(tmpl string, shipped []string) (bool, error) {
|
||||
normalized, err := normalizeMSTeamsTemplate(tmpl)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
for _, candidate := range shipped {
|
||||
normalizedCandidate, err := normalizeMSTeamsTemplate(candidate)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if normalized == normalizedCandidate {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func isMSTeamsSlackSeedDerived(text string) bool {
|
||||
masked, _ := maskMSTeamsActions(text)
|
||||
|
||||
found := 0
|
||||
for _, match := range findMSTeamsSlackBold(masked) {
|
||||
if slices.Contains(msteamsSlackSeedLabels, masked[match[2]:match[3]]) {
|
||||
found++
|
||||
}
|
||||
}
|
||||
|
||||
return found >= msteamsSlackSeedLabelThreshold
|
||||
}
|
||||
|
||||
// convertMSTeamsSlackSeed rewrites Slack mrkdwn into the markdown a Teams card renders, leaving every {{ }} action as written.
|
||||
func convertMSTeamsSlackSeed(text string) string {
|
||||
text = strings.ReplaceAll(text, msteamsSlackRelatedLinksName, msteamsMarkdownRelatedLinksName)
|
||||
text = strings.ReplaceAll(text, "\r\n", "\n")
|
||||
|
||||
masked, actions := maskMSTeamsActions(text)
|
||||
|
||||
var bolded strings.Builder
|
||||
last := 0
|
||||
for _, match := range findMSTeamsSlackBold(masked) {
|
||||
bolded.WriteString(masked[last:match[0]])
|
||||
fmt.Fprintf(&bolded, "**%s**", masked[match[2]:match[3]])
|
||||
last = match[1]
|
||||
}
|
||||
bolded.WriteString(masked[last:])
|
||||
masked = bolded.String()
|
||||
|
||||
masked = msteamsSlackLinkPattern.ReplaceAllString(masked, "[$2]($1)")
|
||||
masked = msteamsSlackBulletPattern.ReplaceAllString(masked, "- ")
|
||||
masked = msteamsIndentPattern.ReplaceAllString(masked, "")
|
||||
masked = separateMSTeamsParagraphs(masked, actions)
|
||||
|
||||
return msteamsMaskPattern.ReplaceAllStringFunc(masked, func(mask string) string {
|
||||
var index int
|
||||
_, _ = fmt.Sscanf(strings.TrimSuffix(strings.TrimPrefix(mask, msteamsMaskOpen), msteamsMaskClose), "%d", &index)
|
||||
return actions[index]
|
||||
})
|
||||
}
|
||||
|
||||
// maskMSTeamsActions swaps each {{ }} action for a placeholder so text rules can span them, as in *{{ .Name }}:*.
|
||||
func maskMSTeamsActions(text string) (string, []string) {
|
||||
actions := make([]string, 0)
|
||||
|
||||
masked := msteamsActionPattern.ReplaceAllStringFunc(text, func(action string) string {
|
||||
actions = append(actions, action)
|
||||
return fmt.Sprintf("%s%d%s", msteamsMaskOpen, len(actions)-1, msteamsMaskClose)
|
||||
})
|
||||
|
||||
return masked, actions
|
||||
}
|
||||
|
||||
// findMSTeamsSlackBold returns the *bold* spans that are not already part of a **bold** one.
|
||||
func findMSTeamsSlackBold(masked string) [][]int {
|
||||
matches := make([][]int, 0)
|
||||
|
||||
for _, match := range msteamsSlackBoldPattern.FindAllStringSubmatchIndex(masked, -1) {
|
||||
if match[0] > 0 && masked[match[0]-1] == '*' {
|
||||
continue
|
||||
}
|
||||
if match[1] < len(masked) && masked[match[1]] == '*' {
|
||||
continue
|
||||
}
|
||||
if strings.TrimRight(masked[match[2]:match[3]], " \t") != masked[match[2]:match[3]] {
|
||||
continue
|
||||
}
|
||||
matches = append(matches, match)
|
||||
}
|
||||
|
||||
return matches
|
||||
}
|
||||
|
||||
// separateMSTeamsParagraphs puts a blank line between adjacent lines of content, which Teams needs outside a list.
|
||||
func separateMSTeamsParagraphs(masked string, actions []string) string {
|
||||
lines := strings.Split(masked, "\n")
|
||||
|
||||
separated := make([]string, 0, len(lines))
|
||||
for i, line := range lines {
|
||||
separated = append(separated, line)
|
||||
if i == len(lines)-1 {
|
||||
continue
|
||||
}
|
||||
|
||||
content, list := classifyMSTeamsLine(line, actions)
|
||||
nextContent, nextList := classifyMSTeamsLine(lines[i+1], actions)
|
||||
if content && nextContent && (!list || !nextList) {
|
||||
separated = append(separated, "")
|
||||
}
|
||||
}
|
||||
|
||||
return strings.Join(separated, "\n")
|
||||
}
|
||||
|
||||
// classifyMSTeamsLine reports whether a line renders any text and whether that text is a list item.
|
||||
func classifyMSTeamsLine(line string, actions []string) (bool, bool) {
|
||||
rendered := msteamsMaskPattern.ReplaceAllStringFunc(line, func(mask string) string {
|
||||
var index int
|
||||
_, _ = fmt.Sscanf(strings.TrimSuffix(strings.TrimPrefix(mask, msteamsMaskOpen), msteamsMaskClose), "%d", &index)
|
||||
if isMSTeamsControlAction(actions[index]) {
|
||||
return ""
|
||||
}
|
||||
return mask
|
||||
})
|
||||
rendered = strings.TrimSpace(rendered)
|
||||
|
||||
return rendered != "", strings.HasPrefix(rendered, "- ")
|
||||
}
|
||||
|
||||
func isMSTeamsControlAction(action string) bool {
|
||||
inner := strings.TrimSpace(strings.Trim(strings.TrimSuffix(strings.TrimPrefix(action, "{{"), "}}"), "-"))
|
||||
if strings.HasPrefix(inner, "/*") {
|
||||
return true
|
||||
}
|
||||
|
||||
keyword, _, _ := strings.Cut(inner, " ")
|
||||
|
||||
return slices.Contains(msteamsControlKeywords, keyword)
|
||||
}
|
||||
|
||||
// normalizeMSTeamsTemplate re-emits a parsed template with whitespace collapsed, so two templates that differ only in spacing compare equal.
|
||||
func normalizeMSTeamsTemplate(tmpl string) (string, error) {
|
||||
tree := parse.New("msteams")
|
||||
tree.Mode = parse.SkipFuncCheck
|
||||
parsed, err := tree.Parse(tmpl, "{{", "}}", map[string]*parse.Tree{})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var builder strings.Builder
|
||||
writeNormalizedMSTeamsNode(&builder, parsed.Root)
|
||||
|
||||
return builder.String(), nil
|
||||
}
|
||||
|
||||
func writeNormalizedMSTeamsNode(builder *strings.Builder, node parse.Node) {
|
||||
switch node := node.(type) {
|
||||
case *parse.ListNode:
|
||||
if node == nil {
|
||||
return
|
||||
}
|
||||
for _, child := range node.Nodes {
|
||||
writeNormalizedMSTeamsNode(builder, child)
|
||||
}
|
||||
case *parse.TextNode:
|
||||
builder.WriteString(strings.Join(strings.Fields(string(node.Text)), " "))
|
||||
builder.WriteString("|")
|
||||
case *parse.IfNode:
|
||||
writeNormalizedMSTeamsBranch(builder, "if", &node.BranchNode)
|
||||
case *parse.RangeNode:
|
||||
writeNormalizedMSTeamsBranch(builder, "range", &node.BranchNode)
|
||||
case *parse.WithNode:
|
||||
writeNormalizedMSTeamsBranch(builder, "with", &node.BranchNode)
|
||||
default:
|
||||
builder.WriteString(node.String())
|
||||
}
|
||||
}
|
||||
|
||||
func writeNormalizedMSTeamsBranch(builder *strings.Builder, keyword string, branch *parse.BranchNode) {
|
||||
fmt.Fprintf(builder, "{{%s %s}}", keyword, branch.Pipe.String())
|
||||
writeNormalizedMSTeamsNode(builder, branch.List)
|
||||
if branch.ElseList != nil {
|
||||
builder.WriteString("{{else}}")
|
||||
writeNormalizedMSTeamsNode(builder, branch.ElseList)
|
||||
}
|
||||
builder.WriteString("{{end}}")
|
||||
}
|
||||
@@ -6,11 +6,29 @@ import (
|
||||
"github.com/prometheus/alertmanager/config"
|
||||
)
|
||||
|
||||
// The text is markdown, which a Teams Adaptive Card TextBlock renders as is.
|
||||
const (
|
||||
DefaultMSTeamsTitleTemplate = `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}`
|
||||
|
||||
DefaultMSTeamsTextTemplate = `{{ range .Alerts -}}
|
||||
**Alert:** {{ .Labels.alertname }}{{ if .Labels.severity }} ({{ .Labels.severity }}){{ end }} - {{ .Status }}
|
||||
|
||||
{{ if .Annotations.summary }}**Summary:** {{ .Annotations.summary }}
|
||||
|
||||
{{ end }}{{ if .Annotations.description }}**Description:** {{ .Annotations.description }}
|
||||
|
||||
{{ end }}{{ template "signoz.relatedLinks.markdown" . }}{{ with (.Labels.Remove (stringSlice "alertname" "severity" "ruleId" "ruleSource")).SortedPairs }}**Details:**
|
||||
|
||||
{{ range . }}- **{{ .Name }}:** {{ .Value }}
|
||||
{{ end }}
|
||||
{{ end }}{{ end }}`
|
||||
)
|
||||
|
||||
type ChannelMSTeamsConfig struct {
|
||||
SendResolved *bool `json:"sendResolved,omitempty" description:"Also notify when the alert resolves. Defaults to true."`
|
||||
WebhookURL string `json:"webhookUrl" required:"true" format:"password" description:"The Teams incoming webhook URL. A secret; returned by create, update and fetch by ID, never by list."`
|
||||
Title valuer.UnsetOrNonEmptyString `json:"title,omitzero" description:"Alertmanager template for the card title; defaults to the Alertmanager Teams default."`
|
||||
Text valuer.UnsetOrNonEmptyString `json:"text,omitzero" description:"Alertmanager template for the card body; defaults to the Alertmanager Teams default."`
|
||||
Title valuer.UnsetOrNonEmptyString `json:"title,omitzero" description:"Alertmanager template for the card title; defaults to the SigNoz Teams default."`
|
||||
Text valuer.UnsetOrNonEmptyString `json:"text,omitzero" description:"Alertmanager template for the card body, rendered as Teams markdown; defaults to the SigNoz Teams default."`
|
||||
}
|
||||
|
||||
func (c *ChannelMSTeamsConfig) UnmarshalJSON(data []byte) error {
|
||||
|
||||
@@ -2,6 +2,7 @@ package alertmanagertypes
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"net/url"
|
||||
|
||||
tmplhtml "html/template"
|
||||
@@ -42,17 +43,19 @@ func FromGlobs(paths []string) (*alertmanagertemplate.Template, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := t.Parse(bytes.NewReader([]byte(`
|
||||
if err := t.Parse(bytes.NewReader([]byte(fmt.Sprintf(`
|
||||
{{ define "__ruleIdPath" }}{{- $isTestAlert := "" -}}{{- range .CommonLabels.SortedPairs -}}{{- if eq .Name "testalert" -}}{{- if eq .Value "true" -}}{{- $isTestAlert = "true" -}}{{- end -}}{{- end -}}{{- end -}}{{- range .CommonLabels.SortedPairs -}}{{- if eq .Name "ruleId" -}}{{- if ne .Value "" -}}/edit?ruleId={{ .Value | urlescape }}{{- if $isTestAlert -}}&isTestAlert=true{{- end -}}{{- end -}}{{- end -}}{{- end -}}{{- end }}
|
||||
{{ define "__alertmanagerURL" }}{{ .ExternalURL }}/alerts{{ template "__ruleIdPath" . }}{{ end }}
|
||||
{{ define "msteamsv2.default.titleLink" }}{{ template "__alertmanagerURL" . }}{{ end }}
|
||||
{{ define "msteamsv2.default.title" }}%s{{ end }}
|
||||
{{ define "msteamsv2.default.text" }}%s{{ end }}
|
||||
{{ define "signoz.relatedLinks.slack" }}{{ range $i, $link := relatedLinks . }}{{ if $i }} · {{ end }}<{{ $link.URL }}|{{ $link.Label }}>{{ end }}{{ end }}
|
||||
{{ define "signoz.relatedLinks.markdown" }}{{ range relatedLinks . }}[{{ .Label }}]({{ .URL }})
|
||||
|
||||
{{ end }}{{ end }}
|
||||
{{ define "signoz.relatedLinks.html" }}{{ range relatedLinks . }}<a href="{{ .URL | html }}">{{ .Label | html }}</a>
|
||||
{{ end }}{{ end }}
|
||||
`))); err != nil {
|
||||
`, DefaultMSTeamsTitleTemplate, DefaultMSTeamsTextTemplate)))); err != nil {
|
||||
return nil, errors.WrapInternalf(err, errors.CodeInternal, "error parsing alertmanager templates")
|
||||
}
|
||||
|
||||
|
||||
@@ -314,3 +314,84 @@ func TestFromGlobsRelatedLinksHTML(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFromGlobsMSTeamsDefaults(t *testing.T) {
|
||||
tmpl, err := FromGlobs([]string{})
|
||||
require.NoError(t, err)
|
||||
tmpl.ExternalURL = &url.URL{Scheme: "http", Host: "localhost:8080"}
|
||||
|
||||
firing := time.Now().Add(time.Hour)
|
||||
resolved := time.Now().Add(-time.Minute)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
template string
|
||||
alerts []*types.Alert
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "Title_Firing_CountAndAlertName",
|
||||
template: `{{ template "msteamsv2.default.title" . }}`,
|
||||
alerts: []*types.Alert{
|
||||
{Alert: model.Alert{Labels: model.LabelSet{"alertname": "High CPU"}, EndsAt: firing}},
|
||||
},
|
||||
expected: "[FIRING:1] High CPU",
|
||||
},
|
||||
{
|
||||
name: "Title_Resolved_NoCount",
|
||||
template: `{{ template "msteamsv2.default.title" . }}`,
|
||||
alerts: []*types.Alert{
|
||||
{Alert: model.Alert{Labels: model.LabelSet{"alertname": "Disk Full"}, EndsAt: resolved}},
|
||||
},
|
||||
expected: "[RESOLVED] Disk Full",
|
||||
},
|
||||
{
|
||||
name: "Text_AllFields_HidesRuleLabels",
|
||||
template: `{{ template "msteamsv2.default.text" . }}`,
|
||||
alerts: []*types.Alert{
|
||||
{Alert: model.Alert{
|
||||
Labels: model.LabelSet{
|
||||
"alertname": "Error Rate", "severity": "critical", "ruleId": "0199051c-f374-71f7-a340-ec79ad81e70f",
|
||||
"ruleSource": "http://localhost:8080/alerts/overview?ruleId=0199051c", "service.name": "checkout",
|
||||
},
|
||||
Annotations: model.LabelSet{
|
||||
"summary": "errors are up", "description": "error rate crossed 5%",
|
||||
"related_logs": "https://signoz.io/logs/logs-explorer?f=6", "related_traces": "https://signoz.io/traces-explorer?f=6",
|
||||
},
|
||||
EndsAt: firing,
|
||||
}},
|
||||
},
|
||||
expected: "**Alert:** Error Rate (critical) - firing\n\n**Summary:** errors are up\n\n**Description:** error rate crossed 5%\n\n" +
|
||||
"[View Related Logs](https://signoz.io/logs/logs-explorer?f=6)\n\n[View Related Traces](https://signoz.io/traces-explorer?f=6)\n\n" +
|
||||
"**Details:**\n\n- **service.name:** checkout\n\n",
|
||||
},
|
||||
{
|
||||
name: "Text_NoAnnotationsNoExtraLabels_AlertLineOnly",
|
||||
template: `{{ template "msteamsv2.default.text" . }}`,
|
||||
alerts: []*types.Alert{
|
||||
{Alert: model.Alert{Labels: model.LabelSet{"alertname": "Queue Lag", "ruleId": "01a10b3d-e55d-75e3-aa44-8d73f1d969d7"}, EndsAt: resolved}},
|
||||
},
|
||||
expected: "**Alert:** Queue Lag - resolved\n\n",
|
||||
},
|
||||
{
|
||||
name: "Text_TwoAlerts_OneBlockEach",
|
||||
template: `{{ template "msteamsv2.default.text" . }}`,
|
||||
alerts: []*types.Alert{
|
||||
{Alert: model.Alert{Labels: model.LabelSet{"alertname": "Pod Restarts", "pod": "api-1"}, EndsAt: firing}},
|
||||
{Alert: model.Alert{Labels: model.LabelSet{"alertname": "Pod Restarts", "pod": "api-2"}, EndsAt: resolved}},
|
||||
},
|
||||
expected: "**Alert:** Pod Restarts - firing\n\n**Details:**\n\n- **pod:** api-1\n\n" +
|
||||
"**Alert:** Pod Restarts - resolved\n\n**Details:**\n\n- **pod:** api-2\n\n",
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
data := tmpl.Data("__receiver", model.LabelSet{}, testCase.alerts...)
|
||||
|
||||
got, err := tmpl.ExecuteTextString(testCase.template, data)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testCase.expected, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ type QueryBuilderQuery[T any] struct {
|
||||
|
||||
Signal telemetrytypes.Signal `json:"signal,omitempty" description:"The telemetry signal to query: traces, logs or metrics. It selects the aggregation shape and is required for builder_query."`
|
||||
|
||||
Source telemetrytypes.Source `json:"source" description:"The data source within the signal. Set to meter for Cost Meter metrics; leave empty for regular telemetry."`
|
||||
Source telemetrytypes.Source `json:"source" description:"The data source within the signal. Set to meter for Cost Meter metrics or audit for audit logs; leave empty for regular telemetry."`
|
||||
|
||||
Aggregations []T `json:"aggregations,omitzero" description:"The aggregations to compute, one result per entry. Traces and logs take expressions such as count() or p99(duration_nano); metrics take a metricName with time and space aggregations. Omit for raw requests."`
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ var (
|
||||
SourceMetrics = Source{valuer.NewString("metrics")}
|
||||
SourceMeter = Source{valuer.NewString("meter")}
|
||||
SourceAIObservability = Source{valuer.NewString("ai_observability")}
|
||||
SourceAudit = Source{valuer.NewString("audit")}
|
||||
)
|
||||
|
||||
type SavedView struct {
|
||||
@@ -36,7 +37,7 @@ type SavedView struct {
|
||||
types.UserAuditable
|
||||
OrgID string `json:"-"`
|
||||
Name string `json:"name" description:"The machine name of the view, a DNS-1123 label unique within the organization. Immutable after creation."`
|
||||
Source Source `json:"source" description:"The explorer page the view belongs to: traces, logs, metrics, meter or ai_observability."`
|
||||
Source Source `json:"source" description:"The explorer page the view belongs to: traces, logs, metrics, meter, ai_observability or audit."`
|
||||
SchemaVersion SchemaVersion `json:"schemaVersion" required:"true" description:"The version of the spec shape. The only accepted value is v2."`
|
||||
Spec SavedViewSpec `json:"spec" required:"true" description:"The display name, panel type, request type, queries and column selection of the view."`
|
||||
}
|
||||
@@ -92,19 +93,19 @@ func NewStorableSavedView(view *SavedView) *StorableSavedView {
|
||||
type PostableSavedView struct {
|
||||
Name string `json:"name" description:"The machine name of the view, a DNS-1123 label (lowercase letters, digits and hyphens, at most 63 characters) unique within the organization. Required unless generateName is true, in which case it must be empty."`
|
||||
GenerateName bool `json:"generateName" description:"When true the server derives name from spec.displayName and appends a random suffix. Defaults to false."`
|
||||
Source Source `json:"source" required:"true" description:"The explorer page the view belongs to: traces, logs, metrics, meter or ai_observability. Builder queries inside spec must use the matching signal; meter views use signal metrics with source meter."`
|
||||
Source Source `json:"source" required:"true" description:"The explorer page the view belongs to: traces, logs, metrics, meter, ai_observability or audit. Builder queries inside spec must use the matching signal; meter views use signal metrics with source meter, and audit views use signal logs with source audit."`
|
||||
SchemaVersion SchemaVersion `json:"schemaVersion" required:"true" description:"The version of the spec shape. The only accepted value is v2."`
|
||||
Spec SavedViewSpec `json:"spec" required:"true" description:"The display name, panel type, request type, queries and column selection of the view."`
|
||||
}
|
||||
|
||||
type UpdatableSavedView struct {
|
||||
Source Source `json:"source" required:"true" description:"The explorer page the view belongs to: traces, logs, metrics, meter or ai_observability. The machine name cannot be changed; it is identified by the id in the path."`
|
||||
Source Source `json:"source" required:"true" description:"The explorer page the view belongs to: traces, logs, metrics, meter, ai_observability or audit. The machine name cannot be changed; it is identified by the id in the path."`
|
||||
SchemaVersion SchemaVersion `json:"schemaVersion" required:"true" description:"The version of the spec shape. The only accepted value is v2."`
|
||||
Spec SavedViewSpec `json:"spec" required:"true" description:"The full replacement spec. Fields left out are reset, not preserved."`
|
||||
}
|
||||
|
||||
type ListSavedViewsParams struct {
|
||||
Source Source `query:"source" description:"Returns only the views of this explorer page: traces, logs, metrics, meter or ai_observability. Defaults to every source."`
|
||||
Source Source `query:"source" description:"Returns only the views of this explorer page: traces, logs, metrics, meter, ai_observability or audit. Defaults to every source."`
|
||||
Name string `query:"name" description:"Returns only the view with this exact machine name."`
|
||||
}
|
||||
|
||||
@@ -119,12 +120,13 @@ func (Source) Enum() []any {
|
||||
SourceMetrics,
|
||||
SourceMeter,
|
||||
SourceAIObservability,
|
||||
SourceAudit,
|
||||
}
|
||||
}
|
||||
|
||||
func (s Source) Validate() error {
|
||||
switch s {
|
||||
case SourceTraces, SourceLogs, SourceMetrics, SourceMeter, SourceAIObservability:
|
||||
case SourceTraces, SourceLogs, SourceMetrics, SourceMeter, SourceAIObservability, SourceAudit:
|
||||
return nil
|
||||
default:
|
||||
return errors.NewInvalidInputf(ErrCodeSavedViewInvalidInput, "invalid source: %s", s.StringValue())
|
||||
|
||||
@@ -40,6 +40,7 @@ func TestSourceValidate(t *testing.T) {
|
||||
{name: "metrics", source: SourceMetrics},
|
||||
{name: "meter", source: SourceMeter},
|
||||
{name: "ai_observability", source: SourceAIObservability},
|
||||
{name: "Audit_Valid", source: SourceAudit},
|
||||
{name: "unknown is rejected", source: Source{valuer.NewString("bogus")}, expectError: true},
|
||||
}
|
||||
|
||||
@@ -293,13 +294,15 @@ func TestNewStatsFromStorableSavedViews(t *testing.T) {
|
||||
{Source: SourceLogs},
|
||||
{Source: SourceLogs},
|
||||
{Source: SourceTraces},
|
||||
{Source: SourceAudit},
|
||||
}
|
||||
|
||||
stats := NewStatsFromStorableSavedViews(storables)
|
||||
|
||||
assert.Equal(t, int64(3), stats["savedview.count"])
|
||||
assert.Equal(t, int64(4), stats["savedview.count"])
|
||||
assert.Equal(t, int64(2), stats["savedview.source.logs.count"])
|
||||
assert.Equal(t, int64(1), stats["savedview.source.traces.count"])
|
||||
assert.Equal(t, int64(1), stats["savedview.source.audit.count"])
|
||||
assert.NotContains(t, stats, "savedview.source.metrics.count")
|
||||
}
|
||||
|
||||
|
||||
@@ -188,6 +188,39 @@ func TestSavedViewSpecValidate(t *testing.T) {
|
||||
},
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "AuditList_NoAggregation_Valid",
|
||||
spec: SavedViewSpec{
|
||||
DisplayName: "Audit Events",
|
||||
PanelType: PanelTypeList,
|
||||
RequestType: qbtypes.RequestTypeRaw,
|
||||
Queries: []qbtypes.QueryEnvelope{{
|
||||
Type: qbtypes.QueryTypeBuilder,
|
||||
Spec: qbtypes.QueryBuilderQuery[qbtypes.LogAggregation]{
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
Source: telemetrytypes.SourceAudit,
|
||||
},
|
||||
}},
|
||||
},
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "AuditGraph_WithAggregation_Valid",
|
||||
spec: SavedViewSpec{
|
||||
DisplayName: "Audit Event Rate",
|
||||
PanelType: PanelTypeGraph,
|
||||
RequestType: qbtypes.RequestTypeTimeSeries,
|
||||
Queries: []qbtypes.QueryEnvelope{{
|
||||
Type: qbtypes.QueryTypeBuilder,
|
||||
Spec: qbtypes.QueryBuilderQuery[qbtypes.LogAggregation]{
|
||||
Signal: telemetrytypes.SignalLogs,
|
||||
Source: telemetrytypes.SourceAudit,
|
||||
Aggregations: []qbtypes.LogAggregation{{Expression: "count()"}},
|
||||
},
|
||||
}},
|
||||
},
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "graph panel query with no aggregation is still rejected",
|
||||
spec: SavedViewSpec{
|
||||
|
||||
12
tests/fixtures/notification_channel.py
vendored
12
tests/fixtures/notification_channel.py
vendored
@@ -110,8 +110,16 @@ msteams_default_config = {
|
||||
"msteamsv2_configs": [
|
||||
{
|
||||
"webhook_url": "msteams/webhook_url", # base_url configured on runtime
|
||||
"title": '[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }} for {{ .CommonLabels.job }}\n {{- if gt (len .CommonLabels) (len .GroupLabels) -}}\n {{" "}}(\n {{- with .CommonLabels.Remove .GroupLabels.Names }}\n {{- range $index, $label := .SortedPairs -}}\n {{ if $index }}, {{ end }}\n {{- $label.Name }}="{{ $label.Value -}}"\n {{- end }}\n {{- end -}}\n )\n {{- end }}',
|
||||
"text": '{{ range .Alerts -}}\r\n *Alert:* {{ .Labels.alertname }}{{ if .Labels.severity }} - {{ .Labels.severity }}{{ end }}\r\n\r\n *Summary:* {{ .Annotations.summary }}\r\n *Description:* {{ .Annotations.description }}\r\n {{ template "signoz.relatedLinks.slack" . }}\r\n\r\n *Details:*\r\n {{ range .Labels.SortedPairs -}}\r\n {{- if ne .Name "ruleId" -}}\r\n \u2022 *{{ .Name }}:* {{ .Value }}\r\n {{ end -}}\r\n {{ end -}}\r\n{{ end }}',
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
msteams_custom_text_config = {
|
||||
"msteamsv2_configs": [
|
||||
{
|
||||
"webhook_url": "msteams/custom_text_webhook_url", # base_url configured on runtime
|
||||
"title": "Teams custom title: {{ .CommonLabels.alertname }}",
|
||||
"text": "Teams custom description for {{ range .Alerts }}{{ .Labels.alertname }} ({{ .Labels.severity }}){{ end }}",
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
58
tests/integration/testdata/alertmanager/rule_body_template_rule.json
vendored
Normal file
58
tests/integration/testdata/alertmanager/rule_body_template_rule.json
vendored
Normal file
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"alert": "rule_body_template",
|
||||
"ruleType": "threshold_rule",
|
||||
"alertType": "METRIC_BASED_ALERT",
|
||||
"condition": {
|
||||
"thresholds": {
|
||||
"kind": "basic",
|
||||
"spec": [
|
||||
{
|
||||
"name": "critical",
|
||||
"target": 10,
|
||||
"matchType": "at_least_once",
|
||||
"op": "above",
|
||||
"channels": [
|
||||
"test channel"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"compositeQuery": {
|
||||
"queryType": "clickhouse_sql",
|
||||
"panelType": "graph",
|
||||
"queries": [
|
||||
{
|
||||
"type": "clickhouse_sql",
|
||||
"spec": {
|
||||
"name": "A",
|
||||
"query": "WITH __temporal_aggregation_cte AS (\n SELECT \n fingerprint, \n toStartOfInterval(toDateTime(intDiv(unix_milli, 1000)), toIntervalSecond(60)) AS ts, \n avg(value) AS per_series_value \n FROM signoz_metrics.distributed_samples_v4 AS points \n INNER JOIN (\n SELECT fingerprint \n FROM signoz_metrics.time_series_v4 \n WHERE metric_name IN ('request_total_threshold_above_at_least_once') \n AND LOWER(temporality) LIKE LOWER('cumulative') \n GROUP BY fingerprint\n ) AS filtered_time_series ON points.fingerprint = filtered_time_series.fingerprint \n WHERE metric_name IN ('request_total_threshold_above_at_least_once') \n AND unix_milli >= $start_timestamp_ms \n AND unix_milli < $end_timestamp_ms \n GROUP BY fingerprint, ts \n ORDER BY fingerprint, ts\n), \n__spatial_aggregation_cte AS (\n SELECT \n ts, \n sum(per_series_value) AS value \n FROM __temporal_aggregation_cte \n WHERE isNaN(per_series_value) = 0 \n GROUP BY ts\n) \nSELECT * FROM __spatial_aggregation_cte \nORDER BY ts"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"selectedQueryName": "A"
|
||||
},
|
||||
"evaluation": {
|
||||
"kind": "rolling",
|
||||
"spec": {
|
||||
"evalWindow": "5m0s",
|
||||
"frequency": "15s"
|
||||
}
|
||||
},
|
||||
"labels": {},
|
||||
"annotations": {
|
||||
"description": "This alert is fired when the defined metric (current value: {{$value}}) crosses the threshold ({{$threshold}})",
|
||||
"summary": "This alert is fired when the defined metric (current value: {{$value}}) crosses the threshold ({{$threshold}})",
|
||||
"_body_template": "Rule body for $alertname at severity $severity"
|
||||
},
|
||||
"notificationSettings": {
|
||||
"groupBy": [],
|
||||
"usePolicy": false,
|
||||
"renotify": {
|
||||
"enabled": false,
|
||||
"interval": "30m",
|
||||
"alertStates": []
|
||||
}
|
||||
},
|
||||
"schemaVersion": "v2alpha1"
|
||||
}
|
||||
@@ -19,6 +19,7 @@ from fixtures.logger import setup_logger
|
||||
from fixtures.maildev import delete_all_mails
|
||||
from fixtures.notification_channel import (
|
||||
email_default_config,
|
||||
msteams_custom_text_config,
|
||||
msteams_default_config,
|
||||
opsgenie_default_config,
|
||||
pagerduty_default_config,
|
||||
@@ -92,7 +93,7 @@ NOTIFIERS_TEST = [
|
||||
"body": [
|
||||
{
|
||||
"type": "TextBlock",
|
||||
"text": "Alerts",
|
||||
"text": "[FIRING:1] threshold_above_at_least_once",
|
||||
"weight": "Bolder",
|
||||
"size": "Medium",
|
||||
"wrap": True,
|
||||
@@ -100,35 +101,13 @@ NOTIFIERS_TEST = [
|
||||
},
|
||||
{
|
||||
"type": "TextBlock",
|
||||
"text": "Labels",
|
||||
"weight": "Bolder",
|
||||
"size": "Medium",
|
||||
},
|
||||
{
|
||||
"type": "FactSet",
|
||||
"text": "",
|
||||
"facts": [
|
||||
{
|
||||
"title": "threshold.name",
|
||||
"value": "critical",
|
||||
}
|
||||
],
|
||||
},
|
||||
{
|
||||
"type": "TextBlock",
|
||||
"text": "Annotations",
|
||||
"weight": "Bolder",
|
||||
"size": "Medium",
|
||||
},
|
||||
{
|
||||
"type": "FactSet",
|
||||
"text": "",
|
||||
"facts": [
|
||||
{
|
||||
"title": "description",
|
||||
"value": "This alert is fired when the defined metric (current value: 15) crosses the threshold (10)",
|
||||
},
|
||||
],
|
||||
"text": re.compile(
|
||||
r"^\*\*Alert:\*\* threshold_above_at_least_once \(critical\) - firing\n\n"
|
||||
r"\*\*Summary:\*\* This alert is fired when the defined metric \(current value: 15\) crosses the threshold \(10\)\n\n"
|
||||
r"\*\*Description:\*\* This alert is fired when the defined metric \(current value: 15\) crosses the threshold \(10\)\n\n"
|
||||
r"\*\*Details:\*\*\n\n- \*\*threshold\.name:\*\* critical"
|
||||
),
|
||||
"wrap": True,
|
||||
},
|
||||
],
|
||||
"msteams": {"width": "full"},
|
||||
@@ -147,6 +126,98 @@ NOTIFIERS_TEST = [
|
||||
],
|
||||
),
|
||||
),
|
||||
types.AlertManagerNotificationTestCase(
|
||||
name="msteams_notifier_custom_channel_text",
|
||||
rule_path="ruler/test_scenarios/threshold_above_at_least_once/rule.json",
|
||||
alert_data=[
|
||||
types.AlertData(
|
||||
type="metrics",
|
||||
data_path="ruler/test_scenarios/threshold_above_at_least_once/alert_data.jsonl",
|
||||
),
|
||||
],
|
||||
channel_config=msteams_custom_text_config,
|
||||
notification_expectation=types.AMNotificationExpectation(
|
||||
should_notify=True,
|
||||
wait_time_seconds=120,
|
||||
notification_validations=[
|
||||
types.NotificationValidation(
|
||||
destination_type="webhook",
|
||||
validation_data={
|
||||
"path": "/msteams/custom_text_webhook_url",
|
||||
"json_body": {
|
||||
"type": "message",
|
||||
"attachments": [
|
||||
{
|
||||
"contentType": "application/vnd.microsoft.card.adaptive",
|
||||
"content": {
|
||||
"type": "AdaptiveCard",
|
||||
"body": [
|
||||
{
|
||||
"type": "TextBlock",
|
||||
"text": "Teams custom title: threshold_above_at_least_once",
|
||||
"color": "Attention",
|
||||
},
|
||||
{
|
||||
"type": "TextBlock",
|
||||
"text": "Teams custom description for threshold_above_at_least_once (critical)",
|
||||
"wrap": True,
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
],
|
||||
},
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
types.AlertManagerNotificationTestCase(
|
||||
name="msteams_notifier_rule_body_template",
|
||||
rule_path="alertmanager/rule_body_template_rule.json",
|
||||
alert_data=[
|
||||
types.AlertData(
|
||||
type="metrics",
|
||||
data_path="ruler/test_scenarios/threshold_above_at_least_once/alert_data.jsonl",
|
||||
),
|
||||
],
|
||||
channel_config=msteams_custom_text_config,
|
||||
notification_expectation=types.AMNotificationExpectation(
|
||||
should_notify=True,
|
||||
wait_time_seconds=120,
|
||||
notification_validations=[
|
||||
types.NotificationValidation(
|
||||
destination_type="webhook",
|
||||
validation_data={
|
||||
"path": "/msteams/custom_text_webhook_url",
|
||||
"json_body": {
|
||||
"type": "message",
|
||||
"attachments": [
|
||||
{
|
||||
"contentType": "application/vnd.microsoft.card.adaptive",
|
||||
"content": {
|
||||
"type": "AdaptiveCard",
|
||||
"body": [
|
||||
{
|
||||
"type": "TextBlock",
|
||||
"text": "Teams custom title: rule_body_template",
|
||||
},
|
||||
{
|
||||
"type": "TextBlock",
|
||||
"text": "Rule body for rule_body_template at severity critical",
|
||||
"wrap": True,
|
||||
"color": "Attention",
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
],
|
||||
},
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
types.AlertManagerNotificationTestCase(
|
||||
name="pagerduty_notifier_default_templating",
|
||||
rule_path="ruler/test_scenarios/threshold_above_at_least_once/rule.json",
|
||||
|
||||
@@ -55,10 +55,18 @@ CONTENT_TEMPLATING_TEST = [
|
||||
"content": {
|
||||
"type": "AdaptiveCard",
|
||||
"body": [
|
||||
{
|
||||
"type": "TextBlock",
|
||||
"text": "[FIRING:1] content_templating_metrics",
|
||||
},
|
||||
{
|
||||
"type": "TextBlock",
|
||||
"text": re.compile(
|
||||
r'\[FIRING:1\] content_templating_metrics for \(alertname="content_templating_metrics", container="checkout", namespace="production", node="ip-10-0-1-23", pod="checkout-7d9c8b5f4-x2k9p", ruleSource="http://localhost:8080/alerts/overview\?ruleId=[0-9a-f-]+", severity="critical", threshold\.name="critical"\)'
|
||||
r"^\*\*Alert:\*\* content_templating_metrics \(critical\) - firing\n\n"
|
||||
r"\*\*Summary:\*\* High container memory in production/checkout-7d9c8b5f4-x2k9p\n\n"
|
||||
r"\*\*Description:\*\* Container checkout in pod checkout-7d9c8b5f4-x2k9p \(production\) exceeded memory threshold\n\n"
|
||||
r"\*\*Details:\*\*\n\n- \*\*container:\*\* checkout\n- \*\*namespace:\*\* production\n"
|
||||
r"- \*\*node:\*\* ip-10-0-1-23\n- \*\*pod:\*\* checkout-7d9c8b5f4-x2k9p\n- \*\*threshold\.name:\*\* critical$"
|
||||
),
|
||||
},
|
||||
],
|
||||
|
||||
@@ -652,6 +652,126 @@ def test_ai_observability_view_with_builder_ai_query_roundtrip(
|
||||
)
|
||||
|
||||
|
||||
def test_audit_view_roundtrip(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
headers = {"Authorization": f"Bearer {token}"}
|
||||
|
||||
response = requests.post(
|
||||
signoz.self.host_configs["8080"].get(BASE_URL),
|
||||
json={
|
||||
"name": "audit-dashboard-events",
|
||||
"generateName": False,
|
||||
"source": "audit",
|
||||
"schemaVersion": "v2",
|
||||
"spec": {
|
||||
"displayName": "Audit dashboard events",
|
||||
"requestType": "raw",
|
||||
"queries": [
|
||||
{
|
||||
"type": "builder_query",
|
||||
"spec": {
|
||||
"name": "A",
|
||||
"signal": "logs",
|
||||
"source": "audit",
|
||||
"filter": {"expression": "signoz.resource.kind = 'dashboard'"},
|
||||
"order": [
|
||||
{"key": {"name": "timestamp"}, "direction": "desc"},
|
||||
{"key": {"name": "id"}, "direction": "desc"},
|
||||
],
|
||||
"limit": 100,
|
||||
},
|
||||
}
|
||||
],
|
||||
"selectedFields": [
|
||||
{
|
||||
"name": "event_name",
|
||||
"signal": "logs",
|
||||
"fieldContext": "log",
|
||||
"fieldDataType": "string",
|
||||
}
|
||||
],
|
||||
"panelType": "list",
|
||||
"display": {"maxLines": 2, "fontSize": "small", "format": "list", "color": ""},
|
||||
},
|
||||
},
|
||||
headers=headers,
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.CREATED, response.text
|
||||
view_id = response.json()["data"]["id"]
|
||||
|
||||
try:
|
||||
response = requests.get(
|
||||
signoz.self.host_configs["8080"].get(f"{BASE_URL}/{view_id}"),
|
||||
headers=headers,
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
got = response.json()["data"]
|
||||
assert got["source"] == "audit"
|
||||
assert got["spec"]["queries"][0]["spec"]["signal"] == "logs"
|
||||
assert got["spec"]["queries"][0]["spec"]["source"] == "audit"
|
||||
|
||||
response = requests.get(
|
||||
signoz.self.host_configs["8080"].get(BASE_URL),
|
||||
params={"source": "audit"},
|
||||
headers=headers,
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
assert {v["name"] for v in response.json()["data"]} == {"audit-dashboard-events"}
|
||||
|
||||
response = requests.put(
|
||||
signoz.self.host_configs["8080"].get(f"{BASE_URL}/{view_id}"),
|
||||
json={
|
||||
"source": "audit",
|
||||
"schemaVersion": "v2",
|
||||
"spec": {
|
||||
"displayName": "Audit dashboard events updated",
|
||||
"requestType": "time_series",
|
||||
"queries": [
|
||||
{
|
||||
"type": "builder_query",
|
||||
"spec": {
|
||||
"name": "A",
|
||||
"signal": "logs",
|
||||
"source": "audit",
|
||||
"aggregations": [{"expression": "count()"}],
|
||||
},
|
||||
}
|
||||
],
|
||||
"selectedFields": [],
|
||||
"panelType": "graph",
|
||||
"display": {"maxLines": 0, "fontSize": "", "format": "", "color": ""},
|
||||
},
|
||||
},
|
||||
headers=headers,
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
|
||||
|
||||
response = requests.get(
|
||||
signoz.self.host_configs["8080"].get(f"{BASE_URL}/{view_id}"),
|
||||
headers=headers,
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
updated = response.json()["data"]
|
||||
assert updated["source"] == "audit"
|
||||
assert updated["spec"]["displayName"] == "Audit dashboard events updated"
|
||||
assert updated["spec"]["queries"][0]["spec"]["source"] == "audit"
|
||||
finally:
|
||||
requests.delete(
|
||||
signoz.self.host_configs["8080"].get(f"{BASE_URL}/{view_id}"),
|
||||
headers=headers,
|
||||
timeout=5,
|
||||
)
|
||||
|
||||
|
||||
def test_empty_name_derives_a_slug_from_display_name(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
|
||||
Reference in New Issue
Block a user