plugin-document-understanding 1.1.11 → 1.1.12

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.
@@ -1 +1 @@
1
- {"author":"Felix Geisendörfer <felix@debuggable.com> (http://debuggable.com/)","name":"form-data","description":"A library to create readable \"multipart/form-data\" streams. Can be used to submit forms and file uploads to other web applications.","version":"4.0.5","repository":{"type":"git","url":"git://github.com/form-data/form-data.git"},"main":"./lib/form_data","browser":"./lib/browser","typings":"./index.d.ts","scripts":{"pretest":"npm run lint","pretests-only":"rimraf coverage test/tmp","tests-only":"istanbul cover test/run.js","posttests-only":"istanbul report lcov text","test":"npm run tests-only","posttest":"npx npm@'>=10.2' audit --production","lint":"eslint --ext=js,mjs .","report":"istanbul report lcov text","ci-lint":"is-node-modern 8 && npm run lint || is-node-not-modern 8","ci-test":"npm run tests-only && npm run browser && npm run report","predebug":"rimraf coverage test/tmp","debug":"verbose=1 ./test/run.js","browser":"browserify -t browserify-istanbul test/run-browser.js | obake --coverage","check":"istanbul check-coverage coverage/coverage*.json","files":"pkgfiles --sort=name","get-version":"node -e \"console.log(require('./package.json').version)\"","update-readme":"sed -i.bak 's/\\/master\\.svg/\\/v'$(npm --silent run get-version)'.svg/g' README.md","postupdate-readme":"mv README.md.bak READ.ME.md.bak","restore-readme":"mv READ.ME.md.bak README.md","prepublish":"not-in-publish || npm run prepublishOnly","prepack":"npm run update-readme","postpack":"npm run restore-readme","version":"auto-changelog && git add CHANGELOG.md","postversion":"auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\""},"engines":{"node":">= 6"},"dependencies":{"asynckit":"^0.4.0","combined-stream":"^1.0.8","es-set-tostringtag":"^2.1.0","hasown":"^2.0.2","mime-types":"^2.1.12"},"devDependencies":{"@ljharb/eslint-config":"^21.4.0","auto-changelog":"^2.5.0","browserify":"^13.3.0","browserify-istanbul":"^2.0.0","coveralls":"^3.1.1","cross-spawn":"^6.0.6","eslint":"^8.57.1","fake":"^0.2.2","far":"^0.0.7","formidable":"^1.2.6","in-publish":"^2.0.1","is-node-modern":"^1.0.0","istanbul":"^0.4.5","js-randomness-predictor":"^1.5.5","obake":"^0.1.2","pkgfiles":"^2.3.2","pre-commit":"^1.2.2","puppeteer":"^1.20.0","request":"~2.87.0","rimraf":"^2.7.1","semver":"^6.3.1","tape":"^5.9.0"},"license":"MIT","auto-changelog":{"output":"CHANGELOG.md","template":"keepachangelog","unreleased":false,"commitLimit":false,"backfillLimit":false,"hideCredit":true},"_lastModified":"2026-04-09T17:58:37.184Z"}
1
+ {"author":"Felix Geisendörfer <felix@debuggable.com> (http://debuggable.com/)","name":"form-data","description":"A library to create readable \"multipart/form-data\" streams. Can be used to submit forms and file uploads to other web applications.","version":"4.0.6","repository":{"type":"git","url":"git://github.com/form-data/form-data.git"},"main":"./lib/form_data","browser":"./lib/browser","typings":"./index.d.ts","scripts":{"pretest":"npm run lint","pretests-only":"rimraf coverage test/tmp","tests-only":"istanbul cover test/run.js","posttests-only":"istanbul report lcov text","test":"npm run tests-only","posttest":"npx npm@'>=10.2' audit --production","lint":"eslint --ext=js,mjs .","report":"istanbul report lcov text","ci-lint":"is-node-modern 8 && npm run lint || is-node-not-modern 8","ci-test":"npm run tests-only && npm run browser && npm run report","predebug":"rimraf coverage test/tmp","debug":"verbose=1 ./test/run.js","browser":"browserify -t browserify-istanbul test/run-browser.js | obake --coverage","check":"istanbul check-coverage coverage/coverage*.json","files":"pkgfiles --sort=name","get-version":"node -e \"console.log(require('./package.json').version)\"","update-readme":"sed -i.bak 's/\\/master\\.svg/\\/v'$(npm --silent run get-version)'.svg/g' README.md","postupdate-readme":"mv README.md.bak READ.ME.md.bak","restore-readme":"mv READ.ME.md.bak README.md","prepublish":"not-in-publish || npm run prepublishOnly","prepack":"npm run update-readme","postpack":"npm run restore-readme","version":"auto-changelog && git add CHANGELOG.md","postversion":"auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\""},"engines":{"node":">= 6"},"dependencies":{"asynckit":"^0.4.0","combined-stream":"^1.0.8","es-set-tostringtag":"^2.1.0","hasown":"^2.0.4","mime-types":"^2.1.35"},"devDependencies":{"@ljharb/eslint-config":"^22.2.3","auto-changelog":"^2.6.0","browserify":"^13.3.0","browserify-istanbul":"^2.0.0","coveralls":"^3.1.1","cross-spawn":"^6.0.6","eslint":"^8.57.1","fake":"^0.2.2","far":"^0.0.7","formidable":"^1.2.6","in-publish":"^2.0.1","is-node-modern":"^1.0.0","istanbul":"^0.4.5","js-randomness-predictor":"^3.6.0","obake":"^0.1.2","pkgfiles":"^2.3.2","pre-commit":"^1.2.2","puppeteer":"^1.20.0","request":"~2.87.0","rimraf":"^2.7.1","semver":"^6.3.1","tape":"^5.10.1"},"license":"MIT","auto-changelog":{"output":"CHANGELOG.md","template":"keepachangelog","unreleased":false,"commitLimit":false,"backfillLimit":false,"hideCredit":true},"_lastModified":"2026-08-17T10:39:36.887Z"}
@@ -48,11 +48,24 @@ var jobs_default = {
48
48
  { type: "json", name: "externalTaskIds" },
49
49
  { type: "date", name: "startedAt" },
50
50
  { type: "date", name: "completedAt" },
51
+ // Cluster ownership: which node is executing/polling this job, and until when
52
+ // its lease is valid. Orphaned jobs (owner restarted or lease expired) are
53
+ // failed or re-adopted by the maintenance sweep.
54
+ { type: "string", name: "ownedBy", length: 255 },
55
+ { type: "date", name: "leaseExpiresAt" },
51
56
  {
52
57
  type: "belongsTo",
53
58
  name: "createdBy",
54
59
  target: "users",
55
60
  foreignKey: "createdById"
56
61
  }
62
+ ],
63
+ indexes: [
64
+ {
65
+ fields: ["status"]
66
+ },
67
+ {
68
+ fields: ["leaseExpiresAt"]
69
+ }
57
70
  ]
