@exulu/backend 5.5.1 → 5.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-ZWFL6YUH.js → chunk-SJNP75II.js} +112 -5
- package/dist/{convert-exulu-tools-to-ai-sdk-tools-C5LYP4UN.js → convert-exulu-tools-to-ai-sdk-tools-7TYZVHEQ.js} +1 -1
- package/dist/index.cjs +1765 -550
- package/dist/index.js +1468 -378
- package/ee/queues/import-queue.ts +27 -0
- package/ee/queues/prune-job-results.test.ts +105 -1
- package/ee/queues/prune-job-results.ts +85 -9
- package/ee/queues/queues.ts +1 -0
- package/ee/workers.ts +173 -2
- package/package.json +1 -1
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { queues as ExuluQueues, global_queues } from "./queues";
|
|
2
|
+
import type { ExuluQueueConfig } from "@EXULU_TYPES/queue-config";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Server-side bulk import (CSV -> items): one job at a time, one context's
|
|
6
|
+
* import running per worker slot -- a bulk import already runs its own
|
|
7
|
+
* bounded concurrency pool internally (src/exulu/import/run-import.ts), so
|
|
8
|
+
* the queue just serializes whole import runs. The 6 h timeout covers a large
|
|
9
|
+
* file streamed + chunk-processed end to end.
|
|
10
|
+
*
|
|
11
|
+
* Both callers (ExuluApp's boot-time registration in src/exulu/app/index.ts
|
|
12
|
+
* and the StartImport/CancelImport resolvers' `getImportQueue()`) go through
|
|
13
|
+
* this one helper so the parameters cannot drift apart -- `register` is
|
|
14
|
+
* idempotent per queue name, so calling it from both is safe.
|
|
15
|
+
*/
|
|
16
|
+
export const IMPORT_QUEUE_CONCURRENCY = { worker: 1, queue: 1 };
|
|
17
|
+
export const IMPORT_QUEUE_RATELIMIT = 1;
|
|
18
|
+
export const IMPORT_QUEUE_TIMEOUT_SECONDS = 6 * 3600;
|
|
19
|
+
|
|
20
|
+
export function registerImportQueue(): { use: () => Promise<ExuluQueueConfig> } {
|
|
21
|
+
return ExuluQueues.register(
|
|
22
|
+
global_queues.import,
|
|
23
|
+
IMPORT_QUEUE_CONCURRENCY,
|
|
24
|
+
IMPORT_QUEUE_RATELIMIT,
|
|
25
|
+
IMPORT_QUEUE_TIMEOUT_SECONDS,
|
|
26
|
+
);
|
|
27
|
+
}
|
|
@@ -21,14 +21,21 @@ describe("maybePruneJobResults", () => {
|
|
|
21
21
|
whereInCalls.push(args);
|
|
22
22
|
return builder;
|
|
23
23
|
},
|
|
24
|
+
whereNot: () => builder,
|
|
25
|
+
whereRaw: () => builder,
|
|
26
|
+
orWhereNull: () => builder,
|
|
24
27
|
orderBy: () => builder,
|
|
25
28
|
offset: () => builder,
|
|
26
29
|
limit: () => builder,
|
|
27
30
|
first: async () => undefined, // under cap: nothing to delete
|
|
28
|
-
where: () =>
|
|
31
|
+
where: (arg: any) => {
|
|
32
|
+
if (typeof arg === "function") arg.call(builder);
|
|
33
|
+
return builder;
|
|
34
|
+
},
|
|
29
35
|
del: async () => 0,
|
|
30
36
|
};
|
|
31
37
|
const db: any = jest.fn(() => builder);
|
|
38
|
+
db.client = { config: { client: "pg" } };
|
|
32
39
|
|
|
33
40
|
// The module-level counter only reaches the prune body every 100th call.
|
|
34
41
|
for (let i = 0; i < 100; i++) {
|
|
@@ -39,3 +46,100 @@ describe("maybePruneJobResults", () => {
|
|
|
39
46
|
expect(whereInCalls[0]).toEqual(["state", TERMINAL_JOB_STATES]);
|
|
40
47
|
});
|
|
41
48
|
});
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Review Focus 7: import rows get their own, smaller, per-context retention
|
|
52
|
+
* instead of sharing the generic MAX_TERMINAL rolling window -- a tenant
|
|
53
|
+
* running frequent imports in one context should not crowd out every other
|
|
54
|
+
* context's/job type's terminal rows. Fake-db pattern: chainable builder
|
|
55
|
+
* recording every call per method name (as in
|
|
56
|
+
* src/exulu/email-inbound/intake.test.ts), so each assertion checks the
|
|
57
|
+
* actual knex calls the module made rather than its return value.
|
|
58
|
+
*/
|
|
59
|
+
describe("maybePruneJobResults -- import retention exemption", () => {
|
|
60
|
+
function fakeDb(opts: { dialect?: string; boundaryCreatedAt?: string } = {}) {
|
|
61
|
+
const calls: Record<string, any[][]> = {};
|
|
62
|
+
const builder: any = {};
|
|
63
|
+
const record =
|
|
64
|
+
(name: string) =>
|
|
65
|
+
(...args: any[]) => {
|
|
66
|
+
(calls[name] ||= []).push(args);
|
|
67
|
+
return builder;
|
|
68
|
+
};
|
|
69
|
+
builder.whereIn = record("whereIn");
|
|
70
|
+
builder.whereNot = record("whereNot");
|
|
71
|
+
builder.orWhereNull = record("orWhereNull");
|
|
72
|
+
// Grouped predicate: `.where((b) => b.whereNot(...).orWhereNull(...))`.
|
|
73
|
+
// Knex invokes the callback with `this` bound to a sub-builder -- record
|
|
74
|
+
// the call itself, then run the callback against this same builder so
|
|
75
|
+
// its whereNot/orWhereNull calls land in the same `calls` map (matching
|
|
76
|
+
// how the production code's grouped predicate is actually built).
|
|
77
|
+
builder.where = (...args: any[]) => {
|
|
78
|
+
(calls["where"] ||= []).push(args);
|
|
79
|
+
if (typeof args[0] === "function") args[0].call(builder);
|
|
80
|
+
return builder;
|
|
81
|
+
};
|
|
82
|
+
builder.whereRaw = record("whereRaw");
|
|
83
|
+
builder.orderBy = record("orderBy");
|
|
84
|
+
builder.offset = record("offset");
|
|
85
|
+
builder.limit = record("limit");
|
|
86
|
+
builder.first = jest.fn(async () =>
|
|
87
|
+
opts.boundaryCreatedAt ? { createdAt: opts.boundaryCreatedAt } : undefined,
|
|
88
|
+
);
|
|
89
|
+
builder.del = jest.fn(async () => 0);
|
|
90
|
+
const db: any = jest.fn(() => builder);
|
|
91
|
+
db.client = { config: { client: opts.dialect ?? "pg" } };
|
|
92
|
+
return { db, calls, del: builder.del as jest.Mock };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
it("excludes import rows from both the generic boundary query and its delete, via a grouped predicate", async () => {
|
|
96
|
+
const { db, calls } = fakeDb({ boundaryCreatedAt: "2026-01-01T00:00:00.000Z" });
|
|
97
|
+
for (let i = 0; i < 100; i++) await maybePruneJobResults(db);
|
|
98
|
+
|
|
99
|
+
// Both queries build the predicate as `.where((b) => b.whereNot({type:
|
|
100
|
+
// "import"}).orWhereNull("type"))` -- a plain top-level `.whereNot({type:
|
|
101
|
+
// "import"})` compiles to `not type = 'import'`, which SQL evaluates to
|
|
102
|
+
// NULL/false for a row with `type IS NULL`, making such rows unprunable
|
|
103
|
+
// forever (D-Fix F2). The grouped `orWhereNull` closes that gap.
|
|
104
|
+
expect((calls["where"] ?? []).length).toBeGreaterThanOrEqual(2);
|
|
105
|
+
const whereNotCalls = calls["whereNot"] ?? [];
|
|
106
|
+
expect(whereNotCalls.length).toBeGreaterThanOrEqual(2);
|
|
107
|
+
for (const args of whereNotCalls) {
|
|
108
|
+
expect(args[0]).toEqual({ type: "import" });
|
|
109
|
+
}
|
|
110
|
+
const orWhereNullCalls = calls["orWhereNull"] ?? [];
|
|
111
|
+
expect(orWhereNullCalls.length).toBeGreaterThanOrEqual(2);
|
|
112
|
+
for (const args of orWhereNullCalls) {
|
|
113
|
+
expect(args).toEqual(["type"]);
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it("runs its own per-context cap query and delete for import rows (Postgres)", async () => {
|
|
118
|
+
// No boundaryCreatedAt: the generic cap's own delete never fires (under
|
|
119
|
+
// cap), isolating this assertion to the import cap's independent delete.
|
|
120
|
+
const { db, calls, del } = fakeDb();
|
|
121
|
+
for (let i = 0; i < 100; i++) await maybePruneJobResults(db);
|
|
122
|
+
|
|
123
|
+
const whereRawCalls = calls["whereRaw"] ?? [];
|
|
124
|
+
expect(whereRawCalls.length).toBeGreaterThanOrEqual(1);
|
|
125
|
+
const [sql, bindings] = whereRawCalls[0]!;
|
|
126
|
+
expect(sql).toMatch(/row_number\(\)/i);
|
|
127
|
+
expect(sql).toMatch(/partition by context/i);
|
|
128
|
+
expect(bindings).toContain(200);
|
|
129
|
+
|
|
130
|
+
// Scoped to type = "import", and runs its own delete independent of the
|
|
131
|
+
// generic cap's boundary check above.
|
|
132
|
+
const typeWhereCalls = (calls["where"] ?? []).filter(
|
|
133
|
+
(args) => JSON.stringify(args[0]) === JSON.stringify({ type: "import" }),
|
|
134
|
+
);
|
|
135
|
+
expect(typeWhereCalls.length).toBeGreaterThanOrEqual(1);
|
|
136
|
+
expect(del).toHaveBeenCalledTimes(1);
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it("skips the per-context import cap on a non-Postgres dialect", async () => {
|
|
140
|
+
const { db, calls } = fakeDb({ dialect: "mysql" });
|
|
141
|
+
for (let i = 0; i < 100; i++) await maybePruneJobResults(db);
|
|
142
|
+
|
|
143
|
+
expect(calls["whereRaw"]).toBeUndefined();
|
|
144
|
+
});
|
|
145
|
+
});
|
|
@@ -17,6 +17,15 @@ import { TERMINAL_JOB_STATES } from "@EXULU_TYPES/enums/jobs";
|
|
|
17
17
|
|
|
18
18
|
const MAX_TERMINAL = 10_000;
|
|
19
19
|
const PRUNE_EVERY = 100;
|
|
20
|
+
/**
|
|
21
|
+
* Import runs (server-side bulk import) get their own, smaller, per-context
|
|
22
|
+
* cap instead of sharing the generic MAX_TERMINAL rolling window below -- a
|
|
23
|
+
* tenant running frequent imports in one context should not crowd out every
|
|
24
|
+
* other context's or job type's terminal rows, and 200 per context is plenty
|
|
25
|
+
* to review (older ones are still available in the context's own audit trail
|
|
26
|
+
* via the item rows they created/updated).
|
|
27
|
+
*/
|
|
28
|
+
const MAX_IMPORT_PER_CONTEXT = 200;
|
|
20
29
|
|
|
21
30
|
let sinceLastPrune = 0;
|
|
22
31
|
let pruning = false;
|
|
@@ -27,19 +36,50 @@ export async function maybePruneJobResults(db: any): Promise<void> {
|
|
|
27
36
|
sinceLastPrune = 0;
|
|
28
37
|
pruning = true;
|
|
29
38
|
try {
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
39
|
+
await pruneGenericJobResults(db);
|
|
40
|
+
await pruneImportJobResults(db);
|
|
41
|
+
} finally {
|
|
42
|
+
pruning = false;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Excludes import rows from the generic cap, on either a SELECT or a
|
|
48
|
+
* DELETE: a plain top-level `.whereNot({ type: "import" })` compiles to
|
|
49
|
+
* `not (type = 'import')`, and SQL's three-valued logic evaluates that to
|
|
50
|
+
* NULL (neither true nor false, so excluded from the result) for any row
|
|
51
|
+
* whose `type` is NULL -- making every untyped job_results row permanently
|
|
52
|
+
* unprunable (D-Fix F2). The grouped `orWhereNull("type")` catches those
|
|
53
|
+
* rows back into the generic cap, where they belong (they were never
|
|
54
|
+
* exempted on purpose -- `type` is just nullable on the column).
|
|
55
|
+
*/
|
|
56
|
+
function excludeImportType(builder: any): any {
|
|
57
|
+
return builder.where(function (this: any) {
|
|
58
|
+
this.whereNot({ type: "import" }).orWhereNull("type");
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The (MAX_TERMINAL+1)-th newest terminal row marks the boundary; delete it
|
|
64
|
+
* and everything older. Dialect-agnostic (knex offset/limit) so it works on
|
|
65
|
+
* both Postgres and MySQL. Import rows are excluded here (see
|
|
66
|
+
* excludeImportType) -- they get their own, smaller, per-context cap in
|
|
67
|
+
* pruneImportJobResults instead.
|
|
68
|
+
*/
|
|
69
|
+
async function pruneGenericJobResults(db: any): Promise<void> {
|
|
70
|
+
try {
|
|
71
|
+
const boundary = await excludeImportType(
|
|
72
|
+
db("job_results").whereIn("state", TERMINAL_JOB_STATES),
|
|
73
|
+
)
|
|
35
74
|
.orderBy("createdAt", "desc")
|
|
36
75
|
.offset(MAX_TERMINAL)
|
|
37
76
|
.limit(1)
|
|
38
77
|
.first();
|
|
39
78
|
|
|
40
79
|
if (boundary?.createdAt) {
|
|
41
|
-
const deleted = await
|
|
42
|
-
.whereIn("state", TERMINAL_JOB_STATES)
|
|
80
|
+
const deleted = await excludeImportType(
|
|
81
|
+
db("job_results").whereIn("state", TERMINAL_JOB_STATES),
|
|
82
|
+
)
|
|
43
83
|
.where("createdAt", "<=", boundary.createdAt)
|
|
44
84
|
.del();
|
|
45
85
|
if (deleted) {
|
|
@@ -50,7 +90,43 @@ export async function maybePruneJobResults(db: any): Promise<void> {
|
|
|
50
90
|
}
|
|
51
91
|
} catch (err) {
|
|
52
92
|
console.error("[EXULU] job_results prune failed", err);
|
|
53
|
-
}
|
|
54
|
-
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Per-context cap for import job_results rows: keeps only the newest
|
|
98
|
+
* MAX_IMPORT_PER_CONTEXT terminal rows per context, independent of the
|
|
99
|
+
* generic MAX_TERMINAL window above. Needs a Postgres window function
|
|
100
|
+
* (row_number() over (partition by context ...)), so this step is skipped
|
|
101
|
+
* entirely on any other knex dialect -- the generic cap above still bounds
|
|
102
|
+
* the table's overall size regardless, and this codebase only ever connects
|
|
103
|
+
* with the "pg" client (src/postgres/client.ts), so the guard is defensive
|
|
104
|
+
* rather than a real supported-dialect split.
|
|
105
|
+
*/
|
|
106
|
+
async function pruneImportJobResults(db: any): Promise<void> {
|
|
107
|
+
if (db.client?.config?.client !== "pg") return;
|
|
108
|
+
try {
|
|
109
|
+
const statePlaceholders = TERMINAL_JOB_STATES.map(() => "?").join(", ");
|
|
110
|
+
const deleted = await db("job_results")
|
|
111
|
+
.where({ type: "import" })
|
|
112
|
+
.whereRaw(
|
|
113
|
+
`id in (
|
|
114
|
+
select id from (
|
|
115
|
+
select id, row_number() over (partition by context order by "createdAt" desc) as rn
|
|
116
|
+
from job_results
|
|
117
|
+
where type = 'import' and state in (${statePlaceholders})
|
|
118
|
+
) ranked
|
|
119
|
+
where rn > ?
|
|
120
|
+
)`,
|
|
121
|
+
[...TERMINAL_JOB_STATES, MAX_IMPORT_PER_CONTEXT],
|
|
122
|
+
)
|
|
123
|
+
.del();
|
|
124
|
+
if (deleted) {
|
|
125
|
+
console.log(
|
|
126
|
+
`[EXULU] pruned ${deleted} terminal import job_results rows (cap ${MAX_IMPORT_PER_CONTEXT}/context).`,
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
} catch (err) {
|
|
130
|
+
console.error("[EXULU] import job_results prune failed", err);
|
|
55
131
|
}
|
|
56
132
|
}
|
package/ee/queues/queues.ts
CHANGED
package/ee/workers.ts
CHANGED
|
@@ -42,6 +42,11 @@ import { createRunSession } from "@SRC/exulu/routines/run-session.ts";
|
|
|
42
42
|
import { casJobResultState, parseRunMetadata, upsertWorkflowRunStart } from "@SRC/exulu/routines/run-state.ts";
|
|
43
43
|
import { findLiteLLMModel } from "@SRC/exulu/litellm/catalog.ts";
|
|
44
44
|
import { computeRunCostUsd } from "@SRC/exulu/routines/run-cost.ts";
|
|
45
|
+
import { getS3ObjectStream } from "@SRC/uppy";
|
|
46
|
+
import { runImport, ImportAbort } from "@SRC/exulu/import/run-import.ts";
|
|
47
|
+
import { buildWorkerDeps, finalizeCancelled, parseMetadata } from "@SRC/exulu/import/worker-deps.ts";
|
|
48
|
+
import { importFieldsFor } from "@SRC/exulu/import/mapping.ts";
|
|
49
|
+
import type { ImportJobData } from "@EXULU_TYPES/queue-config.ts";
|
|
45
50
|
|
|
46
51
|
/**
|
|
47
52
|
* Session-backed runs persist messages at each step boundary, so retries must
|
|
@@ -209,9 +214,9 @@ export const createWorkers = async (
|
|
|
209
214
|
type: bullmqJob.data.type,
|
|
210
215
|
});
|
|
211
216
|
|
|
212
|
-
// For long-running processor jobs, set up progress heartbeat to prevent stalling
|
|
217
|
+
// For long-running processor/import jobs, set up progress heartbeat to prevent stalling
|
|
213
218
|
let progressInterval: NodeJS.Timeout | undefined;
|
|
214
|
-
if (bullmqJob.data.type === "processor") {
|
|
219
|
+
if (bullmqJob.data.type === "processor" || bullmqJob.data.type === "import") {
|
|
215
220
|
// Update progress every 25 seconds to keep the job alive
|
|
216
221
|
// This prevents BullMQ from marking the job as stalled during long-running operations
|
|
217
222
|
progressInterval = setInterval(async () => {
|
|
@@ -1109,6 +1114,172 @@ export const createWorkers = async (
|
|
|
1109
1114
|
};
|
|
1110
1115
|
}
|
|
1111
1116
|
|
|
1117
|
+
if (data.type === "import") {
|
|
1118
|
+
console.log("[EXULU] running a server-side bulk import job.", bullmqJob.name);
|
|
1119
|
+
|
|
1120
|
+
if (!data.jobResultId) {
|
|
1121
|
+
throw new Error(`No jobResultId set for import job ${bullmqJob.id}.`);
|
|
1122
|
+
}
|
|
1123
|
+
if (!data.context) {
|
|
1124
|
+
throw new Error(`No context id set for import job ${bullmqJob.id}.`);
|
|
1125
|
+
}
|
|
1126
|
+
// Narrowed, exact shape of this job type's data (types/queue-config.ts)
|
|
1127
|
+
// now that the two required fields above are confirmed present.
|
|
1128
|
+
const importData: ImportJobData = {
|
|
1129
|
+
type: "import",
|
|
1130
|
+
jobResultId: data.jobResultId,
|
|
1131
|
+
context: data.context,
|
|
1132
|
+
user: data.user,
|
|
1133
|
+
role: data.role,
|
|
1134
|
+
};
|
|
1135
|
+
const jobResultId = importData.jobResultId;
|
|
1136
|
+
|
|
1137
|
+
// The StartImport mutation (Task 5) inserts this row (state
|
|
1138
|
+
// "waiting", job_id = its own id) before enqueuing -- load it by
|
|
1139
|
+
// jobResultId (== job_id == bullmqJob.id) for its trigger_metadata
|
|
1140
|
+
// (s3Key/mapping/access/options/user) and current metadata.
|
|
1141
|
+
const row = await db
|
|
1142
|
+
.from("job_results")
|
|
1143
|
+
.where({ id: jobResultId })
|
|
1144
|
+
.first();
|
|
1145
|
+
if (!row) {
|
|
1146
|
+
throw new Error(
|
|
1147
|
+
`job_results row ${jobResultId} not found for import job ${bullmqJob.id}.`,
|
|
1148
|
+
);
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
// Stalled re-delivery guard: `attempts: 1` stops *failure*
|
|
1152
|
+
// retries, but BullMQ's stalled recovery (lockDuration 5 min,
|
|
1153
|
+
// stalledInterval 2 min, maxStalledCount 1 below) still moves
|
|
1154
|
+
// the job back to `wait` once after a worker crash, a long
|
|
1155
|
+
// event-loop block, or a Redis gap. Restarting the stream from
|
|
1156
|
+
// row 0 would re-create every key-less row a second time and
|
|
1157
|
+
// reset the counters, so a second pickup fails loudly instead:
|
|
1158
|
+
// the "failed" handler records this message on the row, which
|
|
1159
|
+
// also reopens the context's one-import gate (D6).
|
|
1160
|
+
const priorMetadata = parseMetadata(row.metadata);
|
|
1161
|
+
const priorProcessed = Number(priorMetadata.processed ?? 0);
|
|
1162
|
+
if (row.state === JOB_STATUS_ENUM.active || priorProcessed > 0) {
|
|
1163
|
+
throw new Error(
|
|
1164
|
+
`IMPORT_RESTARTED_AFTER_STALL: import ${jobResultId} was already running; ` +
|
|
1165
|
+
`partial rows are kept, start a new import`,
|
|
1166
|
+
);
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
// Moves the row to "active" (CAS-free: the row is keyed by
|
|
1170
|
+
// job_id, owned by this one worker pickup).
|
|
1171
|
+
await upsertJobStart(db, bullmqJob, row.label, "import");
|
|
1172
|
+
|
|
1173
|
+
const context = contexts.find((c) => c.id === importData.context);
|
|
1174
|
+
if (!context) {
|
|
1175
|
+
throw new Error(`Context ${importData.context} not found in the registry.`);
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
const triggerMetadata = parseRunMetadata(row.trigger_metadata) as {
|
|
1179
|
+
s3Key?: string;
|
|
1180
|
+
fileName?: string;
|
|
1181
|
+
mapping?: any;
|
|
1182
|
+
access?: any;
|
|
1183
|
+
options?: { skipEmbeddings?: boolean; delimiter?: string };
|
|
1184
|
+
user?: unknown;
|
|
1185
|
+
};
|
|
1186
|
+
if (!triggerMetadata.s3Key) {
|
|
1187
|
+
throw new Error(
|
|
1188
|
+
`No s3Key recorded on job_results row ${jobResultId} for import job.`,
|
|
1189
|
+
);
|
|
1190
|
+
}
|
|
1191
|
+
if (!triggerMetadata.access) {
|
|
1192
|
+
throw new Error(
|
|
1193
|
+
`No batch access recorded on job_results row ${jobResultId} for import job.`,
|
|
1194
|
+
);
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
// trigger_metadata.user is a snapshot of the acting user
|
|
1198
|
+
// ({ id, super_admin, role, team }) taken at StartImport time --
|
|
1199
|
+
// the top-level importData.user/importData.role on the BullMQ
|
|
1200
|
+
// job are plain ids/strings and carry neither super_admin nor
|
|
1201
|
+
// team, which canWrite needs. The snapshot may also just be a
|
|
1202
|
+
// bare id (number or numeric string); `snap ?? importData.user`
|
|
1203
|
+
// only reaches that branch when `snap` itself is not an object,
|
|
1204
|
+
// so a bare-number snapshot (not just a wholly absent one) also
|
|
1205
|
+
// falls back correctly -- `triggerMetadata.user ?? {...}` did
|
|
1206
|
+
// not (a bare number is not nullish, so it short-circuited the
|
|
1207
|
+
// fallback and `importUser` ended up as that raw number instead
|
|
1208
|
+
// of an object with an `.id`).
|
|
1209
|
+
const snap = triggerMetadata.user as
|
|
1210
|
+
| { id?: unknown; super_admin?: unknown; role?: unknown; team?: unknown }
|
|
1211
|
+
| number
|
|
1212
|
+
| string
|
|
1213
|
+
| undefined;
|
|
1214
|
+
const importUser =
|
|
1215
|
+
snap && typeof snap === "object"
|
|
1216
|
+
? {
|
|
1217
|
+
id: Number(snap.id),
|
|
1218
|
+
super_admin: snap.super_admin === true,
|
|
1219
|
+
role: snap.role,
|
|
1220
|
+
team: snap.team,
|
|
1221
|
+
}
|
|
1222
|
+
: { id: Number(snap ?? importData.user), role: importData.role };
|
|
1223
|
+
if (!importUser.id) {
|
|
1224
|
+
throw new Error(`No acting user recorded for import job ${bullmqJob.id}.`);
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
// trigger_metadata.s3Key arrives in the frontend's "bucket/key"
|
|
1228
|
+
// form (same as uploadFile's return value) -- getS3ObjectStream
|
|
1229
|
+
// wants the bare key.
|
|
1230
|
+
const bareS3Key = triggerMetadata.s3Key.slice(triggerMetadata.s3Key.indexOf("/") + 1);
|
|
1231
|
+
const stream = await getS3ObjectStream(bareS3Key, config);
|
|
1232
|
+
|
|
1233
|
+
try {
|
|
1234
|
+
const deps = buildWorkerDeps({
|
|
1235
|
+
db,
|
|
1236
|
+
config,
|
|
1237
|
+
context,
|
|
1238
|
+
contextId: importData.context,
|
|
1239
|
+
jobResultId,
|
|
1240
|
+
stream,
|
|
1241
|
+
fields: importFieldsFor(context.fields),
|
|
1242
|
+
mapping: triggerMetadata.mapping,
|
|
1243
|
+
access: triggerMetadata.access,
|
|
1244
|
+
options: triggerMetadata.options ?? {},
|
|
1245
|
+
user: importUser,
|
|
1246
|
+
log: (m: string) => console.log(`[EXULU] import ${jobResultId}: ${m}`),
|
|
1247
|
+
// The row count StartImport seeded into metadata.total
|
|
1248
|
+
// (from the caller's `totalRows`); buildWorkerDeps treats a
|
|
1249
|
+
// 0/absent value as "unknown" so the progress patch does
|
|
1250
|
+
// not overwrite it with null on the first tick.
|
|
1251
|
+
total: priorMetadata.total,
|
|
1252
|
+
});
|
|
1253
|
+
|
|
1254
|
+
const result = await runImport(deps);
|
|
1255
|
+
|
|
1256
|
+
if (result.cancelled) {
|
|
1257
|
+
// The completed handler's CAS only fires `WHERE state =
|
|
1258
|
+
// "active"` -- finalizeCancelled flips the row to
|
|
1259
|
+
// "cancelled" (so that CAS no longer matches and the state
|
|
1260
|
+
// stays "cancelled" instead of being overwritten back to
|
|
1261
|
+
// "completed") AND persists `result`/`errorReportKey` in
|
|
1262
|
+
// the same statement, since no handler will run for this
|
|
1263
|
+
// return value once the row is no longer "active".
|
|
1264
|
+
await finalizeCancelled(db, row.id, result);
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
return { result, metadata: result };
|
|
1268
|
+
} catch (error: unknown) {
|
|
1269
|
+
if (error instanceof ImportAbort) {
|
|
1270
|
+
console.error(`[EXULU] import ${jobResultId} aborted: ${error.code}`);
|
|
1271
|
+
}
|
|
1272
|
+
throw error;
|
|
1273
|
+
} finally {
|
|
1274
|
+
// The worker owns the S3 stream's lifecycle -- csv-stream.ts
|
|
1275
|
+
// only forwards a source error into the parser, it never
|
|
1276
|
+
// destroys the source itself. Safe to call unconditionally:
|
|
1277
|
+
// a stream already ended (full read) or already destroyed
|
|
1278
|
+
// (prior error) is a no-op.
|
|
1279
|
+
stream.destroy();
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1112
1283
|
if (data.type === "email_intake") {
|
|
1113
1284
|
console.log("[EXULU] running a routine webhook intake job.", bullmqJob.name);
|
|
1114
1285
|
if (!data.inputs?.s3Key || !data.inputs?.triggerId) {
|