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,23 +1,34 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
1
3
|
import * as crypto from 'crypto';
|
|
2
|
-
import { Application } from '@nocobase/server';
|
|
3
|
-
import { Database
|
|
4
|
+
import type { Application } from '@nocobase/server';
|
|
5
|
+
import type { Database } from '@nocobase/database';
|
|
4
6
|
import { ExternalApiClient, FileInput } from './ExternalApiClient';
|
|
5
7
|
import { AsyncJobManager } from './AsyncJobManager';
|
|
6
8
|
import { PipelineExecutor } from './PipelineExecutor';
|
|
9
|
+
import { ArtifactStorageService } from './ArtifactStorageService';
|
|
10
|
+
import { BuiltinBusinessEngine } from './BuiltinBusinessEngine';
|
|
11
|
+
import { ExternalDuReworkClient } from './ExternalDuReworkClient';
|
|
12
|
+
import { OperationOrchestrator } from './OperationOrchestrator';
|
|
13
|
+
import { seedDugateEndpoints } from '../dugate-seed';
|
|
7
14
|
import { ClientServiceConfig, ServiceConfig, EndpointDef, PipelineDef, JobState } from '../types';
|
|
8
15
|
|
|
16
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
17
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
18
|
+
}
|
|
19
|
+
|
|
9
20
|
export class DocumentUnderstandingService {
|
|
10
21
|
private app: Application;
|
|
11
22
|
private db: Database;
|
|
12
23
|
private apiClient!: ExternalApiClient;
|
|
13
24
|
private pipelineExecutor!: PipelineExecutor;
|
|
14
25
|
private jobManager!: AsyncJobManager;
|
|
26
|
+
public orchestrator!: OperationOrchestrator;
|
|
15
27
|
private initialized = false;
|
|
16
28
|
private startupRecoveryCompleted = false;
|
|
17
29
|
private initializationPromise?: Promise<void>;
|
|
18
30
|
private maintenanceTimer?: NodeJS.Timeout;
|
|
19
|
-
|
|
20
|
-
// jobs apart from jobs that are still being processed.
|
|
31
|
+
private processedWebhookDeliveries = new Set<string>();
|
|
21
32
|
private readonly nodeId: string;
|
|
22
33
|
private static readonly HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
23
34
|
private static readonly MAINTENANCE_INTERVAL_MS = 30_000;
|
|
@@ -50,6 +61,40 @@ export class DocumentUnderstandingService {
|
|
|
50
61
|
|
|
51
62
|
this.jobManager?.destroy();
|
|
52
63
|
this.stopMaintenance();
|
|
64
|
+
|
|
65
|
+
const artifactStorage = new ArtifactStorageService(this.db);
|
|
66
|
+
const builtinEngine = new BuiltinBusinessEngine(this.app, artifactStorage, async (pipelineRef, input, userId) => {
|
|
67
|
+
const pipelines = await this.listPipelines();
|
|
68
|
+
const target = pipelineRef.pipelineId
|
|
69
|
+
? pipelines.find((p) => p.id === pipelineRef.pipelineId)
|
|
70
|
+
: pipelines.find((p) => p.name === pipelineRef.pipelineName);
|
|
71
|
+
if (!target) {
|
|
72
|
+
throw new Error(`Referenced pipeline ${pipelineRef.pipelineName || pipelineRef.pipelineId} not found`);
|
|
73
|
+
}
|
|
74
|
+
const { jobId } = await this.executePipeline(target.id, input, [], userId);
|
|
75
|
+
const deadline = Date.now() + (config.pollTimeout || 120_000);
|
|
76
|
+
while (Date.now() < deadline) {
|
|
77
|
+
const j = await this.getJobStatus(jobId);
|
|
78
|
+
if (j.status === 'completed') {
|
|
79
|
+
return isRecord(j.finalResult) ? j.finalResult : { result: j.finalResult };
|
|
80
|
+
}
|
|
81
|
+
if (['failed', 'cancelled', 'timeout'].includes(j.status)) {
|
|
82
|
+
throw new Error(j.error || `Pipeline job #${jobId} ended with ${j.status}`);
|
|
83
|
+
}
|
|
84
|
+
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
85
|
+
}
|
|
86
|
+
throw new Error(`Schema workflow pipeline #${target.id} timed out`);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
this.orchestrator = new OperationOrchestrator({
|
|
90
|
+
app: this.app,
|
|
91
|
+
db: this.db,
|
|
92
|
+
artifactStorage,
|
|
93
|
+
builtinEngine,
|
|
94
|
+
getConfig: () => this.getConfig(),
|
|
95
|
+
nodeId: this.nodeId,
|
|
96
|
+
});
|
|
97
|
+
|
|
53
98
|
this.apiClient = new ExternalApiClient(config);
|
|
54
99
|
this.jobManager = new AsyncJobManager(
|
|
55
100
|
this.db,
|
|
@@ -59,7 +104,7 @@ export class DocumentUnderstandingService {
|
|
|
59
104
|
await this.pipelineExecutor.resumeFromStep(jobId, result);
|
|
60
105
|
},
|
|
61
106
|
onJobError: async (jobId, error) => {
|
|
62
|
-
const jobsRepo = this.db.getRepository
|
|
107
|
+
const jobsRepo = this.db.getRepository('doc_understanding_jobs');
|
|
63
108
|
await jobsRepo.update({
|
|
64
109
|
filterByTk: jobId,
|
|
65
110
|
values: { status: 'failed', error, completedAt: new Date() },
|
|
@@ -76,6 +121,7 @@ export class DocumentUnderstandingService {
|
|
|
76
121
|
this.jobManager,
|
|
77
122
|
this.app.logger,
|
|
78
123
|
this.nodeId,
|
|
124
|
+
this.orchestrator,
|
|
79
125
|
);
|
|
80
126
|
|
|
81
127
|
if (recoverJobs && !this.startupRecoveryCompleted) {
|
|
@@ -87,11 +133,6 @@ export class DocumentUnderstandingService {
|
|
|
87
133
|
this.initialized = true;
|
|
88
134
|
}
|
|
89
135
|
|
|
90
|
-
/**
|
|
91
|
-
* Cluster maintenance sweep: fails active jobs whose owner is gone and
|
|
92
|
-
* re-adopts orphaned polling jobs. Safe to run on every node — all state
|
|
93
|
-
* transitions are guarded by ownership checks and row-level claims.
|
|
94
|
-
*/
|
|
95
136
|
async maintainJobs(): Promise<void> {
|
|
96
137
|
if (!this.jobManager) return;
|
|
97
138
|
try {
|
|
@@ -107,7 +148,6 @@ export class DocumentUnderstandingService {
|
|
|
107
148
|
this.maintenanceTimer = setInterval(() => {
|
|
108
149
|
this.maintainJobs();
|
|
109
150
|
}, DocumentUnderstandingService.MAINTENANCE_INTERVAL_MS);
|
|
110
|
-
// The sweep must never keep the process alive on shutdown.
|
|
111
151
|
this.maintenanceTimer.unref?.();
|
|
112
152
|
}
|
|
113
153
|
|
|
@@ -119,7 +159,7 @@ export class DocumentUnderstandingService {
|
|
|
119
159
|
}
|
|
120
160
|
|
|
121
161
|
private async ensureConfig(): Promise<ServiceConfig> {
|
|
122
|
-
const configRepo = this.db.getRepository
|
|
162
|
+
const configRepo = this.db.getRepository('doc_understanding_config');
|
|
123
163
|
let config = await configRepo.findOne();
|
|
124
164
|
|
|
125
165
|
if (!config) {
|
|
@@ -131,13 +171,15 @@ export class DocumentUnderstandingService {
|
|
|
131
171
|
defaultRetries: 2,
|
|
132
172
|
pollInterval: 5000,
|
|
133
173
|
pollTimeout: 300000,
|
|
174
|
+
engineMode: 'builtin',
|
|
175
|
+
maxFileSizeBytes: 10485760,
|
|
176
|
+
maxFilesPerRequest: 20,
|
|
177
|
+
publicGatewayEnabled: true,
|
|
134
178
|
},
|
|
135
179
|
});
|
|
136
180
|
}
|
|
137
181
|
|
|
138
|
-
|
|
139
|
-
// result would otherwise get an object with none of the config fields.
|
|
140
|
-
return config.toJSON();
|
|
182
|
+
return config.toJSON() as ServiceConfig;
|
|
141
183
|
}
|
|
142
184
|
|
|
143
185
|
isReady(): boolean {
|
|
@@ -158,7 +200,7 @@ export class DocumentUnderstandingService {
|
|
|
158
200
|
}
|
|
159
201
|
|
|
160
202
|
async updateConfig(data: Partial<ServiceConfig>): Promise<void> {
|
|
161
|
-
const configRepo = this.db.getRepository
|
|
203
|
+
const configRepo = this.db.getRepository('doc_understanding_config');
|
|
162
204
|
const conf = await configRepo.findOne();
|
|
163
205
|
if (conf) {
|
|
164
206
|
const values = { ...data };
|
|
@@ -166,10 +208,37 @@ export class DocumentUnderstandingService {
|
|
|
166
208
|
if (!values.webhookSecret) delete values.webhookSecret;
|
|
167
209
|
await configRepo.update({ filterByTk: conf.id, values });
|
|
168
210
|
}
|
|
169
|
-
// Reinitialize to pick up new config
|
|
170
211
|
await this.initialize();
|
|
171
212
|
}
|
|
172
213
|
|
|
214
|
+
async getGatewayHealth(): Promise<Record<string, unknown>> {
|
|
215
|
+
await this.ensureInitialized();
|
|
216
|
+
const config = await this.getConfig();
|
|
217
|
+
const llmServices = await this.orchestrator.builtinEngine.listAvailableLlmServices();
|
|
218
|
+
let externalStatus: Record<string, unknown> | undefined;
|
|
219
|
+
if (config.engineMode === 'du_rework' || config.engineMode === 'hybrid') {
|
|
220
|
+
const extClient = new ExternalDuReworkClient(config);
|
|
221
|
+
externalStatus = await extClient.checkHealth();
|
|
222
|
+
}
|
|
223
|
+
return {
|
|
224
|
+
status: 'ok',
|
|
225
|
+
engineMode: config.engineMode || 'builtin',
|
|
226
|
+
publicGatewayEnabled: config.publicGatewayEnabled !== false,
|
|
227
|
+
builtinAiAvailable: llmServices.length > 0 || Boolean(this.orchestrator.builtinEngine.resolveAiManager()),
|
|
228
|
+
llmServiceCount: llmServices.length,
|
|
229
|
+
...(externalStatus ? { externalGateway: externalStatus } : {}),
|
|
230
|
+
businesses: [
|
|
231
|
+
{ businessId: 'document-core', version: '2.0.0', state: 'ACTIVE' },
|
|
232
|
+
{ businessId: 'lc-checker', version: '1.2.0', state: 'ACTIVE' },
|
|
233
|
+
{ businessId: 'example-review', version: '1.0.0', state: 'ACTIVE' },
|
|
234
|
+
],
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async syncCatalog(): Promise<{ endpoints: number; pipelines: number }> {
|
|
239
|
+
return seedDugateEndpoints(this.db);
|
|
240
|
+
}
|
|
241
|
+
|
|
173
242
|
destroy(): void {
|
|
174
243
|
this.stopMaintenance();
|
|
175
244
|
this.jobManager?.destroy();
|
|
@@ -179,15 +248,19 @@ export class DocumentUnderstandingService {
|
|
|
179
248
|
|
|
180
249
|
async listEndpoints(): Promise<EndpointDef[]> {
|
|
181
250
|
await this.ensureInitialized();
|
|
182
|
-
|
|
251
|
+
const rows = await this.db.getRepository('doc_understanding_endpoints').find({ sort: 'sortOrder' });
|
|
252
|
+
return rows as unknown as EndpointDef[];
|
|
183
253
|
}
|
|
184
254
|
|
|
185
255
|
async createEndpoint(data: Partial<EndpointDef>): Promise<EndpointDef> {
|
|
186
|
-
|
|
256
|
+
const created = await this.db
|
|
257
|
+
.getRepository('doc_understanding_endpoints')
|
|
258
|
+
.create({ values: this.normalizeEndpoint(data) });
|
|
259
|
+
return created as unknown as EndpointDef;
|
|
187
260
|
}
|
|
188
261
|
|
|
189
262
|
async updateEndpoint(id: number, data: Partial<EndpointDef>): Promise<void> {
|
|
190
|
-
await this.db.getRepository
|
|
263
|
+
await this.db.getRepository('doc_understanding_endpoints').update({
|
|
191
264
|
filterByTk: id,
|
|
192
265
|
values: this.normalizeEndpoint(data),
|
|
193
266
|
});
|
|
@@ -203,7 +276,7 @@ export class DocumentUnderstandingService {
|
|
|
203
276
|
};
|
|
204
277
|
}
|
|
205
278
|
|
|
206
|
-
private normalizeHeaders(headers?: Record<string,
|
|
279
|
+
private normalizeHeaders(headers?: Record<string, unknown>): Record<string, string> {
|
|
207
280
|
const normalized: Record<string, string> = {};
|
|
208
281
|
if (!headers || typeof headers !== 'object' || Array.isArray(headers)) {
|
|
209
282
|
return normalized;
|
|
@@ -222,27 +295,29 @@ export class DocumentUnderstandingService {
|
|
|
222
295
|
}
|
|
223
296
|
|
|
224
297
|
async deleteEndpoint(id: number): Promise<void> {
|
|
225
|
-
await this.db.getRepository
|
|
298
|
+
await this.db.getRepository('doc_understanding_endpoints').destroy({ filterByTk: id });
|
|
226
299
|
}
|
|
227
300
|
|
|
228
301
|
async listPipelines(): Promise<PipelineDef[]> {
|
|
229
302
|
await this.ensureInitialized();
|
|
230
|
-
|
|
303
|
+
const rows = await this.db.getRepository('doc_understanding_pipelines').find({
|
|
231
304
|
appends: ['steps', 'steps.endpoint'],
|
|
232
305
|
});
|
|
306
|
+
return rows as unknown as PipelineDef[];
|
|
233
307
|
}
|
|
234
308
|
|
|
235
309
|
async createPipeline(data: Partial<PipelineDef>): Promise<PipelineDef> {
|
|
236
310
|
this.validateStepAliases(data.steps);
|
|
237
|
-
|
|
311
|
+
const created = await this.db.getRepository('doc_understanding_pipelines').create({ values: data });
|
|
312
|
+
return created as unknown as PipelineDef;
|
|
238
313
|
}
|
|
239
314
|
|
|
240
315
|
async updatePipeline(id: number, data: Partial<PipelineDef>): Promise<void> {
|
|
241
316
|
this.validateStepAliases(data.steps);
|
|
242
|
-
await this.db.getRepository
|
|
317
|
+
await this.db.getRepository('doc_understanding_pipelines').update({ filterByTk: id, values: data });
|
|
243
318
|
}
|
|
244
319
|
|
|
245
|
-
private validateStepAliases(steps?:
|
|
320
|
+
private validateStepAliases(steps?: Array<{ outputAlias?: string }>) {
|
|
246
321
|
if (!steps) return;
|
|
247
322
|
const aliases = steps.map((s) => s.outputAlias).filter(Boolean);
|
|
248
323
|
const unique = new Set(aliases);
|
|
@@ -252,12 +327,12 @@ export class DocumentUnderstandingService {
|
|
|
252
327
|
}
|
|
253
328
|
|
|
254
329
|
async deletePipeline(id: number): Promise<void> {
|
|
255
|
-
await this.db.getRepository
|
|
330
|
+
await this.db.getRepository('doc_understanding_pipelines').destroy({ filterByTk: id });
|
|
256
331
|
}
|
|
257
332
|
|
|
258
333
|
async executePipeline(
|
|
259
334
|
pipelineId: number,
|
|
260
|
-
input: Record<string,
|
|
335
|
+
input: Record<string, unknown>,
|
|
261
336
|
files: FileInput[] = [],
|
|
262
337
|
userId?: number,
|
|
263
338
|
): Promise<{ jobId: number }> {
|
|
@@ -268,46 +343,105 @@ export class DocumentUnderstandingService {
|
|
|
268
343
|
|
|
269
344
|
async getJobStatus(jobId: number, userId?: number): Promise<JobState> {
|
|
270
345
|
const filter = userId ? { id: jobId, createdById: userId } : { id: jobId };
|
|
271
|
-
const job = await this.db.getRepository
|
|
346
|
+
const job = await this.db.getRepository('doc_understanding_jobs').findOne({ filter });
|
|
272
347
|
if (!job) throw new Error('Job not found');
|
|
273
|
-
return job;
|
|
348
|
+
return job as unknown as JobState;
|
|
274
349
|
}
|
|
275
350
|
|
|
276
351
|
async listJobs(filters?: Record<string, unknown>, userId?: number): Promise<JobState[]> {
|
|
277
352
|
const filter = userId ? { ...(filters || {}), createdById: userId } : filters;
|
|
278
|
-
|
|
353
|
+
const rows = await this.db.getRepository('doc_understanding_jobs').find({
|
|
279
354
|
filter,
|
|
280
355
|
sort: ['-createdAt'],
|
|
281
356
|
});
|
|
357
|
+
return rows as unknown as JobState[];
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
async cancelJob(jobId: number): Promise<JobState> {
|
|
361
|
+
await this.ensureInitialized();
|
|
362
|
+
const job = await this.getJobStatus(jobId);
|
|
363
|
+
this.jobManager.stopPolling(jobId);
|
|
364
|
+
if (job.operationId) {
|
|
365
|
+
await this.orchestrator.cancelOperation('*', job.operationId).catch(() => undefined);
|
|
366
|
+
}
|
|
367
|
+
await this.db.getRepository('doc_understanding_jobs').update({
|
|
368
|
+
filterByTk: jobId,
|
|
369
|
+
values: {
|
|
370
|
+
status: 'cancelled',
|
|
371
|
+
completedAt: new Date(),
|
|
372
|
+
leaseExpiresAt: null,
|
|
373
|
+
},
|
|
374
|
+
});
|
|
375
|
+
return this.getJobStatus(jobId);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
async resumeJob(jobId: number, input: Record<string, unknown>, resumedBy?: string): Promise<JobState> {
|
|
379
|
+
await this.ensureInitialized();
|
|
380
|
+
const job = await this.getJobStatus(jobId);
|
|
381
|
+
if (job.status !== 'waiting_input' || !job.operationId) {
|
|
382
|
+
throw new Error(`Job #${jobId} is not waiting for human input`);
|
|
383
|
+
}
|
|
384
|
+
await this.orchestrator.resumeOperation({
|
|
385
|
+
tenantId: '*',
|
|
386
|
+
operationId: job.operationId,
|
|
387
|
+
input,
|
|
388
|
+
resumedBy,
|
|
389
|
+
});
|
|
390
|
+
const opView = await this.orchestrator.waitForOperation('*', job.operationId, 30);
|
|
391
|
+
if (opView.state === 'SUCCEEDED') {
|
|
392
|
+
const opRecord = await this.orchestrator.getOperationRecordOrThrow('*', job.operationId);
|
|
393
|
+
await this.pipelineExecutor.resumeFromStep(jobId, {
|
|
394
|
+
...(opRecord.outputPayload || {}),
|
|
395
|
+
usage: opRecord.usage,
|
|
396
|
+
operationId: opRecord.operationId,
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
return this.getJobStatus(jobId);
|
|
282
400
|
}
|
|
283
401
|
|
|
284
|
-
async handleWebhook(
|
|
402
|
+
async handleWebhook(
|
|
403
|
+
payload: Record<string, unknown>,
|
|
404
|
+
signature?: string,
|
|
405
|
+
duHeaders?: { signature?: string; timestamp?: string; deliveryId?: string },
|
|
406
|
+
): Promise<void> {
|
|
285
407
|
await this.ensureInitialized();
|
|
286
408
|
const config = await this.getConfig();
|
|
409
|
+
|
|
410
|
+
if (duHeaders?.deliveryId && this.processedWebhookDeliveries.has(duHeaders.deliveryId)) {
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
|
|
287
414
|
if (config.webhookSecret) {
|
|
288
|
-
|
|
415
|
+
const effectiveSig = duHeaders?.signature || signature;
|
|
416
|
+
if (!effectiveSig) {
|
|
289
417
|
throw new Error('Webhook signature missing');
|
|
290
418
|
}
|
|
291
|
-
const
|
|
292
|
-
const
|
|
293
|
-
|
|
419
|
+
const rawJson = JSON.stringify(payload);
|
|
420
|
+
const signedInput = duHeaders?.timestamp ? `${duHeaders.timestamp}.${rawJson}` : rawJson;
|
|
421
|
+
const expected = crypto.createHmac('sha256', config.webhookSecret).update(signedInput).digest('hex');
|
|
422
|
+
const signatureHash = effectiveSig.startsWith('sha256=') ? effectiveSig.slice(7) : effectiveSig;
|
|
423
|
+
const sigBuf = Buffer.from(signatureHash, 'hex');
|
|
424
|
+
const expBuf = Buffer.from(expected, 'hex');
|
|
425
|
+
if (sigBuf.length !== expBuf.length || !crypto.timingSafeEqual(sigBuf, expBuf)) {
|
|
294
426
|
throw new Error('Webhook signature verification failed');
|
|
295
427
|
}
|
|
296
428
|
}
|
|
297
429
|
|
|
298
|
-
const taskId = payload.task_id ?? payload.operation_id;
|
|
299
|
-
|
|
300
|
-
|
|
430
|
+
const taskId = String(payload.operationId ?? payload.task_id ?? payload.operation_id ?? '');
|
|
431
|
+
if (!taskId) throw new Error('Webhook missing task_id / operationId');
|
|
432
|
+
|
|
433
|
+
if (duHeaders?.deliveryId) {
|
|
434
|
+
this.processedWebhookDeliveries.add(duHeaders.deliveryId);
|
|
435
|
+
}
|
|
301
436
|
|
|
302
|
-
|
|
303
|
-
const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
|
|
437
|
+
const jobsRepo = this.db.getRepository('doc_understanding_jobs');
|
|
304
438
|
const PAGE_SIZE = 100;
|
|
305
439
|
let offset = 0;
|
|
306
440
|
let hasMoreJobs = true;
|
|
307
441
|
|
|
308
442
|
while (hasMoreJobs) {
|
|
309
443
|
const jobs = await jobsRepo.find({
|
|
310
|
-
filter: { status: 'polling' },
|
|
444
|
+
filter: { status: { $in: ['polling', 'waiting_input'] } },
|
|
311
445
|
limit: PAGE_SIZE,
|
|
312
446
|
offset,
|
|
313
447
|
});
|
|
@@ -315,8 +449,16 @@ export class DocumentUnderstandingService {
|
|
|
315
449
|
if (jobs.length === 0) break;
|
|
316
450
|
|
|
317
451
|
for (const job of jobs) {
|
|
318
|
-
|
|
319
|
-
|
|
452
|
+
const extIds = Object.values((job.externalTaskIds as Record<string, string>) || {});
|
|
453
|
+
if (extIds.includes(taskId) || job.operationId === taskId) {
|
|
454
|
+
if (payload.state === 'WAITING_INPUT' && isRecord(payload.wait)) {
|
|
455
|
+
await jobsRepo.update({
|
|
456
|
+
filterByTk: job.id,
|
|
457
|
+
values: { status: 'waiting_input', waitState: payload.wait, leaseExpiresAt: null },
|
|
458
|
+
});
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
await this.pipelineExecutor.resumeFromStep(job.id, payload.result || payload);
|
|
320
462
|
return;
|
|
321
463
|
}
|
|
322
464
|
}
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
import * as crypto from 'crypto';
|
|
4
|
+
import axios, { type AxiosInstance, type AxiosRequestConfig } from 'axios';
|
|
5
|
+
import type {
|
|
6
|
+
DocumentSelection,
|
|
7
|
+
OperationView,
|
|
8
|
+
ProblemDetails,
|
|
9
|
+
ResultEnvelope,
|
|
10
|
+
SubmissionArtifactRef,
|
|
11
|
+
} from '../contracts/du-contracts';
|
|
12
|
+
import type { ServiceConfig } from '../types';
|
|
13
|
+
import { DuHttpError, type ArtifactRecord } from './ArtifactStorageService';
|
|
14
|
+
|
|
15
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
16
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function sleep(ms: number): Promise<void> {
|
|
20
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Optional API connector for delegating execution to an external `du-rework` Orchestrator (:3000)
|
|
25
|
+
* using the canonical 2-step Upload Gateway, Idempotency-Key + Retry-After backoff,
|
|
26
|
+
* 12-state Operation polling, HITL resume/cancel, and ResultEnvelope + Artifact download.
|
|
27
|
+
*/
|
|
28
|
+
export class ExternalDuReworkClient {
|
|
29
|
+
private readonly config: ServiceConfig;
|
|
30
|
+
private readonly http: AxiosInstance;
|
|
31
|
+
|
|
32
|
+
constructor(config: ServiceConfig) {
|
|
33
|
+
this.config = config;
|
|
34
|
+
this.http = axios.create({
|
|
35
|
+
baseURL: config.baseUrl.replace(/\/+$/, ''),
|
|
36
|
+
timeout: config.defaultTimeout || 30_000,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
private buildAuthHeaders(): Record<string, string> {
|
|
41
|
+
const headers: Record<string, string> = {};
|
|
42
|
+
if (!this.config.authType || this.config.authType === 'none' || !this.config.authKey) {
|
|
43
|
+
return headers;
|
|
44
|
+
}
|
|
45
|
+
if (this.config.authType === 'bearer') {
|
|
46
|
+
headers['Authorization'] = `Bearer ${this.config.authKey}`;
|
|
47
|
+
} else if (this.config.authType === 'api_key') {
|
|
48
|
+
headers[this.config.authHeaderName || 'x-api-key'] = this.config.authKey;
|
|
49
|
+
} else if (this.config.authType === 'custom_header' && this.config.authHeaderName) {
|
|
50
|
+
headers[this.config.authHeaderName] = this.config.authKey;
|
|
51
|
+
}
|
|
52
|
+
return headers;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
private async requestWithRetry<T>(
|
|
56
|
+
reqConfig: AxiosRequestConfig,
|
|
57
|
+
maxRetries = this.config.defaultRetries ?? 2,
|
|
58
|
+
): Promise<T> {
|
|
59
|
+
for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
|
|
60
|
+
try {
|
|
61
|
+
const res = await this.http.request<T>({
|
|
62
|
+
...reqConfig,
|
|
63
|
+
headers: {
|
|
64
|
+
...this.buildAuthHeaders(),
|
|
65
|
+
...(reqConfig.headers || {}),
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
return res.data;
|
|
69
|
+
} catch (err: unknown) {
|
|
70
|
+
const axiosErr = err as {
|
|
71
|
+
response?: { status: number; data?: unknown; headers?: Record<string, string> };
|
|
72
|
+
message?: string;
|
|
73
|
+
};
|
|
74
|
+
const status = axiosErr.response?.status;
|
|
75
|
+
// Per BRD Section 5: retry 429 / 503 with exponential backoff + Retry-After while keeping Idempotency-Key
|
|
76
|
+
if ((status === 429 || status === 503) && attempt < maxRetries) {
|
|
77
|
+
const retryAfterHeader = Number(axiosErr.response?.headers?.['retry-after']);
|
|
78
|
+
const delayMs =
|
|
79
|
+
Number.isFinite(retryAfterHeader) && retryAfterHeader > 0
|
|
80
|
+
? retryAfterHeader * 1000
|
|
81
|
+
: Math.min(1000 * 2 ** attempt, 10_000);
|
|
82
|
+
await sleep(delayMs);
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (axiosErr.response && isRecord(axiosErr.response.data) && typeof axiosErr.response.data.code === 'string') {
|
|
86
|
+
throw new DuHttpError(axiosErr.response.data as unknown as ProblemDetails);
|
|
87
|
+
}
|
|
88
|
+
throw err;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
throw new Error('Retry loop exhausted');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async uploadArtifact(artifact: ArtifactRecord, buffer: Buffer): Promise<string> {
|
|
95
|
+
const sha256 = crypto.createHash('sha256').update(buffer).digest('hex');
|
|
96
|
+
const uploadToken = crypto.randomUUID();
|
|
97
|
+
const initRes = await this.requestWithRetry<{ artifactId: string; uploadUrl?: string }>({
|
|
98
|
+
method: 'POST',
|
|
99
|
+
url: '/api/v1/uploads',
|
|
100
|
+
headers: {
|
|
101
|
+
'Idempotency-Key': `upload-${artifact.artifactId}`,
|
|
102
|
+
'Content-Type': 'application/json',
|
|
103
|
+
},
|
|
104
|
+
data: {
|
|
105
|
+
fileName: artifact.fileName,
|
|
106
|
+
mimeType: artifact.mimeType,
|
|
107
|
+
sizeBytes: buffer.length,
|
|
108
|
+
uploadToken,
|
|
109
|
+
},
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
const remoteArtifactId = initRes.artifactId;
|
|
113
|
+
const uploadUrl = initRes.uploadUrl || `/api/v1/uploads/${remoteArtifactId}/content`;
|
|
114
|
+
|
|
115
|
+
await this.requestWithRetry({
|
|
116
|
+
method: 'PUT',
|
|
117
|
+
url: uploadUrl,
|
|
118
|
+
headers: {
|
|
119
|
+
'Content-Type': artifact.mimeType,
|
|
120
|
+
'Content-Length': String(buffer.length),
|
|
121
|
+
'x-content-sha256': sha256,
|
|
122
|
+
},
|
|
123
|
+
data: buffer,
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
return remoteArtifactId;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async submitAction(params: {
|
|
130
|
+
businessId: string;
|
|
131
|
+
action: string;
|
|
132
|
+
input: Record<string, unknown>;
|
|
133
|
+
artifacts: SubmissionArtifactRef[];
|
|
134
|
+
documentSelection?: DocumentSelection;
|
|
135
|
+
sourceUrl?: string;
|
|
136
|
+
clientReference?: string;
|
|
137
|
+
correlationId?: string;
|
|
138
|
+
idempotencyKey: string;
|
|
139
|
+
}): Promise<{ operationId: string; state: string; stateVersion: number }> {
|
|
140
|
+
return this.requestWithRetry({
|
|
141
|
+
method: 'POST',
|
|
142
|
+
url: `/api/v1/businesses/${encodeURIComponent(params.businessId)}/actions/${encodeURIComponent(params.action)}`,
|
|
143
|
+
headers: {
|
|
144
|
+
'Idempotency-Key': params.idempotencyKey,
|
|
145
|
+
...(params.correlationId ? { 'x-correlation-id': params.correlationId } : {}),
|
|
146
|
+
'Content-Type': 'application/json',
|
|
147
|
+
},
|
|
148
|
+
data: {
|
|
149
|
+
input: params.input,
|
|
150
|
+
...(params.artifacts.length > 0 ? { artifacts: params.artifacts } : {}),
|
|
151
|
+
...(params.documentSelection ? { documentSelection: params.documentSelection } : {}),
|
|
152
|
+
...(params.sourceUrl ? { sourceUrl: params.sourceUrl } : {}),
|
|
153
|
+
...(params.clientReference ? { clientReference: params.clientReference } : {}),
|
|
154
|
+
},
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
async getOperation(remoteOperationId: string, waitSeconds?: number): Promise<OperationView> {
|
|
159
|
+
return this.requestWithRetry({
|
|
160
|
+
method: 'GET',
|
|
161
|
+
url: `/api/v1/operations/${encodeURIComponent(remoteOperationId)}`,
|
|
162
|
+
params: waitSeconds ? { wait: waitSeconds } : undefined,
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async cancelOperation(remoteOperationId: string): Promise<{ operationId: string; state: string }> {
|
|
167
|
+
return this.requestWithRetry({
|
|
168
|
+
method: 'POST',
|
|
169
|
+
url: `/api/v1/operations/${encodeURIComponent(remoteOperationId)}/cancel`,
|
|
170
|
+
headers: { 'Idempotency-Key': `cancel-${remoteOperationId}` },
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async resumeOperation(
|
|
175
|
+
remoteOperationId: string,
|
|
176
|
+
body: { waitId: string; expectedStateVersion: number; input: Record<string, unknown> },
|
|
177
|
+
): Promise<{ operationId: string; state: string; stateVersion: number }> {
|
|
178
|
+
return this.requestWithRetry({
|
|
179
|
+
method: 'POST',
|
|
180
|
+
url: `/api/v1/operations/${encodeURIComponent(remoteOperationId)}/resume`,
|
|
181
|
+
headers: {
|
|
182
|
+
'Idempotency-Key': `resume-${remoteOperationId}-${body.expectedStateVersion}`,
|
|
183
|
+
'Content-Type': 'application/json',
|
|
184
|
+
},
|
|
185
|
+
data: body,
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async fetchResultAndPayload(remoteOperationId: string): Promise<{
|
|
190
|
+
envelope: ResultEnvelope;
|
|
191
|
+
outputPayload: Record<string, unknown>;
|
|
192
|
+
}> {
|
|
193
|
+
const envelope = await this.requestWithRetry<ResultEnvelope>({
|
|
194
|
+
method: 'GET',
|
|
195
|
+
url: `/api/v1/operations/${encodeURIComponent(remoteOperationId)}/result`,
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
let outputPayload: Record<string, unknown> = envelope.data || {};
|
|
199
|
+
const resultRef = typeof envelope.data?.resultRef === 'string' ? envelope.data.resultRef : undefined;
|
|
200
|
+
if (resultRef && resultRef.startsWith('artifact://')) {
|
|
201
|
+
const outputArtifactId = resultRef.slice('artifact://'.length);
|
|
202
|
+
const downloaded = await this.requestWithRetry<unknown>({
|
|
203
|
+
method: 'GET',
|
|
204
|
+
url: `/api/v1/artifacts/${encodeURIComponent(outputArtifactId)}/download`,
|
|
205
|
+
});
|
|
206
|
+
if (isRecord(downloaded)) {
|
|
207
|
+
outputPayload = downloaded;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
return { envelope, outputPayload };
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async checkHealth(): Promise<{ ok: boolean; status?: string; detail?: unknown }> {
|
|
215
|
+
try {
|
|
216
|
+
const data = await this.requestWithRetry<Record<string, unknown>>({ method: 'GET', url: '/api/v1/health' }, 0);
|
|
217
|
+
return { ok: true, status: String(data.status || 'healthy'), detail: data };
|
|
218
|
+
} catch (err) {
|
|
219
|
+
return { ok: false, status: 'unreachable', detail: err instanceof Error ? err.message : String(err) };
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|