plugin-elastic-report 0.1.1 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ai/skills/elastic-report/SKILLS.md +5 -3
- package/dist/client/357.0dd385384cab5dbf.js +10 -0
- package/dist/client/index.js +1 -1
- package/dist/client-v2/851.142c93fc6d666b28.js +10 -0
- package/dist/client-v2/857.a5bf9637d5fd4ef5.js +10 -0
- package/dist/client-v2/877.f4095a3dbcadf98f.js +10 -0
- package/dist/client-v2/index.js +1 -1
- package/dist/externalVersion.js +3 -2
- package/dist/locale/en-US.json +100 -1
- package/dist/locale/vi-VN.json +100 -1
- package/dist/locale/zh-CN.json +100 -1
- package/dist/node_modules/@elastic/elasticsearch/package.json +1 -1
- package/dist/server/acl-guard.js +97 -25
- package/dist/server/collections/es-report-data-views.js +6 -0
- package/dist/server/collections/es-reports.js +6 -0
- package/dist/server/mcp/ElasticReportToolCatalog.js +232 -10
- package/dist/server/plugin.js +153 -19
- package/dist/server/services/ElasticReportService.js +125 -11
- package/dist/server/services/ElasticsearchConnectionService.js +274 -34
- package/dist/server/services/ReportExportService.js +243 -0
- package/dist/server/services/ReportQueryCompiler.js +532 -91
- package/dist/server/workflow/ElasticReportQueryInstruction.js +123 -0
- package/dist/shared/constants.js +17 -2
- package/package.json +3 -2
- package/src/client/index.tsx +16 -1
- package/src/client/workflow-instructions.tsx +44 -0
- package/src/client-v2/__tests__/elastic-report.test.tsx +519 -39
- package/src/client-v2/__tests__/kql-autocomplete.test.ts +178 -0
- package/src/client-v2/api.ts +96 -0
- package/src/client-v2/bus/DashboardFilterBus.ts +212 -0
- package/src/client-v2/components/ElasticBasicCharts.tsx +345 -92
- package/src/client-v2/components/ElasticFilterBar.tsx +372 -0
- package/src/client-v2/components/ElasticKqlInput.tsx +421 -0
- package/src/client-v2/components/ElasticReportBlock.tsx +157 -11
- package/src/client-v2/components/ElasticReportRenderer.tsx +621 -71
- package/src/client-v2/components/ReportSelect.tsx +39 -26
- package/src/client-v2/models/ElasticFilterBarBlockModel.tsx +115 -0
- package/src/client-v2/models/ElasticReportBlockModel.tsx +36 -3
- package/src/client-v2/pages/ElasticReportManager.tsx +432 -26
- package/src/client-v2/plugin.tsx +20 -0
- package/src/client-v2/utils/kqlAutocomplete.ts +861 -0
- package/src/client-v2/workflow/instructions.tsx +149 -0
- package/src/locale/en-US.json +100 -1
- package/src/locale/vi-VN.json +100 -1
- package/src/locale/zh-CN.json +100 -1
- package/src/server/__tests__/query-compiler.test.ts +390 -1
- package/src/server/__tests__/report-mcp-acl.integration.test.ts +271 -3
- package/src/server/acl-guard.ts +119 -28
- package/src/server/collections/es-report-data-views.ts +6 -0
- package/src/server/collections/es-reports.ts +6 -0
- package/src/server/mcp/ElasticReportToolCatalog.ts +255 -9
- package/src/server/plugin.ts +189 -21
- package/src/server/services/ElasticReportService.ts +165 -5
- package/src/server/services/ElasticsearchConnectionService.ts +375 -48
- package/src/server/services/ReportExportService.ts +282 -0
- package/src/server/services/ReportQueryCompiler.ts +629 -94
- package/src/server/workflow/ElasticReportQueryInstruction.ts +124 -0
- package/src/shared/constants.ts +7 -0
- package/src/shared/types.ts +98 -1
- package/dist/client-v2/851.488fdbf5bc5b6a36.js +0 -10
package/src/server/plugin.ts
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
|
|
10
10
|
import { resolve } from 'path';
|
|
11
11
|
import type { Context, Next } from '@nocobase/actions';
|
|
12
|
+
import type WorkflowPlugin from '@nocobase/plugin-workflow';
|
|
12
13
|
import { Plugin, type InstallOptions } from '@nocobase/server';
|
|
13
14
|
import {
|
|
14
15
|
ACL_SNIPPET,
|
|
@@ -18,13 +19,22 @@ import {
|
|
|
18
19
|
MCP_SERVER_NAME,
|
|
19
20
|
REPORTS_COLLECTION,
|
|
20
21
|
SERVICE_RESOURCE,
|
|
22
|
+
WORKFLOW_INSTRUCTION_TYPE,
|
|
21
23
|
} from '../shared/constants';
|
|
22
|
-
import type { ID, ReportRuntimeOverrides } from '../shared/types';
|
|
23
|
-
import {
|
|
24
|
+
import type { ExportFormat, ID, ReportRuntimeOverrides } from '../shared/types';
|
|
25
|
+
import {
|
|
26
|
+
assertCanAccessDataView,
|
|
27
|
+
assertCanAccessReport,
|
|
28
|
+
assertCanManageReports,
|
|
29
|
+
canAccessReport,
|
|
30
|
+
normalizeRoleList,
|
|
31
|
+
} from './acl-guard';
|
|
24
32
|
import { ElasticReportMcpServer } from './mcp/ElasticReportMcpServer';
|
|
25
33
|
import { createElasticReportToolCatalog, type ElasticReportToolDefinition } from './mcp/ElasticReportToolCatalog';
|
|
26
34
|
import { ElasticsearchConnectionService } from './services/ElasticsearchConnectionService';
|
|
27
|
-
import { ElasticReportService, extractCurrentUserId } from './services/ElasticReportService';
|
|
35
|
+
import { ElasticReportService, extractCurrentUserId, extractServerUserContext } from './services/ElasticReportService';
|
|
36
|
+
import { ReportExportService } from './services/ReportExportService';
|
|
37
|
+
import { ElasticReportQueryInstruction } from './workflow/ElasticReportQueryInstruction';
|
|
28
38
|
|
|
29
39
|
interface AIToolsManagerLike {
|
|
30
40
|
registerTools: (
|
|
@@ -68,9 +78,25 @@ function parseIdParam(value: unknown, label: string): ID {
|
|
|
68
78
|
throw err;
|
|
69
79
|
}
|
|
70
80
|
|
|
81
|
+
function parseOverridesParam(raw: unknown): ReportRuntimeOverrides | undefined {
|
|
82
|
+
if (isRecord(raw)) {
|
|
83
|
+
return raw as ReportRuntimeOverrides;
|
|
84
|
+
}
|
|
85
|
+
if (typeof raw === 'string' && raw.trim()) {
|
|
86
|
+
try {
|
|
87
|
+
const parsed = JSON.parse(raw);
|
|
88
|
+
return isRecord(parsed) ? (parsed as ReportRuntimeOverrides) : undefined;
|
|
89
|
+
} catch {
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
|
|
71
96
|
export class PluginElasticReportServer extends Plugin {
|
|
72
97
|
public connectionService!: ElasticsearchConnectionService;
|
|
73
98
|
public reportService!: ElasticReportService;
|
|
99
|
+
public exportService!: ReportExportService;
|
|
74
100
|
public mcpServer!: ElasticReportMcpServer;
|
|
75
101
|
private toolsCatalog: ElasticReportToolDefinition[] = [];
|
|
76
102
|
private readonly schemaCollections = [DATA_VIEWS_COLLECTION, REPORTS_COLLECTION];
|
|
@@ -81,9 +107,10 @@ export class PluginElasticReportServer extends Plugin {
|
|
|
81
107
|
});
|
|
82
108
|
this.connectionService = new ElasticsearchConnectionService(this.app);
|
|
83
109
|
this.reportService = new ElasticReportService(this.app, this.connectionService);
|
|
110
|
+
this.exportService = new ReportExportService(this.connectionService, this.reportService);
|
|
84
111
|
this.toolsCatalog = createElasticReportToolCatalog(this.app, this.reportService);
|
|
85
112
|
this.mcpServer = new ElasticReportMcpServer({
|
|
86
|
-
version: this.options?.version || '0.
|
|
113
|
+
version: this.options?.version || '0.7.0',
|
|
87
114
|
tools: this.toolsCatalog,
|
|
88
115
|
logger: this.app.logger,
|
|
89
116
|
});
|
|
@@ -93,6 +120,7 @@ export class PluginElasticReportServer extends Plugin {
|
|
|
93
120
|
this.registerServiceResource();
|
|
94
121
|
this.registerMcpEndpoint();
|
|
95
122
|
this.registerAclRules();
|
|
123
|
+
this.registerWorkflowInstructions();
|
|
96
124
|
this.registerAITools();
|
|
97
125
|
await this.registerPluginMcpClientEntry();
|
|
98
126
|
|
|
@@ -101,6 +129,17 @@ export class PluginElasticReportServer extends Plugin {
|
|
|
101
129
|
});
|
|
102
130
|
}
|
|
103
131
|
|
|
132
|
+
private registerWorkflowInstructions() {
|
|
133
|
+
const workflow = this.app.pm.get('workflow') as WorkflowPlugin | undefined;
|
|
134
|
+
if (!workflow || typeof workflow.registerInstruction !== 'function') {
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
workflow.registerInstruction(
|
|
138
|
+
WORKFLOW_INSTRUCTION_TYPE,
|
|
139
|
+
new ElasticReportQueryInstruction(workflow, this.reportService),
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
|
|
104
143
|
async install(_options?: InstallOptions) {
|
|
105
144
|
await this.ensureSchema();
|
|
106
145
|
}
|
|
@@ -130,11 +169,36 @@ export class PluginElasticReportServer extends Plugin {
|
|
|
130
169
|
name: SERVICE_RESOURCE,
|
|
131
170
|
actions: {
|
|
132
171
|
listConnections: async (ctx: Context, next: Next) => {
|
|
172
|
+
assertCanManageReports(this.app, ctx);
|
|
133
173
|
ctx.body = await this.reportService.listConnections();
|
|
134
174
|
await next();
|
|
135
175
|
},
|
|
136
176
|
|
|
177
|
+
testConnection: async (ctx: Context, next: Next) => {
|
|
178
|
+
assertCanManageReports(this.app, ctx);
|
|
179
|
+
const payload = getActionPayload(ctx);
|
|
180
|
+
const dataSourceKey = typeof payload.dataSourceKey === 'string' ? payload.dataSourceKey.trim() : '';
|
|
181
|
+
if (!dataSourceKey) {
|
|
182
|
+
ctx.throw(400, 'dataSourceKey is required');
|
|
183
|
+
}
|
|
184
|
+
const indexPattern =
|
|
185
|
+
typeof payload.indexPattern === 'string' && payload.indexPattern.trim() ? payload.indexPattern.trim() : '*';
|
|
186
|
+
try {
|
|
187
|
+
ctx.body = await this.reportService.testConnection(dataSourceKey, indexPattern);
|
|
188
|
+
} catch (error) {
|
|
189
|
+
ctx.throw(400, error instanceof Error ? error.message : String(error));
|
|
190
|
+
}
|
|
191
|
+
await next();
|
|
192
|
+
},
|
|
193
|
+
|
|
194
|
+
listRoles: async (ctx: Context, next: Next) => {
|
|
195
|
+
assertCanManageReports(this.app, ctx);
|
|
196
|
+
ctx.body = await this.reportService.listAvailableRoles();
|
|
197
|
+
await next();
|
|
198
|
+
},
|
|
199
|
+
|
|
137
200
|
listIndices: async (ctx: Context, next: Next) => {
|
|
201
|
+
assertCanManageReports(this.app, ctx);
|
|
138
202
|
const payload = getActionPayload(ctx);
|
|
139
203
|
const dataSourceKey = typeof payload.dataSourceKey === 'string' ? payload.dataSourceKey.trim() : '';
|
|
140
204
|
if (!dataSourceKey) {
|
|
@@ -154,12 +218,17 @@ export class PluginElasticReportServer extends Plugin {
|
|
|
154
218
|
const payload = getActionPayload(ctx);
|
|
155
219
|
try {
|
|
156
220
|
if (payload.dataViewId !== undefined && payload.dataViewId !== null && String(payload.dataViewId).trim()) {
|
|
221
|
+
const dvId = parseIdParam(payload.dataViewId, 'dataViewId');
|
|
157
222
|
const refresh = payload.refresh === true || payload.refresh === 'true';
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
223
|
+
if (refresh) {
|
|
224
|
+
assertCanManageReports(this.app, ctx);
|
|
225
|
+
} else {
|
|
226
|
+
const dv = await this.reportService.getDataView(dvId);
|
|
227
|
+
assertCanAccessDataView(this.app, ctx, dv);
|
|
228
|
+
}
|
|
229
|
+
ctx.body = await this.reportService.inspectDataViewFields(dvId, refresh);
|
|
162
230
|
} else {
|
|
231
|
+
assertCanManageReports(this.app, ctx);
|
|
163
232
|
const dataSourceKey = typeof payload.dataSourceKey === 'string' ? payload.dataSourceKey.trim() : '';
|
|
164
233
|
const indexPattern = typeof payload.indexPattern === 'string' ? payload.indexPattern.trim() : '';
|
|
165
234
|
if (!dataSourceKey || !indexPattern) {
|
|
@@ -176,6 +245,7 @@ export class PluginElasticReportServer extends Plugin {
|
|
|
176
245
|
},
|
|
177
246
|
|
|
178
247
|
upsertDataView: async (ctx: Context, next: Next) => {
|
|
248
|
+
assertCanManageReports(this.app, ctx);
|
|
179
249
|
const payload = getActionPayload(ctx);
|
|
180
250
|
try {
|
|
181
251
|
ctx.body = await this.reportService.upsertDataView(
|
|
@@ -188,23 +258,29 @@ export class PluginElasticReportServer extends Plugin {
|
|
|
188
258
|
indexPattern: typeof payload.indexPattern === 'string' ? payload.indexPattern : '',
|
|
189
259
|
timeField: typeof payload.timeField === 'string' ? payload.timeField : null,
|
|
190
260
|
description: typeof payload.description === 'string' ? payload.description : null,
|
|
261
|
+
...(payload.allowedRoles !== undefined
|
|
262
|
+
? { allowedRoles: normalizeRoleList(payload.allowedRoles) }
|
|
263
|
+
: {}),
|
|
191
264
|
},
|
|
192
265
|
extractCurrentUserId(ctx),
|
|
193
266
|
);
|
|
194
267
|
} catch (error) {
|
|
195
|
-
|
|
268
|
+
const status = (error as { status?: number } | undefined)?.status ?? 400;
|
|
269
|
+
ctx.throw(status, error instanceof Error ? error.message : String(error));
|
|
196
270
|
}
|
|
197
271
|
await next();
|
|
198
272
|
},
|
|
199
273
|
|
|
200
274
|
previewReport: async (ctx: Context, next: Next) => {
|
|
275
|
+
assertCanManageReports(this.app, ctx);
|
|
201
276
|
const payload = getActionPayload(ctx);
|
|
202
277
|
try {
|
|
203
278
|
const dataViewId = parseIdParam(payload.dataViewId, 'dataViewId');
|
|
204
279
|
ctx.body = await this.reportService.previewReport({
|
|
205
280
|
dataViewId,
|
|
206
281
|
spec: payload.spec,
|
|
207
|
-
overrides:
|
|
282
|
+
overrides: parseOverridesParam(payload.overrides),
|
|
283
|
+
userContext: extractServerUserContext(ctx),
|
|
208
284
|
});
|
|
209
285
|
} catch (error) {
|
|
210
286
|
const status = (error as { status?: number } | undefined)?.status ?? 400;
|
|
@@ -214,6 +290,7 @@ export class PluginElasticReportServer extends Plugin {
|
|
|
214
290
|
},
|
|
215
291
|
|
|
216
292
|
saveReport: async (ctx: Context, next: Next) => {
|
|
293
|
+
assertCanManageReports(this.app, ctx);
|
|
217
294
|
const payload = getActionPayload(ctx);
|
|
218
295
|
try {
|
|
219
296
|
ctx.body = await this.reportService.saveReport(
|
|
@@ -226,11 +303,15 @@ export class PluginElasticReportServer extends Plugin {
|
|
|
226
303
|
dataViewId: parseIdParam(payload.dataViewId, 'dataViewId'),
|
|
227
304
|
spec: payload.spec,
|
|
228
305
|
published: payload.published !== false,
|
|
306
|
+
...(payload.allowedRoles !== undefined
|
|
307
|
+
? { allowedRoles: normalizeRoleList(payload.allowedRoles) }
|
|
308
|
+
: {}),
|
|
229
309
|
},
|
|
230
310
|
extractCurrentUserId(ctx),
|
|
231
311
|
);
|
|
232
312
|
} catch (error) {
|
|
233
|
-
|
|
313
|
+
const status = (error as { status?: number } | undefined)?.status ?? 400;
|
|
314
|
+
ctx.throw(status, error instanceof Error ? error.message : String(error));
|
|
234
315
|
}
|
|
235
316
|
await next();
|
|
236
317
|
},
|
|
@@ -238,10 +319,11 @@ export class PluginElasticReportServer extends Plugin {
|
|
|
238
319
|
listPublishedReports: async (ctx: Context, next: Next) => {
|
|
239
320
|
const payload = getActionPayload(ctx);
|
|
240
321
|
const search = typeof payload.search === 'string' ? payload.search : undefined;
|
|
241
|
-
|
|
322
|
+
const publishedReports = await this.reportService.listReports({
|
|
242
323
|
publishedOnly: true,
|
|
243
324
|
search,
|
|
244
325
|
});
|
|
326
|
+
ctx.body = publishedReports.filter((report) => canAccessReport(this.app, ctx, report, report.dataView));
|
|
245
327
|
await next();
|
|
246
328
|
},
|
|
247
329
|
|
|
@@ -251,11 +333,8 @@ export class PluginElasticReportServer extends Plugin {
|
|
|
251
333
|
try {
|
|
252
334
|
const reportId = parseIdParam(rawId, 'reportId');
|
|
253
335
|
const report = await this.reportService.getReport(reportId);
|
|
254
|
-
const isManager = canManageReports(this.app, ctx);
|
|
255
|
-
if (!isManager && !report.published) {
|
|
256
|
-
ctx.throw(404, 'Report not found');
|
|
257
|
-
}
|
|
258
336
|
const { dataView, fields } = await this.reportService.inspectDataViewFields(report.dataViewId, false);
|
|
337
|
+
assertCanAccessReport(this.app, ctx, report, dataView);
|
|
259
338
|
ctx.body = { report, dataView, fields };
|
|
260
339
|
} catch (error) {
|
|
261
340
|
const status = (error as { status?: number } | undefined)?.status ?? 400;
|
|
@@ -269,12 +348,97 @@ export class PluginElasticReportServer extends Plugin {
|
|
|
269
348
|
const rawId = payload.reportId ?? ctx.action?.params?.filterByTk;
|
|
270
349
|
try {
|
|
271
350
|
const reportId = parseIdParam(rawId, 'reportId');
|
|
272
|
-
const
|
|
351
|
+
const report = await this.reportService.getReport(reportId);
|
|
352
|
+
const dataView = report.dataView ?? (await this.reportService.getDataView(report.dataViewId));
|
|
353
|
+
assertCanAccessReport(this.app, ctx, report, dataView);
|
|
273
354
|
ctx.body = await this.reportService.runSavedReport({
|
|
274
355
|
reportId,
|
|
275
|
-
overrides:
|
|
276
|
-
requirePublished:
|
|
356
|
+
overrides: parseOverridesParam(payload.overrides),
|
|
357
|
+
requirePublished: false,
|
|
358
|
+
userContext: extractServerUserContext(ctx),
|
|
359
|
+
});
|
|
360
|
+
} catch (error) {
|
|
361
|
+
const status = (error as { status?: number } | undefined)?.status ?? 400;
|
|
362
|
+
ctx.throw(status, error instanceof Error ? error.message : String(error));
|
|
363
|
+
}
|
|
364
|
+
await next();
|
|
365
|
+
},
|
|
366
|
+
|
|
367
|
+
inspectTopValues: async (ctx: Context, next: Next) => {
|
|
368
|
+
const payload = getActionPayload(ctx);
|
|
369
|
+
try {
|
|
370
|
+
const field = typeof payload.field === 'string' ? payload.field.trim() : '';
|
|
371
|
+
if (!field) {
|
|
372
|
+
ctx.throw(400, 'field is required');
|
|
373
|
+
}
|
|
374
|
+
let dataViewId: ID;
|
|
375
|
+
let reportId: ID | undefined;
|
|
376
|
+
if (payload.reportId !== undefined && payload.reportId !== null && String(payload.reportId).trim() !== '') {
|
|
377
|
+
reportId = parseIdParam(payload.reportId, 'reportId');
|
|
378
|
+
const report = await this.reportService.getReport(reportId);
|
|
379
|
+
const dataView = report.dataView ?? (await this.reportService.getDataView(report.dataViewId));
|
|
380
|
+
assertCanAccessReport(this.app, ctx, report, dataView);
|
|
381
|
+
dataViewId = report.dataViewId;
|
|
382
|
+
} else {
|
|
383
|
+
dataViewId = parseIdParam(payload.dataViewId, 'dataViewId');
|
|
384
|
+
const dataView = await this.reportService.getDataView(dataViewId);
|
|
385
|
+
assertCanAccessDataView(this.app, ctx, dataView);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
ctx.body = await this.reportService.inspectFieldTopValues({
|
|
389
|
+
dataViewId,
|
|
390
|
+
...(reportId !== undefined ? { reportId } : {}),
|
|
391
|
+
field,
|
|
392
|
+
size: typeof payload.size === 'number' ? payload.size : Number(payload.size) || 10,
|
|
393
|
+
overrides: parseOverridesParam(payload.overrides),
|
|
394
|
+
userContext: extractServerUserContext(ctx),
|
|
395
|
+
});
|
|
396
|
+
} catch (error) {
|
|
397
|
+
const status = (error as { status?: number } | undefined)?.status ?? 400;
|
|
398
|
+
ctx.throw(status, error instanceof Error ? error.message : String(error));
|
|
399
|
+
}
|
|
400
|
+
await next();
|
|
401
|
+
},
|
|
402
|
+
|
|
403
|
+
exportReport: async (ctx: Context, next: Next) => {
|
|
404
|
+
const payload = getActionPayload(ctx);
|
|
405
|
+
const rawId = payload.reportId ?? ctx.action?.params?.filterByTk;
|
|
406
|
+
try {
|
|
407
|
+
const reportId = parseIdParam(rawId, 'reportId');
|
|
408
|
+
const report = await this.reportService.getReport(reportId);
|
|
409
|
+
const dataView = report.dataView ?? (await this.reportService.getDataView(report.dataViewId));
|
|
410
|
+
assertCanAccessReport(this.app, ctx, report, dataView);
|
|
411
|
+
|
|
412
|
+
const format: ExportFormat = payload.format === 'ndjson' ? 'ndjson' : 'csv';
|
|
413
|
+
const columns = Array.isArray(payload.columns)
|
|
414
|
+
? payload.columns.filter((c): c is string => typeof c === 'string' && Boolean(c.trim()))
|
|
415
|
+
: typeof payload.columns === 'string' && payload.columns.trim()
|
|
416
|
+
? payload.columns
|
|
417
|
+
.split(',')
|
|
418
|
+
.map((c) => c.trim())
|
|
419
|
+
.filter(Boolean)
|
|
420
|
+
: undefined;
|
|
421
|
+
const maxRows =
|
|
422
|
+
typeof payload.maxRows === 'number'
|
|
423
|
+
? payload.maxRows
|
|
424
|
+
: payload.maxRows !== undefined
|
|
425
|
+
? Number(payload.maxRows)
|
|
426
|
+
: undefined;
|
|
427
|
+
|
|
428
|
+
const { stream, filename, contentType } = await this.exportService.createExportStream({
|
|
429
|
+
reportId,
|
|
430
|
+
format,
|
|
431
|
+
overrides: parseOverridesParam(payload.overrides),
|
|
432
|
+
...(columns ? { columns } : {}),
|
|
433
|
+
...(maxRows !== undefined && Number.isFinite(maxRows) ? { maxRows } : {}),
|
|
434
|
+
userContext: extractServerUserContext(ctx),
|
|
277
435
|
});
|
|
436
|
+
|
|
437
|
+
ctx.withoutDataWrapping = true;
|
|
438
|
+
ctx.status = 200;
|
|
439
|
+
ctx.type = contentType;
|
|
440
|
+
ctx.set('Content-Disposition', `attachment; filename="${filename}"`);
|
|
441
|
+
ctx.body = stream;
|
|
278
442
|
} catch (error) {
|
|
279
443
|
const status = (error as { status?: number } | undefined)?.status ?? 400;
|
|
280
444
|
ctx.throw(status, error instanceof Error ? error.message : String(error));
|
|
@@ -312,8 +476,12 @@ export class PluginElasticReportServer extends Plugin {
|
|
|
312
476
|
}
|
|
313
477
|
|
|
314
478
|
private registerAclRules() {
|
|
315
|
-
// Viewers on pages can list published reports, inspect report metadata, and
|
|
316
|
-
this.app.acl.allow(
|
|
479
|
+
// Viewers on pages can list published reports, inspect report metadata/top-values, run, and export published reports.
|
|
480
|
+
this.app.acl.allow(
|
|
481
|
+
SERVICE_RESOURCE,
|
|
482
|
+
['listPublishedReports', 'getReportMeta', 'runReport', 'inspectTopValues', 'exportReport'],
|
|
483
|
+
'loggedIn',
|
|
484
|
+
);
|
|
317
485
|
// Dedicated MCP endpoint requires authentication; tool-level ACL enforces read vs manage permissions.
|
|
318
486
|
this.app.acl.allow(MCP_RESOURCE_NAME, '*', 'loggedIn');
|
|
319
487
|
|
|
@@ -16,17 +16,28 @@ import {
|
|
|
16
16
|
REPORTS_COLLECTION,
|
|
17
17
|
} from '../../shared/constants';
|
|
18
18
|
import type {
|
|
19
|
+
EsConnectionHealthResult,
|
|
19
20
|
EsConnectionSummary,
|
|
20
21
|
EsDataViewRecord,
|
|
21
22
|
EsFieldCapability,
|
|
22
23
|
EsReportRecord,
|
|
24
|
+
FieldTopValuesResult,
|
|
23
25
|
ID,
|
|
24
26
|
ReportExecutionResult,
|
|
25
27
|
ReportRuntimeOverrides,
|
|
26
|
-
|
|
28
|
+
RoleSummary,
|
|
27
29
|
} from '../../shared/types';
|
|
30
|
+
import { getEffectiveRoles, normalizeRoleList } from '../acl-guard';
|
|
28
31
|
import type { ElasticsearchConnectionService } from './ElasticsearchConnectionService';
|
|
29
|
-
import {
|
|
32
|
+
import {
|
|
33
|
+
type ServerUserTokenContext,
|
|
34
|
+
buildFieldCapabilityMap,
|
|
35
|
+
compileKqlToQueryDsl,
|
|
36
|
+
compileSearchRequest,
|
|
37
|
+
normalizeReportSpec,
|
|
38
|
+
parseSearchResponse,
|
|
39
|
+
resolveAggregatableField,
|
|
40
|
+
} from './ReportQueryCompiler';
|
|
30
41
|
|
|
31
42
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
32
43
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
@@ -49,6 +60,7 @@ function serializeDataView(row: unknown): EsDataViewRecord {
|
|
|
49
60
|
indexPattern: typeof plain.indexPattern === 'string' ? plain.indexPattern : '',
|
|
50
61
|
timeField: typeof plain.timeField === 'string' && plain.timeField.trim() ? plain.timeField.trim() : null,
|
|
51
62
|
description: typeof plain.description === 'string' ? plain.description : null,
|
|
63
|
+
allowedRoles: normalizeRoleList(plain.allowedRoles),
|
|
52
64
|
cachedFields: Array.isArray(plain.cachedFields) ? (plain.cachedFields as EsFieldCapability[]) : null,
|
|
53
65
|
...(typeof plain.createdAt === 'string' ? { createdAt: plain.createdAt } : {}),
|
|
54
66
|
...(typeof plain.updatedAt === 'string' ? { updatedAt: plain.updatedAt } : {}),
|
|
@@ -67,6 +79,7 @@ function serializeReport(row: unknown): EsReportRecord {
|
|
|
67
79
|
visualization: spec.visualization,
|
|
68
80
|
spec,
|
|
69
81
|
published: plain.published !== false,
|
|
82
|
+
allowedRoles: normalizeRoleList(plain.allowedRoles),
|
|
70
83
|
...(typeof plain.createdAt === 'string' ? { createdAt: plain.createdAt } : {}),
|
|
71
84
|
...(typeof plain.updatedAt === 'string' ? { updatedAt: plain.updatedAt } : {}),
|
|
72
85
|
};
|
|
@@ -79,6 +92,7 @@ export interface UpsertDataViewInput {
|
|
|
79
92
|
indexPattern: string;
|
|
80
93
|
timeField?: string | null;
|
|
81
94
|
description?: string | null;
|
|
95
|
+
allowedRoles?: string[];
|
|
82
96
|
refreshFields?: boolean;
|
|
83
97
|
}
|
|
84
98
|
|
|
@@ -89,6 +103,7 @@ export interface SaveReportInput {
|
|
|
89
103
|
dataViewId: ID;
|
|
90
104
|
spec: unknown;
|
|
91
105
|
published?: boolean;
|
|
106
|
+
allowedRoles?: string[];
|
|
92
107
|
}
|
|
93
108
|
|
|
94
109
|
export class ElasticReportService {
|
|
@@ -101,6 +116,29 @@ export class ElasticReportService {
|
|
|
101
116
|
return this.connections.listConnections();
|
|
102
117
|
}
|
|
103
118
|
|
|
119
|
+
async testConnection(dataSourceKey: string, indexPattern = '*'): Promise<EsConnectionHealthResult> {
|
|
120
|
+
const client = await this.connections.getClient(dataSourceKey);
|
|
121
|
+
return client.testConnection(indexPattern);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async listAvailableRoles(): Promise<RoleSummary[]> {
|
|
125
|
+
if (!this.app.db.hasCollection('roles')) {
|
|
126
|
+
return [];
|
|
127
|
+
}
|
|
128
|
+
const rows = await this.app.db.getRepository('roles').find({
|
|
129
|
+
sort: ['name'],
|
|
130
|
+
});
|
|
131
|
+
return rows
|
|
132
|
+
.map((row) => {
|
|
133
|
+
const plain = toPlainObject(row);
|
|
134
|
+
const name = typeof plain.name === 'string' ? plain.name.trim() : '';
|
|
135
|
+
const rawTitle = typeof plain.title === 'string' && plain.title.trim() ? plain.title.trim() : name;
|
|
136
|
+
const title = rawTitle.replace(/^\{\{\s*t\(\s*['"](.+?)['"]\s*\)\s*\}\}$/, '$1');
|
|
137
|
+
return { name, title };
|
|
138
|
+
})
|
|
139
|
+
.filter((r) => Boolean(r.name) && r.name !== 'anonymous');
|
|
140
|
+
}
|
|
141
|
+
|
|
104
142
|
async listIndices(dataSourceKey: string, indexPattern = '*'): Promise<string[]> {
|
|
105
143
|
const client = await this.connections.getClient(dataSourceKey);
|
|
106
144
|
return client.readIndices(indexPattern);
|
|
@@ -176,6 +214,7 @@ export class ElasticReportService {
|
|
|
176
214
|
timeField,
|
|
177
215
|
description: input.description ?? null,
|
|
178
216
|
cachedFields: fields,
|
|
217
|
+
...(input.allowedRoles !== undefined ? { allowedRoles: normalizeRoleList(input.allowedRoles) } : {}),
|
|
179
218
|
};
|
|
180
219
|
|
|
181
220
|
if (input.id !== undefined && input.id !== null && String(input.id).trim() !== '') {
|
|
@@ -186,6 +225,9 @@ export class ElasticReportService {
|
|
|
186
225
|
return this.getDataView(input.id);
|
|
187
226
|
}
|
|
188
227
|
|
|
228
|
+
if (values.allowedRoles === undefined) {
|
|
229
|
+
values.allowedRoles = [];
|
|
230
|
+
}
|
|
189
231
|
if (userId !== undefined) {
|
|
190
232
|
values.createdById = userId;
|
|
191
233
|
}
|
|
@@ -229,6 +271,9 @@ export class ElasticReportService {
|
|
|
229
271
|
}
|
|
230
272
|
const dataView = await this.getDataView(input.dataViewId);
|
|
231
273
|
const spec = normalizeReportSpec(input.spec);
|
|
274
|
+
if (spec.queryMode !== 'simple' && spec.query && spec.query.trim()) {
|
|
275
|
+
compileKqlToQueryDsl(spec.query);
|
|
276
|
+
}
|
|
232
277
|
const repo = this.app.db.getRepository(REPORTS_COLLECTION);
|
|
233
278
|
|
|
234
279
|
const values: Record<string, unknown> = {
|
|
@@ -238,6 +283,7 @@ export class ElasticReportService {
|
|
|
238
283
|
visualization: spec.visualization,
|
|
239
284
|
spec,
|
|
240
285
|
published: input.published !== false,
|
|
286
|
+
...(input.allowedRoles !== undefined ? { allowedRoles: normalizeRoleList(input.allowedRoles) } : {}),
|
|
241
287
|
...(userId !== undefined ? { updatedById: userId } : {}),
|
|
242
288
|
};
|
|
243
289
|
|
|
@@ -249,6 +295,9 @@ export class ElasticReportService {
|
|
|
249
295
|
return this.getReport(input.id);
|
|
250
296
|
}
|
|
251
297
|
|
|
298
|
+
if (values.allowedRoles === undefined) {
|
|
299
|
+
values.allowedRoles = [];
|
|
300
|
+
}
|
|
252
301
|
if (userId !== undefined) {
|
|
253
302
|
values.createdById = userId;
|
|
254
303
|
}
|
|
@@ -262,23 +311,45 @@ export class ElasticReportService {
|
|
|
262
311
|
spec: unknown;
|
|
263
312
|
overrides?: ReportRuntimeOverrides;
|
|
264
313
|
forMcp?: boolean;
|
|
314
|
+
userContext?: ServerUserTokenContext;
|
|
265
315
|
}): Promise<{
|
|
266
316
|
dataView: EsDataViewRecord;
|
|
267
317
|
result: ReportExecutionResult;
|
|
268
318
|
}> {
|
|
269
319
|
const { dataView, fields } = await this.inspectDataViewFields(params.dataViewId, false);
|
|
270
320
|
const normalizedSpec = normalizeReportSpec(params.spec);
|
|
321
|
+
const client = await this.connections.getClient(dataView.dataSourceKey);
|
|
322
|
+
|
|
323
|
+
let activePitId = params.overrides?.pitId;
|
|
324
|
+
const needsDeepCursor =
|
|
325
|
+
normalizedSpec.visualization === 'table' &&
|
|
326
|
+
!activePitId &&
|
|
327
|
+
((params.overrides?.page ?? 1) * (params.overrides?.pageSize ?? normalizedSpec.pageSize ?? 20) > 10000 ||
|
|
328
|
+
Boolean(params.overrides?.searchAfter));
|
|
329
|
+
|
|
330
|
+
if (needsDeepCursor && !params.overrides?.searchAfter) {
|
|
331
|
+
activePitId = (await client.openPit(dataView.indexPattern, '1m')) ?? undefined;
|
|
332
|
+
}
|
|
333
|
+
|
|
271
334
|
const { body, effectiveSpec } = compileSearchRequest({
|
|
272
335
|
spec: normalizedSpec,
|
|
273
336
|
overrides: params.overrides,
|
|
274
337
|
timeField: dataView.timeField,
|
|
275
338
|
fields,
|
|
276
339
|
maxRowsCap: params.forMcp ? MAX_MCP_PREVIEW_SIZE : MAX_UI_PAGE_SIZE,
|
|
340
|
+
userContext: params.userContext,
|
|
341
|
+
usePit: Boolean(activePitId),
|
|
277
342
|
});
|
|
278
343
|
|
|
279
|
-
const
|
|
280
|
-
|
|
344
|
+
const rawSearch = await client.search(
|
|
345
|
+
dataView.indexPattern,
|
|
346
|
+
body,
|
|
347
|
+
activePitId ? { pitId: activePitId } : undefined,
|
|
348
|
+
);
|
|
281
349
|
const result = parseSearchResponse(rawSearch, body, effectiveSpec, dataView.timeField);
|
|
350
|
+
if (activePitId && !result.pitId) {
|
|
351
|
+
result.pitId = activePitId;
|
|
352
|
+
}
|
|
282
353
|
return { dataView, result };
|
|
283
354
|
}
|
|
284
355
|
|
|
@@ -287,6 +358,7 @@ export class ElasticReportService {
|
|
|
287
358
|
overrides?: ReportRuntimeOverrides;
|
|
288
359
|
requirePublished?: boolean;
|
|
289
360
|
forMcp?: boolean;
|
|
361
|
+
userContext?: ServerUserTokenContext;
|
|
290
362
|
}): Promise<{
|
|
291
363
|
report: EsReportRecord;
|
|
292
364
|
dataView: EsDataViewRecord;
|
|
@@ -297,12 +369,16 @@ export class ElasticReportService {
|
|
|
297
369
|
throw new Error(`Report "${report.title}" is not published`);
|
|
298
370
|
}
|
|
299
371
|
|
|
300
|
-
const runtimeOverrides =
|
|
372
|
+
const runtimeOverrides: ReportRuntimeOverrides | undefined =
|
|
301
373
|
report.spec.allowInteractiveControls === false
|
|
302
374
|
? {
|
|
375
|
+
contextFilters: params.overrides?.contextFilters,
|
|
376
|
+
sharedFilters: params.overrides?.sharedFilters,
|
|
377
|
+
timeZone: params.overrides?.timeZone,
|
|
303
378
|
page: params.overrides?.page,
|
|
304
379
|
pageSize: params.overrides?.pageSize,
|
|
305
380
|
searchAfter: params.overrides?.searchAfter,
|
|
381
|
+
pitId: params.overrides?.pitId,
|
|
306
382
|
}
|
|
307
383
|
: params.overrides;
|
|
308
384
|
|
|
@@ -311,10 +387,73 @@ export class ElasticReportService {
|
|
|
311
387
|
spec: report.spec,
|
|
312
388
|
overrides: runtimeOverrides,
|
|
313
389
|
forMcp: params.forMcp,
|
|
390
|
+
userContext: params.userContext,
|
|
314
391
|
});
|
|
315
392
|
|
|
316
393
|
return { report, dataView, result };
|
|
317
394
|
}
|
|
395
|
+
|
|
396
|
+
async inspectFieldTopValues(params: {
|
|
397
|
+
dataViewId: ID;
|
|
398
|
+
reportId?: ID;
|
|
399
|
+
field: string;
|
|
400
|
+
size?: number;
|
|
401
|
+
overrides?: ReportRuntimeOverrides;
|
|
402
|
+
userContext?: ServerUserTokenContext;
|
|
403
|
+
}): Promise<FieldTopValuesResult> {
|
|
404
|
+
const rawField = params.field.trim();
|
|
405
|
+
if (!rawField) {
|
|
406
|
+
throw new Error('field is required');
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
let baseSpec = normalizeReportSpec({ visualization: 'bar' });
|
|
410
|
+
let targetDataViewId = params.dataViewId;
|
|
411
|
+
if (params.reportId !== undefined && params.reportId !== null && String(params.reportId).trim() !== '') {
|
|
412
|
+
const report = await this.getReport(params.reportId);
|
|
413
|
+
targetDataViewId = report.dataViewId;
|
|
414
|
+
baseSpec = report.spec;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
const { dataView, fields } = await this.inspectDataViewFields(targetDataViewId, false);
|
|
418
|
+
const fieldMap = buildFieldCapabilityMap(fields);
|
|
419
|
+
const resolvedField = resolveAggregatableField(rawField, fieldMap);
|
|
420
|
+
const topSize = Math.max(1, Math.min(25, Math.trunc(params.size ?? 10)));
|
|
421
|
+
|
|
422
|
+
const probeSpec = normalizeReportSpec({
|
|
423
|
+
...baseSpec,
|
|
424
|
+
visualization: 'bar',
|
|
425
|
+
chart: {
|
|
426
|
+
bucketType: 'terms',
|
|
427
|
+
bucketField: resolvedField,
|
|
428
|
+
topN: topSize,
|
|
429
|
+
metricType: 'count',
|
|
430
|
+
},
|
|
431
|
+
});
|
|
432
|
+
|
|
433
|
+
const { body, effectiveSpec } = compileSearchRequest({
|
|
434
|
+
spec: probeSpec,
|
|
435
|
+
overrides: params.overrides,
|
|
436
|
+
timeField: dataView.timeField,
|
|
437
|
+
fields,
|
|
438
|
+
userContext: params.userContext,
|
|
439
|
+
});
|
|
440
|
+
|
|
441
|
+
const client = await this.connections.getClient(dataView.dataSourceKey);
|
|
442
|
+
const rawSearch = await client.search(dataView.indexPattern, body);
|
|
443
|
+
const parsed = parseSearchResponse(rawSearch, body, effectiveSpec, dataView.timeField);
|
|
444
|
+
const totalDocs = parsed.total;
|
|
445
|
+
|
|
446
|
+
return {
|
|
447
|
+
field: rawField,
|
|
448
|
+
resolvedField,
|
|
449
|
+
totalDocs,
|
|
450
|
+
buckets: parsed.series.map((pt) => ({
|
|
451
|
+
value: pt.label,
|
|
452
|
+
count: pt.count,
|
|
453
|
+
percentage: totalDocs > 0 ? Number(((pt.count / totalDocs) * 100).toFixed(1)) : 0,
|
|
454
|
+
})),
|
|
455
|
+
};
|
|
456
|
+
}
|
|
318
457
|
}
|
|
319
458
|
|
|
320
459
|
export function extractCurrentUserId(ctx?: Partial<Context>): ID | undefined {
|
|
@@ -324,3 +463,24 @@ export function extractCurrentUserId(ctx?: Partial<Context>): ID | undefined {
|
|
|
324
463
|
if (authUser !== undefined && authUser !== null) return authUser;
|
|
325
464
|
return undefined;
|
|
326
465
|
}
|
|
466
|
+
|
|
467
|
+
export function extractServerUserContext(ctx?: Partial<Context>): ServerUserTokenContext {
|
|
468
|
+
const stateUser = (
|
|
469
|
+
ctx?.state as
|
|
470
|
+
| {
|
|
471
|
+
currentUser?: {
|
|
472
|
+
id?: ID;
|
|
473
|
+
username?: string;
|
|
474
|
+
email?: string;
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
| undefined
|
|
478
|
+
)?.currentUser;
|
|
479
|
+
const effectiveRole = getEffectiveRoles(ctx)[0];
|
|
480
|
+
return {
|
|
481
|
+
userId: extractCurrentUserId(ctx),
|
|
482
|
+
...(typeof stateUser?.username === 'string' ? { username: stateUser.username } : {}),
|
|
483
|
+
...(typeof stateUser?.email === 'string' ? { email: stateUser.email } : {}),
|
|
484
|
+
...(effectiveRole ? { role: effectiveRole } : {}),
|
|
485
|
+
};
|
|
486
|
+
}
|