Skip to content

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.

Backup reliability: restore fixes, faster download, real progress (#956)

Sid58c0cbc51723
diff --git a/.claude/rules/company-backup-restore.md b/.claude/rules/company-backup-restore.md
index efed262c05..5547af1043 100644
--- a/.claude/rules/company-backup-restore.md
+++ b/.claude/rules/company-backup-restore.md
@@ -150,7 +150,11 @@ Forward flow:
column**, not only `hasId` (sole-`id` PK) tables — the ~25 composite
`("id","companyId")`-PK tables (`stockTransfer`, `supplierPart`, …) are
referenced by their `id` too, and gating on `hasId` falsely flagged every
- child of them and refused otherwise-valid restores.
+ child of them and refused otherwise-valid restores. It also skips
+ `SECRET_TABLES` on both sides (a secret table is never written to a backup
+ and never loaded) — an OLDER backup that predates a table joining
+ `SECRET_TABLES` still carries its rows (e.g. `apiKeyRateLimit` → the stripped
+ `apiKey`); they're ignored on load, so the preflight ignores them too.
5. `restoreAssetsFromBackup` (outside the txn, non-transactional) copies the files
from the backup's `.assets/` folder back to `private/<rewritten path>`,
server-side. It runs **before** the `ready` marker (step below) so the progress
diff --git a/apps/erp/app/modules/settings/backups.service.ts b/apps/erp/app/modules/settings/backups.service.ts
index 2b0c005169..eecffa42f4 100644
--- a/apps/erp/app/modules/settings/backups.service.ts
+++ b/apps/erp/app/modules/settings/backups.service.ts
@@ -163,6 +163,8 @@ export async function getCompanyRestoreRuns(
rows?: number;
label?: string | null;
error?: string | null;
+ startedAt?: string;
+ progress?: { phase: string; done: number; total: number };
};
return {
restoreRunId: meta.restoreRunId ?? m.entityId,
@@ -170,9 +172,49 @@ export async function getCompanyRestoreRuns(
rows: meta.rows ?? 0,
label: meta.label ?? null,
error: meta.error ?? null,
- startedAt: m.createdAt
+ progress: meta.progress ?? null,
+ startedAt: meta.startedAt ?? m.createdAt
};
});
return { data: runs, error: null };
}
+
+/**
+ * The in-flight export's live progress, or null when none is running. One marker
+ * per company (integration = 'company-export'), written by the export job and
+ * cleared when it finishes — so its absence means "not running" (the new backup
+ * appearing in the list is what signals completion).
+ */
+export async function getCompanyExportRun(
+ client: SupabaseClient<Database>,
+ companyId: string
+): Promise<{
+ data: {
+ progress: { phase: string; done: number; total: number } | null;
+ startedAt: string | null;
+ } | null;
+ error: Error | null;
+}> {
+ const marker = await client
+ .from("externalIntegrationMapping")
+ .select("metadata, createdAt")
+ .eq("integration", "company-export")
+ .eq("companyId", companyId)
+ .maybeSingle();
+
+ if (marker.error) return { data: null, error: marker.error };
+ if (!marker.data) return { data: null, error: null };
+
+ const meta = (marker.data.metadata ?? {}) as {
+ startedAt?: string;
+ progress?: { phase: string; done: number; total: number };
+ };
+ return {
+ data: {
+ progress: meta.progress ?? null,
+ startedAt: meta.startedAt ?? marker.data.createdAt
+ },
+ error: null
+ };
+}
diff --git a/apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx b/apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx
index 4828864959..2d4007fa28 100644
--- a/apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx
+++ b/apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx
@@ -11,24 +11,39 @@ import { useEffect, useState } from "react";
import { LuCheck, LuLoaderCircle, LuTriangleAlert } from "react-icons/lu";
import { useFetcher, useRevalidator } from "react-router";
-// Simulated step labels per job. Restore/revert resolve from a real poll; export
-// has no signal, so its steps play out then settle. Either way the steps make the
-// wait legible — "what is it doing right now".
-const STEP_SETS: Record<"export" | "restore" | "revert", string[]> = {
- export: [
- "Collecting records",
- "Bundling files",
- "Compressing",
- "Saving backup"
- ],
- restore: [
- "Snapshotting current data",
- "Clearing existing data",
- "Loading backup",
- "Restoring files"
- ],
- revert: ["Clearing restored data", "Restoring your snapshot"]
+// The job reports progress as a stable phase KEY + done/total; these order the
+// keys and map them to labels per mode (display copy stays out of the job).
+const PHASE_ORDER: Record<"export" | "restore" | "revert", string[]> = {
+ export: ["tables", "files"],
+ restore: ["snapshot", "wipe", "load", "files"],
+ revert: ["wipe", "load", "files"]
};
+const PHASE_LABELS: Record<
+ "export" | "restore" | "revert",
+ Record<string, string>
+> = {
+ export: {
+ tables: "Collecting records",
+ files: "Bundling files"
+ },
+ restore: {
+ snapshot: "Snapshotting current data",
+ wipe: "Clearing existing data",
+ load: "Loading backup",
+ files: "Restoring files"
+ },
+ revert: {
+ wipe: "Clearing restored data",
+ load: "Restoring your snapshot",
+ files: "Restoring files"
+ }
+};
+
+function formatElapsed(ms: number): string {
+ const s = Math.max(0, Math.floor(ms / 1000));
+ const m = Math.floor(s / 60);
+ return m > 0 ? `${m}m ${s % 60}s` : `${s}s`;
+}
// The animated step checklist. Completed steps get a check that pops in
// (ease-out), the active step spins (constant motion → linear), pending steps sit
@@ -36,21 +51,26 @@ const STEP_SETS: Record<"export" | "restore" | "revert", string[]> = {
function StepChecklist({
steps,
step,
- done
+ fraction,
+ done,
+ detail
}: {
steps: string[];
step: number;
+ /** 0..1 bar fill. Real for restore/revert (phase + intra-phase done/total),
+ * synthetic for export. */
+ fraction: number;
done: boolean;
+ /** Optional line under the list, e.g. "23 / 50 · 4s". */
+ detail?: string;
}) {
- const fraction = done
- ? 1
- : (Math.min(step, steps.length - 1) + 0.5) / steps.length;
+ const f = done ? 1 : Math.max(0, Math.min(1, fraction));
return (
<div className="flex w-full flex-col gap-4 py-2">
<div className="h-1 w-full overflow-hidden rounded-full bg-muted">
<div
className="h-full origin-left rounded-full bg-primary transition-transform duration-700 ease-out motion-reduce:transition-none"
- style={{ transform: `scaleX(${fraction})` }}
+ style={{ transform: `scaleX(${f})` }}
/>
</div>
<div className="flex flex-col gap-2.5">
@@ -83,6 +103,9 @@ function StepChecklist({
);
})}
</div>
+ {detail ? (
+ <p className="text-xs tabular-nums text-muted-foreground">{detail}</p>
+ ) : null}
</div>
);
}
@@ -105,26 +128,47 @@ export function JobProgressModal({
const isExport = mode === "export";
const isRevert = mode === "revert";
const revalidator = useRevalidator();
- const steps = STEP_SETS[mode];
const statusFetcher = useFetcher<{
status: "running" | "ready" | "failed" | "reverting" | "gone";
rows: number;
error: string | null;
+ progress: { phase: string; done: number; total: number } | null;
+ startedAt: string | null;
+ }>();
+ // Export reports progress via a separate company-scoped marker (no run id).
+ const exportFetcher = useFetcher<{
+ progress: { phase: string; done: number; total: number } | null;
+ startedAt: string | null;
}>();
const raw = statusFetcher.data?.status;
const failed = !isExport && raw === "failed";
const restoreReady = mode === "restore" && raw === "ready";
const revertDone = isRevert && raw === "gone";
- const [step, setStep] = useState(0);
const success = restoreReady || revertDone || (isExport && !!completed);
const done = success || failed;
const rows = statusFetcher.data?.rows ?? 0;
const error = statusFetcher.data?.error;
+ const progress = isExport
+ ? (exportFetcher.data?.progress ?? null)
+ : (statusFetcher.data?.progress ?? null);
+ const startedAt = isExport
+ ? (exportFetcher.data?.startedAt ?? null)
+ : (statusFetcher.data?.startedAt ?? null);
+ // Watchdog thresholds are in 500ms ticks: ~120s "slow", ~60s "stalled".
const [ticks, setTicks] = useState(0);
- const slow = !done && ticks > 80;
+ const slow = !done && ticks > 240;
+
+ // Elapsed clock — refresh once a second while the job runs.
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ if (done || !startedAt) return;
+ const id = setInterval(() => setNow(Date.now()), 1000);
+ return () => clearInterval(id);
+ }, [done, startedAt]);
+ const elapsedMs = startedAt ? now - new Date(startedAt).getTime() : 0;
// Pre-heartbeat watchdog: if a restore never writes its first marker (the job
// failed to start / never reached Inngest), the status stays "gone" forever.
@@ -133,7 +177,7 @@ export function JobProgressModal({
useEffect(() => {
if (raw && raw !== "gone") setSawMarker(true);
}, [raw]);
- const stalled = mode === "restore" && !done && !sawMarker && ticks > 40;
+ const stalled = mode === "restore" && !done && !sawMarker && ticks > 120;
// Poll the real job status (restore / revert only).
const load = statusFetcher.load;
@@ -148,34 +192,55 @@ export function JobProgressModal({
const id = setInterval(() => {
load(href);
setTicks((t) => t + 1);
- }, 1500);
+ }, 500);
return () => clearInterval(id);
}, [isExport, runId, done, load, revalidator]);
- // Export has no status marker — poll by revalidating the backups list until the
- // new backup actually appears (the parent flips `completed` when it does). The
- // dialog never claims success before the file exists.
+ // Export: poll the marker fast for smooth live counts, but revalidate the (much
+ // heavier) backup list slower — completion is just the new backup appearing.
+ const loadExport = exportFetcher.load;
useEffect(() => {
if (!isExport || done) return;
- const id = setInterval(() => {
- revalidator.revalidate();
+ const href = `/api/settings/backup-export-status`;
+ loadExport(href);
+ const poll = setInterval(() => {
+ loadExport(href);
setTicks((t) => t + 1);
- }, 2000);
- return () => clearInterval(id);
- }, [isExport, done, revalidator]);
+ }, 500);
+ const reval = setInterval(() => revalidator.revalidate(), 2000);
+ return () => {
+ clearInterval(poll);
+ clearInterval(reval);
+ };
+ }, [isExport, done, revalidator, loadExport]);
- // Advance the visible steps on a cadence while the job runs.
- useEffect(() => {
- if (done) {
- setStep(steps.length);
- return;
+ // Checklist + bar from the real phase + done/total. Before the first heartbeat
+ // we hold phase 1 rather than fake-advancing (which would snap backward once
+ // real progress arrives).
+ const order = PHASE_ORDER[mode];
+ const checklist = (() => {
+ const labels = order.map((k) => PHASE_LABELS[mode][k] ?? k);
+ const elapsed = startedAt ? formatElapsed(elapsedMs) : null;
+ if (progress) {
+ const idx = order.indexOf(progress.phase);
+ const activeStep = idx >= 0 ? idx : 0;
+ const sub = progress.total > 0 ? progress.done / progress.total : 0;
+ const fraction = done ? 1 : (activeStep + sub) / order.length;
+ const counts =
+ progress.total > 1
+ ? `${progress.done.toLocaleString()} / ${progress.total.toLocaleString()}`
+ : null;
+ const detail = [counts, elapsed].filter(Boolean).join(" · ") || undefined;
+ return { steps: labels, step: activeStep, fraction, detail };
}
- const id = setInterval(
- () => setStep((s) => Math.min(s + 1, steps.length - 1)),
- 900
- );
- return () => clearInterval(id);
- }, [done, steps.length]);
+ // No heartbeat yet: first phase active, bar empty, no fake advance.
+ return {
+ steps: labels,
+ step: 0,
+ fraction: done ? 1 : 0,
+ detail: elapsed ?? undefined
+ };
+ })();
const workingTitle = isExport
? "Creating backup…"
@@ -236,7 +301,13 @@ export function JobProgressModal({
</div>
) : (
<>
- <StepChecklist steps={steps} step={step} done={done} />
+ <StepChecklist
+ steps={checklist.steps}
+ step={checklist.step}
+ fraction={checklist.fraction}
+ done={done}
+ detail={checklist.detail}
+ />
{stalled ? (
<p className="text-center text-xs text-muted-foreground">
Couldn't confirm the restore started. It may still be running
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index 8c9d58fb0a..b13ef71164 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,5 +1,5 @@
{
- "generated": "2026-06-25T12:53:58.410Z",
+ "generated": "2026-06-26T04:49:29.455Z",
"totalTools": 1219,
"modules": 15,
"tools": [
diff --git a/apps/erp/app/routes/api+/settings.backup-archive.$file.ts b/apps/erp/app/routes/api+/settings.backup-archive.$file.ts
index 4f7afe5720..0f01b3a167 100644
--- a/apps/erp/app/routes/api+/settings.backup-archive.$file.ts
+++ b/apps/erp/app/routes/api+/settings.backup-archive.$file.ts
@@ -28,12 +28,17 @@ async function listRelative(
return out;
}
+/** How many objects to download concurrently while packing the tar in order.
+ * Bounds memory to ~this many buffered files (NOT the whole backup). */
+const DOWNLOAD_CONCURRENCY = 6;
+
/**
- * Stream a self-contained `.carbon.tar.gz` of a backup: the whole
- * `exports/<name>/` folder (manifest, per-table files, assets) bundled into one
- * gzipped tar so a cross-environment import carries everything. Storage keeps the
- * folder layout; the tar only exists in transit, and one file is buffered at a
- * time, so a large backup streams at flat memory.
+ * Stream a self-contained `.carbon.tar.gz` of a backup's `exports/<name>/` folder
+ * (manifest, per-table files, assets) so a cross-environment import carries
+ * everything. Objects are prefetched in a bounded window (overlapping downloads)
+ * but packed in order, so memory stays bounded to ~DOWNLOAD_CONCURRENCY files.
+ * Outer gzip is level 1 — the entries are already compressed — but stays a valid
+ * gzip tar, which `backups-archive.server.ts` unpacks on re-import.
*/
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId, email } = await requirePermissions(request, {
@@ -60,14 +65,31 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
});
+ const downloadAt = (i: number): Promise<Buffer | null> =>
+ client.storage
+ .from(companyId)
+ .download(`${dir}/${relPaths[i]}`)
+ .then((f) =>
+ f.error || !f.data
+ ? null
+ : f.data.arrayBuffer().then((b) => Buffer.from(b))
+ )
+ .catch(() => null); // best-effort: a missing/failed object is skipped
+
(async () => {
try {
- for (const rel of relPaths) {
- const f = await client.storage
- .from(companyId)
- .download(`${dir}/${rel}`);
- if (f.error || !f.data) continue; // best-effort
- await addEntry(rel, Buffer.from(await f.data.arrayBuffer()));
+ // Sliding window: keep up to DOWNLOAD_CONCURRENCY downloads in flight, but
+ // write entries to the tar strictly in index order.
+ const inflight = new Map<number, Promise<Buffer | null>>();
+ const prime = Math.min(DOWNLOAD_CONCURRENCY, relPaths.length);
+ for (let i = 0; i < prime; i++) inflight.set(i, downloadAt(i));
+
+ for (let i = 0; i < relPaths.length; i++) {
+ const buf = await inflight.get(i)!;
+ inflight.delete(i);
+ const next = i + DOWNLOAD_CONCURRENCY;
+ if (next < relPaths.length) inflight.set(next, downloadAt(next));
+ if (buf) await addEntry(relPaths[i], buf);
}
archive.finalize();
} catch (err) {
@@ -77,7 +99,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
// tar -> gzip -> web stream. (Readable.toWeb yields a byte stream undici rejects
// with "highWaterMark is required", so drain the gzip output by hand.)
- const gzip = createGzip();
+ const gzip = createGzip({ level: 1 });
archive.on("error", (err) => gzip.destroy(err));
archive.pipe(gzip);
const stream = new ReadableStream({
diff --git a/apps/erp/app/routes/api+/settings.backup-export-status.ts b/apps/erp/app/routes/api+/settings.backup-export-status.ts
new file mode 100644
index 0000000000..56a8ffc731
--- /dev/null
+++ b/apps/erp/app/routes/api+/settings.backup-export-status.ts
@@ -0,0 +1,21 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { isInternalEmail } from "@carbon/utils";
+import type { LoaderFunctionArgs } from "react-router";
+import { getCompanyExportRun } from "~/modules/settings";
+
+// Polled by the export progress modal for live phase/done/total. One marker per
+// company (the export job writes it while running, clears it when done), so a
+// null `progress` means the run hasn't written its first heartbeat yet OR has
+// finished — the modal uses the backup list appearing to confirm completion.
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId, email } = await requirePermissions(request, {
+ update: "settings"
+ });
+ if (!isInternalEmail(email)) throw new Response("Not found", { status: 404 });
+
+ const run = await getCompanyExportRun(client, companyId);
+ return {
+ progress: run.data?.progress ?? null,
+ startedAt: run.data?.startedAt ?? null
+ };
+}
diff --git a/apps/erp/app/routes/api+/settings.backup-restore-status.$restoreRunId.ts b/apps/erp/app/routes/api+/settings.backup-restore-status.$restoreRunId.ts
index 4384171ba8..d3cb06a938 100644
--- a/apps/erp/app/routes/api+/settings.backup-restore-status.$restoreRunId.ts
+++ b/apps/erp/app/routes/api+/settings.backup-restore-status.$restoreRunId.ts
@@ -23,6 +23,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return {
status: run?.status ?? ("gone" as const),
rows: run?.rows ?? 0,
- error: run?.error ?? null
+ error: run?.error ?? null,
+ progress: run?.progress ?? null,
+ startedAt: run?.startedAt ?? null
};
}
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts
index ce30026e7b..e4c84a6b9b 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts
@@ -169,6 +169,24 @@ describe("findDanglingReferences", () => {
expect(result).toEqual([]);
});
+ it("ignores a secret table's rows referencing another stripped secret (old backup)", () => {
+ // apiKeyRateLimit joined SECRET_TABLES, but a backup made before that still
+ // carries its rows pointing at the always-stripped secret `apiKey`. Those
+ // rows are skipped on load, so the preflight must not report them as a gap.
+ const apiKey = table("apiKey", [col("id"), col("companyId")]);
+ const apiKeyRateLimit = table(
+ "apiKeyRateLimit",
+ [col("apiKeyId"), col("companyId")],
+ [fk("apiKeyId", "apiKey")],
+ { pkColumns: ["apiKeyId"] }
+ );
+ const result = findDanglingReferences(catalog([apiKey, apiKeyRateLimit]), {
+ apiKey: [], // secret → never exported
+ apiKeyRateLimit: [{ apiKeyId: "api_x", companyId: "c1" }]
+ });
+ expect(result).toEqual([]);
+ });
+
it("still flags a missing NOT-NULL FK into an ordinary company table (revert did not loosen general closure)", () => {
// A non-reference company table (item) is NOT in the deferral set, so a
// dangling NOT-NULL ref to it is a fatal closure gap, as before.
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.transforms.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.transforms.ts
index 0f28dffa1a..f06e1fb1f2 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.transforms.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.transforms.ts
@@ -8,6 +8,7 @@ import {
RETAINED_REF_TABLES,
rewriteStoragePath,
rewriteToTemplateAssetPath,
+ SECRET_TABLES,
STORAGE_PATH_COLUMNS,
type TableInfo
} from "./company-backup";
@@ -50,6 +51,13 @@ export function findDanglingReferences(
knownSubstrateIds?: Map<string, Set<unknown>>
): DanglingRef[] {
const catalogNames = new Set(catalog.tables.map((t) => t.name));
+ // Secret tables (credentials/tokens) are never written to a backup and never
+ // loaded on restore, so they can be neither a row source nor a resolvable ref
+ // target here. An OLDER backup made before a table joined SECRET_TABLES may
+ // still carry its rows (e.g. `apiKeyRateLimit` → the stripped `apiKey`) — those
+ // are ignored on load, so the preflight must ignore them too rather than report
+ // a gap that can't exist for the restore.
+ const secret = new Set<string>(SECRET_TABLES);
const idsByTable = new Map<string, Set<unknown>>();
for (const t of catalog.tables) {
// FKs are only ever checked against `refColumn === "id"` below, so any table
@@ -68,9 +76,11 @@ export function findDanglingReferences(
for (const t of catalog.tables) {
const rows = dataByTable[t.name];
if (!rows?.length) continue;
+ if (secret.has(t.name)) continue; // not loaded → its refs are moot
const colByName = new Map(t.columns.map((c) => [c.name, c]));
for (const fk of t.foreignKeys) {
if (fk.refColumn !== "id") continue;
+ if (secret.has(fk.refTable)) continue; // parent never present in any backup
if (RETAINED_REF_TABLES.has(fk.refTable)) continue;
if (!catalogNames.has(fk.refTable)) continue; // non-scoped global → stable ids
const col = colByName.get(fk.column);
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
index 644a6b389e..e84cda3be3 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
@@ -1109,9 +1109,12 @@ export async function wipeScopedData(
trx: Kysely<KyselyDatabase>,
tables: TableInfo[],
byName: Map<string, TableInfo>,
- scope: { companyId: string; companyGroupId: string | null }
+ scope: { companyId: string; companyGroupId: string | null },
+ onProgress?: (done: number, total: number) => Promise<void>
): Promise<void> {
- for (const table of [...tables].reverse()) {
+ const ordered = [...tables].reverse();
+ for (let i = 0; i < ordered.length; i++) {
+ const table = ordered[i]!;
// buildScopeFilter scopes by parent FK for `via` tables; a null
// companyGroupId yields `= NULL` (no match), so group data is left untouched
// when the company has no group.
@@ -1119,6 +1122,7 @@ export async function wipeScopedData(
DELETE FROM ${sql.id(table.name)}
WHERE ${buildScopeFilter(table, byName, scope.companyId, scope.companyGroupId)}
`.execute(trx);
+ await onProgress?.(i + 1, ordered.length);
}
}
@@ -1159,7 +1163,8 @@ async function copyStorageObject(
*/
export async function copyAssetsToBackup(
client: SupabaseClient,
- args: { sourcePaths: string[]; destBucket: string; destPrefix: string }
+ args: { sourcePaths: string[]; destBucket: string; destPrefix: string },
+ onProgress?: (done: number, total: number) => Promise<void>
): Promise<{ copied: number; failed: number }> {
const { sourcePaths, destBucket, destPrefix } = args;
let copied = 0;
@@ -1177,6 +1182,7 @@ export async function copyAssetsToBackup(
failed++;
console.warn("Failed to copy backup asset", { path, error });
}
+ await onProgress?.(copied + failed, sourcePaths.length);
}
return { copied, failed };
}
@@ -1197,12 +1203,15 @@ export async function restoreAssetsFromBackup(
sourceCompanyId: string;
companyId: string;
idRewrite: Map<string, string>;
- }
+ },
+ onProgress?: (done: number, total: number) => Promise<void>
): Promise<{ copied: number; failed: number }> {
const { files, srcBucket, srcPrefix, sourceCompanyId, companyId, idRewrite } =
args;
+ const total = files.filter((f) => f.included).length;
let copied = 0;
let failed = 0;
+ let processed = 0;
for (const file of files) {
if (!file.included) continue;
const targetPath = rewriteStoragePath(
@@ -1216,6 +1225,7 @@ export async function restoreAssetsFromBackup(
path: file.path,
targetPath
});
+ await onProgress?.(++processed, total);
continue;
}
const { ok, error } = await copyStorageObject(client, {
@@ -1234,6 +1244,7 @@ export async function restoreAssetsFromBackup(
error
});
}
+ await onProgress?.(++processed, total);
}
return { copied, failed };
}
diff --git a/packages/jobs/src/inngest/functions/tasks/company-export.ts b/packages/jobs/src/inngest/functions/tasks/company-export.ts
index b4329c4d13..cde3c90f4b 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-export.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-export.ts
@@ -52,6 +52,12 @@ export async function buildCompanyBackup(
includeStorage: "none" | "all";
/** Override the generated folder name (snapshots pass their own). */
name?: string;
+ /** Live progress of the table-dump phase (`tables`). Throttled by the caller. */
+ onProgress?: (p: {
+ phase: string;
+ done: number;
+ total: number;
+ }) => Promise<void>;
}
): Promise<{
name: string;
@@ -124,6 +130,7 @@ export async function buildCompanyBackup(
// Dump each non-empty table to its own `tables/<table>.ndjson.gz`, in parallel.
const tableManifest: Manifest["tables"] = [];
+ let dumped = 0; // incremented as each table completes (single-threaded → safe)
await mapWithConcurrency(exportable, TABLE_CONCURRENCY, async (table) => {
const columns = table.columns.filter((c) => !c.isGenerated);
// a prior import's revert ledger must never travel in an artifact
@@ -140,7 +147,15 @@ export async function buildCompanyBackup(
WHERE ${buildScopeFilter(table, byName, companyId, companyGroupId)}${ledgerFilter}
`.execute(db);
- if (result.rows.length === 0) return; // empty tables get no file
+ if (result.rows.length === 0) {
+ dumped++;
+ await opts.onProgress?.({
+ phase: "tables",
+ done: dumped,
+ total: exportable.length
+ });
+ return; // empty tables get no file
+ }
const rows = result.rows.map((row) => {
const encoded: Record<string, unknown> = {};
@@ -163,6 +178,12 @@ export async function buildCompanyBackup(
rows: result.rows.length,
columns: columns.map((c) => c.name)
});
+ dumped++;
+ await opts.onProgress?.({
+ phase: "tables",
+ done: dumped,
+ total: exportable.length
+ });
});
// Decide which storage assets are in scope. They live in the shared `private`
@@ -212,6 +233,54 @@ export async function buildCompanyBackup(
return { name, manifest, rows, assetSourcePaths };
}
+// One company-scoped progress marker (exports run one-at-a-time, so no run id).
+// The UI polls it for live phase/done/total; it's cleared when the run ends, and
+// the backup appearing in the list is what signals completion.
+const EXPORT_INTEGRATION = "company-export";
+type ExportProgress = { phase: string; done: number; total: number };
+
+async function upsertExportMarker(
+ client: ServiceRole,
+ companyId: string,
+ userId: string,
+ metadata: { status: "running"; startedAt: string; progress?: ExportProgress }
+): Promise<void> {
+ const existing = await client
+ .from("externalIntegrationMapping")
+ .select("id")
+ .eq("integration", EXPORT_INTEGRATION)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ if (existing.data) {
+ await client
+ .from("externalIntegrationMapping")
+ .update({ metadata })
+ .eq("id", existing.data.id)
+ .eq("companyId", companyId);
+ } else {
+ await client.from("externalIntegrationMapping").insert({
+ entityType: "export",
+ entityId: companyId,
+ integration: EXPORT_INTEGRATION,
+ externalId: "",
+ metadata,
+ companyId,
+ createdBy: userId
+ });
+ }
+}
+
+async function clearExportMarker(
+ client: ServiceRole,
+ companyId: string
+): Promise<void> {
+ await client
+ .from("externalIntegrationMapping")
+ .delete()
+ .eq("integration", EXPORT_INTEGRATION)
+ .eq("companyId", companyId);
+}
+
export const companyExportFunction = inngest.createFunction(
{
id: "company-export",
@@ -226,37 +295,75 @@ export const companyExportFunction = inngest.createFunction(
const client = getCarbonServiceRole();
const db = getJobDatabaseClient(TABLE_CONCURRENCY);
- const { name, manifest, rows, assetSourcePaths } =
- await buildCompanyBackup(client, db, {
- companyId,
- userId,
- label,
- includeStorage
+ // Live-progress marker (cleared in `finally`, success or failure). Throttled
+ // so a fast parallel dump doesn't hammer the row.
+ const startedAt = new Date().toISOString();
+ await upsertExportMarker(client, companyId, userId, {
+ status: "running",
+ startedAt
+ });
+ let lastAt = 0;
+ let lastPhase = "";
+ const report = async (progress: ExportProgress) => {
+ const now = Date.now();
+ const terminal = progress.done >= progress.total;
+ if (progress.phase === lastPhase && !terminal && now - lastAt < 250) {
+ return;
+ }
+ lastPhase = progress.phase;
+ lastAt = now;
+ await upsertExportMarker(client, companyId, userId, {
+ status: "running",
+ startedAt,
+ progress
});
+ };
- // Copy the in-scope assets server-side into the backup's `assets/` folder.
- // Best-effort (matches restore/import): the table files are already
- // committed; per-file copy failures only warn.
- const assets = await copyAssetsToBackup(client, {
- sourcePaths: assetSourcePaths,
- destBucket: companyId,
- destPrefix: backupAssetsDir(name)
- });
+ try {
+ const { name, manifest, rows, assetSourcePaths } =
+ await buildCompanyBackup(client, db, {
+ companyId,
+ userId,
+ label,
+ includeStorage,
+ onProgress: report
+ });
+
+ // Copy the in-scope assets server-side into the backup's `assets/` folder.
+ // Best-effort (matches restore/import): the table files are already
+ // committed; per-file copy failures only warn.
+ await report({
+ phase: "files",
+ done: 0,
+ total: assetSourcePaths.length
+ });
+ const assets = await copyAssetsToBackup(
+ client,
+ {
+ sourcePaths: assetSourcePaths,
+ destBucket: companyId,
+ destPrefix: backupAssetsDir(name)
+ },
+ (done, total) => report({ phase: "files", done, total })
+ );
- // Manifest LAST — its presence marks the backup complete, so the list never
- // shows a half-written backup as ready.
- await writeBackupManifest(client, companyId, name, manifest);
+ // Manifest LAST — its presence marks the backup complete, so the list
+ // never shows a half-written backup as ready.
+ await writeBackupManifest(client, companyId, name, manifest);
- console.log("Company export complete", {
- companyId,
- name,
- tables: manifest.tables.length,
- rows,
- assetsCopied: assets.copied,
- assetsFailed: assets.failed
- });
+ console.log("Company export complete", {
+ companyId,
+ name,
+ tables: manifest.tables.length,
+ rows,
+ assetsCopied: assets.copied,
+ assetsFailed: assets.failed
+ });
- return { name, tables: manifest.tables.length, rows };
+ return { name, tables: manifest.tables.length, rows };
+ } finally {
+ await clearExportMarker(client, companyId);
+ }
});
}
);
diff --git a/packages/jobs/src/inngest/functions/tasks/company-restore.ts b/packages/jobs/src/inngest/functions/tasks/company-restore.ts
index f1060b7340..9a4fa2c07d 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-restore.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-restore.ts
@@ -59,6 +59,8 @@ async function wipeAndLoad(
* remap (foreign/template) load so a FK into a seeded global row is kept
* verbatim instead of treated as a dangling gap. */
substrateIds?: Map<string, Set<unknown>>;
+ /** Live phase progress (`wipe` then `load`). Throttled by the caller. */
+ onProgress?: (p: JobProgress) => Promise<void>;
}
): Promise<{ rows: number; idRewrite: Map<string, string> }> {
const {
@@ -67,7 +69,8 @@ async function wipeAndLoad(
remap,
includeGroup,
targetGroupId,
- substrateIds
+ substrateIds,
+ onProgress
} = opts;
// Refuse if the schema would let a kept row dangle once we wipe (drift guard).
@@ -122,12 +125,19 @@ async function wipeAndLoad(
await sql`SET LOCAL session_replication_role = 'replica'`.execute(trx);
}
- await wipeScopedData(trx, wipeTables, byName, {
- companyId,
- companyGroupId: targetGroupId
- });
-
- for (const table of loadTables) {
+ await onProgress?.({ phase: "wipe", done: 0, total: wipeTables.length });
+ await wipeScopedData(
+ trx,
+ wipeTables,
+ byName,
+ { companyId, companyGroupId: targetGroupId },
+ onProgress
+ ? (done, total) => onProgress({ phase: "wipe", done, total })
+ : undefined
+ );
+
+ for (let t = 0; t < loadTables.length; t++) {
+ const table = loadTables[t]!;
const backupCols =
backupColumns.get(table.name) ??
new Set(Object.keys(backup.data[table.name]![0] ?? {}));
@@ -190,6 +200,11 @@ async function wipeAndLoad(
`.execute(trx);
}
inserted += rows.length;
+ await onProgress?.({
+ phase: "load",
+ done: t + 1,
+ total: loadTables.length
+ });
}
});
@@ -197,6 +212,10 @@ async function wipeAndLoad(
}
type RestoreStatus = "running" | "ready" | "failed" | "reverting";
+/** Live progress of the current phase. `phase` is a stable KEY
+ * (`snapshot`/`wipe`/`load`/`files`); the UI maps it to a human label per mode
+ * (restore vs revert), so the job never bakes in display copy. */
+type JobProgress = { phase: string; done: number; total: number };
type RestoreMeta = {
restoreRunId: string;
status: RestoreStatus;
@@ -204,6 +223,10 @@ type RestoreMeta = {
rows?: number;
label?: string | null;
error?: string | null;
+ /** ISO timestamp of the first heartbeat — the UI shows elapsed time from it. */
+ startedAt?: string;
+ /** Current phase + done/total; updated as the run progresses (throttled). */
+ progress?: JobProgress;
/** True when the restored backup came from another company (its rows were
* re-stamped onto this one). */
foreign?: boolean;
@@ -291,6 +314,37 @@ async function writeRestoreMarker(
}
}
+// Throttled progress writer: drop same-phase ticks within the window, always
+// flush a phase change or a terminal done===total. The marker write is a separate
+// connection, so this is safe to call inside the wipe+load transaction.
+const PROGRESS_THROTTLE_MS = 250;
+function makeProgressReporter(
+ client: ServiceRole,
+ companyId: string,
+ restoreRunId: string
+): (p: JobProgress) => Promise<void> {
+ let lastAt = 0;
+ let lastPhase = "";
+ return async (progress) => {
+ const now = Date.now();
+ const terminal = progress.done >= progress.total;
+ if (
+ progress.phase === lastPhase &&
+ !terminal &&
+ now - lastAt < PROGRESS_THROTTLE_MS
+ ) {
+ return;
+ }
+ lastPhase = progress.phase;
+ lastAt = now;
+ await writeRestoreMarker(client, {
+ companyId,
+ restoreRunId,
+ patch: { progress }
+ });
+ };
+}
+
async function deleteRestoreMarker(
client: ServiceRole,
companyId: string,
@@ -344,8 +398,13 @@ export const companyRestoreFunction = inngest.createFunction(
companyId,
userId,
restoreRunId,
- patch: { status: "running", label: label ?? null }
+ patch: {
+ status: "running",
+ label: label ?? null,
+ startedAt: existing?.metadata.startedAt ?? new Date().toISOString()
+ }
});
+ const report = makeProgressReporter(client, companyId, restoreRunId);
try {
const name = backupNameFromSource(filePath);
@@ -414,6 +473,7 @@ export const companyRestoreFunction = inngest.createFunction(
// capture the WIPED state and overwrite the real pre-restore copy.
let snapshotPath = existing?.metadata.snapshotPath ?? undefined;
if (!snapshotPath) {
+ await report({ phase: "snapshot", done: 0, total: 1 });
// buildCompanyBackup writes the snapshot's table files; the manifest is
// written last (its presence marks the snapshot complete). The marker
// stores the folder name.
@@ -437,6 +497,7 @@ export const companyRestoreFunction = inngest.createFunction(
restoreRunId,
patch: { snapshotPath, foreign, includeGroup }
});
+ await report({ phase: "snapshot", done: 1, total: 1 });
}
// 2. Wipe + load (atomic). If this throws, the transaction rolls back —
@@ -450,7 +511,8 @@ export const companyRestoreFunction = inngest.createFunction(
remap: foreign,
includeGroup,
targetGroupId,
- substrateIds
+ substrateIds,
+ onProgress: report
});
// 3. Files (best-effort, non-transactional) — copied BEFORE marking ready
@@ -460,15 +522,22 @@ export const companyRestoreFunction = inngest.createFunction(
// so a storage hiccup still can't flip a committed restore to "failed".
// A revert restores files from the snapshot.
if (includeStorage === "all") {
+ const fileCount =
+ backup.manifest.storage?.filter((f) => f.included).length ?? 0;
try {
- await restoreAssetsFromBackup(client, {
- files: backup.manifest.storage,
- srcBucket: companyId,
- srcPrefix: backupAssetsDir(name),
- sourceCompanyId: backup.manifest.sourceCompanyId,
- companyId,
- idRewrite
- });
+ await report({ phase: "files", done: 0, total: fileCount });
+ await restoreAssetsFromBackup(
+ client,
+ {
+ files: backup.manifest.storage,
+ srcBucket: companyId,
+ srcPrefix: backupAssetsDir(name),
+ sourceCompanyId: backup.manifest.sourceCompanyId,
+ companyId,
+ idRewrite
+ },
+ (done, total) => report({ phase: "files", done, total })
+ );
} catch (storageErr) {
console.warn("Restore: file restore failed (data is intact)", {
restoreRunId,
@@ -582,8 +651,9 @@ export const companyRestoreRevertFunction = inngest.createFunction(
await writeRestoreMarker(client, {
companyId,
restoreRunId,
- patch: { status: "reverting" }
+ patch: { status: "reverting", startedAt: new Date().toISOString() }
});
+ const report = makeProgressReporter(client, companyId, restoreRunId);
try {
// The snapshot is THIS company's own pre-restore data — ids and scope
@@ -599,16 +669,24 @@ export const companyRestoreRevertFunction = inngest.createFunction(
userId: "",
remap: false,
includeGroup: marker?.metadata.includeGroup ?? false,
- targetGroupId
- });
- await restoreAssetsFromBackup(client, {
- files: snapshot.manifest.storage,
- srcBucket: companyId,
- srcPrefix: backupAssetsDir(snapshotPath),
- sourceCompanyId: companyId,
- companyId,
- idRewrite
+ targetGroupId,
+ onProgress: report
});
+ const fileCount =
+ snapshot.manifest.storage?.filter((f) => f.included).length ?? 0;
+ await report({ phase: "files", done: 0, total: fileCount });
+ await restoreAssetsFromBackup(
+ client,
+ {
+ files: snapshot.manifest.storage,
+ srcBucket: companyId,
+ srcPrefix: backupAssetsDir(snapshotPath),
+ sourceCompanyId: companyId,
+ companyId,
+ idRewrite
+ },
+ (done, total) => report({ phase: "files", done, total })
+ );
await removeStoragePrefix(client, companyId, backupDir(snapshotPath));
await deleteRestoreMarker(client, companyId, restoreRunId);