plugin-elastic-report 0.1.1 → 0.9.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.
Files changed (80) hide show
  1. package/client-v2.d.ts +2 -2
  2. package/client-v2.js +1 -1
  3. package/client.d.ts +2 -2
  4. package/client.js +1 -1
  5. package/dist/ai/skills/elastic-report/SKILLS.md +52 -0
  6. package/dist/client/357.0dd385384cab5dbf.js +10 -0
  7. package/dist/client/index.js +1 -1
  8. package/dist/client-v2/851.35e416bfb3fb565f.js +10 -0
  9. package/dist/client-v2/857.a5bf9637d5fd4ef5.js +10 -0
  10. package/dist/client-v2/877.81b10beb7b7f4bd7.js +10 -0
  11. package/dist/client-v2/index.js +1 -1
  12. package/dist/externalVersion.js +5 -3
  13. package/dist/locale/en-US.json +213 -99
  14. package/dist/locale/vi-VN.json +213 -99
  15. package/dist/locale/zh-CN.json +213 -99
  16. package/dist/node_modules/@elastic/elasticsearch/package.json +1 -1
  17. package/dist/server/acl-guard.js +97 -25
  18. package/dist/server/collections/es-report-data-views.js +6 -0
  19. package/dist/server/collections/es-reports.js +6 -0
  20. package/dist/server/mcp/ElasticReportToolCatalog.js +238 -14
  21. package/dist/server/plugin.js +156 -22
  22. package/dist/server/report-block-tools.js +340 -0
  23. package/dist/server/services/ElasticReportService.js +137 -17
  24. package/dist/server/services/ElasticsearchConnectionService.js +274 -34
  25. package/dist/server/services/ReportExportService.js +243 -0
  26. package/dist/server/services/ReportQueryCompiler.js +532 -91
  27. package/dist/server/workflow/ElasticReportQueryInstruction.js +123 -0
  28. package/dist/shared/constants.js +26 -2
  29. package/package.json +3 -3
  30. package/server.d.ts +2 -2
  31. package/server.js +1 -1
  32. package/src/ai/skills/elastic-report/SKILLS.md +52 -0
  33. package/src/client/index.tsx +34 -19
  34. package/src/client/workflow-instructions.tsx +44 -0
  35. package/src/client-v2/__tests__/elastic-report.test.tsx +879 -311
  36. package/src/client-v2/__tests__/kql-autocomplete.test.ts +178 -0
  37. package/src/client-v2/api.ts +320 -224
  38. package/src/client-v2/bus/DashboardFilterBus.ts +212 -0
  39. package/src/client-v2/components/ElasticBasicCharts.tsx +652 -399
  40. package/src/client-v2/components/ElasticFilterBar.tsx +372 -0
  41. package/src/client-v2/components/ElasticKqlInput.tsx +421 -0
  42. package/src/client-v2/components/ElasticReportBlock.tsx +306 -160
  43. package/src/client-v2/components/ElasticReportRenderer.tsx +1257 -707
  44. package/src/client-v2/components/HighlightText.tsx +50 -50
  45. package/src/client-v2/components/ReportSelect.tsx +85 -72
  46. package/src/client-v2/index.tsx +14 -14
  47. package/src/client-v2/locale.ts +23 -23
  48. package/src/client-v2/models/ElasticFilterBarBlockModel.tsx +115 -0
  49. package/src/client-v2/models/ElasticReportBlockModel.tsx +118 -85
  50. package/src/client-v2/pages/ElasticReportManager.tsx +1453 -1047
  51. package/src/client-v2/plugin.tsx +107 -52
  52. package/src/client-v2/report-destination.tsx +126 -0
  53. package/src/client-v2/utils/kqlAutocomplete.ts +861 -0
  54. package/src/client-v2/workflow/instructions.tsx +149 -0
  55. package/src/index.ts +11 -11
  56. package/src/locale/en-US.json +213 -99
  57. package/src/locale/vi-VN.json +213 -99
  58. package/src/locale/zh-CN.json +213 -99
  59. package/src/server/__tests__/ai-blocks.integration.test.ts +292 -0
  60. package/src/server/__tests__/query-compiler.test.ts +620 -231
  61. package/src/server/__tests__/report-mcp-acl.integration.test.ts +645 -377
  62. package/src/server/acl-guard.ts +194 -103
  63. package/src/server/collections/es-report-data-views.ts +64 -58
  64. package/src/server/collections/es-reports.ts +80 -74
  65. package/src/server/index.ts +15 -15
  66. package/src/server/mcp/ElasticReportMcpServer.ts +391 -391
  67. package/src/server/mcp/ElasticReportToolCatalog.ts +667 -417
  68. package/src/server/plugin.ts +599 -431
  69. package/src/server/report-block-tools.ts +400 -0
  70. package/src/server/services/ElasticReportService.ts +494 -326
  71. package/src/server/services/ElasticsearchConnectionService.ts +728 -401
  72. package/src/server/services/ReportExportService.ts +282 -0
  73. package/src/server/services/ReportQueryCompiler.ts +1552 -1017
  74. package/src/server/workflow/ElasticReportQueryInstruction.ts +124 -0
  75. package/src/shared/constants.ts +39 -29
  76. package/src/shared/types.ts +272 -175
  77. package/ai/skills/elastic-report/SKILLS.md +0 -32
  78. package/dist/client-v2/851.488fdbf5bc5b6a36.js +0 -10
  79. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv +0 -15
  80. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv.cmd +0 -7
