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.

13.1 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 { modelPathOptimizeFormat } from "@carbon/files/cad";
import { MODEL_RAW_KEEP_MAX_BYTES } from "@carbon/utils";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useRef, useState } from "react";
import { isRawRenderable } from "./raw/formats";

export type ModelArtifacts = {
  optimizedModelPath: string | null;
  /** When the optimised GLB last landed — the client cache-buster for its
   * stable, immutable-cached URL. */
  optimizedAt?: string | null;
  /** Whether the reoptimise SOURCE (the modelPath object) still exists in
   * storage — pruned/dangling rows can't be re-optimised, so hosts hide the
   * refresh affordance. Absent (older server) → treat as available. */
  sourceAvailable?: boolean;
  lodPath: string | null;
  glbPath: string | null;
  thumbnailPath: string | null;
  /** The model's `pmi.json` (PMI read from a STEP AP242 source by the
   *  optimise ingest), or null when the model has none. Absent (older
   *  server) → treat as null. */
  pmiPath?: string | null;
  /** Raw upload (non-`.zst`) for the viewer's WASM fallback tier, with its
   *  resolved bucket (temp-staging for current uploads, private for old rows). */
  rawPath: string | null;
  rawBucket: string;
  /** Whether the optimiser (assembler) is configured server-side. When false, the
   *  viewer hides the failed-retry affordance and never auto-fires an optimise. */
  optimizerAvailable?: boolean;
  optimizeStatus:
    | "Idle"
    | "Queued"
    | "Processing"
    | "Success"
    | "Failed"
    | null;
  /** As-uploaded raw bytes (originalSize; older rows fall back to size). */
  size: number | null;
  optimizedSize: number | null;
};

/**
 * modelUpload.id is the model's filename (`${company}/models/${id}.ext`), so the
 * id — and thus its artifact paths — is recoverable from `modelPath` alone.
 * Compaction repoints `modelPath` at the compacted artifact (STEP →
 * `${id}.xbf.zst`, mesh → `${id}.{ext}.zst`, with the original STEP retained
 * separately at `originalPath`); the `.zst` wrapper is peeled before the
 * source extension.
 */
export function modelIdFromPath(modelPath: string | null): string | null {
  if (!modelPath) return null;
  let base = modelPath.split("/").pop() ?? "";
  if (base.toLowerCase().endsWith(".zst")) base = base.slice(0, -4);
  return base.replace(/\.[^.]+$/, "") || null;
}

const POLL_MS = 3000;
// `Idle`/null is the brief window before a just-triggered job starts (or a
// non-mesh upload that never optimises) — poll it only for a short grace
// window before settling.
const GRACE_POLLS = 8;

// Same routes in ERP and MES — overridable if a host ever diverges.
const DEFAULT_PATHS = {
  artifacts: (modelUploadId: string) => `/api/model/artifacts/${modelUploadId}`,
  reoptimize: "/api/model/reoptimize",
  cancel: "/api/model/optimize-cancel"
};

async function postModelAction(
  action: string,
  modelUploadId: string,
  extra?: Record<string, string>
) {
  const body = new FormData();
  body.append("modelUploadId", modelUploadId);
  for (const [k, v] of Object.entries(extra ?? {})) body.append(k, v);
  await fetch(action, { method: "POST", body }).catch(() => {
    // Best-effort — polling reflects whatever actually happened server-side.
  });
}

/**
 * The full optimise lifecycle for a model preview, shared by ERP CadModel and
 * the MES model tab so behavior is identical (hosts differ only in chrome —
 * upload/delete exist in ERP only):
 *
 * - TanStack Query polls the artifacts route while an optimise is genuinely in
 *   flight (and through a short grace window otherwise); results are cached and
 *   deduped across viewers of the same model.
 * - Viewing IS the intent: a model with no artifact and no optimise in flight
 *   auto-fires the optimise on mount. A Failed status never auto-refires (that
 *   would loop a deterministic failure and override an explicit cancel) — the
 *   settled card's Retry covers it.
 * - retry() re-fires the optimise and resumes polling via invalidation.
 * - cancel() stamps the row Failed and cancels the assembler job.
 */
