Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
refactor(jobs): the export and bulk-action jobs share one failure handler and remove their files by folder instead of guessing how many there are
aashu14189b907ec9
diff --git a/packages/jobs/src/inngest/functions/tasks/table-bulk-action.ts b/packages/jobs/src/inngest/functions/tasks/table-bulk-action.tsindex f0766f81a1..0d694a193a 100644--- a/packages/jobs/src/inngest/functions/tasks/table-bulk-action.ts+++ b/packages/jobs/src/inngest/functions/tasks/table-bulk-action.ts@@ -20,6 +20,7 @@ import {collectIds,storeSelectedIds} from "../../../table-jobs/bulk-run";+import { failTableJob } from "../../../table-jobs/failure";import {requireTableJobHandlers,type TableBulkAction,@@ -31,8 +32,9 @@ import {releaseTableJobLock} from "../../../table-jobs/lock";import { notifyTableJobUser } from "../../../table-jobs/notify";-import { TABLE_JOB_ROWS_PER_STEP } from "../../../table-jobs/paging";import {+ removeTableJobFolder,+ tableBulkIdsFolder,tableBulkIdsKey,tempStagingStorage} from "../../../table-jobs/storage";@@ -47,22 +49,14 @@ function deps() {};}-/** Deletes the id files of a run; the nightly cleanup is the backstop. The- * files are numbered from 0, one per collect step. */-async function removeIdFiles(args: {- companyId: string;- bulkActionId: string;- files: number;-}) {- const files = Array.from({ length: args.files }, (_, file) =>- tableBulkIdsKey(args.companyId, args.bulkActionId, file)- );+/** Deletes the id files of a run; the nightly cleanup is the backstop. */+async function removeIdFiles(companyId: string, bulkActionId: string) {try {- await tempStagingStorage().remove(files);+ await removeTableJobFolder(tableBulkIdsFolder(companyId, bulkActionId));} catch (error) {log.error("Failed to delete the id files of a bulk action", {- companyId: args.companyId,- bulkActionId: args.bulkActionId,+ companyId,+ bulkActionId,error});}@@ -79,17 +73,15 @@ export const tableBulkActionFunction = inngest.createFunction(// A failed chunk is counted as failed instead of failing the run.retries: 0,concurrency: { key: "event.data.companyId", limit: 1 },- onFailure: async ({ event, error }) => {+ onFailure: ({ event, error }) => {const { companyId, userId, bulkActionId, actionKey, actionLabel } =event.data.event.data;- log.error("Table bulk action failed", {+ return failTableJob({+ kind: "bulk",companyId,- actionKey,- bulkActionId,- error: error.message- });- try {- await notifyTableJobUser({+ jobId: bulkActionId,+ folder: tableBulkIdsFolder(companyId, bulkActionId),+ notification: {event: NotificationEvent.TableBulkAction,companyId,userId,@@ -97,22 +89,10 @@ export const tableBulkActionFunction = inngest.createFunction(title: `${actionLabel} could not be completed`,body: "Some rows may have changed. Check the list, then try again.",dedupeId: `table-bulk-action:${bulkActionId}:failed`- });- } catch (notifyError) {- log.error("Failed to send the bulk action failure notification", {- companyId,- error: notifyError- });- }- // The run state is gone here: remove every file a run of this size- // could have written.- const maxRows = event.data.event.data.maxRows ?? MAX_BULK_ROWS;- await removeIdFiles({- companyId,- bulkActionId,- files: Math.ceil(maxRows / TABLE_JOB_ROWS_PER_STEP)+ },+ error,+ context: { actionKey }});- await releaseTableJobLock("bulk", companyId, bulkActionId);}},{ event: "carbon/table-bulk-action" },@@ -246,9 +226,7 @@ export const tableBulkActionFunction = inngest.createFunction(}));- await step.run("remove-ids", () =>- removeIdFiles({ companyId, bulkActionId, files: idsPerFile.length })- );+ await step.run("remove-ids", () => removeIdFiles(companyId, bulkActionId));await step.run("release-lock", () =>releaseTableJobLock("bulk", companyId, bulkActionId));diff --git a/packages/jobs/src/inngest/functions/tasks/table-export.ts b/packages/jobs/src/inngest/functions/tasks/table-export.tsindex 954cf6a58d..60ab4fe07f 100644--- a/packages/jobs/src/inngest/functions/tasks/table-export.ts+++ b/packages/jobs/src/inngest/functions/tasks/table-export.ts@@ -2,15 +2,14 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { getLogger } from "@carbon/logger";import { NotificationEvent } from "@carbon/notifications";-import { MAX_EXPORT_ROWS } from "../../../table-jobs/csv";import {composeExport,type ExportDeps,removeExportParts,writeExportPart} from "../../../table-jobs/export-run";+import { failTableJob } from "../../../table-jobs/failure";import {requireTableJobHandlers,type TableJobContext@@ -20,17 +19,14 @@ import {releaseTableJobLock} from "../../../table-jobs/lock";import { notifyTableJobUser } from "../../../table-jobs/notify";-import { TABLE_JOB_ROWS_PER_STEP } from "../../../table-jobs/paging";import {- type TableJobStorage,tableExportPartKey,+ tableExportPartsFolder,tableExportStorageKey,tempStagingStorage} from "../../../table-jobs/storage";import { inngest } from "../../client";-const log = getLogger("jobs", "table-export");-const rowCount = new Intl.NumberFormat("en-US");function deps(): ExportDeps {@@ -40,28 +36,6 @@ function deps(): ExportDeps {};}-/** Deletes the parts of a failed export; the nightly cleanup is the backstop.- * The parts are numbered from 0, one per step of `TABLE_JOB_ROWS_PER_STEP`. */-async function removeParts(- storage: TableJobStorage,- args: { companyId: string; userId: string; exportId: string }-) {- const keys = Array.from(- { length: MAX_EXPORT_ROWS / TABLE_JOB_ROWS_PER_STEP },- (_, part) =>- tableExportPartKey(args.companyId, args.userId, args.exportId, part)- );- try {- await storage.remove(keys);- } catch (error) {- log.error("Failed to delete the parts of a failed export", {- companyId: args.companyId,- exportId: args.exportId,- error- });- }-}-// TODO(scale): this job runs inside the ERP containers (api+/inngest.ts) and shares// CPU with web requests. Move table export/bulk jobs to a dedicated worker service// before large tenants run many 100k-row exports at the same time.@@ -72,16 +46,14 @@ export const tableExportFunction = inngest.createFunction(// key, and the notification carries an event id Inngest de-duplicates.retries: 1,concurrency: { key: "event.data.companyId", limit: 1 },- onFailure: async ({ event, error }) => {+ onFailure: ({ event, error }) => {const { companyId, userId, exportId, listKey } = event.data.event.data;- log.error("Table export failed", {+ return failTableJob({+ kind: "export",companyId,- listKey,- exportId,- error: error.message- });- try {- await notifyTableJobUser({+ jobId: exportId,+ folder: tableExportPartsFolder(companyId, userId, exportId),+ notification: {event: NotificationEvent.TableExport,companyId,userId,@@ -90,15 +62,10 @@ export const tableExportFunction = inngest.createFunction(body: "Try again. If it fails again, filter the list to fewer rows.",inAppOnly: true,dedupeId: `table-export:${exportId}:failed`- });- } catch (notifyError) {- log.error("Failed to send the export failure notification", {- companyId,- error: notifyError- });- }- await removeParts(tempStagingStorage(), { companyId, userId, exportId });- await releaseTableJobLock("export", companyId, exportId);+ },+ error,+ context: { listKey }+ });}},{ event: "carbon/table-export" },diff --git a/packages/jobs/src/table-jobs/failure.ts b/packages/jobs/src/table-jobs/failure.tsnew file mode 100644index 0000000000..9f99e10419--- /dev/null+++ b/packages/jobs/src/table-jobs/failure.ts@@ -0,0 +1,67 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { getLogger } from "@carbon/logger";+import type { TableJobKind } from "./handlers";+import { releaseTableJobLock } from "./lock";+import { notifyTableJobUser } from "./notify";+import { removeTableJobFolder } from "./storage";++const log = getLogger("jobs", "table-jobs");++/**+ * The `onFailure` of a table job (an export, a bulk action): logs the+ * failure, tells the user, deletes the files the run wrote and frees the+ * company's lock. A failed notice or delete is logged and the rest still+ * runs: the nightly cleanup removes the files within 7 days.+ */+export async function failTableJob({+ kind,+ companyId,+ jobId,+ folder,+ notification,+ error,+ context+}: {+ kind: TableJobKind;+ companyId: string;+ jobId: string;+ /** The folder of the run's files (`tableExportPartsFolder`,+ * `tableBulkIdsFolder`). */+ folder: string;+ notification: Parameters<typeof notifyTableJobUser>[0];+ error: { message: string };+ /** What the log names besides the company and the job. */+ context: Record<string, unknown>;+}): Promise<void> {+ log.error("Table job failed", {+ kind,+ companyId,+ jobId,+ ...context,+ error: error.message+ });+ try {+ await notifyTableJobUser(notification);+ } catch (notifyError) {+ log.error("Failed to send a table job's failure notification", {+ kind,+ companyId,+ jobId,+ error: notifyError+ });+ }+ try {+ await removeTableJobFolder(folder);+ } catch (removeError) {+ log.error("Failed to delete the files of a failed table job", {+ kind,+ companyId,+ jobId,+ error: removeError+ });+ }+ await releaseTableJobLock(kind, companyId, jobId);+}diff --git a/packages/jobs/src/table-jobs/storage.ts b/packages/jobs/src/table-jobs/storage.tsindex 4e73ee415f..536bb466aa 100644--- a/packages/jobs/src/table-jobs/storage.ts+++ b/packages/jobs/src/table-jobs/storage.ts@@ -21,6 +21,15 @@ export function tableExportStorageKey(return `${companyId}/exports/${userId}/${exportId}.csv`;}+/** The folder of an export's parts. */+export function tableExportPartsFolder(+ companyId: string,+ userId: string,+ exportId: string+): string {+ return `${companyId}/exports/${userId}/${exportId}.parts`;+}+/** One part of an export, written by one step. The last step joins them. */export function tableExportPartKey(companyId: string,@@ -28,7 +37,15 @@ export function tableExportPartKey(exportId: string,part: number): string {- return `${companyId}/exports/${userId}/${exportId}.parts/${part}.csv`;+ return `${tableExportPartsFolder(companyId, userId, exportId)}/${part}.csv`;+}++/** The folder of a bulk action's id files. */+export function tableBulkIdsFolder(+ companyId: string,+ bulkActionId: string+): string {+ return `${companyId}/bulk-actions/${bulkActionId}`;}/** The ids one collect step of a bulk action read, as a JSON array. */@@ -37,7 +54,20 @@ export function tableBulkIdsKey(bulkActionId: string,file: number): string {- return `${companyId}/bulk-actions/${bulkActionId}/${file}.json`;+ return `${tableBulkIdsFolder(companyId, bulkActionId)}/${file}.json`;+}++/** Deletes every file in a folder of `temp-staging` (a job's parts or id+ * files: at most one per step, so well under one listing). Throws on+ * failure. */+export async function removeTableJobFolder(folder: string): Promise<void> {+ const bucket = getCarbonServiceRole().storage.from(TEMP_STAGING_BUCKET);+ const listed = await bucket.list(folder, { limit: 1000 });+ if (listed.error) throw listed.error;+ const keys = listed.data.map((file) => `${folder}/${file.name}`);+ if (keys.length === 0) return;+ const removed = await bucket.remove(keys);+ if (removed.error) throw removed.error;}/** The storage the table jobs use. Every call throws on failure. */