# Server Bootstrap and Middleware Pipeline

# Server Bootstrap and Middleware Pipeline

<details>
<summary>Relevant source files</summary>

The following files were used as context for generating this wiki page:

- [src/domain/entities/registry.ts](src/domain/entities/registry.ts)
- [src/http/api-errors.ts](src/http/api-errors.ts)
- [src/http/async-handler.ts](src/http/async-handler.ts)
- [src/http/error-handler.ts](src/http/error-handler.ts)
- [src/http/protected-router.ts](src/http/protected-router.ts)
- [src/http/validation.ts](src/http/validation.ts)
- [src/index.ts](src/index.ts)
- [src/lib/bulk/bulk-action-runner.ts](src/lib/bulk/bulk-action-runner.ts)

</details>



The Primebrick v3 backend is built on **Express.js** and follows a structured initialization sequence designed for high availability and security. The bootstrap process ensures that the database connection pool is ready, identity provider (IDP) configurations are loaded, and a secure-first middleware pipeline is established before the server starts accepting traffic.

## Initialization Sequence

The entry point of the application is `src/index.ts`. The bootstrap process follows a strict order to ensure dependencies are resolved before the HTTP server binds to a port.

### Bootstrap Workflow
1.  **Middleware Setup**: Global middleware (CORS, JSON parsing, Cookie parsing) is registered [src/index.ts:27-29]().
2.  **Public Health Check**: The `/api/v1/health` endpoint is mounted early to allow infrastructure probes even if other components are still initializing [src/index.ts:154-156]().
3.  **OpenAPI Documentation**: The OpenAPI router is mounted before any authentication guards to ensure the documentation remains accessible for client integration [src/index.ts:161]().
4.  **Protected Router Creation**: A `makeProtectedRouter` is instantiated to enforce a "secure-first" policy for domain modules [src/index.ts:164]().
5.  **Module Mounting**: Domain-specific routers (Customers, Organizations, Auth) are mounted to the Express application [src/index.ts:175-179]().
6.  **Global Error Handling**: The centralized `errorHandler` is attached as the final middleware in the stack [src/index.ts:181]().
7.  **Data Pre-loading**: Role mappings are fetched from the database and cached in memory [src/index.ts:184]().
8.  **Server Start**: The application begins listening on the configured `PORT` [src/index.ts:186-188]().

### Component Relationship Diagram
This diagram maps the high-level bootstrap concepts to the specific code entities responsible for them.

Title: Server Bootstrap Component Mapping
```mermaid
graph TD
    subgraph "Initialization Space"
        "Entrypoint"["src/index.ts"]
        "DB_Pool"["src/db/pool.ts:getPool()"]
        "Role_Loader"["src/modules/auth/auth.middleware.ts:loadRoleMappings()"]
    end

    subgraph "Middleware Pipeline"
        "CORS"["cors()"]
        "JSON"["express.json()"]
        "Cookies"["cookieParser()"]
        "Auth_Guard"["src/http/protected-router.ts:makeProtectedRouter()"]
        "Error_Handler"["src/http/error-handler.ts:errorHandler"]
    end

    subgraph "Routing Space"
        "Health"["/api/v1/health"]
        "OpenAPI"["src/openapi/router.ts:openApiRouter()"]
        "CRM"["src/modules/customers/router.js:customersRouter()"]
    end

    "Entrypoint" --> "DB_Pool"
    "Entrypoint" --> "CORS"
    "CORS" --> "JSON"
    "JSON" --> "Cookies"
    "Cookies" --> "Health"
    "Health" --> "OpenAPI"
    "OpenAPI" --> "Auth_Guard"
    "Auth_Guard" --> "CRM"
    "CRM" --> "Error_Handler"
    "Entrypoint" --> "Role_Loader"
```
**Sources:** [src/index.ts:1-189](), [src/http/protected-router.ts:87-106]()

---

## Middleware Stack

The middleware pipeline is divided into global utilities and domain-specific guards.

