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.

feat: file-per-table company backups + .carbon.tar.gz transport

Sidwebworksbf90baa85367
diff --git a/apps/erp/app/modules/settings/backups.service.ts b/apps/erp/app/modules/settings/backups.service.ts
index a52aea204d..5151b2ba72 100644
--- a/apps/erp/app/modules/settings/backups.service.ts
+++ b/apps/erp/app/modules/settings/backups.service.ts
@@ -6,17 +6,11 @@ import type { SupabaseClient } from "@supabase/supabase-js";
// enqueued server-side (see backups.server.ts) and tracked via the
// externalIntegrationMapping marker (getCompanyRestoreRuns).
-// A backup is the gz plus its sibling `<name>.assets/` folder of copied storage
-// files. Must match `BACKUP_GZ_SUFFIX` / `backupAssetPrefix` in
-// packages/jobs/src/inngest/functions/tasks/company-backup.ts.
-const BACKUP_GZ_SUFFIX = ".carbon.json.gz";
-
-function backupAssetPrefix(filePath: string) {
- const base = filePath.endsWith(BACKUP_GZ_SUFFIX)
- ? filePath.slice(0, -BACKUP_GZ_SUFFIX.length)
- : filePath;
- return `${base}.assets`;
-}
+// A backup is a folder `exports/<name>/` of small objects: `manifest.json`, one
+// `tables/<table>.ndjson.gz` per table, and `assets/<path>` files. Pre-restore
+// snapshots use the same layout under a `_pre-restore-*` name. Must match the
+// `backup*Path` helpers in packages/jobs/.../company-backup.ts.
+const SNAPSHOT_PREFIX = "_pre-restore-";
/**
* Remove every object under a prefix (recursing into folders) so a deleted
@@ -57,33 +51,86 @@ export async function exportCompanyBackup(
return client.functions.invoke("export-company", { body: args });
}
-export async function listCompanyBackupExports(
+export type CompanyBackupSummary = {
+ /** Backup folder name (also the restore `source` identifier). */
+ name: string;
+ exportedAt: string | null;
+ label: string | null;
+ rows: number;
+ /** Total bundled asset bytes (the bulk of a backup's footprint). */
+ sizeBytes: number;
+};
+
+/**
+ * List a company's backups (the `exports/<name>/` folders, snapshots excluded),
+ * reading each manifest for its metadata. Manifests are tiny, so the per-backup
+ * reads run in parallel.
+ */
+export async function listCompanyBackups(
client: SupabaseClient<Database>,
companyId: string
-) {
- return client.storage.from(companyId).list("exports", {
- limit: 25,
- sortBy: { column: "created_at", order: "desc" }
- });
-}
+): Promise<{ data: CompanyBackupSummary[] | null; error: Error | null }> {
+ const { data, error } = await client.storage
+ .from(companyId)
+ .list("exports", { limit: 100 });
+ if (error) return { data: null, error };
-export async function getCompanyBackupSignedUrl(
- client: SupabaseClient<Database>,
- companyId: string,
- filePath: string
-) {
- return client.storage.from(companyId).createSignedUrl(filePath, 60 * 60);
+ const folders = (data ?? []).filter(
+ (e) => e.id === null && !e.name.startsWith(SNAPSHOT_PREFIX)
+ );
+
+ const backups = await Promise.all(
+ folders.map(async (folder): Promise<CompanyBackupSummary> => {
+ const summary: CompanyBackupSummary = {
+ name: folder.name,
+ exportedAt: null,
+ label: null,
+ rows: 0,
+ sizeBytes: 0
+ };
+ const mf = await client.storage
+ .from(companyId)
+ .download(`exports/${folder.name}/manifest.json`);
+ if (mf.data) {
+ try {
+ const m = JSON.parse(await mf.data.text()) as {
+ exportedAt?: string;
+ label?: string | null;
+ tables?: Array<{ rows?: number }>;
+ storage?: Array<{ size?: number; included?: boolean }>;
+ };
+ summary.exportedAt = m.exportedAt ?? null;
+ summary.label = m.label ?? null;
+ summary.rows = (m.tables ?? []).reduce(
+ (sum, t) => sum + (t.rows ?? 0),
+ 0
+ );
+ summary.sizeBytes = (m.storage ?? [])
+ .filter((x) => x.included)
+ .reduce((sum, x) => sum + (x.size ?? 0), 0);
+ } catch {
+ // A folder without a readable manifest is a partial/aborted export —
+ // still list it (by name) so the user can delete it.
+ }
+ }
+ return summary;
+ })
+ );
+
+ backups.sort((a, b) =>
+ (b.exportedAt ?? "").localeCompare(a.exportedAt ?? "")
+ );
+ return { data: backups, error: null };
}
-export async function deleteCompanyBackupExport(
+/** Delete a backup — the whole `exports/<name>/` folder (data + manifest + assets). */
+export async function deleteCompanyBackup(
client: SupabaseClient<Database>,
companyId: string,
- filePath: string
+ name: string
) {
- // Release the backup's asset folder first, then the gz, so the bucket space
- // is fully reclaimed (the .assets/ files are the bulk of a backup).
- await removeStoragePrefix(client, companyId, backupAssetPrefix(filePath));
- return client.storage.from(companyId).remove([filePath]);
+ await removeStoragePrefix(client, companyId, `exports/${name}`);
+ return { error: null as Error | null };
}
/**
diff --git a/apps/erp/app/modules/settings/ui/Backups/BackupSourcePicker.tsx b/apps/erp/app/modules/settings/ui/Backups/BackupSourcePicker.tsx
index 00fd74079e..6f960d71ae 100644
--- a/apps/erp/app/modules/settings/ui/Backups/BackupSourcePicker.tsx
+++ b/apps/erp/app/modules/settings/ui/Backups/BackupSourcePicker.tsx
@@ -1,4 +1,3 @@
-import { useCarbon } from "@carbon/auth";
import { useControlField } from "@carbon/form";
import {
Command,
@@ -25,13 +24,10 @@ const triggerClass =
// One control combining your backups + upload new. Selecting one sets the
// hidden `source` field the restore form submits.
export function BackupSourcePicker({
- backups,
- companyId
+ backups
}: {
- backups: { path: string; name: string; createdAt: string | null }[];
- companyId: string;
+ backups: { name: string; exportedAt: string | null }[];
}) {
- const { carbon } = useCarbon();
const revalidator = useRevalidator();
const [value, setValue] = useControlField<string>("source");
const [open, setOpen] = useState(false);
@@ -41,7 +37,7 @@ export function BackupSourcePicker({
const label = useMemo(() => {
if (current.startsWith("backup:")) {
- const match = backups.find((b) => `backup:${b.path}` === current);
+ const match = backups.find((b) => `backup:${b.name}` === current);
return match ? formatBackupName(match.name) : "Backup";
}
return "";
@@ -51,27 +47,30 @@ export function BackupSourcePicker({
const file = e.target.files?.[0];
e.target.value = "";
if (!file) return;
- if (!carbon) {
- toast.error("Carbon client not found");
- return;
- }
- if (!file.name.endsWith(".gz")) {
- toast.error("Select a .carbon.json.gz backup");
+ if (!file.name.endsWith(".tar.gz") && !file.name.endsWith(".tgz")) {
+ toast.error("Select a .carbon.tar.gz backup");
return;
}
setUploading(true);
toast.info(`Uploading ${file.name}`);
- const { error: uploadError } = await carbon.storage
- .from(companyId)
- .upload(`exports/${file.name}`, file, { upsert: true });
- setUploading(false);
- if (uploadError) {
- toast.error(`Failed to upload: ${uploadError.message}`);
- return;
+ try {
+ // The server unpacks the archive into a fresh `exports/<name>/` folder so a
+ // cross-environment import has the data + media. Returns the folder name.
+ const res = await fetch("/api/settings/backup-upload", {
+ method: "POST",
+ body: file
+ });
+ if (!res.ok) {
+ toast.error(`Failed to upload: ${await res.text()}`);
+ return;
+ }
+ const { name } = (await res.json()) as { name: string };
+ setValue(`backup:${name}`);
+ toast.success("Backup uploaded");
+ revalidator.revalidate();
+ } finally {
+ setUploading(false);
}
- setValue(`backup:exports/${file.name}`);
- toast.success("Backup uploaded");
- revalidator.revalidate();
};
return (
@@ -80,7 +79,7 @@ export function BackupSourcePicker({
<input
ref={fileRef}
type="file"
- accept=".gz,application/gzip"
+ accept=".tar.gz,.tgz,application/gzip"
className="hidden"
onChange={onUpload}
/>
@@ -109,10 +108,10 @@ export function BackupSourcePicker({
<CommandGroup heading="Your backups">
{backups.map((b) => (
<CommandItem
- key={b.path}
+ key={b.name}
value={`backup ${b.name}`}
onSelect={() => {
- setValue(`backup:${b.path}`);
+ setValue(`backup:${b.name}`);
setOpen(false);
}}
>
@@ -120,7 +119,7 @@ export function BackupSourcePicker({
<span className="flex flex-col">
<span>{formatBackupName(b.name)}</span>
<span className="text-xs text-muted-foreground">
- {formatBackupDate(b.createdAt, false)}
+ {formatBackupDate(b.exportedAt, false)}
</span>
</span>
</CommandItem>
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 12ea7ad2a0..e6b073689c 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-24T20:02:59.411Z",
+ "generated": "2026-06-25T03:20:04.068Z",
"totalTools": 1215,
"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
new file mode 100644
index 0000000000..4f7afe5720
--- /dev/null
+++ b/apps/erp/app/routes/api+/settings.backup-archive.$file.ts
@@ -0,0 +1,104 @@
+import { createGzip } from "node:zlib";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { isInternalEmail } from "@carbon/utils";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import type { LoaderFunctionArgs } from "react-router";
+import { pack as tarPack } from "tar-stream";
+
+/** List every object under a storage prefix, returning paths relative to it. */
+async function listRelative(
+ client: SupabaseClient,
+ bucket: string,
+ prefix: string,
+ base: string = prefix
+): Promise<string[]> {
+ const out: string[] = [];
+ const { data } = await client.storage
+ .from(bucket)
+ .list(prefix, { limit: 1000 });
+ if (!data) return out;
+ for (const entry of data) {
+ const full = `${prefix}/${entry.name}`;
+ if (entry.id === null) {
+ out.push(...(await listRelative(client, bucket, full, base)));
+ } else {
+ out.push(full.slice(base.length + 1));
+ }
+ }
+ return out;
+}
+
+/**
+ * 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.
+ */
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId, email } = await requirePermissions(request, {
+ view: "settings"
+ });
+ if (!isInternalEmail(email)) throw new Response("Not found", { status: 404 });
+
+ const name = params.file ?? "";
+ if (!name || name.includes("/")) {
+ throw new Response("Invalid backup", { status: 400 });
+ }
+ const dir = `exports/${name}`;
+
+ const relPaths = await listRelative(client, companyId, dir);
+ if (relPaths.length === 0) {
+ throw new Response("Backup not found", { status: 404 });
+ }
+
+ const archive = tarPack();
+ const addEntry = (entryName: string, body: Buffer) =>
+ new Promise<void>((resolve, reject) => {
+ archive.entry({ name: entryName }, body, (err) =>
+ err ? reject(err) : resolve()
+ );
+ });
+
+ (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()));
+ }
+ archive.finalize();
+ } catch (err) {
+ archive.destroy(err as Error);
+ }
+ })();
+
+ // 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();
+ archive.on("error", (err) => gzip.destroy(err));
+ archive.pipe(gzip);
+ const stream = new ReadableStream({
+ start(controller) {
+ gzip.on("data", (chunk: Buffer) =>
+ controller.enqueue(new Uint8Array(chunk))
+ );
+ gzip.on("end", () => controller.close());
+ gzip.on("error", (err) => controller.error(err));
+ },
+ cancel() {
+ gzip.destroy();
+ archive.destroy();
+ }
+ });
+
+ return new Response(stream, {
+ status: 200,
+ headers: {
+ "Content-Type": "application/gzip",
+ "Content-Disposition": `attachment; filename="${name}.carbon.tar.gz"`
+ }
+ });
+}
diff --git a/apps/erp/app/routes/api+/settings.backup-upload.ts b/apps/erp/app/routes/api+/settings.backup-upload.ts
new file mode 100644
index 0000000000..67980957c1
--- /dev/null
+++ b/apps/erp/app/routes/api+/settings.backup-upload.ts
@@ -0,0 +1,75 @@
+import { Readable } from "node:stream";
+import { createGunzip } from "node:zlib";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { isInternalEmail } from "@carbon/utils";
+import type { ActionFunctionArgs } from "react-router";
+import { extract as tarExtract } from "tar-stream";
+
+/**
+ * Unpack an uploaded `.carbon.tar.gz` (a whole backup folder) into a fresh
+ * `exports/<name>/` so the normal restore/import then finds it. Entries are
+ * processed one at a time, so a large archive unpacks at flat memory. The raw
+ * archive is the request body (never stored whole).
+ *
+ * NOTE: this receives the upload server-side, so a Vercel-hosted target caps the
+ * body size. It's for local / self-hosted import targets (the prod -> local case).
+ */
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId, email } = await requirePermissions(request, {
+ update: "settings"
+ });
+ if (!isInternalEmail(email)) throw new Response("Not found", { status: 404 });
+ if (request.method !== "POST" || !request.body) {
+ throw new Response("Expected a tar.gz body", { status: 400 });
+ }
+
+ const ts = new Date().toISOString().replace(/[:.]/g, "-");
+ const name = `${ts}_uploaded`;
+ const dir = `exports/${name}`;
+
+ let manifestSeen = false;
+ let fileErrors = 0;
+
+ const extract = tarExtract();
+ const source = Readable.fromWeb(
+ request.body as Parameters<typeof Readable.fromWeb>[0]
+ );
+ const gunzip = createGunzip();
+ source.on("error", (err) => extract.destroy(err));
+ gunzip.on("error", (err) => extract.destroy(err));
+
+ await new Promise<void>((resolve, reject) => {
+ extract.on("entry", (header, stream, next) => {
+ const chunks: Buffer[] = [];
+ stream.on("data", (c: Buffer) => chunks.push(c));
+ stream.on("error", next);
+ stream.on("end", async () => {
+ try {
+ const rel = header.name;
+ // Reject path traversal; only land files inside this backup's folder.
+ if (rel.includes("..") || rel.startsWith("/")) {
+ next();
+ return;
+ }
+ if (rel === "manifest.json") manifestSeen = true;
+ const up = await client.storage
+ .from(companyId)
+ .upload(`${dir}/${rel}`, Buffer.concat(chunks), { upsert: true });
+ if (up.error) fileErrors++;
+ next();
+ } catch (err) {
+ next(err as Error);
+ }
+ });
+ });
+ extract.on("finish", resolve);
+ extract.on("error", reject);
+ source.pipe(gunzip).pipe(extract);
+ });
+
+ if (!manifestSeen) {
+ throw new Response("Archive is missing manifest.json", { status: 400 });
+ }
+
+ return { name, fileErrors };
+}
diff --git a/apps/erp/app/routes/x+/settings+/backups.tsx b/apps/erp/app/routes/x+/settings+/backups.tsx
index 56bd132e2a..399ab4c111 100644
--- a/apps/erp/app/routes/x+/settings+/backups.tsx
+++ b/apps/erp/app/routes/x+/settings+/backups.tsx
@@ -31,11 +31,10 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, Form, redirect, useFetcher, useLoaderData } from "react-router";
import { z } from "zod";
import {
- deleteCompanyBackupExport,
+ deleteCompanyBackup,
exportCompanyBackup,
- getCompanyBackupSignedUrl,
getCompanyRestoreRuns,
- listCompanyBackupExports
+ listCompanyBackups
} from "~/modules/settings";
import {
finalizeCompanyRestore,
@@ -62,10 +61,6 @@ export const handle: Handle = {
to: path.to.backups
};
-// Hidden pre-restore snapshots are named `_pre-restore-<runId>` — never shown
-// in the backups list or offered as a restore source.
-const SNAPSHOT_PREFIX = "_pre-restore-";
-
const exportValidator = z.object({
intent: z.literal("export"),
label: z.string().optional(),
@@ -94,35 +89,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
});
requireInternal(email);
- const [exportsList, restoreRuns] = await Promise.all([
- listCompanyBackupExports(client, companyId),
+ const [backupsList, restoreRuns] = await Promise.all([
+ listCompanyBackups(client, companyId),
getCompanyRestoreRuns(client, companyId)
]);
- const files = await Promise.all(
- (exportsList.data ?? [])
- // Drop folders and the hidden pre-restore snapshots.
- .filter((f) => f.id !== null && !f.name.startsWith(SNAPSHOT_PREFIX))
- .map(async (f) => {
- const filePath = `exports/${f.name}`;
- const signed = await getCompanyBackupSignedUrl(
- client,
- companyId,
- filePath
- );
- return {
- name: f.name,
- path: filePath,
- createdAt: f.created_at,
- size: (f.metadata as { size?: number } | null)?.size ?? 0,
- url: signed.data?.signedUrl ?? null
- };
- })
- );
-
return {
companyId,
- files,
+ files: backupsList.data ?? [],
restoreRuns: restoreRuns.data ?? []
};
}
@@ -174,8 +148,10 @@ export async function action({ request }: ActionFunctionArgs) {
const validation = await validator(restoreValidator).validate(formData);
if (validation.error) return validationError(validation.error);
- const filePath = validation.data.source.replace(/^backup:/, "");
- if (!filePath.startsWith("exports/")) {
+ // The source is the backup folder name. Reject anything with a path
+ // separator (traversal / legacy gz paths).
+ const source = validation.data.source.replace(/^backup:/, "");
+ if (!source || source.includes("/")) {
return { success: false, message: "Choose one of your backups" };
}
@@ -193,9 +169,9 @@ export async function action({ request }: ActionFunctionArgs) {
const restoreRunId = await startCompanyRestore({
companyId,
userId,
- filePath,
+ filePath: source,
includeStorage: validation.data.includeStorage,
- label: filePath.split("/").pop()
+ label: source
});
return { success: true, message: "Restore started", restoreRunId };
} catch (err) {
@@ -239,15 +215,11 @@ export async function action({ request }: ActionFunctionArgs) {
}
case "delete": {
- const filePath = String(formData.get("filePath") ?? "");
- if (!filePath.startsWith("exports/"))
- return data({}, await flash(request, error(null, "Invalid file path")));
+ const name = String(formData.get("name") ?? "");
+ if (!name || name.includes("/"))
+ return data({}, await flash(request, error(null, "Invalid backup")));
- const result = await deleteCompanyBackupExport(
- client,
- companyId,
- filePath
- );
+ const result = await deleteCompanyBackup(client, companyId, name);
if (result.error)
return data(
{},
@@ -262,7 +234,7 @@ export async function action({ request }: ActionFunctionArgs) {
}
export default function BackupsRoute() {
- const { companyId, files, restoreRuns } = useLoaderData<typeof loader>();
+ const { files, restoreRuns } = useLoaderData<typeof loader>();
const fetcher = useFetcher<{
success?: boolean;
message?: string;
@@ -282,7 +254,7 @@ export default function BackupsRoute() {
const exportCompleted =
active?.mode === "export" &&
!!active.exportBaseline &&
- files.some((f) => !active.exportBaseline!.has(f.path));
+ files.some((f) => !active.exportBaseline!.has(f.name));
// keep / dismiss / revert finalize the run via an async Inngest job, so the
// marker is still present on the next revalidation. Hide the row optimistically
@@ -311,7 +283,7 @@ export default function BackupsRoute() {
if (result.success && result.started === "export") {
setActive({
mode: "export",
- exportBaseline: new Set(filesRef.current.map((f) => f.path))
+ exportBaseline: new Set(filesRef.current.map((f) => f.name))
});
return;
}
@@ -384,7 +356,7 @@ export default function BackupsRoute() {
<div className="flex flex-col gap-6">
<div className="flex flex-col gap-1.5">
<span className="text-sm">Source</span>
- <BackupSourcePicker backups={files} companyId={companyId} />
+ <BackupSourcePicker backups={files} />
</div>
<div className="flex flex-col gap-1.5">
<span className="text-sm">Include</span>
@@ -459,7 +431,7 @@ export default function BackupsRoute() {
<VStack spacing={2}>
{files.map((file) => (
<HStack
- key={file.path}
+ key={file.name}
className="w-full justify-between border rounded-lg p-3"
>
<VStack spacing={0}>
@@ -467,30 +439,31 @@ export default function BackupsRoute() {
{formatBackupName(file.name)}
</span>
<span className="text-xs text-muted-foreground">
- {formatBackupDate(file.createdAt)}
- {file.size ? (
+ {formatBackupDate(file.exportedAt)}
+ {file.sizeBytes ? (
<>
{" · "}
- {convertKbToString(Math.round(file.size / 1024))}
+ {convertKbToString(
+ Math.round(file.sizeBytes / 1024)
+ )}
</>
) : null}
</span>
</VStack>
<HStack spacing={2}>
- {file.url && (
- <Button asChild variant="secondary">
- <a href={file.url} download>
- Download
- </a>
- </Button>
- )}
+ <Button asChild variant="secondary">
+ <a
+ href={`/api/settings/backup-archive/${encodeURIComponent(
+ file.name
+ )}`}
+ download
+ >
+ Download
+ </a>
+ </Button>
<Form method="post">
<input type="hidden" name="intent" value="delete" />
- <input
- type="hidden"
- name="filePath"
- value={file.path}
- />
+ <input type="hidden" name="name" value={file.name} />
<Button type="submit" variant="destructive">
Delete
</Button>
diff --git a/apps/erp/package.json b/apps/erp/package.json
index 4c30096340..fa4a44f1ee 100644
--- a/apps/erp/package.json
+++ b/apps/erp/package.json
@@ -45,11 +45,11 @@
"@react-aria/i18n": "catalog:",
"@react-email/components": "catalog:",
"@react-pdf/renderer": "catalog:",
- "@simplewebauthn/browser": "^13.3.0",
"@react-router/remix-routes-option-adapter": "catalog:",
"@react-router/serve": "catalog:",
"@react-types/datepicker": "3.13.5",
"@react-types/shared": "3.33.1",
+ "@simplewebauthn/browser": "^13.3.0",
"@supabase/functions-js": "catalog:",
"@supabase/postgrest-js": "catalog:",
"@supabase/storage-js": "catalog:",
@@ -122,6 +122,7 @@
"spin-delay": "2.0.1",
"sst": "catalog:",
"tailwind-merge": "catalog:",
+ "tar-stream": "^3.2.0",
"tiny-invariant": "1.3.3",
"tsup": "catalog:",
"unified": "11.0.5",
@@ -150,6 +151,7 @@
"@types/react": "catalog:",
"@types/react-csv": "1.1.10",
"@types/react-dom": "catalog:",
+ "@types/tar-stream": "^3.1.4",
"cross-env": "catalog:",
"nodemon": "catalog:",
"npm-run-all": "catalog:",
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
index 8f4783a268..292cb3afcd 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
@@ -20,41 +20,26 @@ import { nanoid } from "nanoid";
*/
export const BACKUP_KIND = "carbon-company-backup";
-// The gz is NDJSON: line 1 is `{ manifest }`, every later line is a single
-// `{ t, r }` table row. Read/written a line at a time (see (de)serializeBackup)
-// so a large backup never materializes as one >512MB string (V8's max) or one
-// giant JSON.parse. Storage assets travel as real files in a sibling `.assets/`
-// folder (server-side copied), not in the gz.
+// A backup is a folder `exports/<name>/` of small objects: `manifest.json`, one
+// `tables/<table>.ndjson.gz` per non-empty table (dumped + loaded in parallel),
+// and `assets/<path>` files. Each object stays under the bucket size cap; the
+// whole folder bundles into one `.carbon.tar.gz` for cross-environment transfer.
+// Per-table NDJSON is read/written a line at a time, so a huge table never
+// materializes as one >512MB string (V8's max) or one giant JSON.parse.
export const BACKUP_VERSION = 1;
export const BACKUP_INTEGRATION = "company-backup";
export const EXPORTS_PREFIX = "exports";
/** Shared, env-agnostic bucket holding the onboarding backup templates. */
export const TEMPLATE_BUCKET = "company-templates";
-/** Suffix of a backup gz object (its sibling asset folder swaps it for `.assets`). */
-export const BACKUP_GZ_SUFFIX = ".carbon.json.gz";
-
/**
* The bucket the app stores per-company assets in (3D models, item thumbnails,
- * document attachments), all under a `{companyId}/` prefix. A backup copies
- * these into its own `.assets/` folder (see `copyAssetsToBackup`); they are NOT
- * in the per-company bucket.
+ * document attachments), all under a `{companyId}/` prefix. A backup copies these
+ * into its own `assets/` folder (see `copyAssetsToBackup`); they are NOT in the
+ * per-company bucket.
*/
export const STORAGE_BUCKET = "private";
-/**
- * The asset folder that travels with a backup gz. A backup at
- * `exports/<name>.carbon.json.gz` keeps its storage files under
- * `exports/<name>.assets/<originalPath>` in the same per-company bucket. Derived
- * from the gz path, so it never needs to be stored in the manifest.
- */
-export function backupAssetPrefix(gzPath: string): string {
- const base = gzPath.endsWith(BACKUP_GZ_SUFFIX)
- ? gzPath.slice(0, -BACKUP_GZ_SUFFIX.length)
- : gzPath;
- return `${base}.assets`;
-}
-
/**
* TEXT columns that hold a storage path (`{companyId}/…/{id}.ext`). On reseed
* the companyId and the embedded ids both change, so these must be rewritten in
@@ -245,18 +230,55 @@ export type CompanyBackup = {
data: Record<string, Record<string, unknown>[]>;
};
-/** One NDJSON line: either the single manifest line, or one table row. */
-type BackupLine =
- | { manifest: Manifest }
- | { t: string; r: Record<string, unknown> };
+// ── File-per-table layout ──────────────────────────────────────────────────
+// A backup is a folder `exports/<name>/` of small objects (each under the bucket
+// size cap): `manifest.json`, one `tables/<table>.ndjson.gz` per non-empty table
+// (dumped + loaded in parallel), and `assets/<path>` files. Bundled as one
+// `.carbon.tar.gz` for cross-environment download / upload.
+
+export function backupDir(name: string): string {
+ return `${EXPORTS_PREFIX}/${name}`;
+}
+export function backupManifestPath(name: string): string {
+ return `${EXPORTS_PREFIX}/${name}/manifest.json`;
+}
+
+/** Run `fn` over `items` with at most `limit` in flight. */
+export async function mapWithConcurrency<T>(
+ items: T[],
+ limit: number,
+ fn: (item: T) => Promise<void>
+): Promise<void> {
+ let next = 0;
+ const workers = Array.from(
+ { length: Math.min(limit, items.length) },
+ async () => {
+ while (next < items.length) {
+ const item = items[next++];
+ if (item === undefined) break;
+ await fn(item);
+ }
+ }
+ );
+ await Promise.all(workers);
+}
+export function backupTablePath(name: string, table: string): string {
+ return `${EXPORTS_PREFIX}/${name}/tables/${table}.ndjson.gz`;
+}
+export function backupTablesDir(name: string): string {
+ return `${EXPORTS_PREFIX}/${name}/tables`;
+}
+export function backupAssetsDir(name: string): string {
+ return `${EXPORTS_PREFIX}/${name}/assets`;
+}
/**
- * Serialize a backup to a gzipped NDJSON buffer. Each row is written as its own
- * line straight into the gzip stream, so we never build a single >512MB string
- * (V8's max string length) the way `JSON.stringify(wholeBackup)` would — large
- * companies serialize at flat memory.
+ * Gzip one table's rows as NDJSON (one JSON object per line). Streamed, so a huge
+ * table never builds a `>512MB` string.
*/
-export async function serializeBackup(backup: CompanyBackup): Promise<Buffer> {
+export async function serializeTable(
+ rows: Record<string, unknown>[]
+): Promise<Buffer> {
const gzip = createGzip();
const chunks: Buffer[] = [];
gzip.on("data", (c: Buffer) => chunks.push(c));
@@ -264,55 +286,86 @@ export async function serializeBackup(backup: CompanyBackup): Promise<Buffer> {
gzip.on("end", resolve);
gzip.on("error", reject);
});
-
- const writeLine = (line: BackupLine) =>
- new Promise<void>((resolve, reject) => {
- gzip.write(`${JSON.stringify(line)}\n`, (err) =>
+ for (const row of rows) {
+ await new Promise<void>((resolve, reject) => {
+ gzip.write(`${JSON.stringify(row)}\n`, (err) =>
err ? reject(err) : resolve()
);
});
-
- await writeLine({ manifest: backup.manifest });
- for (const [table, rows] of Object.entries(backup.data)) {
- for (const row of rows) await writeLine({ t: table, r: row });
}
-
gzip.end();
await finished;
return Buffer.concat(chunks);
}
/**
- * Parse a gzipped NDJSON backup. Streams the gunzip output line by line, so the
- * uncompressed payload (which can exceed V8's max string length for a large
- * company) is never decoded into one string nor passed to a single JSON.parse.
- * Reconstructs the in-memory `CompanyBackup` the rest of the pipeline expects.
+ * Parse a `tables/<table>.ndjson.gz` into rows. Streams the gunzip line by line,
+ * so a huge table is never one giant string nor a single JSON.parse.
*/
-export async function deserializeBackup(
+export async function deserializeTable(
bytes: ArrayBuffer
-): Promise<CompanyBackup> {
+): Promise<Record<string, unknown>[]> {
const gunzip = createGunzip();
Readable.from(Buffer.from(bytes)).pipe(gunzip);
const rl = createInterface({
input: gunzip,
crlfDelay: Number.POSITIVE_INFINITY
});
-
- let manifest: Manifest | undefined;
- const data: CompanyBackup["data"] = {};
+ const rows: Record<string, unknown>[] = [];
for await (const line of rl) {
- if (!line) continue;
- const parsed = JSON.parse(line) as BackupLine;
- if ("manifest" in parsed) {
- manifest = parsed.manifest;
- continue;
- }
- (data[parsed.t] ??= []).push(parsed.r);
+ if (line) rows.push(JSON.parse(line));
}
+ return rows;
+}
- if (!manifest) {
- throw new Error("Backup is missing its manifest line");
+/** How many table files to dump/load concurrently. */
+export const BACKUP_TABLE_CONCURRENCY = 6;
+
+/** A restore/import `source` is the backup folder name. Bridge legacy single-gz
+ * sources (`exports/<name>.carbon.json.gz`) to the folder name during the
+ * transition. */
+export function backupNameFromSource(source: string): string {
+ return source.replace(/^exports\//, "").replace(/\.carbon\.json\.gz$/, "");
+}
+
+/**
+ * Read a backup folder `exports/<name>/`: its manifest, then every table file in
+ * parallel, into the in-memory `CompanyBackup` the load pipeline expects.
+ */
+export async function readBackup(
+ client: SupabaseClient,
+ companyId: string,
+ name: string
+): Promise<CompanyBackup> {
+ const mf = await client.storage
+ .from(companyId)
+ .download(backupManifestPath(name));
+ if (mf.error || !mf.data) {
+ throw new Error(
+ `Failed to download backup manifest ${name}: ${mf.error?.message}`
+ );
+ }
+ const manifest = JSON.parse(await mf.data.text()) as Manifest;
+ if (manifest.kind !== BACKUP_KIND) {
+ throw new Error("Not a Carbon company backup");
}
+
+ const data: CompanyBackup["data"] = {};
+ await mapWithConcurrency(
+ manifest.tables,
+ BACKUP_TABLE_CONCURRENCY,
+ async (t) => {
+ const f = await client.storage
+ .from(companyId)
+ .download(backupTablePath(name, t.name));
+ if (f.error || !f.data) {
+ throw new Error(
+ `Failed to download table ${t.name} for ${name}: ${f.error?.message}`
+ );
+ }
+ data[t.name] = await deserializeTable(await f.data.arrayBuffer());
+ }
+ );
return { manifest, data };
}
diff --git a/packages/jobs/src/inngest/functions/tasks/company-export.ts b/packages/jobs/src/inngest/functions/tasks/company-export.ts
index 60d7c82cf4..63135504b9 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-export.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-export.ts
@@ -1,35 +1,44 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { sql } from "kysely";
import { inngest } from "../../client";
-import type { CompanyBackup, Manifest } from "./company-backup";
+import type { Manifest } from "./company-backup";
import {
BACKUP_INTEGRATION,
BACKUP_KIND,
BACKUP_VERSION,
- backupAssetPrefix,
+ backupAssetsDir,
+ backupManifestPath,
+ backupTablePath,
copyAssetsToBackup,
- EXPORTS_PREFIX,
encodeValue,
getCompanyTableCatalog,
getJobDatabaseClient,
+ mapWithConcurrency,
SECRET_TABLES,
STORAGE_BUCKET,
- serializeBackup
+ serializeTable
} from "./company-backup";
-// Assets are copied server-side into the backup's `.assets/` folder (no bytes
-// pass through this process), so there's no memory reason to cap a single file —
-// the bucket already bounds uploads (120MB CAD models, 50MB docs). The only
-// bound is a storage-cost guard on the whole backup: each export duplicates the
-// bundled bytes, so cap the total at 1GB.
+// Assets are copied server-side into the backup's `assets/` folder (no bytes pass
+// through this process), so there's no memory reason to cap a single file — the
+// bucket already bounds uploads (120MB CAD models, 50MB docs). The only bound is a
+// storage-cost guard on the whole backup: each export duplicates the bundled
+// bytes, so cap the total at 1GB.
const MAX_STORAGE_TOTAL_BYTES = 1024 * 1024 * 1024;
+// How many tables to dump concurrently (query + gzip + upload). Matched by the
+// export job's connection pool size.
+const TABLE_CONCURRENCY = 6;
+
type ServiceRole = ReturnType<typeof getCarbonServiceRole>;
type JobDatabase = ReturnType<typeof getJobDatabaseClient>;
/**
- * Build a gzipped company backup (data + optional storage files). Exported so
- * the same logic that backs the export job can author onboarding templates.
+ * Build a company backup as a folder of small objects under `exports/<name>/`:
+ * one `tables/<table>.ndjson.gz` per non-empty table (dumped in parallel), a
+ * `manifest.json`, and (via the caller) `assets/<path>` files. Returns the folder
+ * name. Exported so the same logic backs the export job, snapshots and onboarding
+ * templates.
*/
export async function buildCompanyBackup(
client: ServiceRole,
@@ -39,12 +48,14 @@ export async function buildCompanyBackup(
userId: string;
label?: string | null;
includeStorage: "none" | "all";
+ /** Override the generated folder name (snapshots pass their own). */
+ name?: string;
}
): Promise<{
- compressed: Buffer;
+ name: string;
manifest: Manifest;
rows: number;
- /** `private`-bucket paths to copy into the backup's `.assets/` folder. */
+ /** `private`-bucket paths to copy into the backup's `assets/` folder. */
assetSourcePaths: string[];
}> {
const { companyId, userId, includeStorage } = opts;
@@ -69,24 +80,29 @@ export async function buildCompanyBackup(
);
}
+ const exportedAt = new Date().toISOString();
+ const slug = label
+ ? `_${label
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .slice(0, 40)}`
+ : "";
+ const name = opts.name ?? `${exportedAt.replace(/[:.]/g, "-")}${slug}`;
+
const catalog = await getCompanyTableCatalog(db);
const secretTables = new Set(SECRET_TABLES);
+ const excludedTables = catalog.tables
+ .filter((t) => secretTables.has(t.name))
+ .map((t) => t.name);
+ const exportable = catalog.tables.filter((t) => !secretTables.has(t.name));
- const data: CompanyBackup["data"] = {};
+ // Dump each non-empty table to its own `tables/<table>.ndjson.gz`, in parallel.
const tableManifest: Manifest["tables"] = [];
- const excludedTables: string[] = [];
-
- for (const table of catalog.tables) {
- if (secretTables.has(table.name)) {
- excludedTables.push(table.name);
- continue;
- }
-
- // companyGroup-scoped tables (chart of accounts, currencies, …) are
- // filtered by the company's group; everything else by companyId.
+ await mapWithConcurrency(exportable, TABLE_CONCURRENCY, async (table) => {
+ // companyGroup-scoped tables (chart of accounts, currencies, …) are filtered
+ // by the company's group; everything else by companyId.
const scopeValue =
table.scopeColumn === "companyGroupId" ? companyGroupId : companyId;
-
const columns = table.columns.filter((c) => !c.isGenerated);
// a prior import's revert ledger must never travel in an artifact
const ledgerFilter =
@@ -99,29 +115,36 @@ export async function buildCompanyBackup(
WHERE ${sql.id(table.scopeColumn)} = ${scopeValue}${ledgerFilter}
`.execute(db);
- if (result.rows.length === 0) continue;
+ if (result.rows.length === 0) return; // empty tables get no file
- data[table.name] = result.rows.map((row) => {
+ const rows = result.rows.map((row) => {
const encoded: Record<string, unknown> = {};
for (const col of columns) {
encoded[col.name] = encodeValue(row[col.name], col);
}
return encoded;
});
+ const buf = await serializeTable(rows);
+ const up = await client.storage
+ .from(companyId)
+ .upload(backupTablePath(name, table.name), buf, {
+ contentType: "application/gzip",
+ upsert: true
+ });
+ if (up.error) throw new Error(`table ${table.name}: ${up.error.message}`);
tableManifest.push({
name: table.name,
rows: result.rows.length,
columns: columns.map((c) => c.name)
});
- }
+ });
// Decide which storage assets are in scope. They live in the shared `private`
// bucket under a `{companyId}/` prefix (3D models, item thumbnails,
- // attachments). They are NOT embedded here — the caller copies the included
- // files server-side into the backup's sibling `.assets/` folder, so a large
- // asset set costs no memory and the gz stays small. Skip anything over the
- // size caps.
+ // attachments). They are NOT embedded — the caller copies the included files
+ // server-side into the backup's `assets/` folder, so a large asset set costs no
+ // memory. Skip anything over the total size guard.
const storageManifest: Manifest["storage"] = [];
const assetSourcePaths: string[] = [];
@@ -132,7 +155,6 @@ export async function buildCompanyBackup(
STORAGE_BUCKET,
companyId
);
-
for (const file of paths) {
const included = totalBytes + file.size <= MAX_STORAGE_TOTAL_BYTES;
if (included) {
@@ -150,7 +172,7 @@ export async function buildCompanyBackup(
sourceCompanyId: companyId,
sourceCompanyGroupId: companyGroupId,
sourceCompanyName: company.data?.name ?? null,
- exportedAt: new Date().toISOString(),
+ exportedAt,
exportedBy: userId,
label,
includeStorage,
@@ -159,10 +181,18 @@ export async function buildCompanyBackup(
excludedTables
};
- const backup: CompanyBackup = { manifest, data };
- const compressed = await serializeBackup(backup);
+ const manifestUpload = await client.storage
+ .from(companyId)
+ .upload(backupManifestPath(name), Buffer.from(JSON.stringify(manifest)), {
+ contentType: "application/json",
+ upsert: true
+ });
+ if (manifestUpload.error) {
+ throw new Error(`manifest: ${manifestUpload.error.message}`);
+ }
+
const rows = tableManifest.reduce((sum, t) => sum + t.rows, 0);
- return { compressed, manifest, rows, assetSourcePaths };
+ return { name, manifest, rows, assetSourcePaths };
}
export const companyExportFunction = inngest.createFunction(
@@ -177,9 +207,9 @@ export const companyExportFunction = inngest.createFunction(
return await step.run("export-company", async () => {
const client = getCarbonServiceRole();
- const db = getJobDatabaseClient(1);
+ const db = getJobDatabaseClient(TABLE_CONCURRENCY);
- const { compressed, manifest, rows, assetSourcePaths } =
+ const { name, manifest, rows, assetSourcePaths } =
await buildCompanyBackup(client, db, {
companyId,
userId,
@@ -187,42 +217,25 @@ export const companyExportFunction = inngest.createFunction(
includeStorage
});
- const timestamp = manifest.exportedAt.replace(/[:.]/g, "-");
- const slug = label
- ? `_${label
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, "-")
- .slice(0, 40)}`
- : "";
- const path = `${EXPORTS_PREFIX}/${timestamp}${slug}.carbon.json.gz`;
-
- const upload = await client.storage
- .from(companyId)
- .upload(path, compressed, {
- contentType: "application/gzip",
- upsert: false
- });
- if (upload.error) throw new Error(upload.error.message);
-
- // Copy the in-scope assets server-side into the backup's `.assets/` folder.
- // Best-effort (matches restore/import): the data gz is already committed.
+ // Copy the in-scope assets server-side into the backup's `assets/` folder.
+ // Best-effort (matches restore/import): the table files + manifest are
+ // already committed.
const assets = await copyAssetsToBackup(client, {
sourcePaths: assetSourcePaths,
destBucket: companyId,
- destPrefix: backupAssetPrefix(path)
+ destPrefix: backupAssetsDir(name)
});
console.log("Company export complete", {
companyId,
- path,
+ name,
tables: manifest.tables.length,
rows,
- bytes: compressed.byteLength,
assetsCopied: assets.copied,
assetsFailed: assets.failed
});
- return { path, tables: manifest.tables.length, rows };
+ return { name, tables: manifest.tables.length, rows };
});
}
);
diff --git a/packages/jobs/src/inngest/functions/tasks/company-import.ts b/packages/jobs/src/inngest/functions/tasks/company-import.ts
index 29988a6100..fdbd4c48ab 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-import.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-import.ts
@@ -6,17 +6,17 @@ import type { ColumnInfo, TableInfo } from "./company-backup";
import {
assertBackupImportable,
BACKUP_INTEGRATION,
- BACKUP_KIND,
- backupAssetPrefix,
+ backupAssetsDir,
+ backupNameFromSource,
bindValue,
canSetReplicationRole,
- deserializeBackup,
filterUnpopulated,
getCompanyTableCatalog,
getJobDatabaseClient,
isUserScopedIdentityTable,
newIdForTable,
RESEED_SKIPPED_TABLES,
+ readBackup,
restoreAssetsFromBackup,
rewriteStoragePath,
rewriteToTemplateAssetPath,
@@ -77,18 +77,9 @@ export const companyImportFunction = inngest.createFunction(
return { importRunId, skipped: true };
}
- const download = await client.storage.from(companyId).download(filePath);
- if (download.error || !download.data) {
- throw new Error(
- `Failed to download artifact ${filePath}: ${download.error?.message}`
- );
- }
+ const name = backupNameFromSource(filePath);
+ const backup = await readBackup(client, companyId, name);
- const backup = await deserializeBackup(await download.data.arrayBuffer());
-
- if (backup.manifest?.kind !== BACKUP_KIND) {
- throw new Error("File is not a Carbon company backup");
- }
if (
mode === "preserve" &&
backup.manifest.sourceCompanyId !== companyId
@@ -461,7 +452,7 @@ export const companyImportFunction = inngest.createFunction(
const assets = await restoreAssetsFromBackup(client, {
files: backup.manifest.storage,
srcBucket: companyId,
- srcPrefix: backupAssetPrefix(filePath),
+ srcPrefix: backupAssetsDir(name),
sourceCompanyId,
companyId,
idRewrite
diff --git a/packages/jobs/src/inngest/functions/tasks/company-restore.ts b/packages/jobs/src/inngest/functions/tasks/company-restore.ts
index ddf7df8930..da0b171ec9 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-restore.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-restore.ts
@@ -11,15 +11,16 @@ import type {
import {
assertBackupImportable,
assertWipeSafe,
- BACKUP_KIND,
- backupAssetPrefix,
+ backupAssetsDir,
+ backupDir,
+ backupNameFromSource,
bindValue,
canSetReplicationRole,
- deserializeBackup,
getCompanyTableCatalog,
getJobDatabaseClient,
newIdForTable,
RESTORE_INTEGRATION,
+ readBackup,
removeStoragePrefix,
restoreAssetsFromBackup,
rewriteStoragePath,
@@ -30,7 +31,6 @@ import {
import { buildCompanyBackup } from "./company-export";
const INSERT_CHUNK_SIZE = 200;
-const EXPORTS_PREFIX = "exports";
/** FKs to these collapse to the importing user when re-stamping a foreign backup. */
const USER_REF_TABLES = new Set(["user", "employee"]);
@@ -38,25 +38,6 @@ const USER_REF_TABLES = new Set(["user", "employee"]);
type ServiceRole = ReturnType<typeof getCarbonServiceRole>;
type JobDatabase = ReturnType<typeof getJobDatabaseClient>;
-/** Parse + structurally validate a gzipped backup blob. */
-async function downloadBackup(
- client: ServiceRole,
- companyId: string,
- filePath: string
-): Promise<CompanyBackup> {
- const download = await client.storage.from(companyId).download(filePath);
- if (download.error || !download.data) {
- throw new Error(
- `Failed to download backup ${filePath}: ${download.error?.message}`
- );
- }
- const backup = await deserializeBackup(await download.data.arrayBuffer());
- if (backup.manifest?.kind !== BACKUP_KIND) {
- throw new Error("File is not a Carbon company backup");
- }
- return backup;
-}
-
type Transform = (value: unknown) => unknown;
/**
@@ -430,7 +411,8 @@ export const companyRestoreFunction = inngest.createFunction(
});
try {
- const backup = await downloadBackup(client, companyId, filePath);
+ const name = backupNameFromSource(filePath);
+ const backup = await readBackup(client, companyId, name);
const targetGroupId = await getCompanyGroupId(client, companyId);
// Group-scoped data (chart of accounts, currencies, dimensions) is shared
@@ -477,24 +459,16 @@ export const companyRestoreFunction = inngest.createFunction(
// capture the WIPED state and overwrite the real pre-restore copy.
let snapshotPath = existing?.metadata.snapshotPath ?? undefined;
if (!snapshotPath) {
- const snapshot = await buildCompanyBackup(client, db, {
+ // buildCompanyBackup writes the snapshot folder (tables + manifest)
+ // directly; the marker stores the folder name.
+ snapshotPath = `_pre-restore-${restoreRunId}`;
+ await buildCompanyBackup(client, db, {
companyId,
userId,
label: `Pre-restore ${restoreRunId}`,
- includeStorage: "all"
+ includeStorage: "all",
+ name: snapshotPath
});
- snapshotPath = `${EXPORTS_PREFIX}/_pre-restore-${restoreRunId}.carbon.json.gz`;
- const snapshotUpload = await client.storage
- .from(companyId)
- .upload(snapshotPath, snapshot.compressed, {
- contentType: "application/gzip",
- upsert: true
- });
- if (snapshotUpload.error) {
- throw new Error(
- `Failed to snapshot before restore: ${snapshotUpload.error.message}`
- );
- }
await writeRestoreMarker(client, {
companyId,
userId,
@@ -527,7 +501,7 @@ export const companyRestoreFunction = inngest.createFunction(
await restoreAssetsFromBackup(client, {
files: backup.manifest.storage,
srcBucket: companyId,
- srcPrefix: backupAssetPrefix(filePath),
+ srcPrefix: backupAssetsDir(name),
sourceCompanyId: backup.manifest.sourceCompanyId,
companyId,
idRewrite
@@ -601,12 +575,7 @@ export const companyRestoreFinalizeFunction = inngest.createFunction(
const snapshotPath = marker?.metadata.snapshotPath;
if (snapshotPath) {
- await client.storage.from(companyId).remove([snapshotPath]);
- await removeStoragePrefix(
- client,
- companyId,
- backupAssetPrefix(snapshotPath)
- );
+ await removeStoragePrefix(client, companyId, backupDir(snapshotPath));
}
await deleteRestoreMarker(client, companyId, restoreRunId);
@@ -659,7 +628,7 @@ export const companyRestoreRevertFunction = inngest.createFunction(
// check). Wipe + reload the SAME scope the forward restore touched so the
// undo is exact — including group data (chart of accounts) when the
// forward run covered it.
- const snapshot = await downloadBackup(client, companyId, snapshotPath);
+ const snapshot = await readBackup(client, companyId, snapshotPath);
const targetGroupId = await getCompanyGroupId(client, companyId);
const catalog = await getCompanyTableCatalog(db);
const { rows, idRewrite } = await wipeAndLoad(db, catalog, snapshot, {
@@ -672,18 +641,13 @@ export const companyRestoreRevertFunction = inngest.createFunction(
await restoreAssetsFromBackup(client, {
files: snapshot.manifest.storage,
srcBucket: companyId,
- srcPrefix: backupAssetPrefix(snapshotPath),
+ srcPrefix: backupAssetsDir(snapshotPath),
sourceCompanyId: companyId,
companyId,
idRewrite
});
- await client.storage.from(companyId).remove([snapshotPath]);
- await removeStoragePrefix(
- client,
- companyId,
- backupAssetPrefix(snapshotPath)
- );
+ await removeStoragePrefix(client, companyId, backupDir(snapshotPath));
await deleteRestoreMarker(client, companyId, restoreRunId);
console.log("Company restore reverted", {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4300c4c331..2d7cd22c33 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -286,7 +286,7 @@ importers:
version: 1.40.0
'@react-router/remix-routes-option-adapter':
specifier: 'catalog:'
cookie:
specifier: 'catalog:'
version: 1.1.1
@@ -323,7 +323,7 @@ importers:
'@react-router/dev':
specifier: 'catalog:'
'@types/aws-lambda':
specifier: 8.10.152
version: 8.10.152
@@ -371,7 +371,7 @@ importers:
version: 5.8.3
vite-plugin-babel-macros:
specifier: 'catalog:'
optionalDependencies:
'@rollup/rollup-linux-x64-gnu':
specifier: 4.60.1
@@ -655,7 +655,7 @@ importers:
'@react-router/remix-routes-option-adapter':
specifier: 'catalog:'
'@react-router/serve':
specifier: 'catalog:'
@@ -700,7 +700,7 @@ importers:
'@vercel/react-router':
specifier: 'catalog:'
'@visx/responsive':
specifier: 2.17.0
version: 2.17.0([email protected])
@@ -884,6 +884,9 @@ importers:
tailwind-merge:
specifier: 'catalog:'
version: 3.3.0
+ tar-stream:
+ specifier: ^3.2.0
+ version: 3.2.0
tiny-invariant:
specifier: 1.3.3
version: 1.3.3
@@ -926,16 +929,16 @@ importers:
'@lingui/vite-plugin':
specifier: 'catalog:'
'@react-router/dev':
specifier: 'catalog:'
'@tailwindcss/typography':
specifier: 'catalog:'
version: 0.5.19([email protected])
'@tailwindcss/vite':
specifier: 'catalog:'
'@types/d3':
specifier: 7.4.3
version: 7.4.3
@@ -963,6 +966,9 @@ importers:
'@types/react-dom':
specifier: 18.3.7
version: 18.3.7(@types/[email protected])
+ '@types/tar-stream':
+ specifier: ^3.1.4
+ version: 3.1.4
cross-env:
specifier: 'catalog:'
version: 7.0.3
@@ -992,13 +998,13 @@ importers:
version: 5.8.3
vite:
specifier: 'catalog:'
vite-plugin-babel-macros:
specifier: 'catalog:'
vitest:
specifier: 'catalog:'
apps/mes:
dependencies:
@@ -9086,6 +9092,9 @@ packages:
resolution: {integrity: sha512-7NQmHra/JILCd1QqpSzl8+mJRc8ZHz3uDm8YV1Ks9IhK0epEiTw8aIErbvH9PI+6XbqhyIQy3462nEsn7UVzjQ==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-921gW0+g29mCJX0fRvqeHzBlE/XclDaAG0Ousy1LCghsOhvaKacDeRGEVzQP9IPfKn8Vysy7FEXAIxycpc/CMg==}
+
resolution: {integrity: sha512-KHPsfX/FoVbUGbyYvk1q9MMQHLPeRZhRJZdO45Q4YjvFkv4hMNghCWTvy7rdKessBsmtz4euWCWAB6/tVpI1Iw==}
@@ -9489,6 +9498,14 @@ packages:
resolution: {integrity: sha512-wWyJDlAatxk30ZJer+GeCWS209sA42X+N5jU2jy6oHTp7ufw8uzUTVFBX9+wTfAlhiJXGS0Bq7X6efruWjuK9Q==}
+ resolution: {integrity: sha512-aiqre1Nr0B/6DgE2N5vwTc+2/oQZ4Wh1t4NznYY4E00y8LCt6NqdRv81so00oo27D8MVKTpUa/MwUUtBLXCoDw==}
+ peerDependencies:
+ react-native-b4a: '*'
+ peerDependenciesMeta:
+ react-native-b4a:
+ optional: true
+
resolution: {integrity: sha512-GERT7L2TiYcYDtYk1IpD+ASAYXjKbLTDPhBtYj7X1NuRMDTMtAx9kyBenub1Ev41lo91OHCKdmP+egTDmfQ7Ig==}
@@ -9509,6 +9526,47 @@ packages:
resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==}
engines: {node: 18 || 20 || >=22}
+ resolution: {integrity: sha512-Z0oHEHAFDZkffN8Qc39zNZjQlMDkPJRyyyZieU1VH7u8c5S+qHZ2S8ixdKIAxEjfHO7FJxXmJWgteOghVanIsg==}
+ peerDependencies:
+ bare-abort-controller: '*'
+ peerDependenciesMeta:
+ bare-abort-controller:
+ optional: true
+
+ resolution: {integrity: sha512-aTvMFUWkBmjzKtEQMDGGDNF8bkfpD5N1b/FCwt7A3wrU4t1o/e/85Wzkluh6JlODCjqVESYCkQCdTXqZ9G7VFg==}
+ engines: {bare: '>=1.16.0'}
+ peerDependencies:
+ bare-buffer: '*'
+ peerDependenciesMeta:
+ bare-buffer:
+ optional: true
+
+ resolution: {integrity: sha512-6M5XjcnsygQNPMCMPXSK379xrJFiZ/AEMNBmFEmQW8d/789VQATvriyi5r0HYTL9TkQ26rn3kgdTG3aisbrXkQ==}
+ engines: {bare: '>=1.14.0'}
+
+ resolution: {integrity: sha512-ghj2DSK/2e99a1anTVPCV4m4YIYtrbXhfM7V3D7XZLOTsybnYyaJloymGqssQc8l/or0UoDyRtNQkmkEF/ysgQ==}
+
+ resolution: {integrity: sha512-Kc+brLqvEqGkjyfiwJmImAOqLZL7OsoLKuavx+hJjgVV3nLTOjloJyPMFxjUPerGGHrNH0fLU06jjykMLWrERQ==}
+ peerDependencies:
+ bare-abort-controller: '*'
+ bare-buffer: '*'
+ bare-events: '*'
+ peerDependenciesMeta:
+ bare-abort-controller:
+ optional: true
+ bare-buffer:
+ optional: true
+ bare-events:
+ optional: true
+
+ resolution: {integrity: sha512-K+y9xF1tN+CdPu4qWwr0QiK1Al07eFPGYK5M2pDXcmHdMdgC/tT/bpmMe1hrmRHaidKLkXrC+cRNYf3XVDUhSQ==}
+
resolution: {integrity: sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==}
engines: {node: '>= 0.4'}
@@ -10521,6 +10579,9 @@ packages:
resolution: {integrity: sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==}
+ resolution: {integrity: sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==}
+
resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==}
engines: {node: '>=0.8.x'}
@@ -10575,6 +10636,9 @@ packages:
resolution: {integrity: sha512-jt2DW/aNFNwke7AUd+Z+e6pz39KO5rzdbbFCg2sGafS4mk13MI7Z8O5z9cADNn5lhGODIgLwug6TZO2ctf7kcw==}
engines: {node: '>=6.0.0'}
+ resolution: {integrity: sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==}
+
resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==}
engines: {node: '>=8.6.0'}
@@ -13823,6 +13887,9 @@ packages:
resolution: {integrity: sha512-rT00SPnTVyRsaSz5zgSPma/aHSOic5U1prhYdRy5HS2kTZviFpmDgzilbtsJsxiroqACmayynDN/9VzIbX5DOw==}
+ resolution: {integrity: sha512-1Yowhzjf0ivGMrTIkY9hav5TxobO9qIVqUE41fiCGMGgc3CLlf4MY+9AHmZqBWgDTue0fY9zWjYFVyf6Diuobw==}
+
resolution: {integrity: sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==}
engines: {node: '>=0.6.19'}
@@ -14008,16 +14075,25 @@ packages:
resolution: {integrity: sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-ojzvCvVaNp6aOTFmG7jaRD0meowIAuPc3cMMhSgKiVWws1GyHbGd/xvnyuRKcKlMpt3qvxx6r0hreCNITP9hIg==}
+
resolution: {integrity: sha512-tOG/7GyXpFevhXVh8jOPJrmtRpOTsYqUIkVdVooZYJS/z8WhfQUX8RJILmeuJNinGAMSu1veBr4asSHFt5/hng==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==}
+
resolution: {integrity: sha512-ye47xp8Cb0nDguAhrrDS1JT1SzwEV9e26sSsrWzVu+yPZ7LzceEcH0i2gci9jWfOfSCCgM3Qv5nOYShVUUFUXA==}
resolution: {integrity: sha512-lDMFv4nKQrSjlkHKAlHVqKrBG4DyFfa9F74cmBZ3Iy3ed8yvWnlWSIdi4IKfSqwmazAohBNwiN64qGx4y5Q3IQ==}
+ resolution: {integrity: sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==}
+
resolution: {integrity: sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==}
engines: {node: '>=0.8'}
@@ -16294,6 +16370,16 @@ snapshots:
transitivePeerDependencies:
- typescript
+ dependencies:
+ '@lingui/cli': 5.9.4([email protected])([email protected])
+ '@lingui/conf': 5.9.4([email protected])
+ transitivePeerDependencies:
+ - babel-plugin-macros
+ - supports-color
+ - typescript
+
dependencies:
'@lingui/cli': 5.9.4([email protected])([email protected])
@@ -20897,6 +20983,13 @@ snapshots:
postcss-selector-parser: 6.0.10
tailwindcss: 4.3.0
+ dependencies:
+ '@tailwindcss/node': 4.3.0
+ '@tailwindcss/oxide': 4.3.0
+ tailwindcss: 4.3.0
+
dependencies:
'@tailwindcss/node': 4.3.0
@@ -21619,6 +21712,10 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 22.19.7
+
dependencies:
'@types/node': 22.19.7
@@ -21696,6 +21793,16 @@ snapshots:
'@vercel/[email protected]': {}
+ dependencies:
+ '@vercel/static-config': 3.2.0
+ isbot: 5.1.37
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ ts-morph: 12.0.0
+
dependencies:
@@ -21826,6 +21933,14 @@ snapshots:
optionalDependencies:
+ dependencies:
+ '@vitest/spy': 4.1.6
+ estree-walker: 3.0.3
+ magic-string: 0.30.21
+ optionalDependencies:
+
dependencies:
'@vitest/spy': 4.1.6
@@ -22079,6 +22194,8 @@ snapshots:
transitivePeerDependencies:
- debug
+
dependencies:
'@babel/core': 7.29.0
@@ -22102,6 +22219,39 @@ snapshots:
+
+ dependencies:
+ bare-events: 2.9.1
+ bare-path: 3.0.1
+ bare-stream: 2.13.3([email protected])
+ bare-url: 2.4.5
+ fast-fifo: 1.3.2
+ transitivePeerDependencies:
+ - bare-abort-controller
+ - react-native-b4a
+
+
+ dependencies:
+ bare-os: 3.9.1
+
+ dependencies:
+ b4a: 1.8.1
+ streamx: 2.28.0
+ teex: 1.0.1
+ optionalDependencies:
+ bare-events: 2.9.1
+ transitivePeerDependencies:
+ - react-native-b4a
+
+ dependencies:
+ bare-path: 3.0.1
+
@@ -23282,6 +23432,12 @@ snapshots:
+ dependencies:
+ bare-events: 2.9.1
+ transitivePeerDependencies:
+ - bare-abort-controller
+
@@ -23390,6 +23546,8 @@ snapshots:
+
dependencies:
'@nodelib/fs.stat': 2.0.5
@@ -27267,6 +27425,15 @@ snapshots:
dependencies:
duplexer: 0.1.2
+ dependencies:
+ events-universal: 1.0.1
+ fast-fifo: 1.3.2
+ text-decoder: 1.2.7
+ transitivePeerDependencies:
+ - bare-abort-controller
+ - react-native-b4a
+
@@ -27481,6 +27648,17 @@ snapshots:
+ dependencies:
+ b4a: 1.8.1
+ bare-fs: 4.7.2
+ fast-fifo: 1.3.2
+ streamx: 2.28.0
+ transitivePeerDependencies:
+ - bare-abort-controller
+ - bare-buffer
+ - react-native-b4a
+
dependencies:
'@isaacs/fs-minipass': 4.0.1
@@ -27489,12 +27667,25 @@ snapshots:
minizlib: 3.1.0
yallist: 5.0.0
+ dependencies:
+ streamx: 2.28.0
+ transitivePeerDependencies:
+ - bare-abort-controller
+ - react-native-b4a
+
dependencies:
temporal-spec: 0.2.4
+ dependencies:
+ b4a: 1.8.1
+ transitivePeerDependencies:
+ - react-native-b4a
+
dependencies:
thenify: 3.3.1
@@ -28149,6 +28340,34 @@ snapshots:
transitivePeerDependencies:
- msw
+ dependencies:
+ '@vitest/expect': 4.1.6
+ '@vitest/pretty-format': 4.1.6
+ '@vitest/runner': 4.1.6
+ '@vitest/snapshot': 4.1.6
+ '@vitest/spy': 4.1.6
+ '@vitest/utils': 4.1.6
+ es-module-lexer: 2.0.0
+ expect-type: 1.3.0
+ magic-string: 0.30.21
+ obug: 2.1.1
+ pathe: 2.0.3
+ picomatch: 4.0.4
+ std-env: 4.0.0
+ tinybench: 2.9.0
+ tinyexec: 1.1.1
+ tinyglobby: 0.2.16
+ tinyrainbow: 3.1.0
+ why-is-node-running: 2.3.0
+ optionalDependencies:
+ '@opentelemetry/api': 1.9.0
+ '@types/node': 24.12.2
+ transitivePeerDependencies:
+ - msw
+
dependencies:
'@vitest/expect': 4.1.6