Naalya Handbook

Architecture

The monorepo's apps, the shared library, and the exact path a request takes through the server.

The Naalya backend is a NestJS monorepo: several apps in one repository, sharing one set of dependencies and one pile of common code. The split exists because not all work is request work: answering HTTP should be fast, while email, audit writes, and external syncs are slow and retryable, so they run in separate processes.

Four things to hold in your head:

  • server: the HTTP API that answers the Hub and the website.
  • worker and audit: background processes. They do not call listen.
  • ehr: a second HTTP API for the clinic, with its own database.
  • libs/shared (imported as @app/shared): code the apps reuse.

This map shows who talks to whom, from the people at the top to the background apps at the bottom. The clinic API (ehr) is left out: it only talks to its own database.

Naalya API map: website and Hub call the server, which uses Postgres, Redis, RabbitMQ, and Centrifugo; the worker and audit apps run jobs.

Default project is server

Projects are declared in nest-cli.json; the default is server, so pnpm start:dev with no arguments runs the API. The worker and audit apps have their own scripts. If a command "does nothing," check which project it targeted.

Repo layout

nest-cli.json (layout)
apps/
  server/   → the schools HTTP API
  worker/   → background job processor
  audit/    → audit-log microservice
  ehr/      → clinic HTTP API
libs/
  shared/   → code shared across the apps (@app/shared)
database/
  migrations/       → Hub TypeORM migrations
  ehr-migrations/   → clinic TypeORM migrations
emails/             → React Email templates

Each app is self-contained, with its own main.ts and root module. Apps never import each other: the only shared code comes through @app/shared.

What the apps talk to

The stores below, plus Gotenberg for PDF. In development, Redis, Centrifugo, and Gotenberg are what task infra starts. Hub Postgres and RabbitMQ are not in that command. See Getting Started.

ServiceRoleReached through
Postgres (Hub)School domain rows. DATABASE_URL. Not a container in either compose file.TypeORM, DatabaseModule.forRoot, synchronize: false
Postgres (clinic)Clinic rows. EHR_DATABASE_URL. Local container ehr-postgres only when you start the EHR infra.The clinic app's own TypeORM config
RabbitMQNest microservice transport (QUEUES.WORKER, QUEUES.AGENT, QUEUES.AUDIT, QUEUES.AGENT_TOOL). RABBIT_MQ_URL. Not in compose.Nest microservice clients
RedisBullMQ, cache, the instance list, collaborative documents, Pip run ownership, and the shared rate-limit windows. REDIS_URL, CACHE_REDIS_URL. The server, worker, and audit apps each construct RedisService.BullMQ in AppModule, and Several copies
CentrifugoWebsocket broker for realtime.RealtimeService, CENTRIFUGO_URL
GotenbergHTML to PDF. GOTENBERG_URL defaults to http://localhost:3010.The worker PDF path

There is also a type bus: the server publishes shared TypeScript types at /.well-known/chowbea.json, which the Education Hub generates from. Types that never appear on a REST body, websocket payloads, domain enums, cross there instead of through Swagger. See How Chowbea works.

The apps

AppBoot fileListens onHosts
serverapps/server/src/main.ts bootstrapconfigService.get('port') ?? 8000, prefix api/v1Domain modules under apps/server/src/app, plus CollabService.attach
workerapps/worker/src/main.tsNo HTTP listen. Consumes QUEUES.WORKER and QUEUES.AGENTJobs, and the Rover agent graph
auditapps/audit/src/main.tsNo HTTP listen. Consumes QUEUES.AUDITAudit-log consumer
ehrapps/ehr/src/main.tsEHR_PORT default 8100, prefix api/v1Clinic HTTP API

server: Express 5 HTTP server. Its root module apps/server/src/app/app.module.ts wires the database, the Redis/BullMQ connection, and one feature module per domain. You add a feature module and register it here. Every route sits under api/v1 (so a users route is /api/v1/users). The exception is /queues*, excluded so Bull Board stays at /queues. Controller prefixes are listed on HTTP surface.

worker does not serve HTTP. Alongside its processors it hosts the Rover agent graph, which reaches school data by calling back into the server over RabbitMQ rather than opening its own database connection for that path. That seam is described in How the AI system works. The queue name constant is QUEUES.WORKER. This page does not guess the broker's string name. The chat, small-talk, slide-reader, and illustration clients in that graph call OpenAI with OPENAI_API_KEY. That was read at main 6bfb9f6b and re-read on the default branch staging ed0e56f8. A search of that tree finds no OPENROUTER_API_KEY. Deployment was not verified. The keys are on Config and environment. The system map above does not draw that hop.

audit consumes QUEUES.AUDIT and does not call listen.

ehr is a separate Nest application with ehrEnvSchema. Do not point it at DATABASE_URL. Its dev Postgres container is ehr-postgres.

BullMQ is Redis. RabbitMQ is the Nest microservice transport. Earlier revisions of this page treated them as one queue. They are not.

libs/shared

@app/shared is exposed through one barrel file (libs/shared/src/index.ts). Import from the package name, never a deep path:

users.service.ts (shape)
import { BaseRepository, UserType, generateSlug } from '@app/shared';
GroupWhat you'll find
DatabaseDatabaseEntity, BaseRepository, DatabaseModule, cursor-pagination helpers
Configconfig, validateConfig, env types
API helpersMessageResponseDto, ErrorResponseDto, Swagger error decorators
EnumsUserType, ApplicationStatus, ScopeLevel, DepartmentRole, ...
Queue contractsqueue names, job-payload types, microservice tokens

Permissions live on a subpath

The CASL Action / Resource enums and PermissionScopeModule come from @app/shared/permission, not the top-level barrel. An Action import that "can't be found" is usually pointed at @app/shared.

Path aliases

Defined in tsconfig.json (and mirrored in the Vitest configs). Use them before reaching for a relative ../ chain.

tsconfig.json
"paths": {
  "@app/shared": ["libs/shared/src"],
  "@app/shared/*": ["libs/shared/src/*"],
  "@server/*": ["apps/server/src/*"],
  "@worker/*": ["apps/worker/src/*"]
}

Rule of thumb: @app/shared for anything reused across apps, @server/* for paths inside the server app.

Request lifecycle

A request to the server app passes through a fixed assembly line before reaching your handler. Order is set in main.ts (middleware, pipe), app.module.ts and audit-log.module.ts (filter, interceptor) and auth.module.ts (guards).

StageJob
MiddlewarePlain Express, runs before Nest. tenantContextMiddleware resolves the active school into AsyncLocalStorage so BaseRepository auto-scopes by schoolId: see Multi-tenancy.
GuardsFive APP_GUARDs: logged in → user type → system role → CASL permission → feature flag. Short-circuit on first failure. Details → Auth & Permissions.
ValidationPipeRuns the controller DTO's class-validator rules; bad input becomes a clean 400, never a crash.
HandlerYour controller method. The only stage you usually write.
AuditInterceptorThe only global interceptor: writes an audit row for handlers marked @Audit. See Auditing.
Request logpino-http writes one line per request when it finishes, with the request ID and any error. See Error handling and logging.
Exception filterAllExceptionsFilter formats throws into the standard error shape and records 5xx errors on the OpenTelemetry trace. Runs only on failure.

Guard order is load-bearing

Authentication (JwtAuthGuard) runs before authorization (PermissionsGuard) and the chain stops on the first false. Don't assume a later guard ran.

Where to go next

On this page