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.
Files changed (60) hide show
  1. package/ai/skills/elastic-report/SKILLS.md +5 -3
  2. package/dist/client/357.0dd385384cab5dbf.js +10 -0
  3. package/dist/client/index.js +1 -1
  4. package/dist/client-v2/851.142c93fc6d666b28.js +10 -0
  5. package/dist/client-v2/857.a5bf9637d5fd4ef5.js +10 -0
  6. package/dist/client-v2/877.f4095a3dbcadf98f.js +10 -0
  7. package/dist/client-v2/index.js +1 -1
  8. package/dist/externalVersion.js +3 -2
  9. package/dist/locale/en-US.json +100 -1
  10. package/dist/locale/vi-VN.json +100 -1
  11. package/dist/locale/zh-CN.json +100 -1
  12. package/dist/node_modules/@elastic/elasticsearch/package.json +1 -1
  13. package/dist/server/acl-guard.js +97 -25
  14. package/dist/server/collections/es-report-data-views.js +6 -0
  15. package/dist/server/collections/es-reports.js +6 -0
  16. package/dist/server/mcp/ElasticReportToolCatalog.js +232 -10
  17. package/dist/server/plugin.js +153 -19
  18. package/dist/server/services/ElasticReportService.js +125 -11
  19. package/dist/server/services/ElasticsearchConnectionService.js +274 -34
  20. package/dist/server/services/ReportExportService.js +243 -0
  21. package/dist/server/services/ReportQueryCompiler.js +532 -91
  22. package/dist/server/workflow/ElasticReportQueryInstruction.js +123 -0
  23. package/dist/shared/constants.js +17 -2
  24. package/package.json +3 -2
  25. package/src/client/index.tsx +16 -1
  26. package/src/client/workflow-instructions.tsx +44 -0
  27. package/src/client-v2/__tests__/elastic-report.test.tsx +519 -39
  28. package/src/client-v2/__tests__/kql-autocomplete.test.ts +178 -0
  29. package/src/client-v2/api.ts +96 -0
  30. package/src/client-v2/bus/DashboardFilterBus.ts +212 -0
  31. package/src/client-v2/components/ElasticBasicCharts.tsx +345 -92
  32. package/src/client-v2/components/ElasticFilterBar.tsx +372 -0
  33. package/src/client-v2/components/ElasticKqlInput.tsx +421 -0
  34. package/src/client-v2/components/ElasticReportBlock.tsx +157 -11
  35. package/src/client-v2/components/ElasticReportRenderer.tsx +621 -71
  36. package/src/client-v2/components/ReportSelect.tsx +39 -26
  37. package/src/client-v2/models/ElasticFilterBarBlockModel.tsx +115 -0
  38. package/src/client-v2/models/ElasticReportBlockModel.tsx +36 -3
  39. package/src/client-v2/pages/ElasticReportManager.tsx +432 -26
  40. package/src/client-v2/plugin.tsx +20 -0
  41. package/src/client-v2/utils/kqlAutocomplete.ts +861 -0
  42. package/src/client-v2/workflow/instructions.tsx +149 -0
  43. package/src/locale/en-US.json +100 -1
  44. package/src/locale/vi-VN.json +100 -1
  45. package/src/locale/zh-CN.json +100 -1
  46. package/src/server/__tests__/query-compiler.test.ts +390 -1
  47. package/src/server/__tests__/report-mcp-acl.integration.test.ts +271 -3
  48. package/src/server/acl-guard.ts +119 -28
  49. package/src/server/collections/es-report-data-views.ts +6 -0
  50. package/src/server/collections/es-reports.ts +6 -0
  51. package/src/server/mcp/ElasticReportToolCatalog.ts +255 -9
  52. package/src/server/plugin.ts +189 -21
  53. package/src/server/services/ElasticReportService.ts +165 -5
  54. package/src/server/services/ElasticsearchConnectionService.ts +375 -48
  55. package/src/server/services/ReportExportService.ts +282 -0
  56. package/src/server/services/ReportQueryCompiler.ts +629 -94
  57. package/src/server/workflow/ElasticReportQueryInstruction.ts +124 -0
  58. package/src/shared/constants.ts +7 -0
  59. package/src/shared/types.ts +98 -1
  60. package/dist/client-v2/851.488fdbf5bc5b6a36.js +0 -10
@@ -10,13 +10,18 @@
10
10
  import { describe, expect, it } from 'vitest';
11
11
  import { HIGHLIGHT_POST_TAG, HIGHLIGHT_PRE_TAG } from '../../shared/constants';
12
12
  import type { EsFieldCapability } from '../../shared/types';
13
+ import { buildEsClientOptions, inferConnectionModes } from '../services/ElasticsearchConnectionService';
14
+ import { escapeCsvCell } from '../services/ReportExportService';
13
15
  import {
16
+ KqlSyntaxError,
14
17
  buildFieldCapabilityMap,
15
18
  compileKqlToQueryDsl,
16
19
  compileSearchRequest,
17
20
  normalizeReportSpec,
18
21
  parseSearchResponse,
22
+ resolveServerLockedFilters,
19
23
  } from '../services/ReportQueryCompiler';
24
+ import { evaluateThreshold } from '../workflow/ElasticReportQueryInstruction';
20
25
 
21
26
  const SAMPLE_FIELDS: EsFieldCapability[] = [
22
27
  { name: '@timestamp', type: 'date', searchable: true, aggregatable: true },
@@ -91,7 +96,10 @@ describe('ReportQueryCompiler', () => {
91
96
  });
92
97
 
93
98
  expect(body.size).toBe(25);
94
- expect(body.sort).toEqual([{ 'service.keyword': { order: 'asc', unmapped_type: 'keyword' } }]);
99
+ expect(body.sort).toEqual([
100
+ { 'service.keyword': { order: 'asc', unmapped_type: 'keyword' } },
101
+ { _doc: { order: 'asc' } },
102
+ ]);
95
103
  expect(body.query).toEqual({
96
104
  bool: {
97
105
  must: [
@@ -228,4 +236,385 @@ describe('ReportQueryCompiler', () => {
228
236
  expect(parsed.columns).toEqual(['@timestamp', 'message']);
229
237
  expect(parsed.rows[0].highlights?.message?.[0]).toContain(HIGHLIGHT_PRE_TAG);
230
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
+ });
231
620
  });