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.

8.8 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.

import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { Json } from "@carbon/database";
import { toJson } from "@carbon/database/json";
import { storage } from "@carbon/files";
import type { AssemblyPlan } from "@carbon/viewer/steps";
import { NonRetriableError } from "inngest";
import { inngest } from "../../client";
import {
  ASSEMBLER_CONCURRENCY,
  assemblerEnabled,
  internalizeStorageUrl,
  requireModelSourceBucket,
  runAssemblerJob,
  signSourceUrl,
  signUploadUrls
} from "./assembler-client";
import { getModelUpload, insertPlanJob, updatePlanJobs } from "./model-rows";
import { loadPlanUnits } from "./plan-units";
import { updateAssemblyStepMotionsFromPlan } from "./update-step-motions";

const SIGNED_URL_EXPIRY = 60 * 60; // seconds — the source (read) URL only.
// How long a plan may run once the service starts it.
const MAX_PLAN_WAIT_MS = 40 * 60 * 1000;

/**
 * Runs the assembler service motion planner over a converted model: computes a
 * collision-free insertion motion per part plus an assembly sequence, stored as
 * plan.json next to the model artifacts. See
 * .ai/specs/2026-07-04-assembler-deployment.md (POST /v1/plan, callback).
 *
 * Event-driven like optimize/convert (`runAssemblerJob`): submit with
 * submit-time signed upload URLs + a callback URL, park on waitForEvent until
 * the service's completion callback fires, one late-mint fallback poll on
 * timeout. The service PUTs plan.json to the upload URL itself and reports a
 * { planPath } pointer; this run just flips the job row.
 */
