plugin-document-understanding 1.1.16 → 2.0.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/LICENSE +201 -0
- package/README.md +19 -25
- package/dist/client/169.6888909107c553c3.js +10 -0
- package/dist/client/379.e29f5ced467ce23d.js +10 -0
- package/dist/client/867.3ed3b814115181ca.js +10 -0
- package/dist/client/index.js +1 -1
- package/dist/client-v2/169.53bf1be2ec192f0c.js +10 -0
- package/dist/client-v2/379.e75c4829567cdb89.js +10 -0
- package/dist/client-v2/867.66d7291e95f1de78.js +10 -0
- package/dist/client-v2/index.js +1 -1
- package/dist/externalVersion.js +9 -7
- package/dist/locale/en-US.json +126 -0
- package/dist/locale/vi-VN.json +130 -2
- package/dist/locale/zh-CN.json +127 -1
- package/dist/node_modules/form-data/package.json +1 -1
- package/dist/node_modules/mime-types/package.json +1 -1
- package/dist/server/actions.js +211 -11
- package/dist/server/collections/api-keys.js +55 -0
- package/dist/server/collections/artifacts.js +59 -0
- package/dist/server/collections/config.js +9 -3
- package/dist/server/collections/endpoints.js +3 -0
- package/dist/server/collections/jobs.js +7 -4
- package/dist/server/collections/operations.js +76 -0
- package/dist/server/contracts/du-contracts.js +828 -0
- package/dist/server/dugate-seed.js +98 -340
- package/dist/server/plugin.js +49 -7
- package/dist/server/routes/du-gateway-router.js +443 -0
- package/dist/server/services/ArtifactStorageService.js +459 -0
- package/dist/server/services/AsyncJobManager.js +1 -1
- package/dist/server/services/BuiltinBusinessEngine.js +1223 -0
- package/dist/server/services/DocumentUnderstandingService.js +151 -25
- package/dist/server/services/ExternalDuReworkClient.js +210 -0
- package/dist/server/services/OperationOrchestrator.js +1087 -0
- package/dist/server/services/PipelineExecutor.js +164 -43
- package/dist/server/tools/document-understanding-tool.js +49 -24
- package/dist/server/workflow/DocumentUnderstandingInstruction.js +292 -0
- package/package.json +8 -4
- package/src/client/index.tsx +11 -0
- package/src/client-v2/components/ApiKeysTab.tsx +198 -0
- package/src/client-v2/components/EndpointsTab.tsx +39 -2
- package/src/client-v2/components/JobsTab.tsx +136 -21
- package/src/client-v2/components/OperationsTab.tsx +586 -0
- package/src/client-v2/components/PluginSettings.tsx +12 -0
- package/src/client-v2/components/ServiceConfigTab.tsx +225 -65
- package/src/client-v2/components/__tests__/PluginSettings.test.tsx +4 -0
- package/src/client-v2/locale.ts +1 -8
- package/src/client-v2/models/index.ts +1 -8
- package/src/client-v2/plugin.tsx +12 -8
- package/src/client-v2/types.ts +13 -1
- package/src/client-v2/workflow/DocumentUnderstandingFieldset.tsx +122 -0
- package/src/client-v2/workflow/DocumentUnderstandingInstruction.tsx +49 -0
- package/src/locale/en-US.json +126 -0
- package/src/locale/vi-VN.json +130 -2
- package/src/locale/zh-CN.json +127 -1
- package/src/server/__tests__/actions.test.ts +1 -8
- package/src/server/__tests__/du-rework-gateway.test.ts +462 -0
- package/src/server/__tests__/dugate-integration.test.ts +79 -42
- package/src/server/__tests__/smoke.test.ts +1 -8
- package/src/server/__tests__/upload-security.test.ts +1 -8
- package/src/server/actions.ts +252 -36
- package/src/server/collections/api-keys.ts +35 -0
- package/src/server/collections/artifacts.ts +39 -0
- package/src/server/collections/config.ts +18 -2
- package/src/server/collections/endpoints.ts +12 -0
- package/src/server/collections/jobs.ts +16 -4
- package/src/server/collections/operations.ts +56 -0
- package/src/server/contracts/du-contracts.ts +1026 -0
- package/src/server/dugate-seed.ts +126 -453
- package/src/server/plugin.ts +64 -14
- package/src/server/routes/du-gateway-router.ts +465 -0
- package/src/server/services/ArtifactStorageService.ts +596 -0
- package/src/server/services/AsyncJobManager.ts +10 -1
- package/src/server/services/BuiltinBusinessEngine.ts +1544 -0
- package/src/server/services/DocumentUnderstandingService.ts +186 -44
- package/src/server/services/ExternalDuReworkClient.ts +222 -0
- package/src/server/services/OperationOrchestrator.ts +1359 -0
- package/src/server/services/PipelineExecutor.ts +245 -108
- package/src/server/tools/document-understanding-tool.ts +63 -45
- package/src/server/types.ts +101 -16
- package/src/server/workflow/DocumentUnderstandingInstruction.ts +308 -0
- package/dist/client/345.277fbb2b97424db5.js +0 -10
- package/dist/client-v2/345.2fa9834b46dd4531.js +0 -10
|
@@ -1,9 +1,12 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
1
3
|
import { existsSync, realpathSync, readFileSync, statSync } from 'fs';
|
|
2
4
|
import { basename, resolve, sep } from 'path';
|
|
3
|
-
import { Database } from '@nocobase/database';
|
|
5
|
+
import type { Database } from '@nocobase/database';
|
|
4
6
|
import mime from 'mime-types';
|
|
5
7
|
import { ExternalApiClient, FileInput } from './ExternalApiClient';
|
|
6
8
|
import { AsyncJobManager, JOB_RUN_LEASE_MS, pollLeaseMs } from './AsyncJobManager';
|
|
9
|
+
import type { OperationOrchestrator } from './OperationOrchestrator';
|
|
7
10
|
import { PipelineDef, PipelineStepDef, JobState, EndpointDef } from '../types';
|
|
8
11
|
|
|
9
12
|
interface LoggerLike {
|
|
@@ -22,20 +25,22 @@ const UPLOAD_ROOTS = [resolve(process.cwd(), 'storage', 'uploads')];
|
|
|
22
25
|
const isInsidePath = (basePath: string, targetPath: string) =>
|
|
23
26
|
targetPath === basePath || targetPath.startsWith(`${basePath}${sep}`);
|
|
24
27
|
|
|
28
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
29
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
30
|
+
}
|
|
31
|
+
|
|
25
32
|
/**
|
|
26
|
-
* Extract a task ID from a
|
|
33
|
+
* Extract a task/operation ID from a 202 Accepted response.
|
|
27
34
|
* Priority:
|
|
28
|
-
* 1. `taskIdExtractPath` + optional `taskIdExtractRegex` (e.g. path="name", regex="operations/([^/]+)")
|
|
35
|
+
* 1. `taskIdExtractPath` + optional `taskIdExtractRegex` (e.g. path="operationId" or path="name", regex="operations/([^/]+)")
|
|
29
36
|
* 2. `pollTaskIdField` (default "task_id")
|
|
30
|
-
* 3.
|
|
37
|
+
* 3. `operationId` field fallback
|
|
38
|
+
* 4. Raw response body as string fallback
|
|
31
39
|
*/
|
|
32
|
-
function extractTaskId(responseData:
|
|
33
|
-
// 1. taskIdExtractPath: navigate to a field, then optionally apply regex
|
|
40
|
+
function extractTaskId(responseData: unknown, endpoint: EndpointDef): string | null {
|
|
34
41
|
const extractPath = endpoint.taskIdExtractPath?.trim();
|
|
35
|
-
if (extractPath) {
|
|
36
|
-
const raw = extractPath
|
|
37
|
-
.split('.')
|
|
38
|
-
.reduce((acc: any, k: string) => (acc != null ? acc[k] : undefined), responseData);
|
|
42
|
+
if (extractPath && isRecord(responseData)) {
|
|
43
|
+
const raw = extractPath.split('.').reduce<unknown>((acc, k) => (isRecord(acc) ? acc[k] : undefined), responseData);
|
|
39
44
|
if (raw != null) {
|
|
40
45
|
const regex = endpoint.taskIdExtractRegex?.trim();
|
|
41
46
|
if (regex) {
|
|
@@ -50,12 +55,13 @@ function extractTaskId(responseData: any, endpoint: EndpointDef): string | null
|
|
|
50
55
|
}
|
|
51
56
|
}
|
|
52
57
|
|
|
53
|
-
// 2. pollTaskIdField (default "task_id")
|
|
54
58
|
const idField = endpoint.pollTaskIdField || 'task_id';
|
|
55
|
-
|
|
56
|
-
|
|
59
|
+
if (isRecord(responseData)) {
|
|
60
|
+
const fieldVal = idField.split('.').reduce<unknown>((acc, k) => (isRecord(acc) ? acc[k] : undefined), responseData);
|
|
61
|
+
if (fieldVal != null) return String(fieldVal);
|
|
62
|
+
if (typeof responseData.operationId === 'string') return responseData.operationId;
|
|
63
|
+
}
|
|
57
64
|
|
|
58
|
-
// 3. Raw string fallback
|
|
59
65
|
if (typeof responseData === 'string') return responseData;
|
|
60
66
|
if (typeof responseData === 'number') return String(responseData);
|
|
61
67
|
|
|
@@ -103,10 +109,12 @@ export function resolveUploadFilePath(urlOrPath: string): string | null {
|
|
|
103
109
|
}
|
|
104
110
|
|
|
105
111
|
export interface ExecutionContext {
|
|
106
|
-
input: Record<string,
|
|
112
|
+
input: Record<string, unknown>;
|
|
107
113
|
files: FileInput[];
|
|
108
|
-
|
|
114
|
+
artifactIds?: string[];
|
|
115
|
+
stepResults: Record<string, unknown>;
|
|
109
116
|
jobId: number;
|
|
117
|
+
userId?: number;
|
|
110
118
|
}
|
|
111
119
|
|
|
112
120
|
export class PipelineExecutor {
|
|
@@ -115,6 +123,7 @@ export class PipelineExecutor {
|
|
|
115
123
|
private jobManager: AsyncJobManager;
|
|
116
124
|
private logger: LoggerLike;
|
|
117
125
|
private nodeId: string;
|
|
126
|
+
private orchestrator?: OperationOrchestrator;
|
|
118
127
|
|
|
119
128
|
constructor(
|
|
120
129
|
db: Database,
|
|
@@ -122,12 +131,14 @@ export class PipelineExecutor {
|
|
|
122
131
|
jobManager: AsyncJobManager,
|
|
123
132
|
logger: LoggerLike,
|
|
124
133
|
nodeId = '',
|
|
134
|
+
orchestrator?: OperationOrchestrator,
|
|
125
135
|
) {
|
|
126
136
|
this.db = db;
|
|
127
137
|
this.apiClient = apiClient;
|
|
128
138
|
this.jobManager = jobManager;
|
|
129
139
|
this.logger = logger;
|
|
130
140
|
this.nodeId = nodeId;
|
|
141
|
+
this.orchestrator = orchestrator;
|
|
131
142
|
}
|
|
132
143
|
|
|
133
144
|
private async resolveFile(urlOrPath: string, fieldName = 'file'): Promise<FileInput | null> {
|
|
@@ -143,7 +154,7 @@ export class PipelineExecutor {
|
|
|
143
154
|
fieldName,
|
|
144
155
|
buffer,
|
|
145
156
|
filename: basename(localPath),
|
|
146
|
-
mimeType,
|
|
157
|
+
mimeType: String(mimeType),
|
|
147
158
|
};
|
|
148
159
|
}
|
|
149
160
|
|
|
@@ -162,12 +173,12 @@ export class PipelineExecutor {
|
|
|
162
173
|
|
|
163
174
|
async execute(
|
|
164
175
|
pipelineId: number,
|
|
165
|
-
input: Record<string,
|
|
176
|
+
input: Record<string, unknown>,
|
|
166
177
|
files: FileInput[] = [],
|
|
167
178
|
userId?: number,
|
|
168
179
|
): Promise<JobState> {
|
|
169
|
-
const pipelineRepo = this.db.getRepository
|
|
170
|
-
const jobsRepo = this.db.getRepository
|
|
180
|
+
const pipelineRepo = this.db.getRepository('doc_understanding_pipelines');
|
|
181
|
+
const jobsRepo = this.db.getRepository('doc_understanding_jobs');
|
|
171
182
|
|
|
172
183
|
const pipeline = await pipelineRepo.findOne({
|
|
173
184
|
filter: { id: pipelineId },
|
|
@@ -177,13 +188,12 @@ export class PipelineExecutor {
|
|
|
177
188
|
if (!pipeline) throw new Error(`Pipeline ${pipelineId} not found`);
|
|
178
189
|
if (!pipeline.enabled) throw new Error(`Pipeline ${pipelineId} is disabled`);
|
|
179
190
|
|
|
180
|
-
|
|
181
|
-
const job = await jobsRepo.create({
|
|
191
|
+
const job = (await jobsRepo.create({
|
|
182
192
|
values: {
|
|
183
193
|
pipelineId,
|
|
184
194
|
status: 'pending',
|
|
185
195
|
input,
|
|
186
|
-
currentStep: 1,
|
|
196
|
+
currentStep: 1,
|
|
187
197
|
stepResults: {},
|
|
188
198
|
externalTaskIds: {},
|
|
189
199
|
startedAt: new Date(),
|
|
@@ -191,7 +201,7 @@ export class PipelineExecutor {
|
|
|
191
201
|
ownedBy: this.nodeId,
|
|
192
202
|
leaseExpiresAt: new Date(Date.now() + JOB_RUN_LEASE_MS),
|
|
193
203
|
},
|
|
194
|
-
});
|
|
204
|
+
})) as unknown as JobState;
|
|
195
205
|
|
|
196
206
|
const resolvedFiles: FileInput[] = [];
|
|
197
207
|
|
|
@@ -202,7 +212,6 @@ export class PipelineExecutor {
|
|
|
202
212
|
}
|
|
203
213
|
};
|
|
204
214
|
|
|
205
|
-
// 1. Process files argument
|
|
206
215
|
if (Array.isArray(files)) {
|
|
207
216
|
for (const f of files) {
|
|
208
217
|
if (f && typeof f === 'object') {
|
|
@@ -216,7 +225,6 @@ export class PipelineExecutor {
|
|
|
216
225
|
}
|
|
217
226
|
}
|
|
218
227
|
|
|
219
|
-
// 2. Scan input for common file URL keys
|
|
220
228
|
const urlFields = ['file_url', 'file_urls', 'file', 'files'];
|
|
221
229
|
for (const key of urlFields) {
|
|
222
230
|
const val = input[key];
|
|
@@ -227,13 +235,20 @@ export class PipelineExecutor {
|
|
|
227
235
|
val.startsWith('http://') ||
|
|
228
236
|
val.startsWith('https://') ||
|
|
229
237
|
val.startsWith('/') ||
|
|
230
|
-
val.startsWith('storage/')
|
|
238
|
+
val.startsWith('storage/') ||
|
|
239
|
+
val.startsWith('uploads/')
|
|
231
240
|
) {
|
|
232
241
|
await tryAddFile(val, 'file');
|
|
233
242
|
} else if (val.includes(',')) {
|
|
234
243
|
const urls = val.split(',').map((s) => s.trim());
|
|
235
244
|
for (const u of urls) {
|
|
236
|
-
if (
|
|
245
|
+
if (
|
|
246
|
+
u.startsWith('http://') ||
|
|
247
|
+
u.startsWith('https://') ||
|
|
248
|
+
u.startsWith('/') ||
|
|
249
|
+
u.startsWith('storage/') ||
|
|
250
|
+
u.startsWith('uploads/')
|
|
251
|
+
) {
|
|
237
252
|
await tryAddFile(u, 'file');
|
|
238
253
|
}
|
|
239
254
|
}
|
|
@@ -245,15 +260,16 @@ export class PipelineExecutor {
|
|
|
245
260
|
item.startsWith('http://') ||
|
|
246
261
|
item.startsWith('https://') ||
|
|
247
262
|
item.startsWith('/') ||
|
|
248
|
-
item.startsWith('storage/')
|
|
263
|
+
item.startsWith('storage/') ||
|
|
264
|
+
item.startsWith('uploads/')
|
|
249
265
|
) {
|
|
250
266
|
await tryAddFile(item, 'file');
|
|
251
267
|
}
|
|
252
|
-
} else if (item && typeof item === '
|
|
268
|
+
} else if (isRecord(item) && typeof item.url === 'string') {
|
|
253
269
|
await tryAddFile(item.url, 'file');
|
|
254
270
|
}
|
|
255
271
|
}
|
|
256
|
-
} else if (val && typeof val === '
|
|
272
|
+
} else if (isRecord(val) && typeof val.url === 'string') {
|
|
257
273
|
await tryAddFile(val.url, 'file');
|
|
258
274
|
}
|
|
259
275
|
}
|
|
@@ -271,12 +287,12 @@ export class PipelineExecutor {
|
|
|
271
287
|
files: resolvedFiles,
|
|
272
288
|
stepResults: {},
|
|
273
289
|
jobId: job.id,
|
|
290
|
+
userId,
|
|
274
291
|
};
|
|
275
292
|
|
|
276
|
-
|
|
277
|
-
const steps = [...
|
|
293
|
+
const rawSteps = (pipeline as unknown as PipelineDef).steps || [];
|
|
294
|
+
const steps = [...rawSteps].sort((a, b) => a.stepOrder - b.stepOrder);
|
|
278
295
|
|
|
279
|
-
// Run steps (Synchronous part)
|
|
280
296
|
this.runSteps(job, steps, context).catch((err) => {
|
|
281
297
|
this.logger.error(`Background pipeline error for job ${job.id}`, err);
|
|
282
298
|
});
|
|
@@ -284,8 +300,126 @@ export class PipelineExecutor {
|
|
|
284
300
|
return job;
|
|
285
301
|
}
|
|
286
302
|
|
|
303
|
+
private async ensureArtifactsForContext(context: ExecutionContext): Promise<string[]> {
|
|
304
|
+
if (context.artifactIds) return context.artifactIds;
|
|
305
|
+
const ids: string[] = [];
|
|
306
|
+
if (Array.isArray(context.input.artifactIds)) {
|
|
307
|
+
for (const id of context.input.artifactIds) {
|
|
308
|
+
if (typeof id === 'string' && id.trim()) ids.push(id.trim());
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
if (this.orchestrator && context.files.length > 0) {
|
|
312
|
+
for (const file of context.files) {
|
|
313
|
+
const created = await this.orchestrator.artifactStorage.createReadyArtifactFromBuffer({
|
|
314
|
+
tenantId: 'default',
|
|
315
|
+
fileName: file.filename,
|
|
316
|
+
mimeType: file.mimeType,
|
|
317
|
+
buffer: file.buffer,
|
|
318
|
+
userId: context.userId,
|
|
319
|
+
});
|
|
320
|
+
ids.push(created.artifactId);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
context.artifactIds = ids;
|
|
324
|
+
return ids;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
private isCanonicalEndpoint(endpoint: EndpointDef): boolean {
|
|
328
|
+
if (!this.orchestrator) return false;
|
|
329
|
+
return (
|
|
330
|
+
endpoint.protocolMode === 'builtin_du' ||
|
|
331
|
+
endpoint.protocolMode === 'du_rework_v1' ||
|
|
332
|
+
Boolean(endpoint.businessId && endpoint.actionName)
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
private async executeCanonicalStep(
|
|
337
|
+
job: JobState,
|
|
338
|
+
step: PipelineStepDef,
|
|
339
|
+
mappedBody: Record<string, unknown>,
|
|
340
|
+
context: ExecutionContext,
|
|
341
|
+
): Promise<{ halted: boolean; responsePayload?: Record<string, unknown> }> {
|
|
342
|
+
if (!this.orchestrator) {
|
|
343
|
+
throw new Error('OperationOrchestrator is not attached');
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
const endpoint = step.endpoint;
|
|
347
|
+
const businessId = endpoint.businessId || 'document-core';
|
|
348
|
+
const action = endpoint.actionName || 'ingest';
|
|
349
|
+
const stepInput: Record<string, unknown> = {};
|
|
350
|
+
for (const [k, v] of Object.entries(mappedBody || {})) {
|
|
351
|
+
if (v !== undefined) stepInput[k] = v;
|
|
352
|
+
}
|
|
353
|
+
if (endpoint.discriminatorField && endpoint.discriminatorValue) {
|
|
354
|
+
stepInput[endpoint.discriminatorField] = endpoint.discriminatorValue;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
const artifactIds = await this.ensureArtifactsForContext(context);
|
|
358
|
+
const submitted = await this.orchestrator.submitOperation({
|
|
359
|
+
principal: {
|
|
360
|
+
kind: 'nocobase_user',
|
|
361
|
+
tenantId: 'default',
|
|
362
|
+
userId: context.userId,
|
|
363
|
+
allowedBusinesses: ['*'],
|
|
364
|
+
allowedActions: ['*'],
|
|
365
|
+
},
|
|
366
|
+
businessId,
|
|
367
|
+
action,
|
|
368
|
+
submission: {
|
|
369
|
+
input: stepInput,
|
|
370
|
+
artifacts: artifactIds.map((artifactId) => ({ artifactId, role: 'input' })),
|
|
371
|
+
documentSelection: isRecord(context.input.documentSelection)
|
|
372
|
+
? (context.input.documentSelection as never)
|
|
373
|
+
: undefined,
|
|
374
|
+
},
|
|
375
|
+
waitCompletionMs: endpoint.pollTimeout || 120_000,
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
const opRecord = await this.orchestrator.getOperationRecordOrThrow('default', submitted.operationId);
|
|
379
|
+
const jobsRepo = this.db.getRepository('doc_understanding_jobs');
|
|
380
|
+
|
|
381
|
+
if (opRecord.state === 'WAITING_INPUT') {
|
|
382
|
+
const externalTaskIds = { ...(job.externalTaskIds || {}), [String(step.stepOrder)]: opRecord.operationId };
|
|
383
|
+
await jobsRepo.update({
|
|
384
|
+
filterByTk: job.id,
|
|
385
|
+
values: {
|
|
386
|
+
status: 'waiting_input',
|
|
387
|
+
operationId: opRecord.operationId,
|
|
388
|
+
waitState: opRecord.waitState,
|
|
389
|
+
usage: opRecord.usage,
|
|
390
|
+
externalTaskIds,
|
|
391
|
+
leaseExpiresAt: null,
|
|
392
|
+
},
|
|
393
|
+
});
|
|
394
|
+
return { halted: true };
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
if (opRecord.state !== 'SUCCEEDED') {
|
|
398
|
+
throw new Error(
|
|
399
|
+
opRecord.errorProblem?.detail || opRecord.errorProblem?.title || `Operation ended in state ${opRecord.state}`,
|
|
400
|
+
);
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
await jobsRepo.update({
|
|
404
|
+
filterByTk: job.id,
|
|
405
|
+
values: {
|
|
406
|
+
operationId: opRecord.operationId,
|
|
407
|
+
usage: opRecord.usage ?? null,
|
|
408
|
+
},
|
|
409
|
+
});
|
|
410
|
+
|
|
411
|
+
return {
|
|
412
|
+
halted: false,
|
|
413
|
+
responsePayload: {
|
|
414
|
+
...(opRecord.outputPayload || {}),
|
|
415
|
+
usage: opRecord.usage,
|
|
416
|
+
operationId: opRecord.operationId,
|
|
417
|
+
},
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
|
|
287
421
|
private async runSteps(job: JobState, steps: PipelineStepDef[], context: ExecutionContext, startFromOrder = 1) {
|
|
288
|
-
const jobsRepo = this.db.getRepository
|
|
422
|
+
const jobsRepo = this.db.getRepository('doc_understanding_jobs');
|
|
289
423
|
let currentOrder = startFromOrder;
|
|
290
424
|
|
|
291
425
|
try {
|
|
@@ -306,7 +440,7 @@ export class PipelineExecutor {
|
|
|
306
440
|
});
|
|
307
441
|
|
|
308
442
|
if (!this.evaluateCondition(step.condition, context)) {
|
|
309
|
-
continue;
|
|
443
|
+
continue;
|
|
310
444
|
}
|
|
311
445
|
|
|
312
446
|
if (!step.endpoint?.enabled) {
|
|
@@ -319,10 +453,20 @@ export class PipelineExecutor {
|
|
|
319
453
|
: context.input;
|
|
320
454
|
let retries = step.onError === 'retry' ? step.retryCount || 0 : 0;
|
|
321
455
|
let success = false;
|
|
322
|
-
let lastError = null;
|
|
456
|
+
let lastError: Error | null = null;
|
|
323
457
|
|
|
324
458
|
while (retries >= 0 && !success) {
|
|
325
459
|
try {
|
|
460
|
+
if (this.isCanonicalEndpoint(step.endpoint)) {
|
|
461
|
+
const canonicalOutcome = await this.executeCanonicalStep(job, step, mappedBody, context);
|
|
462
|
+
if (canonicalOutcome.halted) {
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
context.stepResults[step.outputAlias || step.stepOrder.toString()] = canonicalOutcome.responsePayload;
|
|
466
|
+
success = true;
|
|
467
|
+
continue;
|
|
468
|
+
}
|
|
469
|
+
|
|
326
470
|
const fileFieldName = step.endpoint.fileFieldName || 'file';
|
|
327
471
|
const mappedFiles = context.files
|
|
328
472
|
? context.files.map((f) => ({
|
|
@@ -339,12 +483,7 @@ export class PipelineExecutor {
|
|
|
339
483
|
|
|
340
484
|
if (step.endpoint.executionMode === 'sync') {
|
|
341
485
|
const responseData = result.data;
|
|
342
|
-
|
|
343
|
-
// task id (pipeline/workflow jobs that never run synchronously). In
|
|
344
|
-
// that case we treat the endpoint as an async poll to completion.
|
|
345
|
-
const isAsyncAccepted =
|
|
346
|
-
result.status === 202 ||
|
|
347
|
-
(responseData && typeof responseData === 'object' && responseData.done === false);
|
|
486
|
+
const isAsyncAccepted = result.status === 202 || (isRecord(responseData) && responseData.done === false);
|
|
348
487
|
if (isAsyncAccepted) {
|
|
349
488
|
const taskId = extractTaskId(responseData, step.endpoint);
|
|
350
489
|
if (taskId) {
|
|
@@ -361,16 +500,13 @@ export class PipelineExecutor {
|
|
|
361
500
|
});
|
|
362
501
|
|
|
363
502
|
await this.jobManager.startPolling(job.id, step.endpoint, taskId);
|
|
364
|
-
return;
|
|
503
|
+
return;
|
|
365
504
|
}
|
|
366
|
-
// No task id: fall through and store the raw 202 body as the step result.
|
|
367
505
|
}
|
|
368
506
|
context.stepResults[step.outputAlias || step.stepOrder.toString()] = responseData;
|
|
369
507
|
success = true;
|
|
370
508
|
} else if (step.endpoint.executionMode === 'polling') {
|
|
371
|
-
// Extract taskId from result based on pollTaskIdField / taskIdExtractPath
|
|
372
509
|
const taskId = extractTaskId(result.data, step.endpoint);
|
|
373
|
-
|
|
374
510
|
if (!taskId) throw new Error('Polling taskId not found in response');
|
|
375
511
|
|
|
376
512
|
const externalTaskIds = job.externalTaskIds || {};
|
|
@@ -381,17 +517,13 @@ export class PipelineExecutor {
|
|
|
381
517
|
values: {
|
|
382
518
|
status: 'polling',
|
|
383
519
|
externalTaskIds,
|
|
384
|
-
// This node keeps polling and refreshes the lease on every tick.
|
|
385
520
|
leaseExpiresAt: new Date(Date.now() + pollLeaseMs(step.endpoint.pollInterval)),
|
|
386
521
|
},
|
|
387
522
|
});
|
|
388
523
|
|
|
389
524
|
await this.jobManager.startPolling(job.id, step.endpoint, taskId);
|
|
390
|
-
|
|
391
|
-
// Halt execution. Polling callback will resume from next step.
|
|
392
525
|
return;
|
|
393
526
|
} else if (step.endpoint.executionMode === 'webhook') {
|
|
394
|
-
// Wait for webhook
|
|
395
527
|
const taskId = extractTaskId(result.data, step.endpoint);
|
|
396
528
|
if (!taskId) throw new Error('Webhook taskId not found in response');
|
|
397
529
|
const externalTaskIds = job.externalTaskIds || {};
|
|
@@ -402,18 +534,14 @@ export class PipelineExecutor {
|
|
|
402
534
|
values: {
|
|
403
535
|
status: 'polling',
|
|
404
536
|
externalTaskIds,
|
|
405
|
-
// No process actively owns a webhook wait: the callback may arrive
|
|
406
|
-
// at any node, so there is no lease to renew.
|
|
407
537
|
leaseExpiresAt: null,
|
|
408
538
|
},
|
|
409
539
|
});
|
|
410
|
-
|
|
411
|
-
// End execution. Webhook will resume.
|
|
412
540
|
return;
|
|
413
541
|
}
|
|
414
|
-
} catch (err:
|
|
415
|
-
lastError = err;
|
|
416
|
-
retries
|
|
542
|
+
} catch (err: unknown) {
|
|
543
|
+
lastError = err instanceof Error ? err : new Error(String(err));
|
|
544
|
+
retries -= 1;
|
|
417
545
|
}
|
|
418
546
|
}
|
|
419
547
|
|
|
@@ -421,33 +549,43 @@ export class PipelineExecutor {
|
|
|
421
549
|
if (step.onError === 'fail') {
|
|
422
550
|
throw lastError || new Error(`Step ${step.name} failed`);
|
|
423
551
|
}
|
|
424
|
-
// if 'skip', we continue the loop
|
|
425
552
|
}
|
|
426
553
|
}
|
|
427
554
|
|
|
428
|
-
// If loop completes without being halted for async
|
|
429
555
|
await this.finishJob(job.id, context);
|
|
430
|
-
} catch (err:
|
|
556
|
+
} catch (err: unknown) {
|
|
557
|
+
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
431
558
|
await jobsRepo.update({
|
|
432
559
|
filterByTk: job.id,
|
|
433
|
-
values: { status: 'failed', error:
|
|
560
|
+
values: { status: 'failed', error: errorMessage, completedAt: new Date() },
|
|
434
561
|
});
|
|
435
562
|
}
|
|
436
563
|
}
|
|
437
564
|
|
|
438
|
-
async resumeFromStep(jobId: number, asyncResult:
|
|
439
|
-
const jobsRepo = this.db.getRepository
|
|
440
|
-
const pipelineRepo = this.db.getRepository
|
|
565
|
+
async resumeFromStep(jobId: number, asyncResult: unknown) {
|
|
566
|
+
const jobsRepo = this.db.getRepository('doc_understanding_jobs');
|
|
567
|
+
const pipelineRepo = this.db.getRepository('doc_understanding_pipelines');
|
|
441
568
|
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
569
|
+
interface LockedJobRow {
|
|
570
|
+
id: number;
|
|
571
|
+
get: (name: string) => unknown;
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
type ResumeClaim = {
|
|
575
|
+
job: LockedJobRow;
|
|
576
|
+
steps: PipelineStepDef[];
|
|
577
|
+
stepResults: Record<string, unknown>;
|
|
578
|
+
currentStep: number;
|
|
579
|
+
};
|
|
447
580
|
const resume: ResumeClaim | undefined = await this.db.sequelize.transaction(
|
|
448
581
|
async (transaction: { LOCK: { UPDATE: string } }): Promise<ResumeClaim | undefined> => {
|
|
449
|
-
const locked = await jobsRepo.findOne({
|
|
450
|
-
|
|
582
|
+
const locked = (await jobsRepo.findOne({
|
|
583
|
+
filterByTk: jobId,
|
|
584
|
+
transaction,
|
|
585
|
+
lock: transaction.LOCK.UPDATE,
|
|
586
|
+
})) as LockedJobRow | null;
|
|
587
|
+
const lockedStatus = locked ? String(locked.get('status')) : '';
|
|
588
|
+
if (!locked || (lockedStatus !== 'polling' && lockedStatus !== 'waiting_input')) return undefined;
|
|
451
589
|
|
|
452
590
|
const pipeline = await pipelineRepo.findOne({
|
|
453
591
|
filter: { id: locked.get('pipelineId') },
|
|
@@ -456,12 +594,11 @@ export class PipelineExecutor {
|
|
|
456
594
|
});
|
|
457
595
|
if (!pipeline) return undefined;
|
|
458
596
|
|
|
459
|
-
const
|
|
460
|
-
|
|
461
|
-
);
|
|
597
|
+
const rawSteps = (pipeline as unknown as PipelineDef).steps || [];
|
|
598
|
+
const steps = [...rawSteps].sort((a, b) => a.stepOrder - b.stepOrder);
|
|
462
599
|
const currentStep = Number(locked.get('currentStep'));
|
|
463
600
|
const step = steps.find((s) => s.stepOrder === currentStep);
|
|
464
|
-
const stepResults = { ...((locked.get('stepResults') as Record<string,
|
|
601
|
+
const stepResults = { ...((locked.get('stepResults') as Record<string, unknown>) || {}) };
|
|
465
602
|
if (step) {
|
|
466
603
|
stepResults[step.outputAlias || step.stepOrder.toString()] = asyncResult;
|
|
467
604
|
}
|
|
@@ -470,6 +607,7 @@ export class PipelineExecutor {
|
|
|
470
607
|
filterByTk: jobId,
|
|
471
608
|
values: {
|
|
472
609
|
status: 'running',
|
|
610
|
+
waitState: null,
|
|
473
611
|
ownedBy: this.nodeId,
|
|
474
612
|
leaseExpiresAt: new Date(Date.now() + JOB_RUN_LEASE_MS),
|
|
475
613
|
stepResults,
|
|
@@ -483,30 +621,32 @@ export class PipelineExecutor {
|
|
|
483
621
|
if (!resume) return;
|
|
484
622
|
|
|
485
623
|
const context: ExecutionContext = {
|
|
486
|
-
input: resume.job.get('input'),
|
|
487
|
-
files: [],
|
|
624
|
+
input: (resume.job.get('input') as Record<string, unknown>) || {},
|
|
625
|
+
files: [],
|
|
488
626
|
stepResults: resume.stepResults,
|
|
489
627
|
jobId: resume.job.id,
|
|
490
628
|
};
|
|
491
629
|
|
|
492
|
-
|
|
493
|
-
this.runSteps(resume.job, resume.steps, context, resume.currentStep + 1).catch((err) => {
|
|
630
|
+
this.runSteps(resume.job as unknown as JobState, resume.steps, context, resume.currentStep + 1).catch((err) => {
|
|
494
631
|
this.logger.error(`Failed executing step ${resume.currentStep + 1} for job ${resume.job.id}`, err);
|
|
495
632
|
});
|
|
496
633
|
}
|
|
497
634
|
|
|
498
635
|
private async finishJob(jobId: number, context: ExecutionContext) {
|
|
499
|
-
const jobsRepo = this.db.getRepository
|
|
500
|
-
const pipelineRepo = this.db.getRepository
|
|
636
|
+
const jobsRepo = this.db.getRepository('doc_understanding_jobs');
|
|
637
|
+
const pipelineRepo = this.db.getRepository('doc_understanding_pipelines');
|
|
501
638
|
const job = await jobsRepo.findOne({ filterByTk: jobId });
|
|
502
639
|
if (!job) return;
|
|
503
640
|
|
|
504
|
-
const pipeline = await pipelineRepo.findOne({ filter: { id: job.pipelineId } });
|
|
641
|
+
const pipeline = (await pipelineRepo.findOne({ filter: { id: job.pipelineId } })) as unknown as PipelineDef | null;
|
|
505
642
|
if (!pipeline) return;
|
|
506
643
|
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
644
|
+
let finalResult: unknown = context.stepResults;
|
|
645
|
+
if (pipeline.outputMapping && Object.keys(pipeline.outputMapping).length > 0) {
|
|
646
|
+
const mapped = this.resolveMapping(pipeline.outputMapping, context);
|
|
647
|
+
const compact = Object.fromEntries(Object.entries(mapped).filter(([, v]) => v !== undefined));
|
|
648
|
+
finalResult = Object.keys(compact).length > 0 ? compact : context.stepResults;
|
|
649
|
+
}
|
|
510
650
|
|
|
511
651
|
await jobsRepo.update({
|
|
512
652
|
filterByTk: jobId,
|
|
@@ -519,44 +659,41 @@ export class PipelineExecutor {
|
|
|
519
659
|
});
|
|
520
660
|
}
|
|
521
661
|
|
|
522
|
-
private resolveMapping(mapping: Record<string,
|
|
523
|
-
const result: Record<string,
|
|
662
|
+
private resolveMapping(mapping: Record<string, unknown>, context: ExecutionContext): Record<string, unknown> {
|
|
663
|
+
const result: Record<string, unknown> = {};
|
|
524
664
|
for (const [key, value] of Object.entries(mapping)) {
|
|
525
665
|
if (typeof value === 'string') {
|
|
526
666
|
if (value.startsWith('$input.')) {
|
|
527
667
|
result[key] = this.getNestedValue(context.input, value.replace('$input.', ''));
|
|
528
668
|
} else if (value.startsWith('$step[')) {
|
|
529
|
-
const match = value.match(
|
|
669
|
+
const match = value.match(/^\$step\[(.*?)\]\.(?:response\.)?(.*)$/);
|
|
530
670
|
if (match) {
|
|
531
671
|
const stepKey = match[1];
|
|
532
672
|
const path = match[2];
|
|
533
673
|
const stepResult = context.stepResults[stepKey];
|
|
534
|
-
result[key] = this.getNestedValue(stepResult, path);
|
|
674
|
+
result[key] = path ? this.getNestedValue(stepResult, path) : stepResult;
|
|
535
675
|
} else {
|
|
536
676
|
result[key] = value;
|
|
537
677
|
}
|
|
538
678
|
} else if (value === '$files') {
|
|
539
|
-
//
|
|
679
|
+
// Handled via context.files
|
|
540
680
|
} else {
|
|
541
681
|
result[key] = value;
|
|
542
682
|
}
|
|
543
683
|
} else {
|
|
544
|
-
result[key] = value;
|
|
684
|
+
result[key] = value;
|
|
545
685
|
}
|
|
546
686
|
}
|
|
547
687
|
return result;
|
|
548
688
|
}
|
|
549
689
|
|
|
550
|
-
private evaluateCondition(condition:
|
|
551
|
-
if (!condition) return true;
|
|
690
|
+
private evaluateCondition(condition: unknown, context: ExecutionContext): boolean {
|
|
691
|
+
if (!condition || !isRecord(condition)) return true;
|
|
552
692
|
|
|
553
|
-
const resolveValue = (v:
|
|
554
|
-
if (typeof v === 'string' && v.startsWith('$')) {
|
|
555
|
-
|
|
556
|
-
if (
|
|
557
|
-
const match = v.match(/\$step\[(.*?)\]\.response\.(.*)/);
|
|
558
|
-
if (match) return this.getNestedValue(context.stepResults[match[1]], match[2]);
|
|
559
|
-
}
|
|
693
|
+
const resolveValue = (v: unknown): unknown => {
|
|
694
|
+
if (typeof v === 'string' && v.startsWith('$step[')) {
|
|
695
|
+
const match = v.match(/^\$step\[(.*?)\]\.(?:response\.)?(.*)$/);
|
|
696
|
+
if (match) return this.getNestedValue(context.stepResults[match[1]], match[2]);
|
|
560
697
|
}
|
|
561
698
|
return v;
|
|
562
699
|
};
|
|
@@ -570,13 +707,13 @@ export class PipelineExecutor {
|
|
|
570
707
|
case 'neq':
|
|
571
708
|
return fieldVal !== val;
|
|
572
709
|
case 'gt':
|
|
573
|
-
return fieldVal > val;
|
|
710
|
+
return Number(fieldVal) > Number(val);
|
|
574
711
|
case 'gte':
|
|
575
|
-
return fieldVal >= val;
|
|
712
|
+
return Number(fieldVal) >= Number(val);
|
|
576
713
|
case 'lt':
|
|
577
|
-
return fieldVal < val;
|
|
714
|
+
return Number(fieldVal) < Number(val);
|
|
578
715
|
case 'lte':
|
|
579
|
-
return fieldVal <= val;
|
|
716
|
+
return Number(fieldVal) <= Number(val);
|
|
580
717
|
case 'in':
|
|
581
718
|
return Array.isArray(val) && val.includes(fieldVal);
|
|
582
719
|
case 'contains':
|
|
@@ -586,8 +723,8 @@ export class PipelineExecutor {
|
|
|
586
723
|
}
|
|
587
724
|
}
|
|
588
725
|
|
|
589
|
-
private getNestedValue(obj:
|
|
590
|
-
if (!obj) return obj;
|
|
591
|
-
return path.split('.').reduce((acc, part) => acc
|
|
726
|
+
private getNestedValue(obj: unknown, path: string): unknown {
|
|
727
|
+
if (!obj || !path) return obj;
|
|
728
|
+
return path.split('.').reduce<unknown>((acc, part) => (isRecord(acc) ? acc[part] : undefined), obj);
|
|
592
729
|
}
|
|
593
730
|
}
|