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
@@ -9,39 +9,77 @@
9
9
 
10
10
  import { Client, type ClientOptions } from '@elastic/elasticsearch';
11
11
  import type { Application } from '@nocobase/server';
12
- import type { EsConnectionSummary, EsFieldCapability } from '../../shared/types';
12
+ import type { EsConnectionHealthResult, EsConnectionSummary, EsFieldCapability } from '../../shared/types';
13
+
14
+ export interface EsSearchCallOptions {
15
+ pitId?: string;
16
+ keepAlive?: string;
17
+ }
13
18
 
14
19
  export interface EsReadOnlyClient {
20
+ testConnection(indexPattern?: string): Promise<EsConnectionHealthResult>;
15
21
  readIndices(indexPattern?: string): Promise<string[]>;
16
22
  inspectFields(indexPattern: string): Promise<EsFieldCapability[]>;
17
- search(indexPattern: string, body: Record<string, unknown>): Promise<unknown>;
23
+ openPit(indexPattern: string, keepAlive?: string): Promise<string | null>;
24
+ closePit(pitId: string): Promise<void>;
25
+ search(indexPattern: string, body: Record<string, unknown>, options?: EsSearchCallOptions): Promise<unknown>;
18
26
  }
19
27
 
20
28
  interface RawEsClientLike {
29
+ info?: () => Promise<unknown>;
30
+ ping?: () => Promise<unknown>;
31
+ cluster?: {
32
+ health?: () => Promise<unknown>;
33
+ };
21
34
  cat?: {
22
35
  indices: (params: { index: string; format: 'json'; h: 'index' }) => Promise<unknown>;
23
36
  };
24
37
  fieldCaps?: (params: { index: string; fields: string }) => Promise<unknown>;
25
38
  indices?: {
26
39
  getMapping: (params: { index: string }) => Promise<unknown>;
40
+ resolveIndex?: (params: { name: string }) => Promise<unknown>;
27
41
  };
28
- search: (params: { index: string; body?: Record<string, unknown>; [key: string]: unknown }) => Promise<unknown>;
42
+ openPointInTime?: (params: { index: string; keep_alive: string }) => Promise<unknown>;
43
+ closePointInTime?: (params: { id: string }) => Promise<unknown>;
44
+ search: (params: { index?: string; body?: Record<string, unknown>; [key: string]: unknown }) => Promise<unknown>;
29
45
  close?: () => Promise<void>;
30
46
  }
31
47
 
