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.
Files changed (36) hide show
  1. package/dist/client/345.e6e484fb1974c3d3.js +10 -0
  2. package/dist/client/index.js +1 -1
  3. package/dist/client-v2/345.a8f28526ac21e02a.js +10 -0
  4. package/dist/client-v2/index.js +1 -1
  5. package/dist/externalVersion.js +7 -7
  6. package/dist/locale/en-US.json +182 -171
  7. package/dist/locale/vi-VN.json +182 -171
  8. package/dist/locale/zh-CN.json +182 -171
  9. package/dist/node_modules/form-data/lib/form_data.js +3 -3
  10. package/dist/node_modules/form-data/package.json +1 -1
  11. package/dist/server/collections/endpoints.js +5 -0
  12. package/dist/server/collections/jobs.js +13 -0
  13. package/dist/server/dugate-seed.js +411 -0
  14. package/dist/server/plugin.js +6 -0
  15. package/dist/server/services/AsyncJobManager.js +87 -31
  16. package/dist/server/services/DocumentUnderstandingService.js +48 -5
  17. package/dist/server/services/ExternalApiClient.js +38 -5
  18. package/dist/server/services/PipelineExecutor.js +115 -36
  19. package/package.json +1 -1
  20. package/src/client-v2/components/EndpointsTab.tsx +51 -0
  21. package/src/locale/en-US.json +182 -171
  22. package/src/locale/vi-VN.json +182 -171
  23. package/src/locale/zh-CN.json +182 -171
  24. package/src/server/__tests__/cluster-safety.test.ts +259 -0
  25. package/src/server/__tests__/dugate-integration.test.ts +221 -0
  26. package/src/server/collections/endpoints.ts +5 -0
  27. package/src/server/collections/jobs.ts +13 -0
  28. package/src/server/dugate-seed.ts +491 -0
  29. package/src/server/plugin.ts +143 -134
  30. package/src/server/services/AsyncJobManager.ts +98 -32
  31. package/src/server/services/DocumentUnderstandingService.ts +50 -4
  32. package/src/server/services/ExternalApiClient.ts +40 -5
  33. package/src/server/services/PipelineExecutor.ts +593 -477
  34. package/src/server/types.ts +90 -78
  35. package/dist/client/345.17f88ffb846ec69b.js +0 -10
  36. package/dist/client-v2/345.1e0c321d30702aa1.js +0 -10
@@ -52,10 +52,16 @@ class DocumentUnderstandingService {
52
52
  initialized = false;
53
53
  startupRecoveryCompleted = false;
54
54
  initializationPromise;
55
+ maintenanceTimer;
56
+ // Unique per process; used as the job owner so other nodes can tell orphaned
57
+ // jobs apart from jobs that are still being processed.
58
+ nodeId;
55
59
  static HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
60
+ static MAINTENANCE_INTERVAL_MS = 3e4;
56
61
  constructor(app, db) {
57
62
  this.app = app;
58
63
  this.db = db;
64
+ this.nodeId = `${(app == null ? void 0 : app.name) || "app"}:${process.pid}:${crypto.randomUUID()}`;
59
65
  }
60
66
  async initialize(options = {}) {
61
67
  if (this.initializationPromise) {
@@ -75,6 +81,7 @@ class DocumentUnderstandingService {
75
81
  var _a;
76
82
  const config = await this.ensureConfig();
77
83
  (_a = this.jobManager) == null ? void 0 : _a.destroy();
84
+ this.stopMaintenance();
78
85
  this.apiClient = new import_ExternalApiClient.ExternalApiClient(config);
79
86
  this.jobManager = new import_AsyncJobManager.AsyncJobManager(
80
87
  this.db,
@@ -91,16 +98,51 @@ class DocumentUnderstandingService {
91
98
  });
92
99
  }
93
100
  },
94
- this.app.logger
101
+ this.app.logger,
102
+ this.nodeId
103
+ );
104
+ this.pipelineExecutor = new import_PipelineExecutor.PipelineExecutor(
105
+ this.db,
106
+ this.apiClient,
107
+ this.jobManager,
108
+ this.app.logger,
109
+ this.nodeId
95
110
  );
96
- this.pipelineExecutor = new import_PipelineExecutor.PipelineExecutor(this.db, this.apiClient, this.jobManager, this.app.logger);
97
111
  if (recoverJobs && !this.startupRecoveryCompleted) {
98
- await this.jobManager.cleanupStuckJobs();
99
- await this.jobManager.recoverPollingJobs();
112
+ await this.maintainJobs();
100
113
  this.startupRecoveryCompleted = true;
101
114
  }
115
+ this.startMaintenance();
102
116
  this.initialized = true;
103
117
  }
