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,332 +1,332 @@
|
|
|
1
|
-
import * as crypto from 'crypto';
|
|
2
|
-
import { Application } from '@nocobase/server';
|
|
3
|
-
import { Database, Repository } from '@nocobase/database';
|
|
4
|
-
import { ExternalApiClient, FileInput } from './ExternalApiClient';
|
|
5
|
-
import { AsyncJobManager } from './AsyncJobManager';
|
|
6
|
-
import { PipelineExecutor } from './PipelineExecutor';
|
|
7
|
-
import { ClientServiceConfig, ServiceConfig, EndpointDef, PipelineDef, JobState } from '../types';
|
|
8
|
-
|
|
9
|
-
export class DocumentUnderstandingService {
|
|
10
|
-
private app: Application;
|
|
11
|
-
private db: Database;
|
|
12
|
-
private apiClient!: ExternalApiClient;
|
|
13
|
-
private pipelineExecutor!: PipelineExecutor;
|
|
14
|
-
private jobManager!: AsyncJobManager;
|
|
15
|
-
private initialized = false;
|
|
16
|
-
private startupRecoveryCompleted = false;
|
|
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;
|
|
22
|
-
private static readonly HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
23
|
-
private static readonly MAINTENANCE_INTERVAL_MS = 30_000;
|
|
24
|
-
|
|
25
|
-
constructor(app: Application, db: Database) {
|
|
26
|
-
this.app = app;
|
|
27
|
-
this.db = db;
|
|
28
|
-
this.nodeId = `${app?.name || 'app'}:${process.pid}:${crypto.randomUUID()}`;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
async initialize(options: { recoverJobs?: boolean } = {}): Promise<void> {
|
|
32
|
-
if (this.initializationPromise) {
|
|
33
|
-
await this.initializationPromise;
|
|
34
|
-
return;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
this.initializationPromise = this.doInitialize(options.recoverJobs ?? false).finally(() => {
|
|
38
|
-
this.initializationPromise = undefined;
|
|
39
|
-
});
|
|
40
|
-
await this.initializationPromise;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
async ensureInitialized(): Promise<void> {
|
|
44
|
-
if (this.initialized) return;
|
|
45
|
-
await this.initialize();
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
private async doInitialize(recoverJobs: boolean): Promise<void> {
|
|
49
|
-
const config = await this.ensureConfig();
|
|
50
|
-
|
|
51
|
-
this.jobManager?.destroy();
|
|
52
|
-
this.stopMaintenance();
|
|
53
|
-
this.apiClient = new ExternalApiClient(config);
|
|
54
|
-
this.jobManager = new AsyncJobManager(
|
|
55
|
-
this.db,
|
|
56
|
-
this.apiClient,
|
|
57
|
-
{
|
|
58
|
-
onJobComplete: async (jobId, result) => {
|
|
59
|
-
await this.pipelineExecutor.resumeFromStep(jobId, result);
|
|
60
|
-
},
|
|
61
|
-
onJobError: async (jobId, error) => {
|
|
62
|
-
const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
|
|
63
|
-
await jobsRepo.update({
|
|
64
|
-
filterByTk: jobId,
|
|
65
|
-
values: { status: 'failed', error, completedAt: new Date() },
|
|
66
|
-
});
|
|
67
|
-
},
|
|
68
|
-
},
|
|
69
|
-
this.app.logger,
|
|
70
|
-
this.nodeId,
|
|
71
|
-
);
|
|
72
|
-
|
|
73
|
-
this.pipelineExecutor = new PipelineExecutor(
|
|
74
|
-
this.db,
|
|
75
|
-
this.apiClient,
|
|
76
|
-
this.jobManager,
|
|
77
|
-
this.app.logger,
|
|
78
|
-
this.nodeId,
|
|
79
|
-
);
|
|
80
|
-
|
|
81
|
-
if (recoverJobs && !this.startupRecoveryCompleted) {
|
|
82
|
-
await this.maintainJobs();
|
|
83
|
-
this.startupRecoveryCompleted = true;
|
|
84
|
-
}
|
|
85
|
-
this.startMaintenance();
|
|
86
|
-
|
|
87
|
-
this.initialized = true;
|
|
88
|
-
}
|
|
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
|
-
|
|
121
|
-
private async ensureConfig(): Promise<ServiceConfig> {
|
|
122
|
-
const configRepo = this.db.getRepository<any>('doc_understanding_config');
|
|
123
|
-
let config = await configRepo.findOne();
|
|
124
|
-
|
|
125
|
-
if (!config) {
|
|
126
|
-
config = await configRepo.create({
|
|
127
|
-
values: {
|
|
128
|
-
baseUrl: 'http://localhost:8000',
|
|
129
|
-
authType: 'none',
|
|
130
|
-
defaultTimeout: 30000,
|
|
131
|
-
defaultRetries: 2,
|
|
132
|
-
pollInterval: 5000,
|
|
133
|
-
pollTimeout: 300000,
|
|
134
|
-
},
|
|
135
|
-
});
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
// Attributes live on the Sequelize model prototype, so callers that spread the
|
|
139
|
-
// result would otherwise get an object with none of the config fields.
|
|
140
|
-
return config.toJSON();
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
isReady(): boolean {
|
|
144
|
-
return this.initialized;
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
async getConfig(): Promise<ServiceConfig> {
|
|
148
|
-
return this.ensureConfig();
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
async getConfigForClient(): Promise<ClientServiceConfig> {
|
|
152
|
-
const { authKey, webhookSecret, ...config } = await this.ensureConfig();
|
|
153
|
-
return {
|
|
154
|
-
...config,
|
|
155
|
-
hasAuthKey: Boolean(authKey),
|
|
156
|
-
hasWebhookSecret: Boolean(webhookSecret),
|
|
157
|
-
};
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
async updateConfig(data: Partial<ServiceConfig>): Promise<void> {
|
|
161
|
-
const configRepo = this.db.getRepository<any>('doc_understanding_config');
|
|
162
|
-
const conf = await configRepo.findOne();
|
|
163
|
-
if (conf) {
|
|
164
|
-
const values = { ...data };
|
|
165
|
-
if (!values.authKey) delete values.authKey;
|
|
166
|
-
if (!values.webhookSecret) delete values.webhookSecret;
|
|
167
|
-
await configRepo.update({ filterByTk: conf.id, values });
|
|
168
|
-
}
|
|
169
|
-
// Reinitialize to pick up new config
|
|
170
|
-
await this.initialize();
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
destroy(): void {
|
|
174
|
-
this.stopMaintenance();
|
|
175
|
-
this.jobManager?.destroy();
|
|
176
|
-
this.initialized = false;
|
|
177
|
-
this.startupRecoveryCompleted = false;
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
async listEndpoints(): Promise<EndpointDef[]> {
|
|
181
|
-
await this.ensureInitialized();
|
|
182
|
-
return this.db.getRepository<any>('doc_understanding_endpoints').find({ sort: 'sortOrder' });
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
async createEndpoint(data: Partial<EndpointDef>): Promise<EndpointDef> {
|
|
186
|
-
return this.db.getRepository<any>('doc_understanding_endpoints').create({ values: this.normalizeEndpoint(data) });
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
async updateEndpoint(id: number, data: Partial<EndpointDef>): Promise<void> {
|
|
190
|
-
await this.db.getRepository<any>('doc_understanding_endpoints').update({
|
|
191
|
-
filterByTk: id,
|
|
192
|
-
values: this.normalizeEndpoint(data),
|
|
193
|
-
});
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
private normalizeEndpoint(data: Partial<EndpointDef> = {}): Partial<EndpointDef> {
|
|
197
|
-
if (!Object.prototype.hasOwnProperty.call(data, 'customHeaders')) {
|
|
198
|
-
return data;
|
|
199
|
-
}
|
|
200
|
-
return {
|
|
201
|
-
...data,
|
|
202
|
-
customHeaders: this.normalizeHeaders(data.customHeaders),
|
|
203
|
-
};
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
private normalizeHeaders(headers?: Record<string, any>): Record<string, string> {
|
|
207
|
-
const normalized: Record<string, string> = {};
|
|
208
|
-
if (!headers || typeof headers !== 'object' || Array.isArray(headers)) {
|
|
209
|
-
return normalized;
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
for (const [rawName, rawValue] of Object.entries(headers)) {
|
|
213
|
-
const name = rawName.trim();
|
|
214
|
-
if (!name) continue;
|
|
215
|
-
if (!DocumentUnderstandingService.HEADER_NAME_RE.test(name)) {
|
|
216
|
-
throw new Error(`Invalid HTTP header name: ${rawName}`);
|
|
217
|
-
}
|
|
218
|
-
if (rawValue === undefined || rawValue === null) continue;
|
|
219
|
-
normalized[name] = String(rawValue);
|
|
220
|
-
}
|
|
221
|
-
return normalized;
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
async deleteEndpoint(id: number): Promise<void> {
|
|
225
|
-
await this.db.getRepository<any>('doc_understanding_endpoints').destroy({ filterByTk: id });
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
async listPipelines(): Promise<PipelineDef[]> {
|
|
229
|
-
await this.ensureInitialized();
|
|
230
|
-
return this.db.getRepository<any>('doc_understanding_pipelines').find({
|
|
231
|
-
appends: ['steps', 'steps.endpoint'],
|
|
232
|
-
});
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
async createPipeline(data: Partial<PipelineDef>): Promise<PipelineDef> {
|
|
236
|
-
this.validateStepAliases(data.steps);
|
|
237
|
-
return this.db.getRepository<any>('doc_understanding_pipelines').create({ values: data });
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
async updatePipeline(id: number, data: Partial<PipelineDef>): Promise<void> {
|
|
241
|
-
this.validateStepAliases(data.steps);
|
|
242
|
-
await this.db.getRepository<any>('doc_understanding_pipelines').update({ filterByTk: id, values: data });
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
private validateStepAliases(steps?: any[]) {
|
|
246
|
-
if (!steps) return;
|
|
247
|
-
const aliases = steps.map((s) => s.outputAlias).filter(Boolean);
|
|
248
|
-
const unique = new Set(aliases);
|
|
249
|
-
if (unique.size !== aliases.length) {
|
|
250
|
-
throw new Error('Pipeline steps must have unique outputAlias values');
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
async deletePipeline(id: number): Promise<void> {
|
|
255
|
-
await this.db.getRepository<any>('doc_understanding_pipelines').destroy({ filterByTk: id });
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
async executePipeline(
|
|
259
|
-
pipelineId: number,
|
|
260
|
-
input: Record<string, any>,
|
|
261
|
-
files: FileInput[] = [],
|
|
262
|
-
userId?: number,
|
|
263
|
-
): Promise<{ jobId: number }> {
|
|
264
|
-
await this.ensureInitialized();
|
|
265
|
-
const job = await this.pipelineExecutor.execute(pipelineId, input, files, userId);
|
|
266
|
-
return { jobId: job.id };
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
async getJobStatus(jobId: number, userId?: number): Promise<JobState> {
|
|
270
|
-
const filter = userId ? { id: jobId, createdById: userId } : { id: jobId };
|
|
271
|
-
const job = await this.db.getRepository<any>('doc_understanding_jobs').findOne({ filter });
|
|
272
|
-
if (!job) throw new Error('Job not found');
|
|
273
|
-
return job;
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
async listJobs(filters?: Record<string, unknown>, userId?: number): Promise<JobState[]> {
|
|
277
|
-
const filter = userId ? { ...(filters || {}), createdById: userId } : filters;
|
|
278
|
-
return this.db.getRepository<any>('doc_understanding_jobs').find({
|
|
279
|
-
filter,
|
|
280
|
-
sort: ['-createdAt'],
|
|
281
|
-
});
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
async handleWebhook(payload: any, signature?: string): Promise<void> {
|
|
285
|
-
await this.ensureInitialized();
|
|
286
|
-
const config = await this.getConfig();
|
|
287
|
-
if (config.webhookSecret) {
|
|
288
|
-
if (!signature) {
|
|
289
|
-
throw new Error('Webhook signature missing');
|
|
290
|
-
}
|
|
291
|
-
const expected = crypto.createHmac('sha256', config.webhookSecret).update(JSON.stringify(payload)).digest('hex');
|
|
292
|
-
const signatureHash = signature.startsWith('sha256=') ? signature.slice(7) : signature;
|
|
293
|
-
if (!crypto.timingSafeEqual(Buffer.from(signatureHash, 'hex'), Buffer.from(expected, 'hex'))) {
|
|
294
|
-
throw new Error('Webhook signature verification failed');
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
const taskId = payload.task_id ?? payload.operation_id;
|
|
299
|
-
const result = payload.result;
|
|
300
|
-
if (!taskId) throw new Error('Webhook missing task_id');
|
|
301
|
-
|
|
302
|
-
// Paginated search to avoid loading all polling jobs into memory
|
|
303
|
-
const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
|
|
304
|
-
const PAGE_SIZE = 100;
|
|
305
|
-
let offset = 0;
|
|
306
|
-
let hasMoreJobs = true;
|
|
307
|
-
|
|
308
|
-
while (hasMoreJobs) {
|
|
309
|
-
const jobs = await jobsRepo.find({
|
|
310
|
-
filter: { status: 'polling' },
|
|
311
|
-
limit: PAGE_SIZE,
|
|
312
|
-
offset,
|
|
313
|
-
});
|
|
314
|
-
|
|
315
|
-
if (jobs.length === 0) break;
|
|
316
|
-
|
|
317
|
-
for (const job of jobs) {
|
|
318
|
-
if (Object.values(job.externalTaskIds || {}).includes(taskId)) {
|
|
319
|
-
await this.pipelineExecutor.resumeFromStep(job.id, result || payload);
|
|
320
|
-
return;
|
|
321
|
-
}
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
hasMoreJobs = jobs.length >= PAGE_SIZE;
|
|
325
|
-
if (hasMoreJobs) {
|
|
326
|
-
offset += PAGE_SIZE;
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
throw new Error(`Job not found for webhook task ${taskId}`);
|
|
331
|
-
}
|
|
332
|
-
}
|
|
1
|
+
import * as crypto from 'crypto';
|
|
2
|
+
import { Application } from '@nocobase/server';
|
|
3
|
+
import { Database, Repository } from '@nocobase/database';
|
|
4
|
+
import { ExternalApiClient, FileInput } from './ExternalApiClient';
|
|
5
|
+
import { AsyncJobManager } from './AsyncJobManager';
|
|
6
|
+
import { PipelineExecutor } from './PipelineExecutor';
|
|
7
|
+
import { ClientServiceConfig, ServiceConfig, EndpointDef, PipelineDef, JobState } from '../types';
|
|
8
|
+
|
|
9
|
+
export class DocumentUnderstandingService {
|
|
10
|
+
private app: Application;
|
|
11
|
+
private db: Database;
|
|
12
|
+
private apiClient!: ExternalApiClient;
|
|
13
|
+
private pipelineExecutor!: PipelineExecutor;
|
|
14
|
+
private jobManager!: AsyncJobManager;
|
|
15
|
+
private initialized = false;
|
|
16
|
+
private startupRecoveryCompleted = false;
|
|
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;
|
|
22
|
+
private static readonly HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
23
|
+
private static readonly MAINTENANCE_INTERVAL_MS = 30_000;
|
|
24
|
+
|
|
25
|
+
constructor(app: Application, db: Database) {
|
|
26
|
+
this.app = app;
|
|
27
|
+
this.db = db;
|
|
28
|
+
this.nodeId = `${app?.name || 'app'}:${process.pid}:${crypto.randomUUID()}`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async initialize(options: { recoverJobs?: boolean } = {}): Promise<void> {
|
|
32
|
+
if (this.initializationPromise) {
|
|
33
|
+
await this.initializationPromise;
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
this.initializationPromise = this.doInitialize(options.recoverJobs ?? false).finally(() => {
|
|
38
|
+
this.initializationPromise = undefined;
|
|
39
|
+
});
|
|
40
|
+
await this.initializationPromise;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async ensureInitialized(): Promise<void> {
|
|
44
|
+
if (this.initialized) return;
|
|
45
|
+
await this.initialize();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
private async doInitialize(recoverJobs: boolean): Promise<void> {
|
|
49
|
+
const config = await this.ensureConfig();
|
|
50
|
+
|
|
51
|
+
this.jobManager?.destroy();
|
|
52
|
+
this.stopMaintenance();
|
|
53
|
+
this.apiClient = new ExternalApiClient(config);
|
|
54
|
+
this.jobManager = new AsyncJobManager(
|
|
55
|
+
this.db,
|
|
56
|
+
this.apiClient,
|
|
57
|
+
{
|
|
58
|
+
onJobComplete: async (jobId, result) => {
|
|
59
|
+
await this.pipelineExecutor.resumeFromStep(jobId, result);
|
|
60
|
+
},
|
|
61
|
+
onJobError: async (jobId, error) => {
|
|
62
|
+
const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
|
|
63
|
+
await jobsRepo.update({
|
|
64
|
+
filterByTk: jobId,
|
|
65
|
+
values: { status: 'failed', error, completedAt: new Date() },
|
|
66
|
+
});
|
|
67
|
+
},
|
|
68
|
+
},
|
|
69
|
+
this.app.logger,
|
|
70
|
+
this.nodeId,
|
|
71
|
+
);
|
|
72
|
+
|
|
73
|
+
this.pipelineExecutor = new PipelineExecutor(
|
|
74
|
+
this.db,
|
|
75
|
+
this.apiClient,
|
|
76
|
+
this.jobManager,
|
|
77
|
+
this.app.logger,
|
|
78
|
+
this.nodeId,
|
|
79
|
+
);
|
|
80
|
+
|
|
81
|
+
if (recoverJobs && !this.startupRecoveryCompleted) {
|
|
82
|
+
await this.maintainJobs();
|
|
83
|
+
this.startupRecoveryCompleted = true;
|
|
84
|
+
}
|
|
85
|
+
this.startMaintenance();
|
|
86
|
+
|
|
87
|
+
this.initialized = true;
|
|
88
|
+
}
|
|
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
|
+
|
|
121
|
+
private async ensureConfig(): Promise<ServiceConfig> {
|
|
122
|
+
const configRepo = this.db.getRepository<any>('doc_understanding_config');
|
|
123
|
+
let config = await configRepo.findOne();
|
|
124
|
+
|
|
125
|
+
if (!config) {
|
|
126
|
+
config = await configRepo.create({
|
|
127
|
+
values: {
|
|
128
|
+
baseUrl: 'http://localhost:8000',
|
|
129
|
+
authType: 'none',
|
|
130
|
+
defaultTimeout: 30000,
|
|
131
|
+
defaultRetries: 2,
|
|
132
|
+
pollInterval: 5000,
|
|
133
|
+
pollTimeout: 300000,
|
|
134
|
+
},
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Attributes live on the Sequelize model prototype, so callers that spread the
|
|
139
|
+
// result would otherwise get an object with none of the config fields.
|
|
140
|
+
return config.toJSON();
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
isReady(): boolean {
|
|
144
|
+
return this.initialized;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async getConfig(): Promise<ServiceConfig> {
|
|
148
|
+
return this.ensureConfig();
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async getConfigForClient(): Promise<ClientServiceConfig> {
|
|
152
|
+
const { authKey, webhookSecret, ...config } = await this.ensureConfig();
|
|
153
|
+
return {
|
|
154
|
+
...config,
|
|
155
|
+
hasAuthKey: Boolean(authKey),
|
|
156
|
+
hasWebhookSecret: Boolean(webhookSecret),
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async updateConfig(data: Partial<ServiceConfig>): Promise<void> {
|
|
161
|
+
const configRepo = this.db.getRepository<any>('doc_understanding_config');
|
|
162
|
+
const conf = await configRepo.findOne();
|
|
163
|
+
if (conf) {
|
|
164
|
+
const values = { ...data };
|
|
165
|
+
if (!values.authKey) delete values.authKey;
|
|
166
|
+
if (!values.webhookSecret) delete values.webhookSecret;
|
|
167
|
+
await configRepo.update({ filterByTk: conf.id, values });
|
|
168
|
+
}
|
|
169
|
+
// Reinitialize to pick up new config
|
|
170
|
+
await this.initialize();
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
destroy(): void {
|
|
174
|
+
this.stopMaintenance();
|
|
175
|
+
this.jobManager?.destroy();
|
|
176
|
+
this.initialized = false;
|
|
177
|
+
this.startupRecoveryCompleted = false;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async listEndpoints(): Promise<EndpointDef[]> {
|
|
181
|
+
await this.ensureInitialized();
|
|
182
|
+
return this.db.getRepository<any>('doc_understanding_endpoints').find({ sort: 'sortOrder' });
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async createEndpoint(data: Partial<EndpointDef>): Promise<EndpointDef> {
|
|
186
|
+
return this.db.getRepository<any>('doc_understanding_endpoints').create({ values: this.normalizeEndpoint(data) });
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async updateEndpoint(id: number, data: Partial<EndpointDef>): Promise<void> {
|
|
190
|
+
await this.db.getRepository<any>('doc_understanding_endpoints').update({
|
|
191
|
+
filterByTk: id,
|
|
192
|
+
values: this.normalizeEndpoint(data),
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
private normalizeEndpoint(data: Partial<EndpointDef> = {}): Partial<EndpointDef> {
|
|
197
|
+
if (!Object.prototype.hasOwnProperty.call(data, 'customHeaders')) {
|
|
198
|
+
return data;
|
|
199
|
+
}
|
|
200
|
+
return {
|
|
201
|
+
...data,
|
|
202
|
+
customHeaders: this.normalizeHeaders(data.customHeaders),
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
private normalizeHeaders(headers?: Record<string, any>): Record<string, string> {
|
|
207
|
+
const normalized: Record<string, string> = {};
|
|
208
|
+
if (!headers || typeof headers !== 'object' || Array.isArray(headers)) {
|
|
209
|
+
return normalized;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
for (const [rawName, rawValue] of Object.entries(headers)) {
|
|
213
|
+
const name = rawName.trim();
|
|
214
|
+
if (!name) continue;
|
|
215
|
+
if (!DocumentUnderstandingService.HEADER_NAME_RE.test(name)) {
|
|
216
|
+
throw new Error(`Invalid HTTP header name: ${rawName}`);
|
|
217
|
+
}
|
|
218
|
+
if (rawValue === undefined || rawValue === null) continue;
|
|
219
|
+
normalized[name] = String(rawValue);
|
|
220
|
+
}
|
|
221
|
+
return normalized;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async deleteEndpoint(id: number): Promise<void> {
|
|
225
|
+
await this.db.getRepository<any>('doc_understanding_endpoints').destroy({ filterByTk: id });
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
async listPipelines(): Promise<PipelineDef[]> {
|
|
229
|
+
await this.ensureInitialized();
|
|
230
|
+
return this.db.getRepository<any>('doc_understanding_pipelines').find({
|
|
231
|
+
appends: ['steps', 'steps.endpoint'],
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async createPipeline(data: Partial<PipelineDef>): Promise<PipelineDef> {
|
|
236
|
+
this.validateStepAliases(data.steps);
|
|
237
|
+
return this.db.getRepository<any>('doc_understanding_pipelines').create({ values: data });
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async updatePipeline(id: number, data: Partial<PipelineDef>): Promise<void> {
|
|
241
|
+
this.validateStepAliases(data.steps);
|
|
242
|
+
await this.db.getRepository<any>('doc_understanding_pipelines').update({ filterByTk: id, values: data });
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
private validateStepAliases(steps?: any[]) {
|
|
246
|
+
if (!steps) return;
|
|
247
|
+
const aliases = steps.map((s) => s.outputAlias).filter(Boolean);
|
|
248
|
+
const unique = new Set(aliases);
|
|
249
|
+
if (unique.size !== aliases.length) {
|
|
250
|
+
throw new Error('Pipeline steps must have unique outputAlias values');
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async deletePipeline(id: number): Promise<void> {
|
|
255
|
+
await this.db.getRepository<any>('doc_understanding_pipelines').destroy({ filterByTk: id });
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
async executePipeline(
|
|
259
|
+
pipelineId: number,
|
|
260
|
+
input: Record<string, any>,
|
|
261
|
+
files: FileInput[] = [],
|
|
262
|
+
userId?: number,
|
|
263
|
+
): Promise<{ jobId: number }> {
|
|
264
|
+
await this.ensureInitialized();
|
|
265
|
+
const job = await this.pipelineExecutor.execute(pipelineId, input, files, userId);
|
|
266
|
+
return { jobId: job.id };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
async getJobStatus(jobId: number, userId?: number): Promise<JobState> {
|
|
270
|
+
const filter = userId ? { id: jobId, createdById: userId } : { id: jobId };
|
|
271
|
+
const job = await this.db.getRepository<any>('doc_understanding_jobs').findOne({ filter });
|
|
272
|
+
if (!job) throw new Error('Job not found');
|
|
273
|
+
return job;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
async listJobs(filters?: Record<string, unknown>, userId?: number): Promise<JobState[]> {
|
|
277
|
+
const filter = userId ? { ...(filters || {}), createdById: userId } : filters;
|
|
278
|
+
return this.db.getRepository<any>('doc_understanding_jobs').find({
|
|
279
|
+
filter,
|
|
280
|
+
sort: ['-createdAt'],
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
async handleWebhook(payload: any, signature?: string): Promise<void> {
|
|
285
|
+
await this.ensureInitialized();
|
|
286
|
+
const config = await this.getConfig();
|
|
287
|
+
if (config.webhookSecret) {
|
|
288
|
+
if (!signature) {
|
|
289
|
+
throw new Error('Webhook signature missing');
|
|
290
|
+
}
|
|
291
|
+
const expected = crypto.createHmac('sha256', config.webhookSecret).update(JSON.stringify(payload)).digest('hex');
|
|
292
|
+
const signatureHash = signature.startsWith('sha256=') ? signature.slice(7) : signature;
|
|
293
|
+
if (!crypto.timingSafeEqual(Buffer.from(signatureHash, 'hex'), Buffer.from(expected, 'hex'))) {
|
|
294
|
+
throw new Error('Webhook signature verification failed');
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const taskId = payload.task_id ?? payload.operation_id;
|
|
299
|
+
const result = payload.result;
|
|
300
|
+
if (!taskId) throw new Error('Webhook missing task_id');
|
|
301
|
+
|
|
302
|
+
// Paginated search to avoid loading all polling jobs into memory
|
|
303
|
+
const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
|
|
304
|
+
const PAGE_SIZE = 100;
|
|
305
|
+
let offset = 0;
|
|
306
|
+
let hasMoreJobs = true;
|
|
307
|
+
|
|
308
|
+
while (hasMoreJobs) {
|
|
309
|
+
const jobs = await jobsRepo.find({
|
|
310
|
+
filter: { status: 'polling' },
|
|
311
|
+
limit: PAGE_SIZE,
|
|
312
|
+
offset,
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
if (jobs.length === 0) break;
|
|
316
|
+
|
|
317
|
+
for (const job of jobs) {
|
|
318
|
+
if (Object.values(job.externalTaskIds || {}).includes(taskId)) {
|
|
319
|
+
await this.pipelineExecutor.resumeFromStep(job.id, result || payload);
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
hasMoreJobs = jobs.length >= PAGE_SIZE;
|
|
325
|
+
if (hasMoreJobs) {
|
|
326
|
+
offset += PAGE_SIZE;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
throw new Error(`Job not found for webhook task ${taskId}`);
|
|
331
|
+
}
|
|
332
|
+
}
|