32
- interface DataSourceConnectionOptions {
48
+ type EsEndpointMode = 'nodes' | 'cloud';
49
+ type EsAuthMode = 'none' | 'basic' | 'apiKey' | 'bearer';
50
+ type EsTlsMode = 'verify' | 'caFingerprint' | 'caCert' | 'skip';
51
+
52
+ export interface DataSourceConnectionOptions {
53
+ endpointMode?: EsEndpointMode;
33
54
  nodes?: string;
55
+ cloudId?: string;
56
+ authMode?: EsAuthMode;
34
57
  username?: string;
35
58
  password?: string;
36
59
  apiKey?: string;
37
- indexPattern?: string;
60
+ bearerToken?: string;
61
+ tlsMode?: EsTlsMode;
62
+ caFingerprint?: string;
63
+ caCert?: string;
64
+ tlsServerName?: string;
38
65
  rejectUnauthorized?: boolean;
66
+ requestTimeoutMs?: number;
67
+ maxRetries?: number;
68
+ compression?: boolean;
69
+ indexPattern?: string;
70
+ hasApiKey?: boolean;
71
+ hasBearerToken?: boolean;
72
+ hasCaCert?: boolean;
39
73
  }
40
74
 
41
75
  function isRecord(value: unknown): value is Record<string, unknown> {
42
76
  return typeof value === 'object' && value !== null && !Array.isArray(value);
43
77
  }
44
78
 
79
+ function toNonEmptyString(value: unknown): string | undefined {
80
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
81
+ }
82
+
45
83
  function isRawEsClientLike(value: unknown): value is RawEsClientLike {
46
84
  return isRecord(value) && typeof value.search === 'function';
47
85
  }
@@ -54,33 +92,154 @@ function normaliseApiKey(raw: string): string {
54
92
  return trimmed;
55
93
  }
56
94
 
95
+ function normalizeCaFingerprint(raw: string): string {
96
+ const cleaned = raw.replace(/[\s:]/g, '').toLowerCase();
97
+ if (!/^[0-9a-f]{64}$/.test(cleaned)) {
98
+ throw new Error('Invalid CA SHA-256 fingerprint: expected 64 hexadecimal characters');
99
+ }
100
+ return cleaned;
101
+ }
102
+
103
+ export function inferConnectionModes(opts: DataSourceConnectionOptions): {
104
+ endpointMode: EsEndpointMode;
105
+ authMode: EsAuthMode;
106
+ tlsMode: EsTlsMode;
107
+ } {
108
+ const endpointMode: EsEndpointMode =
109
+ opts.endpointMode === 'cloud' || opts.endpointMode === 'nodes'
110
+ ? opts.endpointMode
111
+ : toNonEmptyString(opts.cloudId)
112
+ ? 'cloud'
113
+ : 'nodes';
114
+
115
+ let authMode: EsAuthMode = 'none';
116
+ if (
117
+ opts.authMode === 'none' ||
118
+ opts.authMode === 'basic' ||
119
+ opts.authMode === 'apiKey' ||
120
+ opts.authMode === 'bearer'
121
+ ) {
122
+ authMode = opts.authMode;
123
+ } else if (opts.hasBearerToken === true || toNonEmptyString(opts.bearerToken)) {
124
+ authMode = 'bearer';
125
+ } else if (opts.hasApiKey === true || toNonEmptyString(opts.apiKey)) {
126
+ authMode = 'apiKey';
127
+ } else if (toNonEmptyString(opts.username)) {
128
+ authMode = 'basic';
129
+ }
130
+
131
+ let tlsMode: EsTlsMode = 'verify';
132
+ if (
133
+ opts.tlsMode === 'verify' ||
134
+ opts.tlsMode === 'caFingerprint' ||
135
+ opts.tlsMode === 'caCert' ||
136
+ opts.tlsMode === 'skip'
137
+ ) {
138
+ tlsMode = opts.tlsMode;
139
+ } else if (toNonEmptyString(opts.caFingerprint)) {
140
+ tlsMode = 'caFingerprint';
141
+ } else if (opts.hasCaCert === true || toNonEmptyString(opts.caCert)) {
142
+ tlsMode = 'caCert';
143
+ } else if (opts.rejectUnauthorized === false) {
144
+ tlsMode = 'skip';
145
+ }
146
+
147
+ return { endpointMode, authMode, tlsMode };
148
+ }
149
+
57
150
  function extractConnectionOptions(raw: unknown): DataSourceConnectionOptions {
58
151
  if (!isRecord(raw)) return {};
59
- if (typeof raw.nodes === 'string') return raw as DataSourceConnectionOptions;
152
+ if (typeof raw.nodes === 'string' || typeof raw.cloudId === 'string' || typeof raw.endpointMode === 'string') {
153
+ return raw as DataSourceConnectionOptions;
154
+ }
60
155
  if (isRecord(raw.options)) return raw.options as DataSourceConnectionOptions;
61
156
  return raw as DataSourceConnectionOptions;
62
157
  }
63
158
 
64
- function buildEsClientOptions(opts: DataSourceConnectionOptions): ClientOptions {
65
- const nodes = (opts.nodes || 'http://localhost:9200')
66
- .split(',')
67
- .map((item) => item.trim())
68
- .filter(Boolean);
159
+ export function buildEsClientOptions(opts: DataSourceConnectionOptions): ClientOptions {
160
+ const { endpointMode, authMode, tlsMode } = inferConnectionModes(opts);
161
+ const timeoutMs =
162
+ typeof opts.requestTimeoutMs === 'number' && Number.isFinite(opts.requestTimeoutMs) && opts.requestTimeoutMs >= 1000
163
+ ? Math.min(300000, Math.trunc(opts.requestTimeoutMs))
164
+ : 30000;
165
+
69
166
  const clientOpts: ClientOptions = {
70
- nodes,
71
- requestTimeout: 20000,
167
+ requestTimeout: timeoutMs,
72
168
  };
73
- if (opts.apiKey) {
74
- clientOpts.auth = { apiKey: normaliseApiKey(opts.apiKey) };
75
- } else if (opts.username) {
76
- clientOpts.auth = {
77
- username: opts.username,
78
- password: opts.password || '',
169
+
170
+ if (endpointMode === 'cloud') {
171
+ const cloudId = toNonEmptyString(opts.cloudId);
172
+ if (!cloudId) {
173
+ throw new Error('Elasticsearch data source has no configured Cloud ID');
174
+ }
175
+ clientOpts.cloud = { id: cloudId };
176
+ } else {
177
+ const nodes = (opts.nodes || 'http://localhost:9200')
178
+ .split(',')
179
+ .map((item) => item.trim())
180
+ .filter(Boolean);
181
+ clientOpts.nodes = nodes;
182
+ }
183
+
184
+ if (authMode === 'bearer') {
185
+ const bearer = toNonEmptyString(opts.bearerToken);
186
+ if (bearer) {
187
+ clientOpts.auth = { bearer };
188
+ }
189
+ } else if (authMode === 'apiKey') {
190
+ const apiKey = toNonEmptyString(opts.apiKey);
191
+ if (apiKey) {
192
+ clientOpts.auth = { apiKey: normaliseApiKey(apiKey) };
193
+ }
194
+ } else if (authMode === 'basic') {
195
+ const username = toNonEmptyString(opts.username);
196
+ if (username) {
197
+ clientOpts.auth = {
198
+ username,
199
+ password: opts.password || '',
200
+ };
201
+ }
202
+ }
203
+
204
+ const servername = toNonEmptyString(opts.tlsServerName);
205
+ if (tlsMode === 'caFingerprint') {
206
+ const fp = toNonEmptyString(opts.caFingerprint);
207
+ if (fp) {
208
+ clientOpts.caFingerprint = normalizeCaFingerprint(fp);
209
+ // Required by @elastic/elasticsearch UndiciConnection so self-signed ES 8.x CA chains reach isCaFingerprintMatch()
210
+ clientOpts.tls = {
211
+ rejectUnauthorized: false,
212
+ ...(servername ? { servername } : {}),
213
+ };
214
+ } else if (servername) {
215
+ clientOpts.tls = { servername };
216
+ }
217
+ } else if (tlsMode === 'caCert') {
218
+ const ca = toNonEmptyString(opts.caCert);
219
+ clientOpts.tls = {
220
+ ...(ca ? { ca } : {}),
221
+ rejectUnauthorized: true,
222
+ ...(servername ? { servername } : {}),
223
+ };
224
+ } else if (tlsMode === 'skip') {
225
+ clientOpts.tls = {
226
+ rejectUnauthorized: false,
227
+ ...(servername ? { servername } : {}),
228
+ };
229
+ } else if (servername) {
230
+ clientOpts.tls = {
231
+ rejectUnauthorized: true,
232
+ servername,
79
233
  };
80
234
  }
81
- if (opts.rejectUnauthorized === false) {
82
- clientOpts.tls = { rejectUnauthorized: false };
235
+
236
+ if (typeof opts.maxRetries === 'number' && Number.isFinite(opts.maxRetries) && opts.maxRetries >= 0) {
237
+ clientOpts.maxRetries = Math.min(10, Math.trunc(opts.maxRetries));
238
+ }
239
+ if (opts.compression === true) {
240
+ clientOpts.compression = true;
83
241
  }
242
+
84
243
  return clientOpts;
85
244
  }
86
245
 
@@ -211,24 +370,131 @@ function linkKeywordSubfields(map: Map<string, EsFieldCapability>): EsFieldCapab
211
370
  return Array.from(map.values()).sort((a, b) => a.name.localeCompare(b.name));
212
371
  }
213
372
 
373
+ function collectResolvedIndexNames(rawResolve: unknown, out: Set<string>): void {
374
+ const unwrapped = isRecord(rawResolve) && isRecord(rawResolve.body) ? rawResolve.body : rawResolve;
375
+ if (!isRecord(unwrapped)) return;
376
+
377
+ for (const bucketKey of ['indices', 'data_streams', 'aliases'] as const) {
378
+ const arr = unwrapped[bucketKey];
379
+ if (!Array.isArray(arr)) continue;
380
+ for (const entry of arr) {
381
+ if (!isRecord(entry) || entry.open === false) continue;
382
+ const name = toNonEmptyString(entry.name);
383
+ if (name && !name.startsWith('.')) {
384
+ out.add(name);
385
+ }
386
+ }
387
+ }
388
+ }
389
+
214
390
  function wrapEsClient(rawClient: RawEsClientLike): EsReadOnlyClient {
215
391
  return {
392
+ async testConnection(indexPattern = '*'): Promise<EsConnectionHealthResult> {
393
+ const safePattern = assertSafeIndexPattern(indexPattern || '*');
394
+
395
+ if (typeof rawClient.info === 'function') {
396
+ try {
397
+ const rawInfo = await rawClient.info();
398
+ const info = isRecord(rawInfo) && isRecord(rawInfo.body) ? rawInfo.body : rawInfo;
399
+ const clusterName = isRecord(info) ? toNonEmptyString(info.cluster_name) : undefined;
400
+ const versionObj = isRecord(info) && isRecord(info.version) ? info.version : undefined;
401
+ const version = versionObj ? toNonEmptyString(versionObj.number) : undefined;
402
+ if (clusterName || version) {
403
+ return {
404
+ ok: true,
405
+ ...(clusterName ? { clusterName } : {}),
406
+ ...(version ? { version } : {}),
407
+ };
408
+ }
409
+ } catch (err) {
410
+ const statusCode = isRecord(err) && typeof err.statusCode === 'number' ? err.statusCode : undefined;
411
+ if (statusCode === 403 && rawClient.fieldCaps) {
412
+ await rawClient.fieldCaps({ index: safePattern, fields: '@timestamp' });
413
+ return { ok: true, limitedPrivileges: true };
414
+ }
415
+ throw err;
416
+ }
417
+ }
418
+
419
+ if (typeof rawClient.cluster?.health === 'function') {
420
+ try {
421
+ const rawHealth = await rawClient.cluster.health();
422
+ const health = isRecord(rawHealth) && isRecord(rawHealth.body) ? rawHealth.body : rawHealth;
423
+ const clusterName = isRecord(health) ? toNonEmptyString(health.cluster_name) : undefined;
424
+ if (clusterName) {
425
+ return { ok: true, clusterName };
426
+ }
427
+ } catch (err) {
428
+ const statusCode = isRecord(err) && typeof err.statusCode === 'number' ? err.statusCode : undefined;
429
+ if (statusCode === 403 && rawClient.fieldCaps) {
430
+ await rawClient.fieldCaps({ index: safePattern, fields: '@timestamp' });
431
+ return { ok: true, limitedPrivileges: true };
432
+ }
433
+ throw err;
434
+ }
435
+ }
436
+
437
+ if (typeof rawClient.ping === 'function') {
438
+ const pong = await rawClient.ping();
439
+ if (pong) {
440
+ return { ok: true };
441
+ }
442
+ }
443
+
444
+ if (rawClient.fieldCaps) {
445
+ await rawClient.fieldCaps({ index: safePattern, fields: '@timestamp' });
446
+ return { ok: true };
447
+ }
448
+
449
+ return { ok: true };
450
+ },
451
+
216
452
  async readIndices(indexPattern = '*'): Promise<string[]> {
217
- const safePattern = indexPattern.trim() || '*';
218
- if (!rawClient.cat?.indices) {
219
- return [];
453
+ const safePattern = assertSafeIndexPattern(indexPattern || '*');
454
+ const names = new Set<string>();
455
+
456
+ const resolvePromise =
457
+ typeof rawClient.indices?.resolveIndex === 'function'
458
+ ? rawClient.indices.resolveIndex({ name: safePattern })
459
+ : Promise.resolve(null);
460
+ const catPromise =
461
+ typeof rawClient.cat?.indices === 'function'
462
+ ? rawClient.cat.indices({ index: safePattern, format: 'json', h: 'index' })
463
+ : Promise.resolve(null);
464
+
465
+ const [resolveOutcome, catOutcome] = await Promise.allSettled([resolvePromise, catPromise]);
466
+
467
+ if (resolveOutcome.status === 'fulfilled' && resolveOutcome.value) {
468
+ collectResolvedIndexNames(resolveOutcome.value, names);
220
469
  }
221
- const response = await rawClient.cat.indices({
222
- index: safePattern,
223
- format: 'json',
224
- h: 'index',
225
- });
226
- const unwrapped = isRecord(response) && Array.isArray(response.body) ? response.body : response;
227
- if (!Array.isArray(unwrapped)) return [];
228
- return unwrapped
229
- .map((row) => (isRecord(row) && typeof row.index === 'string' ? row.index.trim() : ''))
230
- .filter((idx) => Boolean(idx) && !idx.startsWith('.'))
231
- .sort((a, b) => a.localeCompare(b));
470
+
471
+ if (catOutcome.status === 'fulfilled' && catOutcome.value) {
472
+ const unwrapped =
473
+ isRecord(catOutcome.value) && Array.isArray(catOutcome.value.body) ? catOutcome.value.body : catOutcome.value;
474
+ if (Array.isArray(unwrapped)) {
475
+ for (const row of unwrapped) {
476
+ const idx = isRecord(row) ? toNonEmptyString(row.index) : undefined;
477
+ if (idx && !idx.startsWith('.')) {
478
+ names.add(idx);
479
+ }
480
+ }
481
+ }
482
+ }
483
+
484
+ if (
485
+ resolveOutcome.status === 'rejected' &&
486
+ (catOutcome.status === 'rejected' || typeof rawClient.cat?.indices !== 'function')
487
+ ) {
488
+ throw resolveOutcome.reason;
489
+ }
490
+ if (catOutcome.status === 'rejected' && typeof rawClient.indices?.resolveIndex !== 'function') {
491
+ throw catOutcome.reason;
492
+ }
493
+ if (resolveOutcome.status === 'rejected' && catOutcome.status === 'rejected') {
494
+ throw catOutcome.reason || resolveOutcome.reason;
495
+ }
496
+
497
+ return Array.from(names).sort((a, b) => a.localeCompare(b));
232
498
  },
233
499
 
234
500
  async inspectFields(indexPattern: string): Promise<EsFieldCapability[]> {
@@ -265,9 +531,46 @@ function wrapEsClient(rawClient: RawEsClientLike): EsReadOnlyClient {
265
531
  return [];
266
532
  },
267
533
 
268
- async search(indexPattern: string, body: Record<string, unknown>): Promise<unknown> {
534
+ async openPit(indexPattern: string, keepAlive = '1m'): Promise<string | null> {
535
+ const safePattern = assertSafeIndexPattern(indexPattern);
536
+ if (typeof rawClient.openPointInTime !== 'function') {
537
+ return null;
538
+ }
539
+ try {
540
+ const raw = await rawClient.openPointInTime({
541
+ index: safePattern,
542
+ keep_alive: keepAlive,
543
+ });
544
+ const unwrapped = isRecord(raw) && isRecord(raw.body) ? raw.body : raw;
545
+ return isRecord(unwrapped) && typeof unwrapped.id === 'string' && unwrapped.id ? unwrapped.id : null;
546
+ } catch {
547
+ return null;
548
+ }
549
+ },
550
+
551
+ async closePit(pitId: string): Promise<void> {
552
+ if (!pitId || typeof rawClient.closePointInTime !== 'function') {
553
+ return;
554
+ }
555
+ try {
556
+ await rawClient.closePointInTime({ id: pitId });
557
+ } catch {
558
+ // Ignore already-expired PIT cleanup errors.
559
+ }
560
+ },
561
+
562
+ async search(indexPattern: string, body: Record<string, unknown>, options?: EsSearchCallOptions): Promise<unknown> {
563
+ if (options?.pitId) {
564
+ const response = await rawClient.search({
565
+ ...body,
566
+ pit: {
567
+ id: options.pitId,
568
+ keep_alive: options.keepAlive ?? '1m',
569
+ },
570
+ });
571
+ return isRecord(response) && isRecord(response.body) ? response.body : response;
572
+ }
269
573
  const safePattern = assertSafeIndexPattern(indexPattern);
270
- // Elasticsearch v8 client accepts top-level search params (`{ index, ...body }`).
271
574
  const response = await rawClient.search({
272
575
  index: safePattern,
273
576
  ...body,
@@ -278,19 +581,19 @@ function wrapEsClient(rawClient: RawEsClientLike): EsReadOnlyClient {
278
581
  }
279
582
 
280
583
  export class ElasticsearchConnectionService {
281
- private readonly fallbackClients = new Map<string, Client>();
584
+ private readonly fallbackClients = new Map<string, { signature: string; client: Client }>();
282
585
 
283
586
  constructor(private readonly app: Application) {}
284
587
 
285
588
  async close(): Promise<void> {
286
- const clients = Array.from(this.fallbackClients.values());
589
+ const entries = Array.from(this.fallbackClients.values());
287
590
  this.fallbackClients.clear();
288
- await Promise.allSettled(clients.map((client) => client.close()));
591
+ await Promise.allSettled(entries.map((entry) => entry.client.close()));
289
592
  }
290
593
 
291
594
  /**
292
595
  * Discover all Elasticsearch data sources configured via `plugin-data-source-elasticsearch`
293
- * without leaking sensitive credentials (`password`, `apiKey`).
596
+ * without leaking sensitive credentials (`password`, `apiKey`, `bearerToken`, `caCert`).
294
597
  */
295
598
  async listConnections(): Promise<EsConnectionSummary[]> {
296
599
  const byKey = new Map<string, EsConnectionSummary>();
@@ -308,10 +611,15 @@ export class ElasticsearchConnectionService {
308
611
  const isEs = isRawEsClientLike(cm?.esClient) || ds.constructor?.name === 'ElasticsearchDataSource';
309
612
  if (!isEs) continue;
310
613
 
614
+ const modes = inferConnectionModes(opts);
311
615
  byKey.set(key, {
312
616
  key,
313
617
  displayName: typeof ds.displayName === 'string' && ds.displayName ? ds.displayName : key,
314
618
  status: 'loaded',
619
+ endpointMode: modes.endpointMode,
620
+ authMode: modes.authMode,
621
+ tlsMode: modes.tlsMode,
622
+ cloudConfigured: modes.endpointMode === 'cloud',
315
623
  ...(typeof opts.indexPattern === 'string' ? { indexPattern: opts.indexPattern } : {}),
316
624
  ...(typeof opts.nodes === 'string' ? { nodes: opts.nodes } : {}),
317
625
  });
@@ -329,6 +637,7 @@ export class ElasticsearchConnectionService {
329
637
  if (!isRecord(plain) || typeof plain.key !== 'string' || !plain.key.trim()) continue;
330
638
  const key = plain.key.trim();
331
639
  const opts = extractConnectionOptions(plain.options);
640
+ const modes = inferConnectionModes(opts);
332
641
  const existing = byKey.get(key);
333
642
  byKey.set(key, {
334
643
  key,
@@ -337,6 +646,10 @@ export class ElasticsearchConnectionService {
337
646
  ? plain.displayName.trim()
338
647
  : existing?.displayName ?? key,
339
648
  status: typeof plain.status === 'string' ? plain.status : existing?.status ?? 'configured',
649
+ endpointMode: modes.endpointMode,
650
+ authMode: modes.authMode,
651
+ tlsMode: modes.tlsMode,
652
+ cloudConfigured: modes.endpointMode === 'cloud',
340
653
  ...(typeof opts.indexPattern === 'string'
341
654
  ? { indexPattern: opts.indexPattern }
342
655
  : existing?.indexPattern
@@ -372,11 +685,6 @@ export class ElasticsearchConnectionService {
372
685
  return wrapEsClient(liveDs.collectionManager.esClient);
373
686
  }
374
687
 
375
- const cached = this.fallbackClients.get(cleanKey);
376
- if (cached) {
377
- return wrapEsClient(cached as unknown as RawEsClientLike);
378
- }
379
-
380
688
  const repo = this.app.db.getRepository('dataSources');
381
689
  const record = repo
382
690
  ? await repo.findOne({
@@ -385,17 +693,36 @@ export class ElasticsearchConnectionService {
385
693
  : null;
386
694
 
387
695
  if (!record) {
696
+ const existingCached = this.fallbackClients.get(cleanKey);
697
+ if (existingCached) {
698
+ return wrapEsClient(existingCached.client as unknown as RawEsClientLike);
699
+ }
388
700
  throw new Error(`Elasticsearch data source "${cleanKey}" was not found or is not loaded`);
389
701
  }
390
702
 
391
703
  const plain = typeof record.toJSON === 'function' ? record.toJSON() : record;
392
704
  const opts = extractConnectionOptions(isRecord(plain) ? plain.options : undefined);
393
- if (!opts.nodes) {
705
+ const { endpointMode } = inferConnectionModes(opts);
706
+ if (endpointMode === 'cloud') {
707
+ if (!toNonEmptyString(opts.cloudId)) {
708
+ throw new Error(`Elasticsearch data source "${cleanKey}" has no configured Cloud ID`);
709
+ }
710
+ } else if (!toNonEmptyString(opts.nodes)) {
394
711
  throw new Error(`Elasticsearch data source "${cleanKey}" has no configured nodes`);
395
712
  }
396
713
 
714
+ const signature = JSON.stringify(opts);
715
+ const cached = this.fallbackClients.get(cleanKey);
716
+ if (cached && cached.signature === signature) {
717
+ return wrapEsClient(cached.client as unknown as RawEsClientLike);
718
+ }
719
+ if (cached) {
720
+ await cached.client.close().catch(() => undefined);
721
+ this.fallbackClients.delete(cleanKey);
722
+ }
723
+
397
724
  const client = new Client(buildEsClientOptions(opts));
398
- this.fallbackClients.set(cleanKey, client);
725
+ this.fallbackClients.set(cleanKey, { signature, client });
399
726
  return wrapEsClient(client as unknown as RawEsClientLike);
400
727
  }
401
728
  }