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: NDJSON v1 company backups + onboarding data-step gating

Sidwebworksd01f0357a5a6
diff --git a/apps/erp/app/modules/settings/backups.service.ts b/apps/erp/app/modules/settings/backups.service.ts
index 4dbf0e81b1..a52aea204d 100644
--- a/apps/erp/app/modules/settings/backups.service.ts
+++ b/apps/erp/app/modules/settings/backups.service.ts
@@ -6,6 +6,45 @@ 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`;
+}
+
+/**
+ * Remove every object under a prefix (recursing into folders) so a deleted
+ * backup actually releases its bucket space rather than orphaning files.
+ */
+async function removeStoragePrefix(
+ client: SupabaseClient<Database>,
+ bucket: string,
+ prefix: string
+) {
+ const { data } = await client.storage
+ .from(bucket)
+ .list(prefix, { limit: 1000 });
+ if (!data) return;
+ const files: string[] = [];
+ for (const entry of data) {
+ const path = `${prefix}/${entry.name}`;
+ if (entry.id === null) {
+ await removeStoragePrefix(client, bucket, path);
+ } else {
+ files.push(path);
+ }
+ }
+ if (files.length > 0) {
+ await client.storage.from(bucket).remove(files);
+ }
+}
+
export async function exportCompanyBackup(
client: SupabaseClient<Database>,
args: {
@@ -41,6 +80,9 @@ export async function deleteCompanyBackupExport(
companyId: string,
filePath: 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]);
}
diff --git a/apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx b/apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx
index 87bc41b8ce..4828864959 100644
--- a/apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx
+++ b/apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx
@@ -88,15 +88,18 @@ function StepChecklist({
}
// Stepped progress for export / restore / revert. Restore & revert track the real
-// job via the status poll; export has no signal, so its steps simulate then
-// settle and refresh the list. Shows working → success | failed.
+// job via the status poll; export polls the backup list (via `completed`, set by
+// the parent once the new backup actually appears). Shows working → success | failed.
export function JobProgressModal({
mode,
runId,
+ completed,
onClose
}: {
mode: "export" | "restore" | "revert";
runId?: string;
+ /** Export only: true once the new backup has actually landed in the list. */
+ completed?: boolean;
onClose: () => void;
}) {
const isExport = mode === "export";
@@ -115,8 +118,7 @@ export function JobProgressModal({
const revertDone = isRevert && raw === "gone";
const [step, setStep] = useState(0);
- const [simDone, setSimDone] = useState(false);
- const success = restoreReady || revertDone || (isExport && simDone);
+ const success = restoreReady || revertDone || (isExport && !!completed);
const done = success || failed;
const rows = statusFetcher.data?.rows ?? 0;
@@ -150,6 +152,18 @@ export function JobProgressModal({
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.
+ useEffect(() => {
+ if (!isExport || done) return;
+ const id = setInterval(() => {
+ revalidator.revalidate();
+ setTicks((t) => t + 1);
+ }, 2000);
+ return () => clearInterval(id);
+ }, [isExport, done, revalidator]);
+
// Advance the visible steps on a cadence while the job runs.
useEffect(() => {
if (done) {
@@ -163,17 +177,6 @@ export function JobProgressModal({
return () => clearInterval(id);
}, [done, steps.length]);
- // Export has no completion signal — once the steps have played, settle and
- // refresh so the new backup shows in the list.
- useEffect(() => {
- if (!isExport || done || step < steps.length - 1) return;
- const t = setTimeout(() => {
- setSimDone(true);
- revalidator.revalidate();
- }, 900);
- return () => clearTimeout(t);
- }, [isExport, done, step, steps.length, revalidator]);
-
const workingTitle = isExport
? "Creating backup…"
: isRevert
diff --git a/apps/erp/app/routes/onboarding+/_layout.tsx b/apps/erp/app/routes/onboarding+/_layout.tsx
index 4a84c79dab..1332b10eb0 100644
--- a/apps/erp/app/routes/onboarding+/_layout.tsx
+++ b/apps/erp/app/routes/onboarding+/_layout.tsx
@@ -2,7 +2,7 @@ import { CarbonEdition } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { TooltipProvider, useMode } from "@carbon/react";
import { getStripeCustomerByCompanyId } from "@carbon/stripe/stripe.server";
-import { Edition } from "@carbon/utils";
+import { Edition, isInternalEmail } from "@carbon/utils";
import { MeshGradient } from "@paper-design/shaders-react";
import { useEffect, useState } from "react";
import type {
@@ -18,7 +18,11 @@ import { onboardingSequence, path } from "~/utils/path";
export const shouldRevalidate: ShouldRevalidateFunction = () => true;
export async function loader({ request }: LoaderFunctionArgs) {
- const { client, companyId, userId } = await requirePermissions(request, {});
+ const { client, companyId, userId, email } = await requirePermissions(
+ request,
+ {}
+ );
+ const isInternal = isInternalEmail(email);
const [company, stripeCustomer, locations] = await Promise.all([
getCompany(client, companyId),
@@ -41,10 +45,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
}
- const onboardingSteps =
- CarbonEdition === Edition.Cloud
- ? onboardingSequence
- : onboardingSequence.filter((p) => p !== path.to.onboarding.plan);
+ // The data-choice step (demo template / backup import) is internal-only; the
+ // plan step is Cloud-only. Everyone else creates their company in the company
+ // step directly.
+ const onboardingSteps = onboardingSequence.filter((p) => {
+ if (p === path.to.onboarding.plan) return CarbonEdition === Edition.Cloud;
+ if (p === path.to.onboarding.industry) return isInternal;
+ return true;
+ });
const pathIndex = onboardingSteps.findIndex((p) => p === pathname);
diff --git a/apps/erp/app/routes/onboarding+/company.tsx b/apps/erp/app/routes/onboarding+/company.tsx
index 164f2d5ce4..a3a920309b 100644
--- a/apps/erp/app/routes/onboarding+/company.tsx
+++ b/apps/erp/app/routes/onboarding+/company.tsx
@@ -1,5 +1,8 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { setCompanyId } from "@carbon/auth/company.server";
+import { updateCompanySession } from "@carbon/auth/session.server";
import { ValidatedForm, validationError, validator } from "@carbon/form";
import {
Button,
@@ -11,6 +14,7 @@ import {
HStack,
VStack
} from "@carbon/react";
+import { isInternalEmail } from "@carbon/utils";
import {
type ActionFunctionArgs,
Link,
@@ -26,6 +30,7 @@ import {
} from "~/components/Form";
import { useOnboarding } from "~/hooks";
import { addressValidator, getCompany } from "~/modules/settings";
+import { provisionOnboardingCompany } from "~/services/onboarding.server";
import {
getOnboardingDraft,
setOnboardingDraft
@@ -49,7 +54,7 @@ export async function loader({ request }: ActionFunctionArgs) {
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- await requirePermissions(request, {});
+ const { client, userId, email } = await requirePermissions(request, {});
const formData = await request.formData();
@@ -61,13 +66,43 @@ export async function action({ request }: ActionFunctionArgs) {
const { next, ...companyData } = validation.data;
- // Store company data in session draft for the next step (industry)
- const draftCookie = await setOnboardingDraft(request, {
- company: companyData
+ // Internal users get a dedicated data-choice step (demo template / backup
+ // import) that creates the company; stash this step's input for it.
+ if (isInternalEmail(email)) {
+ const draftCookie = await setOnboardingDraft(request, {
+ company: companyData
+ });
+
+ throw redirect(next, {
+ headers: [["Set-Cookie", draftCookie]]
+ });
+ }
+
+ // Public signups skip the data-choice step and create a clean company here.
+ const serviceRole = getCarbonServiceRole();
+ const companyId = await provisionOnboardingCompany(serviceRole, client, {
+ userId,
+ companyData,
+ backup: null
});
+ const companyRecord = await serviceRole
+ .from("company")
+ .select("companyGroupId")
+ .eq("id", companyId)
+ .single();
+ const sessionCookie = await updateCompanySession(
+ request,
+ companyId,
+ companyRecord.data?.companyGroupId ?? ""
+ );
+ const companyIdCookie = setCompanyId(companyId);
+
throw redirect(next, {
- headers: [["Set-Cookie", draftCookie]]
+ headers: [
+ ["Set-Cookie", sessionCookie],
+ ["Set-Cookie", companyIdCookie]
+ ]
});
}
diff --git a/apps/erp/app/routes/onboarding+/industry.tsx b/apps/erp/app/routes/onboarding+/industry.tsx
index e8d4994844..178e797535 100644
--- a/apps/erp/app/routes/onboarding+/industry.tsx
+++ b/apps/erp/app/routes/onboarding+/industry.tsx
@@ -1,10 +1,9 @@
-import { assertIsPost, CarbonEdition } from "@carbon/auth";
+import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { setCompanyId } from "@carbon/auth/company.server";
import { updateCompanySession } from "@carbon/auth/session.server";
import { ValidatedForm, validationError, validator } from "@carbon/form";
-import { trigger } from "@carbon/jobs";
import {
Button,
Card,
@@ -18,8 +17,7 @@ import {
cn,
HStack
} from "@carbon/react";
-import { Edition } from "@carbon/utils";
-import { getLocalTimeZone } from "@internationalized/date";
+import { isInternalEmail } from "@carbon/utils";
import { type ReactNode, useState } from "react";
import {
LuBot,
@@ -40,25 +38,21 @@ import {
import { z } from "zod";
import { Hidden, Submit } from "~/components/Form";
import { useOnboarding } from "~/hooks";
-import { insertEmployeeJob } from "~/modules/people";
-import { getLocationsList, upsertLocation } from "~/modules/resources";
import {
- getCompanies,
getCompany,
getIndustries,
- insertCompany,
- onboardingCompanyValidator,
- updateCompany
+ onboardingCompanyValidator
} from "~/modules/settings";
import {
fetchTemplateBackup,
- provisionCompanyData
+ provisionOnboardingCompany
} from "~/services/onboarding.server";
import {
clearOnboardingDraft,
getOnboardingDraft,
type OnboardingDraft
} from "~/services/onboarding-draft.server";
+import { path } from "~/utils/path";
type DataChoice = "template" | "import" | "none";
@@ -93,7 +87,13 @@ function appendDraftCompany(
}
export async function loader({ request }: ActionFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {});
+ const { client, companyId, email } = await requirePermissions(request, {});
+
+ // The data-choice step is internal-only; public signups create their company
+ // in the company step. Guard direct navigation to this route.
+ if (!isInternalEmail(email)) {
+ throw redirect(path.to.onboarding.company);
+ }
const company = await getCompany(client, companyId);
const draft = await getOnboardingDraft(request);
@@ -108,7 +108,12 @@ export async function loader({ request }: ActionFunctionArgs) {
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {});
+ const { client, userId, email } = await requirePermissions(request, {});
+
+ // Internal-only step — reject direct POSTs from public signups.
+ if (!isInternalEmail(email)) {
+ throw redirect(path.to.onboarding.company);
+ }
// Get draft data from previous step (company)
const draft = await getOnboardingDraft(request);
@@ -144,136 +149,35 @@ export async function action({ request }: ActionFunctionArgs) {
industryId: d.industryId || null
};
- let companyId: string | undefined;
-
- const companies = await getCompanies(client, userId);
- const company = companies?.data?.[0];
-
- const locations = await getLocationsList(client, company?.id ?? "");
- const location = locations?.data?.[0];
-
- // Extract address data for location
- const addressData = {
- addressLine1: d.addressLine1,
- addressLine2: d.addressLine2,
- city: d.city,
- stateProvince: d.stateProvince,
- postalCode: d.postalCode,
- countryCode: d.countryCode
- };
-
- if (company && location) {
- // Update existing company and location
- const [companyUpdate, locationUpdate] = await Promise.all([
- updateCompany(serviceRole, company.id!, {
- ...companyData,
- updatedBy: userId
- }),
- upsertLocation(serviceRole, {
- ...location,
- ...addressData,
- timezone: getLocalTimeZone(),
- updatedBy: userId
- })
- ]);
- if (companyUpdate.error) {
- console.error(companyUpdate.error);
- throw new Error("Fatal: failed to update company");
- }
- if (locationUpdate.error) {
- console.error(locationUpdate.error);
- throw new Error("Fatal: failed to update location");
- }
-
- companyId = company.id!;
- } else {
- // Create new company.
- const companyInsert = await insertCompany(serviceRole, companyData);
- if (companyInsert.error) {
- console.error(companyInsert.error);
- throw new Error("Fatal: failed to insert company");
- }
- companyId = companyInsert.data?.id;
- if (!companyId) {
- throw new Error("Fatal: failed to get company ID");
- }
-
- // A demo template and "restore from a backup" both resolve to a backup
- // file; "none" → a clean seed. provisionCompanyData imports it or seeds.
- const backupFile = formData.get("backup");
- const backup: Blob | null =
- dataChoice === "import" &&
- backupFile instanceof File &&
- backupFile.size > 0
- ? backupFile
- : dataChoice === "template"
- ? await fetchTemplateBackup(serviceRole, finalIndustryId)
- : null;
-
- await provisionCompanyData(serviceRole, {
- companyId,
- userId,
- backup,
- // Only a demo template references shared assets; a user's own uploaded
- // backup ("import") stays self-contained and is copied per company.
- templateIndustryId: dataChoice === "template" ? finalIndustryId : null
- });
-
- if (CarbonEdition === Edition.Cloud) {
- trigger("onboard", {
- type: "lead",
- companyId,
- userId
- });
- }
-
- // Create location
- const [locationInsert] = await Promise.all([
- upsertLocation(serviceRole, {
- ...addressData,
- name: "Headquarters",
- companyId,
- timezone: getLocalTimeZone(),
- createdBy: userId
- })
- ]);
-
- if (locationInsert.error) {
- console.error(locationInsert.error);
- throw new Error("Fatal: failed to insert location");
- }
-
- const locationId = locationInsert.data?.id;
- if (!locationId) {
- throw new Error("Fatal: failed to get location ID");
- }
-
- // Create employee job
- const [job] = await Promise.all([
- insertEmployeeJob(serviceRole, {
- id: userId,
- companyId,
- locationId
- })
- ]);
-
- if (job.error) {
- console.error(job.error);
- throw new Error("Fatal: failed to insert job");
- }
- }
+ // A demo template and "restore from a backup" both resolve to a backup file;
+ // "none" → a clean seed. Only a template references shared assets; a user's
+ // own uploaded backup ("import") stays self-contained and is copied per company.
+ const backupFile = formData.get("backup");
+ const backup: Blob | null =
+ dataChoice === "import" && backupFile instanceof File && backupFile.size > 0
+ ? backupFile
+ : dataChoice === "template"
+ ? await fetchTemplateBackup(serviceRole, finalIndustryId)
+ : null;
+
+ const companyId = await provisionOnboardingCompany(serviceRole, client, {
+ userId,
+ companyData,
+ backup,
+ templateIndustryId: dataChoice === "template" ? finalIndustryId : null
+ });
const companyRecord = await serviceRole
.from("company")
.select("companyGroupId")
- .eq("id", companyId!)
+ .eq("id", companyId)
.single();
const sessionCookie = await updateCompanySession(
request,
- companyId!,
+ companyId,
companyRecord.data?.companyGroupId ?? ""
);
- const companyIdCookie = setCompanyId(companyId!);
+ const companyIdCookie = setCompanyId(companyId);
const clearDraftCookie = await clearOnboardingDraft(request);
throw redirect(next, {
diff --git a/apps/erp/app/routes/x+/settings+/backups.tsx b/apps/erp/app/routes/x+/settings+/backups.tsx
index b1cf8e9591..04341b1ff9 100644
--- a/apps/erp/app/routes/x+/settings+/backups.tsx
+++ b/apps/erp/app/routes/x+/settings+/backups.tsx
@@ -26,7 +26,7 @@ import {
} from "@carbon/react";
import { convertKbToString, isInternalEmail } from "@carbon/utils";
import { msg } from "@lingui/core/macro";
-import { useEffect, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, Form, redirect, useFetcher, useLoaderData } from "react-router";
import { z } from "zod";
@@ -272,7 +272,17 @@ export default function BackupsRoute() {
const [active, setActive] = useState<{
runId?: string;
mode: "export" | "restore" | "revert";
+ /** Export only: the backup paths present when the export started. The run is
+ * done once a path outside this set appears in the (revalidated) list. */
+ exportBaseline?: Set<string>;
} | null>(null);
+ // Latest list, read without re-triggering the fetcher effect when it changes.
+ const filesRef = useRef(files);
+ filesRef.current = files;
+ const exportCompleted =
+ active?.mode === "export" &&
+ !!active.exportBaseline &&
+ files.some((f) => !active.exportBaseline!.has(f.path));
const startRevert = (runId: string) => {
fetcher.submit(
{ intent: "revert", restoreRunId: runId },
@@ -287,7 +297,10 @@ export default function BackupsRoute() {
// Export and restore open a progress modal — let it own the feedback instead
// of also firing a toast. Everything else (keep/revert/dismiss/errors) toasts.
if (result.success && result.started === "export") {
- setActive({ mode: "export" });
+ setActive({
+ mode: "export",
+ exportBaseline: new Set(filesRef.current.map((f) => f.path))
+ });
return;
}
if (result.success && result.restoreRunId) {
@@ -413,6 +426,7 @@ export default function BackupsRoute() {
<JobProgressModal
mode={active.mode}
runId={active.runId}
+ completed={exportCompleted}
onClose={() => setActive(null)}
/>
)}
diff --git a/apps/erp/app/services/onboarding.server.ts b/apps/erp/app/services/onboarding.server.ts
index a47ac3b201..322080631a 100644
--- a/apps/erp/app/services/onboarding.server.ts
+++ b/apps/erp/app/services/onboarding.server.ts
@@ -1,7 +1,21 @@
+import { CarbonEdition } from "@carbon/auth";
import type { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { Database } from "@carbon/database";
import { trigger } from "@carbon/jobs";
+import { Edition } from "@carbon/utils";
+import { getLocalTimeZone } from "@internationalized/date";
+import type { SupabaseClient } from "@supabase/supabase-js";
import { nanoid } from "nanoid";
-import { seedCompany } from "~/modules/settings";
+import type { z } from "zod";
+import { insertEmployeeJob } from "~/modules/people";
+import { getLocationsList, upsertLocation } from "~/modules/resources";
+import {
+ type companyValidator,
+ getCompanies,
+ insertCompany,
+ seedCompany,
+ updateCompany
+} from "~/modules/settings";
type ServiceRole = ReturnType<typeof getCarbonServiceRole>;
@@ -103,3 +117,121 @@ export async function provisionCompanyData(
throw new Error("Fatal: failed to start company data import");
}
}
+
+/**
+ * Insert-or-update the onboarding company, provision its data, and create the
+ * headquarters location plus the owner's employee job. Returns the companyId.
+ * Shared by the public company step (clean seed, `backup: null`) and the
+ * internal data-choice step (demo template / backup import).
+ */
+export async function provisionOnboardingCompany(
+ serviceRole: ServiceRole,
+ client: SupabaseClient<Database>,
+ {
+ userId,
+ companyData,
+ backup,
+ templateIndustryId
+ }: {
+ userId: string;
+ companyData: z.infer<typeof companyValidator> & {
+ industryId?: string | null;
+ customIndustryDescription?: string | null;
+ };
+ backup: Blob | null;
+ templateIndustryId?: string | null;
+ }
+): Promise<string> {
+ const companies = await getCompanies(client, userId);
+ const company = companies?.data?.[0];
+
+ const locations = await getLocationsList(client, company?.id ?? "");
+ const location = locations?.data?.[0];
+
+ const addressData = {
+ addressLine1: companyData.addressLine1,
+ addressLine2: companyData.addressLine2,
+ city: companyData.city,
+ stateProvince: companyData.stateProvince,
+ postalCode: companyData.postalCode,
+ countryCode: companyData.countryCode
+ };
+
+ // Re-entry: a company + location already exist — just update them. No reseed.
+ if (company && location) {
+ const [companyUpdate, locationUpdate] = await Promise.all([
+ updateCompany(serviceRole, company.id!, {
+ ...companyData,
+ updatedBy: userId
+ }),
+ upsertLocation(serviceRole, {
+ ...location,
+ ...addressData,
+ timezone: getLocalTimeZone(),
+ updatedBy: userId
+ })
+ ]);
+ if (companyUpdate.error) {
+ console.error(companyUpdate.error);
+ throw new Error("Fatal: failed to update company");
+ }
+ if (locationUpdate.error) {
+ console.error(locationUpdate.error);
+ throw new Error("Fatal: failed to update location");
+ }
+ return company.id!;
+ }
+
+ const companyInsert = await insertCompany(serviceRole, companyData);
+ if (companyInsert.error) {
+ console.error(companyInsert.error);
+ throw new Error("Fatal: failed to insert company");
+ }
+ const companyId = companyInsert.data?.id;
+ if (!companyId) {
+ throw new Error("Fatal: failed to get company ID");
+ }
+
+ await provisionCompanyData(serviceRole, {
+ companyId,
+ userId,
+ backup,
+ templateIndustryId
+ });
+
+ if (CarbonEdition === Edition.Cloud) {
+ trigger("onboard", {
+ type: "lead",
+ companyId,
+ userId
+ });
+ }
+
+ const locationInsert = await upsertLocation(serviceRole, {
+ ...addressData,
+ name: "Headquarters",
+ companyId,
+ timezone: getLocalTimeZone(),
+ createdBy: userId
+ });
+ if (locationInsert.error) {
+ console.error(locationInsert.error);
+ throw new Error("Fatal: failed to insert location");
+ }
+ const locationId = locationInsert.data?.id;
+ if (!locationId) {
+ throw new Error("Fatal: failed to get location ID");
+ }
+
+ const job = await insertEmployeeJob(serviceRole, {
+ id: userId,
+ companyId,
+ locationId
+ });
+ if (job.error) {
+ console.error(job.error);
+ throw new Error("Fatal: failed to insert job");
+ }
+
+ return companyId;
+}
diff --git a/ci/src/upload-backup-templates.ts b/ci/src/upload-backup-templates.ts
index f46b0f23a0..44e30fa876 100644
--- a/ci/src/upload-backup-templates.ts
+++ b/ci/src/upload-backup-templates.ts
@@ -1,5 +1,5 @@
import { readdir, readFile } from "node:fs/promises";
-import { dirname, join } from "node:path";
+import { dirname, join, relative, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { gunzipSync } from "node:zlib";
import { createClient } from "@supabase/supabase-js";
@@ -11,6 +11,10 @@ dotenv.config();
const TEMPLATE_BUCKET = "company-templates";
const BACKUP_SUFFIX = ".carbon.json.gz";
+// A backup's storage files live in a sibling `<industryId>.assets/` folder
+// (generation 2: assets are no longer base64-embedded in the gz). Must match
+// `BACKUP_GZ_SUFFIX` / `backupAssetPrefix` in @carbon/jobs company-backup.ts.
+const ASSETS_SUFFIX = ".assets";
// The bucket the app serves per-company assets (3D models, …) from, and the
// shared prefix within it where each template's assets live ONCE per workspace.
@@ -95,43 +99,64 @@ async function loadTemplates(): Promise<Template[]> {
fileName,
industryId,
bytes,
- assets: extractTemplateAssets(industryId, bytes)
+ assets: await extractTemplateAssets(industryId, bytes)
};
})
);
}
-// A template gz embeds its storage assets keyed by the source company's path
-// (`{sourceCompanyId}/models/{id}.stl`). Pull them out and rekey to the shared
-// `_templates/{industryId}/…` location so a referenced import can point at them
-// without copying. Mirrors `rewriteToTemplateAssetPath` in @carbon/jobs.
-function extractTemplateAssets(
+/** Every file under a directory, recursing into subfolders (absolute paths). */
+async function walkFiles(dir: string): Promise<string[]> {
+ let entries: Awaited<ReturnType<typeof readdir>>;
+ try {
+ entries = await readdir(dir, { withFileTypes: true });
+ } catch {
+ return [];
+ }
+ const out: string[] = [];
+ for (const entry of entries) {
+ const full = join(dir, entry.name);
+ if (entry.isDirectory()) {
+ out.push(...(await walkFiles(full)));
+ } else {
+ out.push(full);
+ }
+ }
+ return out;
+}
+
+// A template's storage assets live in a committed `<industryId>.assets/` folder
+// next to the gz, mirroring the source path (`{sourceCompanyId}/models/{id}.stl`).
+// Rekey them to the shared `_templates/{industryId}/…` location so a referenced
+// import can point at them without copying. Mirrors `rewriteToTemplateAssetPath`
+// in @carbon/jobs. The gz itself carries only the manifest + data.
+async function extractTemplateAssets(
industryId: string,
gzBytes: Buffer
-): TemplateAsset[] {
- let backup: {
- manifest?: { sourceCompanyId?: string };
- storage?: Record<string, string>;
- };
+): Promise<TemplateAsset[]> {
+ let sourceCompanyId: string | undefined;
try {
- backup = JSON.parse(gunzipSync(gzBytes).toString());
+ const backup = JSON.parse(gunzipSync(gzBytes).toString()) as {
+ manifest?: { sourceCompanyId?: string };
+ };
+ sourceCompanyId = backup.manifest?.sourceCompanyId;
} catch (err) {
console.error(`🔴 ${industryId}: failed to read template gz`, err);
return [];
}
+ if (!sourceCompanyId) return [];
- const sourceCompanyId = backup.manifest?.sourceCompanyId;
- const storage = backup.storage;
- if (!sourceCompanyId || !storage) return [];
-
+ const assetsDir = join(BACKUPS_DIR, `${industryId}${ASSETS_SUFFIX}`);
const assets: TemplateAsset[] = [];
- for (const [path, base64] of Object.entries(storage)) {
- const rest = path.startsWith(`${sourceCompanyId}/`)
- ? path.slice(sourceCompanyId.length + 1)
- : path;
+ for (const file of await walkFiles(assetsDir)) {
+ // Path within the assets folder, e.g. `{sourceCompanyId}/models/x.stl`.
+ const rel = relative(assetsDir, file).split(sep).join("/");
+ const rest = rel.startsWith(`${sourceCompanyId}/`)
+ ? rel.slice(sourceCompanyId.length + 1)
+ : rel;
assets.push({
path: `${TEMPLATE_ASSET_PREFIX}/${industryId}/${rest}`,
- bytes: Buffer.from(base64, "base64")
+ bytes: await readFile(file)
});
}
return assets;
diff --git a/packages/database/supabase/backups/README.md b/packages/database/supabase/backups/README.md
index 74471da87e..7ccc84e3e9 100644
--- a/packages/database/supabase/backups/README.md
+++ b/packages/database/supabase/backups/README.md
@@ -1,16 +1,24 @@
# Onboarding demo templates
-Repo-committed company backups used as onboarding demo data. One file per
-industry, named `<industryId>.carbon.json.gz` (the `industryId` must match a row
-in the `industry` table — see the onboarding migration).
+Repo-committed company backups used as onboarding demo data. Each template is two
+things, named by `industryId` (which must match a row in the `industry` table —
+see the onboarding migration):
+
+- `<industryId>.carbon.json.gz` — the gz of `{ manifest, data }` (records only).
+- `<industryId>.assets/` — the template's storage files (3D models, thumbnails, …),
+ mirroring their source path (`{sourceCompanyId}/models/{id}.stl`). Omit the folder
+ if the template has no files.
+
+> Generation 2: storage assets are real files in the `.assets/` folder, NOT
+> base64-embedded in the gz (which kept the gz small and bounded export memory).
These are published into every workspace by `ci/src/upload-backup-templates.ts`
as a **manual** step — the `Publish backup templates` workflow
(`.github/workflows/publish-templates.yml`, `workflow_dispatch`) or
`pnpm --filter ci ci:upload-backup-templates` locally. It is **not** run on every
deploy (templates change rarely and are large). It uploads the `.gz` to each
-workspace's private `company-templates` bucket and fans the template's storage
-assets (3D models, …) into the shared `_templates/<industryId>/` prefix of the
+workspace's private `company-templates` bucket and fans the files from
+`<industryId>.assets/` into the shared `_templates/<industryId>/` prefix of the
`private` bucket. The publish is **idempotent** — anything that already exists is
skipped; pass `--force` (workflow input `force: true`) to overwrite an updated
template.
@@ -25,9 +33,12 @@ exists for the chosen industry, onboarding falls back to a clean seed.
## Authoring / refreshing a template
1. Populate a company with the data you want as the demo set.
-2. Settings → Backups → Export (choose storage inclusion), then download the
- resulting `.gz`.
-3. Commit it here as `<industryId>.carbon.json.gz`, overwriting the old one.
+2. Settings → Backups → Export (include files), which writes
+ `exports/<name>.carbon.json.gz` plus an `exports/<name>.assets/` folder to the
+ company's bucket.
+3. Download both. Commit the gz here as `<industryId>.carbon.json.gz` and the
+ asset files as `<industryId>.assets/<sourceCompanyId>/…`, overwriting the old
+ template.
## Versioning / backwards compatibility
diff --git a/packages/database/supabase/backups/robotics_oem.carbon.json.gz b/packages/database/supabase/backups/robotics_oem.carbon.json.gz
deleted file mode 100644
index 71fecf422f..0000000000
Binary files a/packages/database/supabase/backups/robotics_oem.carbon.json.gz and /dev/null differ
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
index 8ee90dd96d..884dfbc53b 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
@@ -1,9 +1,13 @@
import { randomUUID } from "node:crypto";
+import { createInterface } from "node:readline";
+import { Readable } from "node:stream";
+import { createGunzip, createGzip } from "node:zlib";
import {
getPostgresClient,
getPostgresConnectionPool,
type KyselyDatabase
} from "@carbon/database/client";
+import type { SupabaseClient } from "@supabase/supabase-js";
import { type Kysely, PostgresDriver, sql } from "kysely";
import { nanoid } from "nanoid";
@@ -16,19 +20,41 @@ 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.
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 self-contained
- * backup must embed these — 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
@@ -214,10 +240,79 @@ export type Manifest = {
export type CompanyBackup = {
manifest: Manifest;
data: Record<string, Record<string, unknown>[]>;
- /** path within the company bucket -> base64 contents */
- storage?: Record<string, string>;
};
+/** One NDJSON line: either the single manifest line, or one table row. */
+type BackupLine =
+ | { manifest: Manifest }
+ | { t: string; r: Record<string, unknown> };
+
+/**
+ * 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.
+ */
+export async function serializeBackup(backup: CompanyBackup): Promise<Buffer> {
+ const gzip = createGzip();
+ const chunks: Buffer[] = [];
+ gzip.on("data", (c: Buffer) => chunks.push(c));
+ const finished = new Promise<void>((resolve, reject) => {
+ gzip.on("end", resolve);
+ gzip.on("error", reject);
+ });
+
+ const writeLine = (line: BackupLine) =>
+ new Promise<void>((resolve, reject) => {
+ gzip.write(`${JSON.stringify(line)}\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.
+ */
+export async function deserializeBackup(
+ bytes: ArrayBuffer
+): Promise<CompanyBackup> {
+ 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"] = {};
+ 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 (!manifest) {
+ throw new Error("Backup is missing its manifest line");
+ }
+ return { manifest, data };
+}
+
export function getJobDatabaseClient(size = 1) {
const pool = getPostgresConnectionPool(size);
return getPostgresClient(
@@ -643,3 +738,147 @@ export async function wipeScopedData(
`.execute(trx);
}
}
+
+/**
+ * Copy one storage object server-side, overwriting the destination if it already
+ * exists. `copy` has no upsert, so on a duplicate we remove the destination and
+ * retry — the bytes never pass through this process either way.
+ */
+async function copyStorageObject(
+ client: SupabaseClient,
+ args: {
+ srcBucket: string;
+ srcPath: string;
+ destBucket: string;
+ destPath: string;
+ }
+): Promise<{ ok: boolean; error?: string }> {
+ const { srcBucket, srcPath, destBucket, destPath } = args;
+ const run = () =>
+ client.storage
+ .from(srcBucket)
+ .copy(srcPath, destPath, { destinationBucket: destBucket });
+
+ let { error } = await run();
+ if (error && /exist|duplicate|409/i.test(error.message)) {
+ await client.storage.from(destBucket).remove([destPath]);
+ ({ error } = await run());
+ }
+ return { ok: !error, error: error?.message };
+}
+
+/**
+ * Copy a company's storage assets (shared `private` bucket, under `{companyId}/`)
+ * into a backup's own `.assets/` folder in the per-company bucket. Server-side —
+ * no bytes pass through this process, so a 200MB asset set costs no memory.
+ * Best-effort: a per-file failure warns and continues, matching the
+ * non-transactional storage semantics of restore/import.
+ */
+export async function copyAssetsToBackup(
+ client: SupabaseClient,
+ args: { sourcePaths: string[]; destBucket: string; destPrefix: string }
+): Promise<{ copied: number; failed: number }> {
+ const { sourcePaths, destBucket, destPrefix } = args;
+ let copied = 0;
+ let failed = 0;
+ for (const path of sourcePaths) {
+ const { ok, error } = await copyStorageObject(client, {
+ srcBucket: STORAGE_BUCKET,
+ srcPath: path,
+ destBucket,
+ destPath: `${destPrefix}/${path}`
+ });
+ if (ok) {
+ copied++;
+ } else {
+ failed++;
+ console.warn("Failed to copy backup asset", { path, error });
+ }
+ }
+ return { copied, failed };
+}
+
+/**
+ * Copy a backup's stored assets back into the shared `private` bucket for the
+ * target company, rewriting each path for a foreign/reseed restore (no-op for an
+ * own restore). Server-side, best-effort. Every write is guarded to the target
+ * company's own `{companyId}/` prefix so a malformed path can never land in
+ * another tenant's space.
+ */
+export async function restoreAssetsFromBackup(
+ client: SupabaseClient,
+ args: {
+ files: Array<{ path: string; included: boolean }>;
+ srcBucket: string;
+ srcPrefix: string;
+ sourceCompanyId: string;
+ companyId: string;
+ idRewrite: Map<string, string>;
+ }
+): Promise<{ copied: number; failed: number }> {
+ const { files, srcBucket, srcPrefix, sourceCompanyId, companyId, idRewrite } =
+ args;
+ let copied = 0;
+ let failed = 0;
+ for (const file of files) {
+ if (!file.included) continue;
+ const targetPath = rewriteStoragePath(
+ file.path,
+ sourceCompanyId,
+ companyId,
+ idRewrite
+ );
+ if (!targetPath.startsWith(`${companyId}/`)) {
+ console.warn("Skipping backup asset outside target company prefix", {
+ path: file.path,
+ targetPath
+ });
+ continue;
+ }
+ const { ok, error } = await copyStorageObject(client, {
+ srcBucket,
+ srcPath: `${srcPrefix}/${file.path}`,
+ destBucket: STORAGE_BUCKET,
+ destPath: targetPath
+ });
+ if (ok) {
+ copied++;
+ } else {
+ failed++;
+ console.warn("Failed to restore backup asset", {
+ path: file.path,
+ targetPath,
+ error
+ });
+ }
+ }
+ return { copied, failed };
+}
+
+/**
+ * Remove every object under a prefix in a bucket (e.g. a backup's `.assets/`
+ * folder), recursing into subfolders, so deleting a backup or snapshot leaves no
+ * orphaned files.
+ */
+export async function removeStoragePrefix(
+ client: SupabaseClient,
+ bucket: string,
+ prefix: string
+): Promise<void> {
+ const { data, error } = await client.storage
+ .from(bucket)
+ .list(prefix, { limit: 1000 });
+ if (error || !data) return;
+ const files: string[] = [];
+ for (const entry of data) {
+ const path = `${prefix}/${entry.name}`;
+ if (entry.id === null) {
+ await removeStoragePrefix(client, bucket, path);
+ } else {
+ files.push(path);
+ }
+ }
+ if (files.length > 0) {
+ await client.storage.from(bucket).remove(files);
+ }
+}
diff --git a/packages/jobs/src/inngest/functions/tasks/company-export.ts b/packages/jobs/src/inngest/functions/tasks/company-export.ts
index 9950e9475d..60d7c82cf4 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-export.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-export.ts
@@ -1,8 +1,3 @@
-import { promisify } from "node:util";
-import { gzip } from "node:zlib";
-
-const gzipAsync = promisify(gzip);
-
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { sql } from "kysely";
import { inngest } from "../../client";
@@ -11,17 +6,23 @@ import {
BACKUP_INTEGRATION,
BACKUP_KIND,
BACKUP_VERSION,
+ backupAssetPrefix,
+ copyAssetsToBackup,
EXPORTS_PREFIX,
encodeValue,
getCompanyTableCatalog,
getJobDatabaseClient,
SECRET_TABLES,
- STORAGE_BUCKET
+ STORAGE_BUCKET,
+ serializeBackup
} from "./company-backup";
-/** Per-file and total caps for embedded storage files (base64 inflates ~33%). */
-const MAX_STORAGE_FILE_BYTES = 25 * 1024 * 1024;
-const MAX_STORAGE_TOTAL_BYTES = 200 * 1024 * 1024;
+// 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;
type ServiceRole = ReturnType<typeof getCarbonServiceRole>;
type JobDatabase = ReturnType<typeof getJobDatabaseClient>;
@@ -39,7 +40,13 @@ export async function buildCompanyBackup(
label?: string | null;
includeStorage: "none" | "all";
}
-): Promise<{ compressed: Buffer; manifest: Manifest; rows: number }> {
+): Promise<{
+ compressed: Buffer;
+ manifest: Manifest;
+ rows: number;
+ /** `private`-bucket paths to copy into the backup's `.assets/` folder. */
+ assetSourcePaths: string[];
+}> {
const { companyId, userId, includeStorage } = opts;
const label = opts.label ?? null;
@@ -109,15 +116,16 @@ export async function buildCompanyBackup(
});
}
- // Optionally embed the company's storage assets so the backup is a
- // self-contained unit. These live in the shared `private` bucket under a
- // `{companyId}/` prefix (3D models, item thumbnails, attachments) — NOT in
- // the per-company bucket. Skip anything over the size caps.
+ // 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.
const storageManifest: Manifest["storage"] = [];
- let storageFiles: Record<string, string> | undefined;
+ const assetSourcePaths: string[] = [];
if (includeStorage === "all") {
- storageFiles = {};
let totalBytes = 0;
const paths = await listBucketFilesRecursive(
client,
@@ -126,28 +134,11 @@ export async function buildCompanyBackup(
);
for (const file of paths) {
- let included =
- file.size <= MAX_STORAGE_FILE_BYTES &&
- totalBytes + file.size <= MAX_STORAGE_TOTAL_BYTES;
-
+ const included = totalBytes + file.size <= MAX_STORAGE_TOTAL_BYTES;
if (included) {
- const download = await client.storage
- .from(STORAGE_BUCKET)
- .download(file.path);
- if (download.error || !download.data) {
- console.error("Failed to download storage file", {
- path: file.path,
- error: download.error
- });
- included = false;
- } else {
- storageFiles[file.path] = Buffer.from(
- await download.data.arrayBuffer()
- ).toString("base64");
- totalBytes += file.size;
- }
+ assetSourcePaths.push(file.path);
+ totalBytes += file.size;
}
-
storageManifest.push({ path: file.path, size: file.size, included });
}
}
@@ -168,10 +159,10 @@ export async function buildCompanyBackup(
excludedTables
};
- const backup: CompanyBackup = { manifest, data, storage: storageFiles };
- const compressed = await gzipAsync(Buffer.from(JSON.stringify(backup)));
+ const backup: CompanyBackup = { manifest, data };
+ const compressed = await serializeBackup(backup);
const rows = tableManifest.reduce((sum, t) => sum + t.rows, 0);
- return { compressed, manifest, rows };
+ return { compressed, manifest, rows, assetSourcePaths };
}
export const companyExportFunction = inngest.createFunction(
@@ -188,11 +179,13 @@ export const companyExportFunction = inngest.createFunction(
const client = getCarbonServiceRole();
const db = getJobDatabaseClient(1);
- const { compressed, manifest, rows } = await buildCompanyBackup(
- client,
- db,
- { companyId, userId, label, includeStorage }
- );
+ const { compressed, manifest, rows, assetSourcePaths } =
+ await buildCompanyBackup(client, db, {
+ companyId,
+ userId,
+ label,
+ includeStorage
+ });
const timestamp = manifest.exportedAt.replace(/[:.]/g, "-");
const slug = label
@@ -211,12 +204,22 @@ export const companyExportFunction = inngest.createFunction(
});
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.
+ const assets = await copyAssetsToBackup(client, {
+ sourcePaths: assetSourcePaths,
+ destBucket: companyId,
+ destPrefix: backupAssetPrefix(path)
+ });
+
console.log("Company export complete", {
companyId,
path,
tables: manifest.tables.length,
rows,
- bytes: compressed.byteLength
+ bytes: compressed.byteLength,
+ assetsCopied: assets.copied,
+ assetsFailed: assets.failed
});
return { path, 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 64e002dfea..f1f3b262ff 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-import.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-import.ts
@@ -1,28 +1,25 @@
-import { promisify } from "node:util";
-import { gunzip } from "node:zlib";
-
-const gunzipAsync = promisify(gunzip);
-
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { chunkArray } from "@carbon/utils";
import { sql } from "kysely";
import { inngest } from "../../client";
-import type { ColumnInfo, CompanyBackup, TableInfo } from "./company-backup";
+import type { ColumnInfo, TableInfo } from "./company-backup";
import {
assertBackupImportable,
BACKUP_INTEGRATION,
BACKUP_KIND,
+ backupAssetPrefix,
bindValue,
canSetReplicationRole,
+ deserializeBackup,
filterUnpopulated,
getCompanyTableCatalog,
getJobDatabaseClient,
newIdForTable,
RESEED_SKIPPED_TABLES,
+ restoreAssetsFromBackup,
rewriteStoragePath,
rewriteToTemplateAssetPath,
SECRET_TABLES,
- STORAGE_BUCKET,
STORAGE_PATH_COLUMNS
} from "./company-backup";
@@ -86,11 +83,7 @@ export const companyImportFunction = inngest.createFunction(
);
}
- const backup = JSON.parse(
- (
- await gunzipAsync(Buffer.from(await download.data.arrayBuffer()))
- ).toString()
- ) as CompanyBackup;
+ const backup = await deserializeBackup(await download.data.arrayBuffer());
if (backup.manifest?.kind !== BACKUP_KIND) {
throw new Error("File is not a Carbon company backup");
@@ -449,39 +442,27 @@ export const companyImportFunction = inngest.createFunction(
);
}
- // Storage files travel outside the transaction — failures here leave
- // the imported rows intact and are surfaced as warnings. Restore into the
- // shared `private` bucket with the path rewritten for the target company
- // (and remapped ids on reseed), matching the path columns rewritten above.
+ // Storage files travel outside the transaction — failures here leave the
+ // imported rows intact and are surfaced as warnings. Copy them server-side
+ // from the artifact's `.assets/` folder into the shared `private` bucket,
+ // with the path rewritten for the target company (and remapped ids on
+ // reseed) to match the path columns rewritten above.
//
// A referenced template skips this entirely: its assets already live once
// per workspace at `_templates/<industryId>/` (the path columns above now
// point there), so copying them into `{companyId}/` would defeat the
- // purpose. The embedded bytes in the gz are ignored here — they exist for
- // the deploy step that seeds the shared prefix.
+ // purpose.
let storageUploaded = 0;
- if (backup.storage && !referencedTemplate) {
- for (const [path, base64] of Object.entries(backup.storage)) {
- const targetPath = rewriteStoragePath(
- path,
- sourceCompanyId,
- companyId,
- idRewrite
- );
- const upload = await client.storage
- .from(STORAGE_BUCKET)
- .upload(targetPath, Buffer.from(base64, "base64"), {
- upsert: true
- });
- if (upload.error) {
- console.warn("Failed to upload storage file", {
- path: targetPath,
- error: upload.error.message
- });
- } else {
- storageUploaded++;
- }
- }
+ if (!referencedTemplate) {
+ const assets = await restoreAssetsFromBackup(client, {
+ files: backup.manifest.storage,
+ srcBucket: companyId,
+ srcPrefix: backupAssetPrefix(filePath),
+ sourceCompanyId,
+ companyId,
+ idRewrite
+ });
+ storageUploaded = assets.copied;
}
// Onboarding-from-a-backup commits immediately — no human review — so
diff --git a/packages/jobs/src/inngest/functions/tasks/company-restore.ts b/packages/jobs/src/inngest/functions/tasks/company-restore.ts
index 57f1b1bf08..ddf7df8930 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-restore.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-restore.ts
@@ -1,8 +1,3 @@
-import { promisify } from "node:util";
-import { gunzip } from "node:zlib";
-
-const gunzipAsync = promisify(gunzip);
-
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { chunkArray } from "@carbon/utils";
import { sql } from "kysely";
@@ -17,14 +12,17 @@ import {
assertBackupImportable,
assertWipeSafe,
BACKUP_KIND,
+ backupAssetPrefix,
bindValue,
canSetReplicationRole,
+ deserializeBackup,
getCompanyTableCatalog,
getJobDatabaseClient,
newIdForTable,
RESTORE_INTEGRATION,
+ removeStoragePrefix,
+ restoreAssetsFromBackup,
rewriteStoragePath,
- STORAGE_BUCKET,
STORAGE_PATH_COLUMNS,
selectWipeableTables,
wipeScopedData
@@ -52,11 +50,7 @@ async function downloadBackup(
`Failed to download backup ${filePath}: ${download.error?.message}`
);
}
- const backup = JSON.parse(
- (
- await gunzipAsync(Buffer.from(await download.data.arrayBuffer()))
- ).toString()
- ) as CompanyBackup;
+ const backup = await deserializeBackup(await download.data.arrayBuffer());
if (backup.manifest?.kind !== BACKUP_KIND) {
throw new Error("File is not a Carbon company backup");
}
@@ -284,37 +278,6 @@ async function wipeAndLoad(
return { rows: inserted, idRewrite };
}
-/** Restore the backup's storage files into the shared private bucket. Same
- * company, so paths are unchanged. Outside the transaction — failures warn. */
-async function restoreStorage(
- client: ServiceRole,
- backup: CompanyBackup,
- ctx: { companyId: string; idRewrite: Map<string, string> }
-): Promise<void> {
- if (!backup.storage) return;
- const sourceCompanyId = backup.manifest.sourceCompanyId;
- for (const [path, base64] of Object.entries(backup.storage)) {
- // Own backup → path unchanged (same company, empty idRewrite). Foreign →
- // rewritten to this company's prefix with the remapped ids, matching the
- // path columns rewritten in wipeAndLoad.
- const targetPath = rewriteStoragePath(
- path,
- sourceCompanyId,
- ctx.companyId,
- ctx.idRewrite
- );
- const upload = await client.storage
- .from(STORAGE_BUCKET)
- .upload(targetPath, Buffer.from(base64, "base64"), { upsert: true });
- if (upload.error) {
- console.warn("Failed to restore storage file", {
- path: targetPath,
- error: upload.error.message
- });
- }
- }
-}
-
type RestoreStatus = "running" | "ready" | "failed" | "reverting";
type RestoreMeta = {
restoreRunId: string;
@@ -553,21 +516,22 @@ export const companyRestoreFunction = inngest.createFunction(
targetGroupId
});
- // 3. Terminal: mark ready as soon as the data is committed — BEFORE the
- // (best-effort, non-transactional) file restore, so a storage hiccup
- // can't flip a committed restore back to "failed".
- await writeRestoreMarker(client, {
- companyId,
- userId,
- restoreRunId,
- patch: { status: "ready", rows }
- });
-
- // Files are optional, and the data is already committed — never let a
- // file error fail the run. A revert restores files from the snapshot.
+ // 3. Files (best-effort, non-transactional) — copied BEFORE marking ready
+ // so the progress dialog only reports "complete" once the data AND the
+ // files are actually in place, never sooner. The data txn already
+ // committed above and the copy never throws (per-file warnings only),
+ // so a storage hiccup still can't flip a committed restore to "failed".
+ // A revert restores files from the snapshot.
if (includeStorage === "all") {
try {
- await restoreStorage(client, backup, { companyId, idRewrite });
+ await restoreAssetsFromBackup(client, {
+ files: backup.manifest.storage,
+ srcBucket: companyId,
+ srcPrefix: backupAssetPrefix(filePath),
+ sourceCompanyId: backup.manifest.sourceCompanyId,
+ companyId,
+ idRewrite
+ });
} catch (storageErr) {
console.warn("Restore: file restore failed (data is intact)", {
restoreRunId,
@@ -579,6 +543,14 @@ export const companyRestoreFunction = inngest.createFunction(
}
}
+ // 4. Terminal: data committed and files copied — the run is fully done.
+ await writeRestoreMarker(client, {
+ companyId,
+ userId,
+ restoreRunId,
+ patch: { status: "ready", rows }
+ });
+
console.log("Company restore complete — pending keep/revert", {
companyId,
restoreRunId,
@@ -630,6 +602,11 @@ export const companyRestoreFinalizeFunction = inngest.createFunction(
if (snapshotPath) {
await client.storage.from(companyId).remove([snapshotPath]);
+ await removeStoragePrefix(
+ client,
+ companyId,
+ backupAssetPrefix(snapshotPath)
+ );
}
await deleteRestoreMarker(client, companyId, restoreRunId);
@@ -692,9 +669,21 @@ export const companyRestoreRevertFunction = inngest.createFunction(
includeGroup: marker?.metadata.includeGroup ?? false,
targetGroupId
});
- await restoreStorage(client, snapshot, { companyId, idRewrite });
+ await restoreAssetsFromBackup(client, {
+ files: snapshot.manifest.storage,
+ srcBucket: companyId,
+ srcPrefix: backupAssetPrefix(snapshotPath),
+ sourceCompanyId: companyId,
+ companyId,
+ idRewrite
+ });
await client.storage.from(companyId).remove([snapshotPath]);
+ await removeStoragePrefix(
+ client,
+ companyId,
+ backupAssetPrefix(snapshotPath)
+ );
await deleteRestoreMarker(client, companyId, restoreRunId);
console.log("Company restore reverted", {