plugin-elastic-report 0.1.1 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ai/skills/elastic-report/SKILLS.md +5 -3
- package/dist/client/357.0dd385384cab5dbf.js +10 -0
- package/dist/client/index.js +1 -1
- package/dist/client-v2/851.142c93fc6d666b28.js +10 -0
- package/dist/client-v2/857.a5bf9637d5fd4ef5.js +10 -0
- package/dist/client-v2/877.f4095a3dbcadf98f.js +10 -0
- package/dist/client-v2/index.js +1 -1
- package/dist/externalVersion.js +3 -2
- package/dist/locale/en-US.json +100 -1
- package/dist/locale/vi-VN.json +100 -1
- package/dist/locale/zh-CN.json +100 -1
- package/dist/node_modules/@elastic/elasticsearch/package.json +1 -1
- package/dist/server/acl-guard.js +97 -25
- package/dist/server/collections/es-report-data-views.js +6 -0
- package/dist/server/collections/es-reports.js +6 -0
- package/dist/server/mcp/ElasticReportToolCatalog.js +232 -10
- package/dist/server/plugin.js +153 -19
- package/dist/server/services/ElasticReportService.js +125 -11
- package/dist/server/services/ElasticsearchConnectionService.js +274 -34
- package/dist/server/services/ReportExportService.js +243 -0
- package/dist/server/services/ReportQueryCompiler.js +532 -91
- package/dist/server/workflow/ElasticReportQueryInstruction.js +123 -0
- package/dist/shared/constants.js +17 -2
- package/package.json +3 -2
- package/src/client/index.tsx +16 -1
- package/src/client/workflow-instructions.tsx +44 -0
- package/src/client-v2/__tests__/elastic-report.test.tsx +519 -39
- package/src/client-v2/__tests__/kql-autocomplete.test.ts +178 -0
- package/src/client-v2/api.ts +96 -0
- package/src/client-v2/bus/DashboardFilterBus.ts +212 -0
- package/src/client-v2/components/ElasticBasicCharts.tsx +345 -92
- package/src/client-v2/components/ElasticFilterBar.tsx +372 -0
- package/src/client-v2/components/ElasticKqlInput.tsx +421 -0
- package/src/client-v2/components/ElasticReportBlock.tsx +157 -11
- package/src/client-v2/components/ElasticReportRenderer.tsx +621 -71
- package/src/client-v2/components/ReportSelect.tsx +39 -26
- package/src/client-v2/models/ElasticFilterBarBlockModel.tsx +115 -0
- package/src/client-v2/models/ElasticReportBlockModel.tsx +36 -3
- package/src/client-v2/pages/ElasticReportManager.tsx +432 -26
- package/src/client-v2/plugin.tsx +20 -0
- package/src/client-v2/utils/kqlAutocomplete.ts +861 -0
- package/src/client-v2/workflow/instructions.tsx +149 -0
- package/src/locale/en-US.json +100 -1
- package/src/locale/vi-VN.json +100 -1
- package/src/locale/zh-CN.json +100 -1
- package/src/server/__tests__/query-compiler.test.ts +390 -1
- package/src/server/__tests__/report-mcp-acl.integration.test.ts +271 -3
- package/src/server/acl-guard.ts +119 -28
- package/src/server/collections/es-report-data-views.ts +6 -0
- package/src/server/collections/es-reports.ts +6 -0
- package/src/server/mcp/ElasticReportToolCatalog.ts +255 -9
- package/src/server/plugin.ts +189 -21
- package/src/server/services/ElasticReportService.ts +165 -5
- package/src/server/services/ElasticsearchConnectionService.ts +375 -48
- package/src/server/services/ReportExportService.ts +282 -0
- package/src/server/services/ReportQueryCompiler.ts +629 -94
- package/src/server/workflow/ElasticReportQueryInstruction.ts +124 -0
- package/src/shared/constants.ts +7 -0
- package/src/shared/types.ts +98 -1
- package/dist/client-v2/851.488fdbf5bc5b6a36.js +0 -10
|
@@ -12,29 +12,45 @@ import {
|
|
|
12
12
|
HIGHLIGHT_POST_TAG,
|
|
13
13
|
HIGHLIGHT_PRE_TAG,
|
|
14
14
|
MAX_RESULT_WINDOW,
|
|
15
|
+
MAX_SPLIT_SERIES,
|
|
15
16
|
MAX_TERMS_BUCKETS,
|
|
16
17
|
MAX_UI_PAGE_SIZE,
|
|
17
18
|
} from '../../shared/constants';
|
|
18
19
|
import type {
|
|
19
20
|
BucketAggType,
|
|
20
21
|
CalendarIntervalOption,
|
|
22
|
+
ChartStackMode,
|
|
21
23
|
EsFieldCapability,
|
|
24
|
+
FieldFormatType,
|
|
22
25
|
FilterOperator,
|
|
26
|
+
ID,
|
|
23
27
|
MetricAggType,
|
|
28
|
+
RecordContextBinding,
|
|
24
29
|
ReportExecutionResult,
|
|
25
30
|
ReportFilterItem,
|
|
26
31
|
ReportHistogramBucket,
|
|
27
32
|
ReportRowHit,
|
|
28
33
|
ReportRuntimeOverrides,
|
|
29
34
|
ReportSeriesPoint,
|
|
35
|
+
ReportShardStats,
|
|
30
36
|
ReportSortItem,
|
|
31
37
|
ReportSpec,
|
|
38
|
+
ReportSubSeriesPoint,
|
|
32
39
|
ReportTimeRange,
|
|
33
40
|
ReportVisualizationType,
|
|
34
41
|
ScalarFilterValue,
|
|
35
42
|
TimeRangePreset,
|
|
36
43
|
} from '../../shared/types';
|
|
37
44
|
|
|
45
|
+
export class KqlSyntaxError extends Error {
|
|
46
|
+
public readonly status = 400;
|
|
47
|
+
|
|
48
|
+
constructor(message: string) {
|
|
49
|
+
super(message);
|
|
50
|
+
this.name = 'KqlSyntaxError';
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
38
54
|
const VALID_VISUALIZATIONS: ReadonlySet<ReportVisualizationType> = new Set([
|
|
39
55
|
'table',
|
|
40
56
|
'bar',
|
|
@@ -70,7 +86,27 @@ const VALID_PRESETS: ReadonlySet<TimeRangePreset> = new Set([
|
|
|
70
86
|
'custom',
|
|
71
87
|
]);
|
|
72
88
|
|
|
73
|
-
const VALID_METRICS: ReadonlySet<MetricAggType> = new Set([
|
|
89
|
+
const VALID_METRICS: ReadonlySet<MetricAggType> = new Set([
|
|
90
|
+
'count',
|
|
91
|
+
'sum',
|
|
92
|
+
'avg',
|
|
93
|
+
'min',
|
|
94
|
+
'max',
|
|
95
|
+
'cardinality',
|
|
96
|
+
'p50',
|
|
97
|
+
'p95',
|
|
98
|
+
'p99',
|
|
99
|
+
]);
|
|
100
|
+
const VALID_STACK_MODES: ReadonlySet<ChartStackMode> = new Set(['none', 'stacked', 'percent']);
|
|
101
|
+
const VALID_FIELD_FORMATS: ReadonlySet<FieldFormatType> = new Set([
|
|
102
|
+
'auto',
|
|
103
|
+
'duration_ms',
|
|
104
|
+
'bytes',
|
|
105
|
+
'percent',
|
|
106
|
+
'number',
|
|
107
|
+
'status_badge',
|
|
108
|
+
'url',
|
|
109
|
+
]);
|
|
74
110
|
const VALID_BUCKETS: ReadonlySet<BucketAggType> = new Set(['date_histogram', 'terms']);
|
|
75
111
|
const VALID_INTERVALS: ReadonlySet<CalendarIntervalOption> = new Set([
|
|
76
112
|
'auto',
|
|
@@ -83,6 +119,9 @@ const VALID_INTERVALS: ReadonlySet<CalendarIntervalOption> = new Set([
|
|
|
83
119
|
'1M',
|
|
84
120
|
]);
|
|
85
121
|
|
|
122
|
+
// Elasticsearch calendar_interval only accepts single calendar units; multi-unit durations require fixed_interval.
|
|
123
|
+
const CALENDAR_UNIT_INTERVALS: ReadonlySet<CalendarIntervalOption> = new Set(['1m', '1h', '1d', '1w', '1M']);
|
|
124
|
+
|
|
86
125
|
const PRESET_TO_ES_EXPR: Record<Exclude<TimeRangePreset, 'all' | 'custom'>, string> = {
|
|
87
126
|
last_15m: 'now-15m',
|
|
88
127
|
last_1h: 'now-1h',
|
|
@@ -92,6 +131,26 @@ const PRESET_TO_ES_EXPR: Record<Exclude<TimeRangePreset, 'all' | 'custom'>, stri
|
|
|
92
131
|
last_90d: 'now-90d',
|
|
93
132
|
};
|
|
94
133
|
|
|
134
|
+
const PRESET_TO_PREV_ES_EXPR: Record<Exclude<TimeRangePreset, 'all' | 'custom'>, { gte: string; lt: string }> = {
|
|
135
|
+
last_15m: { gte: 'now-30m', lt: 'now-15m' },
|
|
136
|
+
last_1h: { gte: 'now-2h', lt: 'now-1h' },
|
|
137
|
+
last_24h: { gte: 'now-48h', lt: 'now-24h' },
|
|
138
|
+
last_7d: { gte: 'now-14d', lt: 'now-7d' },
|
|
139
|
+
last_30d: { gte: 'now-60d', lt: 'now-30d' },
|
|
140
|
+
last_90d: { gte: 'now-180d', lt: 'now-90d' },
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
export function sanitizeTimeZone(raw?: unknown): string | undefined {
|
|
144
|
+
if (typeof raw !== 'string' || !raw.trim()) return undefined;
|
|
145
|
+
const candidate = raw.trim();
|
|
146
|
+
try {
|
|
147
|
+
Intl.DateTimeFormat(undefined, { timeZone: candidate });
|
|
148
|
+
return candidate;
|
|
149
|
+
} catch {
|
|
150
|
+
return undefined;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
95
154
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
96
155
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
97
156
|
}
|
|
@@ -246,13 +305,103 @@ export function normalizeTimeRange(raw: unknown): ReportTimeRange | undefined {
|
|
|
246
305
|
: 'last_24h';
|
|
247
306
|
const from = typeof raw.from === 'string' && raw.from.trim() ? raw.from.trim() : undefined;
|
|
248
307
|
const to = typeof raw.to === 'string' && raw.to.trim() ? raw.to.trim() : undefined;
|
|
308
|
+
const timeZone = sanitizeTimeZone(raw.timeZone);
|
|
249
309
|
return {
|
|
250
310
|
preset,
|
|
251
311
|
...(from ? { from } : {}),
|
|
252
312
|
...(to ? { to } : {}),
|
|
313
|
+
...(timeZone ? { timeZone } : {}),
|
|
253
314
|
};
|
|
254
315
|
}
|
|
255
316
|
|
|
317
|
+
function normalizeFieldFormats(raw: unknown): Record<string, FieldFormatType> | undefined {
|
|
318
|
+
if (!isRecord(raw)) return undefined;
|
|
319
|
+
const out: Record<string, FieldFormatType> = {};
|
|
320
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
321
|
+
const fieldName = k.trim();
|
|
322
|
+
if (fieldName && typeof v === 'string' && VALID_FIELD_FORMATS.has(v as FieldFormatType) && v !== 'auto') {
|
|
323
|
+
out[fieldName] = v as FieldFormatType;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
return Object.keys(out).length > 0 ? out : undefined;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function normalizeContextBindings(raw: unknown): RecordContextBinding[] | undefined {
|
|
330
|
+
if (!Array.isArray(raw)) return undefined;
|
|
331
|
+
const out: RecordContextBinding[] = [];
|
|
332
|
+
for (const item of raw) {
|
|
333
|
+
if (!isRecord(item)) continue;
|
|
334
|
+
const esField = typeof item.esField === 'string' ? item.esField.trim() : '';
|
|
335
|
+
const recordFieldPath = typeof item.recordFieldPath === 'string' ? item.recordFieldPath.trim() : '';
|
|
336
|
+
if (esField && recordFieldPath) {
|
|
337
|
+
out.push({ esField, recordFieldPath });
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
return out.length > 0 ? out : undefined;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
export interface ServerUserTokenContext {
|
|
344
|
+
userId?: ID;
|
|
345
|
+
username?: string;
|
|
346
|
+
email?: string;
|
|
347
|
+
role?: string;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function resolveTokenScalar(val: ScalarFilterValue, userCtx: ServerUserTokenContext): ScalarFilterValue {
|
|
351
|
+
if (typeof val !== 'string') return val;
|
|
352
|
+
const trimmed = val.trim();
|
|
353
|
+
const tokenMatch = trimmed.match(/^\{\{\s*\$(user\.(?:id|username|email)|role)\s*\}\}$/);
|
|
354
|
+
if (!tokenMatch) return val;
|
|
355
|
+
const tokenName = tokenMatch[1];
|
|
356
|
+
let resolved: ScalarFilterValue | undefined;
|
|
357
|
+
if (
|
|
358
|
+
tokenName === 'user.id' &&
|
|
359
|
+
userCtx.userId !== undefined &&
|
|
360
|
+
userCtx.userId !== null &&
|
|
361
|
+
String(userCtx.userId) !== ''
|
|
362
|
+
) {
|
|
363
|
+
resolved = userCtx.userId;
|
|
364
|
+
} else if (tokenName === 'user.username' && userCtx.username?.trim()) {
|
|
365
|
+
resolved = userCtx.username.trim();
|
|
366
|
+
} else if (tokenName === 'user.email' && userCtx.email?.trim()) {
|
|
367
|
+
resolved = userCtx.email.trim();
|
|
368
|
+
} else if (tokenName === 'role' && userCtx.role?.trim()) {
|
|
369
|
+
resolved = userCtx.role.trim();
|
|
370
|
+
}
|
|
371
|
+
if (resolved === undefined) {
|
|
372
|
+
const err = new Error(
|
|
373
|
+
`Permission denied: missing authenticated value for locked filter token "$${tokenName}"`,
|
|
374
|
+
) as Error & {
|
|
375
|
+
status?: number;
|
|
376
|
+
};
|
|
377
|
+
err.status = 403;
|
|
378
|
+
throw err;
|
|
379
|
+
}
|
|
380
|
+
return resolved;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
export function resolveServerLockedFilters(
|
|
384
|
+
lockedFilters: ReportFilterItem[] | undefined,
|
|
385
|
+
userCtx?: ServerUserTokenContext,
|
|
386
|
+
): ReportFilterItem[] {
|
|
387
|
+
if (!lockedFilters || lockedFilters.length === 0) return [];
|
|
388
|
+
const ctx = userCtx ?? {};
|
|
389
|
+
return lockedFilters.map((item) => {
|
|
390
|
+
const nextVal = Array.isArray(item.value)
|
|
391
|
+
? item.value.map((v) => resolveTokenScalar(v, ctx))
|
|
392
|
+
: item.value !== undefined
|
|
393
|
+
? resolveTokenScalar(item.value, ctx)
|
|
394
|
+
: undefined;
|
|
395
|
+
const nextValTo = item.valueTo !== undefined ? resolveTokenScalar(item.valueTo, ctx) : undefined;
|
|
396
|
+
return {
|
|
397
|
+
...item,
|
|
398
|
+
...(nextVal !== undefined ? { value: nextVal } : {}),
|
|
399
|
+
...(nextValTo !== undefined ? { valueTo: nextValTo } : {}),
|
|
400
|
+
enabled: true,
|
|
401
|
+
};
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
|
|
256
405
|
export function normalizeReportSpec(raw: unknown, fallbackVisualization?: unknown): ReportSpec {
|
|
257
406
|
const obj = isRecord(raw) ? raw : {};
|
|
258
407
|
const visCandidate = typeof obj.visualization === 'string' ? obj.visualization : fallbackVisualization;
|
|
@@ -264,6 +413,10 @@ export function normalizeReportSpec(raw: unknown, fallbackVisualization?: unknow
|
|
|
264
413
|
const query = typeof obj.query === 'string' ? obj.query.trim() : '';
|
|
265
414
|
const queryMode = obj.queryMode === 'simple' ? 'simple' : 'kql';
|
|
266
415
|
const filters = normalizeReportFilters(obj.filters);
|
|
416
|
+
const lockedFilters = normalizeReportFilters(obj.lockedFilters).map((item) => ({
|
|
417
|
+
...item,
|
|
418
|
+
enabled: true,
|
|
419
|
+
}));
|
|
267
420
|
const sort = normalizeReportSort(obj.sort);
|
|
268
421
|
const timeRange = normalizeTimeRange(obj.timeRange);
|
|
269
422
|
const columns = Array.isArray(obj.columns)
|
|
@@ -271,6 +424,8 @@ export function normalizeReportSpec(raw: unknown, fallbackVisualization?: unknow
|
|
|
271
424
|
.filter((col): col is string => typeof col === 'string' && col.trim().length > 0)
|
|
272
425
|
.map((col) => col.trim())
|
|
273
426
|
: [];
|
|
427
|
+
const fieldFormats = normalizeFieldFormats(obj.fieldFormats);
|
|
428
|
+
const contextBindings = normalizeContextBindings(obj.contextBindings);
|
|
274
429
|
const pageSize = clamp(typeof obj.pageSize === 'number' ? obj.pageSize : DEFAULT_PAGE_SIZE, 1, MAX_UI_PAGE_SIZE);
|
|
275
430
|
|
|
276
431
|
const rawChart = isRecord(obj.chart) ? obj.chart : {};
|
|
@@ -287,14 +442,21 @@ export function normalizeReportSpec(raw: unknown, fallbackVisualization?: unknow
|
|
|
287
442
|
VALID_INTERVALS.has(rawChart.calendarInterval as CalendarIntervalOption)
|
|
288
443
|
? (rawChart.calendarInterval as CalendarIntervalOption)
|
|
289
444
|
: 'auto';
|
|
445
|
+
const stackMode: ChartStackMode =
|
|
446
|
+
typeof rawChart.stackMode === 'string' && VALID_STACK_MODES.has(rawChart.stackMode as ChartStackMode)
|
|
447
|
+
? (rawChart.stackMode as ChartStackMode)
|
|
448
|
+
: 'none';
|
|
290
449
|
|
|
291
450
|
return {
|
|
292
451
|
query,
|
|
293
452
|
queryMode,
|
|
294
453
|
filters,
|
|
454
|
+
lockedFilters,
|
|
295
455
|
sort,
|
|
296
456
|
...(timeRange ? { timeRange } : {}),
|
|
297
457
|
columns,
|
|
458
|
+
...(fieldFormats ? { fieldFormats } : {}),
|
|
459
|
+
...(contextBindings ? { contextBindings } : {}),
|
|
298
460
|
pageSize,
|
|
299
461
|
visualization,
|
|
300
462
|
chart: {
|
|
@@ -312,11 +474,65 @@ export function normalizeReportSpec(raw: unknown, fallbackVisualization?: unknow
|
|
|
312
474
|
? { metricLabel: rawChart.metricLabel.trim() }
|
|
313
475
|
: {}),
|
|
314
476
|
showHistogram: rawChart.showHistogram !== false,
|
|
477
|
+
...(typeof rawChart.splitSeriesField === 'string' && rawChart.splitSeriesField.trim()
|
|
478
|
+
? { splitSeriesField: rawChart.splitSeriesField.trim() }
|
|
479
|
+
: {}),
|
|
480
|
+
...(typeof rawChart.splitSeriesTopN === 'number'
|
|
481
|
+
? { splitSeriesTopN: clamp(rawChart.splitSeriesTopN, 1, MAX_SPLIT_SERIES) }
|
|
482
|
+
: {}),
|
|
483
|
+
...(stackMode !== 'none' ? { stackMode } : {}),
|
|
484
|
+
...(rawChart.comparePreviousPeriod === true ? { comparePreviousPeriod: true } : {}),
|
|
315
485
|
},
|
|
316
486
|
allowInteractiveControls: obj.allowInteractiveControls !== false,
|
|
487
|
+
allowExport: obj.allowExport !== false,
|
|
317
488
|
};
|
|
318
489
|
}
|
|
319
490
|
|
|
491
|
+
function assertBalancedKqlDelimiters(input: string): void {
|
|
492
|
+
let inQuotes = false;
|
|
493
|
+
let quoteChar = '';
|
|
494
|
+
const openParenPositions: number[] = [];
|
|
495
|
+
|
|
496
|
+
for (let i = 0; i < input.length; i++) {
|
|
497
|
+
const ch = input[i];
|
|
498
|
+
if (inQuotes) {
|
|
499
|
+
if (ch === '\\') {
|
|
500
|
+
i++;
|
|
501
|
+
continue;
|
|
502
|
+
}
|
|
503
|
+
if (ch === quoteChar) {
|
|
504
|
+
inQuotes = false;
|
|
505
|
+
}
|
|
506
|
+
continue;
|
|
507
|
+
}
|
|
508
|
+
if (ch === '"' || ch === "'") {
|
|
509
|
+
inQuotes = true;
|
|
510
|
+
quoteChar = ch;
|
|
511
|
+
continue;
|
|
512
|
+
}
|
|
513
|
+
if (ch === '(') {
|
|
514
|
+
openParenPositions.push(i);
|
|
515
|
+
continue;
|
|
516
|
+
}
|
|
517
|
+
if (ch === ')') {
|
|
518
|
+
const openIdx = openParenPositions.pop();
|
|
519
|
+
if (openIdx === undefined) {
|
|
520
|
+
throw new KqlSyntaxError('Invalid KQL syntax: unexpected closing parenthesis ")"');
|
|
521
|
+
}
|
|
522
|
+
if (!input.slice(openIdx + 1, i).trim()) {
|
|
523
|
+
throw new KqlSyntaxError('Invalid KQL syntax: empty parentheses "()"');
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
if (inQuotes) {
|
|
529
|
+
throw new KqlSyntaxError('Invalid KQL syntax: unclosed quotation mark');
|
|
530
|
+
}
|
|
531
|
+
if (openParenPositions.length > 0) {
|
|
532
|
+
throw new KqlSyntaxError('Invalid KQL syntax: unclosed parenthesis "("');
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
320
536
|
/**
|
|
321
537
|
* Split a KQL expression on top-level boolean connectors (`AND` / `OR`) while
|
|
322
538
|
* respecting quoted strings and nested parentheses.
|
|
@@ -327,6 +543,7 @@ function splitTopLevelBoolean(input: string, keyword: 'AND' | 'OR'): string[] {
|
|
|
327
543
|
let inQuotes = false;
|
|
328
544
|
let quoteChar = '';
|
|
329
545
|
let lastIdx = 0;
|
|
546
|
+
let splitFound = false;
|
|
330
547
|
|
|
331
548
|
for (let i = 0; i < input.length; i++) {
|
|
332
549
|
const ch = input[i];
|
|
@@ -354,18 +571,22 @@ function splitTopLevelBoolean(input: string, keyword: 'AND' | 'OR'): string[] {
|
|
|
354
571
|
continue;
|
|
355
572
|
}
|
|
356
573
|
if (depth === 0) {
|
|
357
|
-
const prevBoundary = i === 0 ||
|
|
574
|
+
const prevBoundary = i === 0 || /[\s)]/.test(input[i - 1]);
|
|
358
575
|
const slice = input.slice(i, i + keyword.length);
|
|
359
576
|
const nextChar = input[i + keyword.length];
|
|
360
|
-
const nextBoundary = nextChar
|
|
577
|
+
const nextBoundary = nextChar === undefined || /[\s(]/.test(nextChar);
|
|
361
578
|
if (prevBoundary && nextBoundary && slice.toUpperCase() === keyword) {
|
|
579
|
+
splitFound = true;
|
|
362
580
|
parts.push(input.slice(lastIdx, i).trim());
|
|
363
|
-
i += keyword.length;
|
|
364
|
-
lastIdx = i;
|
|
581
|
+
i += keyword.length - 1;
|
|
582
|
+
lastIdx = i + 1;
|
|
365
583
|
}
|
|
366
584
|
}
|
|
367
585
|
}
|
|
368
586
|
parts.push(input.slice(lastIdx).trim());
|
|
587
|
+
if (splitFound && parts.some((part) => !part)) {
|
|
588
|
+
throw new KqlSyntaxError(`Invalid KQL syntax: missing operand around "${keyword}"`);
|
|
589
|
+
}
|
|
369
590
|
return parts.filter(Boolean);
|
|
370
591
|
}
|
|
371
592
|
|
|
@@ -412,25 +633,129 @@ function unquote(raw: string): { value: string; wasQuoted: boolean } {
|
|
|
412
633
|
return { value: trimmed, wasQuoted: false };
|
|
413
634
|
}
|
|
414
635
|
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
636
|
+
function compileSingleFieldValue(
|
|
637
|
+
rawField: string,
|
|
638
|
+
rawVal: string,
|
|
639
|
+
fieldMap: Map<string, EsFieldCapability>,
|
|
640
|
+
): Record<string, unknown> {
|
|
641
|
+
const trimmed = rawVal.trim();
|
|
642
|
+
if (!trimmed) {
|
|
643
|
+
throw new KqlSyntaxError(`Invalid KQL syntax: missing value for field "${rawField}"`);
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
const inlineRangeMatch = trimmed.match(/^(>=|<=|>|<)\s*(.+)$/);
|
|
647
|
+
if (inlineRangeMatch) {
|
|
648
|
+
const [, op, rangeRhs] = inlineRangeMatch;
|
|
649
|
+
const { value } = unquote(rangeRhs);
|
|
650
|
+
if (!value) {
|
|
651
|
+
throw new KqlSyntaxError(`Invalid KQL syntax: missing range bound for field "${rawField}"`);
|
|
652
|
+
}
|
|
653
|
+
const coerced = coerceLiteral(value, fieldMap.get(rawField));
|
|
654
|
+
const opKey = op === '>=' ? 'gte' : op === '<=' ? 'lte' : op === '>' ? 'gt' : 'lt';
|
|
655
|
+
return { range: { [rawField]: { [opKey]: coerced } } };
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
const { value, wasQuoted } = unquote(trimmed);
|
|
659
|
+
if (!wasQuoted) {
|
|
660
|
+
if (/^[[{].*[\]}]$/.test(value)) {
|
|
661
|
+
throw new KqlSyntaxError('Lucene range brackets [a TO b] are not valid KQL; use >= and <= instead');
|
|
662
|
+
}
|
|
663
|
+
if (/^\/.*\/$/.test(value)) {
|
|
664
|
+
throw new KqlSyntaxError('Regular expressions /.../ are not valid KQL; use * or ? wildcards instead');
|
|
665
|
+
}
|
|
666
|
+
if (value.includes('(') || value.includes(')')) {
|
|
667
|
+
throw new KqlSyntaxError(`Unsupported KQL field value syntax near "${value}"`);
|
|
668
|
+
}
|
|
669
|
+
if (value.includes(':')) {
|
|
670
|
+
throw new KqlSyntaxError(`Unexpected ":" in unquoted KQL value "${value}"; wrap values containing ":" in quotes`);
|
|
671
|
+
}
|
|
672
|
+
if (value === '*') {
|
|
673
|
+
return { exists: { field: rawField } };
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
const fieldMeta = fieldMap.get(rawField);
|
|
678
|
+
if (!wasQuoted && (value.includes('*') || value.includes('?'))) {
|
|
679
|
+
const wildcardField = resolveAggregatableField(rawField, fieldMap);
|
|
680
|
+
return {
|
|
681
|
+
wildcard: {
|
|
682
|
+
[wildcardField]: {
|
|
683
|
+
value,
|
|
684
|
+
case_insensitive: true,
|
|
685
|
+
},
|
|
686
|
+
},
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
if (wasQuoted) {
|
|
691
|
+
if (fieldMeta?.type === 'keyword' || fieldMeta?.type === 'constant_keyword') {
|
|
692
|
+
return { term: { [rawField]: value } };
|
|
693
|
+
}
|
|
694
|
+
return { match_phrase: { [rawField]: value } };
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
const coerced = coerceLiteral(value, fieldMeta);
|
|
698
|
+
if (typeof coerced === 'number' || typeof coerced === 'boolean') {
|
|
699
|
+
return { term: { [rawField]: coerced } };
|
|
700
|
+
}
|
|
701
|
+
if (fieldMeta?.type === 'keyword' || fieldMeta?.type === 'constant_keyword') {
|
|
702
|
+
return { term: { [rawField]: coerced } };
|
|
703
|
+
}
|
|
704
|
+
return { match_phrase: { [rawField]: String(coerced) } };
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
function compileFieldGroupClause(
|
|
708
|
+
fieldName: string,
|
|
709
|
+
groupBody: string,
|
|
710
|
+
fieldMap: Map<string, EsFieldCapability>,
|
|
711
|
+
): Record<string, unknown> {
|
|
712
|
+
const expr = groupBody.trim();
|
|
713
|
+
if (!expr) {
|
|
714
|
+
throw new KqlSyntaxError(`Invalid KQL syntax: empty value group for field "${fieldName}"`);
|
|
715
|
+
}
|
|
716
|
+
if (/^NOT$/i.test(expr)) {
|
|
717
|
+
throw new KqlSyntaxError(`Invalid KQL syntax: incomplete "NOT" inside "${fieldName}: (...)"`);
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
if (hasBalancedOuterParens(expr)) {
|
|
721
|
+
return compileFieldGroupClause(fieldName, expr.slice(1, -1), fieldMap);
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
const orParts = splitTopLevelBoolean(expr, 'OR');
|
|
725
|
+
if (orParts.length > 1) {
|
|
726
|
+
const should = orParts.map((part) => compileFieldGroupClause(fieldName, part, fieldMap));
|
|
727
|
+
return should.length === 1 ? should[0] : { bool: { should, minimum_should_match: 1 } };
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
const andParts = splitTopLevelBoolean(expr, 'AND');
|
|
731
|
+
if (andParts.length > 1) {
|
|
732
|
+
const must = andParts.map((part) => compileFieldGroupClause(fieldName, part, fieldMap));
|
|
733
|
+
return must.length === 1 ? must[0] : { bool: { must } };
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
if (/^NOT\s+/i.test(expr)) {
|
|
737
|
+
const inner = compileFieldGroupClause(fieldName, expr.replace(/^NOT\s+/i, ''), fieldMap);
|
|
738
|
+
return { bool: { must_not: [inner] } };
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
return compileSingleFieldValue(fieldName, expr, fieldMap);
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
function compileKqlAst(exprInput: string, fieldMap: Map<string, EsFieldCapability>): Record<string, unknown> | null {
|
|
745
|
+
const expr = exprInput.trim();
|
|
424
746
|
if (!expr) return null;
|
|
747
|
+
if (/^NOT$/i.test(expr)) {
|
|
748
|
+
throw new KqlSyntaxError('Invalid KQL syntax: incomplete "NOT" operator');
|
|
749
|
+
}
|
|
425
750
|
|
|
426
751
|
if (hasBalancedOuterParens(expr)) {
|
|
427
|
-
return
|
|
752
|
+
return compileKqlAst(expr.slice(1, -1), fieldMap);
|
|
428
753
|
}
|
|
429
754
|
|
|
430
755
|
const orParts = splitTopLevelBoolean(expr, 'OR');
|
|
431
756
|
if (orParts.length > 1) {
|
|
432
757
|
const should = orParts
|
|
433
|
-
.map((part) =>
|
|
758
|
+
.map((part) => compileKqlAst(part, fieldMap))
|
|
434
759
|
.filter((item): item is Record<string, unknown> => item !== null);
|
|
435
760
|
if (should.length === 0) return null;
|
|
436
761
|
if (should.length === 1) return should[0];
|
|
@@ -440,7 +765,7 @@ export function compileKqlToQueryDsl(
|
|
|
440
765
|
const andParts = splitTopLevelBoolean(expr, 'AND');
|
|
441
766
|
if (andParts.length > 1) {
|
|
442
767
|
const must = andParts
|
|
443
|
-
.map((part) =>
|
|
768
|
+
.map((part) => compileKqlAst(part, fieldMap))
|
|
444
769
|
.filter((item): item is Record<string, unknown> => item !== null);
|
|
445
770
|
if (must.length === 0) return null;
|
|
446
771
|
if (must.length === 1) return must[0];
|
|
@@ -448,58 +773,38 @@ export function compileKqlToQueryDsl(
|
|
|
448
773
|
}
|
|
449
774
|
|
|
450
775
|
if (/^NOT\s+/i.test(expr)) {
|
|
451
|
-
const
|
|
776
|
+
const rest = expr.replace(/^NOT\s+/i, '').trim();
|
|
777
|
+
if (!rest) {
|
|
778
|
+
throw new KqlSyntaxError('Invalid KQL syntax: incomplete "NOT" operator');
|
|
779
|
+
}
|
|
780
|
+
const inner = compileKqlAst(rest, fieldMap);
|
|
452
781
|
return inner ? { bool: { must_not: [inner] } } : null;
|
|
453
782
|
}
|
|
454
783
|
|
|
784
|
+
if (/^[A-Za-z0-9_@.-]+\s*(:|>=|<=|>|<)\s*$/.test(expr)) {
|
|
785
|
+
throw new KqlSyntaxError('Invalid KQL syntax: missing value after field operator');
|
|
786
|
+
}
|
|
787
|
+
|
|
455
788
|
// Range expression: field >= value, field > value, field <= value, field < value
|
|
456
789
|
const rangeMatch = expr.match(/^([A-Za-z0-9_@.-]+)\s*(>=|<=|>|<)\s*(.+)$/);
|
|
457
790
|
if (rangeMatch) {
|
|
458
791
|
const [, rawField, op, rawVal] = rangeMatch;
|
|
459
|
-
|
|
460
|
-
const coerced = coerceLiteral(value, fieldMap.get(rawField));
|
|
461
|
-
const opKey = op === '>=' ? 'gte' : op === '<=' ? 'lte' : op === '>' ? 'gt' : 'lt';
|
|
462
|
-
return { range: { [rawField]: { [opKey]: coerced } } };
|
|
792
|
+
return compileSingleFieldValue(rawField, `${op} ${rawVal}`, fieldMap);
|
|
463
793
|
}
|
|
464
794
|
|
|
465
|
-
// Field-value expression: field : value
|
|
795
|
+
// Field-value or field-group expression: field : value OR field : (a OR b)
|
|
466
796
|
const colonMatch = expr.match(/^([A-Za-z0-9_@.-]+)\s*:\s*(.+)$/);
|
|
467
797
|
if (colonMatch) {
|
|
468
798
|
const [, rawField, rawVal] = colonMatch;
|
|
469
|
-
const
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
return { exists: { field: rawField } };
|
|
473
|
-
}
|
|
474
|
-
|
|
475
|
-
const fieldMeta = fieldMap.get(rawField);
|
|
476
|
-
if (!wasQuoted && (value.includes('*') || value.includes('?'))) {
|
|
477
|
-
const wildcardField = resolveAggregatableField(rawField, fieldMap);
|
|
478
|
-
return {
|
|
479
|
-
wildcard: {
|
|
480
|
-
[wildcardField]: {
|
|
481
|
-
value,
|
|
482
|
-
case_insensitive: true,
|
|
483
|
-
},
|
|
484
|
-
},
|
|
485
|
-
};
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
if (wasQuoted) {
|
|
489
|
-
if (fieldMeta?.type === 'keyword' || fieldMeta?.type === 'constant_keyword') {
|
|
490
|
-
return { term: { [rawField]: value } };
|
|
491
|
-
}
|
|
492
|
-
return { match_phrase: { [rawField]: value } };
|
|
799
|
+
const rhs = rawVal.trim();
|
|
800
|
+
if (hasBalancedOuterParens(rhs)) {
|
|
801
|
+
return compileFieldGroupClause(rawField, rhs.slice(1, -1), fieldMap);
|
|
493
802
|
}
|
|
803
|
+
return compileSingleFieldValue(rawField, rhs, fieldMap);
|
|
804
|
+
}
|
|
494
805
|
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
return { term: { [rawField]: coerced } };
|
|
498
|
-
}
|
|
499
|
-
if (fieldMeta?.type === 'keyword' || fieldMeta?.type === 'constant_keyword') {
|
|
500
|
-
return { term: { [rawField]: coerced } };
|
|
501
|
-
}
|
|
502
|
-
return { match_phrase: { [rawField]: String(coerced) } };
|
|
806
|
+
if (!unquote(expr).wasQuoted && (/^[[{].*[\]}]$/.test(expr) || /^\/.*\/$/.test(expr))) {
|
|
807
|
+
throw new KqlSyntaxError(`Unsupported KQL expression "${expr}"`);
|
|
503
808
|
}
|
|
504
809
|
|
|
505
810
|
return {
|
|
@@ -511,6 +816,20 @@ export function compileKqlToQueryDsl(
|
|
|
511
816
|
};
|
|
512
817
|
}
|
|
513
818
|
|
|
819
|
+
/**
|
|
820
|
+
* Compile a KQL-compatible search string into universal Elasticsearch Query DSL
|
|
821
|
+
* so queries run reliably across ES 7.x, 8.x, 9.x, and OpenSearch.
|
|
822
|
+
*/
|
|
823
|
+
export function compileKqlToQueryDsl(
|
|
824
|
+
rawQuery: string,
|
|
825
|
+
fieldMap: Map<string, EsFieldCapability> = new Map(),
|
|
826
|
+
): Record<string, unknown> | null {
|
|
827
|
+
const expr = rawQuery.trim();
|
|
828
|
+
if (!expr) return null;
|
|
829
|
+
assertBalancedKqlDelimiters(expr);
|
|
830
|
+
return compileKqlAst(expr, fieldMap);
|
|
831
|
+
}
|
|
832
|
+
|
|
514
833
|
export function compileFilterItem(
|
|
515
834
|
item: ReportFilterItem,
|
|
516
835
|
fieldMap: Map<string, EsFieldCapability>,
|
|
@@ -596,15 +915,19 @@ export function compileFilterItem(
|
|
|
596
915
|
export function compileTimeRange(
|
|
597
916
|
timeRange: ReportTimeRange | undefined,
|
|
598
917
|
timeField: string | null | undefined,
|
|
918
|
+
fallbackTimeZone?: string,
|
|
599
919
|
): Record<string, unknown> | null {
|
|
600
920
|
const cleanField = typeof timeField === 'string' ? timeField.trim() : '';
|
|
601
921
|
if (!cleanField || !timeRange || timeRange.preset === 'all') return null;
|
|
602
922
|
|
|
923
|
+
const tz = sanitizeTimeZone(timeRange.timeZone ?? fallbackTimeZone);
|
|
924
|
+
|
|
603
925
|
if (timeRange.preset === 'custom') {
|
|
604
926
|
const bounds: Record<string, string> = {};
|
|
605
927
|
if (timeRange.from) bounds.gte = timeRange.from;
|
|
606
928
|
if (timeRange.to) bounds.lte = timeRange.to;
|
|
607
929
|
if (Object.keys(bounds).length === 0) return null;
|
|
930
|
+
if (tz) bounds.time_zone = tz;
|
|
608
931
|
return { range: { [cleanField]: bounds } };
|
|
609
932
|
}
|
|
610
933
|
|
|
@@ -615,17 +938,99 @@ export function compileTimeRange(
|
|
|
615
938
|
[cleanField]: {
|
|
616
939
|
gte: expr,
|
|
617
940
|
lte: 'now',
|
|
941
|
+
...(tz ? { time_zone: tz } : {}),
|
|
942
|
+
},
|
|
943
|
+
},
|
|
944
|
+
};
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
export function compilePreviousTimeRange(
|
|
948
|
+
timeRange: ReportTimeRange | undefined,
|
|
949
|
+
timeField: string | null | undefined,
|
|
950
|
+
fallbackTimeZone?: string,
|
|
951
|
+
): Record<string, unknown> | null {
|
|
952
|
+
const cleanField = typeof timeField === 'string' ? timeField.trim() : '';
|
|
953
|
+
if (!cleanField || !timeRange || timeRange.preset === 'all') return null;
|
|
954
|
+
const tz = sanitizeTimeZone(timeRange.timeZone ?? fallbackTimeZone);
|
|
955
|
+
|
|
956
|
+
if (timeRange.preset === 'custom') {
|
|
957
|
+
const fromMs = timeRange.from ? Date.parse(timeRange.from) : NaN;
|
|
958
|
+
const toMs = timeRange.to ? Date.parse(timeRange.to) : NaN;
|
|
959
|
+
if (!Number.isFinite(fromMs) || !Number.isFinite(toMs) || toMs <= fromMs) {
|
|
960
|
+
return null;
|
|
961
|
+
}
|
|
962
|
+
const duration = toMs - fromMs;
|
|
963
|
+
return {
|
|
964
|
+
range: {
|
|
965
|
+
[cleanField]: {
|
|
966
|
+
gte: new Date(fromMs - duration).toISOString(),
|
|
967
|
+
lt: new Date(fromMs).toISOString(),
|
|
968
|
+
...(tz ? { time_zone: tz } : {}),
|
|
969
|
+
},
|
|
970
|
+
},
|
|
971
|
+
};
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
const prev = PRESET_TO_PREV_ES_EXPR[timeRange.preset];
|
|
975
|
+
if (!prev) return null;
|
|
976
|
+
return {
|
|
977
|
+
range: {
|
|
978
|
+
[cleanField]: {
|
|
979
|
+
gte: prev.gte,
|
|
980
|
+
lt: prev.lt,
|
|
981
|
+
...(tz ? { time_zone: tz } : {}),
|
|
982
|
+
},
|
|
983
|
+
},
|
|
984
|
+
};
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
function buildMetricAggDefinition(
|
|
988
|
+
metricType: MetricAggType,
|
|
989
|
+
metricField: string | undefined,
|
|
990
|
+
fieldMap: Map<string, EsFieldCapability>,
|
|
991
|
+
): Record<string, unknown> | undefined {
|
|
992
|
+
if (metricType === 'count' || !metricField?.trim()) return undefined;
|
|
993
|
+
const targetField = resolveAggregatableField(metricField, fieldMap);
|
|
994
|
+
if (metricType === 'p50' || metricType === 'p95' || metricType === 'p99') {
|
|
995
|
+
const pct = metricType === 'p50' ? 50 : metricType === 'p95' ? 95 : 99;
|
|
996
|
+
return {
|
|
997
|
+
percentiles: {
|
|
998
|
+
field: targetField,
|
|
999
|
+
percents: [pct],
|
|
618
1000
|
},
|
|
1001
|
+
};
|
|
1002
|
+
}
|
|
1003
|
+
return {
|
|
1004
|
+
[metricType]: {
|
|
1005
|
+
field: targetField,
|
|
619
1006
|
},
|
|
620
1007
|
};
|
|
621
1008
|
}
|
|
622
1009
|
|
|
1010
|
+
function extractMetricValue(aggNode: unknown, metricType: MetricAggType, fallbackCount: number): number | null {
|
|
1011
|
+
if (metricType === 'count') {
|
|
1012
|
+
return fallbackCount;
|
|
1013
|
+
}
|
|
1014
|
+
if (!isRecord(aggNode)) return null;
|
|
1015
|
+
if (metricType === 'p50' || metricType === 'p95' || metricType === 'p99') {
|
|
1016
|
+
const values = isRecord(aggNode.values) ? aggNode.values : undefined;
|
|
1017
|
+
if (!values) return null;
|
|
1018
|
+
const exactKey = metricType === 'p50' ? '50.0' : metricType === 'p95' ? '95.0' : '99.0';
|
|
1019
|
+
const shortKey = metricType === 'p50' ? '50' : metricType === 'p95' ? '95' : '99';
|
|
1020
|
+
const raw = values[exactKey] ?? values[shortKey];
|
|
1021
|
+
return typeof raw === 'number' && Number.isFinite(raw) ? Number(raw.toFixed(4)) : null;
|
|
1022
|
+
}
|
|
1023
|
+
return typeof aggNode.value === 'number' && Number.isFinite(aggNode.value) ? Number(aggNode.value.toFixed(4)) : null;
|
|
1024
|
+
}
|
|
1025
|
+
|
|
623
1026
|
export interface CompileSearchOptions {
|
|
624
1027
|
spec: ReportSpec;
|
|
625
1028
|
overrides?: ReportRuntimeOverrides;
|
|
626
1029
|
timeField?: string | null;
|
|
627
1030
|
fields?: EsFieldCapability[] | null;
|
|
628
1031
|
maxRowsCap?: number;
|
|
1032
|
+
userContext?: ServerUserTokenContext;
|
|
1033
|
+
usePit?: boolean;
|
|
629
1034
|
}
|
|
630
1035
|
|
|
631
1036
|
export function mergeSpecWithOverrides(
|
|
@@ -633,6 +1038,8 @@ export function mergeSpecWithOverrides(
|
|
|
633
1038
|
overrides?: ReportRuntimeOverrides,
|
|
634
1039
|
): {
|
|
635
1040
|
effectiveSpec: ReportSpec;
|
|
1041
|
+
extraRuntimeFilters: ReportFilterItem[];
|
|
1042
|
+
effectiveTimeZone?: string;
|
|
636
1043
|
page: number;
|
|
637
1044
|
pageSize: number;
|
|
638
1045
|
searchAfter?: Array<string | number | boolean | null>;
|
|
@@ -640,19 +1047,34 @@ export function mergeSpecWithOverrides(
|
|
|
640
1047
|
if (!overrides) {
|
|
641
1048
|
return {
|
|
642
1049
|
effectiveSpec: spec,
|
|
1050
|
+
extraRuntimeFilters: [],
|
|
1051
|
+
effectiveTimeZone: sanitizeTimeZone(spec.timeRange?.timeZone),
|
|
643
1052
|
page: 1,
|
|
644
1053
|
pageSize: spec.pageSize ?? DEFAULT_PAGE_SIZE,
|
|
645
1054
|
};
|
|
646
1055
|
}
|
|
647
1056
|
|
|
1057
|
+
const effectiveTimeRange =
|
|
1058
|
+
overrides.timeRange !== undefined ? normalizeTimeRange(overrides.timeRange) : spec.timeRange;
|
|
1059
|
+
const effectiveTimeZone = sanitizeTimeZone(
|
|
1060
|
+
overrides.timeZone ?? effectiveTimeRange?.timeZone ?? spec.timeRange?.timeZone,
|
|
1061
|
+
);
|
|
1062
|
+
|
|
648
1063
|
const effectiveSpec: ReportSpec = {
|
|
649
1064
|
...spec,
|
|
650
1065
|
query: overrides.query !== undefined ? overrides.query.trim() : spec.query,
|
|
651
1066
|
filters: overrides.filters !== undefined ? normalizeReportFilters(overrides.filters) : spec.filters,
|
|
1067
|
+
// Security invariant: lockedFilters are server-owned and can never be replaced or cleared by runtime overrides.
|
|
1068
|
+
lockedFilters: spec.lockedFilters,
|
|
652
1069
|
sort: overrides.sort !== undefined ? normalizeReportSort(overrides.sort) : spec.sort,
|
|
653
|
-
timeRange:
|
|
1070
|
+
timeRange: effectiveTimeRange,
|
|
654
1071
|
};
|
|
655
1072
|
|
|
1073
|
+
const extraRuntimeFilters: ReportFilterItem[] = [
|
|
1074
|
+
...normalizeReportFilters(overrides.sharedFilters),
|
|
1075
|
+
...normalizeReportFilters(overrides.contextFilters),
|
|
1076
|
+
];
|
|
1077
|
+
|
|
656
1078
|
const page = clamp(typeof overrides.page === 'number' ? overrides.page : 1, 1, 10000);
|
|
657
1079
|
const pageSize = clamp(
|
|
658
1080
|
typeof overrides.pageSize === 'number' ? overrides.pageSize : spec.pageSize ?? DEFAULT_PAGE_SIZE,
|
|
@@ -664,6 +1086,8 @@ export function mergeSpecWithOverrides(
|
|
|
664
1086
|
|
|
665
1087
|
return {
|
|
666
1088
|
effectiveSpec,
|
|
1089
|
+
extraRuntimeFilters,
|
|
1090
|
+
...(effectiveTimeZone ? { effectiveTimeZone } : {}),
|
|
667
1091
|
page,
|
|
668
1092
|
pageSize,
|
|
669
1093
|
...(searchAfter ? { searchAfter } : {}),
|
|
@@ -675,7 +1099,10 @@ export function compileSearchRequest(options: CompileSearchOptions): {
|
|
|
675
1099
|
effectiveSpec: ReportSpec;
|
|
676
1100
|
} {
|
|
677
1101
|
const fieldMap = buildFieldCapabilityMap(options.fields);
|
|
678
|
-
const { effectiveSpec, page, pageSize, searchAfter } = mergeSpecWithOverrides(
|
|
1102
|
+
const { effectiveSpec, extraRuntimeFilters, effectiveTimeZone, page, pageSize, searchAfter } = mergeSpecWithOverrides(
|
|
1103
|
+
options.spec,
|
|
1104
|
+
options.overrides,
|
|
1105
|
+
);
|
|
679
1106
|
const maxCap = options.maxRowsCap ? clamp(options.maxRowsCap, 1, MAX_UI_PAGE_SIZE) : MAX_UI_PAGE_SIZE;
|
|
680
1107
|
const effectivePageSize = Math.min(pageSize, maxCap);
|
|
681
1108
|
const timeField = options.timeField?.trim() || null;
|
|
@@ -701,7 +1128,13 @@ export function compileSearchRequest(options: CompileSearchOptions): {
|
|
|
701
1128
|
}
|
|
702
1129
|
}
|
|
703
1130
|
|
|
704
|
-
|
|
1131
|
+
const resolvedLockedFilters = resolveServerLockedFilters(effectiveSpec.lockedFilters, options.userContext);
|
|
1132
|
+
const combinedFilters: ReportFilterItem[] = [
|
|
1133
|
+
...resolvedLockedFilters,
|
|
1134
|
+
...extraRuntimeFilters,
|
|
1135
|
+
...(effectiveSpec.filters ?? []),
|
|
1136
|
+
];
|
|
1137
|
+
for (const item of combinedFilters) {
|
|
705
1138
|
const compiled = compileFilterItem(item, fieldMap);
|
|
706
1139
|
if (!compiled) continue;
|
|
707
1140
|
if (compiled.negated) {
|
|
@@ -711,9 +1144,15 @@ export function compileSearchRequest(options: CompileSearchOptions): {
|
|
|
711
1144
|
}
|
|
712
1145
|
}
|
|
713
1146
|
|
|
714
|
-
const
|
|
715
|
-
|
|
716
|
-
|
|
1147
|
+
const currentTimeClause = compileTimeRange(effectiveSpec.timeRange, timeField, effectiveTimeZone);
|
|
1148
|
+
const previousTimeClause =
|
|
1149
|
+
effectiveSpec.visualization === 'metric' && effectiveSpec.chart?.comparePreviousPeriod === true
|
|
1150
|
+
? compilePreviousTimeRange(effectiveSpec.timeRange, timeField, effectiveTimeZone)
|
|
1151
|
+
: null;
|
|
1152
|
+
const useDualPeriodMetric = Boolean(currentTimeClause && previousTimeClause);
|
|
1153
|
+
|
|
1154
|
+
if (currentTimeClause && !useDualPeriodMetric) {
|
|
1155
|
+
filter.push(currentTimeClause);
|
|
717
1156
|
}
|
|
718
1157
|
|
|
719
1158
|
let queryDsl: Record<string, unknown>;
|
|
@@ -731,7 +1170,7 @@ export function compileSearchRequest(options: CompileSearchOptions): {
|
|
|
731
1170
|
|
|
732
1171
|
const body: Record<string, unknown> = {
|
|
733
1172
|
query: queryDsl,
|
|
734
|
-
track_total_hits: MAX_RESULT_WINDOW,
|
|
1173
|
+
track_total_hits: effectiveSpec.visualization === 'metric' ? true : MAX_RESULT_WINDOW,
|
|
735
1174
|
};
|
|
736
1175
|
|
|
737
1176
|
// Build sort clauses
|
|
@@ -746,7 +1185,7 @@ export function compileSearchRequest(options: CompileSearchOptions): {
|
|
|
746
1185
|
body.size = effectivePageSize;
|
|
747
1186
|
|
|
748
1187
|
if (requestedSorts.length > 0) {
|
|
749
|
-
|
|
1188
|
+
const sortClauses: Array<Record<string, unknown>> = requestedSorts.map((sortItem) => {
|
|
750
1189
|
const targetField = resolveAggregatableField(sortItem.field, fieldMap);
|
|
751
1190
|
const unmappedType = resolveUnmappedSortType(targetField, fieldMap);
|
|
752
1191
|
return {
|
|
@@ -756,6 +1195,16 @@ export function compileSearchRequest(options: CompileSearchOptions): {
|
|
|
756
1195
|
},
|
|
757
1196
|
};
|
|
758
1197
|
});
|
|
1198
|
+
const hasTieBreaker = requestedSorts.some(
|
|
1199
|
+
(s) => s.field === '_id' || s.field === '_shard_doc' || s.field === '_doc',
|
|
1200
|
+
);
|
|
1201
|
+
const legacyCursorMatchesUserSortOnly =
|
|
1202
|
+
searchAfter !== undefined && searchAfter.length === requestedSorts.length && !hasTieBreaker;
|
|
1203
|
+
if (!hasTieBreaker && !legacyCursorMatchesUserSortOnly) {
|
|
1204
|
+
const tieBreakerField = options.usePit ? '_shard_doc' : '_doc';
|
|
1205
|
+
sortClauses.push({ [tieBreakerField]: { order: 'asc' } });
|
|
1206
|
+
}
|
|
1207
|
+
body.sort = sortClauses;
|
|
759
1208
|
}
|
|
760
1209
|
|
|
761
1210
|
if (searchAfter && body.sort) {
|
|
@@ -787,6 +1236,7 @@ export function compileSearchRequest(options: CompileSearchOptions): {
|
|
|
787
1236
|
auto_date_histogram: {
|
|
788
1237
|
field: timeField,
|
|
789
1238
|
buckets: 24,
|
|
1239
|
+
...(effectiveTimeZone ? { time_zone: effectiveTimeZone } : {}),
|
|
790
1240
|
},
|
|
791
1241
|
},
|
|
792
1242
|
};
|
|
@@ -794,16 +1244,23 @@ export function compileSearchRequest(options: CompileSearchOptions): {
|
|
|
794
1244
|
} else if (effectiveSpec.visualization === 'metric') {
|
|
795
1245
|
body.size = 0;
|
|
796
1246
|
const metricType = effectiveSpec.chart?.metricType ?? 'count';
|
|
797
|
-
const
|
|
798
|
-
|
|
799
|
-
|
|
1247
|
+
const metricDef = buildMetricAggDefinition(metricType, effectiveSpec.chart?.metricField, fieldMap);
|
|
1248
|
+
|
|
1249
|
+
if (useDualPeriodMetric && currentTimeClause && previousTimeClause) {
|
|
800
1250
|
body.aggs = {
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
1251
|
+
es_current_window: {
|
|
1252
|
+
filter: currentTimeClause,
|
|
1253
|
+
...(metricDef ? { aggs: { es_metric: metricDef } } : {}),
|
|
1254
|
+
},
|
|
1255
|
+
es_previous_window: {
|
|
1256
|
+
filter: previousTimeClause,
|
|
1257
|
+
...(metricDef ? { aggs: { es_metric: metricDef } } : {}),
|
|
805
1258
|
},
|
|
806
1259
|
};
|
|
1260
|
+
} else if (metricDef) {
|
|
1261
|
+
body.aggs = {
|
|
1262
|
+
es_metric: metricDef,
|
|
1263
|
+
};
|
|
807
1264
|
}
|
|
808
1265
|
} else {
|
|
809
1266
|
// Chart visualizations: bar, line, area, pie
|
|
@@ -822,39 +1279,54 @@ export function compileSearchRequest(options: CompileSearchOptions): {
|
|
|
822
1279
|
|
|
823
1280
|
const bucketField = resolveAggregatableField(rawBucketField, fieldMap);
|
|
824
1281
|
const metricType = chartCfg.metricType ?? 'count';
|
|
825
|
-
const
|
|
826
|
-
const
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
1282
|
+
const metricDef = buildMetricAggDefinition(metricType, chartCfg.metricField, fieldMap);
|
|
1283
|
+
const canOrderByMetric = Boolean(metricDef) && metricType !== 'p50' && metricType !== 'p95' && metricType !== 'p99';
|
|
1284
|
+
|
|
1285
|
+
const rawSplitField = chartCfg.splitSeriesField?.trim();
|
|
1286
|
+
const splitField = rawSplitField ? resolveAggregatableField(rawSplitField, fieldMap) : undefined;
|
|
1287
|
+
const splitTopN = clamp(chartCfg.splitSeriesTopN ?? 5, 1, MAX_SPLIT_SERIES);
|
|
1288
|
+
|
|
1289
|
+
const bucketChildAggs: Record<string, unknown> = {};
|
|
1290
|
+
if (metricDef) {
|
|
1291
|
+
bucketChildAggs.es_metric = metricDef;
|
|
1292
|
+
}
|
|
1293
|
+
if (splitField) {
|
|
1294
|
+
bucketChildAggs.es_split = {
|
|
1295
|
+
terms: {
|
|
1296
|
+
field: splitField,
|
|
1297
|
+
size: splitTopN,
|
|
1298
|
+
...(canOrderByMetric ? { order: { es_metric: 'desc' } } : {}),
|
|
1299
|
+
},
|
|
1300
|
+
...(metricDef ? { aggs: { es_metric: metricDef } } : {}),
|
|
1301
|
+
};
|
|
1302
|
+
}
|
|
1303
|
+
const hasChildAggs = Object.keys(bucketChildAggs).length > 0;
|
|
836
1304
|
|
|
837
1305
|
if (defaultBucketType === 'date_histogram') {
|
|
838
1306
|
const interval = chartCfg.calendarInterval ?? 'auto';
|
|
1307
|
+
const intervalKey =
|
|
1308
|
+
interval !== 'auto' && CALENDAR_UNIT_INTERVALS.has(interval) ? 'calendar_interval' : 'fixed_interval';
|
|
839
1309
|
const bucketAgg =
|
|
840
1310
|
interval === 'auto'
|
|
841
1311
|
? {
|
|
842
1312
|
auto_date_histogram: {
|
|
843
1313
|
field: bucketField,
|
|
844
1314
|
buckets: 24,
|
|
1315
|
+
...(effectiveTimeZone ? { time_zone: effectiveTimeZone } : {}),
|
|
845
1316
|
},
|
|
846
1317
|
}
|
|
847
1318
|
: {
|
|
848
1319
|
date_histogram: {
|
|
849
1320
|
field: bucketField,
|
|
850
|
-
|
|
1321
|
+
[intervalKey]: interval,
|
|
851
1322
|
min_doc_count: 0,
|
|
1323
|
+
...(effectiveTimeZone ? { time_zone: effectiveTimeZone } : {}),
|
|
852
1324
|
},
|
|
853
1325
|
};
|
|
854
1326
|
body.aggs = {
|
|
855
1327
|
es_buckets: {
|
|
856
1328
|
...bucketAgg,
|
|
857
|
-
...(
|
|
1329
|
+
...(hasChildAggs ? { aggs: bucketChildAggs } : {}),
|
|
858
1330
|
},
|
|
859
1331
|
};
|
|
860
1332
|
} else {
|
|
@@ -864,9 +1336,9 @@ export function compileSearchRequest(options: CompileSearchOptions): {
|
|
|
864
1336
|
terms: {
|
|
865
1337
|
field: bucketField,
|
|
866
1338
|
size: topN,
|
|
867
|
-
...(
|
|
1339
|
+
...(canOrderByMetric ? { order: { es_metric: 'desc' } } : {}),
|
|
868
1340
|
},
|
|
869
|
-
...(
|
|
1341
|
+
...(hasChildAggs ? { aggs: bucketChildAggs } : {}),
|
|
870
1342
|
},
|
|
871
1343
|
};
|
|
872
1344
|
}
|
|
@@ -913,6 +1385,22 @@ export function parseSearchResponse(
|
|
|
913
1385
|
): ReportExecutionResult {
|
|
914
1386
|
const res = isRecord(rawResponse) ? rawResponse : {};
|
|
915
1387
|
const tookMs = typeof res.took === 'number' ? res.took : 0;
|
|
1388
|
+
const timedOut = res.timed_out === true;
|
|
1389
|
+
const shards: ReportShardStats | undefined = isRecord(res._shards)
|
|
1390
|
+
? {
|
|
1391
|
+
total: typeof res._shards.total === 'number' ? res._shards.total : 0,
|
|
1392
|
+
successful: typeof res._shards.successful === 'number' ? res._shards.successful : 0,
|
|
1393
|
+
skipped: typeof res._shards.skipped === 'number' ? res._shards.skipped : 0,
|
|
1394
|
+
failed: typeof res._shards.failed === 'number' ? res._shards.failed : 0,
|
|
1395
|
+
}
|
|
1396
|
+
: undefined;
|
|
1397
|
+
const warnings: string[] = [];
|
|
1398
|
+
if (timedOut) {
|
|
1399
|
+
warnings.push('Elasticsearch query timed out; displayed results may be incomplete.');
|
|
1400
|
+
}
|
|
1401
|
+
if (shards && shards.failed > 0) {
|
|
1402
|
+
warnings.push(`Partial results: ${shards.failed} of ${shards.total} Elasticsearch shards failed.`);
|
|
1403
|
+
}
|
|
916
1404
|
|
|
917
1405
|
const hitsContainer = isRecord(res.hits) ? res.hits : {};
|
|
918
1406
|
const rawTotal = hitsContainer.total;
|
|
@@ -970,47 +1458,94 @@ export function parseSearchResponse(
|
|
|
970
1458
|
}
|
|
971
1459
|
}
|
|
972
1460
|
|
|
1461
|
+
const metricType = spec.chart?.metricType ?? 'count';
|
|
973
1462
|
const series: ReportSeriesPoint[] = [];
|
|
1463
|
+
const seenSeriesKeys = new Set<string>();
|
|
974
1464
|
if (isRecord(aggs.es_buckets) && Array.isArray(aggs.es_buckets.buckets)) {
|
|
975
1465
|
for (const bucket of aggs.es_buckets.buckets) {
|
|
976
1466
|
if (!isRecord(bucket)) continue;
|
|
977
1467
|
const label = typeof bucket.key_as_string === 'string' ? bucket.key_as_string : String(bucket.key ?? '');
|
|
978
1468
|
const docCount = typeof bucket.doc_count === 'number' ? bucket.doc_count : 0;
|
|
979
|
-
const
|
|
980
|
-
const metricVal =
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
1469
|
+
const extracted = extractMetricValue(bucket.es_metric, metricType, docCount);
|
|
1470
|
+
const metricVal = extracted ?? docCount;
|
|
1471
|
+
|
|
1472
|
+
let breakdown: ReportSubSeriesPoint[] | undefined;
|
|
1473
|
+
if (isRecord(bucket.es_split) && Array.isArray(bucket.es_split.buckets)) {
|
|
1474
|
+
breakdown = [];
|
|
1475
|
+
for (const sub of bucket.es_split.buckets) {
|
|
1476
|
+
if (!isRecord(sub)) continue;
|
|
1477
|
+
const sKey = typeof sub.key_as_string === 'string' ? sub.key_as_string : String(sub.key ?? '');
|
|
1478
|
+
const sCount = typeof sub.doc_count === 'number' ? sub.doc_count : 0;
|
|
1479
|
+
const sVal = extractMetricValue(sub.es_metric, metricType, sCount) ?? sCount;
|
|
1480
|
+
seenSeriesKeys.add(sKey);
|
|
1481
|
+
breakdown.push({
|
|
1482
|
+
seriesKey: sKey,
|
|
1483
|
+
value: sVal,
|
|
1484
|
+
count: sCount,
|
|
1485
|
+
});
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
|
|
984
1489
|
series.push({
|
|
985
1490
|
key: String(bucket.key ?? label),
|
|
986
1491
|
label,
|
|
987
1492
|
value: metricVal,
|
|
988
1493
|
count: docCount,
|
|
1494
|
+
...(breakdown ? { breakdown } : {}),
|
|
989
1495
|
});
|
|
990
1496
|
}
|
|
991
1497
|
}
|
|
992
1498
|
|
|
993
1499
|
let metricValue: number | null = null;
|
|
1500
|
+
let previousMetricValue: number | null | undefined;
|
|
1501
|
+
let deltaPercent: number | null | undefined;
|
|
1502
|
+
|
|
994
1503
|
if (spec.visualization === 'metric') {
|
|
995
|
-
|
|
996
|
-
|
|
1504
|
+
if (isRecord(aggs.es_current_window) && isRecord(aggs.es_previous_window)) {
|
|
1505
|
+
const curCount = typeof aggs.es_current_window.doc_count === 'number' ? aggs.es_current_window.doc_count : 0;
|
|
1506
|
+
const prevCount = typeof aggs.es_previous_window.doc_count === 'number' ? aggs.es_previous_window.doc_count : 0;
|
|
1507
|
+
total = curCount;
|
|
1508
|
+
totalRelation = 'eq';
|
|
1509
|
+
metricValue =
|
|
1510
|
+
metricType === 'count' || !spec.chart?.metricField
|
|
1511
|
+
? curCount
|
|
1512
|
+
: extractMetricValue(aggs.es_current_window.es_metric, metricType, curCount);
|
|
1513
|
+
previousMetricValue =
|
|
1514
|
+
metricType === 'count' || !spec.chart?.metricField
|
|
1515
|
+
? prevCount
|
|
1516
|
+
: extractMetricValue(aggs.es_previous_window.es_metric, metricType, prevCount);
|
|
1517
|
+
if (metricValue !== null && previousMetricValue !== null && previousMetricValue !== 0) {
|
|
1518
|
+
deltaPercent = Number((((metricValue - previousMetricValue) / Math.abs(previousMetricValue)) * 100).toFixed(2));
|
|
1519
|
+
} else {
|
|
1520
|
+
deltaPercent = null;
|
|
1521
|
+
}
|
|
1522
|
+
} else if (metricType === 'count' || !spec.chart?.metricField) {
|
|
997
1523
|
metricValue = total;
|
|
998
|
-
} else
|
|
999
|
-
metricValue =
|
|
1524
|
+
} else {
|
|
1525
|
+
metricValue = extractMetricValue(aggs.es_metric, metricType, total);
|
|
1000
1526
|
}
|
|
1001
1527
|
}
|
|
1002
1528
|
|
|
1529
|
+
const responsePitId = typeof res.pit_id === 'string' && res.pit_id ? res.pit_id : undefined;
|
|
1530
|
+
|
|
1003
1531
|
return {
|
|
1004
1532
|
total,
|
|
1005
1533
|
totalRelation,
|
|
1006
1534
|
tookMs,
|
|
1535
|
+
...(timedOut ? { timedOut: true } : {}),
|
|
1536
|
+
...(shards ? { shards } : {}),
|
|
1537
|
+
...(warnings.length > 0 ? { warnings } : {}),
|
|
1007
1538
|
visualization: spec.visualization,
|
|
1008
1539
|
rows,
|
|
1009
1540
|
columns,
|
|
1010
1541
|
...(nextSearchAfter ? { nextSearchAfter } : {}),
|
|
1542
|
+
...(responsePitId ? { pitId: responsePitId } : {}),
|
|
1011
1543
|
series,
|
|
1544
|
+
...(seenSeriesKeys.size > 0 ? { seriesKeys: Array.from(seenSeriesKeys) } : {}),
|
|
1012
1545
|
histogram,
|
|
1013
1546
|
metricValue,
|
|
1547
|
+
...(previousMetricValue !== undefined ? { previousMetricValue } : {}),
|
|
1548
|
+
...(deltaPercent !== undefined ? { deltaPercent } : {}),
|
|
1014
1549
|
metricLabel: buildDefaultMetricLabel(spec),
|
|
1015
1550
|
compiledDsl,
|
|
1016
1551
|
};
|