Open MercatoDocsSearch docsAPI reference

Framework

Request lifecycle

For an unexpected response, follow one request from route selection through authentication, scope resolution and service dispatch. The request context is where a handler obtains the identity and organization that should govern its reads and writes.

Understanding the request lifecycle helps when debugging complex modules. Every HTTP request – page or API – follows the same high-level flow:

  1. Routing – Next.js dispatches the request to a generated route handler. For APIs this lives in src/app/api/[...slug]/route.ts. The handler locates the module definition (method + path) and loads its module file. Runtime event emitted: application.request.received.
  2. Container scope – A new Awilix scope is created by createRequestContainer. Core services (logger, repositories, RBAC, query engine, data engine) are registered, then module registrars extend the container.
  3. Auth context – The framework resolves session/tenant data, attaches it to the request context, and enforces requireAuth/requireFeatures metadata declared by the route or page. Runtime events emitted: application.request.auth_resolved, application.request.authorization_denied (when blocked).
  4. Rate limiting – If route metadata declares a rate limiter, request limits are evaluated before handler execution. Runtime event emitted on block: application.request.rate_limited.
  5. Business logic – Handler code (often the CRUD factory) executes, relying on injected services. Writes go through MikroORM repositories or the data engine; reads use the query engine for projection and filtering.
  6. Events – If the handler calls eventBus.emitEvent, subscribers are resolved lazily and executed. Persistent subscribers are queued when offline and retried later.
  7. Response & telemetry – The handler returns JSON/NextResponse. Middleware logs timing and errors with correlation identifiers for tracing across services. Runtime events emitted: application.request.not_found, application.request.completed, application.request.failed.

The same lifecycle powers server actions and background jobs; in each case we create a scope, load module registrars, and execute the requested operation in a tenant-aware context.

Optional process DI root

Development branch. The opt-in process container and its helpers below were added after v0.10.0. On v0.10.0 the request creates its own scope through createRequestContainer().

Set OM_PROCESS_CONTAINER_ROOT=on to initialize audited module registrations once per process generation. The default is off. Node startup initializes the root after the generated bootstrap; CLI and worker callers initialize it lazily. Each createRequestContainer() still returns an independent caller scope with its own EntityManager, command bus, encryption and query services. Do not use this option to share a unit of work between separate callers.

An unmarked module or app registrar, module DI overrides, a module/app-provided custom event bus, or disabled process infrastructure sharing selects the complete legacy builder. getProcessContainerStats() from @open-mercato/shared/lib/di/container reports the fallback reason and separate root, registrar and caller counts. Registry changes retire the current generation and direct new callers to a replacement. Existing callers and nested scopes retain their generation until they are disposed; the retired root then disposes its generation-owned singletons exactly once. The app and standalone API dispatcher own scopes acquired during authorization and handler execution until the response body closes, errors or is cancelled. For HEAD requests, the dispatcher starts cancellation of the ownership-wrapped response body and immediately returns the same status and headers without a body. The wrapper retains scopes until cancellation settles, including when a tee sibling keeps cancellation pending; cleanup does not depend on the transport consuming the suppressed body. Cancellation failures are observed without delaying or replacing the HEAD response. App-shell lookup and authorization boundaries own their scopes until that work finishes; returned React children do not inherit those resources. Other scope owners must dispose every caller and nested scope in a finally block, including background work. Abandoning an unowned scope without disposal does not release its ownership; garbage collection is not a deterministic resource-cleanup mechanism.

Module authors opt in only after auditing every registration:

import { defineProcessDiRegistrar, asScopedService } from '@open-mercato/shared/lib/di/process-registrar'
import type { AppContainer } from '@open-mercato/shared/lib/di/container'

export const register = defineProcessDiRegistrar((root: AppContainer) => {
  root.register({
    myService: asScopedService((caller) => createMyService(caller)),
  })
})

A process registrar must not eagerly resolve request services or capture the root in a request-service factory. Use scoped factories for mutable/request state. Reserve singleton registrations and values for audited process resources or immutable definitions. Existing register(container) exports remain supported without opting in. When moving immediate setup into process-only hooks, use defineProcessDiRegistrar(processRegister, { legacy: legacyRegister }) so the disabled/fallback path retains its original setup.

