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
|
@@ -1,326 +1,494 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* This file is part of the NocoBase (R) project.
|
|
3
|
-
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
|
|
4
|
-
* Authors: NocoBase Team.
|
|
5
|
-
*
|
|
6
|
-
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
|
|
7
|
-
* For more information, please refer to: https://www.nocobase.com/agreement.
|
|
8
|
-
*/
|
|
9
|
-
|
|
10
|
-
import type { Context } from '@nocobase/actions';
|
|
11
|
-
import type {
|
|
12
|
-
import {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
function
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
async
|
|
155
|
-
const
|
|
156
|
-
const
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
if (
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
const
|
|
280
|
-
const
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* This file is part of the NocoBase (R) project.
|
|
3
|
+
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
|
|
4
|
+
* Authors: NocoBase Team.
|
|
5
|
+
*
|
|
6
|
+
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
|
|
7
|
+
* For more information, please refer to: https://www.nocobase.com/agreement.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { Context } from '@nocobase/actions';
|
|
11
|
+
import type { Transaction } from '@nocobase/database';
|
|
12
|
+
import type { Application } from '@nocobase/server';
|
|
13
|
+
import {
|
|
14
|
+
DATA_VIEWS_COLLECTION,
|
|
15
|
+
MAX_MCP_PREVIEW_SIZE,
|
|
16
|
+
MAX_UI_PAGE_SIZE,
|
|
17
|
+
REPORTS_COLLECTION,
|
|
18
|
+
} from '../../shared/constants';
|
|
19
|
+
import type {
|
|
20
|
+
EsConnectionHealthResult,
|
|
21
|
+
EsConnectionSummary,
|
|
22
|
+
EsDataViewRecord,
|
|
23
|
+
EsFieldCapability,
|
|
24
|
+
EsReportRecord,
|
|
25
|
+
FieldTopValuesResult,
|
|
26
|
+
ID,
|
|
27
|
+
ReportExecutionResult,
|
|
28
|
+
ReportRuntimeOverrides,
|
|
29
|
+
RoleSummary,
|
|
30
|
+
} from '../../shared/types';
|
|
31
|
+
import { getEffectiveRoles, normalizeRoleList } from '../acl-guard';
|
|
32
|
+
import type { ElasticsearchConnectionService } from './ElasticsearchConnectionService';
|
|
33
|
+
import {
|
|
34
|
+
type ServerUserTokenContext,
|
|
35
|
+
buildFieldCapabilityMap,
|
|
36
|
+
compileKqlToQueryDsl,
|
|
37
|
+
compileSearchRequest,
|
|
38
|
+
normalizeReportSpec,
|
|
39
|
+
parseSearchResponse,
|
|
40
|
+
resolveAggregatableField,
|
|
41
|
+
} from './ReportQueryCompiler';
|
|
42
|
+
|
|
43
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
44
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function toPlainObject(modelOrRow: unknown): Record<string, unknown> {
|
|
48
|
+
if (isRecord(modelOrRow) && typeof modelOrRow.toJSON === 'function') {
|
|
49
|
+
const json = modelOrRow.toJSON();
|
|
50
|
+
return isRecord(json) ? json : {};
|
|
51
|
+
}
|
|
52
|
+
return isRecord(modelOrRow) ? modelOrRow : {};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function serializeDataView(row: unknown): EsDataViewRecord {
|
|
56
|
+
const plain = toPlainObject(row);
|
|
57
|
+
return {
|
|
58
|
+
id: (plain.id as ID) ?? '',
|
|
59
|
+
title: typeof plain.title === 'string' ? plain.title : '',
|
|
60
|
+
dataSourceKey: typeof plain.dataSourceKey === 'string' ? plain.dataSourceKey : '',
|
|
61
|
+
indexPattern: typeof plain.indexPattern === 'string' ? plain.indexPattern : '',
|
|
62
|
+
timeField: typeof plain.timeField === 'string' && plain.timeField.trim() ? plain.timeField.trim() : null,
|
|
63
|
+
description: typeof plain.description === 'string' ? plain.description : null,
|
|
64
|
+
allowedRoles: normalizeRoleList(plain.allowedRoles),
|
|
65
|
+
cachedFields: Array.isArray(plain.cachedFields) ? (plain.cachedFields as EsFieldCapability[]) : null,
|
|
66
|
+
...(typeof plain.createdAt === 'string' ? { createdAt: plain.createdAt } : {}),
|
|
67
|
+
...(typeof plain.updatedAt === 'string' ? { updatedAt: plain.updatedAt } : {}),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function serializeReport(row: unknown): EsReportRecord {
|
|
72
|
+
const plain = toPlainObject(row);
|
|
73
|
+
const spec = normalizeReportSpec(plain.spec, plain.visualization);
|
|
74
|
+
return {
|
|
75
|
+
id: (plain.id as ID) ?? '',
|
|
76
|
+
title: typeof plain.title === 'string' ? plain.title : '',
|
|
77
|
+
description: typeof plain.description === 'string' ? plain.description : null,
|
|
78
|
+
dataViewId: (plain.dataViewId as ID) ?? '',
|
|
79
|
+
dataView: isRecord(plain.dataView) ? serializeDataView(plain.dataView) : null,
|
|
80
|
+
visualization: spec.visualization,
|
|
81
|
+
spec,
|
|
82
|
+
published: plain.published !== false,
|
|
83
|
+
allowedRoles: normalizeRoleList(plain.allowedRoles),
|
|
84
|
+
...(typeof plain.createdAt === 'string' ? { createdAt: plain.createdAt } : {}),
|
|
85
|
+
...(typeof plain.updatedAt === 'string' ? { updatedAt: plain.updatedAt } : {}),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface UpsertDataViewInput {
|
|
90
|
+
id?: ID;
|
|
91
|
+
title: string;
|
|
92
|
+
dataSourceKey: string;
|
|
93
|
+
indexPattern: string;
|
|
94
|
+
timeField?: string | null;
|
|
95
|
+
description?: string | null;
|
|
96
|
+
allowedRoles?: string[];
|
|
97
|
+
refreshFields?: boolean;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export interface SaveReportInput {
|
|
101
|
+
id?: ID;
|
|
102
|
+
title: string;
|
|
103
|
+
description?: string | null;
|
|
104
|
+
dataViewId: ID;
|
|
105
|
+
spec: unknown;
|
|
106
|
+
published?: boolean;
|
|
107
|
+
allowedRoles?: string[];
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export class ElasticReportService {
|
|
111
|
+
constructor(
|
|
112
|
+
private readonly app: Application,
|
|
113
|
+
private readonly connections: ElasticsearchConnectionService,
|
|
114
|
+
) {}
|
|
115
|
+
|
|
116
|
+
async listConnections(): Promise<EsConnectionSummary[]> {
|
|
117
|
+
return this.connections.listConnections();
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async testConnection(dataSourceKey: string, indexPattern = '*'): Promise<EsConnectionHealthResult> {
|
|
121
|
+
const client = await this.connections.getClient(dataSourceKey);
|
|
122
|
+
return client.testConnection(indexPattern);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async listAvailableRoles(): Promise<RoleSummary[]> {
|
|
126
|
+
if (!this.app.db.hasCollection('roles')) {
|
|
127
|
+
return [];
|
|
128
|
+
}
|
|
129
|
+
const rows = await this.app.db.getRepository('roles').find({
|
|
130
|
+
sort: ['name'],
|
|
131
|
+
});
|
|
132
|
+
return rows
|
|
133
|
+
.map((row) => {
|
|
134
|
+
const plain = toPlainObject(row);
|
|
135
|
+
const name = typeof plain.name === 'string' ? plain.name.trim() : '';
|
|
136
|
+
const rawTitle = typeof plain.title === 'string' && plain.title.trim() ? plain.title.trim() : name;
|
|
137
|
+
const title = rawTitle.replace(/^\{\{\s*t\(\s*['"](.+?)['"]\s*\)\s*\}\}$/, '$1');
|
|
138
|
+
return { name, title };
|
|
139
|
+
})
|
|
140
|
+
.filter((r) => Boolean(r.name) && r.name !== 'anonymous');
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async listIndices(dataSourceKey: string, indexPattern = '*'): Promise<string[]> {
|
|
144
|
+
const client = await this.connections.getClient(dataSourceKey);
|
|
145
|
+
return client.readIndices(indexPattern);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async listDataViews(): Promise<EsDataViewRecord[]> {
|
|
149
|
+
const repo = this.app.db.getRepository(DATA_VIEWS_COLLECTION);
|
|
150
|
+
const rows = await repo.find({ sort: ['-id'] });
|
|
151
|
+
return rows.map(serializeDataView);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async getDataView(dataViewId: ID): Promise<EsDataViewRecord> {
|
|
155
|
+
const repo = this.app.db.getRepository(DATA_VIEWS_COLLECTION);
|
|
156
|
+
const row = await repo.findOne({ filterByTk: dataViewId });
|
|
157
|
+
if (!row) {
|
|
158
|
+
throw new Error(`Data view "${String(dataViewId)}" was not found`);
|
|
159
|
+
}
|
|
160
|
+
return serializeDataView(row);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async inspectFieldsBySource(dataSourceKey: string, indexPattern: string): Promise<EsFieldCapability[]> {
|
|
164
|
+
const client = await this.connections.getClient(dataSourceKey);
|
|
165
|
+
return client.inspectFields(indexPattern);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async inspectDataViewFields(
|
|
169
|
+
dataViewId: ID,
|
|
170
|
+
refresh = false,
|
|
171
|
+
): Promise<{
|
|
172
|
+
dataView: EsDataViewRecord;
|
|
173
|
+
fields: EsFieldCapability[];
|
|
174
|
+
}> {
|
|
175
|
+
const dataView = await this.getDataView(dataViewId);
|
|
176
|
+
if (!refresh && Array.isArray(dataView.cachedFields) && dataView.cachedFields.length > 0) {
|
|
177
|
+
return { dataView, fields: dataView.cachedFields };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const fields = await this.inspectFieldsBySource(dataView.dataSourceKey, dataView.indexPattern);
|
|
181
|
+
const repo = this.app.db.getRepository(DATA_VIEWS_COLLECTION);
|
|
182
|
+
await repo.update({
|
|
183
|
+
filterByTk: dataView.id,
|
|
184
|
+
values: { cachedFields: fields },
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
return {
|
|
188
|
+
dataView: { ...dataView, cachedFields: fields },
|
|
189
|
+
fields,
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async upsertDataView(input: UpsertDataViewInput, userId?: ID): Promise<EsDataViewRecord> {
|
|
194
|
+
const title = input.title?.trim();
|
|
195
|
+
const dataSourceKey = input.dataSourceKey?.trim();
|
|
196
|
+
const indexPattern = input.indexPattern?.trim();
|
|
197
|
+
if (!title) throw new Error('Data view title is required');
|
|
198
|
+
if (!dataSourceKey) throw new Error('Elasticsearch dataSourceKey is required');
|
|
199
|
+
if (!indexPattern) throw new Error('Index pattern is required');
|
|
200
|
+
|
|
201
|
+
const fields = await this.inspectFieldsBySource(dataSourceKey, indexPattern);
|
|
202
|
+
let timeField = input.timeField?.trim() || null;
|
|
203
|
+
if (!timeField) {
|
|
204
|
+
const autoDate =
|
|
205
|
+
fields.find((f) => f.name === '@timestamp' && (f.type === 'date' || f.type === 'date_nanos')) ??
|
|
206
|
+
fields.find((f) => f.type === 'date' || f.type === 'date_nanos');
|
|
207
|
+
timeField = autoDate?.name ?? null;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const repo = this.app.db.getRepository(DATA_VIEWS_COLLECTION);
|
|
211
|
+
const values: Record<string, unknown> = {
|
|
212
|
+
title,
|
|
213
|
+
dataSourceKey,
|
|
214
|
+
indexPattern,
|
|
215
|
+
timeField,
|
|
216
|
+
description: input.description ?? null,
|
|
217
|
+
cachedFields: fields,
|
|
218
|
+
...(input.allowedRoles !== undefined ? { allowedRoles: normalizeRoleList(input.allowedRoles) } : {}),
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
if (input.id !== undefined && input.id !== null && String(input.id).trim() !== '') {
|
|
222
|
+
await repo.update({
|
|
223
|
+
filterByTk: input.id,
|
|
224
|
+
values,
|
|
225
|
+
});
|
|
226
|
+
return this.getDataView(input.id);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
if (values.allowedRoles === undefined) {
|
|
230
|
+
values.allowedRoles = [];
|
|
231
|
+
}
|
|
232
|
+
if (userId !== undefined) {
|
|
233
|
+
values.createdById = userId;
|
|
234
|
+
}
|
|
235
|
+
const created = await repo.create({ values });
|
|
236
|
+
return serializeDataView(created);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
async listReports(options?: { publishedOnly?: boolean; search?: string }): Promise<EsReportRecord[]> {
|
|
240
|
+
const repo = this.app.db.getRepository(REPORTS_COLLECTION);
|
|
241
|
+
const filter: Record<string, unknown> = {};
|
|
242
|
+
if (options?.publishedOnly) {
|
|
243
|
+
filter.published = true;
|
|
244
|
+
}
|
|
245
|
+
if (options?.search?.trim()) {
|
|
246
|
+
filter.title = { $includes: options.search.trim() };
|
|
247
|
+
}
|
|
248
|
+
const rows = await repo.find({
|
|
249
|
+
filter,
|
|
250
|
+
appends: ['dataView'],
|
|
251
|
+
sort: ['-updatedAt', '-id'],
|
|
252
|
+
});
|
|
253
|
+
return rows.map(serializeReport);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
async findReport(reportId: ID, transaction?: Transaction): Promise<EsReportRecord | null> {
|
|
257
|
+
const repo = this.app.db.getRepository(REPORTS_COLLECTION);
|
|
258
|
+
const row = await repo.findOne({
|
|
259
|
+
filterByTk: reportId,
|
|
260
|
+
appends: ['dataView'],
|
|
261
|
+
transaction,
|
|
262
|
+
});
|
|
263
|
+
return row ? serializeReport(row) : null;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async getReport(reportId: ID): Promise<EsReportRecord> {
|
|
267
|
+
const report = await this.findReport(reportId);
|
|
268
|
+
if (!report) {
|
|
269
|
+
throw new Error(`Report "${String(reportId)}" was not found`);
|
|
270
|
+
}
|
|
271
|
+
return report;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
async saveReport(input: SaveReportInput, userId?: ID): Promise<EsReportRecord> {
|
|
275
|
+
const title = input.title?.trim();
|
|
276
|
+
if (!title) {
|
|
277
|
+
throw new Error('Report title is required');
|
|
278
|
+
}
|
|
279
|
+
const dataView = await this.getDataView(input.dataViewId);
|
|
280
|
+
const spec = normalizeReportSpec(input.spec);
|
|
281
|
+
if (spec.queryMode !== 'simple' && spec.query && spec.query.trim()) {
|
|
282
|
+
compileKqlToQueryDsl(spec.query);
|
|
283
|
+
}
|
|
284
|
+
const repo = this.app.db.getRepository(REPORTS_COLLECTION);
|
|
285
|
+
|
|
286
|
+
const values: Record<string, unknown> = {
|
|
287
|
+
title,
|
|
288
|
+
...(input.description !== undefined ? { description: input.description } : {}),
|
|
289
|
+
dataViewId: dataView.id,
|
|
290
|
+
visualization: spec.visualization,
|
|
291
|
+
spec,
|
|
292
|
+
...(input.published !== undefined ? { published: input.published } : {}),
|
|
293
|
+
...(input.allowedRoles !== undefined ? { allowedRoles: normalizeRoleList(input.allowedRoles) } : {}),
|
|
294
|
+
...(userId !== undefined ? { updatedById: userId } : {}),
|
|
295
|
+
};
|
|
296
|
+
|
|
297
|
+
if (input.id !== undefined && input.id !== null && String(input.id).trim() !== '') {
|
|
298
|
+
await repo.update({
|
|
299
|
+
filterByTk: input.id,
|
|
300
|
+
values,
|
|
301
|
+
});
|
|
302
|
+
return this.getReport(input.id);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
values.published ??= true;
|
|
306
|
+
if (values.allowedRoles === undefined) {
|
|
307
|
+
values.allowedRoles = [];
|
|
308
|
+
}
|
|
309
|
+
if (userId !== undefined) {
|
|
310
|
+
values.createdById = userId;
|
|
311
|
+
}
|
|
312
|
+
const created = await repo.create({ values });
|
|
313
|
+
const plain = toPlainObject(created);
|
|
314
|
+
return this.getReport(plain.id as ID);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
async previewReport(params: {
|
|
318
|
+
dataViewId: ID;
|
|
319
|
+
spec: unknown;
|
|
320
|
+
overrides?: ReportRuntimeOverrides;
|
|
321
|
+
forMcp?: boolean;
|
|
322
|
+
userContext?: ServerUserTokenContext;
|
|
323
|
+
}): Promise<{
|
|
324
|
+
dataView: EsDataViewRecord;
|
|
325
|
+
result: ReportExecutionResult;
|
|
326
|
+
}> {
|
|
327
|
+
const { dataView, fields } = await this.inspectDataViewFields(params.dataViewId, false);
|
|
328
|
+
const normalizedSpec = normalizeReportSpec(params.spec);
|
|
329
|
+
const client = await this.connections.getClient(dataView.dataSourceKey);
|
|
330
|
+
|
|
331
|
+
let activePitId = params.overrides?.pitId;
|
|
332
|
+
const needsDeepCursor =
|
|
333
|
+
normalizedSpec.visualization === 'table' &&
|
|
334
|
+
!activePitId &&
|
|
335
|
+
((params.overrides?.page ?? 1) * (params.overrides?.pageSize ?? normalizedSpec.pageSize ?? 20) > 10000 ||
|
|
336
|
+
Boolean(params.overrides?.searchAfter));
|
|
337
|
+
|
|
338
|
+
if (needsDeepCursor && !params.overrides?.searchAfter) {
|
|
339
|
+
activePitId = (await client.openPit(dataView.indexPattern, '1m')) ?? undefined;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const { body, effectiveSpec } = compileSearchRequest({
|
|
343
|
+
spec: normalizedSpec,
|
|
344
|
+
overrides: params.overrides,
|
|
345
|
+
timeField: dataView.timeField,
|
|
346
|
+
fields,
|
|
347
|
+
maxRowsCap: params.forMcp ? MAX_MCP_PREVIEW_SIZE : MAX_UI_PAGE_SIZE,
|
|
348
|
+
userContext: params.userContext,
|
|
349
|
+
usePit: Boolean(activePitId),
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
const rawSearch = await client.search(
|
|
353
|
+
dataView.indexPattern,
|
|
354
|
+
body,
|
|
355
|
+
activePitId ? { pitId: activePitId } : undefined,
|
|
356
|
+
);
|
|
357
|
+
const result = parseSearchResponse(rawSearch, body, effectiveSpec, dataView.timeField);
|
|
358
|
+
if (activePitId && !result.pitId) {
|
|
359
|
+
result.pitId = activePitId;
|
|
360
|
+
}
|
|
361
|
+
return { dataView, result };
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
async runSavedReport(params: {
|
|
365
|
+
reportId: ID;
|
|
366
|
+
overrides?: ReportRuntimeOverrides;
|
|
367
|
+
requirePublished?: boolean;
|
|
368
|
+
forMcp?: boolean;
|
|
369
|
+
userContext?: ServerUserTokenContext;
|
|
370
|
+
}): Promise<{
|
|
371
|
+
report: EsReportRecord;
|
|
372
|
+
dataView: EsDataViewRecord;
|
|
373
|
+
result: ReportExecutionResult;
|
|
374
|
+
}> {
|
|
375
|
+
const report = await this.getReport(params.reportId);
|
|
376
|
+
if (params.requirePublished && !report.published) {
|
|
377
|
+
throw new Error(`Report "${report.title}" is not published`);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
const runtimeOverrides: ReportRuntimeOverrides | undefined =
|
|
381
|
+
report.spec.allowInteractiveControls === false
|
|
382
|
+
? {
|
|
383
|
+
contextFilters: params.overrides?.contextFilters,
|
|
384
|
+
sharedFilters: params.overrides?.sharedFilters,
|
|
385
|
+
timeZone: params.overrides?.timeZone,
|
|
386
|
+
page: params.overrides?.page,
|
|
387
|
+
pageSize: params.overrides?.pageSize,
|
|
388
|
+
searchAfter: params.overrides?.searchAfter,
|
|
389
|
+
pitId: params.overrides?.pitId,
|
|
390
|
+
}
|
|
391
|
+
: params.overrides;
|
|
392
|
+
|
|
393
|
+
const { dataView, result } = await this.previewReport({
|
|
394
|
+
dataViewId: report.dataViewId,
|
|
395
|
+
spec: report.spec,
|
|
396
|
+
overrides: runtimeOverrides,
|
|
397
|
+
forMcp: params.forMcp,
|
|
398
|
+
userContext: params.userContext,
|
|
399
|
+
});
|
|
400
|
+
|
|
401
|
+
return { report, dataView, result };
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
async inspectFieldTopValues(params: {
|
|
405
|
+
dataViewId: ID;
|
|
406
|
+
reportId?: ID;
|
|
407
|
+
field: string;
|
|
408
|
+
size?: number;
|
|
409
|
+
overrides?: ReportRuntimeOverrides;
|
|
410
|
+
userContext?: ServerUserTokenContext;
|
|
411
|
+
}): Promise<FieldTopValuesResult> {
|
|
412
|
+
const rawField = params.field.trim();
|
|
413
|
+
if (!rawField) {
|
|
414
|
+
throw new Error('field is required');
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
let baseSpec = normalizeReportSpec({ visualization: 'bar' });
|
|
418
|
+
let targetDataViewId = params.dataViewId;
|
|
419
|
+
if (params.reportId !== undefined && params.reportId !== null && String(params.reportId).trim() !== '') {
|
|
420
|
+
const report = await this.getReport(params.reportId);
|
|
421
|
+
targetDataViewId = report.dataViewId;
|
|
422
|
+
baseSpec = report.spec;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
const { dataView, fields } = await this.inspectDataViewFields(targetDataViewId, false);
|
|
426
|
+
const fieldMap = buildFieldCapabilityMap(fields);
|
|
427
|
+
const resolvedField = resolveAggregatableField(rawField, fieldMap);
|
|
428
|
+
const topSize = Math.max(1, Math.min(25, Math.trunc(params.size ?? 10)));
|
|
429
|
+
|
|
430
|
+
const probeSpec = normalizeReportSpec({
|
|
431
|
+
...baseSpec,
|
|
432
|
+
visualization: 'bar',
|
|
433
|
+
chart: {
|
|
434
|
+
bucketType: 'terms',
|
|
435
|
+
bucketField: resolvedField,
|
|
436
|
+
topN: topSize,
|
|
437
|
+
metricType: 'count',
|
|
438
|
+
},
|
|
439
|
+
});
|
|
440
|
+
|
|
441
|
+
const { body, effectiveSpec } = compileSearchRequest({
|
|
442
|
+
spec: probeSpec,
|
|
443
|
+
overrides: params.overrides,
|
|
444
|
+
timeField: dataView.timeField,
|
|
445
|
+
fields,
|
|
446
|
+
userContext: params.userContext,
|
|
447
|
+
});
|
|
448
|
+
|
|
449
|
+
const client = await this.connections.getClient(dataView.dataSourceKey);
|
|
450
|
+
const rawSearch = await client.search(dataView.indexPattern, body);
|
|
451
|
+
const parsed = parseSearchResponse(rawSearch, body, effectiveSpec, dataView.timeField);
|
|
452
|
+
const totalDocs = parsed.total;
|
|
453
|
+
|
|
454
|
+
return {
|
|
455
|
+
field: rawField,
|
|
456
|
+
resolvedField,
|
|
457
|
+
totalDocs,
|
|
458
|
+
buckets: parsed.series.map((pt) => ({
|
|
459
|
+
value: pt.label,
|
|
460
|
+
count: pt.count,
|
|
461
|
+
percentage: totalDocs > 0 ? Number(((pt.count / totalDocs) * 100).toFixed(1)) : 0,
|
|
462
|
+
})),
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
export function extractCurrentUserId(ctx?: Partial<Context>): ID | undefined {
|
|
468
|
+
const stateUser = (ctx?.state as { currentUser?: { id?: ID } } | undefined)?.currentUser?.id;
|
|
469
|
+
if (stateUser !== undefined && stateUser !== null) return stateUser;
|
|
470
|
+
const authUser = (ctx?.auth as { user?: { id?: ID } } | undefined)?.user?.id;
|
|
471
|
+
if (authUser !== undefined && authUser !== null) return authUser;
|
|
472
|
+
return undefined;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
export function extractServerUserContext(ctx?: Partial<Context>): ServerUserTokenContext {
|
|
476
|
+
const stateUser = (
|
|
477
|
+
ctx?.state as
|
|
478
|
+
| {
|
|
479
|
+
currentUser?: {
|
|
480
|
+
id?: ID;
|
|
481
|
+
username?: string;
|
|
482
|
+
email?: string;
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
| undefined
|
|
486
|
+
)?.currentUser;
|
|
487
|
+
const effectiveRole = getEffectiveRoles(ctx)[0];
|
|
488
|
+
return {
|
|
489
|
+
userId: extractCurrentUserId(ctx),
|
|
490
|
+
...(typeof stateUser?.username === 'string' ? { username: stateUser.username } : {}),
|
|
491
|
+
...(typeof stateUser?.email === 'string' ? { email: stateUser.email } : {}),
|
|
492
|
+
...(effectiveRole ? { role: effectiveRole } : {}),
|
|
493
|
+
};
|
|
494
|
+
}
|