plugin-document-understanding 1.1.11 → 1.1.13
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/dist/client/345.e6e484fb1974c3d3.js +10 -0
- package/dist/client/index.js +1 -1
- package/dist/client-v2/345.a8f28526ac21e02a.js +10 -0
- package/dist/client-v2/index.js +1 -1
- package/dist/externalVersion.js +7 -7
- package/dist/locale/en-US.json +182 -171
- package/dist/locale/vi-VN.json +182 -171
- package/dist/locale/zh-CN.json +182 -171
- package/dist/node_modules/form-data/lib/form_data.js +3 -3
- package/dist/node_modules/form-data/package.json +1 -1
- package/dist/server/collections/endpoints.js +5 -0
- package/dist/server/collections/jobs.js +13 -0
- package/dist/server/dugate-seed.js +411 -0
- package/dist/server/plugin.js +6 -0
- package/dist/server/services/AsyncJobManager.js +87 -31
- package/dist/server/services/DocumentUnderstandingService.js +48 -5
- package/dist/server/services/ExternalApiClient.js +38 -5
- package/dist/server/services/PipelineExecutor.js +115 -36
- package/package.json +1 -1
- package/src/client-v2/components/EndpointsTab.tsx +51 -0
- package/src/locale/en-US.json +182 -171
- package/src/locale/vi-VN.json +182 -171
- package/src/locale/zh-CN.json +182 -171
- package/src/server/__tests__/cluster-safety.test.ts +259 -0
- package/src/server/__tests__/dugate-integration.test.ts +221 -0
- package/src/server/collections/endpoints.ts +5 -0
- package/src/server/collections/jobs.ts +13 -0
- package/src/server/dugate-seed.ts +491 -0
- package/src/server/plugin.ts +143 -134
- package/src/server/services/AsyncJobManager.ts +98 -32
- package/src/server/services/DocumentUnderstandingService.ts +50 -4
- package/src/server/services/ExternalApiClient.ts +40 -5
- package/src/server/services/PipelineExecutor.ts +593 -477
- package/src/server/types.ts +90 -78
- package/dist/client/345.17f88ffb846ec69b.js +0 -10
- package/dist/client-v2/345.1e0c321d30702aa1.js +0 -10
|
@@ -1,477 +1,593 @@
|
|
|
1
|
-
import { existsSync, realpathSync, readFileSync, statSync } from 'fs';
|
|
2
|
-
import { basename, resolve, sep } from 'path';
|
|
3
|
-
import { Database } from '@nocobase/database';
|
|
4
|
-
import mime from 'mime-types';
|
|
5
|
-
import { ExternalApiClient, FileInput } from './ExternalApiClient';
|
|
6
|
-
import { AsyncJobManager } from './AsyncJobManager';
|
|
7
|
-
import { PipelineDef, PipelineStepDef, JobState, EndpointDef } from '../types';
|
|
8
|
-
|
|
9
|
-
interface LoggerLike {
|
|
10
|
-
error: (...args: unknown[]) => void;
|
|
11
|
-
warn?: (...args: unknown[]) => void;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
interface FileReferenceInput {
|
|
15
|
-
buffer?: Buffer;
|
|
16
|
-
url?: string;
|
|
17
|
-
fieldName?: string;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
const UPLOAD_ROOTS = [resolve(process.cwd(), 'storage', 'uploads')];
|
|
21
|
-
|
|
22
|
-
const isInsidePath = (basePath: string, targetPath: string) =>
|
|
23
|
-
targetPath === basePath || targetPath.startsWith(`${basePath}${sep}`);
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
return null;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
export
|
|
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
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
const
|
|
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
|
-
|
|
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
|
-
|
|
280
|
-
|
|
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
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
}
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
};
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
1
|
+
import { existsSync, realpathSync, readFileSync, statSync } from 'fs';
|
|
2
|
+
import { basename, resolve, sep } from 'path';
|
|
3
|
+
import { Database } from '@nocobase/database';
|
|
4
|
+
import mime from 'mime-types';
|
|
5
|
+
import { ExternalApiClient, FileInput } from './ExternalApiClient';
|
|
6
|
+
import { AsyncJobManager, JOB_RUN_LEASE_MS, pollLeaseMs } from './AsyncJobManager';
|
|
7
|
+
import { PipelineDef, PipelineStepDef, JobState, EndpointDef } from '../types';
|
|
8
|
+
|
|
9
|
+
interface LoggerLike {
|
|
10
|
+
error: (...args: unknown[]) => void;
|
|
11
|
+
warn?: (...args: unknown[]) => void;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
interface FileReferenceInput {
|
|
15
|
+
buffer?: Buffer;
|
|
16
|
+
url?: string;
|
|
17
|
+
fieldName?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const UPLOAD_ROOTS = [resolve(process.cwd(), 'storage', 'uploads')];
|
|
21
|
+
|
|
22
|
+
const isInsidePath = (basePath: string, targetPath: string) =>
|
|
23
|
+
targetPath === basePath || targetPath.startsWith(`${basePath}${sep}`);
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Extract a task ID from a DUGate-style 202 Accepted response.
|
|
27
|
+
* Priority:
|
|
28
|
+
* 1. `taskIdExtractPath` + optional `taskIdExtractRegex` (e.g. path="name", regex="operations/([^/]+)")
|
|
29
|
+
* 2. `pollTaskIdField` (default "task_id")
|
|
30
|
+
* 3. Raw response body as string fallback
|
|
31
|
+
*/
|
|
32
|
+
function extractTaskId(responseData: any, endpoint: EndpointDef): string | null {
|
|
33
|
+
// 1. taskIdExtractPath: navigate to a field, then optionally apply regex
|
|
34
|
+
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);
|
|
39
|
+
if (raw != null) {
|
|
40
|
+
const regex = endpoint.taskIdExtractRegex?.trim();
|
|
41
|
+
if (regex) {
|
|
42
|
+
try {
|
|
43
|
+
const m = String(raw).match(new RegExp(regex));
|
|
44
|
+
if (m?.[1]) return m[1];
|
|
45
|
+
} catch {
|
|
46
|
+
/* invalid regex, fall through */
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return String(raw);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// 2. pollTaskIdField (default "task_id")
|
|
54
|
+
const idField = endpoint.pollTaskIdField || 'task_id';
|
|
55
|
+
const fieldVal = idField.split('.').reduce((acc: any, k: string) => (acc != null ? acc[k] : undefined), responseData);
|
|
56
|
+
if (fieldVal != null) return String(fieldVal);
|
|
57
|
+
|
|
58
|
+
// 3. Raw string fallback
|
|
59
|
+
if (typeof responseData === 'string') return responseData;
|
|
60
|
+
if (typeof responseData === 'number') return String(responseData);
|
|
61
|
+
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function resolveUploadFilePath(urlOrPath: string): string | null {
|
|
66
|
+
if (!urlOrPath || urlOrPath.includes('\0')) return null;
|
|
67
|
+
|
|
68
|
+
let pathname = urlOrPath.replace(/\\/g, '/').split(/[?#]/)[0];
|
|
69
|
+
try {
|
|
70
|
+
if (pathname.startsWith('http://') || pathname.startsWith('https://')) {
|
|
71
|
+
pathname = new URL(pathname).pathname;
|
|
72
|
+
}
|
|
73
|
+
} catch {
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
pathname = decodeURIComponent(pathname).replace(/^\/+/, '');
|
|
78
|
+
const uploadsIndex = pathname.indexOf('uploads/');
|
|
79
|
+
if (pathname.startsWith('storage/uploads/')) {
|
|
80
|
+
pathname = pathname.slice('storage/uploads/'.length);
|
|
81
|
+
} else if (pathname.startsWith('uploads/')) {
|
|
82
|
+
pathname = pathname.slice('uploads/'.length);
|
|
83
|
+
} else if (uploadsIndex >= 0) {
|
|
84
|
+
pathname = pathname.slice(uploadsIndex + 'uploads/'.length);
|
|
85
|
+
} else {
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const parts = pathname.split('/').filter(Boolean);
|
|
90
|
+
if (parts.some((part) => part === '..' || part.includes('\0'))) return null;
|
|
91
|
+
|
|
92
|
+
for (const root of UPLOAD_ROOTS) {
|
|
93
|
+
const candidate = resolve(root, ...parts);
|
|
94
|
+
const realRoot = existsSync(root) ? realpathSync(root) : root;
|
|
95
|
+
if (!existsSync(candidate)) continue;
|
|
96
|
+
const realCandidate = realpathSync(candidate);
|
|
97
|
+
if (isInsidePath(realRoot, realCandidate) && statSync(realCandidate).isFile()) {
|
|
98
|
+
return realCandidate;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export interface ExecutionContext {
|
|
106
|
+
input: Record<string, any>;
|
|
107
|
+
files: FileInput[];
|
|
108
|
+
stepResults: Record<string, any>;
|
|
109
|
+
jobId: number;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export class PipelineExecutor {
|
|
113
|
+
private db: Database;
|
|
114
|
+
private apiClient: ExternalApiClient;
|
|
115
|
+
private jobManager: AsyncJobManager;
|
|
116
|
+
private logger: LoggerLike;
|
|
117
|
+
private nodeId: string;
|
|
118
|
+
|
|
119
|
+
constructor(
|
|
120
|
+
db: Database,
|
|
121
|
+
apiClient: ExternalApiClient,
|
|
122
|
+
jobManager: AsyncJobManager,
|
|
123
|
+
logger: LoggerLike,
|
|
124
|
+
nodeId = '',
|
|
125
|
+
) {
|
|
126
|
+
this.db = db;
|
|
127
|
+
this.apiClient = apiClient;
|
|
128
|
+
this.jobManager = jobManager;
|
|
129
|
+
this.logger = logger;
|
|
130
|
+
this.nodeId = nodeId;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
private async resolveFile(urlOrPath: string, fieldName = 'file'): Promise<FileInput | null> {
|
|
134
|
+
if (!urlOrPath || typeof urlOrPath !== 'string') return null;
|
|
135
|
+
|
|
136
|
+
try {
|
|
137
|
+
const localPath = resolveUploadFilePath(urlOrPath);
|
|
138
|
+
if (localPath) {
|
|
139
|
+
const buffer = readFileSync(localPath);
|
|
140
|
+
const mimeType = mime.lookup(localPath) || 'application/octet-stream';
|
|
141
|
+
|
|
142
|
+
return {
|
|
143
|
+
fieldName,
|
|
144
|
+
buffer,
|
|
145
|
+
filename: basename(localPath),
|
|
146
|
+
mimeType,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Only files in NocoBase's upload storage are accepted. Fetching arbitrary
|
|
151
|
+
// HTTP(S) URLs here would turn a user/AI-provided value into an SSRF primitive.
|
|
152
|
+
if (urlOrPath.startsWith('http://') || urlOrPath.startsWith('https://')) {
|
|
153
|
+
this.logger.warn?.('Ignoring remote file URL; use a NocoBase upload URL instead.');
|
|
154
|
+
}
|
|
155
|
+
} catch (err) {
|
|
156
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
157
|
+
this.logger.warn?.(`Failed to resolve file input: ${message}`);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return null;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async execute(
|
|
164
|
+
pipelineId: number,
|
|
165
|
+
input: Record<string, any>,
|
|
166
|
+
files: FileInput[] = [],
|
|
167
|
+
userId?: number,
|
|
168
|
+
): Promise<JobState> {
|
|
169
|
+
const pipelineRepo = this.db.getRepository<any>('doc_understanding_pipelines');
|
|
170
|
+
const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
|
|
171
|
+
|
|
172
|
+
const pipeline = await pipelineRepo.findOne({
|
|
173
|
+
filter: { id: pipelineId },
|
|
174
|
+
appends: ['steps', 'steps.endpoint'],
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
if (!pipeline) throw new Error(`Pipeline ${pipelineId} not found`);
|
|
178
|
+
if (!pipeline.enabled) throw new Error(`Pipeline ${pipelineId} is disabled`);
|
|
179
|
+
|
|
180
|
+
// Create Job
|
|
181
|
+
const job = await jobsRepo.create({
|
|
182
|
+
values: {
|
|
183
|
+
pipelineId,
|
|
184
|
+
status: 'pending',
|
|
185
|
+
input,
|
|
186
|
+
currentStep: 1, // 1-based ordering
|
|
187
|
+
stepResults: {},
|
|
188
|
+
externalTaskIds: {},
|
|
189
|
+
startedAt: new Date(),
|
|
190
|
+
createdById: userId,
|
|
191
|
+
ownedBy: this.nodeId,
|
|
192
|
+
leaseExpiresAt: new Date(Date.now() + JOB_RUN_LEASE_MS),
|
|
193
|
+
},
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
const resolvedFiles: FileInput[] = [];
|
|
197
|
+
|
|
198
|
+
const tryAddFile = async (urlOrPath: string, fieldName = 'file') => {
|
|
199
|
+
const resolved = await this.resolveFile(urlOrPath, fieldName);
|
|
200
|
+
if (resolved) {
|
|
201
|
+
resolvedFiles.push(resolved);
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
// 1. Process files argument
|
|
206
|
+
if (Array.isArray(files)) {
|
|
207
|
+
for (const f of files) {
|
|
208
|
+
if (f && typeof f === 'object') {
|
|
209
|
+
const fileRef = f as FileReferenceInput;
|
|
210
|
+
if (fileRef.buffer) {
|
|
211
|
+
resolvedFiles.push(f);
|
|
212
|
+
} else if (fileRef.url) {
|
|
213
|
+
await tryAddFile(fileRef.url, fileRef.fieldName || 'file');
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// 2. Scan input for common file URL keys
|
|
220
|
+
const urlFields = ['file_url', 'file_urls', 'file', 'files'];
|
|
221
|
+
for (const key of urlFields) {
|
|
222
|
+
const val = input[key];
|
|
223
|
+
if (!val) continue;
|
|
224
|
+
|
|
225
|
+
if (typeof val === 'string') {
|
|
226
|
+
if (
|
|
227
|
+
val.startsWith('http://') ||
|
|
228
|
+
val.startsWith('https://') ||
|
|
229
|
+
val.startsWith('/') ||
|
|
230
|
+
val.startsWith('storage/')
|
|
231
|
+
) {
|
|
232
|
+
await tryAddFile(val, 'file');
|
|
233
|
+
} else if (val.includes(',')) {
|
|
234
|
+
const urls = val.split(',').map((s) => s.trim());
|
|
235
|
+
for (const u of urls) {
|
|
236
|
+
if (u.startsWith('http://') || u.startsWith('https://') || u.startsWith('/') || u.startsWith('storage/')) {
|
|
237
|
+
await tryAddFile(u, 'file');
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
} else if (Array.isArray(val)) {
|
|
242
|
+
for (const item of val) {
|
|
243
|
+
if (typeof item === 'string') {
|
|
244
|
+
if (
|
|
245
|
+
item.startsWith('http://') ||
|
|
246
|
+
item.startsWith('https://') ||
|
|
247
|
+
item.startsWith('/') ||
|
|
248
|
+
item.startsWith('storage/')
|
|
249
|
+
) {
|
|
250
|
+
await tryAddFile(item, 'file');
|
|
251
|
+
}
|
|
252
|
+
} else if (item && typeof item === 'object' && item.url) {
|
|
253
|
+
await tryAddFile(item.url, 'file');
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
} else if (val && typeof val === 'object' && val.url) {
|
|
257
|
+
await tryAddFile(val.url, 'file');
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
if (resolvedFiles.length === 0 && files && files.length > 0) {
|
|
262
|
+
for (const f of files) {
|
|
263
|
+
if ((f as FileReferenceInput).buffer) {
|
|
264
|
+
resolvedFiles.push(f);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
const context: ExecutionContext = {
|
|
270
|
+
input,
|
|
271
|
+
files: resolvedFiles,
|
|
272
|
+
stepResults: {},
|
|
273
|
+
jobId: job.id,
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
// Sorting steps by order
|
|
277
|
+
const steps = [...(pipeline.steps || [])].sort((a, b) => a.stepOrder - b.stepOrder);
|
|
278
|
+
|
|
279
|
+
// Run steps (Synchronous part)
|
|
280
|
+
this.runSteps(job, steps, context).catch((err) => {
|
|
281
|
+
this.logger.error(`Background pipeline error for job ${job.id}`, err);
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
return job;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
private async runSteps(job: JobState, steps: PipelineStepDef[], context: ExecutionContext, startFromOrder = 1) {
|
|
288
|
+
const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
|
|
289
|
+
let currentOrder = startFromOrder;
|
|
290
|
+
|
|
291
|
+
try {
|
|
292
|
+
await jobsRepo.update({
|
|
293
|
+
filterByTk: job.id,
|
|
294
|
+
values: { status: 'running', ownedBy: this.nodeId, leaseExpiresAt: new Date(Date.now() + JOB_RUN_LEASE_MS) },
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
for (const step of steps) {
|
|
298
|
+
if (step.stepOrder < startFromOrder) continue;
|
|
299
|
+
|
|
300
|
+
context.jobId = job.id;
|
|
301
|
+
currentOrder = step.stepOrder;
|
|
302
|
+
|
|
303
|
+
await jobsRepo.update({
|
|
304
|
+
filterByTk: job.id,
|
|
305
|
+
values: { currentStep: currentOrder, leaseExpiresAt: new Date(Date.now() + JOB_RUN_LEASE_MS) },
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
if (!this.evaluateCondition(step.condition, context)) {
|
|
309
|
+
continue; // Skip step
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
if (!step.endpoint?.enabled) {
|
|
313
|
+
throw new Error(`Endpoint for step ${step.name} is disabled`);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const mappedBody =
|
|
317
|
+
step.inputMapping && Object.keys(step.inputMapping).length > 0
|
|
318
|
+
? this.resolveMapping(step.inputMapping, context)
|
|
319
|
+
: context.input;
|
|
320
|
+
let retries = step.onError === 'retry' ? step.retryCount || 0 : 0;
|
|
321
|
+
let success = false;
|
|
322
|
+
let lastError = null;
|
|
323
|
+
|
|
324
|
+
while (retries >= 0 && !success) {
|
|
325
|
+
try {
|
|
326
|
+
const fileFieldName = step.endpoint.fileFieldName || 'file';
|
|
327
|
+
const mappedFiles = context.files
|
|
328
|
+
? context.files.map((f) => ({
|
|
329
|
+
...f,
|
|
330
|
+
fieldName: fileFieldName,
|
|
331
|
+
}))
|
|
332
|
+
: [];
|
|
333
|
+
|
|
334
|
+
const result = await this.apiClient.call({
|
|
335
|
+
endpoint: step.endpoint,
|
|
336
|
+
body: mappedBody,
|
|
337
|
+
files: mappedFiles,
|
|
338
|
+
});
|
|
339
|
+
|
|
340
|
+
if (step.endpoint.executionMode === 'sync') {
|
|
341
|
+
const responseData = result.data;
|
|
342
|
+
// DUGate sync mode (?sync=true) can still return 202 Accepted with a
|
|
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);
|
|
348
|
+
if (isAsyncAccepted) {
|
|
349
|
+
const taskId = extractTaskId(responseData, step.endpoint);
|
|
350
|
+
if (taskId) {
|
|
351
|
+
const externalTaskIds = { ...(job.externalTaskIds || {}) };
|
|
352
|
+
externalTaskIds[step.stepOrder.toString()] = taskId;
|
|
353
|
+
|
|
354
|
+
await jobsRepo.update({
|
|
355
|
+
filterByTk: job.id,
|
|
356
|
+
values: {
|
|
357
|
+
status: 'polling',
|
|
358
|
+
externalTaskIds,
|
|
359
|
+
leaseExpiresAt: new Date(Date.now() + pollLeaseMs(step.endpoint.pollInterval)),
|
|
360
|
+
},
|
|
361
|
+
});
|
|
362
|
+
|
|
363
|
+
await this.jobManager.startPolling(job.id, step.endpoint, taskId);
|
|
364
|
+
return; // Halt execution. Polling callback will resume from next step.
|
|
365
|
+
}
|
|
366
|
+
// No task id: fall through and store the raw 202 body as the step result.
|
|
367
|
+
}
|
|
368
|
+
context.stepResults[step.outputAlias || step.stepOrder.toString()] = responseData;
|
|
369
|
+
success = true;
|
|
370
|
+
} else if (step.endpoint.executionMode === 'polling') {
|
|
371
|
+
// Extract taskId from result based on pollTaskIdField / taskIdExtractPath
|
|
372
|
+
const taskId = extractTaskId(result.data, step.endpoint);
|
|
373
|
+
|
|
374
|
+
if (!taskId) throw new Error('Polling taskId not found in response');
|
|
375
|
+
|
|
376
|
+
const externalTaskIds = job.externalTaskIds || {};
|
|
377
|
+
externalTaskIds[step.stepOrder.toString()] = taskId;
|
|
378
|
+
|
|
379
|
+
await jobsRepo.update({
|
|
380
|
+
filterByTk: job.id,
|
|
381
|
+
values: {
|
|
382
|
+
status: 'polling',
|
|
383
|
+
externalTaskIds,
|
|
384
|
+
// This node keeps polling and refreshes the lease on every tick.
|
|
385
|
+
leaseExpiresAt: new Date(Date.now() + pollLeaseMs(step.endpoint.pollInterval)),
|
|
386
|
+
},
|
|
387
|
+
});
|
|
388
|
+
|
|
389
|
+
await this.jobManager.startPolling(job.id, step.endpoint, taskId);
|
|
390
|
+
|
|
391
|
+
// Halt execution. Polling callback will resume from next step.
|
|
392
|
+
return;
|
|
393
|
+
} else if (step.endpoint.executionMode === 'webhook') {
|
|
394
|
+
// Wait for webhook
|
|
395
|
+
const taskId = extractTaskId(result.data, step.endpoint);
|
|
396
|
+
if (!taskId) throw new Error('Webhook taskId not found in response');
|
|
397
|
+
const externalTaskIds = job.externalTaskIds || {};
|
|
398
|
+
externalTaskIds[step.stepOrder.toString()] = taskId;
|
|
399
|
+
|
|
400
|
+
await jobsRepo.update({
|
|
401
|
+
filterByTk: job.id,
|
|
402
|
+
values: {
|
|
403
|
+
status: 'polling',
|
|
404
|
+
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
|
+
leaseExpiresAt: null,
|
|
408
|
+
},
|
|
409
|
+
});
|
|
410
|
+
|
|
411
|
+
// End execution. Webhook will resume.
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
} catch (err: any) {
|
|
415
|
+
lastError = err;
|
|
416
|
+
retries--;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
if (!success) {
|
|
421
|
+
if (step.onError === 'fail') {
|
|
422
|
+
throw lastError || new Error(`Step ${step.name} failed`);
|
|
423
|
+
}
|
|
424
|
+
// if 'skip', we continue the loop
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// If loop completes without being halted for async
|
|
429
|
+
await this.finishJob(job.id, context);
|
|
430
|
+
} catch (err: any) {
|
|
431
|
+
await jobsRepo.update({
|
|
432
|
+
filterByTk: job.id,
|
|
433
|
+
values: { status: 'failed', error: err.message, completedAt: new Date() },
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
async resumeFromStep(jobId: number, asyncResult: any) {
|
|
439
|
+
const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
|
|
440
|
+
const pipelineRepo = this.db.getRepository<any>('doc_understanding_pipelines');
|
|
441
|
+
|
|
442
|
+
// Atomic claim: webhooks can be delivered more than once and a polling tick can
|
|
443
|
+
// race with a webhook, so only the first caller that still finds the job in
|
|
444
|
+
// 'polling' may resume it. The row lock plus status re-check makes the claim
|
|
445
|
+
// safe across nodes.
|
|
446
|
+
type ResumeClaim = { job: any; steps: PipelineStepDef[]; stepResults: Record<string, any>; currentStep: number };
|
|
447
|
+
const resume: ResumeClaim | undefined = await this.db.sequelize.transaction(
|
|
448
|
+
async (transaction: { LOCK: { UPDATE: string } }): Promise<ResumeClaim | undefined> => {
|
|
449
|
+
const locked = await jobsRepo.findOne({ filterByTk: jobId, transaction, lock: transaction.LOCK.UPDATE });
|
|
450
|
+
if (!locked || String(locked.get('status')) !== 'polling') return undefined;
|
|
451
|
+
|
|
452
|
+
const pipeline = await pipelineRepo.findOne({
|
|
453
|
+
filter: { id: locked.get('pipelineId') },
|
|
454
|
+
appends: ['steps', 'steps.endpoint'],
|
|
455
|
+
transaction,
|
|
456
|
+
});
|
|
457
|
+
if (!pipeline) return undefined;
|
|
458
|
+
|
|
459
|
+
const steps = [...((pipeline as any).steps || [])].sort(
|
|
460
|
+
(a: PipelineStepDef, b: PipelineStepDef) => a.stepOrder - b.stepOrder,
|
|
461
|
+
);
|
|
462
|
+
const currentStep = Number(locked.get('currentStep'));
|
|
463
|
+
const step = steps.find((s) => s.stepOrder === currentStep);
|
|
464
|
+
const stepResults = { ...((locked.get('stepResults') as Record<string, any>) || {}) };
|
|
465
|
+
if (step) {
|
|
466
|
+
stepResults[step.outputAlias || step.stepOrder.toString()] = asyncResult;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
await jobsRepo.update({
|
|
470
|
+
filterByTk: jobId,
|
|
471
|
+
values: {
|
|
472
|
+
status: 'running',
|
|
473
|
+
ownedBy: this.nodeId,
|
|
474
|
+
leaseExpiresAt: new Date(Date.now() + JOB_RUN_LEASE_MS),
|
|
475
|
+
stepResults,
|
|
476
|
+
},
|
|
477
|
+
transaction,
|
|
478
|
+
});
|
|
479
|
+
return { job: locked, steps, stepResults, currentStep };
|
|
480
|
+
},
|
|
481
|
+
);
|
|
482
|
+
|
|
483
|
+
if (!resume) return;
|
|
484
|
+
|
|
485
|
+
const context: ExecutionContext = {
|
|
486
|
+
input: resume.job.get('input'),
|
|
487
|
+
files: [], // Files cannot easily persist across webhook unless stored in bucket. For now assume next steps use only json.
|
|
488
|
+
stepResults: resume.stepResults,
|
|
489
|
+
jobId: resume.job.id,
|
|
490
|
+
};
|
|
491
|
+
|
|
492
|
+
// resume from next step
|
|
493
|
+
this.runSteps(resume.job, resume.steps, context, resume.currentStep + 1).catch((err) => {
|
|
494
|
+
this.logger.error(`Failed executing step ${resume.currentStep + 1} for job ${resume.job.id}`, err);
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
private async finishJob(jobId: number, context: ExecutionContext) {
|
|
499
|
+
const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
|
|
500
|
+
const pipelineRepo = this.db.getRepository<any>('doc_understanding_pipelines');
|
|
501
|
+
const job = await jobsRepo.findOne({ filterByTk: jobId });
|
|
502
|
+
if (!job) return;
|
|
503
|
+
|
|
504
|
+
const pipeline = await pipelineRepo.findOne({ filter: { id: job.pipelineId } });
|
|
505
|
+
if (!pipeline) return;
|
|
506
|
+
|
|
507
|
+
const finalResult = pipeline.outputMapping
|
|
508
|
+
? this.resolveMapping(pipeline.outputMapping, context)
|
|
509
|
+
: context.stepResults;
|
|
510
|
+
|
|
511
|
+
await jobsRepo.update({
|
|
512
|
+
filterByTk: jobId,
|
|
513
|
+
values: {
|
|
514
|
+
status: 'completed',
|
|
515
|
+
stepResults: context.stepResults,
|
|
516
|
+
finalResult,
|
|
517
|
+
completedAt: new Date(),
|
|
518
|
+
},
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
private resolveMapping(mapping: Record<string, string>, context: ExecutionContext): Record<string, any> {
|
|
523
|
+
const result: Record<string, any> = {};
|
|
524
|
+
for (const [key, value] of Object.entries(mapping)) {
|
|
525
|
+
if (typeof value === 'string') {
|
|
526
|
+
if (value.startsWith('$input.')) {
|
|
527
|
+
result[key] = this.getNestedValue(context.input, value.replace('$input.', ''));
|
|
528
|
+
} else if (value.startsWith('$step[')) {
|
|
529
|
+
const match = value.match(/\$step\[(.*?)\]\.response\.(.*)/);
|
|
530
|
+
if (match) {
|
|
531
|
+
const stepKey = match[1];
|
|
532
|
+
const path = match[2];
|
|
533
|
+
const stepResult = context.stepResults[stepKey];
|
|
534
|
+
result[key] = this.getNestedValue(stepResult, path);
|
|
535
|
+
} else {
|
|
536
|
+
result[key] = value;
|
|
537
|
+
}
|
|
538
|
+
} else if (value === '$files') {
|
|
539
|
+
// special case: mapping wants files. Not mapped here as form data handles files via input.files.
|
|
540
|
+
} else {
|
|
541
|
+
result[key] = value;
|
|
542
|
+
}
|
|
543
|
+
} else {
|
|
544
|
+
result[key] = value; // copy raw if not string mapping
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
return result;
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
private evaluateCondition(condition: any, context: ExecutionContext): boolean {
|
|
551
|
+
if (!condition) return true;
|
|
552
|
+
|
|
553
|
+
const resolveValue = (v: any) => {
|
|
554
|
+
if (typeof v === 'string' && v.startsWith('$')) {
|
|
555
|
+
// Resolve simple $ expressions
|
|
556
|
+
if (v.startsWith('$step[')) {
|
|
557
|
+
const match = v.match(/\$step\[(.*?)\]\.response\.(.*)/);
|
|
558
|
+
if (match) return this.getNestedValue(context.stepResults[match[1]], match[2]);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
return v;
|
|
562
|
+
};
|
|
563
|
+
|
|
564
|
+
const fieldVal = resolveValue(condition.field);
|
|
565
|
+
const val = resolveValue(condition.value);
|
|
566
|
+
|
|
567
|
+
switch (condition.op) {
|
|
568
|
+
case 'eq':
|
|
569
|
+
return fieldVal === val;
|
|
570
|
+
case 'neq':
|
|
571
|
+
return fieldVal !== val;
|
|
572
|
+
case 'gt':
|
|
573
|
+
return fieldVal > val;
|
|
574
|
+
case 'gte':
|
|
575
|
+
return fieldVal >= val;
|
|
576
|
+
case 'lt':
|
|
577
|
+
return fieldVal < val;
|
|
578
|
+
case 'lte':
|
|
579
|
+
return fieldVal <= val;
|
|
580
|
+
case 'in':
|
|
581
|
+
return Array.isArray(val) && val.includes(fieldVal);
|
|
582
|
+
case 'contains':
|
|
583
|
+
return typeof fieldVal === 'string' && fieldVal.includes(String(val));
|
|
584
|
+
default:
|
|
585
|
+
return false;
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
private getNestedValue(obj: any, path: string): any {
|
|
590
|
+
if (!obj) return obj;
|
|
591
|
+
return path.split('.').reduce((acc, part) => acc && acc[part], obj);
|
|
592
|
+
}
|
|
593
|
+
}
|