58
71
  };
@@ -26,9 +26,17 @@ var __copyProps = (to, from, except, desc) => {
26
26
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
27
  var AsyncJobManager_exports = {};
28
28
  __export(AsyncJobManager_exports, {
29
- AsyncJobManager: () => AsyncJobManager
29
+ AsyncJobManager: () => AsyncJobManager,
30
+ JOB_RUN_LEASE_MS: () => JOB_RUN_LEASE_MS,
31
+ pollLeaseMs: () => pollLeaseMs
30
32
  });
31
33
  module.exports = __toCommonJS(AsyncJobManager_exports);
34
+ const JOB_RUN_LEASE_MS = 10 * 60 * 1e3;
35
+ const JOB_POLL_LEASE_MIN_MS = 60 * 1e3;
36
+ function pollLeaseMs(pollInterval) {
37
+ return Math.max((pollInterval || 5e3) * 3, JOB_POLL_LEASE_MIN_MS);
38
+ }
39
+ const JOBS_COLLECTION = "doc_understanding_jobs";
32
40
  class AsyncJobManager {
33
41
  db;
34
42
  apiClient;
@@ -36,12 +44,14 @@ class AsyncJobManager {
36
44
  onJobComplete;
37
45
  onJobError;
38
46
  logger;
39
- constructor(db, apiClient, callbacks, logger) {
47
+ nodeId;
48
+ constructor(db, apiClient, callbacks, logger, nodeId) {
40
49
  this.db = db;
41
50
  this.apiClient = apiClient;
42
51
  this.onJobComplete = callbacks.onJobComplete;
43
52
  this.onJobError = callbacks.onJobError;
44
53
  this.logger = logger;
54
+ this.nodeId = nodeId;
45
55
  }
46
56
  async startPolling(jobId, endpoint, taskId, customInterval, customTimeout) {
47
57
  if (this.intervals.has(jobId)) return;
@@ -55,8 +65,13 @@ class AsyncJobManager {
55
65
  await this.onJobError(jobId, "Polling timeout exceeded");
56
66
  return;
57
67
  }
68
+ if (!await this.refreshLease(jobId, endpoint)) {
69
+ this.stopPolling(jobId);
70
+ return;
71
+ }
58
72
  const pollResultSubpath = endpoint.pollResultSubpath;
59
73
  if (!pollResultSubpath) {
74
+ this.stopPolling(jobId);
60
75
  await this.onJobError(jobId, "Polling result subpath is not configured");
61
76
  return;
62
77
  }
@@ -87,39 +102,54 @@ class AsyncJobManager {
87
102
  }, interval);
88
103
  this.intervals.set(jobId, timer);
89
104
  }
105
+ async refreshLease(jobId, endpoint) {
106
+ const jobsRepo = this.db.getRepository(JOBS_COLLECTION);
107
+ const updated = await jobsRepo.update({
108
+ filter: { id: jobId, status: "polling", ownedBy: this.nodeId },
109
+ values: { leaseExpiresAt: new Date(Date.now() + pollLeaseMs(endpoint.pollInterval)) }
110
+ });
111
+ return Array.isArray(updated) ? updated.length > 0 : Boolean(updated);
112
+ }
90
113
  /**
91
- * Transition pending and running jobs to failed state during startup.
114
+ * Fail pending/running jobs that can no longer be executing. First the jobs
115
+ * this node owned (in-memory execution state is lost across a restart), then
116
+ * any remaining job whose owner lease expired. Rows without a lease predate
117
+ * ownership tracking and are treated as orphaned too.
92
118
  */
93
- async cleanupStuckJobs() {
94
- const jobsRepo = this.db.getRepository("doc_understanding_jobs");
95
- const stuckJobs = await jobsRepo.find({
119
+ async failOrphanedActiveJobs() {
120
+ const jobsRepo = this.db.getRepository(JOBS_COLLECTION);
121
+ const now = /* @__PURE__ */ new Date();
122
+ await jobsRepo.update({
123
+ filter: { status: { $in: ["pending", "running"] }, ownedBy: this.nodeId },
124
+ values: { status: "failed", error: "Server restarted during execution", completedAt: now }
125
+ });
126
+ await jobsRepo.update({
96
127
  filter: {
97
- status: ["pending", "running"]
98
- }
128
+ status: { $in: ["pending", "running"] },
129
+ $or: [{ leaseExpiresAt: { $lt: now } }, { leaseExpiresAt: null }]
130
+ },
131
+ values: { status: "failed", error: "Job lease expired before completion", completedAt: now }
99
132
  });
100
- for (const job of stuckJobs) {
101
- await jobsRepo.update({
102
- filterByTk: job.id,
103
- values: {
104
- status: "failed",
105
- error: "Server restarted during execution",
106
- completedAt: /* @__PURE__ */ new Date()
107
- }
108
- });
109
- }
110
133
  }
111
134
  /**
112
- * Recover polling jobs that were in-flight when server restarted.
113
- * Call this during service initialization.
135
+ * Re-adopt 'polling' jobs whose owner can no longer be polling them: jobs this
136
+ * node owned before a restart, jobs whose lease expired, and legacy rows without
137
+ * ownership. Webhook-mode jobs are skipped — nothing polls them, and any node
138
+ * can process the webhook when it arrives.
114
139
  */
115
- async recoverPollingJobs() {
116
- var _a;
117
- const jobsRepo = this.db.getRepository("doc_understanding_jobs");
118
- const stuckJobs = await jobsRepo.find({ filter: { status: "polling" } });
119
- for (const job of stuckJobs) {
120
- if (!job.externalTaskIds) continue;
121
- const stepKey = job.currentStep.toString();
122
- const taskId = job.externalTaskIds[stepKey];
140
+ async adoptOrphanedPollingJobs() {
141
+ const jobsRepo = this.db.getRepository(JOBS_COLLECTION);
142
+ const now = /* @__PURE__ */ new Date();
143
+ const candidates = await jobsRepo.find({
144
+ filter: {
145
+ status: "polling",
146
+ $or: [{ ownedBy: this.nodeId }, { leaseExpiresAt: { $lt: now } }, { ownedBy: null }]
147
+ }
148
+ });
149
+ for (const job of candidates) {
150
+ const externalTaskIds = job.externalTaskIds || {};
151
+ const stepKey = String(job.currentStep);
152
+ const taskId = externalTaskIds[stepKey];
123
153
  if (!taskId) continue;
124
154
  const pipelineRepo = this.db.getRepository("doc_understanding_pipelines");
125
155
  const pipeline = await pipelineRepo.findOne({
@@ -127,11 +157,35 @@ class AsyncJobManager {
127
157
  appends: ["steps", "steps.endpoint"]
128
158
  });
129
159
  if (!pipeline) continue;
130
- const step = (_a = pipeline.steps) == null ? void 0 : _a.find((s) => s.stepOrder === job.currentStep);
160
+ const steps = pipeline.steps || [];
161
+ const step = steps.find((s) => s.stepOrder === job.currentStep);
131
162
  if (!(step == null ? void 0 : step.endpoint) || step.endpoint.executionMode !== "polling") continue;
132
- await this.startPolling(job.id, step.endpoint, taskId);
163
+ if (await this.claimJobForPolling(job.id, step.endpoint)) {
164
+ await this.startPolling(job.id, step.endpoint, taskId);
165
+ }
133
166
  }
134
167
  }
168
+ async claimJobForPolling(jobId, endpoint) {
169
+ return this.db.sequelize.transaction(async (transaction) => {
170
+ const jobsRepo = this.db.getRepository(JOBS_COLLECTION);
171
+ const row = await jobsRepo.findOne({ filterByTk: jobId, transaction, lock: transaction.LOCK.UPDATE });
172
+ if (!row) return false;
173
+ if (String(row.get("status")) !== "polling") return false;
174
+ const owner = row.get("ownedBy");
175
+ const lease = row.get("leaseExpiresAt");
176
+ const leaseValid = lease != null && new Date(lease).getTime() > Date.now();
177
+ if (owner !== this.nodeId && leaseValid) return false;
178
+ await jobsRepo.update({
179
+ filterByTk: jobId,
180
+ values: {
181
+ ownedBy: this.nodeId,
182
+ leaseExpiresAt: new Date(Date.now() + pollLeaseMs(endpoint.pollInterval))
183
+ },
184
+ transaction
185
+ });
186
+ return true;
187
+ });
188
+ }
135
189
  stopPolling(jobId) {
136
190
  const timer = this.intervals.get(jobId);
137
191
  if (timer) {
@@ -152,5 +206,7 @@ class AsyncJobManager {
152
206
  }
153
207
  // Annotate the CommonJS export names for ESM import in node:
154
208
  0 && (module.exports = {
155
- AsyncJobManager
209
+ AsyncJobManager,
210
+ JOB_RUN_LEASE_MS,
211
+ pollLeaseMs
156
212
  });
@@ -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;
@@ -43,6 +43,7 @@ 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}`);
48
49
  function resolveUploadFilePath(urlOrPath) {
@@ -84,11 +85,13 @@ class PipelineExecutor {
84
85
  apiClient;
85
86
  jobManager;
86
87
  logger;
87
- constructor(db, apiClient, jobManager, logger) {
88
+ nodeId;
89
+ constructor(db, apiClient, jobManager, logger, nodeId = "") {
88
90
  this.db = db;
89
91
  this.apiClient = apiClient;
90
92
  this.jobManager = jobManager;
91
93
  this.logger = logger;
94
+ this.nodeId = nodeId;
92
95
  }
93
96
  async resolveFile(urlOrPath, fieldName = "file") {
94
97
  var _a, _b, _c, _d;
@@ -133,7 +136,9 @@ class PipelineExecutor {
133
136
  stepResults: {},
134
137
  externalTaskIds: {},
135
138
  startedAt: /* @__PURE__ */ new Date(),
136
- createdById: userId
139
+ createdById: userId,
140
+ ownedBy: this.nodeId,
141
+ leaseExpiresAt: new Date(Date.now() + import_AsyncJobManager.JOB_RUN_LEASE_MS)
137
142
  }
138
143
  });
139
144
  const resolvedFiles = [];
@@ -208,12 +213,18 @@ class PipelineExecutor {
208
213
  const jobsRepo = this.db.getRepository("doc_understanding_jobs");
209
214
  let currentOrder = startFromOrder;
210
215
  try {
211
- await jobsRepo.update({ filterByTk: job.id, values: { status: "running" } });
216
+ await jobsRepo.update({
217
+ filterByTk: job.id,
218
+ values: { status: "running", ownedBy: this.nodeId, leaseExpiresAt: new Date(Date.now() + import_AsyncJobManager.JOB_RUN_LEASE_MS) }
219
+ });
212
220
  for (const step of steps) {
213
221
  if (step.stepOrder < startFromOrder) continue;
214
222
  context.jobId = job.id;
215
223
  currentOrder = step.stepOrder;
216
- await jobsRepo.update({ filterByTk: job.id, values: { currentStep: currentOrder } });
224
+ await jobsRepo.update({
225
+ filterByTk: job.id,
226
+ values: { currentStep: currentOrder, leaseExpiresAt: new Date(Date.now() + import_AsyncJobManager.JOB_RUN_LEASE_MS) }
227
+ });
217
228
  if (!this.evaluateCondition(step.condition, context)) {
218
229
  continue;
219
230
  }
@@ -247,7 +258,12 @@ class PipelineExecutor {
247
258
  externalTaskIds[step.stepOrder.toString()] = taskId;
248
259
  await jobsRepo.update({
249
260
  filterByTk: job.id,
250
- values: { status: "polling", externalTaskIds }
261
+ values: {
262
+ status: "polling",
263
+ externalTaskIds,
264
+ // This node keeps polling and refreshes the lease on every tick.
265
+ leaseExpiresAt: new Date(Date.now() + (0, import_AsyncJobManager.pollLeaseMs)(step.endpoint.pollInterval))
266
+ }
251
267
  });
252
268
  await this.jobManager.startPolling(job.id, step.endpoint, taskId);
253
269
  return;
@@ -258,7 +274,13 @@ class PipelineExecutor {
258
274
  externalTaskIds[step.stepOrder.toString()] = taskId;
259
275
  await jobsRepo.update({
260
276
  filterByTk: job.id,
261
- values: { status: "polling", externalTaskIds }
277
+ values: {
278
+ status: "polling",
279
+ externalTaskIds,
280
+ // No process actively owns a webhook wait: the callback may arrive
281
+ // at any node, so there is no lease to renew.
282
+ leaseExpiresAt: null
283
+ }
262
284
  });
263
285
  return;
264
286
  }
@@ -284,33 +306,48 @@ class PipelineExecutor {
284
306
  async resumeFromStep(jobId, asyncResult) {
285
307
  const jobsRepo = this.db.getRepository("doc_understanding_jobs");
286
308
  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
- }
309
+ const resume = await this.db.sequelize.transaction(
310
+ async (transaction) => {
311
+ const locked = await jobsRepo.findOne({ filterByTk: jobId, transaction, lock: transaction.LOCK.UPDATE });
312
+ if (!locked || String(locked.get("status")) !== "polling") return void 0;
313
+ const pipeline = await pipelineRepo.findOne({
314
+ filter: { id: locked.get("pipelineId") },
315
+ appends: ["steps", "steps.endpoint"],
316
+ transaction
317
+ });
318
+ if (!pipeline) return void 0;
319
+ const steps = [...pipeline.steps || []].sort(
320
+ (a, b) => a.stepOrder - b.stepOrder
321
+ );
322
+ const currentStep = Number(locked.get("currentStep"));
323
+ const step = steps.find((s) => s.stepOrder === currentStep);
324
+ const stepResults = { ...locked.get("stepResults") || {} };
325
+ if (step) {
326
+ stepResults[step.outputAlias || step.stepOrder.toString()] = asyncResult;
327
+ }
328
+ await jobsRepo.update({
329
+ filterByTk: jobId,
330
+ values: {
331
+ status: "running",
332
+ ownedBy: this.nodeId,
333
+ leaseExpiresAt: new Date(Date.now() + import_AsyncJobManager.JOB_RUN_LEASE_MS),
334
+ stepResults
335
+ },
336
+ transaction
337
+ });
338
+ return { job: locked, steps, stepResults, currentStep };
339
+ }
340
+ );
341
+ if (!resume) return;
305
342
  const context = {
306
- input: job.input,
343
+ input: resume.job.get("input"),
307
344
  files: [],
308
345
  // 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
346
+ stepResults: resume.stepResults,
347
+ jobId: resume.job.id
311
348
  };
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);
349
+ this.runSteps(resume.job, resume.steps, context, resume.currentStep + 1).catch((err) => {
350
+ this.logger.error(`Failed executing step ${resume.currentStep + 1} for job ${resume.job.id}`, err);
314
351
  });
315
352
  }
316
353
  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.12",
7
7
  "license": "Apache-2.0",
8
8
  "main": "dist/server/index.js",
9
9
  "files": [