| Middleware | Source | Purpose |
| :--- | :--- | :--- |
| `cors` | [src/index.ts:27]() | Enables Cross-Origin Resource Sharing (currently set to `origin: true`). |
| `express.json` | [src/index.ts:28]() | Parses incoming requests with JSON payloads. |
| `cookieParser` | [src/index.ts:29]() | Parses Cookie headers and populates `req.cookies`. |
| `rbacHandler` | [src/modules/auth/rbac.middleware.js:15]() | Validates user permissions against the required `Permission` enum. |
| `errorHandler` | [src/http/error-handler.ts:4]() | Catches all upstream errors and formats them into RFC 7807 responses. |

### Secure-First Routing
The `makeProtectedRouter` factory [src/http/protected-router.ts:87]() wraps the standard Express Router. It enforces that every route registered using HTTP verbs (`get`, `post`, etc.) must include an `rbacHandler`. If a developer forgets to declare a permission, the router automatically injects a `defaultDenyHandler` [src/http/protected-router.ts:38](), which returns a `403 Forbidden` with the internal code `ROUTE_PERMISSION_NOT_DECLARED`.

**Sources:** [src/index.ts:27-29](), [src/http/protected-router.ts:1-107]()

---

## Health Check and Diagnostics

The `/api/v1/health` endpoint provides a comprehensive status of the system's vital signs. It returns a `200 OK` only if both the database and the Identity Provider (Casdoor) are reachable [src/index.ts:149-150]().

### Health Check Logic
- **Database**: Executes a cheap `SELECT 1` query using the `getPool()` instance [src/index.ts:54-64]().
- **IDP (Casdoor)**: Attempts to fetch version information from the Casdoor API. It first tries to load configuration from the `auth_config` table in the database before falling back to environment variables [src/index.ts:66-132]().

Title: Health Check Data Flow
```mermaid
sequenceDiagram
    participant LB as Load Balancer
    participant API as src/index.ts:sendHealth
    participant DB as src/db/pool.ts
    participant IDP as Casdoor API

    LB->>API: GET /api/v1/health
    activate API
    API->>DB: pool.query("select 1")
    DB-->>API: { ok: true }
    API->>IDP: GET /api/get-version-info
    IDP-->>API: { version: "1.x" }
    API-->>LB: 200 OK { db: {ok: true}, idp: {ok: true} }
    deactivate API
```
**Sources:** [src/index.ts:54-156]()

---

## Centralized Error Handling

The system uses a centralized `errorHandler` [src/http/error-handler.ts:4]() to ensure all API responses follow the **RFC 7807 (Problem Details for HTTP APIs)** specification.

### Error Classification
The handler distinguishes between several types of failures:

1.  **ApiError**: Custom errors (like `NotFoundError` or `ForbiddenError`) that already contain RFC 7807 metadata [src/http/api-errors.ts:32]().
2.  **Database Unavailable**: Detected via `isDatabaseUnavailableError` [src/http/api-errors.ts:197](). It maps Postgres codes (e.g., `57P01`, `57P03`) or network codes (e.g., `ECONNREFUSED`) to a `503 Service Unavailable` response [src/http/error-handler.ts:24-36]().
3.  **Validation Errors**: Produced by `validateBody` or `validateQuery` [src/http/validation.ts:23-45](). These use Zod schemas to validate input and return a `400 Bad Request` with a detailed `issues` array [src/http/validation.ts:4-21]().
4.  **Internal Server Error**: Any unhandled exception is caught and returned as a `500 Internal Server Error` with a `HIGH` severity rating [src/http/error-handler.ts:38-46]().

### RFC 7807 Response Structure
All errors returned to the client follow this schema:
- `type`: A URI identifier for the error type.
- `title`: A short, human-readable summary.
- `status`: The HTTP status code.
- `detail`: A specific explanation of this occurrence.
- `instance`: The URI of the specific endpoint that failed.
- `internal_code`: A stable string for programmatic handling (e.g., `VALIDATION_ERROR`).

**Sources:** [src/http/error-handler.ts:4-47](), [src/http/api-errors.ts:1-224](), [src/http/validation.ts:1-45]()

---