118
+ /**
119
+ * Cluster maintenance sweep: fails active jobs whose owner is gone and
120
+ * re-adopts orphaned polling jobs. Safe to run on every node — all state
121
+ * transitions are guarded by ownership checks and row-level claims.
122
+ */
123
+ async maintainJobs() {
124
+ if (!this.jobManager) return;
125
+ try {
126
+ await this.jobManager.failOrphanedActiveJobs();
127
+ await this.jobManager.adoptOrphanedPollingJobs();
128
+ } catch (err) {
129
+ this.app.logger.warn("Document Understanding: job maintenance sweep failed.", err);
130
+ }
131
+ }
132
+ startMaintenance() {
133
+ var _a, _b;
134
+ this.stopMaintenance();
135
+ this.maintenanceTimer = setInterval(() => {
136
+ this.maintainJobs();
137
+ }, DocumentUnderstandingService.MAINTENANCE_INTERVAL_MS);
138
+ (_b = (_a = this.maintenanceTimer).unref) == null ? void 0 : _b.call(_a);
139
+ }
140
+ stopMaintenance() {
141
+ if (this.maintenanceTimer) {
142
+ clearInterval(this.maintenanceTimer);
143
+ this.maintenanceTimer = void 0;
144
+ }
145
+ }
104
146
  async ensureConfig() {
105
147
  const configRepo = this.db.getRepository("doc_understanding_config");
106
148
  let config = await configRepo.findOne();
@@ -145,6 +187,7 @@ class DocumentUnderstandingService {
145
187
  }
146
188
  destroy() {
147
189
  var _a;
190
+ this.stopMaintenance();
148
191
  (_a = this.jobManager) == null ? void 0 : _a.destroy();
149
192
  this.initialized = false;
150
193
  this.startupRecoveryCompleted = false;
@@ -246,7 +289,7 @@ class DocumentUnderstandingService {
246
289
  throw new Error("Webhook signature verification failed");
247
290
  }
248
291
  }
249
- const taskId = payload.task_id;
292
+ const taskId = payload.task_id ?? payload.operation_id;
250
293
  const result = payload.result;
251
294
  if (!taskId) throw new Error("Webhook missing task_id");
252
295
  const jobsRepo = this.db.getRepository("doc_understanding_jobs");
@@ -83,6 +83,36 @@ class ExternalApiClient {
83
83
  }
84
84
  return normalized;
85
85
  }