export const assemblyPlanFunction = inngest.createFunction(
  {
    id: "assembly-plan",
    retries: 2,
    concurrency: ASSEMBLER_CONCURRENCY,
    onFailure: async ({ event }) => {
      const { modelUploadId, companyId } = event.data.event.data;
      // Queued included: a pre-created row (planJobId) stays Queued when the
      // function fails before its "queue" step promotes it to Processing.
      await updatePlanJobs(
        companyId,
        { modelUploadId, kind: "plan", statuses: ["Queued", "Processing"] },
        { status: "Failed", error: event.data.error.message }
      );
    }
  },
  { event: "carbon/assembly-plan" },
  async ({ event, step, logger }) => {
    const {
      modelUploadId,
      companyId,
      userId,
      reMotionFor,
      planJobId,
      reDetectUnits
    } = event.data;

    // Feature-gated. Plan is an explicit user action ("Generate Steps"), so a
    // pre-created Queued row is failed with a clear reason instead of hanging.
    if (!assemblerEnabled()) {
      if (planJobId) {
        await step.run("mark-unconfigured", () =>
          updatePlanJobs(
            companyId,
            { id: planJobId },
            { status: "Failed", error: "Assembler service is not configured" }
          )
        );
      }
      logger.info("assembly plan skipped — assembler is not configured", {
        modelUploadId
      });
      return { jobId: planJobId ?? null, status: "Skipped" as const };
    }

    const job = await step.run("queue", async () => {
      const modelUpload = await getModelUpload(companyId, modelUploadId);
      if (!modelUpload?.modelPath) {
        throw new NonRetriableError(
          `Model upload ${modelUploadId} not found or has no file`
        );
      }
      const found = {
        modelPath: modelUpload.modelPath,
        graphPath: modelUpload.graphPath
      };

      // Adopt the trigger's pre-created row when given (created Queued so the
      // UI shows "planning" from the moment of the click); fall back to
      // inserting a row when adoption fails.
      if (planJobId) {
        const adopted = await updatePlanJobs(
          companyId,
          { id: planJobId },
          { status: "Processing" }
        );
        if (adopted > 0) return { id: planJobId, ...found };
      }

      const id = await insertPlanJob({
        companyId,
        modelUploadId,
        kind: "plan",
        createdBy: userId
      });
      return { id, ...found };
    });

    // Where plan.json lands. The service PUTs it here itself (offload) via the
    // submit-time signed upload URL; this run just records the pointer the
    // service reports back.
    const planPath = `${companyId}/models/${modelUploadId}/${job.id}/plan.json`;

    // Re-motion mode (order-preserving): take the existing step order as the
    // fixed assembly sequence and let the planner only recompute each step's
    // motion (forward-collision against earlier steps). Otherwise plan fresh:
    // send the user-authored "plan as one component" overrides as units — the
    // planner auto-detects PCB detail swarms from geometry on its own.
    const sequence = reMotionFor
      ? await step.run("derive-sequence", async () => {
          const client = getCarbonServiceRole();
          const steps = await client
            .from("assemblyInstructionStep")
            .select("componentNodeIds")
            .eq("assemblyInstructionId", reMotionFor)
            .eq("companyId", companyId)
            .order("sortOrder", { ascending: true });
          // Every step's parts (Done included — they're obstacles) in order.
          return (steps.data ?? [])
            .map((row) => row.componentNodeIds ?? [])
            .filter((group) => group.length > 0);
        })
      : null;
    const units =
      sequence != null
        ? []
        : await step.run("load-authored-units", () =>
            loadPlanUnits({
              modelUploadId,
              companyId,
              excludeAuto: reDetectUnits
            })
          );

    // Submit with submit-time upload URLs + callback, then park on the
    // completion event (one late-mint fallback poll on timeout). A failure or
    // cancel throws — retries then onFailure flip the job row to Failed.
    const plan = await runAssemblerJob(step, {
      idPrefix: "plan",
      action: "plan",
      jobId: job.id,
      maxWaitMs: MAX_PLAN_WAIT_MS,
      logger,
      buildBody: async () => {
        const client = getCarbonServiceRole();
        const sourceBucket = await requireModelSourceBucket(
          companyId,
          job.modelPath
        );
        const signedUrl = await signSourceUrl(
          client,
          sourceBucket,
          job.modelPath,
          SIGNED_URL_EXPIRY
        );
        return {
          source: {
            url: internalizeStorageUrl(signedUrl),
            format: "step"
          },
          // The service reads planPath (completion pointer) and modelUploadId
          // (to scope its content-hash result cache) out of meta.
          meta: {
            companyId,
            userId,
            modelUploadId,
            reMotionFor: reMotionFor ?? null,
            graphPath: job.graphPath ?? null,
            planPath
          },
          ...(sequence != null
            ? { options: { sequence } }
            : units.length > 0
              ? { options: { units } }
              : {})
        };
      },
      mintUploadUrls: () =>
        signUploadUrls({
          plan: {
            bucket: storage(getCarbonServiceRole()).company(companyId),
            path: planPath
          }
        })
    });

    const donePlanPath =
      (plan.result as { planPath?: string } | null)?.planPath ?? planPath;
    const stats: Json = plan.stats;

    // Persist: flip the row to the pointer the service reported. Guarded by
    // status=Processing so a cancel/racing-retry no-ops.
    await step.run("persist-plan", async () => {
      await updatePlanJobs(
        companyId,
        { id: job.id, statuses: ["Processing"] },
        { status: "Success", planPath: donePlanPath, stats: toJson(stats) }
      );
    });

    // Re-motion: preserve step order, refresh each step's motion from the new
    // plan (Done steps kept, titles/typed fields untouched).
    if (reMotionFor) {
      await step.run("update-step-motions", async () => {
        const client = getCarbonServiceRole();
        const download = await storage(client)
          .company(companyId)
          .download(donePlanPath);
        if (!download.data) {
          throw new Error(
            `Failed to download plan.json for re-motion: ${download.error.message}`
          );
        }
        const plan = JSON.parse(await download.data.text()) as AssemblyPlan;
        await updateAssemblyStepMotionsFromPlan(client, {
          assemblyInstructionId: reMotionFor,
          plan,
          graphPath: job.graphPath ?? null,
          companyId,
          userId
        });
      });
    }

    logger.info("plan finalized", {
      jobId: job.id,
      reMotion: Boolean(reMotionFor)
    });
    return { jobId: job.id, status: "Success" as const };
  }
);