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(jobs): auto-register ERP with Inngest on boot

Sidwebworksdc72d6365a95
diff --git a/.claude/rules/sst-deployment-infrastructure.md b/.claude/rules/sst-deployment-infrastructure.md
index fb6a37ab71..cd693ed15f 100644
--- a/.claude/rules/sst-deployment-infrastructure.md
+++ b/.claude/rules/sst-deployment-infrastructure.md
@@ -4,7 +4,10 @@ paths:
- "sst.config.ts"
- "ci/**"
- ".github/workflows/deploy.yml"
+ - ".github/workflows/inngest.yml"
- "Dockerfile"
+ - "apps/erp/app/utils/inngest-self-sync.server.ts"
+ - "apps/erp/app/entry.server.tsx"
---
# SST / AWS ECS Deployment (managed cloud path)
@@ -74,6 +77,41 @@ Triggers on push to `main` touching `apps/erp/**`, `apps/mes/**`, `packages/**`
root (`cwd: ".."` relative to `ci/`): `npx --yes [email protected] deploy --stage prod`.
- Per-workspace failures are caught; the script exits non-zero if any failed.
+## Inngest function sync — two mechanisms, both fire on every deploy
+
+Inngest (Cloud or self-hosted) only knows an app's current function list once
+something PUTs its serve endpoint (`/api/inngest`) — that's Inngest's own
+registration handshake, not Carbon-specific. Two independent triggers exist:
+
+- **Boot self-sync** (`apps/erp/app/utils/inngest-self-sync.server.ts`,
+ wired from `apps/erp/app/entry.server.tsx`): on every process boot where
+ `NODE_ENV=production` (both this ECS/SST path and self-hosted Swarm), the
+ app retries `PUT http://127.0.0.1:${PORT}/api/inngest` against itself
+ (up to 10 attempts, 2s apart) until it succeeds, then stops. Fire-and-forget
+ — never blocks or fails server boot. Covers every case a per-workspace
+ fan-out can't: ECS task reschedules, autoscale-out, self-host restarts —
+ not just a `main` push. No-ops in local `pnpm dev`/`vitest` (gated on
+ `NODE_ENV === "production"`, which those don't set), and no-ops on a real
+ Vercel deployment (`VERCEL_DEPLOYMENT_ID` set) — a serverless function has
+ no persistent port to self-connect to; Vercel's own Inngest integration
+ syncs via a deploy webhook instead. Carbon doesn't deploy to real Vercel
+ today (the `VERCEL_ENV`/`VERCEL_URL` vars above are just an env shim for
+ app code that reads them for its own base-URL detection), but the adapter
+ path (`server/app.ts`, `@vercel/react-router` in `entry.server.tsx`) is
+ still live, so this stays inert there rather than retrying uselessly.
+- **CI-triggered sync** (`.github/workflows/inngest.yml`, `ci/src/jobs.ts`):
+ runs after "Deploy Apps" succeeds on `main`. Reads every row in the
+ `workspaces` table and does the same `PUT .../api/inngest` against each
+ `url_erp`. Redundant with boot self-sync today, but kept as an
+ externally-triggered backstop (e.g. if a task's own retries were exhausted
+ before the app was reachable). Only targets `url_erp`, never `url_mes` — MES
+ has no `/api/inngest` route to sync.
+
+Both hit the same handler (`apps/erp/app/routes/api+/inngest.ts`, `serve()`
+from `inngest/remix`) — the registration target URL is fixed by that route's
+`serveHost` config (`INNGEST_SERVE_HOST || ERP_URL`), so it doesn't matter
+whether the PUT arrives via loopback or the public domain.
+
## Migrations are a separate CI step
SST deploy does **not** run DB migrations. Migrations live in
`ci/src/migrations.ts` (script `ci:migrations`), a separate workspace fan-out over
diff --git a/apps/erp/app/entry.server.tsx b/apps/erp/app/entry.server.tsx
index aa7a1aa739..9edde6881b 100644
--- a/apps/erp/app/entry.server.tsx
+++ b/apps/erp/app/entry.server.tsx
@@ -4,8 +4,10 @@ import { getRequestId } from "@carbon/logger/middleware.server";
import { handleRequest as vercelHandleRequest } from "@vercel/react-router/entry.server";
import type { EntryContext, RouterContextProvider } from "react-router";
import { isRouteErrorResponse } from "react-router";
+import { scheduleInngestSelfSync } from "./utils/inngest-self-sync.server";
ensureLoggingConfigured();
+scheduleInngestSelfSync();
const log = getLogger("erp");
diff --git a/apps/erp/app/utils/inngest-self-sync.server.ts b/apps/erp/app/utils/inngest-self-sync.server.ts
new file mode 100644
index 0000000000..aeb5b27728
--- /dev/null
+++ b/apps/erp/app/utils/inngest-self-sync.server.ts
@@ -0,0 +1,83 @@
+import { sleep } from "@carbon/lib/async";
+import { getLogger } from "@carbon/logger";
+
+const log = getLogger("erp", "inngest-self-sync");
+
+const MAX_ATTEMPTS = 10;
+const RETRY_DELAY_MS = 2_000;
+
+// A PUT to our own serve endpoint is Inngest's registration handshake — the
+// same request `ci/src/jobs.ts` curls from CI after a deploy. Doing it here
+// too means a freshly booted task (deploy, ECS reschedule, autoscale-out)
+// re-syncs itself immediately instead of waiting on that external job, which
+// only fires after a "Deploy Apps" success on `main`. `serveHost` (set from
+// INNGEST_SERVE_HOST/ERP_URL in the route) already fixes the URL Inngest is
+// told to call back on, so hitting our own loopback address here is
+// equivalent to CI hitting the public one.
+async function syncInngest() {
+ const port = process.env.PORT || "3000";
+ const url = `http://127.0.0.1:${port}/api/inngest`;
+
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
+ try {
+ const response = await fetch(url, { method: "PUT" });
+ if (response.ok) {
+ log.info(
+ "Inngest self-sync succeeded on attempt {attempt} ({status})",
+ {
+ attempt,
+ status: response.status
+ }
+ );
+ return;
+ }
+ log.warn(
+ "Inngest self-sync got {status} on attempt {attempt}/{maxAttempts}",
+ { status: response.status, attempt, maxAttempts: MAX_ATTEMPTS }
+ );
+ } catch (error) {
+ // Expected for the first attempt or two — the HTTP server isn't
+ // listening yet when this fires at module load.
+ log.debug(
+ "Inngest self-sync attempt {attempt}/{maxAttempts} failed: {message}",
+ {
+ attempt,
+ maxAttempts: MAX_ATTEMPTS,
+ message: error instanceof Error ? error.message : String(error)
+ }
+ );
+ }
+ await sleep(RETRY_DELAY_MS);
+ }
+
+ log.error(
+ "Inngest self-sync failed after {maxAttempts} attempts — functions may be stale in Inngest until the next deploy or manual sync",
+ { maxAttempts: MAX_ATTEMPTS }
+ );
+}
+
+const globalForInngestSync = globalThis as typeof globalThis & {
+ __carbonInngestSyncStarted?: boolean;
+};
+
+/**
+ * Fire-and-forget: never awaited by callers, never allowed to affect server
+ * boot or liveness either way. Only runs in real production boots
+ * (`NODE_ENV=production` — ECS/SST and self-hosted Swarm) — local dev already
+ * points a self-hosted Inngest server at `/api/inngest` via `--sdk-url`, and
+ * this must never fire during `vitest` runs that import the server entry.
+ *
+ * Skipped on Vercel (`VERCEL_DEPLOYMENT_ID`, same check `server/app.ts` uses):
+ * a serverless function has no persistent port to self-connect to, so this
+ * would just retry against a closed connection on every cold start. Vercel's
+ * own Inngest integration syncs via a deploy webhook instead — see
+ * `.claude/rules/sst-deployment-infrastructure.md`.
+ */
+export function scheduleInngestSelfSync() {
+ if (process.env.NODE_ENV !== "production") return;
+ if (process.env.VERCEL_DEPLOYMENT_ID) return;
+ if (globalForInngestSync.__carbonInngestSyncStarted) return;
+ globalForInngestSync.__carbonInngestSyncStarted = true;
+
+ void syncInngest();
+}
diff --git a/packages/lib/package.json b/packages/lib/package.json
index 2af9b92fca..0801cbebcb 100644
--- a/packages/lib/package.json
+++ b/packages/lib/package.json
@@ -27,6 +27,7 @@
"vitest": "catalog:"
},
"exports": {
+ "./async": "./src/async.ts",
"./events": "./src/events.ts",
"./inngest": "./src/inngest/client.ts",
"./resend.server": "./src/resend.server.ts",
diff --git a/packages/lib/src/async.ts b/packages/lib/src/async.ts
new file mode 100644
index 0000000000..421bda080a
--- /dev/null
+++ b/packages/lib/src/async.ts
@@ -0,0 +1,3 @@
+export function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}