plugin-document-understanding 1.1.13 → 1.1.15
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/README.md +29 -29
- package/client-v2.d.ts +2 -2
- package/client-v2.js +1 -1
- package/dist/client-v2/index.js +1 -1
- package/dist/externalVersion.js +8 -7
- package/dist/locale/en-US.json +3 -1
- package/dist/locale/zh-CN.json +3 -1
- package/dist/node_modules/form-data/lib/form_data.js +2 -2
- package/dist/node_modules/form-data/node_modules/es-define-property/.eslintrc +13 -0
- package/dist/node_modules/form-data/node_modules/es-define-property/.github/FUNDING.yml +12 -0
- package/dist/node_modules/form-data/node_modules/es-define-property/.nycrc +9 -0
- package/dist/node_modules/form-data/node_modules/es-define-property/index.d.ts +3 -0
- package/dist/node_modules/form-data/node_modules/es-define-property/index.js +14 -0
- package/dist/node_modules/form-data/node_modules/es-define-property/package.json +81 -0
- package/dist/node_modules/form-data/node_modules/es-define-property/test/index.js +56 -0
- package/dist/node_modules/form-data/node_modules/es-object-atoms/.eslintrc +16 -0
- package/dist/node_modules/form-data/node_modules/es-object-atoms/.github/FUNDING.yml +12 -0
- package/dist/node_modules/form-data/node_modules/es-object-atoms/RequireObjectCoercible.d.ts +3 -0
- package/dist/node_modules/form-data/node_modules/es-object-atoms/RequireObjectCoercible.js +11 -0
- package/dist/node_modules/form-data/node_modules/es-object-atoms/ToObject.d.ts +7 -0
- package/dist/node_modules/form-data/node_modules/es-object-atoms/ToObject.js +10 -0
- package/dist/node_modules/form-data/node_modules/es-object-atoms/index.d.ts +3 -0
- package/dist/node_modules/form-data/node_modules/es-object-atoms/index.js +4 -0
- package/dist/node_modules/form-data/node_modules/es-object-atoms/isObject.d.ts +3 -0
- package/dist/node_modules/form-data/node_modules/es-object-atoms/isObject.js +6 -0
- package/dist/node_modules/form-data/node_modules/es-object-atoms/package.json +80 -0
- package/dist/node_modules/form-data/node_modules/es-object-atoms/test/index.js +38 -0
- package/dist/node_modules/form-data/node_modules/es-set-tostringtag/.eslintrc +13 -0
- package/dist/node_modules/form-data/node_modules/es-set-tostringtag/.nycrc +9 -0
- package/dist/node_modules/form-data/node_modules/es-set-tostringtag/index.d.ts +10 -0
- package/dist/node_modules/form-data/node_modules/es-set-tostringtag/index.js +35 -0
- package/dist/node_modules/form-data/node_modules/es-set-tostringtag/node_modules/hasown/.eslintrc +5 -0
- package/dist/node_modules/form-data/node_modules/es-set-tostringtag/node_modules/hasown/.github/FUNDING.yml +12 -0
- package/dist/node_modules/form-data/node_modules/es-set-tostringtag/node_modules/hasown/.nycrc +13 -0
- package/dist/node_modules/form-data/node_modules/es-set-tostringtag/node_modules/hasown/index.d.ts +3 -0
- package/dist/node_modules/form-data/node_modules/es-set-tostringtag/node_modules/hasown/index.js +8 -0
- package/dist/node_modules/form-data/node_modules/es-set-tostringtag/node_modules/hasown/package.json +92 -0
- package/dist/node_modules/form-data/node_modules/es-set-tostringtag/package.json +78 -0
- package/dist/node_modules/form-data/node_modules/es-set-tostringtag/test/index.js +85 -0
- package/dist/node_modules/form-data/node_modules/get-intrinsic/.eslintrc +42 -0
- package/dist/node_modules/form-data/node_modules/get-intrinsic/.github/FUNDING.yml +12 -0
- package/dist/node_modules/form-data/node_modules/get-intrinsic/.nycrc +9 -0
- package/dist/node_modules/form-data/node_modules/get-intrinsic/index.js +378 -0
- package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/has-symbols/.eslintrc +11 -0
- package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/has-symbols/.github/FUNDING.yml +12 -0
- package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/has-symbols/.nycrc +9 -0
- package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/has-symbols/index.d.ts +3 -0
- package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/has-symbols/index.js +14 -0
- package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/has-symbols/package.json +111 -0
- package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/has-symbols/shams.d.ts +3 -0
- package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/has-symbols/shams.js +45 -0
- package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/has-symbols/test/index.js +22 -0
- package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/has-symbols/test/shams/core-js.js +29 -0
- package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/has-symbols/test/shams/get-own-property-symbols.js +29 -0
- package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/has-symbols/test/tests.js +58 -0
- package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/hasown/.eslintrc +5 -0
- package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/hasown/.github/FUNDING.yml +12 -0
- package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/hasown/.nycrc +13 -0
- package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/hasown/index.d.ts +3 -0
- package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/hasown/index.js +8 -0
- package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/hasown/package.json +92 -0
- package/dist/node_modules/form-data/node_modules/get-intrinsic/package.json +97 -0
- package/dist/node_modules/form-data/node_modules/get-intrinsic/test/GetIntrinsic.js +274 -0
- package/dist/node_modules/form-data/node_modules/gopd/.eslintrc +16 -0
- package/dist/node_modules/form-data/node_modules/gopd/.github/FUNDING.yml +12 -0
- package/dist/node_modules/form-data/node_modules/gopd/gOPD.d.ts +1 -0
- package/dist/node_modules/form-data/node_modules/gopd/gOPD.js +4 -0
- package/dist/node_modules/form-data/node_modules/gopd/index.d.ts +5 -0
- package/dist/node_modules/form-data/node_modules/gopd/index.js +15 -0
- package/dist/node_modules/form-data/node_modules/gopd/package.json +77 -0
- package/dist/node_modules/form-data/node_modules/gopd/test/index.js +36 -0
- package/dist/node_modules/form-data/node_modules/has-tostringtag/.eslintrc +5 -0
- package/dist/node_modules/form-data/node_modules/has-tostringtag/.github/FUNDING.yml +12 -0
- package/dist/node_modules/form-data/node_modules/has-tostringtag/.nycrc +13 -0
- package/dist/node_modules/form-data/node_modules/has-tostringtag/index.d.ts +3 -0
- package/dist/node_modules/form-data/node_modules/has-tostringtag/index.js +8 -0
- package/dist/node_modules/form-data/node_modules/has-tostringtag/package.json +108 -0
- package/dist/node_modules/form-data/node_modules/has-tostringtag/shams.d.ts +3 -0
- package/dist/node_modules/form-data/node_modules/has-tostringtag/shams.js +8 -0
- package/dist/node_modules/form-data/node_modules/has-tostringtag/test/index.js +21 -0
- package/dist/node_modules/form-data/node_modules/has-tostringtag/test/shams/core-js.js +31 -0
- package/dist/node_modules/form-data/node_modules/has-tostringtag/test/shams/get-own-property-symbols.js +30 -0
- package/dist/node_modules/form-data/node_modules/has-tostringtag/test/tests.js +15 -0
- package/dist/node_modules/form-data/node_modules/hasown/.github/FUNDING.yml +12 -0
- package/dist/node_modules/form-data/node_modules/hasown/.nycrc +13 -0
- package/dist/node_modules/form-data/node_modules/hasown/index.d.ts +3 -0
- package/dist/node_modules/form-data/node_modules/hasown/index.js +8 -0
- package/dist/node_modules/form-data/node_modules/hasown/package.json +91 -0
- package/dist/node_modules/form-data/package.json +1 -1
- package/dist/node_modules/mime-types/index.js +3 -3
- package/dist/node_modules/mime-types/package.json +1 -1
- package/dist/server/actions.js +45 -35
- package/package.json +57 -46
- package/src/client/index.tsx +15 -15
- package/src/client-v2/components/EndpointsTab.tsx +578 -578
- package/src/client-v2/components/JobsTab.tsx +294 -294
- package/src/client-v2/components/PipelinesTab.tsx +962 -962
- package/src/client-v2/components/PluginSettings.tsx +50 -50
- package/src/client-v2/components/ServiceConfigTab.tsx +139 -139
- package/src/client-v2/index.tsx +1 -1
- package/src/client-v2/locale.ts +21 -21
- package/src/client-v2/models/index.ts +12 -12
- package/src/client-v2/plugin.tsx +31 -21
- package/src/client-v2/types.ts +32 -32
- package/src/index.ts +2 -2
- package/src/locale/en-US.json +3 -1
- package/src/locale/zh-CN.json +3 -1
- package/src/server/__tests__/actions.test.ts +121 -98
- package/src/server/__tests__/cluster-safety.test.ts +259 -259
- package/src/server/__tests__/document-understanding-service.test.ts +82 -82
- package/src/server/__tests__/dugate-integration.test.ts +221 -221
- package/src/server/__tests__/smoke.test.ts +78 -55
- package/src/server/__tests__/upload-security.test.ts +128 -0
- package/src/server/actions.ts +53 -51
- package/src/server/collections/config.ts +18 -18
- package/src/server/collections/endpoints.ts +33 -33
- package/src/server/collections/jobs.ts +42 -42
- package/src/server/collections/pipeline-steps.ts +27 -27
- package/src/server/collections/pipelines.ts +19 -19
- package/src/server/dugate-seed.ts +491 -491
- package/src/server/index.ts +1 -1
- package/src/server/plugin.ts +143 -143
- package/src/server/services/AsyncJobManager.ts +238 -238
- package/src/server/services/DocumentUnderstandingService.ts +332 -332
- package/src/server/services/ExternalApiClient.ts +178 -178
- package/src/server/services/PipelineExecutor.ts +593 -593
- package/src/server/tools/document-understanding-tool.ts +181 -181
- package/src/server/types.ts +90 -90
|
@@ -1,238 +1,238 @@
|
|
|
1
|
-
import { Database } from '@nocobase/database';
|
|
2
|
-
import { ExternalApiClient } from './ExternalApiClient';
|
|
3
|
-
import { EndpointDef } from '../types';
|
|
4
|
-
|
|
5
|
-
interface LoggerLike {
|
|
6
|
-
warn: (...args: unknown[]) => void;
|
|
7
|
-
}
|
|
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
|
-
|
|
22
|
-
export class AsyncJobManager {
|
|
23
|
-
private db: Database;
|
|
24
|
-
private apiClient: ExternalApiClient;
|
|
25
|
-
private intervals: Map<number, NodeJS.Timeout> = new Map();
|
|
26
|
-
private onJobComplete: (jobId: number, result: any) => Promise<void>;
|
|
27
|
-
private onJobError: (jobId: number, error: string) => Promise<void>;
|
|
28
|
-
private logger: LoggerLike;
|
|
29
|
-
private nodeId: string;
|
|
30
|
-
|
|
31
|
-
constructor(
|
|
32
|
-
db: Database,
|
|
33
|
-
apiClient: ExternalApiClient,
|
|
34
|
-
callbacks: {
|
|
35
|
-
onJobComplete: (jobId: number, result: any) => Promise<void>;
|
|
36
|
-
onJobError: (jobId: number, error: string) => Promise<void>;
|
|
37
|
-
},
|
|
38
|
-
logger: LoggerLike,
|
|
39
|
-
nodeId: string,
|
|
40
|
-
) {
|
|
41
|
-
this.db = db;
|
|
42
|
-
this.apiClient = apiClient;
|
|
43
|
-
this.onJobComplete = callbacks.onJobComplete;
|
|
44
|
-
this.onJobError = callbacks.onJobError;
|
|
45
|
-
this.logger = logger;
|
|
46
|
-
this.nodeId = nodeId;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
async startPolling(
|
|
50
|
-
jobId: number,
|
|
51
|
-
endpoint: EndpointDef,
|
|
52
|
-
taskId: string,
|
|
53
|
-
customInterval?: number,
|
|
54
|
-
customTimeout?: number,
|
|
55
|
-
): Promise<void> {
|
|
56
|
-
// Don't start duplicate polling for same job
|
|
57
|
-
if (this.intervals.has(jobId)) return;
|
|
58
|
-
|
|
59
|
-
const interval = customInterval || endpoint.pollInterval || 5000;
|
|
60
|
-
const timeout = customTimeout || endpoint.pollTimeout || 300000;
|
|
61
|
-
const startTime = Date.now();
|
|
62
|
-
|
|
63
|
-
const timer = setInterval(async () => {
|
|
64
|
-
try {
|
|
65
|
-
if (Date.now() - startTime > timeout) {
|
|
66
|
-
this.stopPolling(jobId);
|
|
67
|
-
await this.onJobError(jobId, 'Polling timeout exceeded');
|
|
68
|
-
return;
|
|
69
|
-
}
|
|
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
|
-
|
|
78
|
-
const pollResultSubpath = endpoint.pollResultSubpath;
|
|
79
|
-
if (!pollResultSubpath) {
|
|
80
|
-
this.stopPolling(jobId);
|
|
81
|
-
await this.onJobError(jobId, 'Polling result subpath is not configured');
|
|
82
|
-
return;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
const url = pollResultSubpath.replace('{taskId}', taskId);
|
|
86
|
-
const response = await this.apiClient.get(url);
|
|
87
|
-
|
|
88
|
-
// Smart completion check: use pollStatusField if configured
|
|
89
|
-
if (endpoint.pollStatusField) {
|
|
90
|
-
const statusValue = this.getNestedValue(response, endpoint.pollStatusField);
|
|
91
|
-
const completedValue = endpoint.pollCompletedValue || 'completed';
|
|
92
|
-
if (String(statusValue) === completedValue) {
|
|
93
|
-
const resultValue = endpoint.pollResultField
|
|
94
|
-
? this.getNestedValue(response, endpoint.pollResultField)
|
|
95
|
-
: response;
|
|
96
|
-
this.stopPolling(jobId);
|
|
97
|
-
await this.onJobComplete(jobId, resultValue);
|
|
98
|
-
} else if (statusValue === 'failed' || statusValue === 'error') {
|
|
99
|
-
this.stopPolling(jobId);
|
|
100
|
-
await this.onJobError(jobId, `External task failed with status: ${statusValue}`);
|
|
101
|
-
}
|
|
102
|
-
// Otherwise still pending, continue polling
|
|
103
|
-
} else {
|
|
104
|
-
// Fallback: check if result field has non-null value
|
|
105
|
-
const resultValue = endpoint.pollResultField
|
|
106
|
-
? this.getNestedValue(response, endpoint.pollResultField)
|
|
107
|
-
: response;
|
|
108
|
-
if (resultValue !== undefined && resultValue !== null) {
|
|
109
|
-
this.stopPolling(jobId);
|
|
110
|
-
await this.onJobComplete(jobId, resultValue);
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
} catch (err) {
|
|
114
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
115
|
-
this.logger.warn(`Polling error for job ${jobId}: ${message}`);
|
|
116
|
-
}
|
|
117
|
-
}, interval);
|
|
118
|
-
|
|
119
|
-
this.intervals.set(jobId, timer);
|
|
120
|
-
}
|
|
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
|
-
|
|
131
|
-
/**
|
|
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.
|
|
136
|
-
*/
|
|
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({
|
|
147
|
-
filter: {
|
|
148
|
-
status: { $in: ['pending', 'running'] },
|
|
149
|
-
$or: [{ leaseExpiresAt: { $lt: now } }, { leaseExpiresAt: null }],
|
|
150
|
-
},
|
|
151
|
-
values: { status: 'failed', error: 'Job lease expired before completion', completedAt: now },
|
|
152
|
-
});
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
/**
|
|
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.
|
|
160
|
-
*/
|
|
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
|
-
});
|
|
170
|
-
|
|
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];
|
|
175
|
-
if (!taskId) continue;
|
|
176
|
-
|
|
177
|
-
const pipelineRepo = this.db.getRepository('doc_understanding_pipelines');
|
|
178
|
-
const pipeline = await pipelineRepo.findOne({
|
|
179
|
-
filter: { id: job.pipelineId },
|
|
180
|
-
appends: ['steps', 'steps.endpoint'],
|
|
181
|
-
});
|
|
182
|
-
if (!pipeline) continue;
|
|
183
|
-
|
|
184
|
-
const steps = ((pipeline as any).steps || []) as Array<{ stepOrder: number; endpoint?: EndpointDef }>;
|
|
185
|
-
const step = steps.find((s) => s.stepOrder === job.currentStep);
|
|
186
|
-
if (!step?.endpoint || step.endpoint.executionMode !== 'polling') continue;
|
|
187
|
-
|
|
188
|
-
if (await this.claimJobForPolling(job.id, step.endpoint)) {
|
|
189
|
-
await this.startPolling(job.id, step.endpoint, taskId);
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
}
|
|
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
|
-
|
|
219
|
-
stopPolling(jobId: number) {
|
|
220
|
-
const timer = this.intervals.get(jobId);
|
|
221
|
-
if (timer) {
|
|
222
|
-
clearInterval(timer);
|
|
223
|
-
this.intervals.delete(jobId);
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
destroy() {
|
|
228
|
-
for (const timer of this.intervals.values()) {
|
|
229
|
-
clearInterval(timer);
|
|
230
|
-
}
|
|
231
|
-
this.intervals.clear();
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
private getNestedValue(obj: any, path: string): any {
|
|
235
|
-
if (!obj) return obj;
|
|
236
|
-
return path.split('.').reduce((acc, part) => acc && acc[part], obj);
|
|
237
|
-
}
|
|
238
|
-
}
|
|
1
|
+
import { Database } from '@nocobase/database';
|
|
2
|
+
import { ExternalApiClient } from './ExternalApiClient';
|
|
3
|
+
import { EndpointDef } from '../types';
|
|
4
|
+
|
|
5
|
+
interface LoggerLike {
|
|
6
|
+
warn: (...args: unknown[]) => void;
|
|
7
|
+
}
|
|
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
|
+
|
|
22
|
+
export class AsyncJobManager {
|
|
23
|
+
private db: Database;
|
|
24
|
+
private apiClient: ExternalApiClient;
|
|
25
|
+
private intervals: Map<number, NodeJS.Timeout> = new Map();
|
|
26
|
+
private onJobComplete: (jobId: number, result: any) => Promise<void>;
|
|
27
|
+
private onJobError: (jobId: number, error: string) => Promise<void>;
|
|
28
|
+
private logger: LoggerLike;
|
|
29
|
+
private nodeId: string;
|
|
30
|
+
|
|
31
|
+
constructor(
|
|
32
|
+
db: Database,
|
|
33
|
+
apiClient: ExternalApiClient,
|
|
34
|
+
callbacks: {
|
|
35
|
+
onJobComplete: (jobId: number, result: any) => Promise<void>;
|
|
36
|
+
onJobError: (jobId: number, error: string) => Promise<void>;
|
|
37
|
+
},
|
|
38
|
+
logger: LoggerLike,
|
|
39
|
+
nodeId: string,
|
|
40
|
+
) {
|
|
41
|
+
this.db = db;
|
|
42
|
+
this.apiClient = apiClient;
|
|
43
|
+
this.onJobComplete = callbacks.onJobComplete;
|
|
44
|
+
this.onJobError = callbacks.onJobError;
|
|
45
|
+
this.logger = logger;
|
|
46
|
+
this.nodeId = nodeId;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async startPolling(
|
|
50
|
+
jobId: number,
|
|
51
|
+
endpoint: EndpointDef,
|
|
52
|
+
taskId: string,
|
|
53
|
+
customInterval?: number,
|
|
54
|
+
customTimeout?: number,
|
|
55
|
+
): Promise<void> {
|
|
56
|
+
// Don't start duplicate polling for same job
|
|
57
|
+
if (this.intervals.has(jobId)) return;
|
|
58
|
+
|
|
59
|
+
const interval = customInterval || endpoint.pollInterval || 5000;
|
|
60
|
+
const timeout = customTimeout || endpoint.pollTimeout || 300000;
|
|
61
|
+
const startTime = Date.now();
|
|
62
|
+
|
|
63
|
+
const timer = setInterval(async () => {
|
|
64
|
+
try {
|
|
65
|
+
if (Date.now() - startTime > timeout) {
|
|
66
|
+
this.stopPolling(jobId);
|
|
67
|
+
await this.onJobError(jobId, 'Polling timeout exceeded');
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
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
|
+
|
|
78
|
+
const pollResultSubpath = endpoint.pollResultSubpath;
|
|
79
|
+
if (!pollResultSubpath) {
|
|
80
|
+
this.stopPolling(jobId);
|
|
81
|
+
await this.onJobError(jobId, 'Polling result subpath is not configured');
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const url = pollResultSubpath.replace('{taskId}', taskId);
|
|
86
|
+
const response = await this.apiClient.get(url);
|
|
87
|
+
|
|
88
|
+
// Smart completion check: use pollStatusField if configured
|
|
89
|
+
if (endpoint.pollStatusField) {
|
|
90
|
+
const statusValue = this.getNestedValue(response, endpoint.pollStatusField);
|
|
91
|
+
const completedValue = endpoint.pollCompletedValue || 'completed';
|
|
92
|
+
if (String(statusValue) === completedValue) {
|
|
93
|
+
const resultValue = endpoint.pollResultField
|
|
94
|
+
? this.getNestedValue(response, endpoint.pollResultField)
|
|
95
|
+
: response;
|
|
96
|
+
this.stopPolling(jobId);
|
|
97
|
+
await this.onJobComplete(jobId, resultValue);
|
|
98
|
+
} else if (statusValue === 'failed' || statusValue === 'error') {
|
|
99
|
+
this.stopPolling(jobId);
|
|
100
|
+
await this.onJobError(jobId, `External task failed with status: ${statusValue}`);
|
|
101
|
+
}
|
|
102
|
+
// Otherwise still pending, continue polling
|
|
103
|
+
} else {
|
|
104
|
+
// Fallback: check if result field has non-null value
|
|
105
|
+
const resultValue = endpoint.pollResultField
|
|
106
|
+
? this.getNestedValue(response, endpoint.pollResultField)
|
|
107
|
+
: response;
|
|
108
|
+
if (resultValue !== undefined && resultValue !== null) {
|
|
109
|
+
this.stopPolling(jobId);
|
|
110
|
+
await this.onJobComplete(jobId, resultValue);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
} catch (err) {
|
|
114
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
115
|
+
this.logger.warn(`Polling error for job ${jobId}: ${message}`);
|
|
116
|
+
}
|
|
117
|
+
}, interval);
|
|
118
|
+
|
|
119
|
+
this.intervals.set(jobId, timer);
|
|
120
|
+
}
|
|
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
|
+
|
|
131
|
+
/**
|
|
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.
|
|
136
|
+
*/
|
|
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({
|
|
147
|
+
filter: {
|
|
148
|
+
status: { $in: ['pending', 'running'] },
|
|
149
|
+
$or: [{ leaseExpiresAt: { $lt: now } }, { leaseExpiresAt: null }],
|
|
150
|
+
},
|
|
151
|
+
values: { status: 'failed', error: 'Job lease expired before completion', completedAt: now },
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
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.
|
|
160
|
+
*/
|
|
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
|
+
});
|
|
170
|
+
|
|
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];
|
|
175
|
+
if (!taskId) continue;
|
|
176
|
+
|
|
177
|
+
const pipelineRepo = this.db.getRepository('doc_understanding_pipelines');
|
|
178
|
+
const pipeline = await pipelineRepo.findOne({
|
|
179
|
+
filter: { id: job.pipelineId },
|
|
180
|
+
appends: ['steps', 'steps.endpoint'],
|
|
181
|
+
});
|
|
182
|
+
if (!pipeline) continue;
|
|
183
|
+
|
|
184
|
+
const steps = ((pipeline as any).steps || []) as Array<{ stepOrder: number; endpoint?: EndpointDef }>;
|
|
185
|
+
const step = steps.find((s) => s.stepOrder === job.currentStep);
|
|
186
|
+
if (!step?.endpoint || step.endpoint.executionMode !== 'polling') continue;
|
|
187
|
+
|
|
188
|
+
if (await this.claimJobForPolling(job.id, step.endpoint)) {
|
|
189
|
+
await this.startPolling(job.id, step.endpoint, taskId);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
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
|
+
|
|
219
|
+
stopPolling(jobId: number) {
|
|
220
|
+
const timer = this.intervals.get(jobId);
|
|
221
|
+
if (timer) {
|
|
222
|
+
clearInterval(timer);
|
|
223
|
+
this.intervals.delete(jobId);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
destroy() {
|
|
228
|
+
for (const timer of this.intervals.values()) {
|
|
229
|
+
clearInterval(timer);
|
|
230
|
+
}
|
|
231
|
+
this.intervals.clear();
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
private getNestedValue(obj: any, path: string): any {
|
|
235
|
+
if (!obj) return obj;
|
|
236
|
+
return path.split('.').reduce((acc, part) => acc && acc[part], obj);
|
|
237
|
+
}
|
|
238
|
+
}
|