registerCallerSetup(root, setup) supports per-caller setup such as an EntityManager subscriber. registerProcessEventSetup(root, setup) installs generation-owned event listeners after both module and app registration finish and custom-bus fallback is decided. A failed caller setup disposes that caller's resources and rejects with the original setup error; it does not discard the healthy process root. registerProcessActivation(root, activate, validate?) publishes synchronous process callbacks only after successful initialization. All supplied validators run before any callback is published; activation must not perform fallible asynchronous work. Background reconciliation may be scheduled at activation, but it must acquire its own caller scope, report failures, and dispose that scope after completion; caller setup must not await queue reconciliation. A custom event bus selects the legacy builder so its existing subscriber registration order is preserved.

runInOwnedRequestScope(operation) from @open-mercato/shared/lib/di/request-scope gives an execution boundary ownership of its acquired caller and nested scopes without sharing their EntityManagers. Ordinary results and failures trigger cleanup; a returned Response transfers cleanup to its body lifetime. Cleanup waits for in-flight acquisitions and reports failures without replacing the operation outcome. Pinning an event context with runWithRequestScopeContainer preserves that ownership. Independent background work must enter runInRequestScope and explicitly dispose its own callers, or use a separate owned boundary; it must not borrow a completed request’s scope.

The CLI per-job worker handler owns caller, helper and nested scopes until all handlers finish or one throws. It clears the primary EntityManager before disposing the owned scopes. Handler return values do not extend the job lifetime; independent background work still needs a separate owner.

A bus resolved from a caller stays bound to that caller. For code using module-level event helpers, wrap the operation in runWithRequestScopeContainer(caller, operation) from @open-mercato/shared/lib/di/request-scope to pin its context, including across nested helper-created containers. Independent background tasks need their own scopes. Scope lifetime follows the operation, including streaming and deferred work; returning a response does not automatically dispose it.

Correlating an Unexpected 500

When an unexpected exception escapes a CRUD factory handler, the client still receives a generic 500 that leaks no internal detail – but it now carries a requestId so a support ticket has something citable, and a stable code so a caller can bucket the failure without server log access:

{
  "error": "Internal server error",
  "message": "Something went wrong. Please try again later.",
  "requestId": "0f9c2b0e-7c4a-4f4b-9a1e-6d2f8f0a1b23",
  "code": "INTERNAL_ERROR"
}

code is derived only from signals the factory already trusts enough to pick a status code from – never from the raw error message, stack, or a pg constraint/table/column name:

CodeWhen
DATABASE_ERRORA Postgres SQLSTATE is present but was not already classified as transient (503) or a foreign-key violation (409).
PERSISTENCE_ERRORA MikroORM ValidationError/NotFoundError that no more specific branch handled.
INTERNAL_ERROREverything else (default).

The 503 transient-database response carries the same requestId/x-request-id correlation contract as the generic 500, plus its own fixed code: 'DATABASE_UNAVAILABLE':

{
  "error": "Service temporarily unavailable",
  "code": "DATABASE_UNAVAILABLE",
  "requestId": "0f9c2b0e-7c4a-4f4b-9a1e-6d2f8f0a1b23"
}

The same id is echoed on an x-request-id response header, added to the Unexpected CRUD error server log line, and forwarded to the APM error funnel as attributes.requestId and attributes.code (plus attributes.pgCode, the raw SQLSTATE, when the error is a Postgres error). Grep the logs for that value to reach the full message/stack detail behind the flattened response.

Callers may supply their own id with an inbound x-request-id request header, so a correlation id already assigned upstream (by a gateway or a client SDK) survives into the logs. Because the header is caller-controlled and lands in a log line, it is honored only when it matches ^[A-Za-z0-9._-]{1,128}$; an empty, whitespace-only, over-long, or otherwise malformed value is discarded and a fresh UUID is generated instead.

This applies to the generic-500 and 503 transient-database branches only. The 400 validation, CrudHttpError, and command-interceptor-rejection responses are unchanged and carry no requestId/code.

The error and message texts shown above are the English defaults; they follow the request locale like any other translated response, so match on the status and, where present, code, never on the text.

Bootstrap Lifecycle Events

App startup exposes bootstrap lifecycle hooks that can be consumed by modules without coupling to core internals:

Use a request that reproduces the symptom

Keep the identity, active organization and route constant while comparing logs. A successful request from a super administrator and a failed one from a branch user may follow different authorization paths even when the URL is identical.

Previous: Structured Logging · Next: OTLP Telemetry Deployment