86
+ /**
87
+ * Appends the endpoint discriminator (if configured) to the request body so
88
+ * DUGate-style gateways can route to the correct sub-case/profile.
89
+ */
90
+ withDiscriminator(endpoint, body) {
91
+ var _a;
92
+ const field = (_a = endpoint.discriminatorField) == null ? void 0 : _a.trim();
93
+ if (!field || !endpoint.discriminatorValue) {
94
+ return body;
95
+ }
96
+ const merged = { ...body || {} };
97
+ if (merged[field] !== void 0 && merged[field] !== endpoint.discriminatorValue) {
98
+ throw new Error(
99
+ `Discriminator field '${field}' is locked by endpoint configuration (expected '${endpoint.discriminatorValue}', got '${merged[field]}').`
100
+ );
101
+ }
102
+ merged[field] = endpoint.discriminatorValue;
103
+ return merged;
104
+ }
105
+ /**
106
+ * Appends the DUGate sync flag (?sync=true) for endpoints configured with
107
+ * `syncQueryParam`. Kept separate from other query parameters so GET/DELETE
108
+ * params in `body` are not polluted by the discriminator logic.
109
+ */
110
+ syncQueryParams(endpoint) {
111
+ var _a;
112
+ const param = (_a = endpoint.syncQueryParam) == null ? void 0 : _a.trim();
113
+ if (!param) return {};
114
+ return { [param]: "true" };
115
+ }
86
116
  async call(options) {
87
117
  const { endpoint, body, files, overrideHeaders } = options;
88
118
  const url = endpoint.subpath;
@@ -95,8 +125,9 @@ class ExternalApiClient {
95
125
  };
96
126
  if (endpoint.fileInputMode === "multipart" && files && files.length > 0) {
97
127
  const formData = new import_form_data.default();
98
- if (body) {
99
- for (const [key, value] of Object.entries(body)) {
128
+ const bodyWithDiscriminator = this.withDiscriminator(endpoint, body);
129
+ if (bodyWithDiscriminator) {
130
+ for (const [key, value] of Object.entries(bodyWithDiscriminator)) {
100
131
  formData.append(key, typeof value === "object" ? JSON.stringify(value) : String(value));
101
132
  }
102
133
  }
@@ -117,17 +148,19 @@ class ExternalApiClient {
117
148
  mimeType: f.mimeType
118
149
  };
119
150
  }
120
- requestData = { ...body, _files: base64Files };
151
+ requestData = { ...this.withDiscriminator(endpoint, body), _files: base64Files };
121
152
  headers["Content-Type"] = "application/json";
122
153
  } else {
154
+ requestData = this.withDiscriminator(endpoint, body);
123
155
  headers["Content-Type"] = "application/json";
124
156
  }
125
157
  try {
158
+ const isBodyless = ["get", "delete"].includes(method);
126
159
  const response = await this.client.request({
127
160
  url,
128
161
  method,
129
- data: ["post", "put", "patch"].includes(method) ? requestData : void 0,
130
- params: ["get", "delete"].includes(method) ? requestData : void 0,
162
+ data: isBodyless ? void 0 : requestData,
163
+ params: isBodyless ? { ...requestData || {}, ...this.syncQueryParams(endpoint) } : this.syncQueryParams(endpoint),
131
164
  headers
132
165
  });
133
166
  return {
@@ -43,8 +43,33 @@ module.exports = __toCommonJS(PipelineExecutor_exports);
43
43
  var import_fs = require("fs");
44
44
  var import_path = require("path");
45
45
  var import_mime_types = __toESM(require("mime-types"));
46
+ var import_AsyncJobManager = require("./AsyncJobManager");
46
47
  const UPLOAD_ROOTS = [(0, import_path.resolve)(process.cwd(), "storage", "uploads")];
47
48
  const isInsidePath = (basePath, targetPath) => targetPath === basePath || targetPath.startsWith(`${basePath}${import_path.sep}`);
49
+ function extractTaskId(responseData, endpoint) {
50
+ var _a, _b;
51
+ const extractPath = (_a = endpoint.taskIdExtractPath) == null ? void 0 : _a.trim();
52
+ if (extractPath) {
53
+ const raw = extractPath.split(".").reduce((acc, k) => acc != null ? acc[k] : void 0, responseData);
54
+ if (raw != null) {
55
+ const regex = (_b = endpoint.taskIdExtractRegex) == null ? void 0 : _b.trim();
56
+ if (regex) {
57
+ try {
58
+ const m = String(raw).match(new RegExp(regex));
59
+ if (m == null ? void 0 : m[1]) return m[1];
60
+ } catch {
61
+ }
62
+ }
63
+ return String(raw);
64
+ }
65
+ }
66
+ const idField = endpoint.pollTaskIdField || "task_id";
67
+ const fieldVal = idField.split(".").reduce((acc, k) => acc != null ? acc[k] : void 0, responseData);
68
+ if (fieldVal != null) return String(fieldVal);
69
+ if (typeof responseData === "string") return responseData;
70
+ if (typeof responseData === "number") return String(responseData);
71
+ return null;
72
+ }
48
73
  function resolveUploadFilePath(urlOrPath) {
49
74
  if (!urlOrPath || urlOrPath.includes("\0")) return null;
50
75
  let pathname = urlOrPath.replace(/\\/g, "/").split(/[?#]/)[0];
@@ -84,11 +109,13 @@ class PipelineExecutor {
84
109
  apiClient;
85
110
  jobManager;
86
111
  logger;
87
- constructor(db, apiClient, jobManager, logger) {
112
+ nodeId;
113
+ constructor(db, apiClient, jobManager, logger, nodeId = "") {
88
114
  this.db = db;
89
115
  this.apiClient = apiClient;
90
116
  this.jobManager = jobManager;
91
117
  this.logger = logger;
118
+ this.nodeId = nodeId;
92
119
  }
93
120
  async resolveFile(urlOrPath, fieldName = "file") {
94
121
  var _a, _b, _c, _d;
@@ -133,7 +160,9 @@ class PipelineExecutor {
133
160
  stepResults: {},
134
161
  externalTaskIds: {},
135
162
  startedAt: /* @__PURE__ */ new Date(),
136
- createdById: userId
163
+ createdById: userId,
164
+ ownedBy: this.nodeId,
165
+ leaseExpiresAt: new Date(Date.now() + import_AsyncJobManager.JOB_RUN_LEASE_MS)
137
166
  }
138
167
  });
139
168
  const resolvedFiles = [];
@@ -208,19 +237,25 @@ class PipelineExecutor {
208
237
  const jobsRepo = this.db.getRepository("doc_understanding_jobs");
209
238
  let currentOrder = startFromOrder;
210
239
  try {
211
- await jobsRepo.update({ filterByTk: job.id, values: { status: "running" } });
240
+ await jobsRepo.update({
241
+ filterByTk: job.id,
242
+ values: { status: "running", ownedBy: this.nodeId, leaseExpiresAt: new Date(Date.now() + import_AsyncJobManager.JOB_RUN_LEASE_MS) }
243
+ });
212
244
  for (const step of steps) {
213
245
  if (step.stepOrder < startFromOrder) continue;
214
246
  context.jobId = job.id;
215
247
  currentOrder = step.stepOrder;
216
- await jobsRepo.update({ filterByTk: job.id, values: { currentStep: currentOrder } });
248
+ await jobsRepo.update({
249
+ filterByTk: job.id,
250
+ values: { currentStep: currentOrder, leaseExpiresAt: new Date(Date.now() + import_AsyncJobManager.JOB_RUN_LEASE_MS) }
251
+ });
217
252
  if (!this.evaluateCondition(step.condition, context)) {
218
253
  continue;
219
254
  }
220
255
  if (!((_a = step.endpoint) == null ? void 0 : _a.enabled)) {
221
256
  throw new Error(`Endpoint for step ${step.name} is disabled`);
222
257
  }
223
- const mappedBody = this.resolveMapping(step.inputMapping || {}, context);
258
+ const mappedBody = step.inputMapping && Object.keys(step.inputMapping).length > 0 ? this.resolveMapping(step.inputMapping, context) : context.input;
224
259
  let retries = step.onError === "retry" ? step.retryCount || 0 : 0;
225
260
  let success = false;
226
261
  let lastError = null;
@@ -237,28 +272,57 @@ class PipelineExecutor {
237
272
  files: mappedFiles
238
273
  });
239
274
  if (step.endpoint.executionMode === "sync") {
240
- context.stepResults[step.outputAlias || step.stepOrder.toString()] = result.data;
275
+ const responseData = result.data;
276
+ const isAsyncAccepted = result.status === 202 || responseData && typeof responseData === "object" && responseData.done === false;
277
+ if (isAsyncAccepted) {
278
+ const taskId = extractTaskId(responseData, step.endpoint);
279
+ if (taskId) {
280
+ const externalTaskIds = { ...job.externalTaskIds || {} };
281
+ externalTaskIds[step.stepOrder.toString()] = taskId;
282
+ await jobsRepo.update({
283
+ filterByTk: job.id,
284
+ values: {
285
+ status: "polling",
286
+ externalTaskIds,
287
+ leaseExpiresAt: new Date(Date.now() + (0, import_AsyncJobManager.pollLeaseMs)(step.endpoint.pollInterval))
288
+ }
289
+ });
290
+ await this.jobManager.startPolling(job.id, step.endpoint, taskId);
291
+ return;
292
+ }
293
+ }
294
+ context.stepResults[step.outputAlias || step.stepOrder.toString()] = responseData;
241
295
  success = true;
242
296
  } else if (step.endpoint.executionMode === "polling") {
243
- const taskIdField = step.endpoint.pollTaskIdField || "task_id";
244
- const taskId = this.getNestedValue(result.data, taskIdField);
245
- if (!taskId) throw new Error(`Polling taskId not found in field ${taskIdField}`);
297
+ const taskId = extractTaskId(result.data, step.endpoint);
298
+ if (!taskId) throw new Error("Polling taskId not found in response");
246
299
  const externalTaskIds = job.externalTaskIds || {};
247
300
  externalTaskIds[step.stepOrder.toString()] = taskId;
248
301
  await jobsRepo.update({
249
302
  filterByTk: job.id,
250
- values: { status: "polling", externalTaskIds }
303
+ values: {
304
+ status: "polling",
305
+ externalTaskIds,
306
+ // This node keeps polling and refreshes the lease on every tick.
307
+ leaseExpiresAt: new Date(Date.now() + (0, import_AsyncJobManager.pollLeaseMs)(step.endpoint.pollInterval))
308
+ }
251
309
  });
252
310
  await this.jobManager.startPolling(job.id, step.endpoint, taskId);
253
311
  return;
254
312
  } else if (step.endpoint.executionMode === "webhook") {
255
- const taskIdField = step.endpoint.pollTaskIdField || "task_id";
256
- const taskId = this.getNestedValue(result.data, taskIdField);
313
+ const taskId = extractTaskId(result.data, step.endpoint);
314
+ if (!taskId) throw new Error("Webhook taskId not found in response");
257
315
  const externalTaskIds = job.externalTaskIds || {};
258
316
  externalTaskIds[step.stepOrder.toString()] = taskId;
259
317
  await jobsRepo.update({
260
318
  filterByTk: job.id,
261
- values: { status: "polling", externalTaskIds }
319
+ values: {
320
+ status: "polling",
321
+ externalTaskIds,
322
+ // No process actively owns a webhook wait: the callback may arrive
323
+ // at any node, so there is no lease to renew.
324
+ leaseExpiresAt: null
325
+ }
262
326
  });
263
327
  return;
264
328
  }
@@ -284,33 +348,48 @@ class PipelineExecutor {
284
348
  async resumeFromStep(jobId, asyncResult) {
285
349
  const jobsRepo = this.db.getRepository("doc_understanding_jobs");
286
350
  const pipelineRepo = this.db.getRepository("doc_understanding_pipelines");
287
- const job = await jobsRepo.findOne({ filterByTk: jobId });
288
- if (!job) throw new Error(`Job ${jobId} not found`);
289
- const pipeline = await pipelineRepo.findOne({
290
- filter: { id: job.pipelineId },
291
- appends: ["steps", "steps.endpoint"]
292
- });
293
- if (!pipeline) throw new Error(`Pipeline not found for job ${jobId}`);
294
- const steps = [...pipeline.steps || []].sort((a, b) => a.stepOrder - b.stepOrder);
295
- const step = steps.find((s) => s.stepOrder === job.currentStep);
296
- if (step) {
297
- job.stepResults = job.stepResults || {};
298
- job.stepResults[step.outputAlias || step.stepOrder.toString()] = asyncResult;
299
- await jobsRepo.update({
300
- filterByTk: jobId,
301
- values: { stepResults: job.stepResults }
302
- // updating stepResults json
303
- });
304
- }
351
+ const resume = await this.db.sequelize.transaction(
352
+ async (transaction) => {
353
+ const locked = await jobsRepo.findOne({ filterByTk: jobId, transaction, lock: transaction.LOCK.UPDATE });
354
+ if (!locked || String(locked.get("status")) !== "polling") return void 0;
355
+ const pipeline = await pipelineRepo.findOne({
356
+ filter: { id: locked.get("pipelineId") },
357
+ appends: ["steps", "steps.endpoint"],
358
+ transaction
359
+ });
360
+ if (!pipeline) return void 0;
361
+ const steps = [...pipeline.steps || []].sort(
362
+ (a, b) => a.stepOrder - b.stepOrder
363
+ );
364
+ const currentStep = Number(locked.get("currentStep"));
365
+ const step = steps.find((s) => s.stepOrder === currentStep);
366
+ const stepResults = { ...locked.get("stepResults") || {} };
367
+ if (step) {
368
+ stepResults[step.outputAlias || step.stepOrder.toString()] = asyncResult;
369
+ }
370
+ await jobsRepo.update({
371
+ filterByTk: jobId,
372
+ values: {
373
+ status: "running",
374
+ ownedBy: this.nodeId,
375
+ leaseExpiresAt: new Date(Date.now() + import_AsyncJobManager.JOB_RUN_LEASE_MS),
376
+ stepResults
377
+ },
378
+ transaction
379
+ });
380
+ return { job: locked, steps, stepResults, currentStep };
381
+ }
382
+ );
383
+ if (!resume) return;
305
384
  const context = {
306
- input: job.input,
385
+ input: resume.job.get("input"),
307
386
  files: [],
308
387
  // Files cannot easily persist across webhook unless stored in bucket. For now assume next steps use only json.
309
- stepResults: job.stepResults,
310
- jobId: job.id
388
+ stepResults: resume.stepResults,
389
+ jobId: resume.job.id
311
390
  };
312
- this.runSteps(job, steps, context, job.currentStep + 1).catch((err) => {
313
- this.logger.error(`Failed executing step ${job.currentStep + 1} for job ${job.id}`, err);
391
+ this.runSteps(resume.job, resume.steps, context, resume.currentStep + 1).catch((err) => {
392
+ this.logger.error(`Failed executing step ${resume.currentStep + 1} for job ${resume.job.id}`, err);
314
393
  });
315
394
  }
316
395
  async finishJob(jobId, context) {
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "displayName": "Document Understanding",
4
4
  "displayName.zh-CN": "文档理解",
5
5
  "description": "Configure external document processing endpoints, chain them into pipelines, and expose enabled pipelines as AI tools.",
6
- "version": "1.1.11",
6
+ "version": "1.1.13",
7
7
  "license": "Apache-2.0",
8
8
  "main": "dist/server/index.js",
9
9
  "files": [
@@ -406,6 +406,57 @@ export const EndpointsTab = () => {
406
406
  </>
407
407
  ),
408
408
  },
409
+ {
410
+ key: 'gateway',
411
+ label: t('Gateway / Discriminator'),
412
+ children: (
413
+ <>
414
+ <Form.Item
415
+ name="discriminatorField"
416
+ label={t('Discriminator Field')}
417
+ help={t(
418
+ 'Form field that selects the API sub-case (e.g. mode/type/task/action/process). Sent automatically.',
419
+ )}
420
+ >
421
+ <Input placeholder="mode" style={{ width: 200 }} />
422
+ </Form.Item>
423
+ <Form.Item
424
+ name="discriminatorValue"
425
+ label={t('Discriminator Value')}
426
+ help={t('Value sent in the discriminator field (e.g. parse, invoice, disbursement).')}
427
+ >
428
+ <Input placeholder="parse" style={{ width: 200 }} />
429
+ </Form.Item>
430
+ <Form.Item
431
+ name="syncQueryParam"
432
+ label={t('Sync Query Param')}
433
+ help={t(
434
+ 'When set, the request appends ?<param>=true to ask for a synchronous response (e.g. sync).',
435
+ )}
436
+ >
437
+ <Input placeholder="sync" style={{ width: 200 }} />
438
+ </Form.Item>
439
+ <Form.Item
440
+ name="taskIdExtractPath"
441
+ label={t('Task ID Extract Path')}
442
+ help={t(
443
+ 'JSON path of the async task id in the 202 response (e.g. name). Used when the response is 202 even in sync mode.',
444
+ )}
445
+ >
446
+ <Input placeholder="name" style={{ width: 200 }} />
447
+ </Form.Item>
448
+ <Form.Item
449
+ name="taskIdExtractRegex"
450
+ label={t('Task ID Extract Regex')}
451
+ help={t(
452
+ 'Regex with one capture group to pull the task id from the extracted path value (e.g. operations/([^/]+)).',
453
+ )}
454
+ >
455
+ <Input placeholder="operations/([^/]+)" style={{ width: 240 }} />
456
+ </Form.Item>
457
+ </>
458
+ ),
459
+ },
409
460
  {
410
461
  key: 'async',
411
462
  label: t('Async Config'),