export function useOptimizedModel({
  modelPath,
  modelUploadId: explicitModelUploadId = null,
  companyId,
  /** A just-dropped local File (ERP upload flow) — counts toward the raw tier. */
  file = null,
  /** Disables the auto-fire (and retry/cancel posts) — e.g. no session. */
  enabled = true,
  paths = DEFAULT_PATHS
}: {
  modelPath: string | null;
  /**
   * The authoritative `modelUpload.id`, when the caller has it (MES has it as
   * `operation.itemModelId ?? job.modelId`). Preferred over deriving the id from
   * `modelPath`: legacy rows whose stored path isn't `${company}/models/${id}.ext`
   * derive a phantom id, which 404s the artifacts/reoptimise lookups and hides an
   * already-optimised model. Falls back to path derivation when not supplied.
   */
  modelUploadId?: string | null;
  companyId: string;
  file?: File | null;
  enabled?: boolean;
  paths?: typeof DEFAULT_PATHS;
}) {
  const queryClient = useQueryClient();
  const modelUploadId = explicitModelUploadId ?? modelIdFromPath(modelPath);
  const gracePolls = useRef(0);

  const query = useQuery<ModelArtifacts>({
    queryKey: ["model-artifacts", companyId, modelUploadId],
    enabled: Boolean(modelUploadId),
    queryFn: async () => {
      const res = await fetch(paths.artifacts(modelUploadId as string));
      if (!res.ok) throw new Error(`artifacts ${res.status}`);
      return res.json();
    },
    staleTime: 0,
    gcTime: 5 * 60 * 1000,
    // A missing model (unknown id → artifacts 404) settles as an error with no
    // data; don't poll it forever. Auto-fire is already gated on `artifacts`
    // being present, so an errored query never triggers an optimise.
    retry: 1,
    refetchInterval: (q) => {
      if (q.state.status === "error") return false;
      const d = q.state.data;
      if (!d) return POLL_MS;
      // In-flight beats "a GLB already exists": a forced re-optimise runs with
      // the previous GLB still present — polling must continue until the run
      // settles, or the UI freezes on the pre-regen snapshot (stale mesh/sizes,
      // regen spinner stuck forever).
      const inFlight =
        d.optimizeStatus === "Queued" || d.optimizeStatus === "Processing";
      if (inFlight) {
        gracePolls.current = 0;
        return POLL_MS;
      }
      if (d.optimizedModelPath || d.glbPath) return false;
      // Terminal/idle: keep a short grace window so a just-fired trigger (row
      // not yet flipped, possibly still showing a STALE Failed from the last
      // attempt) is picked up instead of polling stopping dead — the
      // "click Load Preview twice" bug in the hand-rolled version.
      if (gracePolls.current < GRACE_POLLS) {
        gracePolls.current += 1;
        return POLL_MS;
      }
      return false;
    }
  });

  const artifacts = query.data;
  const hasInteractive = Boolean(
    artifacts?.optimizedModelPath || artifacts?.glbPath
  );
  const optimizeInFlight =
    artifacts?.optimizeStatus === "Queued" ||
    artifacts?.optimizeStatus === "Processing";
  // Match ModelPreview's `useRawTier` eligibility exactly, so the hook never
  // suppresses the blocking progress UI for a raw the renderer won't mount:
  // require a KNOWN size within the cap (an unknown size must not pass via
  // `?? 0`) AND a format the in-browser loaders actually speak.
  const artifactRawName = artifacts?.rawPath?.split("/").pop() ?? "";
  const rawRenderable = Boolean(
    (artifacts?.rawPath &&
      artifacts.size != null &&
      artifacts.size <= MODEL_RAW_KEEP_MAX_BYTES &&
      isRawRenderable(artifactRawName)) ||
      (file &&
        file.size <= MODEL_RAW_KEEP_MAX_BYTES &&
        isRawRenderable(file.name))
  );

  // Bridges the fire -> job-visible gap: the row status takes a couple of
  // polls to flip, and without this the progress overlay wouldn't appear
  // until then. Cleared on handover (or a 15s safety timeout).
  const [optimisticOptimize, setOptimisticOptimize] = useState(false);
  useEffect(() => {
    if (!optimisticOptimize) return;
    if (optimizeInFlight || hasInteractive) {
      setOptimisticOptimize(false);
      return;
    }
    const timeout = setTimeout(() => setOptimisticOptimize(false), 15000);
    return () => clearTimeout(timeout);
  }, [optimisticOptimize, optimizeInFlight, hasInteractive]);

  const [actionBusy, setActionBusy] = useState(false);

  const fireOptimize = useCallback(
    async (id: string, force?: boolean) => {
      gracePolls.current = 0;
      setOptimisticOptimize(true);
      setActionBusy(true);
      await postModelAction(
        paths.reoptimize,
        id,
        force ? { force: "true" } : undefined
      );
      setActionBusy(false);
      await queryClient.invalidateQueries({
        queryKey: ["model-artifacts", companyId, id]
      });
    },
    [companyId, paths.reoptimize, queryClient]
  );

  // Auto-fire: fires once per model per mount, on the first artifacts response
  // showing nothing to render and nothing in flight.
  const autoFiredRef = useRef<string | null>(null);
  useEffect(() => {
    if (!enabled || !artifacts || !modelUploadId || !modelPath) return;
    if (autoFiredRef.current === modelUploadId) return;
    // No optimiser configured → firing reoptimise just no-ops server-side; skip it.
    if (artifacts.optimizerAvailable === false) return;
    // No source left in storage → the run can only fail; don't fire.
    if (artifacts.sourceAvailable === false) return;
    if (
      hasInteractive ||
      optimizeInFlight ||
      artifacts.optimizeStatus === "Failed"
    )
      return;
    if (!modelPathOptimizeFormat(modelPath)) return;
    autoFiredRef.current = modelUploadId;
    void fireOptimize(modelUploadId);
  }, [
    enabled,
    artifacts,
    modelUploadId,
    modelPath,
    hasInteractive,
    optimizeInFlight,
    fireOptimize
  ]);

  const retry = useCallback(() => {
    if (!enabled || !modelUploadId) return;
    void fireOptimize(modelUploadId);
  }, [enabled, modelUploadId, fireOptimize]);

  // Force a fresh optimise of an already-Successful model (the badge's
  // refresh action) — e.g. to pick up improved tessellation/quality settings.
  // The server resets optimizeStatus so the job's already-optimised guard
  // doesn't skip the run.
  const regenerate = useCallback(() => {
    if (!enabled || !modelUploadId) return;
    void fireOptimize(modelUploadId, true);
  }, [enabled, modelUploadId, fireOptimize]);

  const cancel = useCallback(async () => {
    if (!enabled || !modelUploadId) return;
    setActionBusy(true);
    await postModelAction(paths.cancel, modelUploadId);
    setActionBusy(false);
    await queryClient.invalidateQueries({
      queryKey: ["model-artifacts", companyId, modelUploadId]
    });
  }, [enabled, modelUploadId, companyId, paths.cancel, queryClient]);

  // "A GLB is genuinely on its way" — the viewer renders this as the
  // preparing state; a settled model must not wear it.
  const awaitingModel =
    (query.isLoading && Boolean(modelUploadId)) ||
    (optimizeInFlight && !hasInteractive) ||
    Boolean(file);

  // Staged progress overlay: an optimise is running and nothing else can
  // render. When the raw tier renders, the optimise runs silently behind it
  // and the GLB swaps in on success.
  const showOptimizeProgress =
    (optimizeInFlight || optimisticOptimize) &&
    !hasInteractive &&
    !rawRenderable;

  // Optimise running behind a rendered raw tier — drives the viewer's small
  // "Optimizing" chip (as opposed to the full-screen preparing overlay above).
  const backgroundOptimizing =
    (optimizeInFlight || optimisticOptimize) &&
    !hasInteractive &&
    rawRenderable;

  // Last optimise Failed (auto-fire deliberately won't re-run it) — drives the
  // viewer's "Optimize failed · Retry" chip so a WASM-rendered model still has a
  // retry affordance instead of silently sitting on a failed optimise. Suppressed
  // when the optimiser isn't configured — a retry would just fail again.
  const optimizeFailed =
    artifacts?.optimizeStatus === "Failed" &&
    artifacts?.optimizerAvailable !== false;

  // Whether a manual retry can possibly succeed. When the optimiser isn't
  // configured — or the reoptimise SOURCE no longer exists in storage — hosts
  // must not wire `onRetry`: ModelPreview's settled/no-preview state would
  // render a retry button advertising a dead action.
  const canRetry =
    artifacts?.optimizerAvailable !== false &&
    artifacts?.sourceAvailable !== false;

  return {
    artifacts,
    modelUploadId,
    awaitingModel,
    hasInteractive,
    rawRenderable,
    optimizeInFlight,
    showOptimizeProgress,
    backgroundOptimizing,
    optimizeFailed,
    canRetry,
    /** Overlay's first step reads as waiting until the job is picked up. */
    optimizeQueued: artifacts?.optimizeStatus !== "Processing",
    retry,
    regenerate,
    retryLabel:
      artifacts?.optimizeStatus === "Failed" ? "Retry" : "Load Preview",
    cancel,
    actionBusy
  };
}