@@ -1,231 +1,620 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
-
10
- import { describe, expect, it } from 'vitest';
11
- import { HIGHLIGHT_POST_TAG, HIGHLIGHT_PRE_TAG } from '../../shared/constants';
12
- import type { EsFieldCapability } from '../../shared/types';
13
- import {
14
- buildFieldCapabilityMap,
15
- compileKqlToQueryDsl,
16
- compileSearchRequest,
17
- normalizeReportSpec,
18
- parseSearchResponse,
19
- } from '../services/ReportQueryCompiler';
20
-
21
- const SAMPLE_FIELDS: EsFieldCapability[] = [
22
- { name: '@timestamp', type: 'date', searchable: true, aggregatable: true },
23
- {
24
- name: 'service',
25
- type: 'text',
26
- searchable: true,
27
- aggregatable: false,
28
- keywordSubfield: 'service.keyword',
29
- },
30
- {
31
- name: 'service.keyword',
32
- type: 'keyword',
33
- searchable: true,
34
- aggregatable: true,
35
- isSubfield: true,
36
- },
37
- { name: 'status', type: 'integer', searchable: true, aggregatable: true },
38
- { name: 'latency_ms', type: 'double', searchable: true, aggregatable: true },
39
- ];
40
-
41
- describe('ReportQueryCompiler', () => {
42
- it('compiles KQL boolean, range, wildcard, exists, and phrase clauses accurately', () => {
43
- const fieldMap = buildFieldCapabilityMap(SAMPLE_FIELDS);
44
-
45
- const dsl = compileKqlToQueryDsl(
46
- 'status >= 500 AND (service: "checkout-api" OR service: auth*) AND NOT trace_id: *',
47
- fieldMap,
48
- );
49
-
50
- expect(dsl).toEqual({
51
- bool: {
52
- must: [
53
- { range: { status: { gte: 500 } } },
54
- {
55
- bool: {
56
- should: [
57
- { match_phrase: { service: 'checkout-api' } },
58
- { wildcard: { 'service.keyword': { value: 'auth*', case_insensitive: true } } },
59
- ],
60
- minimum_should_match: 1,
61
- },
62
- },
63
- {
64
- bool: {
65
- must_not: [{ exists: { field: 'trace_id' } }],
66
- },
67
- },
68
- ],
69
- },
70
- });
71
- });
72
-
73
- it('resolves .keyword subfield automatically for filters and sorts on text fields', () => {
74
- const spec = normalizeReportSpec({
75
- visualization: 'table',
76
- query: 'timeout',
77
- filters: [
78
- { field: 'service', operator: 'eq', value: 'payment' },
79
- { field: 'status', operator: 'ne', value: 200 },
80
- ],
81
- sort: [{ field: 'service', order: 'asc' }],
82
- timeRange: { preset: 'last_1h' },
83
- columns: ['@timestamp', 'service', 'status'],
84
- pageSize: 25,
85
- });
86
-
87
- const { body } = compileSearchRequest({
88
- spec,
89
- timeField: '@timestamp',
90
- fields: SAMPLE_FIELDS,
91
- });
92
-
93
- expect(body.size).toBe(25);
94
- expect(body.sort).toEqual([{ 'service.keyword': { order: 'asc', unmapped_type: 'keyword' } }]);
95
- expect(body.query).toEqual({
96
- bool: {
97
- must: [
98
- {
99
- simple_query_string: {
100
- query: 'timeout',
101
- default_operator: 'and',
102
- lenient: true,
103
- },
104
- },
105
- ],
106
- filter: [
107
- { term: { 'service.keyword': 'payment' } },
108
- { range: { '@timestamp': { gte: 'now-1h', lte: 'now' } } },
109
- ],
110
- must_not: [{ term: { status: 200 } }],
111
- },
112
- });
113
- expect(body.aggs).toEqual({
114
- es_time_histogram: {
115
- auto_date_histogram: {
116
- field: '@timestamp',
117
- buckets: 24,
118
- },
119
- },
120
- });
121
- });
122
-
123
- it('supports search_after cursor pagination and chart bucket/metric aggregations', () => {
124
- const tableSpec = normalizeReportSpec({
125
- visualization: 'table',
126
- sort: [{ field: '@timestamp', order: 'desc' }],
127
- });
128
-
129
- const paged = compileSearchRequest({
130
- spec: tableSpec,
131
- overrides: { searchAfter: [1730000000000] },
132
- timeField: '@timestamp',
133
- fields: SAMPLE_FIELDS,
134
- });
135
- expect(paged.body.search_after).toEqual([1730000000000]);
136
- expect(paged.body.from).toBeUndefined();
137
-
138
- const barSpec = normalizeReportSpec({
139
- visualization: 'bar',
140
- chart: {
141
- bucketType: 'terms',
142
- bucketField: 'service',
143
- topN: 5,
144
- metricType: 'avg',
145
- metricField: 'latency_ms',
146
- metricLabel: 'Avg Latency (ms)',
147
- },
148
- });
149
-
150
- const { body: chartBody, effectiveSpec } = compileSearchRequest({
151
- spec: barSpec,
152
- timeField: '@timestamp',
153
- fields: SAMPLE_FIELDS,
154
- });
155
-
156
- expect(chartBody.size).toBe(0);
157
- expect(chartBody.aggs).toEqual({
158
- es_buckets: {
159
- terms: {
160
- field: 'service.keyword',
161
- size: 5,
162
- order: { es_metric: 'desc' },
163
- },
164
- aggs: {
165
- es_metric: {
166
- avg: { field: 'latency_ms' },
167
- },
168
- },
169
- },
170
- });
171
-
172
- const parsed = parseSearchResponse(
173
- {
174
- took: 7,
175
- hits: { total: { value: 42, relation: 'eq' }, hits: [] },
176
- aggregations: {
177
- es_buckets: {
178
- buckets: [
179
- { key: 'checkout', doc_count: 30, es_metric: { value: 123.45678 } },
180
- { key: 'search', doc_count: 12, es_metric: { value: 48.5 } },
181
- ],
182
- },
183
- },
184
- },
185
- chartBody,
186
- effectiveSpec,
187
- '@timestamp',
188
- );
189
-
190
- expect(parsed.total).toBe(42);
191
- expect(parsed.metricLabel).toBe('Avg Latency (ms)');
192
- expect(parsed.series).toEqual([
193
- { key: 'checkout', label: 'checkout', value: 123.4568, count: 30 },
194
- { key: 'search', label: 'search', value: 48.5, count: 12 },
195
- ]);
196
- });
197
-
198
- it('extracts document rows, cursor sort values, and safe highlight tokens', () => {
199
- const spec = normalizeReportSpec({ visualization: 'table', query: 'error' });
200
- const parsed = parseSearchResponse(
201
- {
202
- took: 3,
203
- hits: {
204
- total: { value: 1, relation: 'eq' },
205
- hits: [
206
- {
207
- _id: 'doc-1',
208
- _index: 'logs-2026.11',
209
- sort: [1732900000000],
210
- _source: {
211
- '@timestamp': '2026-11-30T00:00:00Z',
212
- message: 'Upstream error timeout',
213
- },
214
- highlight: {
215
- message: [`Upstream ${HIGHLIGHT_PRE_TAG}error${HIGHLIGHT_POST_TAG} timeout`],
216
- },
217
- },
218
- ],
219
- },
220
- },
221
- { query: { match_all: {} } },
222
- spec,
223
- '@timestamp',
224
- );
225
-
226
- expect(parsed.rows).toHaveLength(1);
227
- expect(parsed.nextSearchAfter).toEqual([1732900000000]);
228
- expect(parsed.columns).toEqual(['@timestamp', 'message']);
229
- expect(parsed.rows[0].highlights?.message?.[0]).toContain(HIGHLIGHT_PRE_TAG);
230
- });
231
- });
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import { describe, expect, it } from 'vitest';
11
+ import { HIGHLIGHT_POST_TAG, HIGHLIGHT_PRE_TAG } from '../../shared/constants';
12
+ import type { EsFieldCapability } from '../../shared/types';
13
+ import { buildEsClientOptions, inferConnectionModes } from '../services/ElasticsearchConnectionService';
14
+ import { escapeCsvCell } from '../services/ReportExportService';
15
+ import {
16
+ KqlSyntaxError,
17
+ buildFieldCapabilityMap,
18
+ compileKqlToQueryDsl,
19
+ compileSearchRequest,
20
+ normalizeReportSpec,
21
+ parseSearchResponse,
22
+ resolveServerLockedFilters,
23
+ } from '../services/ReportQueryCompiler';
24
+ import { evaluateThreshold } from '../workflow/ElasticReportQueryInstruction';
25
+
26
+ const SAMPLE_FIELDS: EsFieldCapability[] = [
27
+ { name: '@timestamp', type: 'date', searchable: true, aggregatable: true },
28
+ {
29
+ name: 'service',
30
+ type: 'text',
31
+ searchable: true,
32
+ aggregatable: false,
33
+ keywordSubfield: 'service.keyword',
34
+ },
35
+ {
36
+ name: 'service.keyword',
37
+ type: 'keyword',
38
+ searchable: true,
39
+ aggregatable: true,
40
+ isSubfield: true,
41
+ },
42
+ { name: 'status', type: 'integer', searchable: true, aggregatable: true },
43
+ { name: 'latency_ms', type: 'double', searchable: true, aggregatable: true },
44
+ ];
45
+
46
+ describe('ReportQueryCompiler', () => {
47
+ it('compiles KQL boolean, range, wildcard, exists, and phrase clauses accurately', () => {
48
+ const fieldMap = buildFieldCapabilityMap(SAMPLE_FIELDS);
49
+
50
+ const dsl = compileKqlToQueryDsl(
51
+ 'status >= 500 AND (service: "checkout-api" OR service: auth*) AND NOT trace_id: *',
52
+ fieldMap,
53
+ );
54
+
55
+ expect(dsl).toEqual({
56
+ bool: {
57
+ must: [
58
+ { range: { status: { gte: 500 } } },
59
+ {
60
+ bool: {
61
+ should: [
62
+ { match_phrase: { service: 'checkout-api' } },
63
+ { wildcard: { 'service.keyword': { value: 'auth*', case_insensitive: true } } },
64
+ ],
65
+ minimum_should_match: 1,
66
+ },
67
+ },
68
+ {
69
+ bool: {
70
+ must_not: [{ exists: { field: 'trace_id' } }],
71
+ },
72
+ },
73
+ ],
74
+ },
75
+ });
76
+ });
77
+
78
+ it('resolves .keyword subfield automatically for filters and sorts on text fields', () => {
79
+ const spec = normalizeReportSpec({
80
+ visualization: 'table',
81
+ query: 'timeout',
82
+ filters: [
83
+ { field: 'service', operator: 'eq', value: 'payment' },
84
+ { field: 'status', operator: 'ne', value: 200 },
85
+ ],
86
+ sort: [{ field: 'service', order: 'asc' }],
87
+ timeRange: { preset: 'last_1h' },
88
+ columns: ['@timestamp', 'service', 'status'],
89
+ pageSize: 25,
90
+ });
91
+
92
+ const { body } = compileSearchRequest({
93
+ spec,
94
+ timeField: '@timestamp',
95
+ fields: SAMPLE_FIELDS,
96
+ });
97
+
98
+ expect(body.size).toBe(25);
99
+ expect(body.sort).toEqual([
100
+ { 'service.keyword': { order: 'asc', unmapped_type: 'keyword' } },
101
+ { _doc: { order: 'asc' } },
102
+ ]);
103
+ expect(body.query).toEqual({
104
+ bool: {
105
+ must: [
106
+ {
107
+ simple_query_string: {
108
+ query: 'timeout',
109
+ default_operator: 'and',
110
+ lenient: true,
111
+ },
112
+ },
113
+ ],
114
+ filter: [
115
+ { term: { 'service.keyword': 'payment' } },
116
+ { range: { '@timestamp': { gte: 'now-1h', lte: 'now' } } },
117
+ ],
118
+ must_not: [{ term: { status: 200 } }],
119
+ },
120
+ });
121
+ expect(body.aggs).toEqual({
122
+ es_time_histogram: {
123
+ auto_date_histogram: {
124
+ field: '@timestamp',
125
+ buckets: 24,
126
+ },
127
+ },
128
+ });
129
+ });
130
+
131
+ it('supports search_after cursor pagination and chart bucket/metric aggregations', () => {
132
+ const tableSpec = normalizeReportSpec({
133
+ visualization: 'table',
134
+ sort: [{ field: '@timestamp', order: 'desc' }],
135
+ });
136
+
137
+ const paged = compileSearchRequest({
138
+ spec: tableSpec,
139
+ overrides: { searchAfter: [1730000000000] },
140
+ timeField: '@timestamp',
141
+ fields: SAMPLE_FIELDS,
142
+ });
143
+ expect(paged.body.search_after).toEqual([1730000000000]);
144
+ expect(paged.body.from).toBeUndefined();
145
+
146
+ const barSpec = normalizeReportSpec({
147
+ visualization: 'bar',
148
+ chart: {
149
+ bucketType: 'terms',
150
+ bucketField: 'service',
151
+ topN: 5,
152
+ metricType: 'avg',
153
+ metricField: 'latency_ms',
154
+ metricLabel: 'Avg Latency (ms)',
155
+ },
156
+ });
157
+
158
+ const { body: chartBody, effectiveSpec } = compileSearchRequest({
159
+ spec: barSpec,
160
+ timeField: '@timestamp',
161
+ fields: SAMPLE_FIELDS,
162
+ });
163
+
164
+ expect(chartBody.size).toBe(0);
165
+ expect(chartBody.aggs).toEqual({
166
+ es_buckets: {
167
+ terms: {
168
+ field: 'service.keyword',
169
+ size: 5,
170
+ order: { es_metric: 'desc' },
171
+ },
172
+ aggs: {
173
+ es_metric: {
174
+ avg: { field: 'latency_ms' },
175
+ },
176
+ },
177
+ },
178
+ });
179
+
180
+ const parsed = parseSearchResponse(
181
+ {
182
+ took: 7,
183
+ hits: { total: { value: 42, relation: 'eq' }, hits: [] },
184
+ aggregations: {
185
+ es_buckets: {
186
+ buckets: [
187
+ { key: 'checkout', doc_count: 30, es_metric: { value: 123.45678 } },
188
+ { key: 'search', doc_count: 12, es_metric: { value: 48.5 } },
189
+ ],
190
+ },
191
+ },
192
+ },
193
+ chartBody,
194
+ effectiveSpec,
195
+ '@timestamp',
196
+ );
197
+
198
+ expect(parsed.total).toBe(42);
199
+ expect(parsed.metricLabel).toBe('Avg Latency (ms)');
200
+ expect(parsed.series).toEqual([
201
+ { key: 'checkout', label: 'checkout', value: 123.4568, count: 30 },
202
+ { key: 'search', label: 'search', value: 48.5, count: 12 },
203
+ ]);
204
+ });
205
+
206
+ it('extracts document rows, cursor sort values, and safe highlight tokens', () => {
207
+ const spec = normalizeReportSpec({ visualization: 'table', query: 'error' });
208
+ const parsed = parseSearchResponse(
209
+ {
210
+ took: 3,
211
+ hits: {
212
+ total: { value: 1, relation: 'eq' },
213
+ hits: [
214
+ {
215
+ _id: 'doc-1',
216
+ _index: 'logs-2026.11',
217
+ sort: [1732900000000],
218
+ _source: {
219
+ '@timestamp': '2026-11-30T00:00:00Z',
220
+ message: 'Upstream error timeout',
221
+ },
222
+ highlight: {
223
+ message: [`Upstream ${HIGHLIGHT_PRE_TAG}error${HIGHLIGHT_POST_TAG} timeout`],
224
+ },
225
+ },
226
+ ],
227
+ },
228
+ },
229
+ { query: { match_all: {} } },
230
+ spec,
231
+ '@timestamp',
232
+ );
233
+
234
+ expect(parsed.rows).toHaveLength(1);
235
+ expect(parsed.nextSearchAfter).toEqual([1732900000000]);
236
+ expect(parsed.columns).toEqual(['@timestamp', 'message']);
237
+ expect(parsed.rows[0].highlights?.message?.[0]).toContain(HIGHLIGHT_PRE_TAG);
238
+ });
239
+
240
+ it('uses track_total_hits: true for KPI metric count and fixed_interval for 5m/15m date histograms', () => {
241
+ const metricSpec = normalizeReportSpec({
242
+ visualization: 'metric',
243
+ chart: { metricType: 'count' },
244
+ });
245
+ const { body: metricBody } = compileSearchRequest({
246
+ spec: metricSpec,
247
+ timeField: '@timestamp',
248
+ fields: SAMPLE_FIELDS,
249
+ });
250
+ expect(metricBody.size).toBe(0);
251
+ expect(metricBody.track_total_hits).toBe(true);
252
+
253
+ const line5m = compileSearchRequest({
254
+ spec: normalizeReportSpec({
255
+ visualization: 'line',
256
+ chart: { bucketType: 'date_histogram', calendarInterval: '5m' },
257
+ }),
258
+ timeField: '@timestamp',
259
+ fields: SAMPLE_FIELDS,
260
+ });
261
+ expect(line5m.body.aggs).toEqual({
262
+ es_buckets: {
263
+ date_histogram: {
264
+ field: '@timestamp',
265
+ fixed_interval: '5m',
266
+ min_doc_count: 0,
267
+ },
268
+ },
269
+ });
270
+
271
+ const line15m = compileSearchRequest({
272
+ spec: normalizeReportSpec({
273
+ visualization: 'area',
274
+ chart: { bucketType: 'date_histogram', calendarInterval: '15m' },
275
+ }),
276
+ timeField: '@timestamp',
277
+ fields: SAMPLE_FIELDS,
278
+ });
279
+ expect(line15m.body.aggs).toEqual({
280
+ es_buckets: {
281
+ date_histogram: {
282
+ field: '@timestamp',
283
+ fixed_interval: '15m',
284
+ min_doc_count: 0,
285
+ },
286
+ },
287
+ });
288
+
289
+ const line1h = compileSearchRequest({
290
+ spec: normalizeReportSpec({
291
+ visualization: 'line',
292
+ chart: { bucketType: 'date_histogram', calendarInterval: '1h' },
293
+ }),
294
+ timeField: '@timestamp',
295
+ fields: SAMPLE_FIELDS,
296
+ });
297
+ expect(line1h.body.aggs).toEqual({
298
+ es_buckets: {
299
+ date_histogram: {
300
+ field: '@timestamp',
301
+ calendar_interval: '1h',
302
+ min_doc_count: 0,
303
+ },
304
+ },
305
+ });
306
+ });
307
+
308
+ it('supports KQL field value groups and throws KqlSyntaxError on invalid KQL syntax', () => {
309
+ const fieldMap = buildFieldCapabilityMap(SAMPLE_FIELDS);
310
+
311
+ expect(compileKqlToQueryDsl('status: (400 OR 404)', fieldMap)).toEqual({
312
+ bool: {
313
+ should: [{ term: { status: 400 } }, { term: { status: 404 } }],
314
+ minimum_should_match: 1,
315
+ },
316
+ });
317
+
318
+ expect(
319
+ compileKqlToQueryDsl('service: ("checkout-api" OR auth*) AND latency_ms: (>= 100 AND < 500)', fieldMap),
320
+ ).toEqual({
321
+ bool: {
322
+ must: [
323
+ {
324
+ bool: {
325
+ should: [
326
+ { match_phrase: { service: 'checkout-api' } },
327
+ { wildcard: { 'service.keyword': { value: 'auth*', case_insensitive: true } } },
328
+ ],
329
+ minimum_should_match: 1,
330
+ },
331
+ },
332
+ {
333
+ bool: {
334
+ must: [{ range: { latency_ms: { gte: 100 } } }, { range: { latency_ms: { lt: 500 } } }],
335
+ },
336
+ },
337
+ ],
338
+ },
339
+ });
340
+
341
+ expect(() => compileKqlToQueryDsl('status: (400 OR', fieldMap)).toThrow(KqlSyntaxError);
342
+ expect(() => compileKqlToQueryDsl('status: [400 TO 499]', fieldMap)).toThrow(KqlSyntaxError);
343
+ expect(() => compileKqlToQueryDsl('service: "unclosed', fieldMap)).toThrow(KqlSyntaxError);
344
+ expect(() => compileKqlToQueryDsl('AND status: 500', fieldMap)).toThrow(KqlSyntaxError);
345
+ expect(() => compileKqlToQueryDsl('status:', fieldMap)).toThrow(KqlSyntaxError);
346
+ });
347
+
348
+ it('enforces server lockedFilters regardless of viewer overrides and surfaces timeout/shard warnings', () => {
349
+ const spec = normalizeReportSpec({
350
+ visualization: 'table',
351
+ lockedFilters: [{ field: 'service', operator: 'eq', value: 'tenant-a' }],
352
+ filters: [{ field: 'status', operator: 'gte', value: 400 }],
353
+ timeRange: { preset: 'custom', from: '2026-11-29T00:00:00Z', to: '2026-11-30T00:00:00Z' },
354
+ });
355
+
356
+ const { body } = compileSearchRequest({
357
+ spec,
358
+ overrides: {
359
+ query: '',
360
+ filters: [],
361
+ timeRange: { preset: 'custom', from: '2026-11-29T00:00:00Z', to: '2026-11-30T00:00:00Z' },
362
+ },
363
+ timeField: '@timestamp',
364
+ fields: SAMPLE_FIELDS,
365
+ });
366
+
367
+ expect(body.query).toEqual({
368
+ bool: {
369
+ filter: [
370
+ { term: { 'service.keyword': 'tenant-a' } },
371
+ { range: { '@timestamp': { gte: '2026-11-29T00:00:00Z', lte: '2026-11-30T00:00:00Z' } } },
372
+ ],
373
+ },
374
+ });
375
+
376
+ const partial = parseSearchResponse(
377
+ {
378
+ took: 950,
379
+ timed_out: true,
380
+ _shards: { total: 5, successful: 4, skipped: 0, failed: 1 },
381
+ hits: { total: { value: 10000, relation: 'gte' }, hits: [] },
382
+ },
383
+ body,
384
+ spec,
385
+ '@timestamp',
386
+ );
387
+ expect(partial.timedOut).toBe(true);
388
+ expect(partial.shards).toEqual({ total: 5, successful: 4, skipped: 0, failed: 1 });
389
+ expect(partial.warnings).toHaveLength(2);
390
+ });
391
+
392
+ it('propagates IANA time_zone, _shard_doc PIT tie-breaker, p95 percentiles, and splitSeriesField breakdown', () => {
393
+ const pitTable = compileSearchRequest({
394
+ spec: normalizeReportSpec({
395
+ visualization: 'table',
396
+ timeRange: { preset: 'last_24h' },
397
+ }),
398
+ overrides: {
399
+ timeZone: 'Asia/Ho_Chi_Minh',
400
+ },
401
+ timeField: '@timestamp',
402
+ fields: SAMPLE_FIELDS,
403
+ usePit: true,
404
+ });
405
+
406
+ expect(pitTable.body.sort).toEqual([
407
+ { '@timestamp': { order: 'desc', unmapped_type: 'date' } },
408
+ { _shard_doc: { order: 'asc' } },
409
+ ]);
410
+ expect(pitTable.body.query).toEqual({
411
+ bool: {
412
+ filter: [{ range: { '@timestamp': { gte: 'now-24h', lte: 'now', time_zone: 'Asia/Ho_Chi_Minh' } } }],
413
+ },
414
+ });
415
+ expect(pitTable.body.aggs).toEqual({
416
+ es_time_histogram: {
417
+ auto_date_histogram: {
418
+ field: '@timestamp',
419
+ buckets: 24,
420
+ time_zone: 'Asia/Ho_Chi_Minh',
421
+ },
422
+ },
423
+ });
424
+
425
+ const splitChartSpec = normalizeReportSpec({
426
+ visualization: 'bar',
427
+ chart: {
428
+ bucketType: 'date_histogram',
429
+ calendarInterval: '1h',
430
+ metricType: 'p95',
431
+ metricField: 'latency_ms',
432
+ splitSeriesField: 'service',
433
+ splitSeriesTopN: 3,
434
+ stackMode: 'stacked',
435
+ },
436
+ });
437
+
438
+ const { body: splitBody, effectiveSpec } = compileSearchRequest({
439
+ spec: splitChartSpec,
440
+ overrides: { timeZone: 'Asia/Ho_Chi_Minh' },
441
+ timeField: '@timestamp',
442
+ fields: SAMPLE_FIELDS,
443
+ });
444
+
445
+ expect(splitBody.aggs).toEqual({
446
+ es_buckets: {
447
+ date_histogram: {
448
+ field: '@timestamp',
449
+ calendar_interval: '1h',
450
+ min_doc_count: 0,
451
+ time_zone: 'Asia/Ho_Chi_Minh',
452
+ },
453
+ aggs: {
454
+ es_metric: {
455
+ percentiles: { field: 'latency_ms', percents: [95] },
456
+ },
457
+ es_split: {
458
+ terms: { field: 'service.keyword', size: 3 },
459
+ aggs: {
460
+ es_metric: {
461
+ percentiles: { field: 'latency_ms', percents: [95] },
462
+ },
463
+ },
464
+ },
465
+ },
466
+ },
467
+ });
468
+
469
+ const parsedSplit = parseSearchResponse(
470
+ {
471
+ took: 6,
472
+ hits: { total: { value: 50, relation: 'eq' }, hits: [] },
473
+ aggregations: {
474
+ es_buckets: {
475
+ buckets: [
476
+ {
477
+ key_as_string: '2026-11-30T01:00:00+07:00',
478
+ key: 1732903200000,
479
+ doc_count: 50,
480
+ es_metric: { values: { '95.0': 412.5 } },
481
+ es_split: {
482
+ buckets: [
483
+ { key: 'checkout', doc_count: 30, es_metric: { values: { '95.0': 480.25 } } },
484
+ { key: 'catalog', doc_count: 20, es_metric: { values: { '95.0': 190.5 } } },
485
+ ],
486
+ },
487
+ },
488
+ ],
489
+ },
490
+ },
491
+ },
492
+ splitBody,
493
+ effectiveSpec,
494
+ '@timestamp',
495
+ );
496
+
497
+ expect(parsedSplit.seriesKeys).toEqual(['checkout', 'catalog']);
498
+ expect(parsedSplit.series).toEqual([
499
+ {
500
+ key: '1732903200000',
501
+ label: '2026-11-30T01:00:00+07:00',
502
+ value: 412.5,
503
+ count: 50,
504
+ breakdown: [
505
+ { seriesKey: 'checkout', value: 480.25, count: 30 },
506
+ { seriesKey: 'catalog', value: 190.5, count: 20 },
507
+ ],
508
+ },
509
+ ]);
510
+ });
511
+
512
+ it('compiles single-call KPI comparePreviousPeriod dual-window aggregations and computes deltaPercent', () => {
513
+ const kpiSpec = normalizeReportSpec({
514
+ visualization: 'metric',
515
+ timeRange: { preset: 'last_24h' },
516
+ chart: {
517
+ metricType: 'avg',
518
+ metricField: 'latency_ms',
519
+ comparePreviousPeriod: true,
520
+ },
521
+ });
522
+
523
+ const { body, effectiveSpec } = compileSearchRequest({
524
+ spec: kpiSpec,
525
+ timeField: '@timestamp',
526
+ fields: SAMPLE_FIELDS,
527
+ });
528
+
529
+ expect(body.aggs).toEqual({
530
+ es_current_window: {
531
+ filter: { range: { '@timestamp': { gte: 'now-24h', lte: 'now' } } },
532
+ aggs: { es_metric: { avg: { field: 'latency_ms' } } },
533
+ },
534
+ es_previous_window: {
535
+ filter: { range: { '@timestamp': { gte: 'now-48h', lt: 'now-24h' } } },
536
+ aggs: { es_metric: { avg: { field: 'latency_ms' } } },
537
+ },
538
+ });
539
+
540
+ const parsed = parseSearchResponse(
541
+ {
542
+ took: 4,
543
+ hits: { total: { value: 200, relation: 'eq' }, hits: [] },
544
+ aggregations: {
545
+ es_current_window: { doc_count: 120, es_metric: { value: 250 } },
546
+ es_previous_window: { doc_count: 80, es_metric: { value: 200 } },
547
+ },
548
+ },
549
+ body,
550
+ effectiveSpec,
551
+ '@timestamp',
552
+ );
553
+
554
+ expect(parsed.metricValue).toBe(250);
555
+ expect(parsed.previousMetricValue).toBe(200);
556
+ expect(parsed.deltaPercent).toBe(25);
557
+ });
558
+
559
+ it('resolves server lockedFilters user tokens, neutralizes CSV formula injection, and evaluates workflow thresholds', () => {
560
+ const resolved = resolveServerLockedFilters(
561
+ [
562
+ { field: 'tenant_user_id', operator: 'eq', value: '{{$user.id}}' },
563
+ { field: 'department', operator: 'eq', value: '{{ $role }}' },
564
+ ],
565
+ { userId: 7, username: 'alice', role: 'finance-viewer' },
566
+ );
567
+ expect(resolved).toEqual([
568
+ { field: 'tenant_user_id', operator: 'eq', value: 7, enabled: true },
569
+ { field: 'department', operator: 'eq', value: 'finance-viewer', enabled: true },
570
+ ]);
571
+
572
+ expect(() =>
573
+ resolveServerLockedFilters([{ field: 'owner_email', operator: 'eq', value: '{{$user.email}}' }], {
574
+ userId: 7,
575
+ }),
576
+ ).toThrow(/Permission denied/);
577
+
578
+ // CSV formula-injection neutralization preserves negative numbers and ECS @timestamp header while escaping =, +, -, @ formulas
579
+ expect(escapeCsvCell("=CMD|' /C calc'!A0")).toBe("'=CMD|' /C calc'!A0");
580
+ expect(escapeCsvCell('@SUM(A1:A5)')).toBe("'@SUM(A1:A5)");
581
+ expect(escapeCsvCell('@timestamp', { allowAtIdentifier: true })).toBe('@timestamp');
582
+ expect(escapeCsvCell('@SUM(A1:A5)', { allowAtIdentifier: true })).toBe("'@SUM(A1:A5)");
583
+ expect(escapeCsvCell('-42.5')).toBe('-42.5');
584
+ expect(escapeCsvCell(-42.5)).toBe('-42.5');
585
+ expect(escapeCsvCell('hello, "world"')).toBe('"hello, ""world"""');
586
+
587
+ // Workflow threshold evaluation
588
+ expect(evaluateThreshold(15, 'gte', 10)).toBe(true);
589
+ expect(evaluateThreshold(5, 'gte', 10)).toBe(false);
590
+ expect(evaluateThreshold(null, 'gt', 0)).toBe(false);
591
+ });
592
+
593
+ it('synchronizes ES 8.x connection options (CA fingerprint, PEM, Bearer token, Cloud ID) in ElasticsearchConnectionService', () => {
594
+ const fp = 'AA:BB:' + '11'.repeat(30);
595
+ const opts = buildEsClientOptions({
596
+ nodes: 'https://es8-node:9200',
597
+ authMode: 'bearer',
598
+ bearerToken: 'aae_token_xyz',
599
+ tlsMode: 'caFingerprint',
600
+ caFingerprint: fp,
601
+ requestTimeoutMs: 25000,
602
+ maxRetries: 4,
603
+ compression: true,
604
+ });
605
+ expect(opts).toMatchObject({
606
+ nodes: ['https://es8-node:9200'],
607
+ auth: { bearer: 'aae_token_xyz' },
608
+ caFingerprint: 'aabb' + '11'.repeat(30),
609
+ tls: { rejectUnauthorized: false },
610
+ requestTimeout: 25000,
611
+ maxRetries: 4,
612
+ compression: true,
613
+ });
614
+ expect(inferConnectionModes({ hasApiKey: true, hasCaCert: true })).toEqual({
615
+ endpointMode: 'nodes',
616
+ authMode: 'apiKey',
617
+ tlsMode: 'caCert',
618
+ });
619
+ });
620
+ });