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.

perf: stop audit writes stalling joins, bound and trace each request's database calls (#1814)

Sid1f5183a1f29d
diff --git a/.ai/lessons.md b/.ai/lessons.md
index e93b072089..ba0eb2c5d4 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -2823,3 +2823,47 @@ tag until proven otherwise.
**Rule:** Never cast a typed payload past the table's type. When the compiler names an extra key, destructure it out at the write, where every caller is covered, and say where the value actually lives. `unchecked()` is only for a column or table chosen at runtime (`{ [field]: value }`, `.from(table)`). To list every extra key at once rather than one per error, probe with `Exclude<keyof Payload, keyof Database["public"]["Tables"][T]["Update"]>`.
**Applies to:** every `{module}.service.ts` write, MES `services/*.service.ts`, `packages/utils/src/object.ts` (`unchecked`).
+
+
+## A function redefined by forking its last migration picks up whatever that fork did
+
+**Context:** Database functions were changed by copying the newest definition into a new migration and editing it. `create_audit_log_table` was forked several times; one fork made its existing-table branch re-attach the append-only trigger and re-run `secure_audit_log_table` unconditionally, and `insert_audit_log_batch` calls it on every write.
+
+**Problem:** `CREATE TRIGGER` fires PostgREST's `pgrst_ddl_watch` event trigger, which reloads the schema cache. With one audit table and one search table per company that reload took 10-13 s in production, and every request with an embed waited for it: 480+ reloads a day, each one stalling joins for every company. No test or review could see it, because each fork looked like a small diff against a file nobody reads end to end. `dispatch_event_batch` lost its composite-key pairing the same way once.
+
+**Rule:** A function that changes more than once is authored as a single file, not as a chain of forks. The event system's functions live in `packages/database/src/event-system/functions/<name>.sql`; edit the file and run `pnpm --filter @carbon/database authz migration <name>`. A function on a write path must not run DDL: check the catalog first and only repair what is missing (`audit-log-no-ddl-on-write.test.sql` asserts the trigger and policy oids do not change across writes).
+
+**Applies to:** `packages/database/src/event-system/functions/`, `packages/database/src/authz/helpers/`, `no-authz-ddl-in-migrations` (`@carbon/checks`).
+
+
+## Work a request does not await is frozen with the instance on Vercel
+
+**Context:** Work-event capture (PostHog) and the GTM forward were started and not awaited, so the response would not wait for them.
+
+**Problem:** A Vercel function instance is frozen once its response is sent. The unawaited call stopped mid-flight and finished only when the next request woke the instance, so traces showed analytics calls of 10 s and more, and on an instance that was never reused the event was lost. `request.signal` does not help either: without `supportsCancellation` it never aborts on Vercel.
+
+**Rule:** Anything a request leaves running goes through `async.background(task, onError)` from `@carbon/utils`. Each app registers the host's `waitUntil` once with `async.onBackground` in `entry.server.tsx`, which keeps the instance up until that work settles. Never a bare unawaited promise, a `void` IIFE, or a `.then` chain.
+
+**Applies to:** `apps/{erp,mes}/app/entry.server.tsx`, `packages/lib/src/telemetry/capture.ts`, `packages/stripe/src/stripe.server.ts`, any new fire-and-forget call.
+
+
+## React Router's instrumentation API can observe a request, not change it
+
+**Context:** The request-id, access-log and request-context middlewares looked like candidates to move into `instrumentations`, to shorten the middleware chain.
+
+**Problem:** In React Router 7.18 an instrumentation wrapper receives a read-only view: the request is `{ method, url, headers.get }` with no `signal` and no `clone()`, the context exposes only `get`, and the result carries only `statusCode` and `meta`. It cannot set a response header, open an AsyncLocalStorage scope around the handler, or read the body, which is everything those middlewares do.
+
+**Rule:** Instrumentation is for spans and measurements. Anything that sets a header, provides context to downstream code or reads the request stays a middleware; merge middlewares into one (`requestMiddleware`) instead of moving them. A middleware's own cost is recorded by `timedMiddleware` as `carbon.middleware.<name>.ms`, not by a span, because a middleware span contains everything it calls.
+
+**Applies to:** `packages/logger/src/middleware.server.ts`, `packages/logger/src/tracing.server.ts`, both apps' `root.tsx`.
+
+
+## A limiter must hand a freed slot to the next waiter, not decrement and let it race
+
+**Context:** `async.limit` first released a slot by decrementing the active count and waking the first queued call.
+
+**Problem:** The woken call resumes a microtask later. A call made in between saw a free slot, took it, and the woken call then incremented too: more than `concurrency` ran at once, and under steady load a queued call could be overtaken indefinitely.
+
+**Rule:** When a slot frees and a call is queued, pass the slot to it directly and leave the count unchanged; decrement only when the queue is empty. A queued call never increments. Test it by starting a new call in the same tick a running one finishes and asserting the queued one runs first.
+
+**Applies to:** `packages/utils/src/async.ts` (`limit`), any hand-written semaphore.
diff --git a/.ai/plans/2026-10-02-job-status-latency.md b/.ai/plans/2026-10-02-job-status-latency.md
new file mode 100644
index 0000000000..7acf3d4d50
--- /dev/null
+++ b/.ai/plans/2026-10-02-job-status-latency.md
@@ -0,0 +1,111 @@
+# Job create and job status latency — follow-up for the edge-function removal branch
+
+Findings from production traces (Axiom, week ending 2026-10-02). Nothing here is
+implemented. It is written for the branch that ports the edge functions to Node
+(`refactor/remove-edge-functions`), because two of the three causes are edge
+function calls that branch already removes, and the third lives in code that
+branch's `recalculate` / `get-method` ports will call.
+
+## What is slow
+
+| Route | Median | p95 | Where the time goes |
+|---|---|---|---|
+| `POST /x/job/new` | 2.3 s | 10.5 s | `get-method` edge fn (median 1.2 s, max 6.1 s), then `recalculate` edge fn (median 0.75 s), one after the other |
+| `POST /x/job/:jobId/status` (no scheduling) | 1.2–1.8 s | | `recalculate` edge fn (~0.75 s), job MRP (~0.45 s, 14 calls), sequential reads |
+| `POST /x/job/:jobId/status?schedule=1` | 10 s | 19 s | `runLocationSchedule` (5–7 s), `create` (`purchaseOrderFromJob`) edge fn (1.1 s, once 7.5 s), recalculate, MRP |
+
+The 7 s outliers on a single `job` read were PostgREST schema-reload holds, fixed
+separately (crbnos/carbon#1814).
+
+## Cause 1 — every edge function call costs 0.7–1.4 s
+
+Median call time over a week, whatever the function does:
+
+| Function | Calls | Median | p90 |
+|---|---|---|---|
+| `recalculate` | 22 | 0.76 s | 0.92 s |
+| `get-method` | 17 | 1.29 s | 6.1 s |
+| `create` | 13 | 0.91 s | 1.15 s |
+| `post-receipt` | 5 | 1.33 s | 3.2 s |
+| `issue` | 4 | 1.38 s | 1.44 s |
+| `post-purchase-invoice` | 4 | 1.38 s | 1.48 s |
+
+That floor is the HTTP hop plus function start-up at low traffic. Porting these
+to Node removes it.
+
+- [ ] After the port, confirm in Axiom that `POST /x/job/new` no longer has two
+ sequential ~1 s spans, and that job status changes drop by ~0.75 s.
+- [ ] `job/new` runs `get-method` then `recalculate` back to back. Once both are
+ in-process, check whether `recalculate` can reuse what `get-method` just
+ loaded instead of reading the job's materials again.
+
+## Cause 2 — the scheduler re-plans the whole location, one job at a time
+
+`runLocationSchedule` (`packages/planning/src/scheduling/run-schedule.ts`) loops
+over every job at the location and runs a full `SchedulingEngine` pass for each.
+Measured on a location with ~23 jobs, one status change issued 47 transactions,
+160 `SELECT jobOperation`, 110 `UPDATE jobOperation`, 91 `SELECT jobMakeMethod`
+and 69 calls to the `get_job_methods_by_method_id` RPC (1.9 s on its own).
+
+Per job, inside that loop (`scheduling-engine.ts`, line numbers as of this note):
+
+- [ ] **The assembly tree is built three times** — `buildAssemblyTree` at `:265`,
+ `:341` and `:838`. Each build reads the root make method and calls the
+ RPC. Build it once per job and pass it down: 69 RPC calls become 23.
+- [ ] **The job's operations are read seven times** — `provider.getOperations`
+ at `:231`, `:336`, `:833`, plus `assembly-handler.ts:38` (reached three
+ times through the tree builds) and the cross-job read at `:744`. Later
+ steps read after earlier steps write (`:505` sets status, the persist step
+ writes placements), so check each read before reusing an earlier result.
+- [ ] **Operations are written one row at a time** — the persist loop issues an
+ `UPDATE jobOperation` per operation (`:954`), and a second loop sets each
+ dependency-free operation to `Ready` (`:505`) outside any transaction.
+ Replace each with one set-based statement per job
+ (`UPDATE … FROM (VALUES …)`, as `updateSortOrder` does).
+- [ ] **The location's timezone is read for every job** — `getLocationTimeZone`
+ at `:218`. Read it once per run.
+- [ ] **Work-center availability misses its cache on most jobs** — it is keyed by
+ the job's candidate work-center set (`master-data-provider.ts`
+ `getWorkCenterAvailability`), about 14 distinct sets for 23 jobs. Load the
+ location's work centers, shifts and maintenance once per run and filter in
+ memory.
+- [ ] **Live capacity reservations are fetched per job** (`getLiveReservations`),
+ never cached.
+
+The existing scheduling-engine tests pin the result; these changes must not
+alter it.
+
+- [ ] Decide separately whether re-planning the location has to finish before
+ the redirect. Running it as a background job would make a status change
+ take about 1 s whatever the location's size, at the cost of the job page
+ briefly showing the previous schedule dates.
+
+## Cause 3 — job MRP runs inline on every Planned/Ready change
+
+`$jobId.status.tsx` awaits `recalculateJobRequirements` and then
+`runMRP({ type: "job" })` before it updates the status (about 1.2 s together).
+
+- [ ] Check whether the job MRP result is needed before the response, or can run
+ after it.
+
+## What this branch must reconcile when it merges main
+
+crbnos/carbon#1814 changed code the removal branch also touches:
+
+- [ ] **Event-system functions are files now.**
+ `packages/database/src/event-system/functions/` holds
+ `util.invoke_edge_function.sql`, `util.process_embeddings.sql` and
+ `util.wake_event_queue.sql` with main's definitions. The removal branch
+ changes or drops all three: update or delete the files, drop the old
+ signatures in a hand-written migration (sync refuses a file that would
+ create an overload), then run
+ `pnpm --filter @carbon/database authz migration <name>`.
+- [ ] **One Postgres pool per Node process.** `getPostgresConnectionPool(n)` now
+ throws on Node; use `getProcessPool()`. `getJobDatabaseClient()` takes no
+ size. Ported functions that built their own pool at module scope (the
+ edge-function pattern) must use the shared one.
+- [ ] **Request-bound Supabase clients.** `getCarbonServiceRole()` called while
+ handling a request shares a limit of 8 calls in flight with every other
+ client of that request. A ported function that fans out more than that in
+ parallel will queue; that is intended, but measure the ones that did heavy
+ parallel reads as edge functions (`get-method`, MRP).
diff --git a/.claude/rules/authz-manifest.md b/.claude/rules/authz-manifest.md
index db3baf2b15..d31ab36a26 100644
--- a/.claude/rules/authz-manifest.md
+++ b/.claude/rules/authz-manifest.md
@@ -1,6 +1,7 @@
---
paths:
- "packages/database/src/authz/**"
+ - "packages/database/src/event-system/**"
- "packages/database/supabase/migrations/**"
- "packages/database/supabase/tests/authz-*.test.sql"
- "packages/checks/src/conformance/no-authz-ddl-in-migrations.ts"
@@ -9,17 +10,21 @@ paths:
# Authz manifest: RLS policies and helpers
-Every RLS policy on a `public` table, and the 20 RLS/auth helper functions, are authored in
+Every RLS policy on a `public` table, and the 16 RLS/auth helper functions, are authored in
`packages/database/src/authz/` and nowhere else. Migrations create tables; they never write
`CREATE POLICY` / `ALTER POLICY` on a public table or define a managed helper
(`no-authz-ddl-in-migrations` in `@carbon/checks` fails them, from `20260927000000` on).
`storage.objects` (bucket) policies are not in the manifest and stay in migrations.
+The same machinery owns the event system's 39 functions — see
+[Event-system functions](#event-system-functions) below.
+
| File | What it is |
|---|---|
| `manifest.ts` | one rule per public table, typed by table name (`satisfies Manifest`) |
| `rules.ts` | the pieces and builders; `render()` compiles a rule to `CREATE POLICY` SQL with Kysely |
| `helpers/<name>.sql` | one `CREATE OR REPLACE FUNCTION public.<name>` per file (validated with Postgres's parser) |
+| `../event-system/functions/<name>.sql` | the event system's functions, same format; `util.<name>.sql` for one in the `util` schema |
| `sync.ts` | `authz sync` / `check`: make a database match, in one transaction |
| `migration.ts` | `authz migration`: ship changes to databases that do not sync; `unshipped()` |
| `baseline.json` | what production had when the manifest took over — written once, never regenerated |
@@ -68,6 +73,33 @@ It also refuses a generated file containing anything `authz migration` does not
header exemption cannot be borrowed by a hand-written file. Never edit a generated migration
or `baseline.json` by hand.
+## Event-system functions
+
+`packages/database/src/event-system/functions/` holds one file per function for dispatch,
+subscriptions, the queue wake-up, the audit log, the search index and embeddings (39:
+31 in `public`, 8 in `util`). They are loaded, synced, shipped and guarded exactly like the
+RLS helpers — `loadHelpers()` reads both directories, and a `Helper` carries its `schema`.
+
+- **File name is the function**: `dispatch_event_batch.sql` defines
+ `public.dispatch_event_batch`; `util.wake_event_queue.sql` defines
+ `util.wake_event_queue`. A file whose function is in another schema, or named
+ differently, fails `validateHelper`. Everywhere a helper is reported (sync output,
+ `unshipped()`, the generated migration's name list) it is `name` or `schema.name`.
+- **Changing one**: edit the file, `pnpm db:migrate` (syncs it locally), then
+ `authz migration <name>`. Never fork the definition into a hand-written migration —
+ that is how `create_audit_log_table` came to run `CREATE TRIGGER` on every audit write
+ and how `dispatch_event_batch` lost its composite-key pairing once.
+- **Cutoff**: `no-authz-ddl-in-migrations` checks these from `20261002114954` (the
+ takeover migration, `EVENT_SYSTEM_SINCE`), the RLS helpers from `20260927000000`. Each
+ directory has its own cutoff in `MANAGED_FUNCTION_SETS`.
+- **Not in `baseline.json`**: the takeover migration ships all 39, so every one has a
+ generated block for `unshipped()` to compare against.
+- **Signature changes and new functions** still need a hand-written migration for the
+ `DROP FUNCTION` (sync refuses a file that would create an overload); the new definition
+ goes in the file.
+- **Not managed**: the per-table interceptors (`sync_*`) stay in their table's migration,
+ and `util.api_url()` is not in the set.
+
## Commands
```bash
diff --git a/.claude/rules/database-patterns.md b/.claude/rules/database-patterns.md
index c554282f27..68d7438dba 100644
--- a/.claude/rules/database-patterns.md
+++ b/.claude/rules/database-patterns.md
@@ -35,6 +35,31 @@ dropped connection; uploads, deletes, auth and function calls pass straight thro
re-create this config ad hoc, and do not widen that wrapper to database calls: it would multiply
the SDK's retries.
+**Every Supabase client built while handling a request is bound to it** (`requestFetch` in
+`client.server.ts`). `requirePermissions` passes its `Request`; anything else — a
+`getCarbonServiceRole()` deep in a service, the API-key client, `getUserScopedClient` — finds
+it through `currentRequest()` (`@carbon/logger`, set by `requestMiddleware`). Inngest
+steps run as requests to `/api/inngest`, so their clients are bound too (they are POSTs, so
+never cancelled). Outside a request (scripts, module-level clients) nothing is bound.
+
+- **At most 8 calls in flight per request, across all its clients.** Every call waits for one of
+ `REQUEST_CONCURRENCY` slots of one limiter per request (`async.limit`, memoized with
+ `oncePerRequest`), like an HTTP agent's `maxSockets`, so `Promise.all` over a page's queries
+ cannot take every PostgREST connection. A call never waits on another call, so this cannot
+ deadlock.
+- **On a read (GET/HEAD), `request.signal` cancels reads.** When the browser disconnects before
+ the response is done, selects, RPCs and storage reads in flight are cancelled and later ones
+ fail at once with an `AbortError` in `{ error }`, never retried. Not tied to the signal:
+ actions, table writes even on a GET (an OAuth callback saving its tokens), auth and
+ edge-function calls. Error and warning logs from such an abandoned read are dropped
+ (`liveRequest` filter in `@carbon/logger`'s `config.server.ts`), the stance `handleError`
+ already takes. **On Vercel the signal never aborts**: Vercel only aborts it with
+ `supportsCancellation` in `vercel.json`, which also terminates the function when the client
+ disconnects — the app is one function, so actions would die mid-write. Do not enable it.
+ Cancellation therefore applies on ECS and self-hosted only.
+
+Kysely has neither: it is bounded by the process pool below.
+
### Getting a client in a route
Loaders/actions never construct a client directly. They call `requirePermissions`
@@ -142,9 +167,18 @@ Two real options, in order of preference:
review, and ships through a migration. Do not push app logic into SQL just to get atomicity.
For **multi-row / multi-table writes** where partial failure is a bug, use Kysely. The route passes
-`getDatabaseClient()` (`apps/erp/app/services/database.server.ts` — a cached singleton over a 10-conn
-`pg` pool built by `getPostgresClient`/`getPostgresConnectionPool` in
-`packages/database/supabase/functions/lib/postgres/index.ts`). Kysely opens one PG transaction, runs
+`getDatabaseClient()` (`apps/erp/app/services/database.server.ts` — a cached singleton over
+`getProcessPool()` in `packages/database/supabase/functions/lib/postgres/index.ts`). A Node process
+has ONE pool of 16 connections, shared by the app's client, the jobs (`getJobDatabaseClient()`)
+and scripts, and nothing but an exiting script ends it; `getPostgresConnectionPool(n)` is for edge
+functions only and throws on Node. `traceConnectionWaits` (`@carbon/logger/tracing.server`)
+records a `db pool wait` span when a caller queues for a connection and `db connect` when one is
+opened, since query spans time only the query. On Vercel both apps' `entry.server.tsx` call
+`attachDatabasePool(getProcessPool())` (`@vercel/functions`): a frozen instance cannot run pg's idle
+timer, so it is kept up until idle connections have closed. Sixteen is a per-instance cap, not
+a database budget: the pool connects through the Supabase pooler, so what bounds the total is the
+pooler's client limit across every running instance, and raising the per-process size multiplies by
+the instance count. Kysely opens one PG transaction, runs
every write inside it, and rolls everything back on any error.
**Use transactions when:**
diff --git a/.claude/rules/event-system.md b/.claude/rules/event-system.md
index ee6fc2c953..b9eeb0e594 100644
--- a/.claude/rules/event-system.md
+++ b/.claude/rules/event-system.md
@@ -35,18 +35,26 @@ The wake path (`20260721184852_event-queue-wake.sql`) — both helpers live in t
- **Why `util`, not `public`:** a public function is auto-exposed as a PostgREST RPC, and a non-superuser reference to a function that transitively calls `net.http_post` segfaults the backend (pg_net 0.20 / PG15) — a remote-DoS surface a `REVOKE` can't close because the crash precedes the privilege check. anon/authenticated have no `USAGE` on `util`, so the API can't reach it. The trigger and pg_cron call it as the owner (superuser), where the pg_net path is safe.
- Edge fn `packages/database/supabase/functions/event-wake/index.ts` forwards the doorbell via `sendInngestEvent("carbon/event-queue.process", {})` (`functions/lib/inngest.ts`).
-## Database (migrations)
+## Database (functions are files, not migrations)
+
+Every function named in this document is authored as ONE file in
+`packages/database/src/event-system/functions/` (`<name>.sql`, or `util.<name>.sql`), synced
+locally by `pnpm db:migrate` and shipped by `pnpm --filter @carbon/database authz migration
+<name>`. To change one, edit its file — a migration that redefines one fails
+`no-authz-ddl-in-migrations`. The migration timestamps below are history: they say when a
+behaviour arrived, not where to read the current definition. Details:
+`authz-manifest.md` → Event-system functions.
`eventSystemSubscription` rows decide which table/operation routes to which handler. Final columns (after all migrations): `id`, `name`, `companyId`, `table`, `operations TEXT[]` (subset of `INSERT,UPDATE,DELETE,TRUNCATE`), `filter JSONB`, `handlerType`, `config JSONB`, `active`, `createdAt`. Unique on `(companyId, name, table)`. `batchSize` was removed (`20260204070000`).
`handlerType` CHECK now allows all six: `WEBHOOK, WORKFLOW, SYNC, SEARCH, AUDIT, EMBEDDING` (widened across `20260204080000` → `20260212152709` → `20260326120000`).
### PL/pgSQL functions (in `_event_system_impl` + later)
-- `dispatch_event_batch()` — AFTER STATEMENT. Reads transition tables (`batched_new`/`batched_old`), filters by active subscriptions, builds payload, `pgmq.send_batch('event_system', ...)`. Captures `actorId := auth.uid()::TEXT` (added `20260212153753`; NULL for service-role) and `workflowRunId` from the `workflow_run_id` JWT claim (`20260810100000`). UPDATE pairs transition rows on the table's **full** primary key via `get_primary_key_columns()` (`20260717143448`, restored in `20260810100000` after `20260721184852` copied the older single-column pairing forward). Uses `clock_timestamp()` per event so batched events get unique microsecond timestamps (`20260427120000`). An UPDATE that changes nothing but `updatedAt` / `updatedBy` / `embedding` is not queued for `AUDIT`, `SEARCH` or `EMBEDDING` subscriptions (`20261001195204`) — those handlers discard such an event anyway; `WEBHOOK`, `WORKFLOW` and `SYNC` still receive every UPDATE because their payload is a contract. The column list is `ignored_columns` in the function and must equal `auditConfig.skipFields`; `packages/database/src/event-dispatch.test.ts` reads the NEWEST definition and fails when a fork drops the filter or the two lists diverge.
+- `dispatch_event_batch()` — AFTER STATEMENT. Reads transition tables (`batched_new`/`batched_old`), filters by active subscriptions, builds payload, `pgmq.send_batch('event_system', ...)`. Captures `actorId := auth.uid()::TEXT` (added `20260212153753`; NULL for service-role) and `workflowRunId` from the `workflow_run_id` JWT claim (`20260810100000`). UPDATE pairs transition rows on the table's **full** primary key via `get_primary_key_columns()` (`20260717143448`, restored in `20260810100000` after `20260721184852` copied the older single-column pairing forward). Uses `clock_timestamp()` per event so batched events get unique microsecond timestamps (`20260427120000`). An UPDATE that changes nothing but `updatedAt` / `updatedBy` / `embedding` is not queued for `AUDIT`, `SEARCH` or `EMBEDDING` subscriptions (`20261001195204`) — those handlers discard such an event anyway; `WEBHOOK`, `WORKFLOW` and `SYNC` still receive every UPDATE because their payload is a contract. The column list is `ignored_columns` in the function and must equal `auditConfig.skipFields`; `packages/database/src/event-dispatch.test.ts` reads `event-system/functions/dispatch_event_batch.sql` and fails when the two lists diverge.
- `dispatch_event_interceptors()` — BEFORE ROW. Runs named sync interceptor functions inline (data-integrity, not async).
- `dispatch_event_after_interceptors()` — AFTER ROW. Same but post-commit-of-row, safe for FK refs (added `20260410030406`).
- Both dispatchers are SECURITY DEFINER (`20260925121735`), so interceptors run as the owner on every write. Write a new interceptor as **SECURITY INVOKER**: it still runs as the owner from the dispatcher, but a direct `/rpc/<interceptor>` call with a forged payload runs under the caller's RLS. A SECURITY DEFINER interceptor is callable by anyone with the anon key as the owner — `public-definer-function-authorizes-caller` fails on it.
-- `attach_event_trigger(table, sync_functions[], after_sync_functions[])` — helper that wires the BEFORE SYNC / AFTER SYNC / ASYNC STATEMENT triggers on a table (3rd arg added `20260410030406`). **Two overloads are live** — `(TEXT,TEXT[])` and `(TEXT,TEXT[],TEXT[])` — because `CREATE OR REPLACE` with an added parameter creates a sibling rather than replacing. Adding a *defaulted* parameter to this function is therefore a trap: a 2-arg call then matches more than one candidate and fails with `function attach_event_trigger(unknown, text[]) is not unique`, breaking 62 call sites. Adding an argument means dropping both overloads first.
+- `attach_event_trigger(table, sync_functions[], after_sync_functions[])` — helper that wires the BEFORE SYNC / AFTER SYNC / ASYNC STATEMENT triggers on a table (3rd arg added `20260410030406`). One signature is live, `(TEXT, TEXT[] DEFAULT, TEXT[] DEFAULT)`. `CREATE OR REPLACE` with an added parameter creates a sibling rather than replacing, and a 2-arg call then matches more than one candidate (`function attach_event_trigger(unknown, text[]) is not unique`, breaking every call site) — so adding an argument means a migration that drops the old signature first; `authz sync` refuses a file that would create an overload.
- `attach_statement_handler(table, handler_functions[])` (`20260812002453`) — the STATEMENT-level counterpart to the row-level interceptors. Attaches each function as `trg_event_statement_<fn>_{ins,upd,del}` with transition tables `batched_new` / `batched_old`; an empty array detaches. Does **not** register the table for PGMQ dispatch. Used by `itemLedger` to maintain the `itemStockQuantities` aggregate.
- Handlers are attached for all three operations, so each **must branch on `TG_OP`**: only `batched_new` exists on INSERT, only `batched_old` on DELETE. PL/pgSQL plans lazily, so a branch that doesn't run never resolves its missing transition table.
- **Why handlers can't live inside `dispatch_event_batch()`:** (1) transition tables are visible ONLY to the function the trigger invokes directly — a nested call fails with `relation "batched_new" does not exist`, for static *and* dynamic SQL, so hosting handlers there would force materializing every batch into a temp table per statement; (2) `dispatch_event_batch()` returns early when the table has no active subscription and again when `app.sync_in_progress` is set — both correct for queueing, fatal for an aggregate (`itemLedger` has no subscriptions, so the handler would never run).
@@ -54,7 +62,7 @@ The wake path (`20260721184852_event-queue-wake.sql`) — both helpers live in t
- `get_primary_key_column(table)` — dynamic PK lookup (`20260212165827`).
### RPC (callable from app)
-`create_event_system_subscription(p_name, p_table, p_company_id, p_operations[], p_handler_type, p_config?, p_filter?, p_active?)` → `TABLE(id, name, handlerType, table)`; `delete_event_system_subscription(p_subscription_id)`; `delete_event_system_subscriptions_by_name(p_company_id, p_name)`; plus search helpers `upsert_to_search_index(...)` / `delete_from_search_index(p_company_id, p_entity_type, p_entity_id)`.
+`create_event_system_subscription(p_name, p_table, p_company_id, p_operations[], p_handler_type, p_config?, p_filter?, p_active?)` → `TABLE(id, name, handlerType, table)` (upserts on `(companyId, name, table)`; the caller must be allowed to manage the NEW handler type and, when a row is replaced, the type it already had — `util.can_manage_event_subscription`: WEBHOOK needs a settings permission, the rest any employee; pinned by `supabase/tests/event-subscription-authz.test.sql`); `delete_event_system_subscription(p_subscription_id)`; `delete_event_system_subscriptions_by_name(p_company_id, p_name)`; plus search helpers `upsert_to_search_index(...)` / `delete_from_search_index(p_company_id, p_entity_type, p_entity_id)`.
### Misc
- Queue: PGMQ queue **`event_system`**.
@@ -75,7 +83,7 @@ Zod schemas + helpers. `QueueMessage` = `{ subscriptionId, triggerType: ROW|STAT
| `WEBHOOK` | `carbon/event-webhook` | `webhook.ts` | `axios.post(config.url, toWebhookBody(...), { headers })` — customer-facing webhooks; see below |
| `WORKFLOW` | `carbon/event-workflow` | `workflow.ts` | customer-workflow matcher — announcement → catalog event ids → subscribed workflows → one `workflowRun` each (see `workflow-matcher.md`) |
| `SYNC` | `carbon/event-sync` | `sync.ts` | accounting sync (Xero); maps table→entity, calls `@carbon/ee/accounting` |
-| `SEARCH` | `carbon/event-search` | `search.ts` | upsert/delete `search_index` per entity config (`search-config.ts`): last event per record wins, one read per related table for the whole batch, then one delete and one upsert statement over Kysely. A failed read or write throws so the step retries |
+| `SEARCH` | `carbon/event-search` | `search.ts` | upsert/delete `search_index` per entity config (`search-config.ts`): last event per record wins, one read per related table for the whole batch, then one delete and one upsert statement over Kysely. A failed read or write throws so the step retries; the one exception is a missing search table whose company no longer exists (deleting a company drops the table while its events may still be queued), which is skipped with a warning |
| `AUDIT` | `carbon/event-audit` | `audit.ts` | writes per-company audit log (uses `actorId`, `audit.config`) |
| `EMBEDDING` | `carbon/event-embedding` | `embedding.ts` | invokes `embed` edge fn for `item/customer/supplier` name/description changes |
@@ -93,4 +101,4 @@ Since `20260807234512_webhooks-via-event-system.sql`, user-configured webhooks (
- Latency: typically ~3–5s (sub-second wake + the multi-step drain run). Worst case ~1 min if a push is lost (dead pg_net worker, edge fn down) — the pg_cron sweeper re-wakes while messages are pending. Still async: use sync interceptors, not subscriptions, for data-integrity / real-time needs.
- The wake path depends on a seeded `config` row (`apiUrl`, `anonKey`). Dev seeds it automatically (`ensureConfigRow` in `packages/dev/src/services/migrations.ts`, apiUrl `http://kong:8000`). **Unseeded config (e.g. self-hosted) = events never process** — both the push and the sweeper wake no-op.
- Webhook/workflow handlers use `idempotency: event.data.msgId` and per-record concurrency keys.
-- Don't hand-edit generated DB types; read the newest migration for schema truth.
+- Don't hand-edit generated DB types; read the newest migration for schema truth, and `event-system/functions/` for the functions.
diff --git a/.claude/rules/workflow-event-system.md b/.claude/rules/workflow-event-system.md
index 8512a967d1..3ae972fcaf 100644
--- a/.claude/rules/workflow-event-system.md
+++ b/.claude/rules/workflow-event-system.md
@@ -25,7 +25,8 @@ the procedure, not a re-description — it does not repeat that detail.
| Served `functions` array | `packages/jobs/src/inngest/index.ts` |
| Event-name type registry (`Events`) | `packages/lib/src/events.ts` (re-exported, NOT defined, by `packages/jobs/src/events.ts`) |
| Zod schemas + subscription helpers | `packages/database/src/event.ts` |
-| `attach_event_trigger`, handler-type CHECK | `packages/database/supabase/migrations/` |
+| `attach_event_trigger`, `dispatch_event_batch` and the other event-system functions | `packages/database/src/event-system/functions/<name>.sql` (edit the file, then `authz migration`; see `authz-manifest.md`) |
+| Handler-type CHECK, per-table `attach_event_trigger(...)` calls | `packages/database/supabase/migrations/` |
## Use cases → handler type
diff --git a/apps/erp/app/entry.server.tsx b/apps/erp/app/entry.server.tsx
index 506b39f7f4..882192ed08 100644
--- a/apps/erp/app/entry.server.tsx
+++ b/apps/erp/app/entry.server.tsx
@@ -7,12 +7,14 @@ import {
getNonce,
setStrictContentSecurityPolicy
} from "@carbon/auth/middleware/security.server";
+import { getProcessPool } from "@carbon/database/client";
import { inngest } from "@carbon/lib/inngest";
import { getLogger } from "@carbon/logger";
import { ensureLoggingConfigured } from "@carbon/logger/config.server";
import { getRequestId } from "@carbon/logger/middleware.server";
import { createTracing } from "@carbon/logger/tracing.server";
-import { waitUntil } from "@vercel/functions";
+import { async } from "@carbon/utils";
+import { attachDatabasePool, waitUntil } from "@vercel/functions";
import { handleRequest as vercelHandleRequest } from "@vercel/react-router/entry.server";
import { InngestSpanProcessor } from "inngest/experimental";
import type { EntryContext, RouterContextProvider } from "react-router";
@@ -21,6 +23,13 @@ import { scheduleInngestSelfSync } from "./utils/inngest-self-sync.server";
ensureLoggingConfigured();
+// Vercel freezes an instance once its response is sent: keep it up until idle
+// database connections have closed and background work has finished.
+if (process.env.VERCEL) {
+ attachDatabasePool(getProcessPool());
+ async.onBackground(waitUntil);
+}
+
export const instrumentations = createTracing({
serviceName: "carbon-erp",
// Vercel can suspend the instance once the response is sent.
diff --git a/apps/erp/app/root.tsx b/apps/erp/app/root.tsx
index be794aaa09..fbcc57dc9d 100644
--- a/apps/erp/app/root.tsx
+++ b/apps/erp/app/root.tsx
@@ -13,11 +13,8 @@ import {
import { securityMiddleware } from "@carbon/auth/middleware/security.server";
import { validator } from "@carbon/form";
import { LocaleProvider, resolveLanguage } from "@carbon/locale";
-import {
- requestContextMiddleware,
- requestIdMiddleware
-} from "@carbon/logger/middleware.server";
-import { namedMiddleware } from "@carbon/logger/tracing.server";
+import { requestMiddleware } from "@carbon/logger/middleware.server";
+import { timedMiddleware } from "@carbon/logger/tracing.server";
import {
OperatingSystemContextProvider,
Toaster,
@@ -65,13 +62,12 @@ import "@carbon/lib/shims";
import type { Route } from "./+types/root";
import { getTheme } from "./services/theme.server";
-export const middleware = namedMiddleware([
- // First: publishes the request context so server code can reach it via ALS.
- requestContextMiddleware,
- requestIdMiddleware,
- securityMiddleware,
- flashMiddleware
-]);
+export const middleware = timedMiddleware({
+ // First: the request scope (context, request id, access log).
+ request: requestMiddleware,
+ security: securityMiddleware,
+ flash: flashMiddleware
+});
export const clientMiddleware = [flashClientMiddleware];
export const links: LinksFunction = () => {
diff --git a/apps/erp/app/routes/x+/settings+/company.new.tsx b/apps/erp/app/routes/x+/settings+/company.new.tsx
index e476e66812..9b1cac2e38 100644
--- a/apps/erp/app/routes/x+/settings+/company.new.tsx
+++ b/apps/erp/app/routes/x+/settings+/company.new.tsx
@@ -11,7 +11,7 @@ import { enableAuditLog } from "@carbon/ee/audit.server";
import { validationError, validator } from "@carbon/form";
import { redis } from "@carbon/kv";
import { getLogger } from "@carbon/logger";
-import type { ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { insertEmployeeJob } from "~/modules/people";
import { upsertLocation } from "~/modules/resources";
@@ -21,10 +21,23 @@ import {
seedCompany
} from "~/modules/settings";
import { getPermissionCacheKey } from "~/modules/users/users.server";
-import { path } from "~/utils/path";
+import { path, requestReferrer } from "~/utils/path";
const logger = getLogger("erp", "settings", "company");
+// The form lives in the topbar and only posts here. A tab left open across a
+// deployment cannot submit it: React Router reloads the document at this URL
+// instead, which without a loader is a 400. Send that reload back to the page
+// it came from.
+export function loader({ request }: LoaderFunctionArgs) {
+ const referrer = requestReferrer(request);
+ throw redirect(
+ referrer && !referrer.startsWith(path.to.newCompany)
+ ? referrer
+ : path.to.authenticatedRoot
+ );
+}
+
export async function action({ request }: ActionFunctionArgs) {
try {
assertIsPost(request);
diff --git a/apps/erp/app/services/database.server.ts b/apps/erp/app/services/database.server.ts
index db59f773fc..c716082f7c 100644
--- a/apps/erp/app/services/database.server.ts
+++ b/apps/erp/app/services/database.server.ts
@@ -8,15 +8,12 @@
* Polluting the global namespace like this is usually discouraged, but it's okay as we're just caching connections during development.
* In production, this code path is not hit multiple times as ESM modules are only singletons by default.
*/
-import {
- getPostgresClient,
- getPostgresConnectionPool
-} from "@carbon/database/client";
-import { queryLog } from "@carbon/logger/tracing.server";
+import { getPostgresClient, getProcessPool } from "@carbon/database/client";
+import { queryLog, traceConnectionWaits } from "@carbon/logger/tracing.server";
import { PostgresDriver } from "kysely";
const init = () => {
- const pool = getPostgresConnectionPool(10);
+ const pool = traceConnectionWaits(getProcessPool());
// We use the PostgresDriver from Kysely here as this code only runs in Node environment
return getPostgresClient(pool, PostgresDriver, queryLog);
};
diff --git a/apps/mes/app/entry.server.tsx b/apps/mes/app/entry.server.tsx
index a4b9cc1e45..86f4722fe6 100644
--- a/apps/mes/app/entry.server.tsx
+++ b/apps/mes/app/entry.server.tsx
@@ -7,17 +7,26 @@ import {
getNonce,
setStrictContentSecurityPolicy
} from "@carbon/auth/middleware/security.server";
+import { getProcessPool } from "@carbon/database/client";
import { getLogger } from "@carbon/logger";
import { ensureLoggingConfigured } from "@carbon/logger/config.server";
import { getRequestId } from "@carbon/logger/middleware.server";
import { createTracing } from "@carbon/logger/tracing.server";
-import { waitUntil } from "@vercel/functions";
+import { async } from "@carbon/utils";
+import { attachDatabasePool, waitUntil } from "@vercel/functions";
import { handleRequest as vercelHandleRequest } from "@vercel/react-router/entry.server";
import type { EntryContext, RouterContextProvider } from "react-router";
import { isRouteErrorResponse } from "react-router";
ensureLoggingConfigured();
+// Vercel freezes an instance once its response is sent: keep it up until idle
+// database connections have closed and background work has finished.
+if (process.env.VERCEL) {
+ attachDatabasePool(getProcessPool());
+ async.onBackground(waitUntil);
+}
+
export const instrumentations = createTracing({
serviceName: "carbon-mes",
// Vercel can suspend the instance once the response is sent.
diff --git a/apps/mes/app/root.tsx b/apps/mes/app/root.tsx
index 2b0be4bbd1..0a807822d4 100644
--- a/apps/mes/app/root.tsx
+++ b/apps/mes/app/root.tsx
@@ -13,11 +13,8 @@ import {
import { securityMiddleware } from "@carbon/auth/middleware/security.server";
import { validator } from "@carbon/form";
import { LocaleProvider, resolveLanguage } from "@carbon/locale";
-import {
- requestContextMiddleware,
- requestIdMiddleware
-} from "@carbon/logger/middleware.server";
-import { namedMiddleware } from "@carbon/logger/tracing.server";
+import { requestMiddleware } from "@carbon/logger/middleware.server";
+import { timedMiddleware } from "@carbon/logger/tracing.server";
import {
OperatingSystemContextProvider,
Toaster,
@@ -64,13 +61,12 @@ import "@carbon/lib/shims";
import type { Route } from "./+types/root";
import { getTheme } from "./services/theme.server";
-export const middleware = namedMiddleware([
- // First: publishes the request context so server code can reach it via ALS.
- requestContextMiddleware,
- requestIdMiddleware,
- securityMiddleware,
- flashMiddleware
-]);
+export const middleware = timedMiddleware({
+ // First: the request scope (context, request id, access log).
+ request: requestMiddleware,
+ security: securityMiddleware,
+ flash: flashMiddleware
+});
export const clientMiddleware = [flashClientMiddleware];
export const links: Route.LinksFunction = () => [
diff --git a/apps/mes/app/services/database.server.ts b/apps/mes/app/services/database.server.ts
index db59f773fc..c716082f7c 100644
--- a/apps/mes/app/services/database.server.ts
+++ b/apps/mes/app/services/database.server.ts
@@ -8,15 +8,12 @@
* Polluting the global namespace like this is usually discouraged, but it's okay as we're just caching connections during development.
* In production, this code path is not hit multiple times as ESM modules are only singletons by default.
*/
-import {
- getPostgresClient,
- getPostgresConnectionPool
-} from "@carbon/database/client";
-import { queryLog } from "@carbon/logger/tracing.server";
+import { getPostgresClient, getProcessPool } from "@carbon/database/client";
+import { queryLog, traceConnectionWaits } from "@carbon/logger/tracing.server";
import { PostgresDriver } from "kysely";
const init = () => {
- const pool = getPostgresConnectionPool(10);
+ const pool = traceConnectionWaits(getProcessPool());
// We use the PostgresDriver from Kysely here as this code only runs in Node environment
return getPostgresClient(pool, PostgresDriver, queryLog);
};
diff --git a/packages/auth/AGENTS.md b/packages/auth/AGENTS.md
index 5292ccb744..25f4666811 100644
--- a/packages/auth/AGENTS.md
+++ b/packages/auth/AGENTS.md
@@ -7,6 +7,7 @@ Authentication, RBAC, session management, Supabase client factories, API key aut
- Gate loaders/actions with `requirePermissions(request, { view?, create?, update?, delete? })` — never construct Supabase clients directly in routes.
- `requirePermissions` refuses customer and supplier portal sessions with a 403 (API keys are unaffected). `{}` used to admit them everywhere, and ~50 routes that then read with the service role were reachable by a portal account. Pass `allowPortalAccounts: true` ONLY on a route that acts on the user's own identity (onboarding, company switch, notification links, academy progress) — never on one that returns company data.
- Use the factory from `@carbon/auth/client.server`: `getCarbon(accessToken)` for user-scoped (RLS), `getCarbonServiceRole()` for privileged server ops only.
+- Every server client built while a request is being handled is bound to it through `requestFetch()` (`lib/supabase/client.server.ts`): all of that request's clients share one limit of 8 calls in flight (a wait for a slot is a `supabase slot wait` span), and on a GET/HEAD request their reads (PostgREST GET/HEAD, storage reads) are cancelled when the request is. RPCs, table writes, auth and edge-function calls are never cancelled. Outside a request (jobs, scripts) `requestFetch()` is `undefined` and the client is unbound. A new client factory must pass `requestFetch()` too, or its calls escape both.
- Invalidate Redis permission cache (`redis.del(getPermissionCacheKey(userId))`) when changing user permissions — stale cache is the #1 cause of "Access Denied" bugs.
- API key `scopes: {}` **denies all** — never treat empty scopes as full access.
- Import env constants from `@carbon/auth` (re-exports `@carbon/env`) — not `process.env` directly.
diff --git a/packages/auth/src/lib/supabase/client.server.ts b/packages/auth/src/lib/supabase/client.server.ts
index c0cdfc0fd4..0b7a745cf3 100644
--- a/packages/auth/src/lib/supabase/client.server.ts
+++ b/packages/auth/src/lib/supabase/client.server.ts
@@ -3,16 +3,83 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import type { Database } from "@carbon/database";
+import {
+ currentRequest,
+ isReadRequest,
+ oncePerRequest
+} from "@carbon/logger/middleware.server";
+import { startSpan } from "@carbon/logger/tracing.server";
+import { async } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
import { SignJWT } from "jose";
import {
+ SUPABASE_ANON_KEY,
SUPABASE_JWT_SECRET,
SUPABASE_SERVICE_ROLE_KEY
} from "../../config/env";
-import { getCarbon, getCarbonClient } from "./client";
+import {
+ getCarbonClient,
+ isStorageRead,
+ storageReadFetch,
+ urlAndMethod
+} from "./client";
+
+// How many Supabase calls one request has in flight at once, across every
+// client it builds — its share of PostgREST's connections, like an HTTP
+// agent's maxSockets.
+const REQUEST_CONCURRENCY = 8;
+
+// A select (or an RPC called with `{ get: true }`) or a storage read. Not a
+// POST RPC: some write, and a write cut off mid-call may or may not have
+// committed. Not a table write either: some GET routes write (an OAuth
+// callback saving its tokens), and that must finish.
+const isRead = (url: string, method: string) =>
+ isStorageRead(url, method) ||
+ (url.includes("/rest/v1/") && (method === "GET" || method === "HEAD"));
+
+/**
+ * The fetch for a client built while handling `request` (by default the one
+ * being handled; undefined outside a request, for jobs' own work and scripts).
+ *
+ * - Every call waits for one of REQUEST_CONCURRENCY slots, shared by all the
+ * clients of the request, so `Promise.all` over a page's queries cannot take
+ * every connection. A call never waits on another, so this cannot deadlock.
+ * A call that has to queue records the wait as a `supabase slot wait` span,
+ * or the request would look slow with fast queries.
+ * - On a read request, selects and storage reads stop when `request.signal`
+ * aborts — the browser has gone. RPCs, table writes, auth and edge function
+ * calls run to the end.
+ */
+export function requestFetch(
+ request = currentRequest()
+): typeof fetch | undefined {
+ if (!request) return undefined;
+ const limit = oncePerRequest("supabase:limit", () =>
+ async.limit(REQUEST_CONCURRENCY)
+ );
+ const signal = isReadRequest(request) ? request.signal : undefined;
+ return (input, init) => {
+ const started =
+ limit.activeCount < REQUEST_CONCURRENCY
+ ? undefined
+ : startSpan("supabase slot wait", {
+ "carbon.request.calls_waiting": limit.pendingCount + 1
+ });
+ return limit(() => {
+ started?.();
+ const { url, method } = urlAndMethod(input, init);
+ if (!signal || !isRead(url, method)) return storageReadFetch(input, init);
+ return storageReadFetch(input, {
+ ...init,
+ signal: init?.signal ? AbortSignal.any([init.signal, signal]) : signal
+ });
+ });
+ };
+}
+/** Bound to the request being handled, if any — see `requestFetch`. */
export const getCarbonServiceRole = (): SupabaseClient<Database> => {
- return getCarbonClient(SUPABASE_SERVICE_ROLE_KEY!);
+ return getCarbonClient(SUPABASE_SERVICE_ROLE_KEY!, undefined, requestFetch());
};
export async function getUserScopedClient(
@@ -37,5 +104,5 @@ export async function getUserScopedClient(
.setExpirationTime("5m")
.sign(secret);
- return getCarbon(jwt);
+ return getCarbonClient(SUPABASE_ANON_KEY!, jwt, requestFetch());
}
diff --git a/packages/auth/src/lib/supabase/client.test.ts b/packages/auth/src/lib/supabase/client.test.ts
index 117f927d84..e666477723 100644
--- a/packages/auth/src/lib/supabase/client.test.ts
+++ b/packages/auth/src/lib/supabase/client.test.ts
@@ -12,8 +12,162 @@ vi.mock("../../config/env", () => ({
SUPABASE_URL: "http://supabase.test"
}));
+const waitEnded = vi.fn();
+const startSpan = vi.fn((_name: string, _attributes: object) => waitEnded);
+vi.mock("@carbon/logger/tracing.server", () => ({ startSpan }));
+
const { getCarbonAPIKeyClient, getCarbonClient, storageReadFetch } =
await import("./client");
+const { requestFetch } = await import("./client.server");
+const { requestContextMiddleware } = await import(
+ "@carbon/logger/middleware.server"
+);
+const { RouterContextProvider } = await import("react-router");
+
+// A loader's client carries its request's signal: once the browser has gone,
+// what the loader still wants from the database is not worth fetching.
+// A client serving one request is bound to it: a share of PostgREST's
+// connections, and on a read, the request's abort signal.
+describe("a client bound to a request", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ startSpan.mockClear();
+ waitEnded.mockClear();
+ });
+
+ // Resolves only when its signal aborts, as a slow query would.
+ const hangingFetch = () =>
+ vi.fn(
+ (_input: RequestInfo | URL, init?: RequestInit) =>
+ new Promise<Response>((_, reject) => {
+ const fail = () =>
+ reject(
+ new DOMException("This operation was aborted", "AbortError")
+ );
+ if (init?.signal?.aborted) return fail();
+ init?.signal?.addEventListener("abort", fail);
+ })
+ );
+
+ const pageLoad = (controller: AbortController, method = "GET") =>
+ new Request("http://erp.test/x/part/1", {
+ method,
+ signal: controller.signal
+ });
+
+ it("has at most 8 calls in flight", async () => {
+ const fetchMock = hangingFetch();
+ vi.stubGlobal("fetch", fetchMock);
+ const controller = new AbortController();
+ const client = getCarbonClient(
+ "anon",
+ "user-jwt",
+ requestFetch(pageLoad(controller))
+ );
+
+ const calls = Array.from({ length: 12 }, () =>
+ client.from("item").select("id")
+ ).map((query) => query.then((result) => result));
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ expect(fetchMock).toHaveBeenCalledTimes(8);
+ // The four that queued each opened a wait span, still open.
+ expect(startSpan).toHaveBeenCalledTimes(4);
+ expect(startSpan).toHaveBeenLastCalledWith("supabase slot wait", {
+ "carbon.request.calls_waiting": 4
+ });
+ expect(waitEnded).not.toHaveBeenCalled();
+
+ controller.abort();
+ await Promise.all(calls);
+ expect(waitEnded).toHaveBeenCalledTimes(4);
+ });
+
+ it("shares the limit between every client built during the request", async () => {
+ const fetchMock = hangingFetch();
+ vi.stubGlobal("fetch", fetchMock);
+ const controller = new AbortController();
+ await requestContextMiddleware(
+ {
+ request: pageLoad(controller),
+ context: new RouterContextProvider(),
+ params: {},
+ unstable_pattern: ""
+ } as never,
+ async () => {
+ // A user client and a service-role client, each built without the
+ // request in hand, as a service deep in a loader would.
+ const user = getCarbonClient("anon", "user-jwt", requestFetch());
+ const service = getCarbonClient("service", undefined, requestFetch());
+ const calls = Array.from({ length: 6 }, () => [
+ user.from("item").select("id"),
+ service.from("item").select("id")
+ ])
+ .flat()
+ .map((query) => query.then((result) => result));
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ expect(fetchMock).toHaveBeenCalledTimes(8);
+ controller.abort();
+ await Promise.all(calls);
+ return new Response();
+ }
+ );
+ });
+
+ it("stops a read in flight when the browser leaves, without retrying, and fails later ones at once", async () => {
+ const fetchMock = hangingFetch();
+ vi.stubGlobal("fetch", fetchMock);
+ const controller = new AbortController();
+ const client = getCarbonClient(
+ "anon",
+ "user-jwt",
+ requestFetch(pageLoad(controller))
+ );
+
+ const pending = client.from("item").select("id");
+ setTimeout(() => controller.abort(), 5);
+ const first = await pending;
+ expect(first.error?.message).toContain("AbortError");
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+
+ const second = await client.from("job").select("id");
+ expect(second.error?.message).toContain("AbortError");
+ });
+
+ it("leaves RPCs, table writes, auth and edge function calls alone, and every call of an action", async () => {
+ const fetchMock = vi.fn(
+ async (_input: RequestInfo | URL, _init?: RequestInit) =>
+ new Response("{}", { status: 200 })
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const controller = new AbortController();
+ controller.abort();
+
+ const read = getCarbonClient(
+ "anon",
+ "user-jwt",
+ requestFetch(pageLoad(controller))
+ );
+ const invoked = await read.functions.invoke("create", { body: {} });
+ expect(invoked.error).toBeNull();
+ const written = await read.from("item").update({ name: "x" }).eq("id", "1");
+ expect(written.error).toBeNull();
+ const rpc = await read.rpc("get_part_details", { item_id: "x" });
+ expect(rpc.error).toBeNull();
+
+ const action = getCarbonClient(
+ "anon",
+ "user-jwt",
+ requestFetch(pageLoad(controller, "POST"))
+ );
+ const selected = await action.from("item").select("id");
+ expect(selected.error).toBeNull();
+
+ for (const [, init] of fetchMock.mock.calls) {
+ expect(init?.signal?.aborted ?? false).toBe(false);
+ }
+ expect(fetchMock).toHaveBeenCalledTimes(4);
+ });
+});
// Edge functions recognise a service-role caller by the Authorization bearer.
// supabase-js stops sending a new-format key as that bearer on function calls,
diff --git a/packages/auth/src/lib/supabase/client.ts b/packages/auth/src/lib/supabase/client.ts
index d8aa5c3b4c..e66104ebd0 100644
--- a/packages/auth/src/lib/supabase/client.ts
+++ b/packages/auth/src/lib/supabase/client.ts
@@ -26,17 +26,21 @@ const STORAGE_BACKOFF_MS = [500, 1000];
// response headers and two retries on a 5xx or a dropped connection. The body
// itself is not timed, so a large download is never cut off. Uploads, deletes
// and everything outside storage pass straight through.
-const isStorageRead = (url: string, method: string) =>
+export const isStorageRead = (url: string, method: string) =>
url.includes("/storage/v1/") &&
(method === "GET" ||
method === "HEAD" ||
(method === "POST" && url.includes("/storage/v1/object/list")));
-export const storageReadFetch: typeof fetch = async (input, init) => {
- const url = input instanceof Request ? input.url : String(input);
- const method = (
+export const urlAndMethod = (input: RequestInfo | URL, init?: RequestInit) => ({
+ url: input instanceof Request ? input.url : String(input),
+ method: (
init?.method ?? (input instanceof Request ? input.method : "GET")
- ).toUpperCase();
+ ).toUpperCase()
+});
+
+export const storageReadFetch: typeof fetch = async (input, init) => {
+ const { url, method } = urlAndMethod(input, init);
if (!isStorageRead(url, method)) return fetch(input, init);
for (let attempt = 0; ; attempt++) {
@@ -61,9 +65,11 @@ export const storageReadFetch: typeof fetch = async (input, init) => {
}
};
+/** `fetch` replaces `storageReadFetch` — on the server, `requestFetch()`. */
export const getCarbonClient = (
supabaseKey: string,
- accessToken?: string
+ accessToken?: string,
+ fetch: typeof globalThis.fetch = storageReadFetch
): SupabaseClient<Database, "public"> => {
// Always explicit. Left to supabase-js, a new-format key (`sb_secret_…`) is
// not sent as the bearer on Edge Function calls, and those functions tell a
@@ -79,7 +85,7 @@ export const getCarbonClient = (
autoRefreshToken: false,
persistSession: false
},
- global: { headers, fetch: storageReadFetch }
+ global: { headers, fetch }
}
);
@@ -87,12 +93,13 @@ export const getCarbonClient = (
};
export const getCarbonAPIKeyClient = (
- apiKey: string
+ apiKey: string,
+ fetch: typeof globalThis.fetch = storageReadFetch
): SupabaseClient<Database, "public"> => {
const client = createClient(SUPABASE_INTERNAL_URL!, SUPABASE_ANON_KEY!, {
db,
global: {
- fetch: storageReadFetch,
+ fetch,
headers: {
Authorization: `Bearer ${SUPABASE_ANON_KEY}`,
"carbon-key": apiKey
diff --git a/packages/auth/src/services/auth.server.ts b/packages/auth/src/services/auth.server.ts
index f21ba32d35..e8871a5e03 100644
--- a/packages/auth/src/services/auth.server.ts
+++ b/packages/auth/src/services/auth.server.ts
@@ -22,11 +22,15 @@ import {
IS_LOCAL_DEV,
REFRESH_ACCESS_TOKEN_THRESHOLD,
STRIPE_BYPASS_COMPANY_IDS,
+ SUPABASE_ANON_KEY,
VERCEL_URL
} from "../config/env";
import { getCarbon } from "../lib/supabase";
-import { getCarbonAPIKeyClient } from "../lib/supabase/client";
-import { getCarbonServiceRole } from "../lib/supabase/client.server";
+import { getCarbonAPIKeyClient, getCarbonClient } from "../lib/supabase/client";
+import {
+ getCarbonServiceRole,
+ requestFetch
+} from "../lib/supabase/client.server";
import type { AuthSession } from "../types";
import { path } from "../utils/path";
import { error } from "../utils/result";
@@ -47,9 +51,12 @@ const log = getLogger("auth");
export { logAuthEvent } from "./auth-events.server";
// Each matched loader used to build its own Supabase client for identical
-// credentials; `createClient` is not free and they are interchangeable.
-const carbonForRequest = (accessToken: string) =>
- oncePerRequest(`carbon:${accessToken}`, () => getCarbon(accessToken));
+// credentials; `createClient` is not free and they are interchangeable. Both are
+// bound to the request (`requestFetch`).
+const carbonForRequest = (accessToken: string, request: Request) =>
+ oncePerRequest(`carbon:${accessToken}`, () =>
+ getCarbonClient(SUPABASE_ANON_KEY!, accessToken, requestFetch(request))
+ );
const serviceRoleForRequest = () =>
oncePerRequest("carbon:service-role", () => getCarbonServiceRole());
@@ -330,7 +337,7 @@ export async function requirePermissions(
}
}
- const client = getCarbonAPIKeyClient(apiKey);
+ const client = getCarbonAPIKeyClient(apiKey, requestFetch(request));
return {
client,
@@ -377,7 +384,7 @@ export async function requirePermissions(
client:
requiredPermissions.bypassRls && myClaims.role === "employee"
? serviceRoleForRequest()
- : carbonForRequest(accessToken),
+ : carbonForRequest(accessToken, request),
companyId,
companyGroupId,
email,
@@ -439,7 +446,7 @@ export async function requirePermissions(
client:
!!requiredPermissions.bypassRls && myClaims.role === "employee"
? serviceRoleForRequest()
- : carbonForRequest(accessToken),
+ : carbonForRequest(accessToken, request),
companyId,
companyGroupId,
email,
diff --git a/packages/checks/AGENTS.md b/packages/checks/AGENTS.md
index d0b8a732c3..08f5cdb0b7 100644
--- a/packages/checks/AGENTS.md
+++ b/packages/checks/AGENTS.md
@@ -32,10 +32,10 @@ pnpm --filter @carbon/checks baseline # regenerate baseline (careful!)
## Key Patterns
- **Conformance checks**: `noNumericPrecision`, `noLegacyRls`, `noDerivedPercentColumn`, `noRequiredColumnWithoutDefault`, `noViewWithoutInvoker` — scan SQL migrations for anti-patterns (`noDerivedPercentColumn` flags a `*Percent`/`*Rate` column `GENERATED ALWAYS AS` an expression that divides — a percentage is an entered fact, never a lossy echo of a rounded amount; `noViewWithoutInvoker` fails a `CREATE [OR REPLACE] VIEW` that does not state `security_invoker` — `CREATE OR REPLACE` replaces a view's options, so omitting the clause turns it into an owner-rights view that bypasses RLS for every PostgREST caller, and `openJobMaterialLines` leaked every company's rows that way. `security_invoker = false` passes, so an owner-rights view is a visible decision; materialized views are not matched. It reads one file's text, so an `EXECUTE format(...)` view or a later `ALTER VIEW … RESET` escapes it — the invariant below is the backstop); `noLocalTimezone` (in `SERVER_CHECKS`) scans server TS (`sources/server-files.ts`) for `getLocalTimeZone()`, UTC day-slicing, local date-parts of now (`new Date().getDay()` etc.), and `setHours(0,0,0,0)` midnights. Scanned files: MES services, `packages/jobs`, edge functions, ERP module `.service.ts`/`.server.ts`, **plus both apps' route trees** — route modules are server AND client in one file, so `maskClientCode` blanks the browser half (default export, `clientLoader`/`clientAction`, PascalCase/`use*` declarations) while keeping loaders, actions, and the module-level helpers they call
-- **Authz ownership** (`CONFORMANCE_CHECKS` via `collectFindings`): `noAuthzDdlInMigrations(helpers)` fails a migration newer than `20260927000000` that runs `CREATE`/`ALTER POLICY` on a public table (storage bucket policies stay allowed), or defines, alters or drops a managed RLS helper — policies live in `packages/database/src/authz/manifest.ts`, helpers in `packages/database/src/authz/helpers/<name>.sql`, and `authz sync` applies both after migrations. The helper list is read from that directory (`loadAuthzHelperNames`), so it cannot drift from the files. `DROP POLICY` is allowed (dropping a column a policy uses). Files starting with the `authz migration` header are exempt; `@carbon/database`'s `migration.test.ts` verifies their contents. Older migrations are history, so there are no baseline entries
+- **Authz ownership** (`CONFORMANCE_CHECKS` via `collectFindings`): `noAuthzDdlInMigrations(functions)` fails a migration newer than `20260927000000` that runs `CREATE`/`ALTER POLICY` on a public table (storage bucket policies stay allowed), or defines, alters or drops a managed function — policies live in `packages/database/src/authz/manifest.ts`, RLS helpers in `packages/database/src/authz/helpers/<name>.sql`, event-system functions in `packages/database/src/event-system/functions/<name>.sql` (`util.<name>.sql` outside `public`; checked from `20261002114954`, the migration that took them over), and `authz sync` applies all of them after migrations. The function list is read from those directories (`loadManagedFunctions`, one cutoff per directory in `MANAGED_FUNCTION_SETS`), so it cannot drift from the files. `DROP POLICY` is allowed (dropping a column a policy uses). Files starting with the `authz migration` header are exempt; `@carbon/database`'s `migration.test.ts` verifies their contents. Older migrations are history, so there are no baseline entries
- **Forwarded headers** (own source, `REQUEST_HANDLING_ROOTS`: every app + auth, ee, jobs, lib, utils, edge functions): `noRawForwardedHeaders` fails a raw read of `X-Forwarded-For/-Host/-Proto` or `X-Real-IP` outside `packages/utils/src/headers.ts` — use `getClientIp` / `getRequestProtocol` / `getRequestHost` / `getRequestOrigin`. Hand-rolled reads keyed login rate limits and ITAR audit records on the forgeable first `X-Forwarded-For` entry. No baseline entries
- **Numeric-precision checks** (in `TS_CHECKS`, over `sources/typescript.ts`): `noRawRounding` flags `Math.round/ceil/floor` and `.toFixed` on value-bearing numbers (use `round`/`scrapAllowance`/`applyRate`/`deriveRate` from `@carbon/utils`); `noInlineFractionDigits` flags `minimum`/`maximumFractionDigits` at a call site (pick a named kind from `@carbon/utils` `format.ts`, and `INPUT_FORMAT.*` for anything editable); `noUnroundedTrackedQuantity` flags inline unrounded arithmetic inside a `.updateTable("trackedEntity")` statement's `quantity:` set, and a raw `===`/`!==`/`<` compare against a `*[Ee]ntity*.quantity` read (use `round`/`settleQuantity` at the write, `isFullDraw` at a split gate — see `.claude/rules/traceability-model.md`). It is scoped to what one file can prove: a `quantity:` set from an already-rounded variable is unflaggable either way, and a compare of two locals is presumed rounded where they were defined. It has **no baseline entries** — the whole tree was fixed in the pass that added it, so any finding is new. `sources/typescript.ts` walks `apps/erp/app/{components,hooks,modules,routes}`, `apps/mes/app`, `packages/database/supabase/functions`, `packages/{ee,jobs}/src`, `packages/documents/src/{pdf,utils}` and the shared packages `packages/{utils,form,react,printing,workflows}/src` — tests and the image/logo resizers excluded. The shared packages matter: `@carbon/utils` is where the standard's own helpers live, and `form`/`react` own the number inputs whose `formatOptions` are part of the storage round-trip. See `.claude/rules/numeric-precision.md`
-- **Missing audit columns** (built in `collectFindings`, not `TS_CHECKS`): `noMissingAuditColumn(columns)` fails a write that names `createdBy`/`updatedBy` on a relation that has no such column — PostgREST rejects the whole statement (`PGRST204 Could not find the 'createdBy' column of '<table>'`) and TypeScript does not flag it, because supabase-js widens the insert/upsert argument enough for the excess property to survive. That is how the `customerPartToItem` upsert in `sales-rfq.$rfqId.map-lines.ts` shipped with an unchecked result, so every RFQ-line → customer-part mapping silently failed. Roughly a third of Carbon's tables have no audit columns (favourites, link tables, the lean material lookups, `companySettings`) while golden rule 3 says to include them, so it is an easy assumption to carry into the wrong table. It takes the column map as an ARGUMENT — `loadDbTableColumns(root)` (`sources/db-columns.ts`) reads the generated `packages/database/src/types.ts` `Row:` blocks, so the I/O stays in `sources/` and `scan` stays pure, the same shape as `noAuthzDdlInMigrations(loadAuthzHelperNames(root))`. Scope is the LITERAL argument of the write (`.from`/`insertInto`/`updateTable` + `.insert`/`.upsert`/`.update`/`.values`/`.set`); a payload object spread into the row is invisible here, and for the MCP/API layer that same generated schema drives `withoutAbsentAuditColumns` in `scripts/lib/service-metadata.ts`. No baseline entries — the one hit was fixed when it was added
+- **Missing audit columns** (built in `collectFindings`, not `TS_CHECKS`): `noMissingAuditColumn(columns)` fails a write that names `createdBy`/`updatedBy` on a relation that has no such column — PostgREST rejects the whole statement (`PGRST204 Could not find the 'createdBy' column of '<table>'`) and TypeScript does not flag it, because supabase-js widens the insert/upsert argument enough for the excess property to survive. That is how the `customerPartToItem` upsert in `sales-rfq.$rfqId.map-lines.ts` shipped with an unchecked result, so every RFQ-line → customer-part mapping silently failed. Roughly a third of Carbon's tables have no audit columns (favourites, link tables, the lean material lookups, `companySettings`) while golden rule 3 says to include them, so it is an easy assumption to carry into the wrong table. It takes the column map as an ARGUMENT — `loadDbTableColumns(root)` (`sources/db-columns.ts`) reads the generated `packages/database/src/types.ts` `Row:` blocks, so the I/O stays in `sources/` and `scan` stays pure, the same shape as `noAuthzDdlInMigrations(loadManagedFunctions(root))`. Scope is the LITERAL argument of the write (`.from`/`insertInto`/`updateTable` + `.insert`/`.upsert`/`.update`/`.values`/`.set`); a payload object spread into the row is invisible here, and for the MCP/API layer that same generated schema drives `withoutAbsentAuditColumns` in `scripts/lib/service-metadata.ts`. No baseline entries — the one hit was fixed when it was added
- **Tenant-scoped Kysely writes** (in `TS_CHECKS`): `noUnscopedKyselyWrite` fails any `.updateTable(`/`.deleteFrom(` under `apps/erp/app/{modules,routes}`, `apps/mes/app` or `packages/jobs/src` whose statement (up to `.execute…(`/`.compile(`/`;`/`,` at depth 0, comments blanked) has no `.where("companyId", …)` / `.where("alias.companyId", …)`. Kysely is the superuser connection, and the public API hands a service's `db` param that same client, so the statement's own predicate is the only tenant boundary — ten drag-sort services (`updateQuoteLineOrder` and friends) were a reported cross-tenant write because they keyed on `id` alone. `company` is exempt (its `id` is the tenant); a `companyId` in `.set()` does not count; a link table with no `companyId` column passes by scoping through its parent in a subquery. Edge functions and `packages/ee` are out of scope (see the file header). One baseline entry: the `companyGroup` delete in `packages/jobs/.../scheduled/purge-company.ts` (a group has no `companyId` column; its `id` is the tenant-group key). Every other hit was fixed when it was added
- **Unguarded submit buttons** (in `TS_CHECKS`, `.tsx` only): `noUnguardedSubmit` fails a `<Button>`/`<button>`/`<IconButton>` carrying `type="submit"` whose own opening tag names no in-flight signal (`isLoading`, `isSubmitting`, `isPending`, `isSaving`, `useIsSubmitting`, or a `*fetcher|navigation|transition*.state` read). A live submit button posts again on every click and each POST runs to completion server-side — `fetcher.submit` aborts the previous BROWSER request, but no route action reads `request.signal` — which is how one quote finalize emailed the customer the same PDF three times. It parses the real opening tag (brace- and quote-aware), so a guard written after `type="submit"` still counts and a `>` inside `{a > b}` does not end the tag early. **The presence of `isDisabled` is deliberately not enough**: the incident's button was `isDisabled={loading}` where `loading` was the modal's data-fetch flag, so a check that accepted any `isDisabled` would have passed the exact line it exists to catch; word boundaries matter too (`loading` must not satisfy `isLoading`). Buttons inside a `<ValidatedForm>` are skipped — `ValidatedForm.handleSubmit` drops a re-entrant submit, so a second click cannot produce a second POST however the button is written. `packages/form/src/components/Submit.tsx` is excluded; it IS the guard. The check cannot do dataflow, so a guard held in a differently-named local (`disabled={busy}`) is baselined rather than rewritten. 32 baseline entries, all reviewed: logout/company-switch/theme/console-toggle (idempotent), delete and rule-unassign (a second delete is a no-op), the two chat composers (guarded by a `flushSync` clear plus an empty-message return), and `ConfiguratorForm` (its submit is an `onSubmit` callback — the in-flight state lives at the caller)
- **Edge-function auth** (`EDGE_FUNCTION_CHECKS`): `edgeFunctionAuthorizesCaller` fails any function under `packages/database/supabase/functions/` that never calls `requirePermissions` / `requireCaller` / `requireServiceRole` / `getSupabaseServiceRole`, because `verify_jwt` accepts the published anon key. `ALLOWED` in the check holds the functions that are correct without one, each with its reason (`logo-resizer`, `transcription`). `embed`, `event-wake` and `trigger` are baselined, not allowed: Postgres calls them over pg_net with the anon key from `config`, so gating them needs a migration that makes Postgres send a server credential first
diff --git a/packages/checks/src/conformance/no-authz-ddl-in-migrations.test.ts b/packages/checks/src/conformance/no-authz-ddl-in-migrations.test.ts
index e9c0fca764..321a724200 100644
--- a/packages/checks/src/conformance/no-authz-ddl-in-migrations.test.ts
+++ b/packages/checks/src/conformance/no-authz-ddl-in-migrations.test.ts
@@ -11,8 +11,28 @@ import {
noAuthzDdlInMigrations
} from "./no-authz-ddl-in-migrations";
-const check = noAuthzDdlInMigrations(["get_companies_with_employee_role"]);
+const check = noAuthzDdlInMigrations([
+ {
+ schema: "public",
+ name: "get_companies_with_employee_role",
+ file: "packages/database/src/authz/helpers/get_companies_with_employee_role.sql",
+ since: "20260927000000"
+ },
+ {
+ schema: "public",
+ name: "dispatch_event_batch",
+ file: "packages/database/src/event-system/functions/dispatch_event_batch.sql",
+ since: "20261002114954"
+ },
+ {
+ schema: "util",
+ name: "wake_event_queue",
+ file: "packages/database/src/event-system/functions/util.wake_event_queue.sql",
+ since: "20261002114954"
+ }
+]);
const NEW = "20260928120000_widget.sql";
+const AFTER_EVENT_TAKEOVER = "20261003120000_widget.sql";
describe("noAuthzDdlInMigrations", () => {
it("flags CREATE POLICY and ALTER POLICY in a new migration", () => {
@@ -45,6 +65,34 @@ DROP FUNCTION IF EXISTS get_companies_with_employee_role();`;
expect(check.scan(NEW, sql)).toHaveLength(3);
});
+ it("flags an event-system function, in public or util, after its takeover", () => {
+ const sql = `CREATE OR REPLACE FUNCTION public.dispatch_event_batch() RETURNS trigger AS $$ $$;
+CREATE OR REPLACE FUNCTION util.wake_event_queue() RETURNS void AS $$ $$;`;
+ const found = check.scan(AFTER_EVENT_TAKEOVER, sql);
+ expect(found.map((v) => v.line)).toEqual([1, 2]);
+ expect(found[1]?.message).toContain("util.wake_event_queue.sql");
+ });
+
+ it("leaves event-system migrations from before the takeover as history", () => {
+ const sql =
+ "CREATE OR REPLACE FUNCTION public.dispatch_event_batch() RETURNS trigger AS $$ $$;";
+ expect(
+ check.scan(
+ "20261001195204_event-dispatch-skip-unchanged-updates.sql",
+ sql
+ )
+ ).toEqual([]);
+ });
+
+ it("tells a managed function from its namesake in another schema", () => {
+ expect(
+ check.scan(
+ AFTER_EVENT_TAKEOVER,
+ "CREATE OR REPLACE FUNCTION public.wake_event_queue() RETURNS void AS $$ $$;"
+ )
+ ).toEqual([]);
+ });
+
it("allows any other function", () => {
expect(
check.scan(
diff --git a/packages/checks/src/conformance/no-authz-ddl-in-migrations.ts b/packages/checks/src/conformance/no-authz-ddl-in-migrations.ts
index b17d4a588d..e1d76c0795 100644
--- a/packages/checks/src/conformance/no-authz-ddl-in-migrations.ts
+++ b/packages/checks/src/conformance/no-authz-ddl-in-migrations.ts
@@ -5,19 +5,41 @@
import type { ConformanceCheck, Violation } from "../check";
/**
- * RLS policies and the RLS/auth helper functions are authored only in
- * packages/database/src/authz (manifest + helpers/<name>.sql), and `authz sync` applies
- * them after migrations. A migration that creates or alters a policy, or defines, alters
- * or drops a managed helper, would be silently overwritten at the next sync — or, for a
- * helper, reintroduce exactly the drift the manifest exists to stop (a redefinition once
- * turned get_companies_with_employee_permission from STABLE back to VOLATILE).
+ * RLS policies and the managed functions are authored only as files — the manifest and
+ * packages/database/src/authz/helpers/<name>.sql for RLS, and
+ * packages/database/src/event-system/functions/<name>.sql for the event system — and
+ * `authz sync` applies them after migrations. A migration that creates or alters a policy,
+ * or defines, alters or drops a managed function, would be silently overwritten at the next
+ * sync — or reintroduce exactly the drift the files exist to stop (a redefinition once
+ * turned get_companies_with_employee_permission from STABLE back to VOLATILE; a fork of
+ * create_audit_log_table made every audit write run DDL).
*
* `DROP POLICY` stays allowed: dropping a column a policy uses needs the policy gone
* first, and the next sync recreates the table's policies from the manifest.
*
- * Only migrations after the manifest took over are checked; older ones are history.
+ * Only migrations after a set was taken over are checked; older ones are history.
*/
const SINCE = "20260927000000";
+/** The migration that took over the event-system functions. */
+const EVENT_SYSTEM_SINCE = "20261002114954";
+
+/** The directories of managed function files, and the migration each set is checked from. */
+export const MANAGED_FUNCTION_SETS = [
+ { dir: "packages/database/src/authz/helpers", since: SINCE },
+ {
+ dir: "packages/database/src/event-system/functions",
+ since: EVENT_SYSTEM_SINCE
+ }
+];
+
+/** `file` is `<name>.sql` for public, `<schema>.<name>.sql` otherwise. */
+export type ManagedFunction = {
+ schema: string;
+ name: string;
+ /** Repo-relative path of the file that defines it. */
+ file: string;
+ since: string;
+};
/**
* The first line of a migration rendered from the manifest by `authz migration` — the WHOLE
@@ -29,7 +51,8 @@ const SINCE = "20260927000000";
export const GENERATED_AUTHZ_MIGRATION =
"-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.";
-const NAME = String.raw`(?:(?:"?public"?)\s*\.\s*)?"?(\w+)"?`;
+// Group 2 is the schema when the statement names one, group 3 the function.
+const NAME = String.raw`(?:"?(\w+)"?\s*\.\s*)?"?(\w+)"?`;
// The target may be on a later line; group 2 is its schema, when it names one. The manifest
// owns public tables only, so storage.objects (bucket) policies stay in migrations.
const POLICY_DDL =
@@ -46,14 +69,15 @@ const stripComments = (sql: string) =>
.replace(/--[^\n]*/g, (m) => " ".repeat(m.length));
export const noAuthzDdlInMigrations = (
- helpers: string[]
+ functions: ManagedFunction[]
): ConformanceCheck => ({
id: "no-authz-ddl-in-migrations",
description:
- "Policies and RLS helpers are authored in packages/database/src/authz, not migrations.",
+ "Policies, RLS helpers and event-system functions are authored as files, not migrations.",
provenance: {
- deprecates: "CREATE/ALTER POLICY and managed helper DDL in migrations",
- replacedBy: "packages/database/src/authz (manifest.ts + helpers/*.sql)",
+ deprecates: "CREATE/ALTER POLICY and managed function DDL in migrations",
+ replacedBy:
+ "packages/database/src/authz (manifest.ts + helpers/*.sql) and packages/database/src/event-system/functions/*.sql",
since: SINCE
},
scan(file, contents) {
@@ -65,7 +89,9 @@ export const noAuthzDdlInMigrations = (
)
return [];
- const managed = new Set(helpers.map((h) => h.toLowerCase()));
+ const managed = new Map(
+ functions.map((f) => [`${f.schema}.${f.name}`.toLowerCase(), f])
+ );
const sql = stripComments(contents);
const line = (index: number) => sql.slice(0, index).split("\n").length;
const violations: Violation[] = [];
@@ -80,12 +106,13 @@ export const noAuthzDdlInMigrations = (
});
}
for (const m of sql.matchAll(FUNCTION_DDL)) {
- if (!managed.has((m[2] ?? "").toLowerCase())) continue;
+ const fn = managed.get(`${m[2] ?? "public"}.${m[3]}`.toLowerCase());
+ if (!fn || timestamp < fn.since) continue;
violations.push({
file,
line: line(m.index),
snippet: m[0],
- message: `${m[2]} is a managed helper; edit packages/database/src/authz/helpers/${m[2]}.sql, then run \`pnpm --filter @carbon/database authz migration <name>\`.`
+ message: `${m[3]} is a managed function; edit ${fn.file}, then run \`pnpm --filter @carbon/database authz migration <name>\`.`
});
}
return violations;
diff --git a/packages/checks/src/conformance/no-db-client-in-service.test.ts b/packages/checks/src/conformance/no-db-client-in-service.test.ts
index 8ccd5ce5b2..c917195f36 100644
--- a/packages/checks/src/conformance/no-db-client-in-service.test.ts
+++ b/packages/checks/src/conformance/no-db-client-in-service.test.ts
@@ -8,11 +8,11 @@ import { noDbClientInService } from "./no-db-client-in-service";
const SERVICE = "apps/erp/app/modules/production/production.service.ts";
describe("noDbClientInService", () => {
- it("flags getPostgresConnectionPool() in a service file", () => {
- const ts = "const pool = getPostgresConnectionPool(5);";
+ it("flags getProcessPool() in a service file", () => {
+ const ts = "const pool = getProcessPool();";
const v = noDbClientInService.scan(SERVICE, ts);
expect(v).toHaveLength(1);
- expect(v[0]?.snippet).toBe("getPostgresConnectionPool(");
+ expect(v[0]?.snippet).toBe("getProcessPool(");
});
it("flags getPostgresClient() in a service file", () => {
@@ -29,12 +29,12 @@ describe("noDbClientInService", () => {
it("flags the dynamic-import construction workaround", () => {
const ts = [
- 'const { getPostgresClient, getPostgresConnectionPool } = await import("@carbon/database/client");',
+ 'const { getPostgresClient, getProcessPool } = await import("@carbon/database/client");',
'const { PostgresDriver } = await import("kysely");',
- "return getPostgresClient(getPostgresConnectionPool(5), PostgresDriver);"
+ "return getPostgresClient(getProcessPool(), PostgresDriver);"
].join("\n");
// We match construction CALLS, not the destructured import names: line 3's
- // getPostgresClient( + getPostgresConnectionPool( + PostgresDriver, plus the
+ // getPostgresClient( + getProcessPool( + PostgresDriver, plus the
// PostgresDriver on line 2 = 4. The workaround is caught at the point of use.
expect(noDbClientInService.scan(SERVICE, ts)).toHaveLength(4);
});
@@ -61,7 +61,7 @@ describe("noDbClientInService", () => {
it("does NOT scan .server.ts (the sanctioned home for a DB client)", () => {
const ts =
- "const pool = getPostgresConnectionPool(10); getPostgresClient(pool, PostgresDriver);";
+ "const pool = getProcessPool(); getPostgresClient(pool, PostgresDriver);";
expect(
noDbClientInService.scan("apps/erp/app/services/database.server.ts", ts)
).toHaveLength(0);
@@ -75,7 +75,7 @@ describe("noDbClientInService", () => {
});
it("does not confuse *.service.test.ts for a service file", () => {
- const ts = "const pool = getPostgresConnectionPool(5);";
+ const ts = "const pool = getProcessPool();";
expect(
noDbClientInService.scan(
"apps/erp/app/modules/production/production.service.test.ts",
diff --git a/packages/checks/src/conformance/no-db-client-in-service.ts b/packages/checks/src/conformance/no-db-client-in-service.ts
index e36aefebb8..1ce4a6f94f 100644
--- a/packages/checks/src/conformance/no-db-client-in-service.ts
+++ b/packages/checks/src/conformance/no-db-client-in-service.ts
@@ -30,7 +30,10 @@ const MESSAGE =
"A *.service.ts must not construct a DB pool/Kysely client — this file is bundled for the browser via the module barrel. Build it in a .server file (getDatabaseClient in ~/services/database.server) and pass it into the service as a `db: Kysely<KyselyDatabase>` argument from the route action.";
const BANNED = [
- { pattern: /getPostgresConnectionPool\s*\(/g, message: MESSAGE },
+ {
+ pattern: /\b(?:getProcessPool|getPostgresConnectionPool)\s*\(/g,
+ message: MESSAGE
+ },
{ pattern: /getPostgresClient\s*\(/g, message: MESSAGE },
{ pattern: /new Pool\s*\(/g, message: MESSAGE },
{ pattern: /\bPostgresDriver\b/g, message: MESSAGE }
diff --git a/packages/checks/src/run.ts b/packages/checks/src/run.ts
index d8017c2dbf..94db3d038c 100644
--- a/packages/checks/src/run.ts
+++ b/packages/checks/src/run.ts
@@ -14,7 +14,11 @@ import type {
} from "./check";
import { edgeFunctionAuthorizesCaller } from "./conformance/edge-function-authorizes-caller";
import { moduleShape } from "./conformance/module-shape";
-import { noAuthzDdlInMigrations } from "./conformance/no-authz-ddl-in-migrations";
+import {
+ MANAGED_FUNCTION_SETS,
+ type ManagedFunction,
+ noAuthzDdlInMigrations
+} from "./conformance/no-authz-ddl-in-migrations";
import { noDbClientInService } from "./conformance/no-db-client-in-service";
import { noDefaultOnEffects } from "./conformance/no-default-on-effects";
import { noDerivedPercentColumn } from "./conformance/no-derived-percent-column";
@@ -109,11 +113,21 @@ export function scanModules(
return out;
}
-/** The managed RLS helpers: one packages/database/src/authz/helpers/<name>.sql each. */
-export function loadAuthzHelperNames(root: string): string[] {
- return readdirSync(join(root, "packages/database/src/authz/helpers"))
- .filter((file) => file.endsWith(".sql"))
- .map((file) => file.replace(/\.sql$/, ""));
+/** The managed functions: one `<name>.sql` (or `<schema>.<name>.sql`) file each. */
+export function loadManagedFunctions(root: string): ManagedFunction[] {
+ return MANAGED_FUNCTION_SETS.flatMap(({ dir, since }) =>
+ readdirSync(join(root, dir))
+ .filter((file) => file.endsWith(".sql"))
+ .map((file) => {
+ const [first = "", second] = file.replace(/\.sql$/, "").split(".");
+ return {
+ schema: second ? first : "public",
+ name: second ?? first,
+ file: `${dir}/${file}`,
+ since
+ };
+ })
+ );
}
/** Every finding across the real migrations (text) + modules (structure) + server TS + app TS + edge functions + license headers under `root`. */
@@ -121,7 +135,7 @@ export function collectFindings(root: string = repoRoot()): Finding[] {
return [
...scanAll(loadSqlFiles(migrationsDir(root)), [
...CONFORMANCE_CHECKS,
- noAuthzDdlInMigrations(loadAuthzHelperNames(root))
+ noAuthzDdlInMigrations(loadManagedFunctions(root))
]),
...scanModules(loadModules(modulesDir(root))),
...scanAll(loadServerFiles(root), SERVER_CHECKS),
diff --git a/packages/checks/src/sources/db-columns.ts b/packages/checks/src/sources/db-columns.ts
index 4bf3a93a65..547f768505 100644
--- a/packages/checks/src/sources/db-columns.ts
+++ b/packages/checks/src/sources/db-columns.ts
@@ -15,7 +15,7 @@ import { join } from "node:path";
*
* I/O lives here rather than in a check, so `scan` stays pure: the caller loads
* the map once and closes a check over it (the same shape as
- * `noAuthzDdlInMigrations(loadAuthzHelperNames(root))`).
+ * `noAuthzDdlInMigrations(loadManagedFunctions(root))`).
*/
export function loadDbTableColumns(root: string): Map<string, Set<string>> {
const contents = readFileSync(
diff --git a/packages/database/AGENTS.md b/packages/database/AGENTS.md
index 44e46b5683..5647995ab1 100644
--- a/packages/database/AGENTS.md
+++ b/packages/database/AGENTS.md
@@ -7,6 +7,7 @@ DB types, Supabase/Kysely clients, audit config, event system types, rate limiti
- Use `pnpm db:migrate:new <name>` to create migrations; `pnpm db:migrate` to apply (regenerates types). There is **no** `db:build`.
- Tables: composite PK `("id", "companyId")`, `id` default `id()` or `id('prefix')` — never raw UUID. Audit columns (`createdBy`/`createdAt`/`updatedBy`/`updatedAt`) with inline `REFERENCES "user"("id")`.
- RLS: every public table's policies are a rule in `src/authz/manifest.ts` (usually `company("<module>")` — the four standard policies) and the RLS helpers are `src/authz/helpers/<name>.sql`. `pnpm db:migrate` syncs them locally; `pnpm --filter @carbon/database authz migration <name>` ships them to production (`migration.test.ts` fails until it does). See `.claude/rules/authz-manifest.md`.
+- Event-system functions (dispatch, subscriptions, queue wake-up, audit log, search index, embeddings) are one file each in `src/event-system/functions/` (`<name>.sql`, `util.<name>.sql` for the `util` schema), synced and shipped by the same `authz sync` / `authz migration` commands. Edit the file; never redefine one in a migration.
- Import `Database` type from `@carbon/database`; `KyselyDatabase` / `Kysely` from `@carbon/database/client`. Never hand-edit `src/types.ts` — it's generated.
- `scriptRun` is a deliberate exception to the table conventions above: no `companyId`, no
composite PK, SELECT-only RLS. It is the per-database ledger of one-off scripts that
@@ -32,7 +33,7 @@ DB types, Supabase/Kysely clients, audit config, event system types, rate limiti
- Specify decimal places in `NUMERIC` columns (use bare `NUMERIC`).
- Use `000000` for the HHMMSS portion of migration timestamps (causes cross-branch collisions).
- Recreate or call the retired RLS helpers `has_role`, `has_company_permission`, `get_companies_with_permission`, `get_permission_companies` — dropped in `20260927224314_retire-legacy-rls-helpers.sql` (they admitted customer and supplier portal accounts); `authz-fixes.test.sql` asserts they stay gone.
-- Write `CREATE`/`ALTER POLICY` on a public table, or define a managed RLS helper, in a migration — and never hand-edit a generated authz migration or `src/authz/baseline.json`.
+- Write `CREATE`/`ALTER POLICY` on a public table, or define a managed RLS helper or event-system function, in a migration — and never hand-edit a generated authz migration or `src/authz/baseline.json`.
- Write a `SECURITY DEFINER` function that trusts a company id from its caller without `PERFORM assert_company_access(company_id)` first — every `public` function is an API endpoint (see `.claude/rules/database-migration-patterns.md`).
- `REVOKE EXECUTE` on a `public` function: on this Postgres image calling it then segfaults the backend. Guard inside the function, or make it `SECURITY INVOKER`.
@@ -53,7 +54,7 @@ pnpm --filter @carbon/database authz migration <name> # ship unshipped rules/h
| Subpath | Provides |
|---------|----------|
| `.` (index) | `Database` type, `fetchAllFromTable`, `fetchAllRecords` (takes a query factory), `fetchRecordsInBatches` |
-| `./client` | `Kysely`, `KyselyDatabase`, Postgres pool factories (`getPostgresClient`, `getPostgresConnectionPool`) |
+| `./client` | `Kysely`, `KyselyDatabase`, `getPostgresClient`, and the pools: `getProcessPool()` (Node: one shared pool per process — never create another, never end it outside an exiting script) and `getPostgresConnectionPool(n)` (edge functions only; throws on Node) |
| `./datetime` | Node re-export of `supabase/functions/lib/datetime.ts` — the edge-runtime datetime helpers (`datetime`, `getCompanyTimeZone`, `getLocationTimeZone`) for Node consumers |
| `./methods` | Node re-export of `supabase/functions/lib/methods.ts` — shared make-method helpers |
| `./logging` | Node re-export of `supabase/functions/lib/logging.ts` (`getFunctionLogger`) |
diff --git a/packages/database/src/authz/cli.ts b/packages/database/src/authz/cli.ts
index 5088edc00f..eeae69bbc9 100644
--- a/packages/database/src/authz/cli.ts
+++ b/packages/database/src/authz/cli.ts
@@ -9,7 +9,7 @@ import process from "node:process";
import { fileURLToPath } from "node:url";
import { Client } from "pg";
import { loadEnv } from "../datasets/cli";
-import { loadHelpers } from "./helpers";
+import { helperKey, loadHelpers } from "./helpers";
import { renderMigration, unshipped } from "./migration";
import { syncAuthz } from "./sync";
@@ -39,7 +39,7 @@ async function main() {
}
const sql = await renderMigration(
manifest,
- helpers.filter((h) => todo.helpers.includes(h.name)),
+ helpers.filter((h) => todo.helpers.includes(helperKey(h))),
todo.tables
);
const root = path.resolve(
diff --git a/packages/database/src/authz/helpers.test.ts b/packages/database/src/authz/helpers.test.ts
index 7d4052c665..6c69411b40 100644
--- a/packages/database/src/authz/helpers.test.ts
+++ b/packages/database/src/authz/helpers.test.ts
@@ -4,7 +4,7 @@
import { Client } from "pg";
import { afterAll, beforeAll, describe, expect, test } from "vitest";
-import { loadHelpers, validateHelper } from "./helpers";
+import { helperKey, loadHelpers, validateHelper } from "./helpers";
import { syncAuthz } from "./sync";
const fn = (name: string, body = "SELECT 1") =>
@@ -29,14 +29,32 @@ describe("validateHelper: a helper file is one function, and the right one", ()
).rejects.toThrow();
});
+ test("a file named for a schema defines the function in that schema", async () => {
+ const sql = fn("h").replace("public.h", "util.h");
+ await expect(
+ validateHelper({ schema: "util", name: "h", sql })
+ ).resolves.toBeUndefined();
+ await expect(validateHelper({ name: "h", sql })).rejects.toThrow();
+ await expect(
+ validateHelper({ schema: "util", name: "h", sql: fn("h") })
+ ).rejects.toThrow();
+ });
+
test("rejects CREATE without OR REPLACE", async () => {
await expect(
validateHelper({ name: "h", sql: fn("h").replace("OR REPLACE ", "") })
).rejects.toThrow();
});
- test("every committed helper file passes", async () => {
- expect((await loadHelpers()).length).toBeGreaterThan(0);
+ test("every committed file passes, RLS helpers and event-system functions", async () => {
+ const helpers = await loadHelpers();
+ expect(helpers.map(helperKey)).toEqual(
+ expect.arrayContaining([
+ "get_companies_with_employee_role",
+ "dispatch_event_batch",
+ "util.wake_event_queue"
+ ])
+ );
});
});
diff --git a/packages/database/src/authz/helpers.ts b/packages/database/src/authz/helpers.ts
index fd24c21de6..474a5bad40 100644
--- a/packages/database/src/authz/helpers.ts
+++ b/packages/database/src/authz/helpers.ts
@@ -9,17 +9,30 @@ import { parse } from "libpg-query";
import type { Client } from "pg";
/**
- * The RLS and auth helper functions. `helpers/<name>.sql` is the only place each is
- * defined; migrations must not create or redefine them. Sync applies a file only when the
- * function it produces differs from the live one.
+ * The managed functions: the RLS and auth helpers (`helpers/<name>.sql`) and the event
+ * system's functions (`../event-system/functions/<name>.sql`). Each file is the only place
+ * its function is defined; migrations must not create or redefine one. Sync applies a file
+ * only when the function it produces differs from the live one.
+ *
+ * A file is named for its function. One outside `public` carries its schema:
+ * `util.wake_event_queue.sql`.
*/
-export const HELPERS_DIR = path.join(
- path.dirname(fileURLToPath(import.meta.url)),
- "helpers"
-);
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+export const HELPERS_DIR = path.join(HERE, "helpers");
+export const EVENT_SYSTEM_DIR = path.join(HERE, "../event-system/functions");
+export const HELPER_DIRS = [HELPERS_DIR, EVENT_SYSTEM_DIR];
-export type Helper = { name: string; sql: string };
+/** `schema` defaults to `public`. */
+export type Helper = { name: string; sql: string; schema?: string };
+
+export const helperSchema = (helper: Helper) => helper.schema ?? "public";
+
+/** How a helper is named everywhere it is reported: `name`, or `schema.name` outside public. */
+export const helperKey = (helper: Helper) =>
+ helperSchema(helper) === "public"
+ ? helper.name
+ : `${helperSchema(helper)}.${helper.name}`;
/**
* Helpers that were managed here and have been dropped from the database (by a later
@@ -39,10 +52,12 @@ export const RETIRED_HELPERS: Readonly<Record<string, string>> = {
type Ast = any;
/**
- * A helper file must be exactly one `CREATE OR REPLACE FUNCTION public.<name>(…)` — so a
+ * A helper file must be exactly one `CREATE OR REPLACE FUNCTION <schema>.<name>(…)` — so a
* file can never smuggle in a second statement, or define a function it is not named for.
*/
-export async function validateHelper({ name, sql }: Helper): Promise<void> {
+export async function validateHelper(helper: Helper): Promise<void> {
+ const { sql } = helper;
+ const expected = `${helperSchema(helper)}.${helper.name}`;
const tree: Ast = await parse(sql);
const statements = tree.stmts ?? [];
const fn = statements[0]?.stmt?.CreateFunctionStmt;
@@ -52,33 +67,44 @@ export async function validateHelper({ name, sql }: Helper): Promise<void> {
!fn ||
!fn.replace ||
fn.is_procedure ||
- qualified.join(".") !== `public.${name}`
+ qualified.join(".") !== expected
) {
throw new Error(
- `helpers/${name}.sql must be exactly one CREATE OR REPLACE FUNCTION public.${name}(…)`
+ `${helperKey(helper)}.sql must be exactly one CREATE OR REPLACE FUNCTION ${expected}(…)`
);
}
}
-export async function loadHelpers(dir = HELPERS_DIR): Promise<Helper[]> {
- const helpers = readdirSync(dir)
- .filter((file) => file.endsWith(".sql"))
- .sort()
- .map((file) => ({
- name: file.replace(/\.sql$/, ""),
- sql: readFileSync(path.join(dir, file), "utf8")
- }));
+/** `name.sql` is public.name; `schema.name.sql` is schema.name. */
+const parseFileName = (file: string) => {
+ const [first = "", second] = file.replace(/\.sql$/, "").split(".");
+ return second ? { schema: first, name: second } : { name: first };
+};
+
+export async function loadHelpers(
+ dirs: string | string[] = HELPER_DIRS
+): Promise<Helper[]> {
+ const helpers = [dirs].flat().flatMap((dir) =>
+ readdirSync(dir)
+ .filter((file) => file.endsWith(".sql"))
+ .sort()
+ .map((file) => ({
+ ...parseFileName(file),
+ sql: readFileSync(path.join(dir, file), "utf8")
+ }))
+ );
for (const helper of helpers) await validateHelper(helper);
return helpers;
}
-const definitions = async (db: Client, name: string) =>
+const definitions = async (db: Client, helper: Helper) =>
(
await db.query<{ def: string }>(
`SELECT pg_get_functiondef(p.oid) AS def FROM pg_proc p
- WHERE p.pronamespace = 'public'::regnamespace AND p.proname = $1
+ JOIN pg_namespace n ON n.oid = p.pronamespace
+ WHERE n.nspname = $1 AND p.proname = $2
ORDER BY p.oid`,
- [name]
+ [helperSchema(helper), helper.name]
)
).rows.map((r) => r.def);
@@ -94,20 +120,21 @@ export async function syncHelpers(
{ dryRun }: { dryRun: boolean }
): Promise<string[]> {
const changed: string[] = [];
- for (const { name, sql } of helpers) {
- const before = await definitions(db, name);
+ for (const helper of helpers) {
+ const name = helperKey(helper);
+ const before = await definitions(db, helper);
if (before.length > 1) {
throw new Error(
`helper ${name} has ${before.length} overloads; expected one`
);
}
await db.query("SAVEPOINT authz_helper");
- await db.query(sql);
- const after = await definitions(db, name);
+ await db.query(helper.sql);
+ const after = await definitions(db, helper);
if (after.length !== 1) {
await db.query("ROLLBACK TO SAVEPOINT authz_helper");
throw new Error(
- `helpers/${name}.sql changes the signature of ${name}; that needs a migration`
+ `${name}.sql changes the signature of ${name}; that needs a migration`
);
}
const differs = after[0] !== before[0];
diff --git a/packages/database/src/authz/migration.test.ts b/packages/database/src/authz/migration.test.ts
index 8156b1f783..fd0d33ad1b 100644
--- a/packages/database/src/authz/migration.test.ts
+++ b/packages/database/src/authz/migration.test.ts
@@ -58,6 +58,17 @@ describe("unshipped: production gets every rule and helper through a migration",
expect(result.helpers).toContain("get_companies_with_employee_role");
});
+ test("an edited function outside public is unshipped under its schema", async () => {
+ const helpers = (await loadHelpers()).map((h) =>
+ h.schema === "util" && h.name === "wake_event_queue"
+ ? { ...h, sql: h.sql.replace("SECURITY DEFINER", "SECURITY INVOKER") }
+ : h
+ );
+ expect((await unshipped(manifest, helpers)).helpers).toEqual([
+ "util.wake_event_queue"
+ ]);
+ });
+
test("a generated migration ships its tables and helpers", async () => {
const helpers = (await loadHelpers()).map((h) =>
h.name === "get_companies_with_employee_role"
diff --git a/packages/database/src/authz/migration.ts b/packages/database/src/authz/migration.ts
index d062059d43..c4ca34ec60 100644
--- a/packages/database/src/authz/migration.ts
+++ b/packages/database/src/authz/migration.ts
@@ -7,7 +7,7 @@ import { readdirSync, readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { parse } from "libpg-query";
-import { type Helper, RETIRED_HELPERS } from "./helpers";
+import { type Helper, helperKey, RETIRED_HELPERS } from "./helpers";
import { type AnyRule, type Manifest, render } from "./rules";
import { assertOnlyPolicies } from "./sync";
@@ -143,8 +143,9 @@ async function readShipped(dir: string, managed: Set<string>) {
const policy = node.CreatePolicyStmt?.table;
if (fn) {
const [schema, name] = fn.funcname.map((n: Ast) => n.String?.sval);
- if (schema === "public" && managed.has(name)) {
- shipped.helpers.set(name, { file, text });
+ const key = schema === "public" ? name : `${schema}.${name}`;
+ if (managed.has(key)) {
+ shipped.helpers.set(key, { file, text });
continue;
}
if (schema === "public" && RETIRED_HELPERS[name] === file) continue;
@@ -202,7 +203,7 @@ export async function unshipped(
tables: Record<string, string>;
helpers: Record<string, string>;
} = JSON.parse(readFileSync(BASELINE, "utf8"));
- const shipped = await readShipped(dir, new Set(helpers.map((h) => h.name)));
+ const shipped = await readShipped(dir, new Set(helpers.map(helperKey)));
const result: Unshipped = {
tables: [],
helpers: [],
@@ -220,11 +221,12 @@ export async function unshipped(
}
for (const helper of helpers) {
- const got = shipped.helpers.get(helper.name);
+ const key = helperKey(helper);
+ const got = shipped.helpers.get(key);
const same = got
? got.text === (await statements(helper.sql))[0]?.text
- : baseline.helpers[helper.name] === hash(helper.sql);
- if (!same) result.helpers.push(helper.name);
+ : baseline.helpers[key] === hash(helper.sql);
+ if (!same) result.helpers.push(key);
}
return result;
diff --git a/packages/database/src/check-datasets.ts b/packages/database/src/check-datasets.ts
index 9661b4ec52..29f139c2a4 100644
--- a/packages/database/src/check-datasets.ts
+++ b/packages/database/src/check-datasets.ts
@@ -23,7 +23,7 @@ import process from "node:process";
import { fileURLToPath } from "node:url";
import { parseArgs } from "node:util";
import type { PoolClient } from "pg";
-import { getPostgresConnectionPool } from "./client.ts";
+import { getProcessPool } from "./client.ts";
import { loadEnv } from "./datasets/cli.ts";
import { datasetKeys, getDataset } from "./datasets/index.ts";
import { validateDataset } from "./datasets/validate.ts";
@@ -129,14 +129,14 @@ async function main() {
}
// No connection string configured at all (fresh worktree, no .env.local).
- // getPostgresConnectionPool dereferences it before any connect() can fail,
+ // getProcessPool dereferences it before any connect() can fail,
// so without this the hook blocks the commit on "Cannot read properties of
// undefined (reading 'includes')" — the least actionable message there is.
if (!process.env.SUPABASE_DB_URL) {
skip("SUPABASE_DB_URL is not set (no .env.local in this worktree?)");
}
- const pool = getPostgresConnectionPool(1);
+ const pool = getProcessPool();
let client: PoolClient;
try {
client = await pool.connect();
diff --git a/packages/database/src/event-dispatch.test.ts b/packages/database/src/event-dispatch.test.ts
index b026054574..3b21c2a440 100644
--- a/packages/database/src/event-dispatch.test.ts
+++ b/packages/database/src/event-dispatch.test.ts
@@ -2,32 +2,19 @@
// 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 { readdirSync, readFileSync } from "node:fs";
+import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import { auditConfig } from "./audit.config";
-const migrations = fileURLToPath(
- new URL("../supabase/migrations/", import.meta.url)
-);
-
-function newestDefinition(signature: string) {
- for (const file of readdirSync(migrations).sort().reverse()) {
- const sql = readFileSync(`${migrations}${file}`, "utf8");
- if (sql.includes(signature)) return { file, sql };
- }
- throw new Error(`No migration defines ${signature}`);
-}
+const file = "event-system/functions/dispatch_event_batch.sql";
+const sql = readFileSync(fileURLToPath(new URL(file, import.meta.url)), "utf8");
describe("dispatch_event_batch", () => {
// The trigger drops an UPDATE that changes only these columns before it is
- // queued, because the audit diff would discard it. A new definition forked
- // from an older one silently loses the filter, and a skip field added on one
+ // queued, because the audit diff would discard it. A skip field added on one
// side only makes the trigger and the handler disagree.
it("ignores exactly the columns the audit diff skips", () => {
- const { file, sql } = newestDefinition(
- "CREATE OR REPLACE FUNCTION public.dispatch_event_batch()"
- );
const declared = sql.match(
/ignored_columns CONSTANT TEXT\[\] := ARRAY\[([^\]]*)\]/
);
diff --git a/packages/database/src/event-system/functions/assert_audit_log_access.sql b/packages/database/src/event-system/functions/assert_audit_log_access.sql
new file mode 100644
index 0000000000..bf00fede70
--- /dev/null
+++ b/packages/database/src/event-system/functions/assert_audit_log_access.sql
@@ -0,0 +1,21 @@
+CREATE OR REPLACE FUNCTION public.assert_audit_log_access(p_company_id text, p_permission text)
+ RETURNS void
+ LANGUAGE plpgsql
+ STABLE SECURITY DEFINER
+ SET search_path TO 'public'
+AS $function$
+BEGIN
+ IF current_setting('role', true) NOT IN ('anon', 'authenticated') THEN
+ RETURN;
+ END IF;
+
+ IF p_permission IS NOT NULL AND p_company_id = ANY (
+ COALESCE(get_companies_with_employee_permission(p_permission), '{}')::text[]
+ ) THEN
+ RETURN;
+ END IF;
+
+ RAISE EXCEPTION 'Not authorized to access the audit log for this company'
+ USING ERRCODE = 'insufficient_privilege';
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/attach_audit_log_append_only.sql b/packages/database/src/event-system/functions/attach_audit_log_append_only.sql
new file mode 100644
index 0000000000..721e361ecd
--- /dev/null
+++ b/packages/database/src/event-system/functions/attach_audit_log_append_only.sql
@@ -0,0 +1,13 @@
+CREATE OR REPLACE FUNCTION public.attach_audit_log_append_only(p_table_name text)
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+BEGIN
+ EXECUTE format('DROP TRIGGER IF EXISTS "append_only" ON %I', p_table_name);
+ EXECUTE format(
+ 'CREATE TRIGGER "append_only" BEFORE UPDATE OR DELETE ON %I
+ FOR EACH ROW EXECUTE FUNCTION prevent_audit_log_mutation()',
+ p_table_name
+ );
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/attach_event_trigger.sql b/packages/database/src/event-system/functions/attach_event_trigger.sql
new file mode 100644
index 0000000000..235bc35a14
--- /dev/null
+++ b/packages/database/src/event-system/functions/attach_event_trigger.sql
@@ -0,0 +1,71 @@
+CREATE OR REPLACE FUNCTION public.attach_event_trigger(table_name_text text, sync_functions text[] DEFAULT ARRAY[]::text[], after_sync_functions text[] DEFAULT ARRAY[]::text[])
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ sync_args TEXT;
+ after_sync_args TEXT;
+BEGIN
+ -- A. Attach BEFORE SYNC Trigger (Row Level) -- unchanged behavior
+ IF array_length(sync_functions, 1) > 0 THEN
+ SELECT string_agg(quote_literal(x), ', ') INTO sync_args FROM unnest(sync_functions) x;
+
+ EXECUTE format('
+ DROP TRIGGER IF EXISTS "trg_event_sync_%1$s" ON %1$I;
+ CREATE TRIGGER "trg_event_sync_%1$s"
+ BEFORE INSERT OR UPDATE OR DELETE ON %1$I
+ FOR EACH ROW
+ EXECUTE FUNCTION public.dispatch_event_interceptors(%2$s);
+ ', table_name_text, sync_args);
+ ELSE
+ EXECUTE format('DROP TRIGGER IF EXISTS "trg_event_sync_%1$s" ON %1$I;', table_name_text);
+ END IF;
+
+ -- B. Attach AFTER SYNC Trigger (Row Level) -- NEW
+ IF array_length(after_sync_functions, 1) > 0 THEN
+ SELECT string_agg(quote_literal(x), ', ') INTO after_sync_args FROM unnest(after_sync_functions) x;
+
+ EXECUTE format('
+ DROP TRIGGER IF EXISTS "trg_event_after_sync_%1$s" ON %1$I;
+ CREATE TRIGGER "trg_event_after_sync_%1$s"
+ AFTER INSERT OR UPDATE OR DELETE ON %1$I
+ FOR EACH ROW
+ EXECUTE FUNCTION public.dispatch_event_after_interceptors(%2$s);
+ ', table_name_text, after_sync_args);
+ ELSE
+ EXECUTE format('DROP TRIGGER IF EXISTS "trg_event_after_sync_%1$s" ON %1$I;', table_name_text);
+ END IF;
+
+ -- C. Attach ASYNC Triggers (Statement Level) -- unchanged behavior
+ -- 1. INSERT
+ EXECUTE format('
+ DROP TRIGGER IF EXISTS "trg_event_async_ins_%1$s" ON %1$I;
+ CREATE TRIGGER "trg_event_async_ins_%1$s"
+ AFTER INSERT ON %1$I
+ REFERENCING NEW TABLE AS batched_new
+ FOR EACH STATEMENT
+ EXECUTE FUNCTION public.dispatch_event_batch();
+ ', table_name_text);
+
+ -- 2. DELETE
+ EXECUTE format('
+ DROP TRIGGER IF EXISTS "trg_event_async_del_%1$s" ON %1$I;
+ CREATE TRIGGER "trg_event_async_del_%1$s"
+ AFTER DELETE ON %1$I
+ REFERENCING OLD TABLE AS batched_old
+ FOR EACH STATEMENT
+ EXECUTE FUNCTION public.dispatch_event_batch();
+ ', table_name_text);
+
+ -- 3. UPDATE
+ EXECUTE format('
+ DROP TRIGGER IF EXISTS "trg_event_async_upd_%1$s" ON %1$I;
+ CREATE TRIGGER "trg_event_async_upd_%1$s"
+ AFTER UPDATE ON %1$I
+ REFERENCING NEW TABLE AS batched_new OLD TABLE AS batched_old
+ FOR EACH STATEMENT
+ EXECUTE FUNCTION public.dispatch_event_batch();
+ ', table_name_text);
+
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/attach_statement_handler.sql b/packages/database/src/event-system/functions/attach_statement_handler.sql
new file mode 100644
index 0000000000..20afddc884
--- /dev/null
+++ b/packages/database/src/event-system/functions/attach_statement_handler.sql
@@ -0,0 +1,44 @@
+CREATE OR REPLACE FUNCTION public.attach_statement_handler(table_name_text text, handler_functions text[] DEFAULT ARRAY[]::text[])
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ fn TEXT;
+ existing TEXT;
+BEGIN
+ -- Drop-then-attach, like attach_event_trigger's sync sections: re-running is
+ -- idempotent and an empty array detaches.
+ FOR existing IN
+ SELECT t.tgname
+ FROM pg_trigger t
+ WHERE t.tgrelid = format('%I', table_name_text)::regclass
+ AND NOT t.tgisinternal
+ AND t.tgname LIKE 'trg\_event\_statement\_%'
+ LOOP
+ EXECUTE format('DROP TRIGGER IF EXISTS %2$I ON %1$I;', table_name_text, existing);
+ END LOOP;
+
+ -- One function serves all three operations, so it must branch on TG_OP: only
+ -- batched_new exists on INSERT and only batched_old on DELETE. PL/pgSQL plans
+ -- lazily, so a branch that does not run never resolves its missing table.
+ FOREACH fn IN ARRAY handler_functions LOOP
+ EXECUTE format('
+ CREATE TRIGGER %2$I AFTER INSERT ON %1$I
+ REFERENCING NEW TABLE AS batched_new
+ FOR EACH STATEMENT EXECUTE FUNCTION %3$I();
+ ', table_name_text, format('trg_event_statement_%s_ins', fn), fn);
+
+ EXECUTE format('
+ CREATE TRIGGER %2$I AFTER UPDATE ON %1$I
+ REFERENCING NEW TABLE AS batched_new OLD TABLE AS batched_old
+ FOR EACH STATEMENT EXECUTE FUNCTION %3$I();
+ ', table_name_text, format('trg_event_statement_%s_upd', fn), fn);
+
+ EXECUTE format('
+ CREATE TRIGGER %2$I AFTER DELETE ON %1$I
+ REFERENCING OLD TABLE AS batched_old
+ FOR EACH STATEMENT EXECUTE FUNCTION %3$I();
+ ', table_name_text, format('trg_event_statement_%s_del', fn), fn);
+ END LOOP;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/create_audit_log_table.sql b/packages/database/src/event-system/functions/create_audit_log_table.sql
new file mode 100644
index 0000000000..b15e0a9a4a
--- /dev/null
+++ b/packages/database/src/event-system/functions/create_audit_log_table.sql
@@ -0,0 +1,104 @@
+CREATE OR REPLACE FUNCTION public.create_audit_log_table(p_company_id text)
+ RETURNS void
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+DECLARE
+ tbl_name TEXT;
+ tbl REGCLASS;
+BEGIN
+ PERFORM assert_audit_log_access(p_company_id, 'settings_update');
+
+ tbl_name := 'auditLog_' || p_company_id;
+
+ IF EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ -- Table exists; ensure recordId column is present (for tables created before this migration)
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.columns
+ WHERE table_schema = 'public'
+ AND information_schema.columns.table_name = tbl_name
+ AND column_name = 'recordId'
+ ) THEN
+ EXECUTE format('ALTER TABLE %I ADD COLUMN "recordId" TEXT', tbl_name);
+ EXECUTE format('UPDATE %I SET "recordId" = "entityId" WHERE "recordId" IS NULL', tbl_name);
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("recordId")',
+ 'idx_' || tbl_name || '_record', tbl_name);
+ END IF;
+
+ tbl := format('public.%I', tbl_name)::regclass;
+
+ -- Without row level security the company-scoped read policy below is not
+ -- enforced, and the API roles keep SELECT.
+ IF NOT (SELECT c.relrowsecurity FROM pg_class c WHERE c.oid = tbl) THEN
+ EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', tbl_name);
+ END IF;
+
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_trigger t
+ WHERE t.tgrelid = tbl
+ AND t.tgname = 'append_only'
+ AND NOT t.tgisinternal
+ AND t.tgenabled <> 'D'
+ AND t.tgfoid = 'public.prevent_audit_log_mutation'::regproc
+ ) THEN
+ PERFORM attach_audit_log_append_only(tbl_name);
+ END IF;
+
+ -- Secured means: the company-scoped read policy is there, the old
+ -- open policy is not, and the API roles cannot write.
+ IF EXISTS (
+ SELECT 1 FROM pg_policies p
+ WHERE p.schemaname = 'public' AND p.tablename = tbl_name
+ AND p.policyname = 'audit_log_access'
+ )
+ OR NOT EXISTS (
+ SELECT 1 FROM pg_policies p
+ WHERE p.schemaname = 'public' AND p.tablename = tbl_name
+ AND p.policyname = 'SELECT' AND p.cmd = 'SELECT'
+ AND p.qual LIKE '%' || quote_literal(p_company_id) || '%'
+ AND p.qual LIKE '%settings_view%'
+ )
+ OR has_table_privilege('anon', tbl, 'INSERT, UPDATE, DELETE, TRUNCATE')
+ OR has_table_privilege('authenticated', tbl, 'INSERT, UPDATE, DELETE, TRUNCATE')
+ THEN
+ PERFORM secure_audit_log_table(p_company_id);
+ END IF;
+
+ RETURN;
+ END IF;
+
+ EXECUTE format('
+ CREATE TABLE IF NOT EXISTS %I (
+ "id" TEXT PRIMARY KEY DEFAULT id(''aud''),
+ "tableName" TEXT NOT NULL,
+ "entityType" TEXT NOT NULL,
+ "entityId" TEXT NOT NULL,
+ "recordId" TEXT,
+ "operation" TEXT NOT NULL CHECK ("operation" IN (''INSERT'', ''UPDATE'', ''DELETE'')),
+ "actorId" TEXT,
+ "diff" JSONB,
+ "metadata" JSONB,
+ "createdAt" TIMESTAMPTZ NOT NULL DEFAULT NOW()
+ )
+ ', tbl_name);
+
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("entityType", "entityId")',
+ 'idx_' || tbl_name || '_entity', tbl_name);
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("tableName")',
+ 'idx_' || tbl_name || '_table', tbl_name);
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("recordId")',
+ 'idx_' || tbl_name || '_record', tbl_name);
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("actorId")',
+ 'idx_' || tbl_name || '_actor', tbl_name);
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("createdAt" DESC)',
+ 'idx_' || tbl_name || '_created', tbl_name);
+
+ EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', tbl_name);
+
+ PERFORM attach_audit_log_append_only(tbl_name);
+ PERFORM secure_audit_log_table(p_company_id);
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/create_company_search_index.sql b/packages/database/src/event-system/functions/create_company_search_index.sql
new file mode 100644
index 0000000000..6ce7fc18e2
--- /dev/null
+++ b/packages/database/src/event-system/functions/create_company_search_index.sql
@@ -0,0 +1,46 @@
+CREATE OR REPLACE FUNCTION public.create_company_search_index(p_company_id text)
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ v_table_name TEXT;
+BEGIN
+ v_table_name := 'searchIndex_' || p_company_id;
+
+ -- Create the search index table
+ EXECUTE format('
+ CREATE TABLE IF NOT EXISTS %I (
+ "id" BIGINT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
+ "entityType" TEXT NOT NULL,
+ "entityId" TEXT NOT NULL,
+ "title" TEXT NOT NULL,
+ "description" TEXT DEFAULT '''',
+ "link" TEXT NOT NULL,
+ "tags" TEXT[] DEFAULT ''{}'',
+ "metadata" JSONB DEFAULT ''{}'',
+ "searchVector" TSVECTOR,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT %I UNIQUE ("entityType", "entityId")
+ )', v_table_name, v_table_name || '_entity_unique');
+
+ -- GIN on searchVector: FTS path (multi-word, stemmed prefix via :*).
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I USING GIN ("searchVector")',
+ v_table_name || '_fts_idx', v_table_name);
+
+ -- GIN trigram on title: substring path (find "269" inside "S000269").
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I USING GIN ("title" gin_trgm_ops)',
+ v_table_name || '_title_trgm_idx', v_table_name);
+
+ -- GIN trigram on description: substring path for hits that live in the body text.
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I USING GIN ("description" gin_trgm_ops)',
+ v_table_name || '_description_trgm_idx', v_table_name);
+
+ -- Enable RLS (no SELECT policies - access via service role bypass)
+ EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', v_table_name);
+
+ INSERT INTO "searchIndexRegistry" ("companyId")
+ VALUES (p_company_id)
+ ON CONFLICT ("companyId") DO NOTHING;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/create_embedding_subscriptions_for_company.sql b/packages/database/src/event-system/functions/create_embedding_subscriptions_for_company.sql
new file mode 100644
index 0000000000..9a7cc71774
--- /dev/null
+++ b/packages/database/src/event-system/functions/create_embedding_subscriptions_for_company.sql
@@ -0,0 +1,37 @@
+CREATE OR REPLACE FUNCTION public.create_embedding_subscriptions_for_company(p_company_id text)
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ v_tables TEXT[] := ARRAY['item', 'customer', 'supplier'];
+ v_table TEXT;
+BEGIN
+ FOREACH v_table IN ARRAY v_tables LOOP
+ INSERT INTO "eventSystemSubscription" (
+ "name",
+ "table",
+ "companyId",
+ "operations",
+ "handlerType",
+ "config",
+ "filter",
+ "active"
+ )
+ VALUES (
+ 'embedding-' || v_table,
+ v_table,
+ p_company_id,
+ ARRAY['INSERT', 'UPDATE'],
+ 'EMBEDDING',
+ '{}'::jsonb,
+ '{}'::jsonb,
+ TRUE
+ )
+ ON CONFLICT ON CONSTRAINT "unique_subscription_name_per_company"
+ DO UPDATE SET
+ "operations" = EXCLUDED."operations",
+ "handlerType" = EXCLUDED."handlerType",
+ "active" = EXCLUDED."active";
+ END LOOP;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/create_event_system_subscription.sql b/packages/database/src/event-system/functions/create_event_system_subscription.sql
new file mode 100644
index 0000000000..45aef82d80
--- /dev/null
+++ b/packages/database/src/event-system/functions/create_event_system_subscription.sql
@@ -0,0 +1,45 @@
+CREATE OR REPLACE FUNCTION public.create_event_system_subscription(p_name text, p_table text, p_company_id text, p_operations text[], p_handler_type text, p_config jsonb DEFAULT '{}'::jsonb, p_filter jsonb DEFAULT '{}'::jsonb, p_active boolean DEFAULT true)
+ RETURNS TABLE(id text, name text, "handlerType" text, "table" text)
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public', 'pg_temp'
+AS $function$
+BEGIN
+ IF NOT util.can_manage_event_subscription(p_company_id, p_handler_type) THEN
+ RAISE EXCEPTION 'Not authorized to manage % event subscriptions for company %', p_handler_type, p_company_id
+ USING ERRCODE = '42501';
+ END IF;
+
+ RETURN QUERY
+ INSERT INTO "eventSystemSubscription" (
+ "name", "table", "companyId", "operations",
+ "handlerType", "config", "filter", "active"
+ )
+ VALUES (
+ p_name, p_table, p_company_id, p_operations,
+ p_handler_type, p_config, p_filter, p_active
+ )
+ ON CONFLICT ON CONSTRAINT "unique_subscription_name_per_company"
+ DO UPDATE SET
+ "operations" = EXCLUDED."operations",
+ "filter" = EXCLUDED."filter",
+ "handlerType" = EXCLUDED."handlerType",
+ "config" = EXCLUDED."config",
+ "active" = EXCLUDED."active"
+ -- Replacing a subscription also needs the right to manage what it was.
+ WHERE util.can_manage_event_subscription(
+ p_company_id,
+ "eventSystemSubscription"."handlerType"
+ )
+ RETURNING
+ "eventSystemSubscription"."id",
+ "eventSystemSubscription"."name",
+ "eventSystemSubscription"."handlerType",
+ "eventSystemSubscription"."table";
+
+ IF NOT FOUND THEN
+ RAISE EXCEPTION 'Not authorized to replace event subscription "%" for company %', p_name, p_company_id
+ USING ERRCODE = '42501';
+ END IF;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/create_search_subscriptions_for_company.sql b/packages/database/src/event-system/functions/create_search_subscriptions_for_company.sql
new file mode 100644
index 0000000000..fbe28b7589
--- /dev/null
+++ b/packages/database/src/event-system/functions/create_search_subscriptions_for_company.sql
@@ -0,0 +1,42 @@
+CREATE OR REPLACE FUNCTION public.create_search_subscriptions_for_company(p_company_id text)
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ v_tables TEXT[] := ARRAY[
+ 'employee', 'customer', 'supplier', 'item', 'job',
+ 'purchaseOrder', 'salesInvoice', 'purchaseInvoice',
+ 'nonConformance', 'gauge', 'quote', 'salesRfq',
+ 'salesOrder', 'supplierQuote'
+ ];
+ v_table TEXT;
+BEGIN
+ FOREACH v_table IN ARRAY v_tables LOOP
+ INSERT INTO "eventSystemSubscription" (
+ "name",
+ "table",
+ "companyId",
+ "operations",
+ "handlerType",
+ "config",
+ "filter",
+ "active"
+ )
+ VALUES (
+ 'search-index-' || v_table,
+ v_table,
+ p_company_id,
+ ARRAY['INSERT', 'UPDATE', 'DELETE'],
+ 'SEARCH',
+ '{}'::jsonb,
+ '{}'::jsonb,
+ TRUE
+ )
+ ON CONFLICT ON CONSTRAINT "unique_subscription_name_per_company"
+ DO UPDATE SET
+ "operations" = EXCLUDED."operations",
+ "handlerType" = EXCLUDED."handlerType",
+ "active" = EXCLUDED."active";
+ END LOOP;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/delete_event_system_subscription.sql b/packages/database/src/event-system/functions/delete_event_system_subscription.sql
new file mode 100644
index 0000000000..c35a9f1dd1
--- /dev/null
+++ b/packages/database/src/event-system/functions/delete_event_system_subscription.sql
@@ -0,0 +1,27 @@
+CREATE OR REPLACE FUNCTION public.delete_event_system_subscription(p_subscription_id text)
+ RETURNS void
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public', 'pg_temp'
+AS $function$
+DECLARE
+ v_company_id TEXT;
+ v_handler_type TEXT;
+BEGIN
+ SELECT "companyId", "handlerType" INTO v_company_id, v_handler_type
+ FROM "eventSystemSubscription"
+ WHERE "id" = p_subscription_id;
+
+ -- Nothing to delete (missing id, or already gone) — no-op, as before.
+ IF v_company_id IS NULL THEN
+ RETURN;
+ END IF;
+
+ IF NOT util.can_manage_event_subscription(v_company_id, v_handler_type) THEN
+ RAISE EXCEPTION 'Not authorized to manage % event subscriptions for company %', v_handler_type, v_company_id
+ USING ERRCODE = '42501';
+ END IF;
+
+ DELETE FROM "eventSystemSubscription" WHERE "id" = p_subscription_id;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/delete_event_system_subscriptions_by_name.sql b/packages/database/src/event-system/functions/delete_event_system_subscriptions_by_name.sql
new file mode 100644
index 0000000000..c28683087a
--- /dev/null
+++ b/packages/database/src/event-system/functions/delete_event_system_subscriptions_by_name.sql
@@ -0,0 +1,26 @@
+CREATE OR REPLACE FUNCTION public.delete_event_system_subscriptions_by_name(p_company_id text, p_name text)
+ RETURNS void
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public', 'pg_temp'
+AS $function$
+DECLARE
+ v_handler_type TEXT;
+BEGIN
+ -- A (companyId, name) group is one handler type in practice; if any matching
+ -- row is WEBHOOK, require the stricter WEBHOOK gate. NULL (no rows) falls
+ -- through to the membership gate on a delete that affects nothing.
+ SELECT CASE WHEN bool_or("handlerType" = 'WEBHOOK') THEN 'WEBHOOK' ELSE max("handlerType") END
+ INTO v_handler_type
+ FROM "eventSystemSubscription"
+ WHERE "companyId" = p_company_id AND "name" = p_name;
+
+ IF NOT util.can_manage_event_subscription(p_company_id, COALESCE(v_handler_type, '')) THEN
+ RAISE EXCEPTION 'Not authorized to manage event subscriptions for company %', p_company_id
+ USING ERRCODE = '42501';
+ END IF;
+
+ DELETE FROM "eventSystemSubscription"
+ WHERE "companyId" = p_company_id AND "name" = p_name;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/delete_from_search_index.sql b/packages/database/src/event-system/functions/delete_from_search_index.sql
new file mode 100644
index 0000000000..4f1310769d
--- /dev/null
+++ b/packages/database/src/event-system/functions/delete_from_search_index.sql
@@ -0,0 +1,15 @@
+CREATE OR REPLACE FUNCTION public.delete_from_search_index(p_company_id text, p_entity_type text, p_entity_id text)
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ v_table_name TEXT;
+BEGIN
+ v_table_name := 'searchIndex_' || p_company_id;
+
+ EXECUTE format(
+ 'DELETE FROM %I WHERE "entityType" = $1 AND "entityId" = $2',
+ v_table_name
+ ) USING p_entity_type, p_entity_id;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/delete_old_audit_logs.sql b/packages/database/src/event-system/functions/delete_old_audit_logs.sql
new file mode 100644
index 0000000000..78dbb11c57
--- /dev/null
+++ b/packages/database/src/event-system/functions/delete_old_audit_logs.sql
@@ -0,0 +1,37 @@
+CREATE OR REPLACE FUNCTION public.delete_old_audit_logs(p_company_id text, p_cutoff_date timestamp with time zone)
+ RETURNS integer
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+DECLARE
+ tbl_name TEXT;
+ deleted_count INTEGER;
+BEGIN
+ PERFORM assert_audit_log_access(p_company_id, NULL);
+
+ tbl_name := 'auditLog_' || p_company_id;
+
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN 0;
+ END IF;
+
+ -- Authorize the append-only trigger to permit these retention deletes.
+ PERFORM set_config('app.audit_archiving', 'on', true);
+
+ EXECUTE format('
+ WITH deleted AS (
+ DELETE FROM %I
+ WHERE "createdAt" < $1
+ RETURNING *
+ )
+ SELECT COUNT(*) FROM deleted
+ ', tbl_name)
+ USING p_cutoff_date
+ INTO deleted_count;
+
+ RETURN deleted_count;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/dispatch_event_after_interceptors.sql b/packages/database/src/event-system/functions/dispatch_event_after_interceptors.sql
new file mode 100644
index 0000000000..241c7c284d
--- /dev/null
+++ b/packages/database/src/event-system/functions/dispatch_event_after_interceptors.sql
@@ -0,0 +1,36 @@
+CREATE OR REPLACE FUNCTION public.dispatch_event_after_interceptors()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public'
+AS $function$
+DECLARE
+ func_name TEXT;
+ payload_data JSONB;
+ old_payload_data JSONB;
+ i INTEGER;
+BEGIN
+ -- A. Normalize Data
+ IF TG_OP = 'DELETE' THEN
+ payload_data := row_to_json(OLD)::jsonb;
+ old_payload_data := payload_data;
+ ELSIF TG_OP = 'INSERT' THEN
+ payload_data := row_to_json(NEW)::jsonb;
+ old_payload_data := NULL;
+ ELSE -- UPDATE
+ payload_data := row_to_json(NEW)::jsonb;
+ old_payload_data := row_to_json(OLD)::jsonb;
+ END IF;
+
+ -- B. Execute AFTER Interceptor Functions
+ -- Same calling convention as dispatch_event_interceptors():
+ -- function_name(table_name TEXT, operation TEXT, new_data JSONB, old_data JSONB)
+ FOR i IN 0 .. (TG_NARGS - 1) LOOP
+ func_name := TG_ARGV[i];
+ EXECUTE format('SELECT public.%I($1, $2, $3, $4)', func_name)
+ USING TG_TABLE_NAME::TEXT, TG_OP, payload_data, old_payload_data;
+ END LOOP;
+
+ IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/dispatch_event_batch.sql b/packages/database/src/event-system/functions/dispatch_event_batch.sql
new file mode 100644
index 0000000000..871bb1957d
--- /dev/null
+++ b/packages/database/src/event-system/functions/dispatch_event_batch.sql
@@ -0,0 +1,178 @@
+CREATE OR REPLACE FUNCTION public.dispatch_event_batch()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public', 'pgmq', 'extensions'
+AS $function$
+DECLARE
+ sub RECORD;
+ msg_batch JSONB[];
+ rec_company_id TEXT;
+ has_subs BOOLEAN;
+ current_actor_id TEXT;
+ current_workflow_run_id TEXT;
+ pk_column TEXT;
+ pk_join TEXT;
+ query_text TEXT;
+ did_enqueue BOOLEAN := FALSE;
+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];
+BEGIN
+ current_actor_id := auth.uid()::TEXT;
+ current_workflow_run_id :=
+ (nullif(current_setting('request.jwt.claims', true), '')::jsonb)->>'workflow_run_id';
+ pk_column := public.get_primary_key_column(TG_TABLE_NAME);
+
+ -- Pair UPDATE rows on the full key: single-column pairing cross-joins rows
+ -- on tables with composite identity.
+ SELECT string_agg(format('n.%I = o.%I', col, col), ' AND ')
+ INTO pk_join
+ FROM unnest(public.get_primary_key_columns(TG_TABLE_NAME)) AS col;
+
+ IF TG_OP = 'DELETE' THEN
+ SELECT t."companyId" INTO rec_company_id FROM batched_old t LIMIT 1;
+ ELSIF TG_OP = 'INSERT' THEN
+ SELECT t."companyId" INTO rec_company_id FROM batched_new t LIMIT 1;
+ ELSE
+ SELECT t."companyId" INTO rec_company_id FROM batched_new t LIMIT 1;
+ END IF;
+
+ IF rec_company_id IS NULL THEN RETURN NULL; END IF;
+
+ SELECT EXISTS (
+ SELECT 1 FROM "eventSystemSubscription"
+ WHERE "table" = TG_TABLE_NAME
+ AND "companyId" = rec_company_id
+ AND "active" = TRUE
+ AND TG_OP = ANY("operations")
+ AND ("handlerType" NOT IN ('SYNC','WEBHOOK','WORKFLOW')
+ OR current_setting('app.sync_in_progress', true) IS DISTINCT FROM 'true')
+ ) INTO has_subs;
+
+ IF NOT has_subs THEN RETURN NULL; END IF;
+
+ FOR sub IN
+ SELECT * FROM "eventSystemSubscription"
+ WHERE "table" = TG_TABLE_NAME
+ AND "companyId" = rec_company_id
+ AND "active" = TRUE
+ AND TG_OP = ANY("operations")
+ AND ("handlerType" NOT IN ('SYNC','WEBHOOK','WORKFLOW')
+ OR current_setting('app.sync_in_progress', true) IS DISTINCT FROM 'true')
+ LOOP
+
+ IF TG_OP = 'INSERT' THEN
+ query_text := format('
+ SELECT array_agg(
+ jsonb_build_object(
+ ''subscriptionId'', $1,
+ ''triggerType'', $2,
+ ''handlerType'', $3,
+ ''handlerConfig'', $4,
+ ''companyId'', $5,
+ ''actorId'', $6,
+ ''workflowRunId'', $10,
+ ''event'', jsonb_build_object(
+ ''table'', $7,
+ ''operation'', $8,
+ ''recordId'', t.%I::TEXT,
+ ''new'', row_to_json(t)::jsonb,
+ ''old'', null,
+ ''timestamp'', clock_timestamp()
+ )
+ )
+ )
+ FROM batched_new t
+ WHERE t."companyId" = $5
+ AND ($9 = ''{}''::jsonb OR row_to_json(t)::jsonb @> $9)
+ ', pk_column);
+
+ EXECUTE query_text INTO msg_batch
+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter,
+ current_workflow_run_id;
+
+ ELSIF TG_OP = 'DELETE' THEN
+ query_text := format('
+ SELECT array_agg(
+ jsonb_build_object(
+ ''subscriptionId'', $1,
+ ''triggerType'', $2,
+ ''handlerType'', $3,
+ ''handlerConfig'', $4,
+ ''companyId'', $5,
+ ''actorId'', $6,
+ ''workflowRunId'', $10,
+ ''event'', jsonb_build_object(
+ ''table'', $7,
+ ''operation'', $8,
+ ''recordId'', t.%I::TEXT,
+ ''new'', null,
+ ''old'', row_to_json(t)::jsonb,
+ ''timestamp'', clock_timestamp()
+ )
+ )
+ )
+ FROM batched_old t
+ WHERE t."companyId" = $5
+ AND ($9 = ''{}''::jsonb OR row_to_json(t)::jsonb @> $9)
+ ', pk_column);
+
+ EXECUTE query_text INTO msg_batch
+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter,
+ current_workflow_run_id;
+
+ ELSIF TG_OP = 'UPDATE' THEN
+ query_text := format('
+ SELECT array_agg(
+ jsonb_build_object(
+ ''subscriptionId'', $1,
+ ''triggerType'', $2,
+ ''handlerType'', $3,
+ ''handlerConfig'', $4,
+ ''companyId'', $5,
+ ''actorId'', $6,
+ ''workflowRunId'', $10,
+ ''event'', jsonb_build_object(
+ ''table'', $7,
+ ''operation'', $8,
+ ''recordId'', n.%I::TEXT,
+ ''new'', row_to_json(n)::jsonb,
+ ''old'', row_to_json(o)::jsonb,
+ ''timestamp'', clock_timestamp()
+ )
+ )
+ )
+ FROM batched_new n
+ JOIN batched_old o ON %s
+ WHERE n."companyId" = $5
+ AND ($9 = ''{}''::jsonb OR row_to_json(n)::jsonb @> $9)
+ AND (NOT $11 OR (to_jsonb(n) - $12) IS DISTINCT FROM (to_jsonb(o) - $12))
+ ', pk_column, pk_join);
+
+ EXECUTE query_text INTO msg_batch
+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter,
+ current_workflow_run_id,
+ sub."handlerType" IN ('AUDIT', 'SEARCH', 'EMBEDDING'),
+ ignored_columns;
+ END IF;
+
+ IF msg_batch IS NOT NULL AND array_length(msg_batch, 1) > 0 THEN
+ PERFORM pgmq.send_batch('event_system', msg_batch);
+ did_enqueue := TRUE;
+ END IF;
+
+ END LOOP;
+
+ -- Wake the Inngest drainer once per transaction: the GUC is txn-local, so a
+ -- bulk import posts a single doorbell instead of one per statement.
+ IF did_enqueue
+ AND current_setting('carbon.event_wake_sent', true) IS DISTINCT FROM 'true' THEN
+ PERFORM util.wake_event_queue();
+ PERFORM set_config('carbon.event_wake_sent', 'true', true);
+ END IF;
+
+ RETURN NULL;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/dispatch_event_interceptors.sql b/packages/database/src/event-system/functions/dispatch_event_interceptors.sql
new file mode 100644
index 0000000000..72c798e127
--- /dev/null
+++ b/packages/database/src/event-system/functions/dispatch_event_interceptors.sql
@@ -0,0 +1,35 @@
+CREATE OR REPLACE FUNCTION public.dispatch_event_interceptors()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public'
+AS $function$
+DECLARE
+ func_name TEXT;
+ payload_data JSONB;
+ old_payload_data JSONB;
+ i INTEGER;
+BEGIN
+ -- A. Normalize Data
+ IF TG_OP = 'DELETE' THEN
+ payload_data := row_to_json(OLD)::jsonb;
+ old_payload_data := payload_data;
+ ELSIF TG_OP = 'INSERT' THEN
+ payload_data := row_to_json(NEW)::jsonb;
+ old_payload_data := NULL;
+ ELSE -- UPDATE
+ payload_data := row_to_json(NEW)::jsonb;
+ old_payload_data := row_to_json(OLD)::jsonb;
+ END IF;
+
+ -- B. Execute Interceptor Functions
+ -- Loop through arguments passed in CREATE TRIGGER ... EXECUTE FUNCTION func(arg1, arg2)
+ FOR i IN 0 .. (TG_NARGS - 1) LOOP
+ func_name := TG_ARGV[i];
+ EXECUTE format('SELECT public.%I($1, $2, $3, $4)', func_name)
+ USING TG_TABLE_NAME::TEXT, TG_OP, payload_data, old_payload_data;
+ END LOOP;
+
+ IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/drop_audit_log_table.sql b/packages/database/src/event-system/functions/drop_audit_log_table.sql
new file mode 100644
index 0000000000..fd5138328f
--- /dev/null
+++ b/packages/database/src/event-system/functions/drop_audit_log_table.sql
@@ -0,0 +1,15 @@
+CREATE OR REPLACE FUNCTION public.drop_audit_log_table(p_company_id text)
+ RETURNS void
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+DECLARE
+ tbl_name TEXT;
+BEGIN
+ PERFORM assert_audit_log_access(p_company_id, NULL);
+
+ tbl_name := 'auditLog_' || p_company_id;
+
+ EXECUTE format('DROP TABLE IF EXISTS %I CASCADE', tbl_name);
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/drop_company_search_index.sql b/packages/database/src/event-system/functions/drop_company_search_index.sql
new file mode 100644
index 0000000000..5522900455
--- /dev/null
+++ b/packages/database/src/event-system/functions/drop_company_search_index.sql
@@ -0,0 +1,16 @@
+CREATE OR REPLACE FUNCTION public.drop_company_search_index(p_company_id text)
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ v_table_name TEXT;
+BEGIN
+ v_table_name := 'searchIndex_' || p_company_id;
+
+ -- Drop the search index table if it exists
+ EXECUTE format('DROP TABLE IF EXISTS %I', v_table_name);
+
+ -- Remove from registry
+ DELETE FROM "searchIndexRegistry" WHERE "companyId" = p_company_id;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/get_audit_log.sql b/packages/database/src/event-system/functions/get_audit_log.sql
new file mode 100644
index 0000000000..e84e6970ba
--- /dev/null
+++ b/packages/database/src/event-system/functions/get_audit_log.sql
@@ -0,0 +1,71 @@
+CREATE OR REPLACE FUNCTION public.get_audit_log(p_company_id text, p_entity_type text DEFAULT NULL::text, p_entity_id text DEFAULT NULL::text, p_actor_id text DEFAULT NULL::text, p_operation text DEFAULT NULL::text, p_start_date timestamp with time zone DEFAULT NULL::timestamp with time zone, p_end_date timestamp with time zone DEFAULT NULL::timestamp with time zone, p_limit integer DEFAULT 50, p_offset integer DEFAULT 0, p_search text DEFAULT NULL::text)
+ RETURNS TABLE(id text, "tableName" text, "entityType" text, "entityId" text, operation text, "actorId" text, diff jsonb, metadata jsonb, "createdAt" timestamp with time zone, "totalCount" bigint)
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+DECLARE
+ tbl_name TEXT;
+ where_clauses TEXT[] := ARRAY[]::TEXT[];
+ where_clause TEXT := '';
+ query_text TEXT;
+ count_query TEXT;
+ total BIGINT;
+BEGIN
+ PERFORM assert_audit_log_access(p_company_id, 'settings_view');
+
+ tbl_name := 'auditLog_' || p_company_id;
+
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN;
+ END IF;
+
+ IF p_entity_type IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"entityType" = %L', p_entity_type));
+ END IF;
+
+ IF p_entity_id IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"entityId" = %L', p_entity_id));
+ END IF;
+
+ IF p_actor_id IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"actorId" = %L', p_actor_id));
+ END IF;
+
+ IF p_operation IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"operation" = %L', p_operation));
+ END IF;
+
+ IF p_start_date IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"createdAt" >= %L', p_start_date));
+ END IF;
+
+ IF p_end_date IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"createdAt" <= %L', p_end_date));
+ END IF;
+
+ IF p_search IS NOT NULL AND p_search != '' THEN
+ where_clauses := array_append(where_clauses,
+ format('"entityId" ILIKE %L', '%' || p_search || '%'));
+ END IF;
+
+ IF array_length(where_clauses, 1) > 0 THEN
+ where_clause := 'WHERE ' || array_to_string(where_clauses, ' AND ');
+ END IF;
+
+ count_query := format('SELECT COUNT(*) FROM %I %s', tbl_name, where_clause);
+ EXECUTE count_query INTO total;
+
+ query_text := format('
+ SELECT "id", "tableName", "entityType", "entityId", "operation", "actorId", "diff", "metadata", "createdAt", %s::BIGINT as "totalCount"
+ FROM %I
+ %s
+ ORDER BY "createdAt" DESC
+ LIMIT %s OFFSET %s
+ ', total, tbl_name, where_clause, p_limit, p_offset);
+
+ RETURN QUERY EXECUTE query_text;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/get_audit_log_count.sql b/packages/database/src/event-system/functions/get_audit_log_count.sql
new file mode 100644
index 0000000000..a57f1ad04a
--- /dev/null
+++ b/packages/database/src/event-system/functions/get_audit_log_count.sql
@@ -0,0 +1,55 @@
+CREATE OR REPLACE FUNCTION public.get_audit_log_count(p_company_id text, p_entity_type text DEFAULT NULL::text, p_actor_id text DEFAULT NULL::text, p_operation text DEFAULT NULL::text, p_start_date timestamp with time zone DEFAULT NULL::timestamp with time zone, p_end_date timestamp with time zone DEFAULT NULL::timestamp with time zone, p_search text DEFAULT NULL::text)
+ RETURNS integer
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+DECLARE
+ tbl_name TEXT;
+ where_clauses TEXT[] := ARRAY[]::TEXT[];
+ where_clause TEXT := '';
+ count_val INTEGER;
+BEGIN
+ PERFORM assert_audit_log_access(p_company_id, 'settings_view');
+
+ tbl_name := 'auditLog_' || p_company_id;
+
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN 0;
+ END IF;
+
+ IF p_entity_type IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"entityType" = %L', p_entity_type));
+ END IF;
+
+ IF p_actor_id IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"actorId" = %L', p_actor_id));
+ END IF;
+
+ IF p_operation IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"operation" = %L', p_operation));
+ END IF;
+
+ IF p_start_date IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"createdAt" >= %L', p_start_date));
+ END IF;
+
+ IF p_end_date IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"createdAt" <= %L', p_end_date));
+ END IF;
+
+ IF p_search IS NOT NULL AND p_search != '' THEN
+ where_clauses := array_append(where_clauses,
+ format('"entityId" ILIKE %L', '%' || p_search || '%'));
+ END IF;
+
+ IF array_length(where_clauses, 1) > 0 THEN
+ where_clause := 'WHERE ' || array_to_string(where_clauses, ' AND ');
+ END IF;
+
+ EXECUTE format('SELECT COUNT(*)::INTEGER FROM %I %s', tbl_name, where_clause) INTO count_val;
+ RETURN count_val;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/get_audit_logs_for_archive.sql b/packages/database/src/event-system/functions/get_audit_logs_for_archive.sql
new file mode 100644
index 0000000000..57c67ade64
--- /dev/null
+++ b/packages/database/src/event-system/functions/get_audit_logs_for_archive.sql
@@ -0,0 +1,28 @@
+CREATE OR REPLACE FUNCTION public.get_audit_logs_for_archive(p_company_id text, p_before_date timestamp with time zone)
+ RETURNS TABLE(id text, "tableName" text, "entityType" text, "entityId" text, operation text, "actorId" text, diff jsonb, metadata jsonb, "createdAt" timestamp with time zone)
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+DECLARE
+ tbl_name TEXT;
+BEGIN
+ PERFORM assert_audit_log_access(p_company_id, NULL);
+
+ tbl_name := 'auditLog_' || p_company_id;
+
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN;
+ END IF;
+
+ RETURN QUERY EXECUTE format('
+ SELECT "id", "tableName", "entityType", "entityId", "operation", "actorId", "diff", "metadata", "createdAt"
+ FROM %I
+ WHERE "createdAt" < $1
+ ORDER BY "createdAt" ASC
+ ', tbl_name)
+ USING p_before_date;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/get_entity_audit_log.sql b/packages/database/src/event-system/functions/get_entity_audit_log.sql
new file mode 100644
index 0000000000..ff3c3bb678
--- /dev/null
+++ b/packages/database/src/event-system/functions/get_entity_audit_log.sql
@@ -0,0 +1,40 @@
+CREATE OR REPLACE FUNCTION public.get_entity_audit_log(p_company_id text, p_entity_type text, p_entity_id text, p_limit integer DEFAULT 50, p_offset integer DEFAULT 0, p_record_id text DEFAULT NULL::text)
+ RETURNS TABLE(id text, "tableName" text, "entityType" text, "entityId" text, "recordId" text, operation text, "actorId" text, diff jsonb, metadata jsonb, "createdAt" timestamp with time zone)
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+DECLARE
+ tbl_name TEXT;
+BEGIN
+ PERFORM assert_audit_log_access(p_company_id, 'settings_view');
+
+ tbl_name := 'auditLog_' || p_company_id;
+
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN;
+ END IF;
+
+ IF p_record_id IS NULL THEN
+ RETURN QUERY EXECUTE format('
+ SELECT "id", "tableName", "entityType", "entityId", "recordId", "operation", "actorId", "diff", "metadata", "createdAt"
+ FROM %I
+ WHERE "entityType" = $1 AND "entityId" = $2
+ ORDER BY "createdAt" DESC
+ LIMIT $3 OFFSET $4
+ ', tbl_name)
+ USING p_entity_type, p_entity_id, p_limit, p_offset;
+ ELSE
+ RETURN QUERY EXECUTE format('
+ SELECT "id", "tableName", "entityType", "entityId", "recordId", "operation", "actorId", "diff", "metadata", "createdAt"
+ FROM %I
+ WHERE "entityType" = $1 AND "entityId" = $2 AND "recordId" = $3
+ ORDER BY "createdAt" DESC
+ LIMIT $4 OFFSET $5
+ ', tbl_name)
+ USING p_entity_type, p_entity_id, p_record_id, p_limit, p_offset;
+ END IF;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/get_primary_key_column.sql b/packages/database/src/event-system/functions/get_primary_key_column.sql
new file mode 100644
index 0000000000..4851fed036
--- /dev/null
+++ b/packages/database/src/event-system/functions/get_primary_key_column.sql
@@ -0,0 +1,28 @@
+CREATE OR REPLACE FUNCTION public.get_primary_key_column(p_table_name text)
+ RETURNS text
+ LANGUAGE plpgsql
+ STABLE
+AS $function$
+DECLARE
+ pk_column TEXT;
+BEGIN
+ -- First try to get primary key
+ SELECT a.attname INTO pk_column
+ FROM pg_index i
+ JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
+ WHERE i.indrelid = ('"' || p_table_name || '"')::regclass
+ AND i.indisprimary
+ LIMIT 1;
+
+ -- If no primary key, try to get any unique index column
+ IF pk_column IS NULL THEN
+ SELECT a.attname INTO pk_column
+ FROM pg_index i
+ JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
+ WHERE i.indrelid = ('"' || p_table_name || '"')::regclass
+ LIMIT 1;
+ END IF;
+
+ RETURN COALESCE(pk_column, 'id');
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/get_primary_key_columns.sql b/packages/database/src/event-system/functions/get_primary_key_columns.sql
new file mode 100644
index 0000000000..7615d1c4d2
--- /dev/null
+++ b/packages/database/src/event-system/functions/get_primary_key_columns.sql
@@ -0,0 +1,45 @@
+CREATE OR REPLACE FUNCTION public.get_primary_key_columns(p_table_name text)
+ RETURNS text[]
+ LANGUAGE plpgsql
+ STABLE
+AS $function$
+DECLARE
+ pk_columns TEXT[];
+BEGIN
+ -- All columns of the primary key
+ SELECT array_agg(a.attname ORDER BY a.attnum) INTO pk_columns
+ FROM pg_index i
+ JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
+ WHERE i.indrelid = ('"' || p_table_name || '"')::regclass
+ AND i.indisprimary;
+
+ -- No PK: key columns of the smallest valid, non-partial, non-expression
+ -- unique index. Partial/expression indexes don't guarantee row identity for
+ -- every row, and INCLUDE columns (positions past indnkeyatts) aren't part of
+ -- the uniqueness constraint — the slice keeps key columns only.
+ IF pk_columns IS NULL THEN
+ SELECT array_agg(a.attname ORDER BY a.attnum) INTO pk_columns
+ FROM pg_index i
+ JOIN pg_attribute a ON a.attrelid = i.indrelid
+ AND a.attnum = ANY ((i.indkey::int2[])[1:i.indnkeyatts])
+ WHERE i.indexrelid = (
+ SELECT i2.indexrelid
+ FROM pg_index i2
+ WHERE i2.indrelid = ('"' || p_table_name || '"')::regclass
+ AND i2.indisunique
+ AND i2.indisvalid
+ AND i2.indpred IS NULL
+ AND i2.indexprs IS NULL
+ ORDER BY i2.indnkeyatts ASC
+ LIMIT 1
+ );
+ END IF;
+
+ -- Last resort: the legacy single-column resolver
+ IF pk_columns IS NULL OR array_length(pk_columns, 1) IS NULL THEN
+ pk_columns := ARRAY[public.get_primary_key_column(p_table_name)];
+ END IF;
+
+ RETURN pk_columns;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/insert_audit_log_batch.sql b/packages/database/src/event-system/functions/insert_audit_log_batch.sql
new file mode 100644
index 0000000000..e26223f6c7
--- /dev/null
+++ b/packages/database/src/event-system/functions/insert_audit_log_batch.sql
@@ -0,0 +1,38 @@
+CREATE OR REPLACE FUNCTION public.insert_audit_log_batch(p_company_id text, p_entries jsonb[])
+ RETURNS integer
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+DECLARE
+ tbl_name TEXT;
+ inserted_count INTEGER := 0;
+BEGIN
+ PERFORM assert_audit_log_access(p_company_id, NULL);
+
+ tbl_name := 'auditLog_' || p_company_id;
+
+ PERFORM create_audit_log_table(p_company_id);
+
+ -- createdAt is the entry's own (the original event time) when it has one.
+ -- clock_timestamp() is evaluated per row, so the rest still get distinct
+ -- values rather than sharing NOW().
+ EXECUTE format('
+ INSERT INTO %I ("tableName", "entityType", "entityId", "recordId", "operation", "actorId", "diff", "metadata", "createdAt")
+ SELECT
+ e->>''tableName'',
+ e->>''entityType'',
+ e->>''entityId'',
+ e->>''recordId'',
+ e->>''operation'',
+ e->>''actorId'',
+ NULLIF(e->''diff'', ''null''::jsonb),
+ NULLIF(e->''metadata'', ''null''::jsonb),
+ COALESCE((e->>''createdAt'')::TIMESTAMPTZ, clock_timestamp())
+ FROM unnest($1) AS e
+ ', tbl_name)
+ USING p_entries;
+ GET DIAGNOSTICS inserted_count = ROW_COUNT;
+
+ RETURN inserted_count;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/on_company_created_search_index.sql b/packages/database/src/event-system/functions/on_company_created_search_index.sql
new file mode 100644
index 0000000000..1d77f0168f
--- /dev/null
+++ b/packages/database/src/event-system/functions/on_company_created_search_index.sql
@@ -0,0 +1,12 @@
+CREATE OR REPLACE FUNCTION public.on_company_created_search_index()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+BEGIN
+ PERFORM create_company_search_index(NEW.id);
+ PERFORM create_search_subscriptions_for_company(NEW.id);
+ PERFORM create_embedding_subscriptions_for_company(NEW.id);
+ RETURN NEW;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/populate_company_search_index.sql b/packages/database/src/event-system/functions/populate_company_search_index.sql
new file mode 100644
index 0000000000..fc70dad0eb
--- /dev/null
+++ b/packages/database/src/event-system/functions/populate_company_search_index.sql
@@ -0,0 +1,78 @@
+CREATE OR REPLACE FUNCTION public.populate_company_search_index(p_company_id text)
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ v_table_name TEXT := 'searchIndex_' || p_company_id;
+BEGIN
+ -- Populate employees
+ EXECUTE format('
+ INSERT INTO %I ("entityType", "entityId", "title", "link", "tags", "metadata", "searchVector")
+ SELECT
+ ''employee'',
+ e.id,
+ COALESCE(u."fullName", ''''),
+ ''/x/person/'' || e.id,
+ ARRAY_REMOVE(ARRAY[et.name], NULL),
+ jsonb_build_object(''active'', e.active),
+ to_tsvector(''english'', COALESCE(u."fullName", '''') || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[et.name], NULL), '' ''), ''''))
+ FROM "employee" e
+ INNER JOIN "user" u ON u.id = e.id
+ LEFT JOIN "employeeType" et ON et.id = e."employeeTypeId"
+ WHERE e."companyId" = $1 AND e.active = true
+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET
+ "title" = EXCLUDED."title",
+ "tags" = EXCLUDED."tags",
+ "metadata" = EXCLUDED."metadata",
+ "searchVector" = EXCLUDED."searchVector",
+ "updatedAt" = NOW()
+ ', v_table_name) USING p_company_id;
+
+ -- Populate customers (join customerTax for taxId)
+ EXECUTE format('
+ INSERT INTO %I ("entityType", "entityId", "title", "link", "tags", "metadata", "searchVector")
+ SELECT
+ ''customer'',
+ c.id,
+ c.name,
+ ''/x/customer/'' || c.id,
+ ARRAY_REMOVE(ARRAY[ct.name, cs.name], NULL),
+ jsonb_build_object(''taxId'', ctx."taxId"),
+ to_tsvector(''english'', c.name || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[ct.name, cs.name], NULL), '' ''), ''''))
+ FROM "customer" c
+ LEFT JOIN "customerTax" ctx ON ctx."customerId" = c.id
+ LEFT JOIN "customerType" ct ON ct.id = c."customerTypeId"
+ LEFT JOIN "customerStatus" cs ON cs.id = c."customerStatusId"
+ WHERE c."companyId" = $1
+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET
+ "title" = EXCLUDED."title",
+ "tags" = EXCLUDED."tags",
+ "metadata" = EXCLUDED."metadata",
+ "searchVector" = EXCLUDED."searchVector",
+ "updatedAt" = NOW()
+ ', v_table_name) USING p_company_id;
+
+ -- Populate suppliers (join supplierTax for taxId)
+ EXECUTE format('
+ INSERT INTO %I ("entityType", "entityId", "title", "link", "tags", "metadata", "searchVector")
+ SELECT
+ ''supplier'',
+ s.id,
+ s.name,
+ ''/x/supplier/'' || s.id,
+ ARRAY_REMOVE(ARRAY[st.name, s."supplierStatus"::TEXT], NULL),
+ jsonb_build_object(''taxId'', stx."taxId"),
+ to_tsvector(''english'', s.name || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[st.name, s."supplierStatus"::TEXT], NULL), '' ''), ''''))
+ FROM "supplier" s
+ LEFT JOIN "supplierTax" stx ON stx."supplierId" = s.id
+ LEFT JOIN "supplierType" st ON st.id = s."supplierTypeId"
+ WHERE s."companyId" = $1
+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET
+ "title" = EXCLUDED."title",
+ "tags" = EXCLUDED."tags",
+ "metadata" = EXCLUDED."metadata",
+ "searchVector" = EXCLUDED."searchVector",
+ "updatedAt" = NOW()
+ ', v_table_name) USING p_company_id;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/prevent_audit_log_mutation.sql b/packages/database/src/event-system/functions/prevent_audit_log_mutation.sql
new file mode 100644
index 0000000000..203e70425a
--- /dev/null
+++ b/packages/database/src/event-system/functions/prevent_audit_log_mutation.sql
@@ -0,0 +1,15 @@
+CREATE OR REPLACE FUNCTION public.prevent_audit_log_mutation()
+ RETURNS trigger
+ LANGUAGE plpgsql
+AS $function$
+BEGIN
+ IF TG_OP = 'UPDATE' THEN
+ RAISE EXCEPTION 'Audit log records are immutable (append-only)';
+ END IF;
+ -- DELETE: permitted only during retention/archival, which sets this flag.
+ IF current_setting('app.audit_archiving', true) IS DISTINCT FROM 'on' THEN
+ RAISE EXCEPTION 'Audit log records cannot be deleted (retention/archival only)';
+ END IF;
+ RETURN OLD;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/search_company_index.sql b/packages/database/src/event-system/functions/search_company_index.sql
new file mode 100644
index 0000000000..16f7a8faea
--- /dev/null
+++ b/packages/database/src/event-system/functions/search_company_index.sql
@@ -0,0 +1,69 @@
+CREATE OR REPLACE FUNCTION public.search_company_index(p_company_id text, p_query text, p_entity_types text[], p_limit integer DEFAULT 20)
+ RETURNS TABLE(id bigint, "entityType" text, "entityId" text, title text, description text, link text, tags text[], metadata jsonb)
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ v_table_name TEXT;
+ v_sanitized TEXT;
+ v_tsquery_text TEXT;
+ v_like_pattern TEXT;
+ v_prefix_pattern TEXT;
+BEGIN
+ v_table_name := 'searchIndex_' || p_company_id;
+
+ -- Strip tsquery operators; keep alphanumerics, whitespace, `_`, `-`.
+ v_sanitized := regexp_replace(coalesce(trim(p_query), ''), '[^[:alnum:][:space:]_-]', ' ', 'g');
+ v_sanitized := trim(regexp_replace(v_sanitized, '\s+', ' ', 'g'));
+
+ IF v_sanitized = '' THEN
+ RETURN;
+ END IF;
+
+ -- Build `tok1:* & tok2:* & ...` for the FTS branch (word-prefix match).
+ SELECT string_agg(tok || ':*', ' & ')
+ INTO v_tsquery_text
+ FROM regexp_split_to_table(v_sanitized, '\s+') AS tok
+ WHERE tok ~ '[[:alnum:]]';
+
+ -- Defensive fallback - should not trigger in practice since v_sanitized is
+ -- non-empty and contains at least one alnum, but keep the function robust.
+ IF v_tsquery_text IS NULL OR v_tsquery_text = '' THEN
+ RETURN;
+ END IF;
+
+ -- Substring + prefix patterns use the ORIGINAL sanitized string so users
+ -- can search by any slice of a stored title (e.g. "269" inside "S000269").
+ v_like_pattern := '%' || v_sanitized || '%';
+ v_prefix_pattern := v_sanitized || '%';
+
+ RETURN QUERY EXECUTE format('
+ WITH q AS (
+ SELECT to_tsquery(''english'', $1) AS query
+ )
+ SELECT
+ si.id,
+ si."entityType",
+ si."entityId",
+ si.title,
+ si.description,
+ si.link,
+ si.tags,
+ si.metadata
+ FROM %I si, q
+ WHERE si."entityType" = ANY($2)
+ AND (
+ si."searchVector" @@ q.query
+ OR si.title ILIKE $4
+ OR si.description ILIKE $4
+ )
+ ORDER BY
+ -- Boost rows where the title starts with the query (e.g. typing "S000"
+ -- pins "S000269" to the top).
+ CASE WHEN si.title ILIKE $5 THEN 0 ELSE 1 END,
+ ts_rank_cd(si."searchVector", q.query) DESC,
+ si.id DESC
+ LIMIT $3
+ ', v_table_name)
+ USING v_tsquery_text, p_entity_types, p_limit, v_like_pattern, v_prefix_pattern;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/secure_audit_log_table.sql b/packages/database/src/event-system/functions/secure_audit_log_table.sql
new file mode 100644
index 0000000000..c42b7bfb19
--- /dev/null
+++ b/packages/database/src/event-system/functions/secure_audit_log_table.sql
@@ -0,0 +1,22 @@
+CREATE OR REPLACE FUNCTION public.secure_audit_log_table(p_company_id text)
+ RETURNS void
+ LANGUAGE plpgsql
+ SET search_path TO 'public'
+AS $function$
+DECLARE
+ tbl_name TEXT := 'auditLog_' || p_company_id;
+BEGIN
+ EXECUTE format('DROP POLICY IF EXISTS "audit_log_access" ON %I', tbl_name);
+ EXECUTE format('DROP POLICY IF EXISTS "SELECT" ON %I', tbl_name);
+ EXECUTE format(
+ 'CREATE POLICY "SELECT" ON %I FOR SELECT USING (
+ %L = ANY ((SELECT get_companies_with_employee_permission(''settings_view''))::text[])
+ )',
+ tbl_name, p_company_id
+ );
+ EXECUTE format(
+ 'REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON %I FROM anon, authenticated',
+ tbl_name
+ );
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/upsert_to_search_index.sql b/packages/database/src/event-system/functions/upsert_to_search_index.sql
new file mode 100644
index 0000000000..3ba53ed0cb
--- /dev/null
+++ b/packages/database/src/event-system/functions/upsert_to_search_index.sql
@@ -0,0 +1,33 @@
+CREATE OR REPLACE FUNCTION public.upsert_to_search_index(p_company_id text, p_entity_type text, p_entity_id text, p_title text, p_description text, p_link text, p_tags text[], p_metadata jsonb)
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ v_table_name TEXT;
+ v_search_text TEXT;
+BEGIN
+ v_table_name := 'searchIndex_' || p_company_id;
+ v_search_text := p_title || ' ' || COALESCE(p_description, '') || ' ' || COALESCE(array_to_string(p_tags, ' '), '');
+
+ EXECUTE format('
+ INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")
+ VALUES ($1, $2, $3, $4, $5, $6, $7, to_tsvector(''english'', $8))
+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET
+ "title" = EXCLUDED."title",
+ "description" = EXCLUDED."description",
+ "link" = EXCLUDED."link",
+ "tags" = EXCLUDED."tags",
+ "metadata" = EXCLUDED."metadata",
+ "searchVector" = EXCLUDED."searchVector",
+ "updatedAt" = NOW()
+ ', v_table_name) USING
+ p_entity_type,
+ p_entity_id,
+ p_title,
+ COALESCE(p_description, ''),
+ p_link,
+ COALESCE(p_tags, ARRAY[]::text[]),
+ COALESCE(p_metadata, '{}'::jsonb),
+ v_search_text;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/util.anon_key.sql b/packages/database/src/event-system/functions/util.anon_key.sql
new file mode 100644
index 0000000000..d37fbdac29
--- /dev/null
+++ b/packages/database/src/event-system/functions/util.anon_key.sql
@@ -0,0 +1,12 @@
+CREATE OR REPLACE FUNCTION util.anon_key()
+ RETURNS text
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+DECLARE
+ anon_key text;
+BEGIN
+ SELECT "anonKey" INTO anon_key FROM "config" LIMIT 1;
+ RETURN anon_key;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/util.can_manage_event_subscription.sql b/packages/database/src/event-system/functions/util.can_manage_event_subscription.sql
new file mode 100644
index 0000000000..bbf9a7a958
--- /dev/null
+++ b/packages/database/src/event-system/functions/util.can_manage_event_subscription.sql
@@ -0,0 +1,20 @@
+CREATE OR REPLACE FUNCTION util.can_manage_event_subscription(p_company_id text, p_handler_type text)
+ RETURNS boolean
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public', 'pg_temp'
+AS $function$
+BEGIN
+ IF (SELECT auth.role()) = 'service_role' THEN
+ RETURN TRUE;
+ END IF;
+
+ IF p_handler_type = 'WEBHOOK' THEN
+ RETURN p_company_id = ANY (COALESCE((SELECT get_companies_with_employee_permission('settings_create'))::text[], ARRAY[]::text[]))
+ OR p_company_id = ANY (COALESCE((SELECT get_companies_with_employee_permission('settings_update'))::text[], ARRAY[]::text[]))
+ OR p_company_id = ANY (COALESCE((SELECT get_companies_with_employee_permission('settings_delete'))::text[], ARRAY[]::text[]));
+ END IF;
+
+ RETURN p_company_id = ANY (COALESCE((SELECT get_companies_with_employee_role())::text[], ARRAY[]::text[]));
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/util.clear_column.sql b/packages/database/src/event-system/functions/util.clear_column.sql
new file mode 100644
index 0000000000..e5376d6775
--- /dev/null
+++ b/packages/database/src/event-system/functions/util.clear_column.sql
@@ -0,0 +1,11 @@
+CREATE OR REPLACE FUNCTION util.clear_column()
+ RETURNS trigger
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ clear_column text := TG_ARGV[0];
+BEGIN
+ NEW := NEW #= hstore(clear_column, NULL);
+ RETURN NEW;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/util.invoke_edge_function.sql b/packages/database/src/event-system/functions/util.invoke_edge_function.sql
new file mode 100644
index 0000000000..30524bb0fc
--- /dev/null
+++ b/packages/database/src/event-system/functions/util.invoke_edge_function.sql
@@ -0,0 +1,31 @@
+CREATE OR REPLACE FUNCTION util.invoke_edge_function(name text, body jsonb, timeout_milliseconds integer DEFAULT ((5 * 60) * 1000))
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ headers_raw text;
+ auth_header text;
+BEGIN
+ -- If we're in a PostgREST session, reuse the request headers for authorization
+ headers_raw := current_setting('request.headers', true);
+
+ -- Only try to parse if headers are present
+ auth_header := CASE
+ WHEN headers_raw IS NOT NULL THEN
+ (headers_raw::json->>'authorization')
+ ELSE
+ 'Bearer ' || util.anon_key()
+ END;
+
+ -- Perform async HTTP request to the edge function
+ PERFORM net.http_post(
+ url => util.api_url() || '/functions/v1/' || name,
+ headers => jsonb_build_object(
+ 'Content-Type', 'application/json',
+ 'Authorization', auth_header
+ ),
+ body => body,
+ timeout_milliseconds => timeout_milliseconds
+ );
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/util.process_embeddings.sql b/packages/database/src/event-system/functions/util.process_embeddings.sql
new file mode 100644
index 0000000000..99f54ef5fa
--- /dev/null
+++ b/packages/database/src/event-system/functions/util.process_embeddings.sql
@@ -0,0 +1,44 @@
+CREATE OR REPLACE FUNCTION util.process_embeddings(batch_size integer DEFAULT 10, max_requests integer DEFAULT 10, timeout_milliseconds integer DEFAULT ((5 * 60) * 1000))
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ job_batches JSONB[];
+ batch JSONB;
+BEGIN
+ WITH
+ -- First get jobs and assign batch numbers
+ numbered_jobs AS (
+ SELECT
+ message || jsonb_build_object('jobId', msg_id) AS job_info,
+ (row_number() OVER (ORDER BY 1) - 1) / batch_size AS batch_num
+ FROM pgmq.read(
+ queue_name => 'embedding_jobs',
+ vt => timeout_milliseconds / 1000,
+ qty => max_requests * batch_size
+ )
+ ),
+ -- Then group jobs into batches
+ batched_jobs AS (
+ SELECT
+ jsonb_agg(job_info) AS batch_array,
+ batch_num
+ FROM numbered_jobs
+ GROUP BY batch_num
+ )
+ -- Finally aggregate all batches into array, defaulting to an empty array
+ -- (FOREACH errors on NULL arrays, e.g. when the queue has no pending jobs)
+ SELECT COALESCE(array_agg(batch_array), ARRAY[]::JSONB[])
+ FROM batched_jobs
+ INTO job_batches;
+
+ -- Invoke the embed edge function for each batch
+ FOREACH batch IN ARRAY job_batches LOOP
+ PERFORM util.invoke_edge_function(
+ name => 'embed',
+ body => batch,
+ timeout_milliseconds => timeout_milliseconds
+ );
+ END LOOP;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/util.queue_embeddings.sql b/packages/database/src/event-system/functions/util.queue_embeddings.sql
new file mode 100644
index 0000000000..860cecc9db
--- /dev/null
+++ b/packages/database/src/event-system/functions/util.queue_embeddings.sql
@@ -0,0 +1,14 @@
+CREATE OR REPLACE FUNCTION util.queue_embeddings(record_id text, embedding_table text)
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+BEGIN
+ PERFORM pgmq.send(
+ queue_name => 'embedding_jobs',
+ msg => jsonb_build_object(
+ 'id', record_id,
+ 'table', embedding_table
+ )
+ );
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/util.sweep_event_queue.sql b/packages/database/src/event-system/functions/util.sweep_event_queue.sql
new file mode 100644
index 0000000000..ce3736fd39
--- /dev/null
+++ b/packages/database/src/event-system/functions/util.sweep_event_queue.sql
@@ -0,0 +1,16 @@
+CREATE OR REPLACE FUNCTION util.sweep_event_queue()
+ RETURNS void
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public', 'pgmq', 'extensions'
+AS $function$
+BEGIN
+ -- Only visible messages count: rows hidden by a read's visibility timeout
+ -- are already being drained and must not trigger a spurious wake.
+ IF EXISTS (
+ SELECT 1 FROM pgmq.q_event_system WHERE vt <= clock_timestamp()
+ ) THEN
+ PERFORM util.wake_event_queue();
+ END IF;
+END;
+$function$;
diff --git a/packages/database/src/event-system/functions/util.wake_event_queue.sql b/packages/database/src/event-system/functions/util.wake_event_queue.sql
new file mode 100644
index 0000000000..abe0be02e5
--- /dev/null
+++ b/packages/database/src/event-system/functions/util.wake_event_queue.sql
@@ -0,0 +1,29 @@
+CREATE OR REPLACE FUNCTION util.wake_event_queue()
+ RETURNS void
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public', 'extensions'
+AS $function$
+DECLARE
+ api_url TEXT;
+ anon_key TEXT;
+BEGIN
+ SELECT "apiUrl", "anonKey" INTO api_url, anon_key FROM "config" LIMIT 1;
+
+ IF api_url IS NULL THEN
+ RETURN;
+ END IF;
+
+ PERFORM net.http_post(
+ api_url || '/functions/v1/event-wake',
+ '{}'::jsonb,
+ '{}'::jsonb,
+ jsonb_build_object(
+ 'Content-Type', 'application/json',
+ 'Authorization', 'Bearer ' || anon_key
+ )
+ );
+EXCEPTION WHEN OTHERS THEN
+ RAISE LOG 'wake_event_queue failed: % %', SQLERRM, SQLSTATE;
+END;
+$function$;
diff --git a/packages/database/src/seed-dev.ts b/packages/database/src/seed-dev.ts
index 1b0c799fad..54f947da48 100644
--- a/packages/database/src/seed-dev.ts
+++ b/packages/database/src/seed-dev.ts
@@ -28,7 +28,7 @@ import { homedir } from "node:os";
import path from "node:path";
import process from "node:process";
import { fileURLToPath } from "node:url";
-import { getPostgresConnectionPool } from "./client.ts";
+import { getProcessPool } from "./client.ts";
import { bootstrap, DEV_PASSWORD } from "./datasets/bootstrap.ts";
import { loadEnv, parseSeedArgs } from "./datasets/cli.ts";
import { applyDataset, datasetKeys, getDataset } from "./datasets/index.ts";
@@ -49,7 +49,7 @@ async function main() {
`\nSeeding development environment for: ${email} (${datasetKey})\n`
);
- const pool = getPostgresConnectionPool(1);
+ const pool = getProcessPool();
const client = await pool.connect();
let seeded: { companyId: string; userId: string } | null = null;
diff --git a/packages/database/supabase/functions/lib/postgres/index.ts b/packages/database/supabase/functions/lib/postgres/index.ts
index 515d26cf2b..ef92a75e88 100644
--- a/packages/database/supabase/functions/lib/postgres/index.ts
+++ b/packages/database/supabase/functions/lib/postgres/index.ts
@@ -127,86 +127,103 @@ function registerNodeTypeParsers(): void {
}
registerNodeTypeParsers();
+/**
+ * An edge function's pool of `connections`, cached per size. Edge functions
+ * only: on Node every caller shares `getProcessPool()`.
+ */
export function getPostgresConnectionPool(connections: number): Pool {
+ if (getRuntime() !== "deno") {
+ throw new Error(
+ "getPostgresConnectionPool is for edge functions; on Node use getProcessPool()"
+ );
+ }
const cached = poolCache.get(connections);
- // An ended pool can never serve connections again ("Cannot use a pool after
- // calling end on the pool") — evict it so callers get a live pool instead of
- // a permanently broken process. `ending` is node-postgres only; on Deno it's
- // undefined and the cached pool is always reused.
- if (cached && !(cached as { ending?: boolean }).ending) return cached;
-
- const pool = createPostgresConnectionPool(connections);
+ if (cached) return cached;
+ const pool = createDenoPool(connections);
poolCache.set(connections, pool);
return pool;
}
-function createPostgresConnectionPool(connections: number): Pool {
- const runtime = getRuntime();
+/** Connections in a Node process's one pool. The pools it replaced (10, 5 and
+ * 1, one per size asked for) held up to 16 between them. */
+const PROCESS_POOL_SIZE = 16;
+let processPool: Pool | undefined;
- switch (runtime) {
- case "deno": {
- // @ts-expect-error -- Deno global is only available in Deno runtime
- const url = Deno.env.get("SUPABASE_DB_URL")!;
- const connectionPoolerUrl = url.includes("supabase.co")
- ? url.replace("5432", "6543")
- : url;
- // deno-postgres accepts EITHER a URI string OR a ClientOptions object —
- // the NUMERIC decoder (`controls`) only fits on the object form, so
- // parse the URL ourselves. sslmode mapping mirrors the driver's own:
- // disable -> off; require/verify-* -> enforce; otherwise attempt TLS
- // and fall back (its default).
- const u = new URL(connectionPoolerUrl);
- const sslmode = u.searchParams.get("sslmode");
- const DenoPool = Pool as unknown as DenoPoolConstructor;
- const options: DenoClientOptions = {
- user: decodeURIComponent(u.username),
- password: decodeURIComponent(u.password),
- hostname: u.hostname,
- port: u.port || 5432,
- database: u.pathname.replace(/^\//, "") || undefined,
- controls: {
- // The driver applies these element-wise to array types via the
- // base-type fallback, so arrays decode too. Must mirror
- // `registerNodeTypeParsers` exactly.
- decoders: { [NUMERIC_OID]: Number, [DATE_OID]: identity },
- },
- };
- if (sslmode) {
- options.tls = {
- enabled: sslmode !== "disable",
- enforce: ["require", "verify-ca", "verify-full"].includes(sslmode),
- };
- }
- return new DenoPool(options, connections);
- }
- case "node": {
- const url = process.env.SUPABASE_DB_URL!;
- const connectionPoolerUrl = url.includes("supabase.co")
- ? url.replace("5432", "6543")
- : url;
- const pool = new Pool({
- connectionString: connectionPoolerUrl,
- max: connections,
- // Fail fast instead of queueing forever when the DB/pooler is
- // unreachable or the pool is saturated.
- connectionTimeoutMillis: 10_000,
- // Rotate connections so direct (non-Supavisor) connections can't rot
- // through NAT/firewall idle limits.
- maxLifetimeSeconds: 1800,
- });
- // pg-pool purges the broken client before emitting 'error'; the listener
- // exists because an unlistened EventEmitter 'error' crashes the process.
- pool.on("error", (err) => {
- console.error("postgres pool: idle client error", err);
- });
- return pool;
- }
+/**
+ * The Node process's one connection pool, shared by the app's Kysely client,
+ * the jobs and the scripts. Only a script about to exit ends it. A pool per
+ * caller let one process hold several, and a caller that ended its pool broke
+ * everyone else holding it.
+ */
+export function getProcessPool(): Pool {
+ if (getRuntime() !== "node") {
+ throw new Error("getProcessPool is Node-only");
+ }
+ // An ended pool can never serve again ("Cannot use a pool after calling end
+ // on the pool"): a script that ended it and carries on gets a new one.
+ if (!processPool || (processPool as { ending?: boolean }).ending) {
+ processPool = createNodePool(PROCESS_POOL_SIZE);
+ }
+ return processPool;
+}
- default:
- throw new Error(
- "getPostgresConnectionPool is not supported in non-server environments"
- );
+function createDenoPool(connections: number): Pool {
+ // @ts-expect-error -- Deno global is only available in Deno runtime
+ const url = Deno.env.get("SUPABASE_DB_URL")!;
+ const connectionPoolerUrl = url.includes("supabase.co")
+ ? url.replace("5432", "6543")
+ : url;
+ // deno-postgres accepts EITHER a URI string OR a ClientOptions object —
+ // the NUMERIC decoder (`controls`) only fits on the object form, so
+ // parse the URL ourselves. sslmode mapping mirrors the driver's own:
+ // disable -> off; require/verify-* -> enforce; otherwise attempt TLS
+ // and fall back (its default).
+ const u = new URL(connectionPoolerUrl);
+ const sslmode = u.searchParams.get("sslmode");
+ const DenoPool = Pool as unknown as DenoPoolConstructor;
+ const options: DenoClientOptions = {
+ user: decodeURIComponent(u.username),
+ password: decodeURIComponent(u.password),
+ hostname: u.hostname,
+ port: u.port || 5432,
+ database: u.pathname.replace(/^\//, "") || undefined,
+ controls: {
+ // The driver applies these element-wise to array types via the
+ // base-type fallback, so arrays decode too. Must mirror
+ // `registerNodeTypeParsers` exactly.
+ decoders: { [NUMERIC_OID]: Number, [DATE_OID]: identity },
+ },
+ };
+ if (sslmode) {
+ options.tls = {
+ enabled: sslmode !== "disable",
+ enforce: ["require", "verify-ca", "verify-full"].includes(sslmode),
+ };
}
+ return new DenoPool(options, connections);
+}
+
+function createNodePool(connections: number): Pool {
+ const url = process.env.SUPABASE_DB_URL!;
+ const connectionPoolerUrl = url.includes("supabase.co")
+ ? url.replace("5432", "6543")
+ : url;
+ const pool = new Pool({
+ connectionString: connectionPoolerUrl,
+ max: connections,
+ // Fail fast instead of queueing forever when the DB/pooler is
+ // unreachable or the pool is saturated.
+ connectionTimeoutMillis: 10_000,
+ // Rotate connections so direct (non-Supavisor) connections can't rot
+ // through NAT/firewall idle limits.
+ maxLifetimeSeconds: 1800,
+ });
+ // pg-pool purges the broken client before emitting 'error'; the listener
+ // exists because an unlistened EventEmitter 'error' crashes the process.
+ pool.on("error", (err) => {
+ console.error("postgres pool: idle client error", err);
+ });
+ return pool;
}
interface PgDriverConstructor {
diff --git a/packages/database/supabase/migrations/20261002114954_event-system-functions.sql b/packages/database/supabase/migrations/20261002114954_event-system-functions.sql
new file mode 100644
index 0000000000..d65c7ef170
--- /dev/null
+++ b/packages/database/supabase/migrations/20261002114954_event-system-functions.sql
@@ -0,0 +1,1561 @@
+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.
+
+-- Ships these rules to databases where `authz sync` does not run after migrations yet.
+
+CREATE OR REPLACE FUNCTION public.assert_audit_log_access(p_company_id text, p_permission text)
+ RETURNS void
+ LANGUAGE plpgsql
+ STABLE SECURITY DEFINER
+ SET search_path TO 'public'
+AS $function$
+BEGIN
+ IF current_setting('role', true) NOT IN ('anon', 'authenticated') THEN
+ RETURN;
+ END IF;
+
+ IF p_permission IS NOT NULL AND p_company_id = ANY (
+ COALESCE(get_companies_with_employee_permission(p_permission), '{}')::text[]
+ ) THEN
+ RETURN;
+ END IF;
+
+ RAISE EXCEPTION 'Not authorized to access the audit log for this company'
+ USING ERRCODE = 'insufficient_privilege';
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.attach_audit_log_append_only(p_table_name text)
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+BEGIN
+ EXECUTE format('DROP TRIGGER IF EXISTS "append_only" ON %I', p_table_name);
+ EXECUTE format(
+ 'CREATE TRIGGER "append_only" BEFORE UPDATE OR DELETE ON %I
+ FOR EACH ROW EXECUTE FUNCTION prevent_audit_log_mutation()',
+ p_table_name
+ );
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.attach_event_trigger(table_name_text text, sync_functions text[] DEFAULT ARRAY[]::text[], after_sync_functions text[] DEFAULT ARRAY[]::text[])
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ sync_args TEXT;
+ after_sync_args TEXT;
+BEGIN
+ -- A. Attach BEFORE SYNC Trigger (Row Level) -- unchanged behavior
+ IF array_length(sync_functions, 1) > 0 THEN
+ SELECT string_agg(quote_literal(x), ', ') INTO sync_args FROM unnest(sync_functions) x;
+
+ EXECUTE format('
+ DROP TRIGGER IF EXISTS "trg_event_sync_%1$s" ON %1$I;
+ CREATE TRIGGER "trg_event_sync_%1$s"
+ BEFORE INSERT OR UPDATE OR DELETE ON %1$I
+ FOR EACH ROW
+ EXECUTE FUNCTION public.dispatch_event_interceptors(%2$s);
+ ', table_name_text, sync_args);
+ ELSE
+ EXECUTE format('DROP TRIGGER IF EXISTS "trg_event_sync_%1$s" ON %1$I;', table_name_text);
+ END IF;
+
+ -- B. Attach AFTER SYNC Trigger (Row Level) -- NEW
+ IF array_length(after_sync_functions, 1) > 0 THEN
+ SELECT string_agg(quote_literal(x), ', ') INTO after_sync_args FROM unnest(after_sync_functions) x;
+
+ EXECUTE format('
+ DROP TRIGGER IF EXISTS "trg_event_after_sync_%1$s" ON %1$I;
+ CREATE TRIGGER "trg_event_after_sync_%1$s"
+ AFTER INSERT OR UPDATE OR DELETE ON %1$I
+ FOR EACH ROW
+ EXECUTE FUNCTION public.dispatch_event_after_interceptors(%2$s);
+ ', table_name_text, after_sync_args);
+ ELSE
+ EXECUTE format('DROP TRIGGER IF EXISTS "trg_event_after_sync_%1$s" ON %1$I;', table_name_text);
+ END IF;
+
+ -- C. Attach ASYNC Triggers (Statement Level) -- unchanged behavior
+ -- 1. INSERT
+ EXECUTE format('
+ DROP TRIGGER IF EXISTS "trg_event_async_ins_%1$s" ON %1$I;
+ CREATE TRIGGER "trg_event_async_ins_%1$s"
+ AFTER INSERT ON %1$I
+ REFERENCING NEW TABLE AS batched_new
+ FOR EACH STATEMENT
+ EXECUTE FUNCTION public.dispatch_event_batch();
+ ', table_name_text);
+
+ -- 2. DELETE
+ EXECUTE format('
+ DROP TRIGGER IF EXISTS "trg_event_async_del_%1$s" ON %1$I;
+ CREATE TRIGGER "trg_event_async_del_%1$s"
+ AFTER DELETE ON %1$I
+ REFERENCING OLD TABLE AS batched_old
+ FOR EACH STATEMENT
+ EXECUTE FUNCTION public.dispatch_event_batch();
+ ', table_name_text);
+
+ -- 3. UPDATE
+ EXECUTE format('
+ DROP TRIGGER IF EXISTS "trg_event_async_upd_%1$s" ON %1$I;
+ CREATE TRIGGER "trg_event_async_upd_%1$s"
+ AFTER UPDATE ON %1$I
+ REFERENCING NEW TABLE AS batched_new OLD TABLE AS batched_old
+ FOR EACH STATEMENT
+ EXECUTE FUNCTION public.dispatch_event_batch();
+ ', table_name_text);
+
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.attach_statement_handler(table_name_text text, handler_functions text[] DEFAULT ARRAY[]::text[])
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ fn TEXT;
+ existing TEXT;
+BEGIN
+ -- Drop-then-attach, like attach_event_trigger's sync sections: re-running is
+ -- idempotent and an empty array detaches.
+ FOR existing IN
+ SELECT t.tgname
+ FROM pg_trigger t
+ WHERE t.tgrelid = format('%I', table_name_text)::regclass
+ AND NOT t.tgisinternal
+ AND t.tgname LIKE 'trg\_event\_statement\_%'
+ LOOP
+ EXECUTE format('DROP TRIGGER IF EXISTS %2$I ON %1$I;', table_name_text, existing);
+ END LOOP;
+
+ -- One function serves all three operations, so it must branch on TG_OP: only
+ -- batched_new exists on INSERT and only batched_old on DELETE. PL/pgSQL plans
+ -- lazily, so a branch that does not run never resolves its missing table.
+ FOREACH fn IN ARRAY handler_functions LOOP
+ EXECUTE format('
+ CREATE TRIGGER %2$I AFTER INSERT ON %1$I
+ REFERENCING NEW TABLE AS batched_new
+ FOR EACH STATEMENT EXECUTE FUNCTION %3$I();
+ ', table_name_text, format('trg_event_statement_%s_ins', fn), fn);
+
+ EXECUTE format('
+ CREATE TRIGGER %2$I AFTER UPDATE ON %1$I
+ REFERENCING NEW TABLE AS batched_new OLD TABLE AS batched_old
+ FOR EACH STATEMENT EXECUTE FUNCTION %3$I();
+ ', table_name_text, format('trg_event_statement_%s_upd', fn), fn);
+
+ EXECUTE format('
+ CREATE TRIGGER %2$I AFTER DELETE ON %1$I
+ REFERENCING OLD TABLE AS batched_old
+ FOR EACH STATEMENT EXECUTE FUNCTION %3$I();
+ ', table_name_text, format('trg_event_statement_%s_del', fn), fn);
+ END LOOP;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.create_audit_log_table(p_company_id text)
+ RETURNS void
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+DECLARE
+ tbl_name TEXT;
+ tbl REGCLASS;
+BEGIN
+ PERFORM assert_audit_log_access(p_company_id, 'settings_update');
+
+ tbl_name := 'auditLog_' || p_company_id;
+
+ IF EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ -- Table exists; ensure recordId column is present (for tables created before this migration)
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.columns
+ WHERE table_schema = 'public'
+ AND information_schema.columns.table_name = tbl_name
+ AND column_name = 'recordId'
+ ) THEN
+ EXECUTE format('ALTER TABLE %I ADD COLUMN "recordId" TEXT', tbl_name);
+ EXECUTE format('UPDATE %I SET "recordId" = "entityId" WHERE "recordId" IS NULL', tbl_name);
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("recordId")',
+ 'idx_' || tbl_name || '_record', tbl_name);
+ END IF;
+
+ tbl := format('public.%I', tbl_name)::regclass;
+
+ -- Without row level security the company-scoped read policy below is not
+ -- enforced, and the API roles keep SELECT.
+ IF NOT (SELECT c.relrowsecurity FROM pg_class c WHERE c.oid = tbl) THEN
+ EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', tbl_name);
+ END IF;
+
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_trigger t
+ WHERE t.tgrelid = tbl
+ AND t.tgname = 'append_only'
+ AND NOT t.tgisinternal
+ AND t.tgenabled <> 'D'
+ AND t.tgfoid = 'public.prevent_audit_log_mutation'::regproc
+ ) THEN
+ PERFORM attach_audit_log_append_only(tbl_name);
+ END IF;
+
+ -- Secured means: the company-scoped read policy is there, the old
+ -- open policy is not, and the API roles cannot write.
+ IF EXISTS (
+ SELECT 1 FROM pg_policies p
+ WHERE p.schemaname = 'public' AND p.tablename = tbl_name
+ AND p.policyname = 'audit_log_access'
+ )
+ OR NOT EXISTS (
+ SELECT 1 FROM pg_policies p
+ WHERE p.schemaname = 'public' AND p.tablename = tbl_name
+ AND p.policyname = 'SELECT' AND p.cmd = 'SELECT'
+ AND p.qual LIKE '%' || quote_literal(p_company_id) || '%'
+ AND p.qual LIKE '%settings_view%'
+ )
+ OR has_table_privilege('anon', tbl, 'INSERT, UPDATE, DELETE, TRUNCATE')
+ OR has_table_privilege('authenticated', tbl, 'INSERT, UPDATE, DELETE, TRUNCATE')
+ THEN
+ PERFORM secure_audit_log_table(p_company_id);
+ END IF;
+
+ RETURN;
+ END IF;
+
+ EXECUTE format('
+ CREATE TABLE IF NOT EXISTS %I (
+ "id" TEXT PRIMARY KEY DEFAULT id(''aud''),
+ "tableName" TEXT NOT NULL,
+ "entityType" TEXT NOT NULL,
+ "entityId" TEXT NOT NULL,
+ "recordId" TEXT,
+ "operation" TEXT NOT NULL CHECK ("operation" IN (''INSERT'', ''UPDATE'', ''DELETE'')),
+ "actorId" TEXT,
+ "diff" JSONB,
+ "metadata" JSONB,
+ "createdAt" TIMESTAMPTZ NOT NULL DEFAULT NOW()
+ )
+ ', tbl_name);
+
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("entityType", "entityId")',
+ 'idx_' || tbl_name || '_entity', tbl_name);
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("tableName")',
+ 'idx_' || tbl_name || '_table', tbl_name);
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("recordId")',
+ 'idx_' || tbl_name || '_record', tbl_name);
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("actorId")',
+ 'idx_' || tbl_name || '_actor', tbl_name);
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("createdAt" DESC)',
+ 'idx_' || tbl_name || '_created', tbl_name);
+
+ EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', tbl_name);
+
+ PERFORM attach_audit_log_append_only(tbl_name);
+ PERFORM secure_audit_log_table(p_company_id);
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.create_company_search_index(p_company_id text)
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ v_table_name TEXT;
+BEGIN
+ v_table_name := 'searchIndex_' || p_company_id;
+
+ -- Create the search index table
+ EXECUTE format('
+ CREATE TABLE IF NOT EXISTS %I (
+ "id" BIGINT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
+ "entityType" TEXT NOT NULL,
+ "entityId" TEXT NOT NULL,
+ "title" TEXT NOT NULL,
+ "description" TEXT DEFAULT '''',
+ "link" TEXT NOT NULL,
+ "tags" TEXT[] DEFAULT ''{}'',
+ "metadata" JSONB DEFAULT ''{}'',
+ "searchVector" TSVECTOR,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT %I UNIQUE ("entityType", "entityId")
+ )', v_table_name, v_table_name || '_entity_unique');
+
+ -- GIN on searchVector: FTS path (multi-word, stemmed prefix via :*).
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I USING GIN ("searchVector")',
+ v_table_name || '_fts_idx', v_table_name);
+
+ -- GIN trigram on title: substring path (find "269" inside "S000269").
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I USING GIN ("title" gin_trgm_ops)',
+ v_table_name || '_title_trgm_idx', v_table_name);
+
+ -- GIN trigram on description: substring path for hits that live in the body text.
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I USING GIN ("description" gin_trgm_ops)',
+ v_table_name || '_description_trgm_idx', v_table_name);
+
+ -- Enable RLS (no SELECT policies - access via service role bypass)
+ EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', v_table_name);
+
+ INSERT INTO "searchIndexRegistry" ("companyId")
+ VALUES (p_company_id)
+ ON CONFLICT ("companyId") DO NOTHING;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.create_embedding_subscriptions_for_company(p_company_id text)
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ v_tables TEXT[] := ARRAY['item', 'customer', 'supplier'];
+ v_table TEXT;
+BEGIN
+ FOREACH v_table IN ARRAY v_tables LOOP
+ INSERT INTO "eventSystemSubscription" (
+ "name",
+ "table",
+ "companyId",
+ "operations",
+ "handlerType",
+ "config",
+ "filter",
+ "active"
+ )
+ VALUES (
+ 'embedding-' || v_table,
+ v_table,
+ p_company_id,
+ ARRAY['INSERT', 'UPDATE'],
+ 'EMBEDDING',
+ '{}'::jsonb,
+ '{}'::jsonb,
+ TRUE
+ )
+ ON CONFLICT ON CONSTRAINT "unique_subscription_name_per_company"
+ DO UPDATE SET
+ "operations" = EXCLUDED."operations",
+ "handlerType" = EXCLUDED."handlerType",
+ "active" = EXCLUDED."active";
+ END LOOP;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.create_event_system_subscription(p_name text, p_table text, p_company_id text, p_operations text[], p_handler_type text, p_config jsonb DEFAULT '{}'::jsonb, p_filter jsonb DEFAULT '{}'::jsonb, p_active boolean DEFAULT true)
+ RETURNS TABLE(id text, name text, "handlerType" text, "table" text)
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public', 'pg_temp'
+AS $function$
+BEGIN
+ IF NOT util.can_manage_event_subscription(p_company_id, p_handler_type) THEN
+ RAISE EXCEPTION 'Not authorized to manage % event subscriptions for company %', p_handler_type, p_company_id
+ USING ERRCODE = '42501';
+ END IF;
+
+ RETURN QUERY
+ INSERT INTO "eventSystemSubscription" (
+ "name", "table", "companyId", "operations",
+ "handlerType", "config", "filter", "active"
+ )
+ VALUES (
+ p_name, p_table, p_company_id, p_operations,
+ p_handler_type, p_config, p_filter, p_active
+ )
+ ON CONFLICT ON CONSTRAINT "unique_subscription_name_per_company"
+ DO UPDATE SET
+ "operations" = EXCLUDED."operations",
+ "filter" = EXCLUDED."filter",
+ "handlerType" = EXCLUDED."handlerType",
+ "config" = EXCLUDED."config",
+ "active" = EXCLUDED."active"
+ -- Replacing a subscription also needs the right to manage what it was.
+ WHERE util.can_manage_event_subscription(
+ p_company_id,
+ "eventSystemSubscription"."handlerType"
+ )
+ RETURNING
+ "eventSystemSubscription"."id",
+ "eventSystemSubscription"."name",
+ "eventSystemSubscription"."handlerType",
+ "eventSystemSubscription"."table";
+
+ IF NOT FOUND THEN
+ RAISE EXCEPTION 'Not authorized to replace event subscription "%" for company %', p_name, p_company_id
+ USING ERRCODE = '42501';
+ END IF;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.create_search_subscriptions_for_company(p_company_id text)
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ v_tables TEXT[] := ARRAY[
+ 'employee', 'customer', 'supplier', 'item', 'job',
+ 'purchaseOrder', 'salesInvoice', 'purchaseInvoice',
+ 'nonConformance', 'gauge', 'quote', 'salesRfq',
+ 'salesOrder', 'supplierQuote'
+ ];
+ v_table TEXT;
+BEGIN
+ FOREACH v_table IN ARRAY v_tables LOOP
+ INSERT INTO "eventSystemSubscription" (
+ "name",
+ "table",
+ "companyId",
+ "operations",
+ "handlerType",
+ "config",
+ "filter",
+ "active"
+ )
+ VALUES (
+ 'search-index-' || v_table,
+ v_table,
+ p_company_id,
+ ARRAY['INSERT', 'UPDATE', 'DELETE'],
+ 'SEARCH',
+ '{}'::jsonb,
+ '{}'::jsonb,
+ TRUE
+ )
+ ON CONFLICT ON CONSTRAINT "unique_subscription_name_per_company"
+ DO UPDATE SET
+ "operations" = EXCLUDED."operations",
+ "handlerType" = EXCLUDED."handlerType",
+ "active" = EXCLUDED."active";
+ END LOOP;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.delete_event_system_subscription(p_subscription_id text)
+ RETURNS void
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public', 'pg_temp'
+AS $function$
+DECLARE
+ v_company_id TEXT;
+ v_handler_type TEXT;
+BEGIN
+ SELECT "companyId", "handlerType" INTO v_company_id, v_handler_type
+ FROM "eventSystemSubscription"
+ WHERE "id" = p_subscription_id;
+
+ -- Nothing to delete (missing id, or already gone) — no-op, as before.
+ IF v_company_id IS NULL THEN
+ RETURN;
+ END IF;
+
+ IF NOT util.can_manage_event_subscription(v_company_id, v_handler_type) THEN
+ RAISE EXCEPTION 'Not authorized to manage % event subscriptions for company %', v_handler_type, v_company_id
+ USING ERRCODE = '42501';
+ END IF;
+
+ DELETE FROM "eventSystemSubscription" WHERE "id" = p_subscription_id;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.delete_event_system_subscriptions_by_name(p_company_id text, p_name text)
+ RETURNS void
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public', 'pg_temp'
+AS $function$
+DECLARE
+ v_handler_type TEXT;
+BEGIN
+ -- A (companyId, name) group is one handler type in practice; if any matching
+ -- row is WEBHOOK, require the stricter WEBHOOK gate. NULL (no rows) falls
+ -- through to the membership gate on a delete that affects nothing.
+ SELECT CASE WHEN bool_or("handlerType" = 'WEBHOOK') THEN 'WEBHOOK' ELSE max("handlerType") END
+ INTO v_handler_type
+ FROM "eventSystemSubscription"
+ WHERE "companyId" = p_company_id AND "name" = p_name;
+
+ IF NOT util.can_manage_event_subscription(p_company_id, COALESCE(v_handler_type, '')) THEN
+ RAISE EXCEPTION 'Not authorized to manage event subscriptions for company %', p_company_id
+ USING ERRCODE = '42501';
+ END IF;
+
+ DELETE FROM "eventSystemSubscription"
+ WHERE "companyId" = p_company_id AND "name" = p_name;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.delete_from_search_index(p_company_id text, p_entity_type text, p_entity_id text)
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ v_table_name TEXT;
+BEGIN
+ v_table_name := 'searchIndex_' || p_company_id;
+
+ EXECUTE format(
+ 'DELETE FROM %I WHERE "entityType" = $1 AND "entityId" = $2',
+ v_table_name
+ ) USING p_entity_type, p_entity_id;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.delete_old_audit_logs(p_company_id text, p_cutoff_date timestamp with time zone)
+ RETURNS integer
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+DECLARE
+ tbl_name TEXT;
+ deleted_count INTEGER;
+BEGIN
+ PERFORM assert_audit_log_access(p_company_id, NULL);
+
+ tbl_name := 'auditLog_' || p_company_id;
+
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN 0;
+ END IF;
+
+ -- Authorize the append-only trigger to permit these retention deletes.
+ PERFORM set_config('app.audit_archiving', 'on', true);
+
+ EXECUTE format('
+ WITH deleted AS (
+ DELETE FROM %I
+ WHERE "createdAt" < $1
+ RETURNING *
+ )
+ SELECT COUNT(*) FROM deleted
+ ', tbl_name)
+ USING p_cutoff_date
+ INTO deleted_count;
+
+ RETURN deleted_count;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.dispatch_event_after_interceptors()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public'
+AS $function$
+DECLARE
+ func_name TEXT;
+ payload_data JSONB;
+ old_payload_data JSONB;
+ i INTEGER;
+BEGIN
+ -- A. Normalize Data
+ IF TG_OP = 'DELETE' THEN
+ payload_data := row_to_json(OLD)::jsonb;
+ old_payload_data := payload_data;
+ ELSIF TG_OP = 'INSERT' THEN
+ payload_data := row_to_json(NEW)::jsonb;
+ old_payload_data := NULL;
+ ELSE -- UPDATE
+ payload_data := row_to_json(NEW)::jsonb;
+ old_payload_data := row_to_json(OLD)::jsonb;
+ END IF;
+
+ -- B. Execute AFTER Interceptor Functions
+ -- Same calling convention as dispatch_event_interceptors():
+ -- function_name(table_name TEXT, operation TEXT, new_data JSONB, old_data JSONB)
+ FOR i IN 0 .. (TG_NARGS - 1) LOOP
+ func_name := TG_ARGV[i];
+ EXECUTE format('SELECT public.%I($1, $2, $3, $4)', func_name)
+ USING TG_TABLE_NAME::TEXT, TG_OP, payload_data, old_payload_data;
+ END LOOP;
+
+ IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.dispatch_event_batch()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public', 'pgmq', 'extensions'
+AS $function$
+DECLARE
+ sub RECORD;
+ msg_batch JSONB[];
+ rec_company_id TEXT;
+ has_subs BOOLEAN;
+ current_actor_id TEXT;
+ current_workflow_run_id TEXT;
+ pk_column TEXT;
+ pk_join TEXT;
+ query_text TEXT;
+ did_enqueue BOOLEAN := FALSE;
+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];
+BEGIN
+ current_actor_id := auth.uid()::TEXT;
+ current_workflow_run_id :=
+ (nullif(current_setting('request.jwt.claims', true), '')::jsonb)->>'workflow_run_id';
+ pk_column := public.get_primary_key_column(TG_TABLE_NAME);
+
+ -- Pair UPDATE rows on the full key: single-column pairing cross-joins rows
+ -- on tables with composite identity.
+ SELECT string_agg(format('n.%I = o.%I', col, col), ' AND ')
+ INTO pk_join
+ FROM unnest(public.get_primary_key_columns(TG_TABLE_NAME)) AS col;
+
+ IF TG_OP = 'DELETE' THEN
+ SELECT t."companyId" INTO rec_company_id FROM batched_old t LIMIT 1;
+ ELSIF TG_OP = 'INSERT' THEN
+ SELECT t."companyId" INTO rec_company_id FROM batched_new t LIMIT 1;
+ ELSE
+ SELECT t."companyId" INTO rec_company_id FROM batched_new t LIMIT 1;
+ END IF;
+
+ IF rec_company_id IS NULL THEN RETURN NULL; END IF;
+
+ SELECT EXISTS (
+ SELECT 1 FROM "eventSystemSubscription"
+ WHERE "table" = TG_TABLE_NAME
+ AND "companyId" = rec_company_id
+ AND "active" = TRUE
+ AND TG_OP = ANY("operations")
+ AND ("handlerType" NOT IN ('SYNC','WEBHOOK','WORKFLOW')
+ OR current_setting('app.sync_in_progress', true) IS DISTINCT FROM 'true')
+ ) INTO has_subs;
+
+ IF NOT has_subs THEN RETURN NULL; END IF;
+
+ FOR sub IN
+ SELECT * FROM "eventSystemSubscription"
+ WHERE "table" = TG_TABLE_NAME
+ AND "companyId" = rec_company_id
+ AND "active" = TRUE
+ AND TG_OP = ANY("operations")
+ AND ("handlerType" NOT IN ('SYNC','WEBHOOK','WORKFLOW')
+ OR current_setting('app.sync_in_progress', true) IS DISTINCT FROM 'true')
+ LOOP
+
+ IF TG_OP = 'INSERT' THEN
+ query_text := format('
+ SELECT array_agg(
+ jsonb_build_object(
+ ''subscriptionId'', $1,
+ ''triggerType'', $2,
+ ''handlerType'', $3,
+ ''handlerConfig'', $4,
+ ''companyId'', $5,
+ ''actorId'', $6,
+ ''workflowRunId'', $10,
+ ''event'', jsonb_build_object(
+ ''table'', $7,
+ ''operation'', $8,
+ ''recordId'', t.%I::TEXT,
+ ''new'', row_to_json(t)::jsonb,
+ ''old'', null,
+ ''timestamp'', clock_timestamp()
+ )
+ )
+ )
+ FROM batched_new t
+ WHERE t."companyId" = $5
+ AND ($9 = ''{}''::jsonb OR row_to_json(t)::jsonb @> $9)
+ ', pk_column);
+
+ EXECUTE query_text INTO msg_batch
+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter,
+ current_workflow_run_id;
+
+ ELSIF TG_OP = 'DELETE' THEN
+ query_text := format('
+ SELECT array_agg(
+ jsonb_build_object(
+ ''subscriptionId'', $1,
+ ''triggerType'', $2,
+ ''handlerType'', $3,
+ ''handlerConfig'', $4,
+ ''companyId'', $5,
+ ''actorId'', $6,
+ ''workflowRunId'', $10,
+ ''event'', jsonb_build_object(
+ ''table'', $7,
+ ''operation'', $8,
+ ''recordId'', t.%I::TEXT,
+ ''new'', null,
+ ''old'', row_to_json(t)::jsonb,
+ ''timestamp'', clock_timestamp()
+ )
+ )
+ )
+ FROM batched_old t
+ WHERE t."companyId" = $5
+ AND ($9 = ''{}''::jsonb OR row_to_json(t)::jsonb @> $9)
+ ', pk_column);
+
+ EXECUTE query_text INTO msg_batch
+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter,
+ current_workflow_run_id;
+
+ ELSIF TG_OP = 'UPDATE' THEN
+ query_text := format('
+ SELECT array_agg(
+ jsonb_build_object(
+ ''subscriptionId'', $1,
+ ''triggerType'', $2,
+ ''handlerType'', $3,
+ ''handlerConfig'', $4,
+ ''companyId'', $5,
+ ''actorId'', $6,
+ ''workflowRunId'', $10,
+ ''event'', jsonb_build_object(
+ ''table'', $7,
+ ''operation'', $8,
+ ''recordId'', n.%I::TEXT,
+ ''new'', row_to_json(n)::jsonb,
+ ''old'', row_to_json(o)::jsonb,
+ ''timestamp'', clock_timestamp()
+ )
+ )
+ )
+ FROM batched_new n
+ JOIN batched_old o ON %s
+ WHERE n."companyId" = $5
+ AND ($9 = ''{}''::jsonb OR row_to_json(n)::jsonb @> $9)
+ AND (NOT $11 OR (to_jsonb(n) - $12) IS DISTINCT FROM (to_jsonb(o) - $12))
+ ', pk_column, pk_join);
+
+ EXECUTE query_text INTO msg_batch
+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter,
+ current_workflow_run_id,
+ sub."handlerType" IN ('AUDIT', 'SEARCH', 'EMBEDDING'),
+ ignored_columns;
+ END IF;
+
+ IF msg_batch IS NOT NULL AND array_length(msg_batch, 1) > 0 THEN
+ PERFORM pgmq.send_batch('event_system', msg_batch);
+ did_enqueue := TRUE;
+ END IF;
+
+ END LOOP;
+
+ -- Wake the Inngest drainer once per transaction: the GUC is txn-local, so a
+ -- bulk import posts a single doorbell instead of one per statement.
+ IF did_enqueue
+ AND current_setting('carbon.event_wake_sent', true) IS DISTINCT FROM 'true' THEN
+ PERFORM util.wake_event_queue();
+ PERFORM set_config('carbon.event_wake_sent', 'true', true);
+ END IF;
+
+ RETURN NULL;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.dispatch_event_interceptors()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public'
+AS $function$
+DECLARE
+ func_name TEXT;
+ payload_data JSONB;
+ old_payload_data JSONB;
+ i INTEGER;
+BEGIN
+ -- A. Normalize Data
+ IF TG_OP = 'DELETE' THEN
+ payload_data := row_to_json(OLD)::jsonb;
+ old_payload_data := payload_data;
+ ELSIF TG_OP = 'INSERT' THEN
+ payload_data := row_to_json(NEW)::jsonb;
+ old_payload_data := NULL;
+ ELSE -- UPDATE
+ payload_data := row_to_json(NEW)::jsonb;
+ old_payload_data := row_to_json(OLD)::jsonb;
+ END IF;
+
+ -- B. Execute Interceptor Functions
+ -- Loop through arguments passed in CREATE TRIGGER ... EXECUTE FUNCTION func(arg1, arg2)
+ FOR i IN 0 .. (TG_NARGS - 1) LOOP
+ func_name := TG_ARGV[i];
+ EXECUTE format('SELECT public.%I($1, $2, $3, $4)', func_name)
+ USING TG_TABLE_NAME::TEXT, TG_OP, payload_data, old_payload_data;
+ END LOOP;
+
+ IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.drop_audit_log_table(p_company_id text)
+ RETURNS void
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+DECLARE
+ tbl_name TEXT;
+BEGIN
+ PERFORM assert_audit_log_access(p_company_id, NULL);
+
+ tbl_name := 'auditLog_' || p_company_id;
+
+ EXECUTE format('DROP TABLE IF EXISTS %I CASCADE', tbl_name);
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.drop_company_search_index(p_company_id text)
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ v_table_name TEXT;
+BEGIN
+ v_table_name := 'searchIndex_' || p_company_id;
+
+ -- Drop the search index table if it exists
+ EXECUTE format('DROP TABLE IF EXISTS %I', v_table_name);
+
+ -- Remove from registry
+ DELETE FROM "searchIndexRegistry" WHERE "companyId" = p_company_id;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.get_audit_log(p_company_id text, p_entity_type text DEFAULT NULL::text, p_entity_id text DEFAULT NULL::text, p_actor_id text DEFAULT NULL::text, p_operation text DEFAULT NULL::text, p_start_date timestamp with time zone DEFAULT NULL::timestamp with time zone, p_end_date timestamp with time zone DEFAULT NULL::timestamp with time zone, p_limit integer DEFAULT 50, p_offset integer DEFAULT 0, p_search text DEFAULT NULL::text)
+ RETURNS TABLE(id text, "tableName" text, "entityType" text, "entityId" text, operation text, "actorId" text, diff jsonb, metadata jsonb, "createdAt" timestamp with time zone, "totalCount" bigint)
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+DECLARE
+ tbl_name TEXT;
+ where_clauses TEXT[] := ARRAY[]::TEXT[];
+ where_clause TEXT := '';
+ query_text TEXT;
+ count_query TEXT;
+ total BIGINT;
+BEGIN
+ PERFORM assert_audit_log_access(p_company_id, 'settings_view');
+
+ tbl_name := 'auditLog_' || p_company_id;
+
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN;
+ END IF;
+
+ IF p_entity_type IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"entityType" = %L', p_entity_type));
+ END IF;
+
+ IF p_entity_id IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"entityId" = %L', p_entity_id));
+ END IF;
+
+ IF p_actor_id IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"actorId" = %L', p_actor_id));
+ END IF;
+
+ IF p_operation IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"operation" = %L', p_operation));
+ END IF;
+
+ IF p_start_date IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"createdAt" >= %L', p_start_date));
+ END IF;
+
+ IF p_end_date IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"createdAt" <= %L', p_end_date));
+ END IF;
+
+ IF p_search IS NOT NULL AND p_search != '' THEN
+ where_clauses := array_append(where_clauses,
+ format('"entityId" ILIKE %L', '%' || p_search || '%'));
+ END IF;
+
+ IF array_length(where_clauses, 1) > 0 THEN
+ where_clause := 'WHERE ' || array_to_string(where_clauses, ' AND ');
+ END IF;
+
+ count_query := format('SELECT COUNT(*) FROM %I %s', tbl_name, where_clause);
+ EXECUTE count_query INTO total;
+
+ query_text := format('
+ SELECT "id", "tableName", "entityType", "entityId", "operation", "actorId", "diff", "metadata", "createdAt", %s::BIGINT as "totalCount"
+ FROM %I
+ %s
+ ORDER BY "createdAt" DESC
+ LIMIT %s OFFSET %s
+ ', total, tbl_name, where_clause, p_limit, p_offset);
+
+ RETURN QUERY EXECUTE query_text;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.get_audit_log_count(p_company_id text, p_entity_type text DEFAULT NULL::text, p_actor_id text DEFAULT NULL::text, p_operation text DEFAULT NULL::text, p_start_date timestamp with time zone DEFAULT NULL::timestamp with time zone, p_end_date timestamp with time zone DEFAULT NULL::timestamp with time zone, p_search text DEFAULT NULL::text)
+ RETURNS integer
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+DECLARE
+ tbl_name TEXT;
+ where_clauses TEXT[] := ARRAY[]::TEXT[];
+ where_clause TEXT := '';
+ count_val INTEGER;
+BEGIN
+ PERFORM assert_audit_log_access(p_company_id, 'settings_view');
+
+ tbl_name := 'auditLog_' || p_company_id;
+
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN 0;
+ END IF;
+
+ IF p_entity_type IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"entityType" = %L', p_entity_type));
+ END IF;
+
+ IF p_actor_id IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"actorId" = %L', p_actor_id));
+ END IF;
+
+ IF p_operation IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"operation" = %L', p_operation));
+ END IF;
+
+ IF p_start_date IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"createdAt" >= %L', p_start_date));
+ END IF;
+
+ IF p_end_date IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"createdAt" <= %L', p_end_date));
+ END IF;
+
+ IF p_search IS NOT NULL AND p_search != '' THEN
+ where_clauses := array_append(where_clauses,
+ format('"entityId" ILIKE %L', '%' || p_search || '%'));
+ END IF;
+
+ IF array_length(where_clauses, 1) > 0 THEN
+ where_clause := 'WHERE ' || array_to_string(where_clauses, ' AND ');
+ END IF;
+
+ EXECUTE format('SELECT COUNT(*)::INTEGER FROM %I %s', tbl_name, where_clause) INTO count_val;
+ RETURN count_val;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.get_audit_logs_for_archive(p_company_id text, p_before_date timestamp with time zone)
+ RETURNS TABLE(id text, "tableName" text, "entityType" text, "entityId" text, operation text, "actorId" text, diff jsonb, metadata jsonb, "createdAt" timestamp with time zone)
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+DECLARE
+ tbl_name TEXT;
+BEGIN
+ PERFORM assert_audit_log_access(p_company_id, NULL);
+
+ tbl_name := 'auditLog_' || p_company_id;
+
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN;
+ END IF;
+
+ RETURN QUERY EXECUTE format('
+ SELECT "id", "tableName", "entityType", "entityId", "operation", "actorId", "diff", "metadata", "createdAt"
+ FROM %I
+ WHERE "createdAt" < $1
+ ORDER BY "createdAt" ASC
+ ', tbl_name)
+ USING p_before_date;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.get_entity_audit_log(p_company_id text, p_entity_type text, p_entity_id text, p_limit integer DEFAULT 50, p_offset integer DEFAULT 0, p_record_id text DEFAULT NULL::text)
+ RETURNS TABLE(id text, "tableName" text, "entityType" text, "entityId" text, "recordId" text, operation text, "actorId" text, diff jsonb, metadata jsonb, "createdAt" timestamp with time zone)
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+DECLARE
+ tbl_name TEXT;
+BEGIN
+ PERFORM assert_audit_log_access(p_company_id, 'settings_view');
+
+ tbl_name := 'auditLog_' || p_company_id;
+
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN;
+ END IF;
+
+ IF p_record_id IS NULL THEN
+ RETURN QUERY EXECUTE format('
+ SELECT "id", "tableName", "entityType", "entityId", "recordId", "operation", "actorId", "diff", "metadata", "createdAt"
+ FROM %I
+ WHERE "entityType" = $1 AND "entityId" = $2
+ ORDER BY "createdAt" DESC
+ LIMIT $3 OFFSET $4
+ ', tbl_name)
+ USING p_entity_type, p_entity_id, p_limit, p_offset;
+ ELSE
+ RETURN QUERY EXECUTE format('
+ SELECT "id", "tableName", "entityType", "entityId", "recordId", "operation", "actorId", "diff", "metadata", "createdAt"
+ FROM %I
+ WHERE "entityType" = $1 AND "entityId" = $2 AND "recordId" = $3
+ ORDER BY "createdAt" DESC
+ LIMIT $4 OFFSET $5
+ ', tbl_name)
+ USING p_entity_type, p_entity_id, p_record_id, p_limit, p_offset;
+ END IF;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.get_primary_key_column(p_table_name text)
+ RETURNS text
+ LANGUAGE plpgsql
+ STABLE
+AS $function$
+DECLARE
+ pk_column TEXT;
+BEGIN
+ -- First try to get primary key
+ SELECT a.attname INTO pk_column
+ FROM pg_index i
+ JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
+ WHERE i.indrelid = ('"' || p_table_name || '"')::regclass
+ AND i.indisprimary
+ LIMIT 1;
+
+ -- If no primary key, try to get any unique index column
+ IF pk_column IS NULL THEN
+ SELECT a.attname INTO pk_column
+ FROM pg_index i
+ JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
+ WHERE i.indrelid = ('"' || p_table_name || '"')::regclass
+ LIMIT 1;
+ END IF;
+
+ RETURN COALESCE(pk_column, 'id');
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.get_primary_key_columns(p_table_name text)
+ RETURNS text[]
+ LANGUAGE plpgsql
+ STABLE
+AS $function$
+DECLARE
+ pk_columns TEXT[];
+BEGIN
+ -- All columns of the primary key
+ SELECT array_agg(a.attname ORDER BY a.attnum) INTO pk_columns
+ FROM pg_index i
+ JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
+ WHERE i.indrelid = ('"' || p_table_name || '"')::regclass
+ AND i.indisprimary;
+
+ -- No PK: key columns of the smallest valid, non-partial, non-expression
+ -- unique index. Partial/expression indexes don't guarantee row identity for
+ -- every row, and INCLUDE columns (positions past indnkeyatts) aren't part of
+ -- the uniqueness constraint — the slice keeps key columns only.
+ IF pk_columns IS NULL THEN
+ SELECT array_agg(a.attname ORDER BY a.attnum) INTO pk_columns
+ FROM pg_index i
+ JOIN pg_attribute a ON a.attrelid = i.indrelid
+ AND a.attnum = ANY ((i.indkey::int2[])[1:i.indnkeyatts])
+ WHERE i.indexrelid = (
+ SELECT i2.indexrelid
+ FROM pg_index i2
+ WHERE i2.indrelid = ('"' || p_table_name || '"')::regclass
+ AND i2.indisunique
+ AND i2.indisvalid
+ AND i2.indpred IS NULL
+ AND i2.indexprs IS NULL
+ ORDER BY i2.indnkeyatts ASC
+ LIMIT 1
+ );
+ END IF;
+
+ -- Last resort: the legacy single-column resolver
+ IF pk_columns IS NULL OR array_length(pk_columns, 1) IS NULL THEN
+ pk_columns := ARRAY[public.get_primary_key_column(p_table_name)];
+ END IF;
+
+ RETURN pk_columns;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.insert_audit_log_batch(p_company_id text, p_entries jsonb[])
+ RETURNS integer
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+DECLARE
+ tbl_name TEXT;
+ inserted_count INTEGER := 0;
+BEGIN
+ PERFORM assert_audit_log_access(p_company_id, NULL);
+
+ tbl_name := 'auditLog_' || p_company_id;
+
+ PERFORM create_audit_log_table(p_company_id);
+
+ -- createdAt is the entry's own (the original event time) when it has one.
+ -- clock_timestamp() is evaluated per row, so the rest still get distinct
+ -- values rather than sharing NOW().
+ EXECUTE format('
+ INSERT INTO %I ("tableName", "entityType", "entityId", "recordId", "operation", "actorId", "diff", "metadata", "createdAt")
+ SELECT
+ e->>''tableName'',
+ e->>''entityType'',
+ e->>''entityId'',
+ e->>''recordId'',
+ e->>''operation'',
+ e->>''actorId'',
+ NULLIF(e->''diff'', ''null''::jsonb),
+ NULLIF(e->''metadata'', ''null''::jsonb),
+ COALESCE((e->>''createdAt'')::TIMESTAMPTZ, clock_timestamp())
+ FROM unnest($1) AS e
+ ', tbl_name)
+ USING p_entries;
+ GET DIAGNOSTICS inserted_count = ROW_COUNT;
+
+ RETURN inserted_count;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.on_company_created_search_index()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+BEGIN
+ PERFORM create_company_search_index(NEW.id);
+ PERFORM create_search_subscriptions_for_company(NEW.id);
+ PERFORM create_embedding_subscriptions_for_company(NEW.id);
+ RETURN NEW;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.populate_company_search_index(p_company_id text)
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ v_table_name TEXT := 'searchIndex_' || p_company_id;
+BEGIN
+ -- Populate employees
+ EXECUTE format('
+ INSERT INTO %I ("entityType", "entityId", "title", "link", "tags", "metadata", "searchVector")
+ SELECT
+ ''employee'',
+ e.id,
+ COALESCE(u."fullName", ''''),
+ ''/x/person/'' || e.id,
+ ARRAY_REMOVE(ARRAY[et.name], NULL),
+ jsonb_build_object(''active'', e.active),
+ to_tsvector(''english'', COALESCE(u."fullName", '''') || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[et.name], NULL), '' ''), ''''))
+ FROM "employee" e
+ INNER JOIN "user" u ON u.id = e.id
+ LEFT JOIN "employeeType" et ON et.id = e."employeeTypeId"
+ WHERE e."companyId" = $1 AND e.active = true
+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET
+ "title" = EXCLUDED."title",
+ "tags" = EXCLUDED."tags",
+ "metadata" = EXCLUDED."metadata",
+ "searchVector" = EXCLUDED."searchVector",
+ "updatedAt" = NOW()
+ ', v_table_name) USING p_company_id;
+
+ -- Populate customers (join customerTax for taxId)
+ EXECUTE format('
+ INSERT INTO %I ("entityType", "entityId", "title", "link", "tags", "metadata", "searchVector")
+ SELECT
+ ''customer'',
+ c.id,
+ c.name,
+ ''/x/customer/'' || c.id,
+ ARRAY_REMOVE(ARRAY[ct.name, cs.name], NULL),
+ jsonb_build_object(''taxId'', ctx."taxId"),
+ to_tsvector(''english'', c.name || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[ct.name, cs.name], NULL), '' ''), ''''))
+ FROM "customer" c
+ LEFT JOIN "customerTax" ctx ON ctx."customerId" = c.id
+ LEFT JOIN "customerType" ct ON ct.id = c."customerTypeId"
+ LEFT JOIN "customerStatus" cs ON cs.id = c."customerStatusId"
+ WHERE c."companyId" = $1
+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET
+ "title" = EXCLUDED."title",
+ "tags" = EXCLUDED."tags",
+ "metadata" = EXCLUDED."metadata",
+ "searchVector" = EXCLUDED."searchVector",
+ "updatedAt" = NOW()
+ ', v_table_name) USING p_company_id;
+
+ -- Populate suppliers (join supplierTax for taxId)
+ EXECUTE format('
+ INSERT INTO %I ("entityType", "entityId", "title", "link", "tags", "metadata", "searchVector")
+ SELECT
+ ''supplier'',
+ s.id,
+ s.name,
+ ''/x/supplier/'' || s.id,
+ ARRAY_REMOVE(ARRAY[st.name, s."supplierStatus"::TEXT], NULL),
+ jsonb_build_object(''taxId'', stx."taxId"),
+ to_tsvector(''english'', s.name || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[st.name, s."supplierStatus"::TEXT], NULL), '' ''), ''''))
+ FROM "supplier" s
+ LEFT JOIN "supplierTax" stx ON stx."supplierId" = s.id
+ LEFT JOIN "supplierType" st ON st.id = s."supplierTypeId"
+ WHERE s."companyId" = $1
+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET
+ "title" = EXCLUDED."title",
+ "tags" = EXCLUDED."tags",
+ "metadata" = EXCLUDED."metadata",
+ "searchVector" = EXCLUDED."searchVector",
+ "updatedAt" = NOW()
+ ', v_table_name) USING p_company_id;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.prevent_audit_log_mutation()
+ RETURNS trigger
+ LANGUAGE plpgsql
+AS $function$
+BEGIN
+ IF TG_OP = 'UPDATE' THEN
+ RAISE EXCEPTION 'Audit log records are immutable (append-only)';
+ END IF;
+ -- DELETE: permitted only during retention/archival, which sets this flag.
+ IF current_setting('app.audit_archiving', true) IS DISTINCT FROM 'on' THEN
+ RAISE EXCEPTION 'Audit log records cannot be deleted (retention/archival only)';
+ END IF;
+ RETURN OLD;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.search_company_index(p_company_id text, p_query text, p_entity_types text[], p_limit integer DEFAULT 20)
+ RETURNS TABLE(id bigint, "entityType" text, "entityId" text, title text, description text, link text, tags text[], metadata jsonb)
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ v_table_name TEXT;
+ v_sanitized TEXT;
+ v_tsquery_text TEXT;
+ v_like_pattern TEXT;
+ v_prefix_pattern TEXT;
+BEGIN
+ v_table_name := 'searchIndex_' || p_company_id;
+
+ -- Strip tsquery operators; keep alphanumerics, whitespace, `_`, `-`.
+ v_sanitized := regexp_replace(coalesce(trim(p_query), ''), '[^[:alnum:][:space:]_-]', ' ', 'g');
+ v_sanitized := trim(regexp_replace(v_sanitized, '\s+', ' ', 'g'));
+
+ IF v_sanitized = '' THEN
+ RETURN;
+ END IF;
+
+ -- Build `tok1:* & tok2:* & ...` for the FTS branch (word-prefix match).
+ SELECT string_agg(tok || ':*', ' & ')
+ INTO v_tsquery_text
+ FROM regexp_split_to_table(v_sanitized, '\s+') AS tok
+ WHERE tok ~ '[[:alnum:]]';
+
+ -- Defensive fallback - should not trigger in practice since v_sanitized is
+ -- non-empty and contains at least one alnum, but keep the function robust.
+ IF v_tsquery_text IS NULL OR v_tsquery_text = '' THEN
+ RETURN;
+ END IF;
+
+ -- Substring + prefix patterns use the ORIGINAL sanitized string so users
+ -- can search by any slice of a stored title (e.g. "269" inside "S000269").
+ v_like_pattern := '%' || v_sanitized || '%';
+ v_prefix_pattern := v_sanitized || '%';
+
+ RETURN QUERY EXECUTE format('
+ WITH q AS (
+ SELECT to_tsquery(''english'', $1) AS query
+ )
+ SELECT
+ si.id,
+ si."entityType",
+ si."entityId",
+ si.title,
+ si.description,
+ si.link,
+ si.tags,
+ si.metadata
+ FROM %I si, q
+ WHERE si."entityType" = ANY($2)
+ AND (
+ si."searchVector" @@ q.query
+ OR si.title ILIKE $4
+ OR si.description ILIKE $4
+ )
+ ORDER BY
+ -- Boost rows where the title starts with the query (e.g. typing "S000"
+ -- pins "S000269" to the top).
+ CASE WHEN si.title ILIKE $5 THEN 0 ELSE 1 END,
+ ts_rank_cd(si."searchVector", q.query) DESC,
+ si.id DESC
+ LIMIT $3
+ ', v_table_name)
+ USING v_tsquery_text, p_entity_types, p_limit, v_like_pattern, v_prefix_pattern;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.secure_audit_log_table(p_company_id text)
+ RETURNS void
+ LANGUAGE plpgsql
+ SET search_path TO 'public'
+AS $function$
+DECLARE
+ tbl_name TEXT := 'auditLog_' || p_company_id;
+BEGIN
+ EXECUTE format('DROP POLICY IF EXISTS "audit_log_access" ON %I', tbl_name);
+ EXECUTE format('DROP POLICY IF EXISTS "SELECT" ON %I', tbl_name);
+ EXECUTE format(
+ 'CREATE POLICY "SELECT" ON %I FOR SELECT USING (
+ %L = ANY ((SELECT get_companies_with_employee_permission(''settings_view''))::text[])
+ )',
+ tbl_name, p_company_id
+ );
+ EXECUTE format(
+ 'REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON %I FROM anon, authenticated',
+ tbl_name
+ );
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.upsert_to_search_index(p_company_id text, p_entity_type text, p_entity_id text, p_title text, p_description text, p_link text, p_tags text[], p_metadata jsonb)
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ v_table_name TEXT;
+ v_search_text TEXT;
+BEGIN
+ v_table_name := 'searchIndex_' || p_company_id;
+ v_search_text := p_title || ' ' || COALESCE(p_description, '') || ' ' || COALESCE(array_to_string(p_tags, ' '), '');
+
+ EXECUTE format('
+ INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")
+ VALUES ($1, $2, $3, $4, $5, $6, $7, to_tsvector(''english'', $8))
+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET
+ "title" = EXCLUDED."title",
+ "description" = EXCLUDED."description",
+ "link" = EXCLUDED."link",
+ "tags" = EXCLUDED."tags",
+ "metadata" = EXCLUDED."metadata",
+ "searchVector" = EXCLUDED."searchVector",
+ "updatedAt" = NOW()
+ ', v_table_name) USING
+ p_entity_type,
+ p_entity_id,
+ p_title,
+ COALESCE(p_description, ''),
+ p_link,
+ COALESCE(p_tags, ARRAY[]::text[]),
+ COALESCE(p_metadata, '{}'::jsonb),
+ v_search_text;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION util.anon_key()
+ RETURNS text
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+DECLARE
+ anon_key text;
+BEGIN
+ SELECT "anonKey" INTO anon_key FROM "config" LIMIT 1;
+ RETURN anon_key;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION util.can_manage_event_subscription(p_company_id text, p_handler_type text)
+ RETURNS boolean
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public', 'pg_temp'
+AS $function$
+BEGIN
+ IF (SELECT auth.role()) = 'service_role' THEN
+ RETURN TRUE;
+ END IF;
+
+ IF p_handler_type = 'WEBHOOK' THEN
+ RETURN p_company_id = ANY (COALESCE((SELECT get_companies_with_employee_permission('settings_create'))::text[], ARRAY[]::text[]))
+ OR p_company_id = ANY (COALESCE((SELECT get_companies_with_employee_permission('settings_update'))::text[], ARRAY[]::text[]))
+ OR p_company_id = ANY (COALESCE((SELECT get_companies_with_employee_permission('settings_delete'))::text[], ARRAY[]::text[]));
+ END IF;
+
+ RETURN p_company_id = ANY (COALESCE((SELECT get_companies_with_employee_role())::text[], ARRAY[]::text[]));
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION util.clear_column()
+ RETURNS trigger
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ clear_column text := TG_ARGV[0];
+BEGIN
+ NEW := NEW #= hstore(clear_column, NULL);
+ RETURN NEW;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION util.invoke_edge_function(name text, body jsonb, timeout_milliseconds integer DEFAULT ((5 * 60) * 1000))
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ headers_raw text;
+ auth_header text;
+BEGIN
+ -- If we're in a PostgREST session, reuse the request headers for authorization
+ headers_raw := current_setting('request.headers', true);
+
+ -- Only try to parse if headers are present
+ auth_header := CASE
+ WHEN headers_raw IS NOT NULL THEN
+ (headers_raw::json->>'authorization')
+ ELSE
+ 'Bearer ' || util.anon_key()
+ END;
+
+ -- Perform async HTTP request to the edge function
+ PERFORM net.http_post(
+ url => util.api_url() || '/functions/v1/' || name,
+ headers => jsonb_build_object(
+ 'Content-Type', 'application/json',
+ 'Authorization', auth_header
+ ),
+ body => body,
+ timeout_milliseconds => timeout_milliseconds
+ );
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION util.process_embeddings(batch_size integer DEFAULT 10, max_requests integer DEFAULT 10, timeout_milliseconds integer DEFAULT ((5 * 60) * 1000))
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+DECLARE
+ job_batches JSONB[];
+ batch JSONB;
+BEGIN
+ WITH
+ -- First get jobs and assign batch numbers
+ numbered_jobs AS (
+ SELECT
+ message || jsonb_build_object('jobId', msg_id) AS job_info,
+ (row_number() OVER (ORDER BY 1) - 1) / batch_size AS batch_num
+ FROM pgmq.read(
+ queue_name => 'embedding_jobs',
+ vt => timeout_milliseconds / 1000,
+ qty => max_requests * batch_size
+ )
+ ),
+ -- Then group jobs into batches
+ batched_jobs AS (
+ SELECT
+ jsonb_agg(job_info) AS batch_array,
+ batch_num
+ FROM numbered_jobs
+ GROUP BY batch_num
+ )
+ -- Finally aggregate all batches into array, defaulting to an empty array
+ -- (FOREACH errors on NULL arrays, e.g. when the queue has no pending jobs)
+ SELECT COALESCE(array_agg(batch_array), ARRAY[]::JSONB[])
+ FROM batched_jobs
+ INTO job_batches;
+
+ -- Invoke the embed edge function for each batch
+ FOREACH batch IN ARRAY job_batches LOOP
+ PERFORM util.invoke_edge_function(
+ name => 'embed',
+ body => batch,
+ timeout_milliseconds => timeout_milliseconds
+ );
+ END LOOP;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION util.queue_embeddings(record_id text, embedding_table text)
+ RETURNS void
+ LANGUAGE plpgsql
+AS $function$
+BEGIN
+ PERFORM pgmq.send(
+ queue_name => 'embedding_jobs',
+ msg => jsonb_build_object(
+ 'id', record_id,
+ 'table', embedding_table
+ )
+ );
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION util.sweep_event_queue()
+ RETURNS void
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public', 'pgmq', 'extensions'
+AS $function$
+BEGIN
+ -- Only visible messages count: rows hidden by a read's visibility timeout
+ -- are already being drained and must not trigger a spurious wake.
+ IF EXISTS (
+ SELECT 1 FROM pgmq.q_event_system WHERE vt <= clock_timestamp()
+ ) THEN
+ PERFORM util.wake_event_queue();
+ END IF;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION util.wake_event_queue()
+ RETURNS void
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public', 'extensions'
+AS $function$
+DECLARE
+ api_url TEXT;
+ anon_key TEXT;
+BEGIN
+ SELECT "apiUrl", "anonKey" INTO api_url, anon_key FROM "config" LIMIT 1;
+
+ IF api_url IS NULL THEN
+ RETURN;
+ END IF;
+
+ PERFORM net.http_post(
+ api_url || '/functions/v1/event-wake',
+ '{}'::jsonb,
+ '{}'::jsonb,
+ jsonb_build_object(
+ 'Content-Type', 'application/json',
+ 'Authorization', 'Bearer ' || anon_key
+ )
+ );
+EXCEPTION WHEN OTHERS THEN
+ RAISE LOG 'wake_event_queue failed: % %', SQLERRM, SQLSTATE;
+END;
+$function$;
diff --git a/packages/database/supabase/tests/audit-log-no-ddl-on-write.test.sql b/packages/database/supabase/tests/audit-log-no-ddl-on-write.test.sql
new file mode 100644
index 0000000000..f25683cae7
--- /dev/null
+++ b/packages/database/supabase/tests/audit-log-no-ddl-on-write.test.sql
@@ -0,0 +1,77 @@
+-- An audit write must not run DDL: CREATE TRIGGER makes PostgREST reload its
+-- schema cache, and every request that joins related tables waits for that.
+-- A table that lost its trigger, policy or write restrictions must still heal.
+-- Run from the repository root against an existing local database:
+-- pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/audit-log-no-ddl-on-write.test.sql
+-- All fixtures are confined to the rolled-back transaction.
+\set ON_ERROR_STOP on
+BEGIN;
+SET LOCAL statement_timeout = '30s';
+
+DO $proof$
+DECLARE
+ company text := 'audit_ddl_probe';
+ tbl text := 'auditLog_audit_ddl_probe';
+ entry jsonb := '{"tableName":"job","entityType":"job","entityId":"j1","recordId":"j1","operation":"UPDATE","actorId":null,"diff":{},"metadata":null}';
+ trigger_before oid; policy_before oid; trigger_after oid; policy_after oid;
+ matching int;
+BEGIN
+ PERFORM create_audit_log_table(company);
+
+ SELECT oid INTO trigger_before FROM pg_trigger
+ WHERE tgrelid = format('public.%I', tbl)::regclass AND tgname = 'append_only';
+ SELECT oid INTO policy_before FROM pg_policy
+ WHERE polrelid = format('public.%I', tbl)::regclass AND polname = 'SELECT';
+ ASSERT trigger_before IS NOT NULL AND policy_before IS NOT NULL,
+ 'a new audit table gets its trigger and read policy';
+
+ PERFORM insert_audit_log_batch(company, ARRAY[entry]);
+ PERFORM insert_audit_log_batch(company, ARRAY[entry]);
+
+ SELECT oid INTO trigger_after FROM pg_trigger
+ WHERE tgrelid = format('public.%I', tbl)::regclass AND tgname = 'append_only';
+ SELECT oid INTO policy_after FROM pg_policy
+ WHERE polrelid = format('public.%I', tbl)::regclass AND polname = 'SELECT';
+ ASSERT trigger_after = trigger_before,
+ 'an audit write must not recreate the append-only trigger';
+ ASSERT policy_after = policy_before,
+ 'an audit write must not recreate the read policy';
+
+ -- A batch is one INSERT: every entry lands, a JSON null is stored as NULL,
+ -- and an entry's own createdAt wins over the clock.
+ ASSERT insert_audit_log_batch(company, ARRAY[
+ entry,
+ entry || '{"diff":null,"createdAt":"2020-01-02T03:04:05Z"}'
+ ]) = 2, 'a batch reports how many entries it wrote';
+ EXECUTE format(
+ 'SELECT count(*) FROM %I WHERE "diff" IS NULL AND "metadata" IS NULL
+ AND "createdAt" = ''2020-01-02T03:04:05Z''', tbl) INTO matching;
+ ASSERT matching = 1, 'JSON null is stored as NULL and createdAt is the entry''s';
+ EXECUTE format('SELECT count(*) FROM %I WHERE "diff" = ''{}''', tbl) INTO matching;
+ ASSERT matching = 3, 'an entry without createdAt is still written';
+ ASSERT insert_audit_log_batch(company, ARRAY[]::jsonb[]) = 0, 'an empty batch writes nothing';
+
+ EXECUTE format('DROP TRIGGER "append_only" ON %I', tbl);
+ EXECUTE format('DROP POLICY "SELECT" ON %I', tbl);
+ EXECUTE format('GRANT INSERT ON %I TO authenticated', tbl);
+ EXECUTE format('ALTER TABLE %I DISABLE ROW LEVEL SECURITY', tbl);
+
+ PERFORM insert_audit_log_batch(company, ARRAY[entry]);
+
+ ASSERT (SELECT relrowsecurity FROM pg_class WHERE oid = format('public.%I', tbl)::regclass),
+ 'row level security is enabled again on the next write';
+
+ ASSERT EXISTS (
+ SELECT 1 FROM pg_trigger
+ WHERE tgrelid = format('public.%I', tbl)::regclass AND tgname = 'append_only'
+ ), 'a missing append-only trigger is restored on the next write';
+ ASSERT EXISTS (
+ SELECT 1 FROM pg_policy
+ WHERE polrelid = format('public.%I', tbl)::regclass AND polname = 'SELECT'
+ ), 'a missing read policy is restored on the next write';
+ ASSERT NOT has_table_privilege('authenticated', format('public.%I', tbl), 'INSERT'),
+ 'API write access is revoked again on the next write';
+END;
+$proof$;
+
+ROLLBACK;
diff --git a/packages/database/supabase/tests/event-subscription-authz.test.sql b/packages/database/supabase/tests/event-subscription-authz.test.sql
new file mode 100644
index 0000000000..032670dfa9
--- /dev/null
+++ b/packages/database/supabase/tests/event-subscription-authz.test.sql
@@ -0,0 +1,92 @@
+-- Replacing an event subscription needs the right to manage the one that is
+-- there, not only the one being written: any employee may manage a search or
+-- audit subscription, but a webhook's belongs to whoever may change settings.
+-- Run from the repository root against an existing local database:
+-- pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/event-subscription-authz.test.sql
+-- All fixtures and role changes are confined to the rolled-back transaction.
+\set ON_ERROR_STOP on
+BEGIN;
+SET LOCAL statement_timeout = '30s';
+SET LOCAL "app.sync_in_progress" = 'true';
+
+DO $fixtures$
+DECLARE
+ group_id text;
+ company text;
+ employee text := gen_random_uuid()::text;
+ admin text := gen_random_uuid()::text;
+BEGIN
+ INSERT INTO "companyGroup" (name, "createdBy") VALUES ('Subscription authz ' || id(), 'system') RETURNING id INTO group_id;
+ INSERT INTO "company" (name, "companyGroupId", "baseCurrencyCode") VALUES ('Subscription authz ' || id(), group_id, 'USD') RETURNING id INTO company;
+ INSERT INTO "user" (id, email) VALUES
+ (employee, employee || '@subscription-authz.invalid'),
+ (admin, admin || '@subscription-authz.invalid');
+ INSERT INTO "userToCompany" ("userId", "companyId", role) VALUES
+ (employee, company, 'employee'), (admin, company, 'employee');
+ INSERT INTO "userPermission" (id, permissions) VALUES
+ (employee, '{}'::jsonb),
+ (admin, jsonb_build_object('settings_update', jsonb_build_array(company)));
+ INSERT INTO "eventSystemSubscription" (name, "table", "companyId", operations, "handlerType", config)
+ VALUES ('webhook-probe', 'item', company, ARRAY['INSERT'], 'WEBHOOK', '{"url":"https://example.invalid"}');
+
+ PERFORM set_config('test.company', company, true);
+ PERFORM set_config('test.employee', employee, true);
+ PERFORM set_config('test.admin', admin, true);
+END;
+$fixtures$;
+
+SELECT set_config('request.jwt.claims', jsonb_build_object('sub', current_setting('test.employee'), 'role', 'authenticated')::text, true);
+SET LOCAL ROLE authenticated;
+DO $$
+DECLARE
+ company text := current_setting('test.company');
+BEGIN
+ BEGIN
+ PERFORM * FROM create_event_system_subscription('webhook-probe', 'item', company, ARRAY['INSERT'], 'AUDIT');
+ RAISE EXCEPTION 'FAIL: an employee replaced a webhook subscription with one of a type they may manage';
+ EXCEPTION WHEN insufficient_privilege THEN NULL;
+ END;
+
+ -- Their own kind they may create, and replace.
+ PERFORM * FROM create_event_system_subscription('audit-probe', 'item', company, ARRAY['INSERT'], 'AUDIT');
+ PERFORM * FROM create_event_system_subscription('audit-probe', 'item', company, ARRAY['UPDATE'], 'AUDIT');
+END;
+$$;
+RESET ROLE;
+
+DO $$
+BEGIN
+ IF (SELECT "handlerType" FROM "eventSystemSubscription"
+ WHERE "companyId" = current_setting('test.company') AND name = 'webhook-probe') <> 'WEBHOOK' THEN
+ RAISE EXCEPTION 'FAIL: the webhook subscription was changed';
+ END IF;
+ IF (SELECT operations FROM "eventSystemSubscription"
+ WHERE "companyId" = current_setting('test.company') AND name = 'audit-probe') <> ARRAY['UPDATE'] THEN
+ RAISE EXCEPTION 'FAIL: an employee could not replace their own audit subscription';
+ END IF;
+END;
+$$;
+
+SELECT set_config('request.jwt.claims', jsonb_build_object('sub', current_setting('test.admin'), 'role', 'authenticated')::text, true);
+SET LOCAL ROLE authenticated;
+DO $$
+BEGIN
+ PERFORM * FROM create_event_system_subscription(
+ 'webhook-probe', 'item', current_setting('test.company'), ARRAY['UPDATE'], 'WEBHOOK',
+ '{"url":"https://example.invalid/2"}'
+ );
+END;
+$$;
+RESET ROLE;
+
+DO $$
+BEGIN
+ IF (SELECT config->>'url' FROM "eventSystemSubscription"
+ WHERE "companyId" = current_setting('test.company') AND name = 'webhook-probe') <> 'https://example.invalid/2' THEN
+ RAISE EXCEPTION 'FAIL: a settings holder could not replace the webhook subscription';
+ END IF;
+END;
+$$;
+
+SELECT 'event-subscription-authz: all checks passed' AS result;
+ROLLBACK;
diff --git a/packages/dev/src/services/migrations.ts b/packages/dev/src/services/migrations.ts
index 54ccee4977..26703fa4d3 100644
--- a/packages/dev/src/services/migrations.ts
+++ b/packages/dev/src/services/migrations.ts
@@ -207,7 +207,7 @@ export async function syncAuthz(root: string, dbPort: number): Promise<string> {
process.stderr.write(r.stderr?.toString() ?? "");
process.stdout.write(r.stdout?.toString() ?? "");
throw new Error(
- "authz sync failed: fix packages/database/src/authz/manifest.ts, then migrate again"
+ "authz sync failed: fix the rule or function file named above (packages/database/src/authz, src/event-system/functions), then migrate again"
);
}
const counts = (r.stdout ?? "").match(/changed \d+ (helper|table)\(s\)/g);
diff --git a/packages/ee/src/stripe-connect/payment.server.ts b/packages/ee/src/stripe-connect/payment.server.ts
index 78e3abcff1..8483d14170 100644
--- a/packages/ee/src/stripe-connect/payment.server.ts
+++ b/packages/ee/src/stripe-connect/payment.server.ts
@@ -10,10 +10,7 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { getCompanyTimeZone } from "@carbon/database";
import type { KyselyDatabase } from "@carbon/database/client";
-import {
- getPostgresClient,
- getPostgresConnectionPool
-} from "@carbon/database/client";
+import { getPostgresClient, getProcessPool } from "@carbon/database/client";
import { getLogger } from "@carbon/logger";
import type { ConnectInvoice } from "@carbon/stripe/connect.server";
import {
@@ -33,7 +30,7 @@ const SYSTEM_USER = "system";
// Module-level Kysely pool — one connection is enough; we only use it for the
// replaceInvoiceSettlements transaction path.
-const _pool = getPostgresConnectionPool(1);
+const _pool = getProcessPool();
const _db = getPostgresClient<KyselyDatabase>(_pool, PostgresDriver);
export type StripeConnectPaymentResult =
diff --git a/packages/jobs/AGENTS.md b/packages/jobs/AGENTS.md
index b42943645a..d46db7de52 100644
--- a/packages/jobs/AGENTS.md
+++ b/packages/jobs/AGENTS.md
@@ -25,7 +25,7 @@ Server-only Inngest jobs for event draining, integrations, notifications, workfl
- Never use the async event system for data-integrity or real-time guarantees; use database constraints/interceptors.
- Never write handler tables directly; database triggers route changes through `dispatch_event_batch()` and PGMQ.
- Never give workflow actions a service-role/untagged business client; it bypasses the owner's permissions and workflow loop guards.
-- Never close the shared pool from a job function.
+- Never close the shared pool from a job function. A Node process has one pool (`getProcessPool()`, 16 connections) shared with the app's requests; `getJobDatabaseClient()` takes no size.
## Validation Commands
diff --git a/packages/jobs/src/db.ts b/packages/jobs/src/db.ts
index 10ffbf20d5..769137b65b 100644
--- a/packages/jobs/src/db.ts
+++ b/packages/jobs/src/db.ts
@@ -4,50 +4,34 @@
import {
getPostgresClient,
- getPostgresConnectionPool,
+ getProcessPool,
type KyselyDatabase
} from "@carbon/database/client";
-import { queryLog } from "@carbon/logger/tracing.server";
+import { queryLog, traceConnectionWaits } from "@carbon/logger/tracing.server";
import { type Kysely, PostgresDriver } from "kysely";
-/** Cached per pool size, like the pool itself. The engine, matcher and queue
- * drainer each ask for a client on every step, and a fresh Kysely instance per
- * call rebuilds the whole query-compiler graph for no gain.
- *
- * We cache the pool ALONGSIDE the client so we can detect an ended pool: the
- * accounting sweeps (`accounting-outbound-sweep`, `-consolidation`,
- * `-reconciliation`) call `getPostgresConnectionPool(5)` — the SAME shared pool
- * this client wraps — and `pool.end()` it in a `finally`. `getPostgresConnectionPool`
- * evicts an ended pool for its own callers, but this separate client cache would
- * otherwise keep serving a Kysely bound to the dead pool, so every later
- * `getJobDatabaseClient(size)` user (e.g. `ramp-sync`) threw "Cannot use a pool
- * after calling end on the pool". Rebuild when the underlying pool is ending. */
-const clientCache = new Map<
- number,
- {
- client: Kysely<KyselyDatabase>;
- pool: ReturnType<typeof getPostgresConnectionPool>;
- }
->();
+let client: Kysely<KyselyDatabase> | undefined;
+let clientPool: ReturnType<typeof getProcessPool> | undefined;
-/** `getPostgresClient` is typed against the edge runtime's vendored kysely, so
- * the structurally-identical instance needs a cast for this package's copy. */
-export function getJobDatabaseClient(size = 1) {
- const cached = clientCache.get(size);
- // `ending` is node-postgres only; undefined on Deno (pool always reused).
- if (cached && !(cached.pool as { ending?: boolean }).ending) {
- return cached.client;
+/**
+ * The jobs' Kysely client, over the process's one pool (`getProcessPool`),
+ * built once: the engine, matcher and queue drainer ask for it on every step,
+ * and a fresh instance per call rebuilds the whole query-compiler graph. It is
+ * rebuilt only if a script ended the pool and a new one replaced it.
+ *
+ * `getPostgresClient` is typed against the edge runtime's vendored kysely, so
+ * the structurally-identical instance needs a cast for this package's copy.
+ */
+export function getJobDatabaseClient(): Kysely<KyselyDatabase> {
+ const pool = getProcessPool();
+ if (!client || clientPool !== pool) {
+ clientPool = traceConnectionWaits(pool);
+ client = getPostgresClient(
+ pool,
+ PostgresDriver,
+ queryLog
+ ) as unknown as Kysely<KyselyDatabase>;
}
-
- // getPostgresConnectionPool already evicts+rebuilds an ended pool, so this is
- // guaranteed live.
- const pool = getPostgresConnectionPool(size);
- const client = getPostgresClient(
- pool,
- PostgresDriver,
- queryLog
- ) as unknown as Kysely<KyselyDatabase>;
- clientCache.set(size, { client, pool });
return client;
}
diff --git a/packages/jobs/src/inngest/functions/events/search.ts b/packages/jobs/src/inngest/functions/events/search.ts
index 59d002de01..c02afe8ee9 100644
--- a/packages/jobs/src/inngest/functions/events/search.ts
+++ b/packages/jobs/src/inngest/functions/events/search.ts
@@ -28,6 +28,8 @@ const SearchPayloadSchema = z.object({
export type SearchPayload = z.infer<typeof SearchPayloadSchema>;
+const UNDEFINED_TABLE = "42P01";
+
export const searchFunction = inngest.createFunction(
{
id: "event-handler-search",
@@ -127,6 +129,22 @@ export const searchFunction = inngest.createFunction(
`.execute(pg);
}
} catch (error) {
+ // Deleting a company drops its search table while its events may
+ // still be queued. A missing table on a live company is a real
+ // failure and still throws.
+ if (
+ (error as { code?: string }).code === UNDEFINED_TABLE &&
+ !(await pg
+ .selectFrom("company")
+ .select("id")
+ .where("id", "=", companyId)
+ .executeTakeFirst())
+ ) {
+ logger.warn("Skipped search index events of a deleted company", {
+ companyId
+ });
+ return { updated: 0, deleted: 0, skipped: records.length };
+ }
logger.error("Failed to write search index", { companyId, error });
throw error;
}
diff --git a/packages/jobs/src/inngest/functions/events/sync.ts b/packages/jobs/src/inngest/functions/events/sync.ts
index d74a69145c..3960ff20f4 100644
--- a/packages/jobs/src/inngest/functions/events/sync.ts
+++ b/packages/jobs/src/inngest/functions/events/sync.ts
@@ -2,6 +2,11 @@
// 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 { EventSchema } from "@carbon/database/event";
+import { ProviderID, SpendProviderID } from "@carbon/ee/accounting";
+import { groupBy } from "@carbon/utils";
+import { z } from "zod";
/**
* SYNC event handler — v5 reconciler shape
* (.ai/specs/2026-08-12-accounting-sync-reconciler-unification.md, D3).
@@ -23,16 +28,7 @@
* DELETEs remain logged-and-skipped (DELETE sync is unimplemented; a
* deleted row also reconciles to nothing by construction).
*/
-import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import {
- getPostgresClient,
- getPostgresConnectionPool
-} from "@carbon/database/client";
-import { EventSchema } from "@carbon/database/event";
-import { ProviderID, SpendProviderID } from "@carbon/ee/accounting";
-import { groupBy } from "@carbon/utils";
-import { PostgresDriver } from "kysely";
-import { z } from "zod";
+import { getJobDatabaseClient } from "../../../db";
import { inngest } from "../../client";
import {
type DrainSummary,
@@ -99,12 +95,9 @@ export const syncFunction = inngest.createFunction(
return `${companyId}:${provider}`;
});
- const pool = getPostgresConnectionPool(10);
- const kysely = getPostgresClient(pool, PostgresDriver);
+ const kysely = getJobDatabaseClient();
const client = getCarbonServiceRole();
- // NOTE: the pool from getPostgresConnectionPool is a process-lifetime
- // singleton (see lib/postgres) — do NOT end it per invocation.
for (const [key, records] of Object.entries(byCompanyProvider)) {
const [companyId, provider] = key.split(":");
diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-consolidation.ts b/packages/jobs/src/inngest/functions/integrations/accounting-consolidation.ts
index 1daa099085..a18fb3f26e 100644
--- a/packages/jobs/src/inngest/functions/integrations/accounting-consolidation.ts
+++ b/packages/jobs/src/inngest/functions/integrations/accounting-consolidation.ts
@@ -2,6 +2,32 @@
// 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 {
+ aggregateJournalEntriesForDate,
+ claimPendingOperations,
+ completeOperation,
+ createMappingService,
+ enqueueSyncOperation,
+ failOperation,
+ getAccountingIntegration,
+ getPostingSyncSourceTypeSkipReason,
+ getProviderIntegration,
+ getSyncOperations,
+ JournalEntrySyncError,
+ type JournalEntrySyncer,
+ mapJournalEntryToManualJournal,
+ type PostingSyncSettings,
+ ProviderID,
+ parseJournalEntrySyncEntityId,
+ RatelimitError,
+ resolvePostingSyncSettings,
+ runJournalEntryPreflight,
+ type SyncContext,
+ SyncFactory,
+ type SyncOperation,
+ type XeroProvider
+} from "@carbon/ee/accounting";
/**
* Daily-consolidation cron (posting sync, spec Phase B §6).
*
@@ -44,37 +70,7 @@
* arrives). A RatelimitError aborts the company's step so Inngest retries;
* claimed rows stay In Flight and become re-claimable once stale.
*/
-import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import {
- getPostgresClient,
- getPostgresConnectionPool
-} from "@carbon/database/client";
-import {
- aggregateJournalEntriesForDate,
- claimPendingOperations,
- completeOperation,
- createMappingService,
- enqueueSyncOperation,
- failOperation,
- getAccountingIntegration,
- getPostingSyncSourceTypeSkipReason,
- getProviderIntegration,
- getSyncOperations,
- JournalEntrySyncError,
- type JournalEntrySyncer,
- mapJournalEntryToManualJournal,
- type PostingSyncSettings,
- ProviderID,
- parseJournalEntrySyncEntityId,
- RatelimitError,
- resolvePostingSyncSettings,
- runJournalEntryPreflight,
- type SyncContext,
- SyncFactory,
- type SyncOperation,
- type XeroProvider
-} from "@carbon/ee/accounting";
-import { PostgresDriver } from "kysely";
+import { getJobDatabaseClient } from "../../../db";
import { inngest } from "../../client";
import {
type IsolatedStepOutcome,
@@ -770,10 +766,7 @@ export const accountingConsolidationFunction = inngest.createFunction(
id: `consolidate-${target.companyId}-${target.providerId}`,
target,
fn: async () => {
- // Process-lifetime cached pool shared with events/sync.ts and the
- // pull sweep — never end it here (see accounting-pull-sweep.ts).
- const pool = getPostgresConnectionPool(5);
- const database = getPostgresClient(pool, PostgresDriver);
+ const database = getJobDatabaseClient();
return await consolidateCompany({
companyId: target.companyId,
providerId: target.providerId as ProviderID,
diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-master-sync.ts b/packages/jobs/src/inngest/functions/integrations/accounting-master-sync.ts
index ef0a2415bc..94fd39a7ad 100644
--- a/packages/jobs/src/inngest/functions/integrations/accounting-master-sync.ts
+++ b/packages/jobs/src/inngest/functions/integrations/accounting-master-sync.ts
@@ -2,6 +2,20 @@
// 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 AccountingProvider,
+ createMappingService,
+ getAccountingIntegration,
+ getProviderIntegration,
+ ProviderID,
+ providerSupportsMasterDataImport,
+ type SyncContext,
+ type SyncDirection
+} from "@carbon/ee/accounting";
+import { getLogger } from "@carbon/logger";
+import { chunkArray } from "@carbon/utils";
+import z from "zod";
/**
* One-shot master-data sync — customers, vendors and items, in either
* direction, for any accounting provider.
@@ -33,25 +47,7 @@
* and pushes through the shared mapping service, so adding a provider needs no
* edit here.
*/
-import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import {
- getPostgresClient,
- getPostgresConnectionPool
-} from "@carbon/database/client";
-import {
- type AccountingProvider,
- createMappingService,
- getAccountingIntegration,
- getProviderIntegration,
- ProviderID,
- providerSupportsMasterDataImport,
- type SyncContext,
- type SyncDirection
-} from "@carbon/ee/accounting";
-import { getLogger } from "@carbon/logger";
-import { chunkArray } from "@carbon/utils";
-import { PostgresDriver } from "kysely";
-import z from "zod";
+import { getJobDatabaseClient } from "../../../db";
import { inngest } from "../../client";
import { runUnmappedPushLoop } from "./accounting-master-sync-loop";
import {
@@ -164,10 +160,7 @@ export const accountingMasterSyncFunction = inngest.createFunction(
integration.id,
integration.metadata
) as AccountingProvider;
- const database = getPostgresClient(
- getPostgresConnectionPool(5),
- PostgresDriver
- );
+ const database = getJobDatabaseClient();
const createdBy = getSyncOperationActor(integration);
const result: Record<string, EntityCounts> = {};
diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-outbound-sweep.ts b/packages/jobs/src/inngest/functions/integrations/accounting-outbound-sweep.ts
index c9ddfa3d1f..e6f7be8b68 100644
--- a/packages/jobs/src/inngest/functions/integrations/accounting-outbound-sweep.ts
+++ b/packages/jobs/src/inngest/functions/integrations/accounting-outbound-sweep.ts
@@ -2,6 +2,20 @@
// 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 {
+ createMappingService,
+ ensureProviderSubscriptions,
+ getAccountingIntegration,
+ getProviderIntegration,
+ PAYMENT_PUSH_PROVIDERS,
+ ProviderID,
+ resolvePostingSyncSettings,
+ type SyncContext
+} from "@carbon/ee/accounting";
+import { trigger } from "@carbon/lib/trigger";
+import { NotificationEvent } from "@carbon/notifications";
+import { today } from "@internationalized/date";
/**
* Outbound accounting reconciliation sweep — the correctness guarantee
* behind OUTBOUND push sync (v4 Pillar B, transport unified under the v5
@@ -21,25 +35,7 @@
* The window is deliberately short (SWEEP_LOOKBACK_DAYS) — history beyond
* it is the explicit backfill's job, never a silent mass-push.
*/
-import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import {
- getPostgresClient,
- getPostgresConnectionPool
-} from "@carbon/database/client";
-import {
- createMappingService,
- ensureProviderSubscriptions,
- getAccountingIntegration,
- getProviderIntegration,
- PAYMENT_PUSH_PROVIDERS,
- ProviderID,
- resolvePostingSyncSettings,
- type SyncContext
-} from "@carbon/ee/accounting";
-import { trigger } from "@carbon/lib/trigger";
-import { NotificationEvent } from "@carbon/notifications";
-import { today } from "@internationalized/date";
-import { PostgresDriver } from "kysely";
+import { getJobDatabaseClient } from "../../../db";
import { inngest } from "../../client";
import {
type IsolatedStepOutcome,
@@ -702,10 +698,7 @@ export const accountingOutboundSweepFunction = inngest.createFunction(
id: `outbound-sweep-${target.providerId}-${target.companyId}`,
target,
fn: async () => {
- // Process-lifetime cached pool shared with events/sync.ts and the
- // pull sweep — never end it here (see accounting-pull-sweep.ts).
- const pool = getPostgresConnectionPool(5);
- const database = getPostgresClient(pool, PostgresDriver);
+ const database = getJobDatabaseClient();
return await sweepCompanyProvider({
companyId: target.companyId,
providerId: target.providerId,
diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-pull-sweep.ts b/packages/jobs/src/inngest/functions/integrations/accounting-pull-sweep.ts
index d867fc4d54..bebb850946 100644
--- a/packages/jobs/src/inngest/functions/integrations/accounting-pull-sweep.ts
+++ b/packages/jobs/src/inngest/functions/integrations/accounting-pull-sweep.ts
@@ -2,6 +2,19 @@
// 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 AccountingEntityType,
+ enqueueSyncOperation,
+ findPaymentCompositesByRemoteId,
+ getAccountingIntegration,
+ getProviderIntegration,
+ type ProviderChange,
+ ProviderID,
+ providerSupportsIncrementalPull,
+ type SyncContext
+} from "@carbon/ee/accounting";
+import { chunkArray } from "@carbon/utils";
/**
* Generic accounting pull sweep — the correctness guarantee behind every
* provider's inbound sync (webhooks, where a provider supports them, are
@@ -43,24 +56,7 @@
* Activity, retryable there) — they do NOT hold the cursor back; the
* ledger row is the durable record of the change.
*/
-import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import {
- getPostgresClient,
- getPostgresConnectionPool
-} from "@carbon/database/client";
-import {
- type AccountingEntityType,
- enqueueSyncOperation,
- findPaymentCompositesByRemoteId,
- getAccountingIntegration,
- getProviderIntegration,
- type ProviderChange,
- ProviderID,
- providerSupportsIncrementalPull,
- type SyncContext
-} from "@carbon/ee/accounting";
-import { chunkArray } from "@carbon/utils";
-import { PostgresDriver } from "kysely";
+import { getJobDatabaseClient } from "../../../db";
import { inngest } from "../../client";
import {
type IsolatedStepOutcome,
@@ -460,12 +456,7 @@ export const accountingPullSweepFunction = inngest.createFunction(
id: `sweep-${target.providerId}-${target.companyId}`,
target,
fn: async () => {
- // getPostgresConnectionPool returns a process-lifetime singleton
- // (cached, shared with any other caller requesting the same size) —
- // never end it here, or a concurrent invocation queries an ended pool
- // (matches events/sync.ts).
- const pool = getPostgresConnectionPool(5);
- const database = getPostgresClient(pool, PostgresDriver);
+ const database = getJobDatabaseClient();
return await sweepCompanyProvider({
companyId: target.companyId,
providerId: target.providerId,
diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-reconciliation.ts b/packages/jobs/src/inngest/functions/integrations/accounting-reconciliation.ts
index 26c3fa2a44..b3dd32a7f7 100644
--- a/packages/jobs/src/inngest/functions/integrations/accounting-reconciliation.ts
+++ b/packages/jobs/src/inngest/functions/integrations/accounting-reconciliation.ts
@@ -2,6 +2,23 @@
// 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 {
+ fetchRemoteJournalTotals,
+ getAccountingIntegration,
+ getJournalEntrySyncEntityId,
+ getProviderIntegration,
+ getSyncOperations,
+ ProviderID,
+ parseJournalEntrySyncEntityId,
+ RatelimitError,
+ type RemoteJournalTotals,
+ resolvePostingSyncSettings,
+ type SyncContext,
+ type SyncOperation,
+ toDebitSignedAmount,
+ toPostingDateString
+} from "@carbon/ee/accounting";
/**
* Weekly reconciliation cron (posting sync, v3 spec §5 / v4 Pillar E) —
* presence drift detection plus the per-period × per-account tie-out.
@@ -42,28 +59,7 @@
* Rows upsert on the (companyId, integration, accountingPeriodId,
* accountId) cell via the service role — the table has no write RLS.
*/
-import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import {
- getPostgresClient,
- getPostgresConnectionPool
-} from "@carbon/database/client";
-import {
- fetchRemoteJournalTotals,
- getAccountingIntegration,
- getJournalEntrySyncEntityId,
- getProviderIntegration,
- getSyncOperations,
- ProviderID,
- parseJournalEntrySyncEntityId,
- RatelimitError,
- type RemoteJournalTotals,
- resolvePostingSyncSettings,
- type SyncContext,
- type SyncOperation,
- toDebitSignedAmount,
- toPostingDateString
-} from "@carbon/ee/accounting";
-import { PostgresDriver } from "kysely";
+import { getJobDatabaseClient } from "../../../db";
import { inngest } from "../../client";
import {
type IsolatedStepOutcome,
@@ -1023,10 +1019,7 @@ export const accountingReconciliationFunction = inngest.createFunction(
id: `reconcile-${target.companyId}-${target.providerId}`,
target,
fn: async () => {
- // Process-lifetime cached pool shared with events/sync.ts and the
- // pull sweep — never end it here (see accounting-pull-sweep.ts).
- const pool = getPostgresConnectionPool(5);
- const database = getPostgresClient(pool, PostgresDriver);
+ const database = getJobDatabaseClient();
return await reconcileCompany({
companyId: target.companyId,
providerId: target.providerId as ProviderID,
diff --git a/packages/jobs/src/inngest/functions/integrations/mount-publish.ts b/packages/jobs/src/inngest/functions/integrations/mount-publish.ts
index cf57770e87..92d6848222 100644
--- a/packages/jobs/src/inngest/functions/integrations/mount-publish.ts
+++ b/packages/jobs/src/inngest/functions/integrations/mount-publish.ts
@@ -2,6 +2,10 @@
// 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 { runMountPublish } from "@carbon/ee/mount.server";
+import { getLogger } from "@carbon/logger";
+import z from "zod";
/**
* Mount publish sweep — the "Push customers / suppliers / parts" actions on
* the Mount integration's detail page.
@@ -20,15 +24,7 @@
* this same function, iterating every active Mount integration; nothing here
* assumes a human started it.
*/
-import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import {
- getPostgresClient,
- getPostgresConnectionPool
-} from "@carbon/database/client";
-import { runMountPublish } from "@carbon/ee/mount.server";
-import { getLogger } from "@carbon/logger";
-import { PostgresDriver } from "kysely";
-import z from "zod";
+import { getJobDatabaseClient } from "../../../db";
import { inngest } from "../../client";
const log = getLogger("jobs", "mount-publish");
@@ -61,7 +57,7 @@ export const mountPublishFunction = inngest.createFunction(
const result = await step.run("publish", async () =>
runMountPublish({
serviceRole: getCarbonServiceRole(),
- db: getPostgresClient(getPostgresConnectionPool(5), PostgresDriver),
+ db: getJobDatabaseClient(),
companyId,
entityTypes
})
diff --git a/packages/jobs/src/inngest/functions/integrations/ramp-sync-bill.integration.test.ts b/packages/jobs/src/inngest/functions/integrations/ramp-sync-bill.integration.test.ts
index 47a2d56077..ba535d3f8c 100644
--- a/packages/jobs/src/inngest/functions/integrations/ramp-sync-bill.integration.test.ts
+++ b/packages/jobs/src/inngest/functions/integrations/ramp-sync-bill.integration.test.ts
@@ -36,7 +36,7 @@ describe.skipIf(process.env.RUN_RAMP_DB_TESTS !== "true")(
accountId: string;
};
beforeAll(async () => {
- db = getJobDatabaseClient(2);
+ db = getJobDatabaseClient();
({ getCarbonServiceRole } = await import("@carbon/auth/client.server"));
({ syncRampBills } = await import("./ramp-sync-bill"));
scope = (await db
diff --git a/packages/jobs/src/inngest/functions/integrations/ramp-sync-card.integration.test.ts b/packages/jobs/src/inngest/functions/integrations/ramp-sync-card.integration.test.ts
index e1e8fcde80..a80bd48f99 100644
--- a/packages/jobs/src/inngest/functions/integrations/ramp-sync-card.integration.test.ts
+++ b/packages/jobs/src/inngest/functions/integrations/ramp-sync-card.integration.test.ts
@@ -34,7 +34,7 @@ describe.skipIf(!runDatabaseTests)("Ramp card staging (Postgres)", () => {
const rampIds: string[] = [];
beforeAll(async () => {
- db = getJobDatabaseClient(2);
+ db = getJobDatabaseClient();
const company = await db
.selectFrom("company")
.innerJoin("employeeJob", "employeeJob.companyId", "company.id")
diff --git a/packages/jobs/src/inngest/functions/integrations/ramp-sync-reimbursement-create.integration.test.ts b/packages/jobs/src/inngest/functions/integrations/ramp-sync-reimbursement-create.integration.test.ts
index e8f122d79c..47662825e6 100644
--- a/packages/jobs/src/inngest/functions/integrations/ramp-sync-reimbursement-create.integration.test.ts
+++ b/packages/jobs/src/inngest/functions/integrations/ramp-sync-reimbursement-create.integration.test.ts
@@ -31,7 +31,7 @@ describe.skipIf(process.env.RUN_RAMP_DB_TESTS !== "true")(
const remoteIds: string[] = [];
beforeAll(async () => {
- db = getJobDatabaseClient(2);
+ db = getJobDatabaseClient();
const row = await db
.selectFrom("company")
.innerJoin("employee", "employee.companyId", "company.id")
diff --git a/packages/jobs/src/inngest/functions/integrations/ramp-sync-transaction.integration.test.ts b/packages/jobs/src/inngest/functions/integrations/ramp-sync-transaction.integration.test.ts
index 522bf8e224..d355c5809d 100644
--- a/packages/jobs/src/inngest/functions/integrations/ramp-sync-transaction.integration.test.ts
+++ b/packages/jobs/src/inngest/functions/integrations/ramp-sync-transaction.integration.test.ts
@@ -25,7 +25,7 @@ describe.skipIf(!runDatabaseTests)(
};
beforeAll(async () => {
- db = getJobDatabaseClient(2);
+ db = getJobDatabaseClient();
const row = await db
.selectFrom("company")
.innerJoin(
diff --git a/packages/jobs/src/inngest/functions/integrations/ramp-sync.ts b/packages/jobs/src/inngest/functions/integrations/ramp-sync.ts
index 2bb7b67170..5ca6c50e75 100644
--- a/packages/jobs/src/inngest/functions/integrations/ramp-sync.ts
+++ b/packages/jobs/src/inngest/functions/integrations/ramp-sync.ts
@@ -85,7 +85,7 @@ export const rampSyncFunction = inngest.createFunction(
.eq("companyId", companyId)
.maybeSingle();
- const jobDb = getJobDatabaseClient(5);
+ const jobDb = getJobDatabaseClient();
const ctx: RampSyncContext = {
client,
db: jobDb,
diff --git a/packages/jobs/src/inngest/functions/integrations/sync-external-accounting.ts b/packages/jobs/src/inngest/functions/integrations/sync-external-accounting.ts
index f7b36384f7..eb1989d993 100644
--- a/packages/jobs/src/inngest/functions/integrations/sync-external-accounting.ts
+++ b/packages/jobs/src/inngest/functions/integrations/sync-external-accounting.ts
@@ -2,6 +2,17 @@
// 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 AccountingEntityType,
+ AccountingSyncSchema,
+ createMappingService,
+ getAccountingIntegration,
+ getProviderIntegration,
+ type SyncOperationTrigger
+} from "@carbon/ee/accounting";
+import { getLogger } from "@carbon/logger";
+import { groupBy } from "@carbon/utils";
/**
* Function to sync entities between accounting providers and Carbon.
*
@@ -22,22 +33,7 @@
* cooldown check that used to live here), then a drain step claims Pending
* operations and runs the entity syncers.
*/
-import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import {
- getPostgresClient,
- getPostgresConnectionPool
-} from "@carbon/database/client";
-import {
- type AccountingEntityType,
- AccountingSyncSchema,
- createMappingService,
- getAccountingIntegration,
- getProviderIntegration,
- type SyncOperationTrigger
-} from "@carbon/ee/accounting";
-import { getLogger } from "@carbon/logger";
-import { groupBy } from "@carbon/utils";
-import { PostgresDriver } from "kysely";
+import { getJobDatabaseClient } from "../../../db";
import { inngest } from "../../client";
import {
type DrainSummary,
@@ -77,10 +73,7 @@ export const syncExternalAccountingFunction = inngest.createFunction(
// reuse the same event id (absorbed), later deliveries get fresh keys
const enqueueScope = event.id ?? runId;
- // NOTE: the pool from getPostgresConnectionPool is a process-lifetime
- // singleton (see lib/postgres) — do NOT end it per invocation.
- const pool = getPostgresConnectionPool(10);
- const kysely = getPostgresClient(pool, PostgresDriver);
+ const kysely = getJobDatabaseClient();
// Step 1: resolve each entity's effective direction and enqueue one
// ledger operation per entity + direction
diff --git a/packages/jobs/src/inngest/functions/scheduled/cleanup.ts b/packages/jobs/src/inngest/functions/scheduled/cleanup.ts
index e924c1235f..3c5fa6a814 100644
--- a/packages/jobs/src/inngest/functions/scheduled/cleanup.ts
+++ b/packages/jobs/src/inngest/functions/scheduled/cleanup.ts
@@ -3,12 +3,9 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import {
- LEGACY_PRIVATE_BUCKET,
- storage,
- TEMP_STAGING_BUCKET
-} from "@carbon/files";
+import { LEGACY_PRIVATE_BUCKET, TEMP_STAGING_BUCKET } from "@carbon/files";
import { NotificationEvent } from "@carbon/notifications";
+import { filterEmpty } from "@carbon/utils";
import { sql } from "kysely";
import { getJobDatabaseClient } from "../../../db";
import { inngest } from "../../client";
@@ -41,6 +38,25 @@ async function listStorageObjects(where: ReturnType<typeof sql>) {
}
}
+/**
+ * The staged names that also exist in their company's bucket or the legacy
+ * shared one. One query: probing each name over HTTP was two requests per
+ * object, every night, for objects that are referenced and never pruned.
+ */
+async function findDurableCopies(names: string[]) {
+ const buckets = [
+ LEGACY_PRIVATE_BUCKET,
+ ...new Set(filterEmpty(names.map((name) => name.split("/")[0])))
+ ];
+ const { rows } = await sql<{ name: string }>`
+ SELECT DISTINCT name FROM storage.objects
+ WHERE bucket_id = ANY(${buckets}::text[])
+ AND name = ANY(${names}::text[])
+ AND bucket_id IN (${LEGACY_PRIVATE_BUCKET}, split_part(name, '/', 1))
+ `.execute(getJobDatabaseClient());
+ return new Set(rows.map((row) => row.name));
+}
+
type NotifyEvent = {
name: "carbon/notify";
data: {
@@ -396,28 +412,16 @@ export const cleanupFunction = inngest.createFunction(
// holding a temp-staging source pointer). Once the durable copy exists,
// the staged one is redundant regardless of size or references: every
// reader probes/falls back to `private`.
- const relocated = new Set<string>();
- const CHUNK = 20;
// A durable copy may live in the company's own bucket (current pipeline)
- // or the legacy shared `private` bucket (pre-migration relocations);
- // `info` probes both. Object keys start with the companyId segment, and
- // a key without one can't have a durable copy anywhere.
- const probeDurableCopy = async (name: string) => {
- const companyId = name.split("/")[0];
- if (!companyId) return null;
- const found = await storage(serviceRole)
- .company(companyId)
- .info(name)
- .then((r) => !r.error)
- .catch(() => false);
- return found ? name : null;
- };
- for (let i = 0; i < staleNames.length; i += CHUNK) {
- const chunk = staleNames.slice(i, i + CHUNK);
- const probes = await Promise.all(chunk.map(probeDurableCopy));
- for (const name of probes) {
- if (name) relocated.add(name);
- }
+ // or the legacy shared `private` bucket (pre-migration relocations).
+ // Object keys start with the companyId segment, and a key without one
+ // can't have a durable copy anywhere.
+ let relocated: Set<string>;
+ try {
+ relocated = await findDurableCopies(staleNames);
+ } catch (error) {
+ logger.error("Error finding durable copies of staged raws", { error });
+ return;
}
// Rule 2 — ORPHANED: no modelUpload points at it via EITHER column
diff --git a/packages/jobs/src/inngest/functions/scheduled/dispatch.ts b/packages/jobs/src/inngest/functions/scheduled/dispatch.ts
index 05fb0444ca..5163854762 100644
--- a/packages/jobs/src/inngest/functions/scheduled/dispatch.ts
+++ b/packages/jobs/src/inngest/functions/scheduled/dispatch.ts
@@ -103,14 +103,24 @@ async function isHoliday(
*
* Idempotent: a run whose `nextDueAt` is already in the future creates nothing
* and re-writes the same value.
+ *
+ * `notificationGroup` is the company's `maintenanceDispatchNotificationGroup`
+ * (Settings → Resources), the same group a dispatch created in the MES notifies.
*/
export async function generateDispatchesForSchedule(args: {
serviceRole: ReturnType<typeof getCarbonServiceRole>;
schedule: MaintenanceSchedule;
companyId: string;
currentDateTime: ReturnType<typeof now>;
+ notificationGroup: string[];
}): Promise<number> {
- const { serviceRole, schedule, companyId, currentDateTime } = args;
+ const {
+ serviceRole,
+ schedule,
+ companyId,
+ currentDateTime,
+ notificationGroup
+ } = args;
const timeZone = currentDateTime.timeZone;
let dispatchesCreated = 0;
@@ -312,30 +322,24 @@ export async function generateDispatchesForSchedule(args: {
date: targetDateString
});
- // Get employees assigned to this work center to notify them
- const { data: workCenterEmployees } = await (serviceRole as any)
- .from("workCenterEmployee")
- .select("userId")
- .eq("workCenterId", schedule.workCenterId);
-
- if (workCenterEmployees && workCenterEmployees.length > 0) {
- const userIds = workCenterEmployees.map((e: any) => e.userId as string);
- await inngest.send({
- name: "carbon/notify",
- data: {
- event: NotificationEvent.MaintenanceDispatchCreated,
- companyId,
- documentId: newDispatch.id,
- recipient: {
- type: "users" as const,
- userIds
+ if (notificationGroup.length > 0) {
+ try {
+ await inngest.send({
+ name: "carbon/notify",
+ data: {
+ event: NotificationEvent.MaintenanceDispatchCreated,
+ companyId,
+ documentId: newDispatch.id,
+ recipient: { type: "group" as const, groupIds: notificationGroup }
}
- }
- });
- log.info("Notified work center employees about dispatch", {
- count: userIds.length,
- dispatchId: sequenceData
- });
+ });
+ } catch (error) {
+ log.error("Failed to notify about maintenance dispatch", {
+ scheduleId: schedule.id,
+ dispatchId: sequenceData,
+ error
+ });
+ }
}
// Calculate next due date based on frequency
@@ -392,7 +396,9 @@ export const dispatchFunction = inngest.createFunction(
// Generate for every company; the schedule query below is the real
// gate (only active schedules that are due within the advance window).
const { data: companiesWithSettings, error: settingsError } =
- await serviceRole.from("companySettings").select("id");
+ await serviceRole
+ .from("companySettings")
+ .select("id, maintenanceDispatchNotificationGroup");
if (settingsError) {
logger.error("Failed to fetch company settings", {
@@ -439,7 +445,9 @@ export const dispatchFunction = inngest.createFunction(
serviceRole,
schedule: schedule as MaintenanceSchedule,
companyId: settings.id,
- currentDateTime
+ currentDateTime,
+ notificationGroup:
+ settings.maintenanceDispatchNotificationGroup ?? []
});
} catch (err) {
logger.error("Error processing schedule", {
@@ -507,11 +515,24 @@ export const generateMaintenanceForScheduleFunction = inngest.createFunction(
return { dispatchesCreated: 0 };
}
+ const { data: settings, error: settingsError } = await serviceRole
+ .from("companySettings")
+ .select("maintenanceDispatchNotificationGroup")
+ .eq("id", companyId)
+ .maybeSingle();
+ if (settingsError) {
+ logger.error("Failed to load maintenance notification group", {
+ companyId,
+ error: settingsError
+ });
+ }
+
const dispatchesCreated = await generateDispatchesForSchedule({
serviceRole,
schedule: schedule as MaintenanceSchedule,
companyId,
- currentDateTime
+ currentDateTime,
+ notificationGroup: settings?.maintenanceDispatchNotificationGroup ?? []
});
logger.info("Generated dispatches for schedule on demand", {
diff --git a/packages/jobs/src/inngest/functions/scheduled/purge-company.integration.test.ts b/packages/jobs/src/inngest/functions/scheduled/purge-company.integration.test.ts
index 4a8b11e550..3612003398 100644
--- a/packages/jobs/src/inngest/functions/scheduled/purge-company.integration.test.ts
+++ b/packages/jobs/src/inngest/functions/scheduled/purge-company.integration.test.ts
@@ -57,7 +57,7 @@ async function danglingForeignKeys(
describe.skipIf(!runDatabaseTests)("purgeCompany (Postgres)", () => {
it("deletes a company, posted journals included, leaving no dangling rows", async () => {
- const db = getJobDatabaseClient(1);
+ const db = getJobDatabaseClient();
const replica = await canSetReplicationRole(db);
expect(replica).toBe(true);
const catalog = await getCompanyTableCatalog(db);
diff --git a/packages/jobs/src/inngest/functions/scheduled/workflow-run-retention.ts b/packages/jobs/src/inngest/functions/scheduled/workflow-run-retention.ts
index 626b4d3a21..1ac3d5dcaa 100644
--- a/packages/jobs/src/inngest/functions/scheduled/workflow-run-retention.ts
+++ b/packages/jobs/src/inngest/functions/scheduled/workflow-run-retention.ts
@@ -169,7 +169,7 @@ export const workflowRunRetentionFunction = inngest.createFunction(
{ id: "workflow-run-retention", retries: 2 },
{ cron: "0 4 * * *" },
async ({ step, logger }) => {
- const db = getJobDatabaseClient(5);
+ const db = getJobDatabaseClient();
// 1. A run whose function died without reaching "finish" sits in Running
// forever: permanently in flight in the UI, and invisible to every pass
diff --git a/packages/jobs/src/inngest/functions/tasks/company-export.ts b/packages/jobs/src/inngest/functions/tasks/company-export.ts
index 80c0e270ff..d345c5a658 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-export.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-export.ts
@@ -375,7 +375,7 @@ export const companyExportFunction = inngest.createFunction(
return await step.run("export-company", async () => {
const client = getCarbonServiceRole();
- const db = getJobDatabaseClient(TABLE_CONCURRENCY);
+ const db = getJobDatabaseClient();
// Live-progress marker (cleared on success, flipped to "failed" on error).
// Throttled so a fast parallel dump doesn't hammer the row.
diff --git a/packages/jobs/src/inngest/functions/tasks/company-import.ts b/packages/jobs/src/inngest/functions/tasks/company-import.ts
index fa54285b31..54eaeb05a1 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-import.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-import.ts
@@ -76,7 +76,7 @@ export const companyImportFunction = inngest.createFunction(
return await step.run("import-company", async () => {
const client = getCarbonServiceRole();
- const db = getJobDatabaseClient(1);
+ const db = getJobDatabaseClient();
// Idempotency guard — a retry after a partial failure must not
// duplicate rows that already committed under this run id.
diff --git a/packages/jobs/src/inngest/functions/tasks/company-restore.ts b/packages/jobs/src/inngest/functions/tasks/company-restore.ts
index 9d2b2848dd..09d0a290cb 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-restore.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-restore.ts
@@ -425,7 +425,7 @@ export const companyRestoreFunction = inngest.createFunction(
return await step.run("restore-company", async () => {
const client = getCarbonServiceRole();
- const db = getJobDatabaseClient(1);
+ const db = getJobDatabaseClient();
// Idempotency — a retry after the run already reached a terminal state
// must not wipe again.
@@ -696,7 +696,7 @@ export const companyRestoreRevertFunction = inngest.createFunction(
// mid-restore. The lock is on companyRestoreFunction (the start).
return await step.run("revert-restore", async () => {
const client = getCarbonServiceRole();
- const db = getJobDatabaseClient(1);
+ const db = getJobDatabaseClient();
const marker = await readRestoreMarker(client, companyId, restoreRunId);
const snapshotPath = marker?.metadata.snapshotPath;
diff --git a/packages/jobs/src/inngest/functions/tasks/company-template.ts b/packages/jobs/src/inngest/functions/tasks/company-template.ts
index 400ad89b02..5225a47cf5 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-template.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-template.ts
@@ -4,7 +4,7 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { getCompanyTimeZone } from "@carbon/database";
-import { getPostgresConnectionPool } from "@carbon/database/client";
+import { getProcessPool } from "@carbon/database/client";
import { applyDataset, getDataset } from "@carbon/database/datasets";
import { datetime } from "@carbon/utils";
import { NonRetriableError } from "inngest";
@@ -251,7 +251,7 @@ export const companyTemplateFunction = inngest.createFunction(
// throws on its 10s acquisition timeout — outside this try, either would
// leave the marker stuck on `running` forever. The snapshot is inside for
// the same reason.
- const pool = getPostgresConnectionPool(2);
+ const pool = getProcessPool();
let pgClient: Parameters<typeof applyDataset>[0] | null = null;
try {
let snapshotPath = existing?.metadata.snapshotPath ?? undefined;
@@ -259,7 +259,7 @@ export const companyTemplateFunction = inngest.createFunction(
// IDEMPOTENT: a prior attempt's snapshot is reused, never retaken — a
// retry after the apply committed would otherwise capture the SEEDED
// state and overwrite the user's real pre-apply copy.
- const db = getJobDatabaseClient(1);
+ const db = getJobDatabaseClient();
const { includeGroup } = await resolveRestoreScope(client, companyId);
snapshotPath = `_pre-template-${templateRunId}`;
const snap = await buildCompanyBackup(client, db, {
@@ -458,7 +458,7 @@ export const companyTemplateRevertFunction = inngest.createFunction(
return await step.run("revert-template", async () => {
const client = getCarbonServiceRole();
- const db = getJobDatabaseClient(1);
+ const db = getJobDatabaseClient();
const marker = await readTemplateMarker(client, companyId);
const snapshotPath = marker?.metadata.snapshotPath;
diff --git a/packages/lib/src/telemetry/capture.test.ts b/packages/lib/src/telemetry/capture.test.ts
index 61950fb499..e037a88266 100644
--- a/packages/lib/src/telemetry/capture.test.ts
+++ b/packages/lib/src/telemetry/capture.test.ts
@@ -2,6 +2,7 @@
// 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 { async } from "@carbon/utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const env = vi.hoisted(() => ({
@@ -277,5 +278,27 @@ describe("captureWorkEvent", () => {
expect(() => trackWorkEvent("job_released", released)).not.toThrow();
await new Promise((resolve) => setImmediate(resolve));
});
+
+ // On a host that freezes the process after the response, the capture must
+ // be handed to the host to wait for.
+ it("is handed to the host's lifetime hook, and done when that settles", async () => {
+ const kept: Promise<unknown>[] = [];
+ async.onBackground((work) => kept.push(work));
+ let sent = false;
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ sent = true;
+ return new Response("ok", { status: 200 });
+ })
+ );
+ trackWorkEvent("job_released", released);
+ expect(sent).toBe(false);
+ expect(kept).toHaveLength(1);
+ await kept[0];
+ expect(sent).toBe(true);
+ async.onBackground(undefined);
+ });
});
});
diff --git a/packages/lib/src/telemetry/capture.ts b/packages/lib/src/telemetry/capture.ts
index 9b2e68620b..97d17b1845 100644
--- a/packages/lib/src/telemetry/capture.ts
+++ b/packages/lib/src/telemetry/capture.ts
@@ -8,6 +8,7 @@ import {
POSTHOG_PROJECT_PUBLIC_KEY
} from "@carbon/env";
import { getLogger } from "@carbon/logger";
+import { async } from "@carbon/utils";
import {
WORK_EVENT_MODULE,
WORK_EVENT_RECORD_KEY,
@@ -194,15 +195,20 @@ export async function captureWorkEvent<E extends WorkEventName>(
/**
* Fire-and-forget form, for call sites that should not await telemetry.
*
- * Prefer this everywhere in a request path. The returned promise is already
- * handled; ignoring it will not produce an unhandled rejection.
+ * Prefer this everywhere in a request path. The capture runs as background
+ * work (`async.background`), which the apps hand to Vercel's `waitUntil`
+ * (`async.onBackground` in `entry.server.tsx`): a bare unawaited fetch froze
+ * with the instance and finished, or was lost, a request later.
*/
export function trackWorkEvent<E extends WorkEventName>(
event: E,
payload: WorkEvents[E],
options?: { discriminator?: string | number | null }
): void {
- void captureWorkEvent(event, payload, options);
+ async.background(
+ () => captureWorkEvent(event, payload, options),
+ (error) => log.error("work event failed", { event, error })
+ );
}
export type {
diff --git a/packages/logger/AGENTS.md b/packages/logger/AGENTS.md
index 98ed49de65..53a228ab44 100644
--- a/packages/logger/AGENTS.md
+++ b/packages/logger/AGENTS.md
@@ -81,8 +81,8 @@ pnpm --filter @carbon/logger test
| `.` | `getLogger`, `LOG_LEVELS`, `parseLogLevel`, `CarbonLogLevel`, `Logger` type — isomorphic, safe everywhere |
| `./config.server` | `ensureLoggingConfigured()` (ANSI dev / JSONL+redacted prod, ALS) |
| `./config.client` | `ensureLoggingConfigured()` (plain console sink, no ALS) |
-| `./middleware.server` | `requestIdMiddleware`, `requestIdContext`, `getRequestId`, `REQUEST_ID_HEADER`, plus the request-context API re-exported from `context.server`: `requestContextMiddleware`, `getRouterContext`, `getRequestContext`, `oncePerRequest`, `oncePerRead` |
-| `./tracing.server` | `createTracing({ serviceName, afterRequest })` — React Router `instrumentations` (OpenTelemetry); `annotateRequestSpan(attributes)`; `nameRequestSpan(name)`; `namedMiddleware(list)`; `withSpan(name, attributes, run)`; `queryLog` — Kysely `log` hook, `undefined` when tracing is off |
+| `./middleware.server` | `requestMiddleware` (context + id + access log in one), `requestIdMiddleware`, `requestIdContext`, `getRequestId`, `REQUEST_ID_HEADER`, plus the request-context API re-exported from `context.server`: `requestContextMiddleware`, `getRouterContext`, `getRequestContext`, `oncePerRequest`, `oncePerRead` |
+| `./tracing.server` | `createTracing({ serviceName, afterRequest })` — React Router `instrumentations` (OpenTelemetry); `annotateRequestSpan(attributes)`; `nameRequestSpan(name)`; `timedMiddleware({ name: fn })`; `withSpan(name, attributes, run)`; `queryLog` — Kysely `log` hook, `undefined` when tracing is off |
| `./inngest` | `createInngestLogger()` — adapter passed to `new Inngest({ logger })` |
## Wiring (per app)
@@ -91,7 +91,7 @@ pnpm --filter @carbon/logger test
- `entry.client.tsx`: same from `@carbon/logger/config.client`.
- `entry.server.tsx` also exports
`instrumentations = createTracing({ serviceName: "carbon-erp", afterRequest })`.
-- `root.tsx`: `export const middleware = namedMiddleware([requestContextMiddleware, requestIdMiddleware, securityMiddleware, flashMiddleware])`
+- `root.tsx`: `export const middleware = timedMiddleware({ request: requestMiddleware, security: securityMiddleware, flash: flashMiddleware })` — `requestMiddleware` is the request scope in one middleware (context + request id + access log)
(request context FIRST so every downstream middleware and handler runs inside
the AsyncLocalStorage scope, then request id so downstream logs carry it).
@@ -131,10 +131,13 @@ One trace per request:
`POST /api/mcp call_tool sales_getCustomers`, `POST /api/v1/sales/getCustomers`.
Only known function ids and operations go into the name; the same values are
on `inngest.function.id` / `carbon.operation` for grouping.
-- **`middleware|loader|action <routeId>`** spans, one per route handler. React
- Router reports a middleware by its route alone, so the apps wrap the root list
- in `namedMiddleware([...])`, which renames each span after its function
- (`middleware requestIdMiddleware`). Each one contains everything after it.
+- **`loader|action <routeId>`** spans, one per route handler. Middleware get
+ no span: a middleware span contains everything after it, so it read as slow
+ whenever a loader was. The apps wrap the root list in
+ `timedMiddleware({ name: fn, ... })`, which records each middleware's OWN
+ time on the request span as `carbon.middleware.<name>.ms` (its total minus
+ the time in what it calls next). Named by key, not `fn.name`: the production
+ build minifies function names.
- **Fetch spans** from `@opentelemetry/instrumentation-undici`, only for fetches
made inside a request (`requireParentforSpans`). `fetchSpanName` names a
Supabase call by what it does — `GET /rest/v1/methodMaterial`,
diff --git a/packages/logger/src/config.server.test.ts b/packages/logger/src/config.server.test.ts
index ce51c09704..1b554177b8 100644
--- a/packages/logger/src/config.server.test.ts
+++ b/packages/logger/src/config.server.test.ts
@@ -2,8 +2,11 @@
// 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 { afterEach, describe, expect, it } from "vitest";
+import { RouterContextProvider } from "react-router";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { ensureLoggingConfigured } from "./config.server";
+import { runInRequestContext } from "./context.server";
+import { getLogger } from "./logger";
const CONFIGURED = Symbol.for("carbon.logging.configured");
@@ -19,4 +22,51 @@ describe("ensureLoggingConfigured (server)", () => {
// without reset).
expect(() => ensureLoggingConfigured({ level: "info" })).not.toThrow();
});
+
+ // A cancelled query comes back to its loader as an error. With the client
+ // gone it is not a failure, and logging it would bury the real ones.
+ it("drops cancellation errors logged for a read whose client has gone, and nothing else", () => {
+ const write = vi
+ .spyOn(console, "error")
+ .mockImplementation(() => undefined);
+ ensureLoggingConfigured({ level: "debug", pretty: false });
+ const controller = new AbortController();
+ const request = new Request("http://erp.test/x", {
+ signal: controller.signal
+ });
+ // What supabase-js returns for a cancelled call, as a loader logs it.
+ const cancelled = {
+ error: { message: "AbortError: This operation was aborted", code: "" }
+ };
+ const fail = (properties = {}) =>
+ getLogger("erp").error("Failed to load part", properties);
+ const inRequest = (properties?: object) =>
+ runInRequestContext(new RouterContextProvider(), () => fail(properties), {
+ request
+ });
+
+ inRequest(cancelled);
+ expect(write).toHaveBeenCalledTimes(1);
+
+ controller.abort();
+ inRequest(cancelled);
+ inRequest({ result: cancelled });
+ // A cancelled storage read: the abort sits under `originalError`.
+ inRequest({
+ error: {
+ name: "StorageUnknownError",
+ originalError: new DOMException("aborted", "AbortError")
+ }
+ });
+ expect(write).toHaveBeenCalledTimes(1);
+
+ // A real failure after the client left, e.g. a write, is still logged.
+ inRequest({ error: new Error("duplicate key") });
+ expect(write).toHaveBeenCalledTimes(2);
+
+ // Outside the request, the same AbortError is a timeout, not a departure.
+ fail(cancelled);
+ expect(write).toHaveBeenCalledTimes(3);
+ write.mockRestore();
+ });
});
diff --git a/packages/logger/src/config.server.ts b/packages/logger/src/config.server.ts
index 77e22e2b8b..c9f3231524 100644
--- a/packages/logger/src/config.server.ts
+++ b/packages/logger/src/config.server.ts
@@ -9,6 +9,7 @@ import {
getJsonLinesFormatter
} from "@logtape/logtape";
import { redactByField } from "@logtape/redaction";
+import { isAbandonedRead } from "./context.server";
import { devFormatter } from "./dev-formatter";
import { readEnv } from "./env";
import { httpDevFormatter } from "./http-formatter";
@@ -18,6 +19,26 @@ import { maskRedactedField, REDACT_FIELD_PATTERNS } from "./redaction";
const CONFIGURED = Symbol.for("carbon.logging.configured");
+/**
+ * A cancelled call: the AbortError itself, or what supabase-js makes of it — a
+ * database error whose message starts `AbortError:`, a storage error holding
+ * it as `originalError` — possibly under a result's `error`.
+ */
+function isAbortError(value: unknown, depth = 0): boolean {
+ if (!value || typeof value !== "object" || depth > 2) return false;
+ const { name, message, error, originalError, cause } = value as Record<
+ string,
+ unknown
+ >;
+ return (
+ name === "AbortError" ||
+ (typeof message === "string" && message.startsWith("AbortError")) ||
+ isAbortError(error, depth + 1) ||
+ isAbortError(originalError, depth + 1) ||
+ isAbortError(cause, depth + 1)
+ );
+}
+
export type ConfigureLoggingOptions = {
/** Override the env-derived level. */
level?: CarbonLogLevel;
@@ -67,11 +88,23 @@ export function ensureLoggingConfigured(
reset: true,
contextLocalStorage: new AsyncLocalStorage(),
sinks: { console: sink, httpConsole: httpSink },
+ filters: {
+ // Once the client of a read has gone, its database reads are cancelled
+ // and each comes back as an AbortError. Those are not failures, the same
+ // stance `handleError` takes on an aborted request. Anything else logged
+ // after the client left (a write that failed) still gets through.
+ liveRequest: (record) =>
+ !(
+ isAbandonedRead() &&
+ Object.values(record.properties).some((value) => isAbortError(value))
+ )
+ },
loggers: [
{
category: [CARBON_ROOT_CATEGORY],
lowestLevel: level,
- sinks: ["console"]
+ sinks: ["console"],
+ filters: ["liveRequest"]
},
{
category: [CARBON_ROOT_CATEGORY, "http"],
diff --git a/packages/logger/src/context.server.test.ts b/packages/logger/src/context.server.test.ts
index 7e753c5bd5..f0dc56d85d 100644
--- a/packages/logger/src/context.server.test.ts
+++ b/packages/logger/src/context.server.test.ts
@@ -5,8 +5,10 @@
import { createContext, RouterContextProvider } from "react-router";
import { describe, expect, it } from "vitest";
import {
+ currentRequest,
getRequestContext,
getRouterContext,
+ isAbandonedRead,
oncePerRead,
oncePerRequest,
requestMemoSize,
@@ -38,6 +40,33 @@ describe("request context", () => {
});
});
+describe("currentRequest and isAbandonedRead", () => {
+ const load = (controller: AbortController, method = "GET") =>
+ new Request("http://erp.test/x", { method, signal: controller.signal });
+
+ it("hands over the request being handled, and nothing outside one", () => {
+ const request = load(new AbortController());
+ expect(runInRequestContext(provider(), currentRequest, { request })).toBe(
+ request
+ );
+ expect(currentRequest()).toBeUndefined();
+ });
+
+ it("is true only for a read whose client has gone", () => {
+ const controller = new AbortController();
+ const read = load(controller);
+ const write = load(controller, "POST");
+ const abandoned = (request: Request) =>
+ runInRequestContext(provider(), isAbandonedRead, { request });
+
+ expect(abandoned(read)).toBe(false);
+ controller.abort();
+ expect(abandoned(read)).toBe(true);
+ expect(abandoned(write)).toBe(false);
+ expect(isAbandonedRead()).toBe(false);
+ });
+});
+
describe("oncePerRequest", () => {
it("computes once per key within a request", () => {
let calls = 0;
diff --git a/packages/logger/src/context.server.ts b/packages/logger/src/context.server.ts
index a3bd4452ef..b637c8d175 100644
--- a/packages/logger/src/context.server.ts
+++ b/packages/logger/src/context.server.ts
@@ -50,15 +50,43 @@ export const requestContextMiddleware: MiddlewareFunction<Response> = (
{ context, request },
next
) => {
- context.set(isReadRequestContext, READ_METHODS.has(request.method));
+ context.set(isReadRequestContext, isReadRequest(request));
+ context.set(requestContext, request);
return storage.run(context, () => next());
};
const READ_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
+/** Whether a request only reads. The one definition, shared with `@carbon/auth`. */
+export function isReadRequest(request: { method: string }): boolean {
+ return READ_METHODS.has(request.method);
+}
+
/** Whether this request only reads — see `oncePerRead`. */
const isReadRequestContext = createContext<boolean>(false);
+const requestContext = createContext<Request | null>(null);
+
+/**
+ * The request being handled, for code that is not handed it: a Supabase client
+ * built deep in a service binds itself to it (`requestFetch` in
+ * `@carbon/auth`), and the log filter reads its signal. Undefined outside a
+ * request.
+ */
+export function currentRequest(): Request | undefined {
+ return storage.getStore()?.get(requestContext) ?? undefined;
+}
+
+/**
+ * Whether the current request only reads and its client has gone away before
+ * the response was done. Never true for a mutating request or outside one.
+ */
+export function isAbandonedRead(): boolean {
+ const provider = storage.getStore();
+ if (!provider?.get(isReadRequestContext)) return false;
+ return provider.get(requestContext)?.signal.aborted ?? false;
+}
+
/** The current request's context provider, or undefined outside a request. */
export function getRouterContext(): RequestContext | undefined {
return storage.getStore();
@@ -141,8 +169,13 @@ export function requestMemoSize(): number {
export function runInRequestContext<T>(
provider: RequestContext,
fn: () => T,
- options?: { isRead?: boolean }
+ options?: { isRead?: boolean; request?: Request }
): T {
- provider.set(isReadRequestContext, options?.isRead ?? true);
+ // As the middleware decides it: from the request's method, when there is one.
+ const isRead =
+ options?.isRead ??
+ (options?.request ? isReadRequest(options.request) : true);
+ provider.set(isReadRequestContext, isRead);
+ provider.set(requestContext, options?.request ?? null);
return storage.run(provider, fn);
}
diff --git a/packages/logger/src/middleware.server.ts b/packages/logger/src/middleware.server.ts
index ccbffabc9e..bfb5f4a6b9 100644
--- a/packages/logger/src/middleware.server.ts
+++ b/packages/logger/src/middleware.server.ts
@@ -9,7 +9,11 @@ import {
type MiddlewareFunction,
type RouterContextProvider
} from "react-router";
-import { getRequestContext, requestDetailContext } from "./context.server";
+import {
+ getRequestContext,
+ requestContextMiddleware,
+ requestDetailContext
+} from "./context.server";
import { isSensitiveKey, REDACTED, redactSearch } from "./redaction";
import { annotateRequestSpan } from "./tracing.server";
@@ -20,9 +24,11 @@ import { annotateRequestSpan } from "./tracing.server";
// package's `exports` and repoint the four importers (both apps' root.tsx,
// auth's auth.server.ts and users.server.ts) at it, then drop this re-export.
export {
+ currentRequest,
describeRequest,
getRequestContext,
getRouterContext,
+ isReadRequest,
oncePerRead,
oncePerRequest,
requestContextMiddleware
@@ -162,7 +168,10 @@ export const requestIdMiddleware: MiddlewareFunction<Response> = async (
const res = await next();
annotateRequestSpan({
"http.response.status_code": res.status,
- "carbon.request_id": requestId
+ "carbon.request_id": requestId,
+ // The client left before the response was ready, so a read's queries
+ // were cancelled and its status says nothing about the server.
+ ...(request.signal.aborted && { "carbon.request.abandoned": true })
});
// Debug-level so it is visible in dev but filtered by the prod `info`
// default — the pipeline is observable with zero migrated call sites.
@@ -190,3 +199,14 @@ export const requestIdMiddleware: MiddlewareFunction<Response> = async (
response.headers.set(REQUEST_ID_HEADER, requestId);
return response;
};
+
+/**
+ * The request scope in one middleware: publishes the request context
+ * (`requestContextMiddleware`) and, inside it, assigns the request id and
+ * writes the access log (`requestIdMiddleware`). Register FIRST in an app's
+ * root `middleware`, so everything downstream runs inside both.
+ */
+export const requestMiddleware: MiddlewareFunction<Response> = (args, next) =>
+ requestContextMiddleware(args, () =>
+ Promise.resolve(requestIdMiddleware(args, next) as Response)
+ );
diff --git a/packages/logger/src/middleware.test.ts b/packages/logger/src/middleware.test.ts
index b1381c7c69..e46a9af9a3 100644
--- a/packages/logger/src/middleware.test.ts
+++ b/packages/logger/src/middleware.test.ts
@@ -11,9 +11,9 @@ import {
describeRequest,
getRequestId,
REQUEST_ID_HEADER,
- requestContextMiddleware,
requestIdContext,
- requestIdMiddleware
+ requestIdMiddleware,
+ requestMiddleware
} from "./middleware.server";
const recorder = createLogRecorder();
@@ -244,14 +244,10 @@ describe("describeRequest", () => {
const context = makeContext();
const args = { request, context } as never;
- await requestContextMiddleware(
- args,
- async () =>
- (await requestIdMiddleware(args, async () => {
- describeRequest("carbon-event-queue");
- return new Response("ok");
- })) as Response
- );
+ await requestMiddleware(args, async () => {
+ describeRequest("carbon-event-queue");
+ return new Response("ok");
+ });
const access = recorder.records.find(
(record) => record.properties.pathname === "/api/inngest"
@@ -269,14 +265,14 @@ describe("describeRequest", () => {
context
} as never;
- await requestContextMiddleware(
- args,
- async () =>
- (await requestIdMiddleware(
- args,
- async () => new Response("ok")
- )) as Response
- );
+ // One middleware: the id is readable with no context in hand, and echoed.
+ let ambientId: string | null = null;
+ const response = (await requestMiddleware(args, async () => {
+ ambientId = getRequestId();
+ return new Response("ok");
+ })) as Response;
+ expect(ambientId).not.toBeNull();
+ expect(response.headers.get(REQUEST_ID_HEADER)).toBe(ambientId);
const access = recorder.records.find(
(record) => record.properties.pathname === "/dashboard"
diff --git a/packages/logger/src/tracing.middleware.test.ts b/packages/logger/src/tracing.middleware.test.ts
index de3eafd1df..a80ce7c1b2 100644
--- a/packages/logger/src/tracing.middleware.test.ts
+++ b/packages/logger/src/tracing.middleware.test.ts
@@ -19,37 +19,54 @@ provider.register();
beforeEach(() => exporter.reset());
-it("names each middleware span after its function", async () => {
- const { namedMiddleware, routerInstrumentation } = await import(
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+it("records each middleware's own time on the request span, not what runs after it", async () => {
+ const { routerInstrumentation, timedMiddleware } = await import(
"./tracing.server"
);
- type Handler = () => Promise<{ error?: Error }>;
- let wrap: (call: Handler, info: never) => Promise<void> = async () =>
+ type Handle = () => Promise<{ error?: Error }>;
+ let request: (handle: Handle, info: never) => Promise<void> = async () =>
undefined;
- routerInstrumentation(provider.getTracer("test")).route?.({
- id: "root",
- instrument: (handlers: { middleware?: typeof wrap }) => {
- if (handlers.middleware) wrap = handlers.middleware;
+ routerInstrumentation(provider.getTracer("test")).handler?.({
+ instrument: (handlers: { request?: typeof request }) => {
+ if (handlers.request) request = handlers.request;
}
} as never);
- const requestIdMiddleware = async () => undefined;
- const flashMiddleware = async () => undefined;
- for (const run of namedMiddleware([requestIdMiddleware, flashMiddleware])) {
- await wrap(
- async () => {
- await run();
- return {};
- },
- { request: { method: "GET" }, pattern: "x" } as never
- );
- }
+ const [slow, quick] = timedMiddleware<Response>({
+ // 30 ms of its own before the rest of the request, which takes 60 ms.
+ slow: async (_args, next) => {
+ await sleep(30);
+ return next();
+ },
+ quick: (_args, next) => next()
+ });
- expect(exporter.getFinishedSpans().map((span) => span.name)).toEqual([
- "middleware requestIdMiddleware",
- "middleware flashMiddleware"
- ]);
+ await request(
+ async () => {
+ await slow?.({} as never, () =>
+ Promise.resolve(
+ quick?.({} as never, async () => {
+ await sleep(60);
+ return new Response();
+ }) as Response
+ )
+ );
+ return {};
+ },
+ { request: { method: "GET", url: "http://erp.test/x" } } as never
+ );
+
+ const spans = exporter.getFinishedSpans();
+ expect(spans.map((span) => span.name)).toEqual(["GET"]);
+ const attributes = spans[0]?.attributes ?? {};
+ const slowMs = attributes["carbon.middleware.slow.ms"] as number;
+ const quickMs = attributes["carbon.middleware.quick.ms"] as number;
+ expect(slowMs).toBeGreaterThanOrEqual(25);
+ expect(slowMs).toBeLessThan(55);
+ expect(quickMs).toBeLessThan(10);
});
it("wraps a call in a span and marks it failed when the call throws", async () => {
diff --git a/packages/logger/src/tracing.pool.test.ts b/packages/logger/src/tracing.pool.test.ts
new file mode 100644
index 0000000000..1100732275
--- /dev/null
+++ b/packages/logger/src/tracing.pool.test.ts
@@ -0,0 +1,67 @@
+// 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 {
+ InMemorySpanExporter,
+ NodeTracerProvider,
+ SimpleSpanProcessor
+} from "@opentelemetry/sdk-trace-node";
+import { beforeEach, expect, it, vi } from "vitest";
+
+// Tracing is decided when the module loads, and the global provider registers once.
+vi.stubEnv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4318");
+const exporter = new InMemorySpanExporter();
+new NodeTracerProvider({
+ spanProcessors: [new SimpleSpanProcessor(exporter)]
+}).register();
+
+beforeEach(() => exporter.reset());
+
+// The counts a node-postgres pool reports, settable per test.
+const fakePool = (state: {
+ idleCount: number;
+ totalCount: number;
+ waitingCount: number;
+}) => ({
+ ...state,
+ options: { max: 2 },
+ connect: vi.fn(async (..._args: unknown[]) => "client")
+});
+
+it("records a wait only when connect() cannot hand out an idle connection", async () => {
+ const { traceConnectionWaits } = await import("./tracing.server");
+ const names = () => exporter.getFinishedSpans().map((span) => span.name);
+
+ const idle = traceConnectionWaits(
+ fakePool({ idleCount: 1, totalCount: 2, waitingCount: 0 })
+ );
+ expect(await idle.connect()).toBe("client");
+ expect(names()).toEqual([]);
+
+ const opening = traceConnectionWaits(
+ fakePool({ idleCount: 0, totalCount: 1, waitingCount: 0 })
+ );
+ await opening.connect();
+ expect(names()).toEqual(["db connect"]);
+
+ // One idle connection, but an earlier caller is already queued for it.
+ const full = traceConnectionWaits(
+ fakePool({ idleCount: 1, totalCount: 2, waitingCount: 3 })
+ );
+ await full.connect();
+ expect(names()).toEqual(["db connect", "db pool wait"]);
+ expect(
+ exporter.getFinishedSpans()[1]?.attributes[
+ "db.client.connection.pool.waiting"
+ ]
+ ).toBe(3);
+
+ // pg's own pool.query uses the callback form; it passes straight through.
+ const callback = () => undefined;
+ await full.connect(callback as never);
+ expect(names()).toHaveLength(2);
+
+ // Wrapping twice does not wrap twice.
+ expect(traceConnectionWaits(full)).toBe(full);
+});
diff --git a/packages/logger/src/tracing.server.ts b/packages/logger/src/tracing.server.ts
index 40d16f5bf5..2781ec0501 100644
--- a/packages/logger/src/tracing.server.ts
+++ b/packages/logger/src/tracing.server.ts
@@ -34,7 +34,7 @@ import {
ATTR_URL_PATH,
ATTR_URL_QUERY
} from "@opentelemetry/semantic-conventions";
-import type { ServerInstrumentation } from "react-router";
+import type { MiddlewareFunction, ServerInstrumentation } from "react-router";
import { REDACTED, redactSearch } from "./redaction";
const REQUEST_SPAN = createContextKey("carbon.request-span");
@@ -161,22 +161,35 @@ export function fetchSpanName(method: string, origin: string, path: string) {
}
/**
- * React Router reports a middleware by its route alone, so four root
- * middleware are four spans named `middleware root`. Wrapping the list names
- * each span after its function.
+ * The middleware in the order given, each one's OWN time recorded on the
+ * request span as `carbon.middleware.<key>.ms`: its total minus the time spent
+ * in what it calls next. A span per middleware cannot say that — it contains
+ * everything after it, so it reads as slow whenever a loader is. Named by key,
+ * not by the function's `name`, which the production build minifies.
*/
-export function namedMiddleware<
- Middleware extends (...args: never[]) => unknown
->(middleware: Middleware[]): Middleware[] {
- if (!enabled) return middleware;
- return middleware.map(
- (run) =>
- ((...args) => {
- if (run.name)
- trace.getActiveSpan()?.updateName(`middleware ${run.name}`);
- return run(...args);
- }) as Middleware
- );
+export function timedMiddleware<Result>(
+ middleware: Record<string, MiddlewareFunction<Result>>
+): MiddlewareFunction<Result>[] {
+ const entries = Object.entries(middleware);
+ if (!enabled) return entries.map(([, run]) => run);
+ return entries.map(([name, run]) => async (args, next) => {
+ const start = performance.now();
+ let downstream = 0;
+ try {
+ return await run(args, async () => {
+ const called = performance.now();
+ try {
+ return await next();
+ } finally {
+ downstream += performance.now() - called;
+ }
+ });
+ } finally {
+ annotateRequestSpan({
+ [`carbon.middleware.${name}.ms`]: performance.now() - start - downstream
+ });
+ }
+ });
}
// Inngest's event API takes the event key as a path segment (`POST /e/<key>`),
@@ -224,6 +237,50 @@ export function querySpanName(sql: string) {
return table ? `${operation} ${table}` : operation;
}
+/** The parts of a node-postgres `Pool` that tell whether `connect()` will wait. */
+type ObservablePool = {
+ connect: (...args: never[]) => unknown;
+ idleCount: number;
+ totalCount: number;
+ waitingCount: number;
+ options: { max?: number };
+};
+
+const TRACED_POOL = Symbol.for("carbon.tracing.pool");
+
+/**
+ * Query spans time only the query, so a request waiting for a free connection
+ * looked like a slow request with fast queries. When `connect()` cannot hand
+ * out an idle connection this records the wait as a span: `db pool wait` when
+ * the pool is full and the caller queues, `db connect` when it has to open a
+ * new connection. Taking an idle connection records nothing. Idempotent.
+ */
+export function traceConnectionWaits<P extends ObservablePool>(pool: P): P {
+ if (!enabled || TRACED_POOL in pool) return pool;
+ const connect = pool.connect.bind(pool) as (...args: unknown[]) => unknown;
+ Object.assign(pool, {
+ [TRACED_POOL]: true,
+ // The callback form is pg's own `pool.query`; only the promise form is
+ // awaited by a caller.
+ connect: (...args: unknown[]) => {
+ // Idle connections go to callers already queued first.
+ if (args.length > 0 || pool.idleCount > pool.waitingCount) {
+ return connect(...args);
+ }
+ const full = pool.totalCount >= (pool.options.max ?? 10);
+ return withSpan(
+ full ? "db pool wait" : "db connect",
+ {
+ "db.client.connection.pool.size": pool.totalCount,
+ "db.client.connection.pool.waiting": pool.waitingCount
+ },
+ () => connect() as Promise<unknown>
+ );
+ }
+ });
+ return pool;
+}
+
/** Kysely `log` hook. Kysely reports a query after it ran, so the span is back-dated. */
function traceQuery(event: {
level: "query" | "error";
@@ -283,6 +340,16 @@ function end(span: Span, error: Error | undefined) {
span.end();
}
+/**
+ * Starts a span and returns what ends it, for a wait that someone else's call
+ * finishes. Does nothing when tracing is off.
+ */
+export function startSpan(name: string, attributes: Attributes): () => void {
+ if (!enabled) return () => undefined;
+ const span = trace.getTracer("carbon").startSpan(name, { attributes });
+ return () => span.end();
+}
+
/** Runs `run` in a child span of whatever is active; a plain call when tracing is off. */
export function withSpan<T>(
name: string,
@@ -352,7 +419,6 @@ export function routerInstrumentation(
};
instrument({
- middleware: traced("middleware"),
loader: traced("loader"),
action: traced("action")
});
diff --git a/packages/stripe/src/gtm-events.server.ts b/packages/stripe/src/gtm-events.server.ts
index 9d7e0b09cb..ff5baaafa7 100644
--- a/packages/stripe/src/gtm-events.server.ts
+++ b/packages/stripe/src/gtm-events.server.ts
@@ -7,6 +7,10 @@ import { getLogger } from "@carbon/logger";
const log = getLogger("stripe", "gtm-events");
+// The forward runs as background work that keeps a serverless instance up, so
+// a GTM that never answers must not hold it until the function times out.
+const TIMEOUT_MS = 10_000;
+
export async function forwardToGtm(
type: string,
metadata: Record<string, unknown>
@@ -23,7 +27,8 @@ export async function forwardToGtm(
"content-type": "application/json",
"x-gtm-events-key": GTM_EVENTS_API_SECRET_KEY
},
- body: JSON.stringify({ type, metadata })
+ body: JSON.stringify({ type, metadata }),
+ signal: AbortSignal.timeout(TIMEOUT_MS)
});
if (!res.ok) {
diff --git a/packages/stripe/src/stripe.server.ts b/packages/stripe/src/stripe.server.ts
index ecafde04b2..72a1406054 100644
--- a/packages/stripe/src/stripe.server.ts
+++ b/packages/stripe/src/stripe.server.ts
@@ -15,7 +15,7 @@ import {
import { redis } from "@carbon/kv";
import { trigger } from "@carbon/lib/trigger";
import { getLogger } from "@carbon/logger";
-import { companyPlanCacheKey, Edition, Plan } from "@carbon/utils";
+import { async, companyPlanCacheKey, Edition, Plan } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
import { Stripe } from "stripe";
import { z } from "zod";
@@ -483,9 +483,10 @@ export async function processStripeEvent({
eventType === "invoice.payment_succeeded" ||
eventType === "invoice.payment_failed"
) {
- forwardToGtm(eventType, { invoice: event.data.object }).catch((err) => {
- log.error("gtm-events forward failed", { error: err });
- });
+ async.background(
+ () => forwardToGtm(eventType, { invoice: event.data.object }),
+ (error) => log.error("gtm-events forward failed", { error })
+ );
}
}
diff --git a/packages/utils/AGENTS.md b/packages/utils/AGENTS.md
index a3bab7121f..eacb4a67ca 100644
--- a/packages/utils/AGENTS.md
+++ b/packages/utils/AGENTS.md
@@ -7,7 +7,7 @@ Pure utility functions shared across all Carbon packages and apps. Covers accoun
- Import utilities from `@carbon/utils` — never duplicate utility logic in app code.
- Use `sanitize(obj)` to strip empty values before Supabase insert/update operations.
- Use domain-specific helpers where they exist: `formatCurrency()` for money, `getStatus()` for status resolution, `getBomLevel()` for BOM traversal.
-- Keep utilities **pure** — no side effects, no database calls, no env access (except `isBrowser` check). Only `@internationalized/date`, `zod`, and `lodash.template` (plus `nanoid` and `@supabase/supabase-js` for the typed `supabase.ts` wrappers) are allowed runtime deps.
+- Keep utilities **pure** — no side effects, no database calls, no env access (except `isBrowser` check). The `async` module is the one exception to "no side effects": it schedules work the caller hands it and holds the host's lifetime hook. Only `@internationalized/date`, `zod` and `lodash.template` (plus `nanoid` and `@supabase/supabase-js` for the typed `supabase.ts` wrappers) are allowed runtime deps.
## Ask First
@@ -18,7 +18,7 @@ Pure utility functions shared across all Carbon packages and apps. Covers accoun
## Never
- Import server-only packages (`@carbon/auth`, `@carbon/database`, `@carbon/kv`) from here — `@carbon/utils` must remain client-safe. **Deliberate edge-shared utilities:** `precision.ts`, `accounting-currency.ts`, `accounting-posting.ts`, `payment-funding.ts`, `sales-posting-amounts.ts`, `batch-time-split.ts`, and `batch-compatibility.ts` each re-export their namesake under `packages/database/supabase/functions/shared/` by relative path (`math.ts` consumes `precision.ts`). Those implementations live there because the Supabase edge runtime only mounts `supabase/functions/`; re-exporting rather than duplicating keeps ONE source of truth so the Node and Deno sides never drift. They are client-safe source imports, not imports of the server/database package, and not something to "fix" (same pattern as `packages/database/src/sampling.ts`). Keep their dependency graphs pure.
-- Add async/IO operations — utilities should be synchronous pure functions (the one exception is `supabase.ts` helpers which are typed wrappers). File/image handling lives in `@carbon/files`, not here.
+- Add async/IO operations — utilities should be synchronous pure functions (the exceptions are the `supabase.ts` helpers, which are typed wrappers, and the `async` module, which runs the caller's own async work and does no IO itself). File/image handling lives in `@carbon/files`, not here.
- Duplicate what already exists — check the barrel export (`src/index.ts`) before adding a new utility.
## Validation Commands
@@ -38,6 +38,7 @@ pnpm --filter @carbon/utils typecheck
| `payment-funding` | Shared effective-settlement, invoice/funding balance reducers and exact document-principal allocation; callers own tenant/status/reservation queries |
| `sales-posting-amounts` | Pure sales component normalization and posting calculations |
| `arrays` | Array manipulation, grouping, deduplication |
+| `async` | The `async` object: `Promise.all`, `Promise.allSettled` and `items.map` with a limit on how many run at once (`DEFAULT_CONCURRENCY`, 8, unless `{ concurrency }` says otherwise). `map(items, mapper)` follows p-map, `all(tasks)` and `allSettled(tasks)` take FUNCTIONS (a promise is already running) and keep the tuple's types, `limit(n)` follows p-limit. After a failure `map` / `all` start nothing further. Database calls inside a request need no limit of their own — the client `requirePermissions` returns has at most 8 in flight. `background(task, onError)` is fire-and-forget with a required error handler. `onBackground(hook)` registers what keeps the process alive for that work — both apps register Vercel's `waitUntil` in `entry.server.tsx` — so use `background` (never a bare unawaited promise) for anything a request leaves running |
| `bom` | Bill of Materials traversal and level computation |
| `date` | Date formatting, parsing, range helpers (uses `@internationalized/date`); `HOUR_MS`/`DAY_MS` millisecond constants for instant arithmetic |
| `datetime` | Server-side date derivation with mandatory explicit timezone: `timestamp()`, `today(tz)`, `now(tz)`, `businessDay(instant, tz)`, `weekBounds(tz, offset?, anchor?)` (DST-safe Monday→Sunday instant bounds), `weekNumber(date)`. DST/exotic-zone stress suite in `datetime.test.ts` (gap/overlap disambiguation, midnight-skipping zones, 167/169h weeks, ±30/45-min offsets). Mirrored for Deno at `packages/database/supabase/functions/lib/datetime.ts` — keep in sync |
diff --git a/packages/utils/src/all.ts b/packages/utils/src/all.ts
deleted file mode 100644
index 6d8c526926..0000000000
--- a/packages/utils/src/all.ts
+++ /dev/null
@@ -1,204 +0,0 @@
-// 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.
-
-/**
- * Promise.all with automatic dependency optimization and full type inference
- *
- * Usage:
- * const { a, b, c } = await all({
- * a() { return 1 },
- * async b() { return 'hello' },
- * async c() { return (await this.$.a) + 10 }
- * })
- *
- * Credits: https://github.com/shuding/better-all/blob/main/lib/index.ts
- */
-
-// Extract the resolved return type from task functions
-type TaskResult<T> = T extends (...args: any[]) => infer R ? Awaited<R> : never;
-
-// The $ proxy type - all task results as promises
-type DepProxy<T extends Record<string, (...args: any[]) => any>> = {
- readonly [K in keyof T]: Promise<TaskResult<T[K]>>;
-};
-
-// Context available to each task via `this`
-type TaskContext<T extends Record<string, (...args: any[]) => any>> = {
- $: DepProxy<T>;
-};
-
-// Result type - all tasks resolved to their return values
-type AllResult<T extends Record<string, (...args: any[]) => any>> = {
- [K in keyof T]: TaskResult<T[K]>;
-};
-
-// Settled result types for allSettled
-type SettledFulfilled<T> = {
- status: "fulfilled";
- value: T;
-};
-
-type SettledRejected = {
- status: "rejected";
- reason: any;
-};
-
-type SettledResult<T> = SettledFulfilled<T> | SettledRejected;
-
-// Result type for allSettled - all tasks as settled results
-type AllSettledResult<T extends Record<string, (...args: any[]) => any>> = {
- [K in keyof T]: SettledResult<TaskResult<T[K]>>;
-};
-
-/**
- * Internal core implementation for executing tasks with automatic dependency resolution.
- * This is shared between `all` and `allSettled`.
- */
-function executeTasksInternal<T extends Record<string, any>>(
- tasks: T,
- handleSettled: boolean
-): Promise<any> {
- const taskNames = Object.keys(tasks) as (keyof T)[];
- const results = new Map<keyof T, any>();
- const errors = new Map<keyof T, any>();
- const resolvers = new Map<
- keyof T,
- [(value: any) => void, (reason?: any) => void][]
- >();
- const returnValue: Record<string, any> = {};
-
- const waitForDep = (depName: keyof T): Promise<any> => {
- if (!(depName in tasks)) {
- return Promise.reject(new Error(`Unknown task "${String(depName)}"`));
- }
- if (results.has(depName)) {
- return Promise.resolve(results.get(depName));
- }
- if (errors.has(depName)) {
- return Promise.reject(errors.get(depName));
- }
- return new Promise((resolve, reject) => {
- if (!resolvers.has(depName)) {
- resolvers.set(depName, []);
- }
- resolvers.get(depName)!.push([resolve, reject]);
- });
- };
-
- const handleResult = (name: keyof T, value: any) => {
- results.set(name, value);
- if (handleSettled) {
- returnValue[name as string] = { status: "fulfilled", value };
- } else {
- returnValue[name as string] = value;
- }
- if (resolvers.has(name)) {
- for (const [resolve] of resolvers.get(name)!) {
- resolve(value);
- }
- }
- };
-
- const handleError = (name: keyof T, err: any) => {
- errors.set(name, err);
- if (handleSettled) {
- returnValue[name as string] = { status: "rejected", reason: err };
- }
- if (resolvers.has(name)) {
- for (const [, reject] of resolvers.get(name)!) {
- reject(err);
- }
- }
- };
-
- // Create dep proxy
- const depProxy = new Proxy({} as DepProxy<T>, {
- get(_, depName: string) {
- return waitForDep(depName as keyof T);
- }
- });
-
- // Create context with $ proxy
- const context: TaskContext<T> = { $: depProxy };
-
- // Run all tasks in parallel
- const promises = taskNames.map(async (name) => {
- try {
- const taskFn = tasks[name];
- if (typeof taskFn !== "function") {
- throw new Error(`Task "${String(name)}" is not a function`);
- }
-
- const result = await taskFn.call(context);
- handleResult(name, result);
- } catch (err) {
- handleError(name, err);
- if (!handleSettled) {
- throw err;
- }
- }
- });
-
- if (handleSettled) {
- // For allSettled, wait for all promises to settle (never rejects)
- return Promise.allSettled(promises).then(() => returnValue);
- } else {
- // For all, reject on first error (like Promise.all)
- return Promise.all(promises).then(() => returnValue);
- }
-}
-
-/**
- * Execute tasks with automatic dependency resolution.
- *
- * @example
- * const { a, b, c } = await all({
- * async a() { return 1 },
- * async b() { return 'hello' },
- * async c() { return (await this.$.a) + 10 }
- * })
- */
-export function all<T extends Record<string, any>>(
- tasks: T &
- ThisType<{
- $: {
- [K in keyof T]: ReturnType<T[K]> extends Promise<infer R>
- ? Promise<R>
- : Promise<ReturnType<T[K]>>;
- };
- }> & {
- [P in keyof T]: T[P] extends (...args: any[]) => any ? T[P] : never;
- }
-): Promise<AllResult<T>> {
- return executeTasksInternal(tasks, false) as Promise<AllResult<T>>;
-}
-
-/**
- * Execute tasks with automatic dependency resolution, returning settled results for all tasks.
- * Unlike `all`, this will never reject - failed tasks will be included in the result with their error.
- *
- * @example
- * const { a, b, c } = await allSettled({
- * async a() { return 1 },
- * async b() { throw new Error('failed') },
- * async c() { return (await this.$.a) + 10 }
- * })
- * // a: { status: 'fulfilled', value: 1 }
- * // b: { status: 'rejected', reason: Error('failed') }
- * // c: { status: 'fulfilled', value: 11 }
- */
-export function allSettled<T extends Record<string, any>>(
- tasks: T &
- ThisType<{
- $: {
- [K in keyof T]: ReturnType<T[K]> extends Promise<infer R>
- ? Promise<R>
- : Promise<ReturnType<T[K]>>;
- };
- }> & {
- [P in keyof T]: T[P] extends (...args: any[]) => any ? T[P] : never;
- }
-): Promise<AllSettledResult<T>> {
- return executeTasksInternal(tasks, true) as Promise<AllSettledResult<T>>;
-}
diff --git a/packages/utils/src/async.test.ts b/packages/utils/src/async.test.ts
new file mode 100644
index 0000000000..8c2e056d24
--- /dev/null
+++ b/packages/utils/src/async.test.ts
@@ -0,0 +1,212 @@
+// 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 { afterEach, describe, expect, it } from "vitest";
+import { async } from "./async";
+
+const tick = (ms = 5) => new Promise((resolve) => setTimeout(resolve, ms));
+
+/** Counts how many calls are in flight at once. */
+function gauge() {
+ let running = 0;
+ let peak = 0;
+ return {
+ peak: () => peak,
+ async run<T>(value: T, ms = 5) {
+ peak = Math.max(peak, ++running);
+ await tick(ms);
+ running--;
+ return value;
+ }
+ };
+}
+
+describe("async.map", () => {
+ it("keeps input order and never runs more than the limit at once", async () => {
+ const g = gauge();
+ const items = [5, 1, 4, 2, 3, 6, 7];
+ const doubled = await async.map(items, (n) => g.run(n * 2, n), {
+ concurrency: 3
+ });
+ expect(doubled).toEqual([10, 2, 8, 4, 6, 12, 14]);
+ expect(g.peak()).toBe(3);
+ });
+
+ it("rejects with the first failure and starts nothing after it", async () => {
+ const started: number[] = [];
+ await expect(
+ async.map(
+ [1, 2, 3, 4, 5],
+ async (n) => {
+ started.push(n);
+ // Item 1 is still running when item 2 fails.
+ await tick(n === 1 ? 20 : 5);
+ if (n === 2) throw new Error("two failed");
+ return n;
+ },
+ { concurrency: 2 }
+ )
+ ).rejects.toThrow("two failed");
+ await tick(30);
+ expect(started).toEqual([1, 2]);
+ });
+
+ it("starts nothing when reading the input throws", () => {
+ const started: number[] = [];
+ function* broken() {
+ yield 1;
+ yield 2;
+ throw new Error("input failed");
+ }
+ expect(() =>
+ async.map(broken(), (n) => {
+ started.push(n);
+ return n;
+ })
+ ).toThrow("input failed");
+ expect(started).toEqual([]);
+ });
+
+ it("rejects a limit that is not a positive integer or Infinity", () => {
+ expect(() => async.map([1], (n) => n, { concurrency: 0 })).toThrow(
+ TypeError
+ );
+ });
+});
+
+describe("async.all", () => {
+ it("returns each task's result in order, under the limit", async () => {
+ const g = gauge();
+ const [count, name, flag] = await async.all(
+ [() => g.run(1, 10), () => g.run("two"), () => g.run(true)],
+ { concurrency: 2 }
+ );
+ expect([count, name, flag]).toEqual([1, "two", true]);
+ expect(g.peak()).toBe(2);
+ });
+});
+
+describe("async.allSettled", () => {
+ it("runs every task under the limit and reports each outcome", async () => {
+ const g = gauge();
+ const results = await async.allSettled(
+ [
+ () => g.run(1),
+ () => {
+ throw new Error("sync failure");
+ },
+ () => g.run(3)
+ ],
+ { concurrency: 2 }
+ );
+ expect(results.map((r) => r.status)).toEqual([
+ "fulfilled",
+ "rejected",
+ "fulfilled"
+ ]);
+ expect(g.peak()).toBe(2);
+ });
+});
+
+describe("async.limit", () => {
+ it("runs at most the limit at once, in call order", async () => {
+ const g = gauge();
+ const limit = async.limit(2);
+ const order: number[] = [];
+ const calls = [1, 2, 3, 4, 5].map((n) =>
+ limit(async () => {
+ order.push(n);
+ return g.run(n);
+ })
+ );
+ expect(limit.activeCount).toBe(2);
+ expect(limit.pendingCount).toBe(3);
+ expect(await Promise.all(calls)).toEqual([1, 2, 3, 4, 5]);
+ expect(order).toEqual([1, 2, 3, 4, 5]);
+ expect(g.peak()).toBe(2);
+ expect(limit.activeCount).toBe(0);
+ });
+
+ it("hands a freed slot to the queued call, not to one made while it resumes", async () => {
+ const limit = async.limit(1);
+ const order: string[] = [];
+ let release!: () => void;
+ const first = limit(
+ () =>
+ new Promise<void>((resolve) => {
+ release = resolve;
+ })
+ );
+ const second = limit(async () => {
+ order.push("second");
+ });
+ await Promise.resolve();
+ release();
+ // Runs after the first call has freed its slot, before the second resumes.
+ let third: Promise<void> | undefined;
+ queueMicrotask(() => {
+ third = limit(async () => {
+ order.push("third");
+ });
+ });
+ await Promise.all([first, second]);
+ await third;
+ expect(order).toEqual(["second", "third"]);
+ });
+
+ it("frees the slot when a call fails", async () => {
+ const limit = async.limit(1);
+ await expect(
+ limit(async () => {
+ throw new Error("failed");
+ })
+ ).rejects.toThrow("failed");
+ expect(await limit(() => "next")).toBe("next");
+ });
+});
+
+describe("async.onBackground", () => {
+ afterEach(() => async.onBackground(undefined));
+
+ it("hands every piece of background work to the host's hook, failures included", async () => {
+ const kept: Promise<unknown>[] = [];
+ async.onBackground((work) => kept.push(work));
+ const done: string[] = [];
+ async.background(
+ async () => {
+ await tick(10);
+ done.push("slow");
+ },
+ () => undefined
+ );
+ async.background(
+ async () => {
+ throw new Error("lost");
+ },
+ () => done.push("failed")
+ );
+ expect(kept).toHaveLength(2);
+ expect(done).toEqual([]);
+ // What the host waits for settles only when the work has, and never rejects.
+ await Promise.all(kept);
+ expect(done.sort()).toEqual(["failed", "slow"]);
+ });
+});
+
+describe("async.background", () => {
+ it("contains a failure of the error handler itself", async () => {
+ const kept: Promise<unknown>[] = [];
+ async.onBackground((work) => kept.push(work));
+ async.background(
+ () => {
+ throw new Error("task failed");
+ },
+ () => {
+ throw new Error("handler failed");
+ }
+ );
+ await expect(kept[0]).resolves.toBeUndefined();
+ async.onBackground(undefined);
+ });
+});
diff --git a/packages/utils/src/async.ts b/packages/utils/src/async.ts
new file mode 100644
index 0000000000..8920cd74e1
--- /dev/null
+++ b/packages/utils/src/async.ts
@@ -0,0 +1,170 @@
+// 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.
+
+/** How many things `map`, `all`, `allSettled` and `limit` run at once unless told otherwise. */
+export const DEFAULT_CONCURRENCY = 8;
+
+type MaybePromise<T> = T | Promise<T>;
+
+export type ConcurrencyOptions = { concurrency?: number };
+
+type Tasks = readonly (() => unknown)[];
+
+function assertConcurrency(concurrency: number) {
+ if (
+ !(Number.isSafeInteger(concurrency) && concurrency >= 1) &&
+ concurrency !== Number.POSITIVE_INFINITY
+ ) {
+ throw new TypeError(
+ `Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${concurrency}\``
+ );
+ }
+}
+
+/**
+ * p-limit: `limit(fn)` runs `fn` once fewer than `concurrency` of the calls
+ * made through this `limit` are running, in the order they were made.
+ * `activeCount` and `pendingCount` say how many are running and queued.
+ */
+function limit(concurrency = DEFAULT_CONCURRENCY) {
+ assertConcurrency(concurrency);
+ let active = 0;
+ const queue: (() => void)[] = [];
+ // A freed slot passes straight to the next queued call, so a call made
+ // before that one resumes cannot take it.
+ const next = () => {
+ const waiter = queue.shift();
+ if (waiter) waiter();
+ else active--;
+ };
+ const run = async <R>(fn: () => MaybePromise<R>): Promise<R> => {
+ if (active >= concurrency) {
+ await new Promise<void>((resolve) => queue.push(resolve));
+ } else {
+ active++;
+ }
+ try {
+ return await fn();
+ } finally {
+ next();
+ }
+ };
+ return Object.defineProperties(run, {
+ activeCount: { get: () => active },
+ pendingCount: { get: () => queue.length }
+ }) as typeof run & {
+ readonly activeCount: number;
+ readonly pendingCount: number;
+ };
+}
+
+/**
+ * p-map: `Promise.all(items.map(mapper))`, at most `concurrency` at a time,
+ * results in input order. Rejects with the first failure and starts nothing
+ * after it.
+ */
+function map<T, R>(
+ items: Iterable<T>,
+ mapper: (item: T, index: number) => MaybePromise<R>,
+ { concurrency }: ConcurrencyOptions = {}
+): Promise<R[]> {
+ const run = limit(concurrency);
+ // Read the input to the end before anything starts: if iterating it throws,
+ // no mapper is left running with nobody watching its result.
+ const list = Array.from(items);
+ let failed = false;
+ return Promise.all(
+ list.map((item, index) =>
+ run(async () => {
+ // The result is already a rejection; nobody reads this value.
+ if (failed) return undefined as R;
+ try {
+ return await mapper(item, index);
+ } catch (error) {
+ failed = true;
+ throw error;
+ }
+ })
+ )
+ );
+}
+
+/**
+ * p-all: `Promise.all` over functions instead of promises, so at most
+ * `concurrency` run at a time. Results keep the tuple's types and order.
+ */
+function all<const T extends Tasks>(tasks: T, options?: ConcurrencyOptions) {
+ return map(tasks, (task) => task(), options) as Promise<{
+ -readonly [K in keyof T]: Awaited<ReturnType<T[K]>>;
+ }>;
+}
+
+/** p-settle: `Promise.allSettled` over functions, at most `concurrency` at a time. */
+function allSettled<const T extends Tasks>(
+ tasks: T,
+ { concurrency }: ConcurrencyOptions = {}
+) {
+ const run = limit(concurrency);
+ return Promise.allSettled(tasks.map((task) => run(task))) as Promise<{
+ -readonly [K in keyof T]: PromiseSettledResult<Awaited<ReturnType<T[K]>>>;
+ }>;
+}
+
+let extendLifetime: ((work: Promise<unknown>) => void) | undefined;
+
+/**
+ * Starts work nobody waits for. A failure goes to `onError`, which is required:
+ * a detached promise with no handler is an unhandled rejection.
+ *
+ * The work is handed to the host's lifetime hook when one is registered (see
+ * `onBackground`), so it is not cut off when the response has been sent.
+ */
+function background(
+ task: () => Promise<unknown> | unknown,
+ onError: (error: unknown) => void
+): void {
+ // `onError` is the last resort: if it throws too, there is nowhere left to
+ // report it, and an unhandled rejection can take the process down.
+ const work = Promise.resolve()
+ .then(task)
+ .catch(onError)
+ .catch(() => {});
+ extendLifetime?.(work);
+}
+
+/**
+ * Registers what keeps the process alive for background work: on a host that
+ * freezes it once the response is sent, its `waitUntil`. Each app registers it
+ * once at startup. Without one, unawaited work stalls mid-flight until the
+ * next request wakes the instance, or is lost.
+ */
+function onBackground(
+ hook: ((work: Promise<unknown>) => void) | undefined
+): void {
+ extendLifetime = hook;
+}
+
+/**
+ * `Promise.all`, `Promise.allSettled` and `items.map` with a limit on how many
+ * run at once (8 unless told otherwise). Tasks are functions, since a promise
+ * is already running. Database calls inside a request need no limit of their
+ * own: the Supabase client from `requirePermissions` runs at most 8 at once.
+ *
+ * const [order, lines] = await async.all([
+ * () => getOrder(client, id),
+ * () => getLines(client, id)
+ * ]);
+ * const rows = await async.map(ids, (id) => load(id), { concurrency: 4 });
+ * const results = await async.allSettled(ids.map((id) => () => sync(id)));
+ * async.background(() => track(event), (error) => logger.error("…", { error }));
+ * async.onBackground(waitUntil); // once at startup, on a host that freezes
+ */
+export const async = {
+ all,
+ allSettled,
+ map,
+ limit,
+ background,
+ onBackground
+} as const;
diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts
index 880d984ac3..d9cc0a8a08 100644
--- a/packages/utils/src/index.ts
+++ b/packages/utils/src/index.ts
@@ -6,9 +6,9 @@ export * from "./accounting";
export * from "./accounting-currency";
export * from "./accounting-posting";
export * from "./address";
-export * from "./all";
export * from "./arrays";
export * from "./assembly-units";
+export * from "./async";
export * from "./balloons";
export * from "./bank";
export * from "./batch-compatibility";