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
package/src/server/plugin.ts
CHANGED
|
@@ -1,134 +1,143 @@
|
|
|
1
|
-
import { Plugin } from '@nocobase/server';
|
|
2
|
-
import { resolve } from 'path';
|
|
3
|
-
import { DocumentUnderstandingService } from './services/DocumentUnderstandingService';
|
|
4
|
-
import { defineActions } from './actions';
|
|
5
|
-
import { createDynamicPipelineToolsProvider } from './tools/document-understanding-tool';
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
private
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
//
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
this.
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
runtimeState
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
this.
|
|
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
|
-
|
|
1
|
+
import { Plugin } from '@nocobase/server';
|
|
2
|
+
import { resolve } from 'path';
|
|
3
|
+
import { DocumentUnderstandingService } from './services/DocumentUnderstandingService';
|
|
4
|
+
import { defineActions } from './actions';
|
|
5
|
+
import { createDynamicPipelineToolsProvider } from './tools/document-understanding-tool';
|
|
6
|
+
import { seedDugateEndpoints } from './dugate-seed';
|
|
7
|
+
|
|
8
|
+
type DynamicToolsProvider = ReturnType<typeof createDynamicPipelineToolsProvider>;
|
|
9
|
+
|
|
10
|
+
interface AiManagerLike {
|
|
11
|
+
toolsManager?: {
|
|
12
|
+
registerDynamicTools: (provider: DynamicToolsProvider) => void;
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
interface DocumentToolRuntimeState {
|
|
17
|
+
documentUnderstandingToolProviderRegistered?: boolean;
|
|
18
|
+
documentUnderstandingService?: DocumentUnderstandingService;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const isAiManagerLike = (manager: unknown): manager is AiManagerLike => {
|
|
22
|
+
const candidate = manager as AiManagerLike;
|
|
23
|
+
return typeof candidate?.toolsManager?.registerDynamicTools === 'function';
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export class PluginDocumentUnderstandingServer extends Plugin {
|
|
27
|
+
public service!: DocumentUnderstandingService;
|
|
28
|
+
private aiToolsRegistered = false;
|
|
29
|
+
private readonly registerAIToolsAfterStart = () => this.registerAITools();
|
|
30
|
+
|
|
31
|
+
async afterAdd() {}
|
|
32
|
+
|
|
33
|
+
async beforeLoad() {
|
|
34
|
+
await this.db.import({
|
|
35
|
+
directory: resolve(__dirname, 'collections'),
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async load() {
|
|
40
|
+
// Collections are imported in beforeLoad so database metadata exists before
|
|
41
|
+
// resources and runtime services are registered.
|
|
42
|
+
this.service = new DocumentUnderstandingService(this.app, this.db);
|
|
43
|
+
|
|
44
|
+
// Register REST actions
|
|
45
|
+
this.registerActions();
|
|
46
|
+
|
|
47
|
+
// 4. Register AI tool (graceful)
|
|
48
|
+
this.registerAITools();
|
|
49
|
+
this.app.on('afterStart', this.registerAIToolsAfterStart);
|
|
50
|
+
|
|
51
|
+
// 5. ACL
|
|
52
|
+
this.app.acl.registerSnippet({
|
|
53
|
+
name: `pm.${this.name}`,
|
|
54
|
+
actions: ['docUnderstanding:*'],
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
private registerActions() {
|
|
59
|
+
const actions = defineActions(this);
|
|
60
|
+
|
|
61
|
+
const resourceName = 'docUnderstanding';
|
|
62
|
+
this.app.resource({
|
|
63
|
+
name: resourceName,
|
|
64
|
+
actions: {
|
|
65
|
+
getConfig: actions.getConfig,
|
|
66
|
+
updateConfig: actions.updateConfig,
|
|
67
|
+
listEndpoints: actions.listEndpoints,
|
|
68
|
+
createEndpoint: actions.createEndpoint,
|
|
69
|
+
updateEndpoint: actions.updateEndpoint,
|
|
70
|
+
deleteEndpoint: actions.deleteEndpoint,
|
|
71
|
+
listPipelines: actions.listPipelines,
|
|
72
|
+
createPipeline: actions.createPipeline,
|
|
73
|
+
updatePipeline: actions.updatePipeline,
|
|
74
|
+
deletePipeline: actions.deletePipeline,
|
|
75
|
+
executePipeline: actions.executePipeline,
|
|
76
|
+
getJobStatus: actions.getJobStatus,
|
|
77
|
+
listJobs: actions.listJobs,
|
|
78
|
+
webhookCallback: actions.webhookCallback,
|
|
79
|
+
},
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
private registerAITools() {
|
|
84
|
+
if (this.aiToolsRegistered) return;
|
|
85
|
+
try {
|
|
86
|
+
const aiManager = (this.app as typeof this.app & { aiManager?: unknown }).aiManager;
|
|
87
|
+
if (!isAiManagerLike(aiManager)) {
|
|
88
|
+
this.app.logger.warn('Document Understanding: plugin-ai not available, skip AI tool registration.');
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
const runtimeState = this.app as typeof this.app & DocumentToolRuntimeState;
|
|
92
|
+
runtimeState.documentUnderstandingService = this.service;
|
|
93
|
+
if (!runtimeState.documentUnderstandingToolProviderRegistered) {
|
|
94
|
+
aiManager.toolsManager.registerDynamicTools(async (register) => {
|
|
95
|
+
const currentService = runtimeState.documentUnderstandingService;
|
|
96
|
+
if (!currentService) return;
|
|
97
|
+
await createDynamicPipelineToolsProvider(currentService)(register);
|
|
98
|
+
});
|
|
99
|
+
runtimeState.documentUnderstandingToolProviderRegistered = true;
|
|
100
|
+
}
|
|
101
|
+
this.aiToolsRegistered = true;
|
|
102
|
+
this.app.logger.info('Document Understanding: Dynamic pipeline tools provider registered.');
|
|
103
|
+
} catch (err) {
|
|
104
|
+
this.app.logger.warn('Document Understanding: Failed to register AI tools, continue without it.', err);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async afterStart() {
|
|
109
|
+
try {
|
|
110
|
+
await this.service.initialize({ recoverJobs: true });
|
|
111
|
+
} catch (err) {
|
|
112
|
+
this.app.logger.warn('Document Understanding plugin not configured yet, skip init.', err);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async install() {
|
|
117
|
+
// Seed the DUGate-compatible endpoint/pipeline catalog on first install.
|
|
118
|
+
// Subpaths stay relative so they follow the base URL in Service Config.
|
|
119
|
+
try {
|
|
120
|
+
await seedDugateEndpoints(this.db);
|
|
121
|
+
} catch (err) {
|
|
122
|
+
this.app.logger.warn('Document Understanding: DUGate seed data could not be installed.', err);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async afterEnable() {}
|
|
127
|
+
|
|
128
|
+
async afterDisable() {}
|
|
129
|
+
|
|
130
|
+
async remove() {}
|
|
131
|
+
|
|
132
|
+
async beforeStop() {
|
|
133
|
+
this.app.off?.('afterStart', this.registerAIToolsAfterStart);
|
|
134
|
+
this.app.removeListener?.('afterStart', this.registerAIToolsAfterStart);
|
|
135
|
+
this.service?.destroy();
|
|
136
|
+
const runtimeState = this.app as typeof this.app & DocumentToolRuntimeState;
|
|
137
|
+
if (runtimeState.documentUnderstandingService === this.service) {
|
|
138
|
+
runtimeState.documentUnderstandingService = undefined;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export default PluginDocumentUnderstandingServer;
|
|
@@ -1,11 +1,24 @@
|
|
|
1
1
|
import { Database } from '@nocobase/database';
|
|
2
2
|
import { ExternalApiClient } from './ExternalApiClient';
|
|
3
|
-
import { EndpointDef
|
|
3
|
+
import { EndpointDef } from '../types';
|
|
4
4
|
|
|
5
5
|
interface LoggerLike {
|
|
6
6
|
warn: (...args: unknown[]) => void;
|
|
7
7
|
}
|
|
8
8
|
|
|
9
|
+
// Lease for inline (pending/running) execution. Refreshed at the start of every
|
|
10
|
+
// pipeline step; must outlive the slowest step (endpoint timeout x retries).
|
|
11
|
+
export const JOB_RUN_LEASE_MS = 10 * 60 * 1000;
|
|
12
|
+
// Lease for polling jobs. Refreshed on every poll tick, so it only needs to
|
|
13
|
+
// outlive a few missed ticks before another node may adopt the job.
|
|
14
|
+
const JOB_POLL_LEASE_MIN_MS = 60 * 1000;
|
|
15
|
+
|
|
16
|
+
export function pollLeaseMs(pollInterval?: number): number {
|
|
17
|
+
return Math.max((pollInterval || 5000) * 3, JOB_POLL_LEASE_MIN_MS);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const JOBS_COLLECTION = 'doc_understanding_jobs';
|
|
21
|
+
|
|
9
22
|
export class AsyncJobManager {
|
|
10
23
|
private db: Database;
|
|
11
24
|
private apiClient: ExternalApiClient;
|
|
@@ -13,6 +26,7 @@ export class AsyncJobManager {
|
|
|
13
26
|
private onJobComplete: (jobId: number, result: any) => Promise<void>;
|
|
14
27
|
private onJobError: (jobId: number, error: string) => Promise<void>;
|
|
15
28
|
private logger: LoggerLike;
|
|
29
|
+
private nodeId: string;
|
|
16
30
|
|
|
17
31
|
constructor(
|
|
18
32
|
db: Database,
|
|
@@ -22,12 +36,14 @@ export class AsyncJobManager {
|
|
|
22
36
|
onJobError: (jobId: number, error: string) => Promise<void>;
|
|
23
37
|
},
|
|
24
38
|
logger: LoggerLike,
|
|
39
|
+
nodeId: string,
|
|
25
40
|
) {
|
|
26
41
|
this.db = db;
|
|
27
42
|
this.apiClient = apiClient;
|
|
28
43
|
this.onJobComplete = callbacks.onJobComplete;
|
|
29
44
|
this.onJobError = callbacks.onJobError;
|
|
30
45
|
this.logger = logger;
|
|
46
|
+
this.nodeId = nodeId;
|
|
31
47
|
}
|
|
32
48
|
|
|
33
49
|
async startPolling(
|
|
@@ -52,8 +68,16 @@ export class AsyncJobManager {
|
|
|
52
68
|
return;
|
|
53
69
|
}
|
|
54
70
|
|
|
71
|
+
// Renew our lease; if the row no longer matches (job finished, or another
|
|
72
|
+
// node adopted it after our lease expired) stop polling immediately.
|
|
73
|
+
if (!(await this.refreshLease(jobId, endpoint))) {
|
|
74
|
+
this.stopPolling(jobId);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
|
|
55
78
|
const pollResultSubpath = endpoint.pollResultSubpath;
|
|
56
79
|
if (!pollResultSubpath) {
|
|
80
|
+
this.stopPolling(jobId);
|
|
57
81
|
await this.onJobError(jobId, 'Polling result subpath is not configured');
|
|
58
82
|
return;
|
|
59
83
|
}
|
|
@@ -95,61 +119,103 @@ export class AsyncJobManager {
|
|
|
95
119
|
this.intervals.set(jobId, timer);
|
|
96
120
|
}
|
|
97
121
|
|
|
122
|
+
private async refreshLease(jobId: number, endpoint: EndpointDef): Promise<boolean> {
|
|
123
|
+
const jobsRepo = this.db.getRepository<any>(JOBS_COLLECTION);
|
|
124
|
+
const updated = await jobsRepo.update({
|
|
125
|
+
filter: { id: jobId, status: 'polling', ownedBy: this.nodeId },
|
|
126
|
+
values: { leaseExpiresAt: new Date(Date.now() + pollLeaseMs(endpoint.pollInterval)) },
|
|
127
|
+
});
|
|
128
|
+
return Array.isArray(updated) ? updated.length > 0 : Boolean(updated);
|
|
129
|
+
}
|
|
130
|
+
|
|
98
131
|
/**
|
|
99
|
-
*
|
|
132
|
+
* Fail pending/running jobs that can no longer be executing. First the jobs
|
|
133
|
+
* this node owned (in-memory execution state is lost across a restart), then
|
|
134
|
+
* any remaining job whose owner lease expired. Rows without a lease predate
|
|
135
|
+
* ownership tracking and are treated as orphaned too.
|
|
100
136
|
*/
|
|
101
|
-
async
|
|
102
|
-
const jobsRepo = this.db.getRepository<any>(
|
|
103
|
-
const
|
|
137
|
+
async failOrphanedActiveJobs(): Promise<void> {
|
|
138
|
+
const jobsRepo = this.db.getRepository<any>(JOBS_COLLECTION);
|
|
139
|
+
const now = new Date();
|
|
140
|
+
|
|
141
|
+
await jobsRepo.update({
|
|
142
|
+
filter: { status: { $in: ['pending', 'running'] }, ownedBy: this.nodeId },
|
|
143
|
+
values: { status: 'failed', error: 'Server restarted during execution', completedAt: now },
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
await jobsRepo.update({
|
|
104
147
|
filter: {
|
|
105
|
-
status: ['pending', 'running'],
|
|
148
|
+
status: { $in: ['pending', 'running'] },
|
|
149
|
+
$or: [{ leaseExpiresAt: { $lt: now } }, { leaseExpiresAt: null }],
|
|
106
150
|
},
|
|
151
|
+
values: { status: 'failed', error: 'Job lease expired before completion', completedAt: now },
|
|
107
152
|
});
|
|
108
|
-
|
|
109
|
-
for (const job of stuckJobs) {
|
|
110
|
-
await jobsRepo.update({
|
|
111
|
-
filterByTk: job.id,
|
|
112
|
-
values: {
|
|
113
|
-
status: 'failed',
|
|
114
|
-
error: 'Server restarted during execution',
|
|
115
|
-
completedAt: new Date(),
|
|
116
|
-
},
|
|
117
|
-
});
|
|
118
|
-
}
|
|
119
153
|
}
|
|
120
154
|
|
|
121
155
|
/**
|
|
122
|
-
*
|
|
123
|
-
*
|
|
156
|
+
* Re-adopt 'polling' jobs whose owner can no longer be polling them: jobs this
|
|
157
|
+
* node owned before a restart, jobs whose lease expired, and legacy rows without
|
|
158
|
+
* ownership. Webhook-mode jobs are skipped — nothing polls them, and any node
|
|
159
|
+
* can process the webhook when it arrives.
|
|
124
160
|
*/
|
|
125
|
-
async
|
|
126
|
-
const jobsRepo = this.db.getRepository<any>(
|
|
127
|
-
const
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
161
|
+
async adoptOrphanedPollingJobs(): Promise<void> {
|
|
162
|
+
const jobsRepo = this.db.getRepository<any>(JOBS_COLLECTION);
|
|
163
|
+
const now = new Date();
|
|
164
|
+
const candidates = await jobsRepo.find({
|
|
165
|
+
filter: {
|
|
166
|
+
status: 'polling',
|
|
167
|
+
$or: [{ ownedBy: this.nodeId }, { leaseExpiresAt: { $lt: now } }, { ownedBy: null }],
|
|
168
|
+
},
|
|
169
|
+
});
|
|
131
170
|
|
|
132
|
-
|
|
133
|
-
const
|
|
134
|
-
const
|
|
171
|
+
for (const job of candidates) {
|
|
172
|
+
const externalTaskIds = (job.externalTaskIds || {}) as Record<string, string>;
|
|
173
|
+
const stepKey = String(job.currentStep);
|
|
174
|
+
const taskId = externalTaskIds[stepKey];
|
|
135
175
|
if (!taskId) continue;
|
|
136
176
|
|
|
137
|
-
// We need the endpoint definition for this step
|
|
138
177
|
const pipelineRepo = this.db.getRepository('doc_understanding_pipelines');
|
|
139
178
|
const pipeline = await pipelineRepo.findOne({
|
|
140
179
|
filter: { id: job.pipelineId },
|
|
141
180
|
appends: ['steps', 'steps.endpoint'],
|
|
142
181
|
});
|
|
143
|
-
|
|
144
182
|
if (!pipeline) continue;
|
|
145
183
|
|
|
146
|
-
const
|
|
184
|
+
const steps = ((pipeline as any).steps || []) as Array<{ stepOrder: number; endpoint?: EndpointDef }>;
|
|
185
|
+
const step = steps.find((s) => s.stepOrder === job.currentStep);
|
|
147
186
|
if (!step?.endpoint || step.endpoint.executionMode !== 'polling') continue;
|
|
148
187
|
|
|
149
|
-
await this.
|
|
188
|
+
if (await this.claimJobForPolling(job.id, step.endpoint)) {
|
|
189
|
+
await this.startPolling(job.id, step.endpoint, taskId);
|
|
190
|
+
}
|
|
150
191
|
}
|
|
151
192
|
}
|
|
152
193
|
|
|
194
|
+
private async claimJobForPolling(jobId: number, endpoint: EndpointDef): Promise<boolean> {
|
|
195
|
+
return this.db.sequelize.transaction(async (transaction: { LOCK: { UPDATE: string } }): Promise<boolean> => {
|
|
196
|
+
const jobsRepo = this.db.getRepository<any>(JOBS_COLLECTION);
|
|
197
|
+
const row = await jobsRepo.findOne({ filterByTk: jobId, transaction, lock: transaction.LOCK.UPDATE });
|
|
198
|
+
if (!row) return false;
|
|
199
|
+
if (String(row.get('status')) !== 'polling') return false;
|
|
200
|
+
|
|
201
|
+
const owner = row.get('ownedBy') as string | null;
|
|
202
|
+
const lease = row.get('leaseExpiresAt') as Date | string | null;
|
|
203
|
+
const leaseValid = lease != null && new Date(lease).getTime() > Date.now();
|
|
204
|
+
// A different node still owns the job with a valid lease: leave it alone.
|
|
205
|
+
if (owner !== this.nodeId && leaseValid) return false;
|
|
206
|
+
|
|
207
|
+
await jobsRepo.update({
|
|
208
|
+
filterByTk: jobId,
|
|
209
|
+
values: {
|
|
210
|
+
ownedBy: this.nodeId,
|
|
211
|
+
leaseExpiresAt: new Date(Date.now() + pollLeaseMs(endpoint.pollInterval)),
|
|
212
|
+
},
|
|
213
|
+
transaction,
|
|
214
|
+
});
|
|
215
|
+
return true;
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
|
|
153
219
|
stopPolling(jobId: number) {
|
|
154
220
|
const timer = this.intervals.get(jobId);
|
|
155
221
|
if (timer) {
|
|
@@ -15,11 +15,17 @@ export class DocumentUnderstandingService {
|
|
|
15
15
|
private initialized = false;
|
|
16
16
|
private startupRecoveryCompleted = false;
|
|
17
17
|
private initializationPromise?: Promise<void>;
|
|
18
|
+
private maintenanceTimer?: NodeJS.Timeout;
|
|
19
|
+
// Unique per process; used as the job owner so other nodes can tell orphaned
|
|
20
|
+
// jobs apart from jobs that are still being processed.
|
|
21
|
+
private readonly nodeId: string;
|
|
18
22
|
private static readonly HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
23
|
+
private static readonly MAINTENANCE_INTERVAL_MS = 30_000;
|
|
19
24
|
|
|
20
25
|
constructor(app: Application, db: Database) {
|
|
21
26
|
this.app = app;
|
|
22
27
|
this.db = db;
|
|
28
|
+
this.nodeId = `${app?.name || 'app'}:${process.pid}:${crypto.randomUUID()}`;
|
|
23
29
|
}
|
|
24
30
|
|
|
25
31
|
async initialize(options: { recoverJobs?: boolean } = {}): Promise<void> {
|
|
@@ -43,6 +49,7 @@ export class DocumentUnderstandingService {
|
|
|
43
49
|
const config = await this.ensureConfig();
|
|
44
50
|
|
|
45
51
|
this.jobManager?.destroy();
|
|
52
|
+
this.stopMaintenance();
|
|
46
53
|
this.apiClient = new ExternalApiClient(config);
|
|
47
54
|
this.jobManager = new AsyncJobManager(
|
|
48
55
|
this.db,
|
|
@@ -60,19 +67,57 @@ export class DocumentUnderstandingService {
|
|
|
60
67
|
},
|
|
61
68
|
},
|
|
62
69
|
this.app.logger,
|
|
70
|
+
this.nodeId,
|
|
63
71
|
);
|
|
64
72
|
|
|
65
|
-
this.pipelineExecutor = new PipelineExecutor(
|
|
73
|
+
this.pipelineExecutor = new PipelineExecutor(
|
|
74
|
+
this.db,
|
|
75
|
+
this.apiClient,
|
|
76
|
+
this.jobManager,
|
|
77
|
+
this.app.logger,
|
|
78
|
+
this.nodeId,
|
|
79
|
+
);
|
|
66
80
|
|
|
67
81
|
if (recoverJobs && !this.startupRecoveryCompleted) {
|
|
68
|
-
await this.
|
|
69
|
-
await this.jobManager.recoverPollingJobs();
|
|
82
|
+
await this.maintainJobs();
|
|
70
83
|
this.startupRecoveryCompleted = true;
|
|
71
84
|
}
|
|
85
|
+
this.startMaintenance();
|
|
72
86
|
|
|
73
87
|
this.initialized = true;
|
|
74
88
|
}
|
|
75
89
|
|
|
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
|
+
async maintainJobs(): Promise<void> {
|
|
96
|
+
if (!this.jobManager) return;
|
|
97
|
+
try {
|
|
98
|
+
await this.jobManager.failOrphanedActiveJobs();
|
|
99
|
+
await this.jobManager.adoptOrphanedPollingJobs();
|
|
100
|
+
} catch (err) {
|
|
101
|
+
this.app.logger.warn('Document Understanding: job maintenance sweep failed.', err);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
private startMaintenance(): void {
|
|
106
|
+
this.stopMaintenance();
|
|
107
|
+
this.maintenanceTimer = setInterval(() => {
|
|
108
|
+
this.maintainJobs();
|
|
109
|
+
}, DocumentUnderstandingService.MAINTENANCE_INTERVAL_MS);
|
|
110
|
+
// The sweep must never keep the process alive on shutdown.
|
|
111
|
+
this.maintenanceTimer.unref?.();
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
private stopMaintenance(): void {
|
|
115
|
+
if (this.maintenanceTimer) {
|
|
116
|
+
clearInterval(this.maintenanceTimer);
|
|
117
|
+
this.maintenanceTimer = undefined;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
76
121
|
private async ensureConfig(): Promise<ServiceConfig> {
|
|
77
122
|
const configRepo = this.db.getRepository<any>('doc_understanding_config');
|
|
78
123
|
let config = await configRepo.findOne();
|
|
@@ -126,6 +171,7 @@ export class DocumentUnderstandingService {
|
|
|
126
171
|
}
|
|
127
172
|
|
|
128
173
|
destroy(): void {
|
|
174
|
+
this.stopMaintenance();
|
|
129
175
|
this.jobManager?.destroy();
|
|
130
176
|
this.initialized = false;
|
|
131
177
|
this.startupRecoveryCompleted = false;
|
|
@@ -249,7 +295,7 @@ export class DocumentUnderstandingService {
|
|
|
249
295
|
}
|
|
250
296
|
}
|
|
251
297
|
|
|
252
|
-
const taskId = payload.task_id;
|
|
298
|
+
const taskId = payload.task_id ?? payload.operation_id;
|
|
253
299
|
const result = payload.result;
|
|
254
300
|
if (!taskId) throw new Error('Webhook missing task_id');
|
|
255
301
|
|
|
@@ -67,6 +67,36 @@ export class ExternalApiClient {
|
|
|
67
67
|
return normalized;
|
|
68
68
|
}
|
|
69
69
|
|
|
70
|
+
/**
|
|
71
|
+
* Appends the endpoint discriminator (if configured) to the request body so
|
|
72
|
+
* DUGate-style gateways can route to the correct sub-case/profile.
|
|
73
|
+
*/
|
|
74
|
+
private withDiscriminator(endpoint: EndpointDef, body?: Record<string, any>): Record<string, any> | undefined {
|
|
75
|
+
const field = endpoint.discriminatorField?.trim();
|
|
76
|
+
if (!field || !endpoint.discriminatorValue) {
|
|
77
|
+
return body;
|
|
78
|
+
}
|
|
79
|
+
const merged: Record<string, any> = { ...(body || {}) };
|
|
80
|
+
if (merged[field] !== undefined && merged[field] !== endpoint.discriminatorValue) {
|
|
81
|
+
throw new Error(
|
|
82
|
+
`Discriminator field '${field}' is locked by endpoint configuration (expected '${endpoint.discriminatorValue}', got '${merged[field]}').`,
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
merged[field] = endpoint.discriminatorValue;
|
|
86
|
+
return merged;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Appends the DUGate sync flag (?sync=true) for endpoints configured with
|
|
91
|
+
* `syncQueryParam`. Kept separate from other query parameters so GET/DELETE
|
|
92
|
+
* params in `body` are not polluted by the discriminator logic.
|
|
93
|
+
*/
|
|
94
|
+
private syncQueryParams(endpoint: EndpointDef): Record<string, string> {
|
|
95
|
+
const param = endpoint.syncQueryParam?.trim();
|
|
96
|
+
if (!param) return {};
|
|
97
|
+
return { [param]: 'true' };
|
|
98
|
+
}
|
|
99
|
+
|
|
70
100
|
async call(options: ApiCallOptions): Promise<{ status: number; data: any; headers: any }> {
|
|
71
101
|
const { endpoint, body, files, overrideHeaders } = options;
|
|
72
102
|
|
|
@@ -82,8 +112,9 @@ export class ExternalApiClient {
|
|
|
82
112
|
|
|
83
113
|
if (endpoint.fileInputMode === 'multipart' && files && files.length > 0) {
|
|
84
114
|
const formData = new FormData();
|
|
85
|
-
|
|
86
|
-
|
|
115
|
+
const bodyWithDiscriminator = this.withDiscriminator(endpoint, body);
|
|
116
|
+
if (bodyWithDiscriminator) {
|
|
117
|
+
for (const [key, value] of Object.entries(bodyWithDiscriminator)) {
|
|
87
118
|
formData.append(key, typeof value === 'object' ? JSON.stringify(value) : String(value));
|
|
88
119
|
}
|
|
89
120
|
}
|
|
@@ -107,18 +138,22 @@ export class ExternalApiClient {
|
|
|
107
138
|
mimeType: f.mimeType,
|
|
108
139
|
};
|
|
109
140
|
}
|
|
110
|
-
requestData = { ...body, _files: base64Files };
|
|
141
|
+
requestData = { ...this.withDiscriminator(endpoint, body), _files: base64Files };
|
|
111
142
|
headers['Content-Type'] = 'application/json';
|
|
112
143
|
} else {
|
|
144
|
+
requestData = this.withDiscriminator(endpoint, body);
|
|
113
145
|
headers['Content-Type'] = 'application/json';
|
|
114
146
|
}
|
|
115
147
|
|
|
116
148
|
try {
|
|
149
|
+
const isBodyless = ['get', 'delete'].includes(method);
|
|
117
150
|
const response: AxiosResponse = await this.client.request({
|
|
118
151
|
url,
|
|
119
152
|
method,
|
|
120
|
-
data:
|
|
121
|
-
params:
|
|
153
|
+
data: isBodyless ? undefined : requestData,
|
|
154
|
+
params: isBodyless
|
|
155
|
+
? { ...(requestData || {}), ...this.syncQueryParams(endpoint) }
|
|
156
|
+
: this.syncQueryParams(endpoint),
|
|
122
157
|
headers,
|
|
123
158
|
});
|
|
124
159
|
|