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.
- package/client-v2.d.ts +2 -2
- package/client-v2.js +1 -1
- package/client.d.ts +2 -2
- package/client.js +1 -1
- package/dist/ai/skills/elastic-report/SKILLS.md +52 -0
- package/dist/client/357.0dd385384cab5dbf.js +10 -0
- package/dist/client/index.js +1 -1
- package/dist/client-v2/851.35e416bfb3fb565f.js +10 -0
- package/dist/client-v2/857.a5bf9637d5fd4ef5.js +10 -0
- package/dist/client-v2/877.81b10beb7b7f4bd7.js +10 -0
- package/dist/client-v2/index.js +1 -1
- package/dist/externalVersion.js +5 -3
- package/dist/locale/en-US.json +213 -99
- package/dist/locale/vi-VN.json +213 -99
- package/dist/locale/zh-CN.json +213 -99
- 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 +238 -14
- package/dist/server/plugin.js +156 -22
- package/dist/server/report-block-tools.js +340 -0
- package/dist/server/services/ElasticReportService.js +137 -17
- 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 +26 -2
- package/package.json +3 -3
- package/server.d.ts +2 -2
- package/server.js +1 -1
- package/src/ai/skills/elastic-report/SKILLS.md +52 -0
- package/src/client/index.tsx +34 -19
- package/src/client/workflow-instructions.tsx +44 -0
- package/src/client-v2/__tests__/elastic-report.test.tsx +879 -311
- package/src/client-v2/__tests__/kql-autocomplete.test.ts +178 -0
- package/src/client-v2/api.ts +320 -224
- package/src/client-v2/bus/DashboardFilterBus.ts +212 -0
- package/src/client-v2/components/ElasticBasicCharts.tsx +652 -399
- 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 +306 -160
- package/src/client-v2/components/ElasticReportRenderer.tsx +1257 -707
- package/src/client-v2/components/HighlightText.tsx +50 -50
- package/src/client-v2/components/ReportSelect.tsx +85 -72
- package/src/client-v2/index.tsx +14 -14
- package/src/client-v2/locale.ts +23 -23
- package/src/client-v2/models/ElasticFilterBarBlockModel.tsx +115 -0
- package/src/client-v2/models/ElasticReportBlockModel.tsx +118 -85
- package/src/client-v2/pages/ElasticReportManager.tsx +1453 -1047
- package/src/client-v2/plugin.tsx +107 -52
- package/src/client-v2/report-destination.tsx +126 -0
- package/src/client-v2/utils/kqlAutocomplete.ts +861 -0
- package/src/client-v2/workflow/instructions.tsx +149 -0
- package/src/index.ts +11 -11
- package/src/locale/en-US.json +213 -99
- package/src/locale/vi-VN.json +213 -99
- package/src/locale/zh-CN.json +213 -99
- package/src/server/__tests__/ai-blocks.integration.test.ts +292 -0
- package/src/server/__tests__/query-compiler.test.ts +620 -231
- package/src/server/__tests__/report-mcp-acl.integration.test.ts +645 -377
- package/src/server/acl-guard.ts +194 -103
- package/src/server/collections/es-report-data-views.ts +64 -58
- package/src/server/collections/es-reports.ts +80 -74
- package/src/server/index.ts +15 -15
- package/src/server/mcp/ElasticReportMcpServer.ts +391 -391
- package/src/server/mcp/ElasticReportToolCatalog.ts +667 -417
- package/src/server/plugin.ts +599 -431
- package/src/server/report-block-tools.ts +400 -0
- package/src/server/services/ElasticReportService.ts +494 -326
- package/src/server/services/ElasticsearchConnectionService.ts +728 -401
- package/src/server/services/ReportExportService.ts +282 -0
- package/src/server/services/ReportQueryCompiler.ts +1552 -1017
- package/src/server/workflow/ElasticReportQueryInstruction.ts +124 -0
- package/src/shared/constants.ts +39 -29
- package/src/shared/types.ts +272 -175
- package/ai/skills/elastic-report/SKILLS.md +0 -32
- package/dist/client-v2/851.488fdbf5bc5b6a36.js +0 -10
- package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv +0 -15
- package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv.cmd +0 -7
|
@@ -27,6 +27,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
27
27
|
var ElasticsearchConnectionService_exports = {};
|
|
28
28
|
__export(ElasticsearchConnectionService_exports, {
|
|
29
29
|
ElasticsearchConnectionService: () => ElasticsearchConnectionService,
|
|
30
|
+
buildEsClientOptions: () => buildEsClientOptions,
|
|
31
|
+
inferConnectionModes: () => inferConnectionModes,
|
|
30
32
|
normalizeFieldCapabilitiesResponse: () => normalizeFieldCapabilitiesResponse
|
|
31
33
|
});
|
|
32
34
|
module.exports = __toCommonJS(ElasticsearchConnectionService_exports);
|
|
@@ -34,6 +36,9 @@ var import_elasticsearch = require("@elastic/elasticsearch");
|
|
|
34
36
|
function isRecord(value) {
|
|
35
37
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
36
38
|
}
|
|
39
|
+
function toNonEmptyString(value) {
|
|
40
|
+
return typeof value === "string" && value.trim() ? value.trim() : void 0;
|
|
41
|
+
}
|
|
37
42
|
function isRawEsClientLike(value) {
|
|
38
43
|
return isRecord(value) && typeof value.search === "function";
|
|
39
44
|
}
|
|
@@ -44,28 +49,115 @@ function normaliseApiKey(raw) {
|
|
|
44
49
|
}
|
|
45
50
|
return trimmed;
|
|
46
51
|
}
|
|
52
|
+
function normalizeCaFingerprint(raw) {
|
|
53
|
+
const cleaned = raw.replace(/[\s:]/g, "").toLowerCase();
|
|
54
|
+
if (!/^[0-9a-f]{64}$/.test(cleaned)) {
|
|
55
|
+
throw new Error("Invalid CA SHA-256 fingerprint: expected 64 hexadecimal characters");
|
|
56
|
+
}
|
|
57
|
+
return cleaned;
|
|
58
|
+
}
|
|
59
|
+
function inferConnectionModes(opts) {
|
|
60
|
+
const endpointMode = opts.endpointMode === "cloud" || opts.endpointMode === "nodes" ? opts.endpointMode : toNonEmptyString(opts.cloudId) ? "cloud" : "nodes";
|
|
61
|
+
let authMode = "none";
|
|
62
|
+
if (opts.authMode === "none" || opts.authMode === "basic" || opts.authMode === "apiKey" || opts.authMode === "bearer") {
|
|
63
|
+
authMode = opts.authMode;
|
|
64
|
+
} else if (opts.hasBearerToken === true || toNonEmptyString(opts.bearerToken)) {
|
|
65
|
+
authMode = "bearer";
|
|
66
|
+
} else if (opts.hasApiKey === true || toNonEmptyString(opts.apiKey)) {
|
|
67
|
+
authMode = "apiKey";
|
|
68
|
+
} else if (toNonEmptyString(opts.username)) {
|
|
69
|
+
authMode = "basic";
|
|
70
|
+
}
|
|
71
|
+
let tlsMode = "verify";
|
|
72
|
+
if (opts.tlsMode === "verify" || opts.tlsMode === "caFingerprint" || opts.tlsMode === "caCert" || opts.tlsMode === "skip") {
|
|
73
|
+
tlsMode = opts.tlsMode;
|
|
74
|
+
} else if (toNonEmptyString(opts.caFingerprint)) {
|
|
75
|
+
tlsMode = "caFingerprint";
|
|
76
|
+
} else if (opts.hasCaCert === true || toNonEmptyString(opts.caCert)) {
|
|
77
|
+
tlsMode = "caCert";
|
|
78
|
+
} else if (opts.rejectUnauthorized === false) {
|
|
79
|
+
tlsMode = "skip";
|
|
80
|
+
}
|
|
81
|
+
return { endpointMode, authMode, tlsMode };
|
|
82
|
+
}
|
|
47
83
|
function extractConnectionOptions(raw) {
|
|
48
84
|
if (!isRecord(raw)) return {};
|
|
49
|
-
if (typeof raw.nodes === "string"
|
|
85
|
+
if (typeof raw.nodes === "string" || typeof raw.cloudId === "string" || typeof raw.endpointMode === "string") {
|
|
86
|
+
return raw;
|
|
87
|
+
}
|
|
50
88
|
if (isRecord(raw.options)) return raw.options;
|
|
51
89
|
return raw;
|
|
52
90
|
}
|
|
53
91
|
function buildEsClientOptions(opts) {
|
|
54
|
-
const
|
|
92
|
+
const { endpointMode, authMode, tlsMode } = inferConnectionModes(opts);
|
|
93
|
+
const timeoutMs = typeof opts.requestTimeoutMs === "number" && Number.isFinite(opts.requestTimeoutMs) && opts.requestTimeoutMs >= 1e3 ? Math.min(3e5, Math.trunc(opts.requestTimeoutMs)) : 3e4;
|
|
55
94
|
const clientOpts = {
|
|
56
|
-
|
|
57
|
-
requestTimeout: 2e4
|
|
95
|
+
requestTimeout: timeoutMs
|
|
58
96
|
};
|
|
59
|
-
if (
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
97
|
+
if (endpointMode === "cloud") {
|
|
98
|
+
const cloudId = toNonEmptyString(opts.cloudId);
|
|
99
|
+
if (!cloudId) {
|
|
100
|
+
throw new Error("Elasticsearch data source has no configured Cloud ID");
|
|
101
|
+
}
|
|
102
|
+
clientOpts.cloud = { id: cloudId };
|
|
103
|
+
} else {
|
|
104
|
+
const nodes = (opts.nodes || "http://localhost:9200").split(",").map((item) => item.trim()).filter(Boolean);
|
|
105
|
+
clientOpts.nodes = nodes;
|
|
106
|
+
}
|
|
107
|
+
if (authMode === "bearer") {
|
|
108
|
+
const bearer = toNonEmptyString(opts.bearerToken);
|
|
109
|
+
if (bearer) {
|
|
110
|
+
clientOpts.auth = { bearer };
|
|
111
|
+
}
|
|
112
|
+
} else if (authMode === "apiKey") {
|
|
113
|
+
const apiKey = toNonEmptyString(opts.apiKey);
|
|
114
|
+
if (apiKey) {
|
|
115
|
+
clientOpts.auth = { apiKey: normaliseApiKey(apiKey) };
|
|
116
|
+
}
|
|
117
|
+
} else if (authMode === "basic") {
|
|
118
|
+
const username = toNonEmptyString(opts.username);
|
|
119
|
+
if (username) {
|
|
120
|
+
clientOpts.auth = {
|
|
121
|
+
username,
|
|
122
|
+
password: opts.password || ""
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
const servername = toNonEmptyString(opts.tlsServerName);
|
|
127
|
+
if (tlsMode === "caFingerprint") {
|
|
128
|
+
const fp = toNonEmptyString(opts.caFingerprint);
|
|
129
|
+
if (fp) {
|
|
130
|
+
clientOpts.caFingerprint = normalizeCaFingerprint(fp);
|
|
131
|
+
clientOpts.tls = {
|
|
132
|
+
rejectUnauthorized: false,
|
|
133
|
+
...servername ? { servername } : {}
|
|
134
|
+
};
|
|
135
|
+
} else if (servername) {
|
|
136
|
+
clientOpts.tls = { servername };
|
|
137
|
+
}
|
|
138
|
+
} else if (tlsMode === "caCert") {
|
|
139
|
+
const ca = toNonEmptyString(opts.caCert);
|
|
140
|
+
clientOpts.tls = {
|
|
141
|
+
...ca ? { ca } : {},
|
|
142
|
+
rejectUnauthorized: true,
|
|
143
|
+
...servername ? { servername } : {}
|
|
144
|
+
};
|
|
145
|
+
} else if (tlsMode === "skip") {
|
|
146
|
+
clientOpts.tls = {
|
|
147
|
+
rejectUnauthorized: false,
|
|
148
|
+
...servername ? { servername } : {}
|
|
65
149
|
};
|
|
150
|
+
} else if (servername) {
|
|
151
|
+
clientOpts.tls = {
|
|
152
|
+
rejectUnauthorized: true,
|
|
153
|
+
servername
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
if (typeof opts.maxRetries === "number" && Number.isFinite(opts.maxRetries) && opts.maxRetries >= 0) {
|
|
157
|
+
clientOpts.maxRetries = Math.min(10, Math.trunc(opts.maxRetries));
|
|
66
158
|
}
|
|
67
|
-
if (opts.
|
|
68
|
-
clientOpts.
|
|
159
|
+
if (opts.compression === true) {
|
|
160
|
+
clientOpts.compression = true;
|
|
69
161
|
}
|
|
70
162
|
return clientOpts;
|
|
71
163
|
}
|
|
@@ -175,22 +267,109 @@ function linkKeywordSubfields(map) {
|
|
|
175
267
|
}
|
|
176
268
|
return Array.from(map.values()).sort((a, b) => a.name.localeCompare(b.name));
|
|
177
269
|
}
|
|
270
|
+
function collectResolvedIndexNames(rawResolve, out) {
|
|
271
|
+
const unwrapped = isRecord(rawResolve) && isRecord(rawResolve.body) ? rawResolve.body : rawResolve;
|
|
272
|
+
if (!isRecord(unwrapped)) return;
|
|
273
|
+
for (const bucketKey of ["indices", "data_streams", "aliases"]) {
|
|
274
|
+
const arr = unwrapped[bucketKey];
|
|
275
|
+
if (!Array.isArray(arr)) continue;
|
|
276
|
+
for (const entry of arr) {
|
|
277
|
+
if (!isRecord(entry) || entry.open === false) continue;
|
|
278
|
+
const name = toNonEmptyString(entry.name);
|
|
279
|
+
if (name && !name.startsWith(".")) {
|
|
280
|
+
out.add(name);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
178
285
|
function wrapEsClient(rawClient) {
|
|
179
286
|
return {
|
|
180
|
-
async
|
|
287
|
+
async testConnection(indexPattern = "*") {
|
|
181
288
|
var _a;
|
|
182
|
-
const safePattern = indexPattern
|
|
183
|
-
if (
|
|
184
|
-
|
|
289
|
+
const safePattern = assertSafeIndexPattern(indexPattern || "*");
|
|
290
|
+
if (typeof rawClient.info === "function") {
|
|
291
|
+
try {
|
|
292
|
+
const rawInfo = await rawClient.info();
|
|
293
|
+
const info = isRecord(rawInfo) && isRecord(rawInfo.body) ? rawInfo.body : rawInfo;
|
|
294
|
+
const clusterName = isRecord(info) ? toNonEmptyString(info.cluster_name) : void 0;
|
|
295
|
+
const versionObj = isRecord(info) && isRecord(info.version) ? info.version : void 0;
|
|
296
|
+
const version = versionObj ? toNonEmptyString(versionObj.number) : void 0;
|
|
297
|
+
if (clusterName || version) {
|
|
298
|
+
return {
|
|
299
|
+
ok: true,
|
|
300
|
+
...clusterName ? { clusterName } : {},
|
|
301
|
+
...version ? { version } : {}
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
} catch (err) {
|
|
305
|
+
const statusCode = isRecord(err) && typeof err.statusCode === "number" ? err.statusCode : void 0;
|
|
306
|
+
if (statusCode === 403 && rawClient.fieldCaps) {
|
|
307
|
+
await rawClient.fieldCaps({ index: safePattern, fields: "@timestamp" });
|
|
308
|
+
return { ok: true, limitedPrivileges: true };
|
|
309
|
+
}
|
|
310
|
+
throw err;
|
|
311
|
+
}
|
|
185
312
|
}
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
313
|
+
if (typeof ((_a = rawClient.cluster) == null ? void 0 : _a.health) === "function") {
|
|
314
|
+
try {
|
|
315
|
+
const rawHealth = await rawClient.cluster.health();
|
|
316
|
+
const health = isRecord(rawHealth) && isRecord(rawHealth.body) ? rawHealth.body : rawHealth;
|
|
317
|
+
const clusterName = isRecord(health) ? toNonEmptyString(health.cluster_name) : void 0;
|
|
318
|
+
if (clusterName) {
|
|
319
|
+
return { ok: true, clusterName };
|
|
320
|
+
}
|
|
321
|
+
} catch (err) {
|
|
322
|
+
const statusCode = isRecord(err) && typeof err.statusCode === "number" ? err.statusCode : void 0;
|
|
323
|
+
if (statusCode === 403 && rawClient.fieldCaps) {
|
|
324
|
+
await rawClient.fieldCaps({ index: safePattern, fields: "@timestamp" });
|
|
325
|
+
return { ok: true, limitedPrivileges: true };
|
|
326
|
+
}
|
|
327
|
+
throw err;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
if (typeof rawClient.ping === "function") {
|
|
331
|
+
const pong = await rawClient.ping();
|
|
332
|
+
if (pong) {
|
|
333
|
+
return { ok: true };
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
if (rawClient.fieldCaps) {
|
|
337
|
+
await rawClient.fieldCaps({ index: safePattern, fields: "@timestamp" });
|
|
338
|
+
return { ok: true };
|
|
339
|
+
}
|
|
340
|
+
return { ok: true };
|
|
341
|
+
},
|
|
342
|
+
async readIndices(indexPattern = "*") {
|
|
343
|
+
var _a, _b, _c, _d;
|
|
344
|
+
const safePattern = assertSafeIndexPattern(indexPattern || "*");
|
|
345
|
+
const names = /* @__PURE__ */ new Set();
|
|
346
|
+
const resolvePromise = typeof ((_a = rawClient.indices) == null ? void 0 : _a.resolveIndex) === "function" ? rawClient.indices.resolveIndex({ name: safePattern }) : Promise.resolve(null);
|
|
347
|
+
const catPromise = typeof ((_b = rawClient.cat) == null ? void 0 : _b.indices) === "function" ? rawClient.cat.indices({ index: safePattern, format: "json", h: "index" }) : Promise.resolve(null);
|
|
348
|
+
const [resolveOutcome, catOutcome] = await Promise.allSettled([resolvePromise, catPromise]);
|
|
349
|
+
if (resolveOutcome.status === "fulfilled" && resolveOutcome.value) {
|
|
350
|
+
collectResolvedIndexNames(resolveOutcome.value, names);
|
|
351
|
+
}
|
|
352
|
+
if (catOutcome.status === "fulfilled" && catOutcome.value) {
|
|
353
|
+
const unwrapped = isRecord(catOutcome.value) && Array.isArray(catOutcome.value.body) ? catOutcome.value.body : catOutcome.value;
|
|
354
|
+
if (Array.isArray(unwrapped)) {
|
|
355
|
+
for (const row of unwrapped) {
|
|
356
|
+
const idx = isRecord(row) ? toNonEmptyString(row.index) : void 0;
|
|
357
|
+
if (idx && !idx.startsWith(".")) {
|
|
358
|
+
names.add(idx);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
if (resolveOutcome.status === "rejected" && (catOutcome.status === "rejected" || typeof ((_c = rawClient.cat) == null ? void 0 : _c.indices) !== "function")) {
|
|
364
|
+
throw resolveOutcome.reason;
|
|
365
|
+
}
|
|
366
|
+
if (catOutcome.status === "rejected" && typeof ((_d = rawClient.indices) == null ? void 0 : _d.resolveIndex) !== "function") {
|
|
367
|
+
throw catOutcome.reason;
|
|
368
|
+
}
|
|
369
|
+
if (resolveOutcome.status === "rejected" && catOutcome.status === "rejected") {
|
|
370
|
+
throw catOutcome.reason || resolveOutcome.reason;
|
|
371
|
+
}
|
|
372
|
+
return Array.from(names).sort((a, b) => a.localeCompare(b));
|
|
194
373
|
},
|
|
195
374
|
async inspectFields(indexPattern) {
|
|
196
375
|
var _a;
|
|
@@ -224,7 +403,42 @@ function wrapEsClient(rawClient) {
|
|
|
224
403
|
}
|
|
225
404
|
return [];
|
|
226
405
|
},
|
|
227
|
-
async
|
|
406
|
+
async openPit(indexPattern, keepAlive = "1m") {
|
|
407
|
+
const safePattern = assertSafeIndexPattern(indexPattern);
|
|
408
|
+
if (typeof rawClient.openPointInTime !== "function") {
|
|
409
|
+
return null;
|
|
410
|
+
}
|
|
411
|
+
try {
|
|
412
|
+
const raw = await rawClient.openPointInTime({
|
|
413
|
+
index: safePattern,
|
|
414
|
+
keep_alive: keepAlive
|
|
415
|
+
});
|
|
416
|
+
const unwrapped = isRecord(raw) && isRecord(raw.body) ? raw.body : raw;
|
|
417
|
+
return isRecord(unwrapped) && typeof unwrapped.id === "string" && unwrapped.id ? unwrapped.id : null;
|
|
418
|
+
} catch {
|
|
419
|
+
return null;
|
|
420
|
+
}
|
|
421
|
+
},
|
|
422
|
+
async closePit(pitId) {
|
|
423
|
+
if (!pitId || typeof rawClient.closePointInTime !== "function") {
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
try {
|
|
427
|
+
await rawClient.closePointInTime({ id: pitId });
|
|
428
|
+
} catch {
|
|
429
|
+
}
|
|
430
|
+
},
|
|
431
|
+
async search(indexPattern, body, options) {
|
|
432
|
+
if (options == null ? void 0 : options.pitId) {
|
|
433
|
+
const response2 = await rawClient.search({
|
|
434
|
+
...body,
|
|
435
|
+
pit: {
|
|
436
|
+
id: options.pitId,
|
|
437
|
+
keep_alive: options.keepAlive ?? "1m"
|
|
438
|
+
}
|
|
439
|
+
});
|
|
440
|
+
return isRecord(response2) && isRecord(response2.body) ? response2.body : response2;
|
|
441
|
+
}
|
|
228
442
|
const safePattern = assertSafeIndexPattern(indexPattern);
|
|
229
443
|
const response = await rawClient.search({
|
|
230
444
|
index: safePattern,
|
|
@@ -240,13 +454,13 @@ class ElasticsearchConnectionService {
|
|
|
240
454
|
}
|
|
241
455
|
fallbackClients = /* @__PURE__ */ new Map();
|
|
242
456
|
async close() {
|
|
243
|
-
const
|
|
457
|
+
const entries = Array.from(this.fallbackClients.values());
|
|
244
458
|
this.fallbackClients.clear();
|
|
245
|
-
await Promise.allSettled(
|
|
459
|
+
await Promise.allSettled(entries.map((entry) => entry.client.close()));
|
|
246
460
|
}
|
|
247
461
|
/**
|
|
248
462
|
* Discover all Elasticsearch data sources configured via `plugin-data-source-elasticsearch`
|
|
249
|
-
* without leaking sensitive credentials (`password`, `apiKey`).
|
|
463
|
+
* without leaking sensitive credentials (`password`, `apiKey`, `bearerToken`, `caCert`).
|
|
250
464
|
*/
|
|
251
465
|
async listConnections() {
|
|
252
466
|
var _a;
|
|
@@ -260,10 +474,15 @@ class ElasticsearchConnectionService {
|
|
|
260
474
|
const opts = extractConnectionOptions(pubOpts ?? ds.options);
|
|
261
475
|
const isEs = isRawEsClientLike(cm == null ? void 0 : cm.esClient) || ((_a = ds.constructor) == null ? void 0 : _a.name) === "ElasticsearchDataSource";
|
|
262
476
|
if (!isEs) continue;
|
|
477
|
+
const modes = inferConnectionModes(opts);
|
|
263
478
|
byKey.set(key, {
|
|
264
479
|
key,
|
|
265
480
|
displayName: typeof ds.displayName === "string" && ds.displayName ? ds.displayName : key,
|
|
266
481
|
status: "loaded",
|
|
482
|
+
endpointMode: modes.endpointMode,
|
|
483
|
+
authMode: modes.authMode,
|
|
484
|
+
tlsMode: modes.tlsMode,
|
|
485
|
+
cloudConfigured: modes.endpointMode === "cloud",
|
|
267
486
|
...typeof opts.indexPattern === "string" ? { indexPattern: opts.indexPattern } : {},
|
|
268
487
|
...typeof opts.nodes === "string" ? { nodes: opts.nodes } : {}
|
|
269
488
|
});
|
|
@@ -280,11 +499,16 @@ class ElasticsearchConnectionService {
|
|
|
280
499
|
if (!isRecord(plain) || typeof plain.key !== "string" || !plain.key.trim()) continue;
|
|
281
500
|
const key = plain.key.trim();
|
|
282
501
|
const opts = extractConnectionOptions(plain.options);
|
|
502
|
+
const modes = inferConnectionModes(opts);
|
|
283
503
|
const existing = byKey.get(key);
|
|
284
504
|
byKey.set(key, {
|
|
285
505
|
key,
|
|
286
506
|
displayName: typeof plain.displayName === "string" && plain.displayName.trim() ? plain.displayName.trim() : (existing == null ? void 0 : existing.displayName) ?? key,
|
|
287
507
|
status: typeof plain.status === "string" ? plain.status : (existing == null ? void 0 : existing.status) ?? "configured",
|
|
508
|
+
endpointMode: modes.endpointMode,
|
|
509
|
+
authMode: modes.authMode,
|
|
510
|
+
tlsMode: modes.tlsMode,
|
|
511
|
+
cloudConfigured: modes.endpointMode === "cloud",
|
|
288
512
|
...typeof opts.indexPattern === "string" ? { indexPattern: opts.indexPattern } : (existing == null ? void 0 : existing.indexPattern) ? { indexPattern: existing.indexPattern } : {},
|
|
289
513
|
...typeof opts.nodes === "string" ? { nodes: opts.nodes } : (existing == null ? void 0 : existing.nodes) ? { nodes: existing.nodes } : {}
|
|
290
514
|
});
|
|
@@ -304,29 +528,45 @@ class ElasticsearchConnectionService {
|
|
|
304
528
|
if (isRecord(liveDs) && isRecord(liveDs.collectionManager) && isRawEsClientLike(liveDs.collectionManager.esClient)) {
|
|
305
529
|
return wrapEsClient(liveDs.collectionManager.esClient);
|
|
306
530
|
}
|
|
307
|
-
const cached = this.fallbackClients.get(cleanKey);
|
|
308
|
-
if (cached) {
|
|
309
|
-
return wrapEsClient(cached);
|
|
310
|
-
}
|
|
311
531
|
const repo = this.app.db.getRepository("dataSources");
|
|
312
532
|
const record = repo ? await repo.findOne({
|
|
313
533
|
filter: { key: cleanKey, type: "elasticsearch" }
|
|
314
534
|
}) : null;
|
|
315
535
|
if (!record) {
|
|
536
|
+
const existingCached = this.fallbackClients.get(cleanKey);
|
|
537
|
+
if (existingCached) {
|
|
538
|
+
return wrapEsClient(existingCached.client);
|
|
539
|
+
}
|
|
316
540
|
throw new Error(`Elasticsearch data source "${cleanKey}" was not found or is not loaded`);
|
|
317
541
|
}
|
|
318
542
|
const plain = typeof record.toJSON === "function" ? record.toJSON() : record;
|
|
319
543
|
const opts = extractConnectionOptions(isRecord(plain) ? plain.options : void 0);
|
|
320
|
-
|
|
544
|
+
const { endpointMode } = inferConnectionModes(opts);
|
|
545
|
+
if (endpointMode === "cloud") {
|
|
546
|
+
if (!toNonEmptyString(opts.cloudId)) {
|
|
547
|
+
throw new Error(`Elasticsearch data source "${cleanKey}" has no configured Cloud ID`);
|
|
548
|
+
}
|
|
549
|
+
} else if (!toNonEmptyString(opts.nodes)) {
|
|
321
550
|
throw new Error(`Elasticsearch data source "${cleanKey}" has no configured nodes`);
|
|
322
551
|
}
|
|
552
|
+
const signature = JSON.stringify(opts);
|
|
553
|
+
const cached = this.fallbackClients.get(cleanKey);
|
|
554
|
+
if (cached && cached.signature === signature) {
|
|
555
|
+
return wrapEsClient(cached.client);
|
|
556
|
+
}
|
|
557
|
+
if (cached) {
|
|
558
|
+
await cached.client.close().catch(() => void 0);
|
|
559
|
+
this.fallbackClients.delete(cleanKey);
|
|
560
|
+
}
|
|
323
561
|
const client = new import_elasticsearch.Client(buildEsClientOptions(opts));
|
|
324
|
-
this.fallbackClients.set(cleanKey, client);
|
|
562
|
+
this.fallbackClients.set(cleanKey, { signature, client });
|
|
325
563
|
return wrapEsClient(client);
|
|
326
564
|
}
|
|
327
565
|
}
|
|
328
566
|
// Annotate the CommonJS export names for ESM import in node:
|
|
329
567
|
0 && (module.exports = {
|
|
330
568
|
ElasticsearchConnectionService,
|
|
569
|
+
buildEsClientOptions,
|
|
570
|
+
inferConnectionModes,
|
|
331
571
|
normalizeFieldCapabilitiesResponse
|
|
332
572
|
});
|
|
@@ -0,0 +1,243 @@
|
|
|
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
|
+
var __defProp = Object.defineProperty;
|
|
11
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
12
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
13
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
14
|
+
var __export = (target, all) => {
|
|
15
|
+
for (var name in all)
|
|
16
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
17
|
+
};
|
|
18
|
+
var __copyProps = (to, from, except, desc) => {
|
|
19
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
20
|
+
for (let key of __getOwnPropNames(from))
|
|
21
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
22
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
23
|
+
}
|
|
24
|
+
return to;
|
|
25
|
+
};
|
|
26
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
27
|
+
var ReportExportService_exports = {};
|
|
28
|
+
__export(ReportExportService_exports, {
|
|
29
|
+
ReportExportService: () => ReportExportService,
|
|
30
|
+
escapeCsvCell: () => escapeCsvCell
|
|
31
|
+
});
|
|
32
|
+
module.exports = __toCommonJS(ReportExportService_exports);
|
|
33
|
+
var import_events = require("events");
|
|
34
|
+
var import_stream = require("stream");
|
|
35
|
+
var import_constants = require("../../shared/constants");
|
|
36
|
+
var import_ReportQueryCompiler = require("./ReportQueryCompiler");
|
|
37
|
+
function readNestedField(source, path) {
|
|
38
|
+
if (path in source) return source[path];
|
|
39
|
+
const segments = path.split(".");
|
|
40
|
+
let cur = source;
|
|
41
|
+
for (const seg of segments) {
|
|
42
|
+
if (cur && typeof cur === "object" && !Array.isArray(cur) && seg in cur) {
|
|
43
|
+
cur = cur[seg];
|
|
44
|
+
} else {
|
|
45
|
+
return void 0;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return cur;
|
|
49
|
+
}
|
|
50
|
+
function escapeCsvCell(value, options) {
|
|
51
|
+
if (value === null || value === void 0) return "";
|
|
52
|
+
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
|
53
|
+
let str = typeof value === "string" ? value : JSON.stringify(value);
|
|
54
|
+
const isSafeAtFieldHeader = (options == null ? void 0 : options.allowAtIdentifier) === true && /^@[A-Za-z0-9_.-]+$/.test(str);
|
|
55
|
+
if (!isSafeAtFieldHeader && /^[=+\-@\t\r]/.test(str) && !/^-?\d+(\.\d+)?$/.test(str)) {
|
|
56
|
+
str = `'${str}`;
|
|
57
|
+
}
|
|
58
|
+
if (/[",\r\n]/.test(str)) {
|
|
59
|
+
return `"${str.replace(/"/g, '""')}"`;
|
|
60
|
+
}
|
|
61
|
+
return str;
|
|
62
|
+
}
|
|
63
|
+
function formatRowsAsCsv(rows, columns) {
|
|
64
|
+
const lines = [];
|
|
65
|
+
for (const row of rows) {
|
|
66
|
+
const cells = columns.map((col) => {
|
|
67
|
+
if (col === "_id") return escapeCsvCell(row._id);
|
|
68
|
+
if (col === "_index") return escapeCsvCell(row._index);
|
|
69
|
+
return escapeCsvCell(readNestedField(row.source, col));
|
|
70
|
+
});
|
|
71
|
+
lines.push(`${cells.join(",")}\r
|
|
72
|
+
`);
|
|
73
|
+
}
|
|
74
|
+
return lines.join("");
|
|
75
|
+
}
|
|
76
|
+
function formatRowsAsNdjson(rows) {
|
|
77
|
+
return rows.map((row) => `${JSON.stringify({ _index: row._index, _id: row._id, ...row.source })}
|
|
78
|
+
`).join("");
|
|
79
|
+
}
|
|
80
|
+
async function writeChunk(stream, chunk) {
|
|
81
|
+
if (!chunk) return;
|
|
82
|
+
if (!stream.write(chunk)) {
|
|
83
|
+
await (0, import_events.once)(stream, "drain");
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
class ReportExportService {
|
|
87
|
+
constructor(connections, reportService) {
|
|
88
|
+
this.connections = connections;
|
|
89
|
+
this.reportService = reportService;
|
|
90
|
+
}
|
|
91
|
+
resolveMaxExportCap(requested) {
|
|
92
|
+
const envCap = Number(process.env.ELASTIC_REPORT_MAX_EXPORT_ROWS);
|
|
93
|
+
const hardCap = Number.isFinite(envCap) && envCap > 0 ? Math.trunc(envCap) : import_constants.DEFAULT_MAX_EXPORT_ROWS;
|
|
94
|
+
if (typeof requested === "number" && Number.isFinite(requested) && requested > 0) {
|
|
95
|
+
return Math.min(hardCap, Math.trunc(requested));
|
|
96
|
+
}
|
|
97
|
+
return hardCap;
|
|
98
|
+
}
|
|
99
|
+
async createExportStream(params) {
|
|
100
|
+
var _a, _b, _c;
|
|
101
|
+
const report = await this.reportService.getReport(params.reportId);
|
|
102
|
+
if (report.spec.allowExport === false) {
|
|
103
|
+
const err = new Error("Data export is disabled for this report");
|
|
104
|
+
err.status = 403;
|
|
105
|
+
throw err;
|
|
106
|
+
}
|
|
107
|
+
const { dataView, fields } = await this.reportService.inspectDataViewFields(report.dataViewId, false);
|
|
108
|
+
const client = await this.connections.getClient(dataView.dataSourceKey);
|
|
109
|
+
const maxRows = this.resolveMaxExportCap(params.maxRows);
|
|
110
|
+
const batchSize = Math.min(import_constants.EXPORT_BATCH_SIZE, maxRows);
|
|
111
|
+
const exportSpec = (0, import_ReportQueryCompiler.normalizeReportSpec)({
|
|
112
|
+
...report.spec,
|
|
113
|
+
visualization: "table",
|
|
114
|
+
...params.columns && params.columns.length > 0 ? { columns: params.columns } : {},
|
|
115
|
+
chart: { ...report.spec.chart, showHistogram: false }
|
|
116
|
+
});
|
|
117
|
+
const effectiveOverrides = report.spec.allowInteractiveControls === false ? {
|
|
118
|
+
contextFilters: (_a = params.overrides) == null ? void 0 : _a.contextFilters,
|
|
119
|
+
sharedFilters: (_b = params.overrides) == null ? void 0 : _b.sharedFilters,
|
|
120
|
+
timeZone: (_c = params.overrides) == null ? void 0 : _c.timeZone
|
|
121
|
+
} : params.overrides;
|
|
122
|
+
const pitId = await client.openPit(dataView.indexPattern, "1m");
|
|
123
|
+
const firstCompile = (0, import_ReportQueryCompiler.compileSearchRequest)({
|
|
124
|
+
spec: exportSpec,
|
|
125
|
+
overrides: {
|
|
126
|
+
...effectiveOverrides,
|
|
127
|
+
page: 1,
|
|
128
|
+
pageSize: batchSize,
|
|
129
|
+
searchAfter: void 0
|
|
130
|
+
},
|
|
131
|
+
timeField: dataView.timeField,
|
|
132
|
+
fields,
|
|
133
|
+
maxRowsCap: import_constants.EXPORT_BATCH_SIZE,
|
|
134
|
+
userContext: params.userContext,
|
|
135
|
+
usePit: Boolean(pitId)
|
|
136
|
+
});
|
|
137
|
+
firstCompile.body.size = batchSize;
|
|
138
|
+
delete firstCompile.body.from;
|
|
139
|
+
delete firstCompile.body.highlight;
|
|
140
|
+
delete firstCompile.body.aggs;
|
|
141
|
+
let firstParsed;
|
|
142
|
+
try {
|
|
143
|
+
const firstRaw = await client.search(dataView.indexPattern, firstCompile.body, pitId ? { pitId } : void 0);
|
|
144
|
+
firstParsed = (0, import_ReportQueryCompiler.parseSearchResponse)(firstRaw, firstCompile.body, firstCompile.effectiveSpec, dataView.timeField);
|
|
145
|
+
} catch (error) {
|
|
146
|
+
if (pitId) {
|
|
147
|
+
await client.closePit(pitId);
|
|
148
|
+
}
|
|
149
|
+
throw error;
|
|
150
|
+
}
|
|
151
|
+
const resolvedColumns = params.columns && params.columns.length > 0 ? params.columns : firstParsed.columns.length > 0 ? firstParsed.columns : ["@timestamp", "_index", "_id"];
|
|
152
|
+
const safeSlug = report.title.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || `report-${String(report.id)}`;
|
|
153
|
+
const ext = params.format === "ndjson" ? "ndjson" : "csv";
|
|
154
|
+
const filename = `${safeSlug}.${ext}`;
|
|
155
|
+
const contentType = params.format === "ndjson" ? "application/x-ndjson; charset=utf-8" : "text/csv; charset=utf-8";
|
|
156
|
+
const stream = new import_stream.PassThrough();
|
|
157
|
+
const pumpRemainingBatches = async () => {
|
|
158
|
+
let exportedCount = 0;
|
|
159
|
+
let activeCursor = firstParsed.nextSearchAfter;
|
|
160
|
+
let activePit = firstParsed.pitId ?? pitId ?? void 0;
|
|
161
|
+
try {
|
|
162
|
+
if (params.format === "csv") {
|
|
163
|
+
await writeChunk(
|
|
164
|
+
stream,
|
|
165
|
+
`\uFEFF${resolvedColumns.map((col) => escapeCsvCell(col, { allowAtIdentifier: true })).join(",")}\r
|
|
166
|
+
`
|
|
167
|
+
);
|
|
168
|
+
await writeChunk(stream, formatRowsAsCsv(firstParsed.rows, resolvedColumns));
|
|
169
|
+
} else {
|
|
170
|
+
await writeChunk(stream, formatRowsAsNdjson(firstParsed.rows));
|
|
171
|
+
}
|
|
172
|
+
exportedCount += firstParsed.rows.length;
|
|
173
|
+
while (exportedCount < maxRows && firstParsed.rows.length === batchSize && activeCursor && activeCursor.length > 0) {
|
|
174
|
+
const remaining = maxRows - exportedCount;
|
|
175
|
+
const nextSize = Math.min(import_constants.EXPORT_BATCH_SIZE, remaining);
|
|
176
|
+
const nextCompile = (0, import_ReportQueryCompiler.compileSearchRequest)({
|
|
177
|
+
spec: exportSpec,
|
|
178
|
+
overrides: {
|
|
179
|
+
...effectiveOverrides,
|
|
180
|
+
pageSize: nextSize,
|
|
181
|
+
searchAfter: activeCursor
|
|
182
|
+
},
|
|
183
|
+
timeField: dataView.timeField,
|
|
184
|
+
fields,
|
|
185
|
+
maxRowsCap: import_constants.EXPORT_BATCH_SIZE,
|
|
186
|
+
userContext: params.userContext,
|
|
187
|
+
usePit: Boolean(activePit)
|
|
188
|
+
});
|
|
189
|
+
nextCompile.body.size = nextSize;
|
|
190
|
+
nextCompile.body.search_after = activeCursor;
|
|
191
|
+
delete nextCompile.body.from;
|
|
192
|
+
delete nextCompile.body.highlight;
|
|
193
|
+
delete nextCompile.body.aggs;
|
|
194
|
+
const nextRaw = await client.search(
|
|
195
|
+
dataView.indexPattern,
|
|
196
|
+
nextCompile.body,
|
|
197
|
+
activePit ? { pitId: activePit } : void 0
|
|
198
|
+
);
|
|
199
|
+
const nextParsed = (0, import_ReportQueryCompiler.parseSearchResponse)(
|
|
200
|
+
nextRaw,
|
|
201
|
+
nextCompile.body,
|
|
202
|
+
nextCompile.effectiveSpec,
|
|
203
|
+
dataView.timeField
|
|
204
|
+
);
|
|
205
|
+
if (nextParsed.pitId) {
|
|
206
|
+
activePit = nextParsed.pitId;
|
|
207
|
+
}
|
|
208
|
+
if (nextParsed.rows.length === 0) {
|
|
209
|
+
break;
|
|
210
|
+
}
|
|
211
|
+
if (params.format === "csv") {
|
|
212
|
+
await writeChunk(stream, formatRowsAsCsv(nextParsed.rows, resolvedColumns));
|
|
213
|
+
} else {
|
|
214
|
+
await writeChunk(stream, formatRowsAsNdjson(nextParsed.rows));
|
|
215
|
+
}
|
|
216
|
+
exportedCount += nextParsed.rows.length;
|
|
217
|
+
activeCursor = nextParsed.nextSearchAfter;
|
|
218
|
+
if (nextParsed.rows.length < nextSize) {
|
|
219
|
+
break;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
stream.end();
|
|
223
|
+
} catch (err) {
|
|
224
|
+
stream.destroy(err instanceof Error ? err : new Error(String(err)));
|
|
225
|
+
} finally {
|
|
226
|
+
if (activePit) {
|
|
227
|
+
await client.closePit(activePit);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
pumpRemainingBatches();
|
|
232
|
+
return {
|
|
233
|
+
stream,
|
|
234
|
+
filename,
|
|
235
|
+
contentType
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
240
|
+
0 && (module.exports = {
|
|
241
|
+
ReportExportService,
|
|
242
|
+
escapeCsvCell
|
|
243
|
+
});
|