diff --git a/README.md b/README.md index f0e7d79..943e2dc 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Bliq -Remote fleet control — a small service and two web dashboards that let a pool +Remote fleet control: a small service and two web dashboards that let a pool of remote operators sign in, pick a vehicle from the fleet, and operate it, with hard guarantees that no two operators ever hold the same vehicle at the same time. @@ -11,7 +11,7 @@ same time. sign in, take over vehicles, release them. Live via WebSocket by default, falls back to HTTP polling automatically. - **Admin dashboard** (`apps/admin-dashboard`): React + Vite. Add vehicles, - toggle connectivity, delete. Polling only — kept intentionally simple. + toggle connectivity, delete. Polling only, kept intentionally simple. ## Table of contents @@ -35,39 +35,42 @@ same time. ## Quick start -Prerequisites: **Node 22**, **Docker** with Compose v2 (for MongoDB). +**Prerequisites: [Docker](https://docs.docker.com/get-started/get-docker/) with Compose v2 and [Node 22](https://nodejs.org/).** ```bash # Once, on a fresh clone: -npm run install:all +npm run full:install # Every time you want to work: -npm run dev +npm run full:dev ``` -`npm run dev` starts the whole stack in one shot: +`full:install` installs the frontend dependencies (the backend runs in Docker; no local install needed). -1. `docker compose up -d --wait` boots MongoDB as a single-node replica set - and blocks until the healthcheck reports healthy (transactions require a - replica set — the compose healthcheck also runs `rs.initiate()` on first - start, so no manual step is needed). -2. `concurrently` launches three dev servers side by side: - - **backend** on `http://localhost:3000` - - **operator dashboard** on `http://localhost:5173` - - **admin dashboard** on `http://localhost:5174` +`full:dev` starts the whole stack: -Ctrl+C stops all three. Mongo keeps running — use `npm run docker:down` to -shut it down, or `npm run docker:reset` to wipe the volume and restart fresh -(re-seeds operators on the next boot). +1. Builds the backend Docker image and starts the full stack: + - 2 NestJS replicas behind **Nginx** on `http://localhost:8090` + - **MongoDB** replica set + - **Nginx** load balancer (reverse proxy) + - **Prometheus** · **Loki** · **Promtail** · **Grafana** observability stack +3. Launches both frontends as Vite dev servers pointed at the Nginx backend. -Once running: +Once everything is up: -- Open the **operator dashboard** at `:5173`, pick a seeded operator, and use - the fleet. It defaults to WebSocket mode with a live event log. -- Open the **admin dashboard** at `:5174` to add vehicles and toggle their - connectivity. -- Open the **Swagger UI** at `:3000/docs` for the full API reference with - live examples (dev-only — disabled when `NODE_ENV=production`). +| Service | URL | Description | +|---------|-----|-------------| +| **Operator dashboard** | http://localhost:5173 | For remote operators. Select your operator identity, browse the live vehicle list, take over an available vehicle, and release it when done. Updates arrive in real time via WebSocket (falls back to polling if the socket drops). | +| **Admin dashboard** | http://localhost:5174 | For fleet administrators. Add new vehicles, toggle any vehicle between online and offline, and delete vehicles that are no longer in service. | +| **Grafana** | http://localhost:3001 | Observability UI: HTTP latency histograms, request rates, and container logs. | +| **Prometheus** | http://localhost:9090 | Raw metrics scrape endpoint and query UI. | +| **Backend API** | http://localhost:8090 | REST + WebSocket, load-balanced across 2 replicas by Nginx. Swagger docs at [/docs](http://localhost:8090/docs). | + +![Operator dashboard](static/images/operator-dashboard.png) + +![Swagger UI](static/images/swagger.png) + +**To stop:** `Ctrl+C` kills the frontends; then `npm run full:down` tears down the Docker stack. --- @@ -85,9 +88,9 @@ Once running: These three invariants must be unbreakable under any concurrent load: -- **I1** — A vehicle is assigned to **at most one** operator at any point in time. -- **I2** — An operator holds **at most one** vehicle at any point in time. -- **I3** — A vehicle **cannot go offline** while it is assigned; the operator must release it first. +- **I1**: A vehicle is assigned to **at most one** operator at any point in time. +- **I2**: An operator holds **at most one** vehicle at any point in time. +- **I3**: A vehicle **cannot go offline** while it is assigned; the operator must release it first. Business rules encode preconditions that protect these invariants: @@ -107,7 +110,7 @@ and [Concurrency & consistency](#concurrency--consistency). | Dimension | Target | Implementation | |-----------|--------|----------------| -| **CAP** | Consistency **>>** Availability | Reads from primary only; MongoDB transactions with `majority` write concern. If all replicas are down the service returns an error — it never serves stale takeover state. | +| **CAP** | Consistency **>>** Availability | Reads from primary only; MongoDB transactions with `majority` write concern. If all replicas are down the service returns an error; it never serves stale takeover state. | | **Real-time / latency** | Sub-second vehicle state propagation to connected clients | MongoDB change streams → `EventEmitter2` → socket.io broadcast. p95 UI update < 1 s for up to a few hundred connected clients. | | **Extensibility** | SOLID, independently replaceable components | Clean architecture (see [service architecture section](#fleet-management-service-architecture)). | | **API contract** | Explicitly typed request / response shapes | Swagger UI at `/docs` (dev), class-validator DTOs, stable typed error codes. | @@ -116,92 +119,35 @@ and [Concurrency & consistency](#concurrency--consistency). --- -## Repository layout - -``` -bliq/ -├── apps/ -│ ├── backend/ NestJS API + WebSocket gateway -│ ├── operator-dashboard/ Vite + React, operator UI -│ └── admin-dashboard/ Vite + React, admin UI -├── static/ -│ └── images/ Architecture diagrams referenced in this README -├── docker-compose.yml Mongo replica set with self-initiating healthcheck -├── package.json Root scripts + dev tooling (husky, lint-staged, commitlint) -├── .github/ CI workflow, PR template, CODEOWNERS, branch protection recipe -├── .husky/ pre-commit (prettier), commit-msg (commitlint) -└── README.md -``` - -### Backend layers - -``` -apps/backend/src/ -├── domain/ Entities, rule predicates, repository & service abstracts, -│ typed DomainError hierarchy. Pure TypeScript, no framework. -├── data-access/ Mongoose schemas, mappers, repository implementations, -│ change-stream watcher. -├── services/ Cross-aggregate implementations that need infra -│ (currently: MongoFleetAssignmentService with transactions). -├── apis/ Controllers, DTOs, feature modules, WebSocket gateway, -│ exception filter, interceptor, metrics providers. -└── main.ts Global pipes, filter, interceptor, Swagger (dev-only), CORS. -``` - -Dependency direction is inward-only: `apis → services → domain ← data-access`. -`domain` imports from nothing. `data-access` and `services` import from -`domain` (for entities, rules, contracts). `apis` imports from all three. - ---- - ## System architecture -### Version 1 — monolith +### Version 1: monolith ![System architecture v1](static/images/system-archi-v1.png) **Components:** - One **NestJS** monolith handling all HTTP and WebSocket traffic. -- One **MongoDB** instance (single-node replica set — required for transactions +- One **MongoDB** instance (single-node replica set; required for transactions even in dev; see compose setup). -**Why MongoDB?** - -MongoDB's document model is a natural fit here because the vehicle and operator -relationship is deliberately denormalised: `vehicle.assignedOperatorId` and -`operator.currentVehicleId` mirror each other in two documents. This means: - -- "Who is driving vehicle X?" is answered by reading one document — no join. -- "What vehicle is operator Y holding?" is answered by reading one document — - no join. -- The fleet dashboard gets the full current state in a single collection scan. - -The trade-off is maintaining that denormalisation, which is exactly the -concurrency problem solved by transactions (see -[Concurrency & consistency](#concurrency--consistency)). - -MongoDB's change streams provide the real-time propagation layer without a -separate message broker — the backend subscribes to its own write log and fans -out to WebSocket clients. - **Limits of v1:** -- **Single point of failure** — one backend, one Mongo instance. Any crash +- **Single point of failure**: one backend, one Mongo instance. Any crash takes down the entire service. -- **No zero-downtime deploys** — a restart disconnects all WebSocket clients +- **No zero-downtime deploys**: a restart disconnects all WebSocket clients and interrupts any in-flight request. -- **No horizontal scaling** — the WebSocket state is in memory; a second +- **No horizontal scaling**: the WebSocket state is in memory; a second backend instance would not share it. -- **No A/B testing or canary deploys** — impossible without a load balancer +- **No A/B testing or canary deploys**: impossible without a load balancer in front. --- -### Version 2 — replicated +### Version 2: replicated ![System architecture v2](static/images/system-archi-v2.png) **Changes over v1:** -- **MongoDB replica set (3 nodes)** with `majority` write concern — a write is +- **MongoDB replica set (3 nodes)** with `majority` write concern; a write is only acknowledged after at least 2 of 3 nodes have persisted it. The primary can crash and a secondary promotes automatically without data loss. - **3 NestJS instances** behind a load balancer. Each instance runs its own @@ -210,14 +156,17 @@ out to WebSocket clients. - **Nginx** as a reverse proxy and load balancer: TLS termination, sticky sessions for WebSocket connections (or use the Redis adapter to make sessions stateless), and health-check-based failover. +- **Observability stack** with centralized logging: metrics, distributed traces, and application logs + provide end-to-end visibility into request flows, service health, and + performance across the cluster. **Limits of v2:** -- **Load balancer is still a single point of failure** — mitigated with an +- **Load balancer is still a single point of failure**: mitigated with an active-passive Nginx pair or a cloud load balancer (ALB, GCP LB). -- **No database sharding** — once the vehicles collection grows into the +- **No database sharding**: once the vehicles collection grows into the millions, a sharded cluster becomes necessary. At fleet management scale this is unlikely to be the first bottleneck. -- **Change stream duplication** — 3 NestJS instances each run their own stream +- **Change stream duplication**: 3 NestJS instances each run their own stream and each broadcast to their clients. This is fine with a Redis adapter but could be restructured into a dedicated broadcaster tier. @@ -233,81 +182,44 @@ The service is structured around clean architecture: outer layers depend on inner layers, never the reverse. ``` -┌──────────────────────────────────────┐ -│ apis/ (HTTP, WebSocket, DTOs)│ ← outermost, depends on everything -├──────────────────────────────────────┤ -│ services/ (cross-aggregate logic)│ -├──────────────────────────────────────┤ -│ data-access/ (Mongo, schemas) │ ← depends on domain only -├──────────────────────────────────────┤ -│ domain/ (entities, rules, ports│ ← innermost, depends on nothing -└──────────────────────────────────────┘ +apps/backend/src/ +├── domain/ Entities, rule predicates, repository & service abstracts, +│ typed DomainError hierarchy. Pure TypeScript, no framework. +│ +├── data-access/ Mongoose schemas, mappers, repository implementations, +│ change-stream watcher. +│ +├── services/ Cross-aggregate implementations that need infra +│ (currently: MongoFleetAssignmentService with transactions). +│ +├── apis/ Controllers, DTOs, feature modules, WebSocket gateway, + exception filter, interceptor, metrics providers. ``` -Benefits: -- **Swappable infrastructure** — replacing MongoDB with PostgreSQL only touches - `data-access/`. The domain, services, and API layers are unaffected. -- **Business rules in one place** — `domain/*/rules.ts` holds pure functions - that are reused by the service layer, the exception filter, and tests. -- **Team isolation** — teams owning different layers can evolve them - independently without stepping on each other. -- **Independent testability** — domain rules are tested with no framework, - no DB, no mocks. - -**Where clean architecture is intentionally broken:** -`MongoFleetAssignmentService` lives in the `services/` layer but depends -directly on `mongoose.ClientSession` (a data-access detail) to open -transactions. This is an intentional boundary crossing: enforcing strong -consistency and low-latency concurrent writes requires coupling to the -database transaction primitive. Hiding it behind an additional abstraction -would only add indirection with no payoff. - -### SOLID principles applied - -**Single Responsibility** — each class has one reason to change. The -`VehicleRepository` fetches documents; the `VehicleMapper` converts between -Mongoose documents and domain entities; the `FleetAssignmentService` enforces -business rules; the `VehiclesController` handles HTTP concerns. - -**Open/Closed** — adding a new domain error means adding a new class in -`domain/errors/` and a new entry in the `kind → HTTP status` table in the -exception filter. No existing class is modified. - -**Interface Segregation** — `IVehicleRepository` exposes only the methods the -service layer needs. The concrete Mongoose implementation satisfies the -interface; consumers depend on the interface, never the implementation. - -**Dependency Inversion** — the most heavily used principle. The service layer -declares what it needs (`IVehicleRepository`, `IOperatorRepository`, -`IFleetAssignmentService`) as abstract contracts. NestJS's IoC container -resolves the concrete implementations at startup. Nothing in `services/` or -`domain/` imports from `data-access/` or `apis/` — direction is enforced by -the import graph. - -NestJS's `@Injectable()` and module providers handle the dependency injection -plumbing. Swapping in a test double is done at the module level, not by -patching imports. +Replacing MongoDB with PostgreSQL only touches `data-access/`. Business rules in `domain/*/rules.ts` are pure functions with no framework dependency, reused by the service layer and tests. Swapping in a test double is done at the module level, not by patching imports. + +`MongoFleetAssignmentService` intentionally reaches into `mongoose.ClientSession`; enforcing strong consistency requires coupling to the transaction primitive, and hiding it behind another abstraction would just add indirection. ### Vehicle & operator entities -- **Vehicle** — `{ id, name, connectivityStatus: 'online' | 'offline', assignedOperatorId: string | null }`. -- **Operator** — `{ id, name, currentVehicleId: string | null }`. +- **Vehicle**: `{ id, name, connectivityStatus: 'online' | 'offline', assignedOperatorId: string | null }`. +- **Operator**: `{ id, name, currentVehicleId: string | null }`. `assignedOperatorId` on the vehicle and `currentVehicleId` on the operator are -deliberately denormalised — the same relationship expressed twice. This makes +deliberately denormalised, the same relationship expressed twice. This makes the "at most one vehicle per operator" invariant enforceable with a single guarded write on the operator document, and lets both the UI and the API answer "who is driving what" in one document read. ### Domain rules -Business rules live as pure functions in `domain/*/rules.ts` — one source of +Business rules live as pure functions in `domain/*/rules.ts`, one source of truth, reusable from the service layer, the exception filter, and tests: -- `canBeAssigned(vehicle)` — vehicle is online AND unassigned -- `canGoOffline(vehicle)` — vehicle is unassigned -- `canClaimVehicle(operator)` — operator holds no vehicle -- `isHolding(operator, vehicleId)` — operator currently holds this vehicle +- `canBeAssigned(vehicle)`: vehicle is online AND unassigned +- `canGoOffline(vehicle)`: vehicle is unassigned +- `canClaimVehicle(operator)`: operator holds no vehicle +- `isHolding(operator, vehicleId)`: operator currently holds this vehicle ### Domain errors → HTTP @@ -320,7 +232,7 @@ Domain-level errors are typed and carry two stable fields: A global `DomainExceptionFilter` maps `kind` to HTTP status via a small closed table and returns `{ statusCode, code, message }`. Adding a new domain error -never touches the filter — the mapping is by category, not per-code. The +never touches the filter; the mapping is by category, not per-code. The filter guards on `host.getType()` so a future non-HTTP transport (WebSocket handlers, RPC) doesn't get an accidental HTTP response applied to it. @@ -341,8 +253,8 @@ Three invariants have to hold under any sequence of concurrent requests: A naïve implementation might: -1. Read the vehicle document — check it is online and unassigned. -2. Read the operator document — check they hold no vehicle. +1. Read the vehicle document, check it is online and unassigned. +2. Read the operator document, check they hold no vehicle. 3. Write the vehicle: set `assignedOperatorId`. 4. Write the operator: set `currentVehicleId`. @@ -361,13 +273,13 @@ Time Request A (Op1 → V1) Request B (Op2 → V1) ### How consistency is enforced -**Takeover / release — MongoDB multi-document transaction:** +**Takeover / release: MongoDB multi-document transaction:** `MongoFleetAssignmentService` opens a MongoDB `ClientSession` and wraps the entire read-check-write sequence in `session.withTransaction`: - Both reads use `.session(session)` so they observe a **consistent snapshot** - (MongoDB uses MVCC — snapshot isolation is the default for multi-document + (MongoDB uses MVCC; snapshot isolation is the default for multi-document transactions). - Rule predicates from `domain/*/rules.ts` run against the snapshot. - Both writes happen inside the same transaction with `majority` write concern. @@ -377,7 +289,7 @@ entire read-check-write sequence in `session.withTransaction`: rule check now fails; the transaction aborts with a typed `DomainError`. No partial writes, no silent lost update. -**Connectivity toggle — single-document atomic guard:** +**Connectivity toggle: single-document atomic guard:** ```ts findOneAndUpdate({ _id, assignedOperatorId: null }, { connectivityStatus: 'offline' }) @@ -390,99 +302,29 @@ the caller re-reads and produces a precise `VEHICLE_ALREADY_ASSIGNED` error. | Scope | Guarantee | |-------|-----------| -| Takeover / release | Strong — all reads from primary within session; both writes commit together or neither does | -| Connectivity toggle | Atomic — single guarded `findOneAndUpdate` | -| Client UI | Eventually consistent — WebSocket clients receive `vehicle.changed` within tens of milliseconds; polling clients within 5 seconds | +| Takeover / release | Strong: all reads from primary within session; both writes commit together or neither does | +| Connectivity toggle | Atomic: single guarded `findOneAndUpdate` | +| Client UI | Eventually consistent, almost instantaneous. WebSocket clients receive `vehicle.changed` within tens of milliseconds. | Any client acting on stale UI is safely rejected by the backend with a domain error code the client can display. ### Limits of the transactions approach -- **Consistency is tied to the database** — the invariants are enforced inside +- **Consistency is tied to the database**: the invariants are enforced inside MongoDB. A service that bypasses the backend and writes directly to the collection breaks the guarantees. -- **Transactions don't cross service boundaries** — if a second service (e.g., +- **Transactions don't cross service boundaries**: if a second service (e.g., a billing service) needs to participate in the same atomic operation, MongoDB transactions can't span it. A saga pattern or an outbox pattern would be needed. -- **Throughput** — multi-document transactions add latency (round-trip + lock +- **Throughput**: multi-document transactions add latency (round-trip + lock acquisition). For the expected fleet management scale (hundreds of operators, not hundreds of thousands) this is fine. At higher throughput, the next step would be: ### Alternative: distributed locking with Redis -For invariants that span multiple services or data stores, a Redis-based mutex -(`SET NX PX` / Redlock) can serve as a general-purpose concurrency primitive: - -``` -acquire lock(vehicle_id) → run business logic → release lock -``` - -Trade-offs vs. the current approach: - -| | MongoDB transactions | Redis distributed lock | -|---|---|---| -| Scope | Single MongoDB cluster | Cross-service, cross-DB | -| Failure mode | Transaction aborted, client retries | Lock holder crash → TTL expiry | -| Latency | 1–2 extra round-trips | 1–2 extra round-trips + Redis hop | -| Complexity | Built-in, no new infra | Requires Redis, lock TTL tuning, fencing tokens | -| Current fit | ✅ right for this system | Over-engineered for this system | - -The Redis approach becomes the right choice once the consistency boundary needs -to cross a service edge (e.g., a dedicated assignment service + a billing -service that charges per-minute of vehicle occupancy both need to agree on the -same transaction). - ---- - -## API reference - -Full Swagger UI at [`/docs`](http://localhost:3000/docs) in dev. - -### Vehicles CRUD - -| Method | Path | Body | Response | -| ------ | --------------------------------- | ------------------------ | -------- | -| GET | `/vehicles` | — | `Vehicle[]` | -| POST | `/vehicles` | `{ name }` | `Vehicle` | -| GET | `/vehicles/:id` | — | `Vehicle` | -| PATCH | `/vehicles/:id` | `{ name? }` | `Vehicle` | -| DELETE | `/vehicles/:id` | — | `204` (rejected with `409` if online or assigned) | -| PATCH | `/vehicles/:id/connectivity` | `{ status: 'online' \| 'offline' }` | `Vehicle` | - -### Operators (read-only, seeded on boot) - -| Method | Path | Response | -| ------ | ------------------- | -------- | -| GET | `/operators` | `Operator[]` | -| GET | `/operators/:id` | `Operator` | - -### Fleet management (takeover / release) - -Both endpoints require an `X-Operator-Id: ` header identifying the -acting operator (a stand-in for auth — see [Assumptions](#assumptions--optional-paths-taken)). - -| Method | Path | Headers | Body | Response | -| ------ | --------------------------------- | ------------------ | -------------- | -------- | -| POST | `/fleet-management/takeover` | `X-Operator-Id` | `{ vehicleId }` | `Vehicle` | -| POST | `/fleet-management/release` | `X-Operator-Id` | `{ vehicleId }` | `Vehicle` | - -### Error response shape - -Every domain rule violation returns a JSON body with a stable machine code: - -```json -{ - "statusCode": 409, - "code": "VEHICLE_ALREADY_ASSIGNED", - "message": "Another operator is holding this vehicle" -} -``` - -Both frontends switch on `code` to render specific rejection reasons. - --- ## Real-time updates @@ -501,12 +343,12 @@ receives: when no one is watching. 2. Each raw Mongo event is translated to a domain `VehicleChangedEvent` and emitted on the app-wide `EventEmitter2`. This decouples the data-access - watcher from the WebSocket gateway — neither knows about the other. + watcher from the WebSocket gateway; neither knows about the other. 3. **`VehiclesGateway`** in `apis/vehicles/` subscribes with `@OnEvent('vehicle.changed')` and broadcasts to every socket in `/realtime`. Using change streams as the event source means **every write** is captured -regardless of who wrote it — a service, an admin CLI, or another backend +regardless of who wrote it: a service, an admin CLI, or another backend instance. This also makes horizontal scaling straightforward: each backend instance runs its own stream and broadcasts to its own connected clients. A socket.io Redis adapter propagates the broadcast cluster-wide (see v2 notes). @@ -530,12 +372,11 @@ Three suites, ~15 seconds total against `mongodb-memory-server`. ### Strategy -- **Domain rules** (`vehicle.rules.spec.ts`, `operator.rules.spec.ts`) — pure +- **Domain rules** (`vehicle.rules.spec.ts`, `operator.rules.spec.ts`): pure unit tests for the rule predicates. No mocks, no framework, no DB. These test the invariant logic in total isolation. -- **Assignment service** (`mongo-fleet-assignment.service.spec.ts`) — - integration tests against a real single-node MongoDB replica set spun up +- **Assignment service** (`mongo-fleet-assignment.service.spec.ts`): integration tests against a real single-node MongoDB replica set spun up by `mongodb-memory-server`. This is where the interesting guarantees live: - Full takeover decision table (happy path + every rule violation) - Every failure path also asserts the DB state was **not** mutated @@ -550,7 +391,7 @@ Three suites, ~15 seconds total against `mongodb-memory-server`. the loser vehicle stays unassigned. The concurrency tests prove both sides of the "at most one" invariant under -real contention. They could not be written with fakes — the guarantee lives +real contention. They could not be written with fakes; the guarantee lives in the transaction protocol, not in application code. ### What is not tested (and why) @@ -560,14 +401,14 @@ repeat framework behaviour (class-validator, Nest routing) or verify an obvious delegation. Coverage-driven testing is deliberately avoided; the test surface is chosen by where real risk lives. -### Known limitation — concurrency tests are sequential, not truly concurrent +### Known limitation: concurrency tests are sequential, not truly concurrent The two "race" tests use `Promise.allSettled([callA, callB])` in a single Node.js process. Because Node.js is single-threaded and both calls `await` inside a Mongoose session, the event loop runs them sequentially: the first transaction completes and commits before the second one begins its read. The second call therefore sees already-committed state and fails the in-memory -domain-rule check — no MongoDB write-conflict is triggered. +domain-rule check; no MongoDB write-conflict is triggered. This still catches regression errors, but it does not exercise the actual concurrency path where two transactions read the same unassigned vehicle @@ -582,7 +423,7 @@ To test that path properly you would need either: The behaviour under a true write conflict is described in [Concurrency & consistency](#concurrency--consistency): `session.withTransaction` auto-retries on `TransientTransactionError`, the retry reads the now-committed -state, the rule check fails, and a typed `DomainError` is returned — but this +state, the rule check fails, and a typed `DomainError` is returned, but this path is exercised only in production load, not in the current test suite. --- @@ -601,7 +442,7 @@ Current implementation: Production roadmap (see also [Future optimisations](#future-optimisations)): -- **Prometheus `/metrics` endpoint** — Node runtime metrics, an +- **Prometheus `/metrics` endpoint**: Node runtime metrics, an `http_request_duration_seconds` histogram, a `fleet_assignment_operations_total{operation, outcome}` counter keyed by the domain error code, and a `fleet_websocket_connections` gauge. @@ -611,6 +452,8 @@ Production roadmap (see also [Future optimisations](#future-optimisations)): - **Grafana** dashboards for latency percentiles, takeover success rate by outcome code, and live WebSocket client count. +![Grafana](static/images/grafana.png) + --- ## Containerised components @@ -626,7 +469,7 @@ build would involve: - **Backend**: multi-stage `Dockerfile` (`node:22-alpine` build + distroless runtime), environment variables for `MONGO_URI`, `PORT`, `NODE_ENV`. - **Frontends**: build with `vite build`, serve the `dist/` output via nginx - or a CDN — the Vite build is a static bundle with no runtime Node. + or a CDN; the Vite build is a static bundle with no runtime Node. - **Compose (v2)**: extend `docker-compose.yml` with service definitions for all components plus Nginx as a reverse proxy, enabling the v2 architecture locally with `docker compose up --scale backend=3`. @@ -635,37 +478,63 @@ build would involve: ## Contribution workflow -The repo is set up as if a small team is collaborating on it. - -- Feature branches, PR-only merges. `main` is protected — CI must be green - and a Code Owner must approve before merging. -- Commit messages follow **Conventional Commits** with a repo-specific scope - allowlist (`backend | operator-dashboard | admin-dashboard | repo | ci | docs`), - enforced locally by a husky `commit-msg` hook and in CI on every PR. -- Local `pre-commit` hook runs Prettier on staged files via `lint-staged`. -- CI runs on every PR only (not on push to `main`): backend typecheck + - lint + tests, frontend typecheck + build, commit range linting. -- Type safety is enforced at both compile time (TypeScript strict mode) and - CI — the pipeline fails if `tsc --noEmit` reports errors. -- See [`.github/BRANCH_PROTECTION.md`](.github/BRANCH_PROTECTION.md) for the - one-time GitHub UI settings that turn the ruleset above into hard gates. +### Pull request policy + +Nothing lands on `main` except through a pull request. The branch is +protected: direct pushes are rejected at the GitHub side regardless of +local hook bypasses. + +**Branch naming** follows the Conventional Commits scope: +`feat/`, `fix/`, `chore/`, `docs/`, `ci/` + a short slug (e.g. `feat/operator-auth`). + +**Opening a PR** pre-fills [`.github/PULL_REQUEST_TEMPLATE.md`](.github/PULL_REQUEST_TEMPLATE.md): +summary, notable diffs per layer (backend / frontend / infra / docs), local +testing checklist, and notes for reviewers. + +**Review**: [`.github/CODEOWNERS`](.github/CODEOWNERS) auto-requests a review +from the repo owner on every PR. At least one approval is required; stale +approvals are dismissed when new commits are pushed. + +**Merge strategy**: squash or rebase only — no merge commits. Linear history +is enforced, and the head branch is deleted automatically after merge. + +See [`.github/BRANCH_PROTECTION.md`](.github/BRANCH_PROTECTION.md) for the +one-time GitHub UI steps that turn these rules into hard gates. + +### CI pipeline + +CI runs on every pull request (not on push to `main`). In-flight runs for the +same PR are cancelled when new commits are pushed so only the latest commit +needs to prove itself green. + +Three parallel jobs must all pass before merge is allowed: + +| Job | Steps | +|-----|-------| +| **Backend** | `npm ci` → `tsc --noEmit` → `eslint` → `jest` (against `mongodb-memory-server`) | +| **Frontend** | `npm ci` → `tsc --noEmit` → `vite build` | +| **Commit messages** | `commitlint` against the full PR commit range | + +Two local Husky hooks give developers early feedback before they push: +- `pre-commit`: Prettier via `lint-staged` on staged files. +- `commit-msg`: commitlint immediately after each commit. --- ## Assumptions & optional paths taken -The prompt allows a few explicit choices — this is what I took: +A few things were left open by the spec, here's what I went with: - **Database**: MongoDB (single-node replica set locally, required for the multi-document transactions the fleet-management flow uses). - **Operators**: seeded on startup via `OperatorsSeed` (`OnApplicationBootstrap`). - Four fixed operators — no CRUD API. Rationale: keep the surface focused on - the actual challenge — the assignment lifecycle. + Four fixed operators, no CRUD API. Rationale: keep the surface focused on + the actual challenge: the assignment lifecycle. - **Auth**: the prompt allows using an operator id in the request to identify who is acting. Implemented as an `X-Operator-Id` HTTP header (not the request body), extracted by a custom `@OperatorId()` parameter decorator. Rationale: when JWT auth lands, only the decorator body swaps to - `request.user.operatorId` — controllers and downstream code stay identical. + `request.user.operatorId`; controllers and downstream code stay identical. - **Frontend**: two separate Vite + React apps, one per audience (operators and admins). Rationale: different mental model, different eventual auth scope, different deploy artefacts. Sharing infra between them is easy; @@ -674,77 +543,26 @@ The prompt allows a few explicit choices — this is what I took: Change streams as the source of truth means the fan-out is captured for every write regardless of who wrote it, and horizontal scaling is straightforward. - **Not implemented**: real auth, response DTOs (controllers return the domain - entity directly — its shape is flat and already API-appropriate), pagination + entity directly; its shape is flat and already API-appropriate), pagination on `GET /vehicles`, structured JSON logs. --- ## Future optimisations -### API surface - -- **Response DTOs** with a derived `status: 'offline' | 'available' | 'in_use'` - field so the frontend renders from a single field instead of computing - from `(connectivityStatus, assignedOperatorId)`. -- **Pagination + filtering** on `GET /vehicles` (`?limit`, `?cursor`, - `?status`, `?region`) once the fleet grows past a screenful. -- **Audit log**: an append-only `assignments` collection recording every - takeover, release, and connectivity change with actor + timestamp. - -### Consistency & concurrency hardening - -- **Partial unique index** on `operators.currentVehicleId` and - `vehicles.assignedOperatorId` (`partialFilterExpression: { $type: 'objectId' }`) - — DB-level defence in depth against a hypothetical bug in the rule check. -- **Idempotency keys** on takeover / release so a retried request after a - network blip is safely no-op instead of racing. -- **Exponential backoff with jitter** on the client side for transient errors, - replacing the current "show error toast" UX for network failures. -- **Distributed locking (Redis / Redlock)** once invariants need to span - multiple services — see [Concurrency & consistency](#concurrency--consistency) - for a detailed trade-off comparison. - -### Authentication & authorisation - -- Move from the `X-Operator-Id` header to a JWT bearer token issued by an - identity provider. The `@OperatorId()` decorator becomes a one-liner reading - `request.user.operatorId` — controllers unchanged. Add a `JwtAuthGuard` - (global with `@Public()` opt-out) and role-based guards for admin endpoints. - WebSocket handshakes carry the token in `socket.handshake.auth.token`. - -### Real-time & scaling - -- **socket.io Redis adapter** with sticky-session LB routing once there is - more than one Nest instance. -- **Dedicated broadcaster tier** at ~10+ instances: 2–3 instances own the - change stream and publish to Redis; gateway instances stay thin. -- **Change stream resume tokens** persisted (Redis or Mongo) so a watcher - restart doesn't drop events between crash and reconnect. -- **Server-side sequence numbers** on WebSocket messages so clients can detect - gaps and re-fetch snapshots. - -### Quality & automation - -- **CD pipeline** triggered on `main` merge — build Docker images, push to - registry, deploy to staging, run smoke tests. -- **E2E tests** (Playwright) through the full stack proving the `code` field - surfaces to the operator dashboard UI for each domain error. -- **Chaos / load testing** simulating > 30 000 concurrent operators to stress - the WebSocket layer and the MongoDB transaction throughput ceiling. -- **SonarCloud** or **Semgrep** on PRs for code smells and security hotspots. -- **Dependabot** for automated dependency updates. -- **CodeQL** on PRs for security scanning (free GitHub Actions). -- **`eslint-plugin-boundaries`** to programmatically enforce the layer rules - (`data-access` cannot import from `apis`, etc.) — makes the layering - structurally enforced rather than convention. - -### Developer experience - -- **`.claude/` agents and skills** — structured prompts and tools so AI - assistants can be reliably integrated into the development workflow, reducing - context ramp-up time and boosting productivity on routine tasks (adding a new - endpoint, writing tests for a new domain rule, etc.). -- **Production-readiness checklist**: structured JSON logs, secrets management - (Vault or AWS Secrets Manager), container health endpoints, graceful shutdown - with in-flight request draining, database connection pooling tuned for - concurrent transaction load. +- **Partial unique index** on `vehicles.assignedOperatorId` and `operators.currentVehicleId` as a DB-level safety net against any bug in the rule check. +- **Idempotency keys** on takeover / release so a retried request after a network blip is a safe no-op. +- **JWT auth**: the `@OperatorId()` decorator is already the only thing that would need to change; controllers stay untouched. +- **socket.io Redis adapter** once there's more than one backend instance, so broadcasts reach all connected clients regardless of which replica they hit. +- **Change stream resume tokens** persisted to Redis/Mongo so a watcher restart doesn't drop events. +- **Pagination** on `GET /vehicles` once the fleet grows past a screenful. +- **Audit log**: an append-only `assignments` collection for every takeover, release, and connectivity change. +- **Playwright E2E tests** through the full stack, proving domain error codes surface correctly in the UI. +- **`eslint-plugin-boundaries`** to enforce the layer rules structurally rather than by convention. +- **CD pipeline**: on merge to `main`, build and push the backend Docker image to a registry (Docker Hub / ECR / GCR), then trigger a rolling deploy to a staging environment. A separate release workflow deploys to production on a tagged commit, with a manual approval gate between staging and prod. + +--- + +## License + +MIT © Omar Maaref diff --git a/apps/admin-dashboard/.env.observed b/apps/admin-dashboard/.env.observed new file mode 100644 index 0000000..dc27dbc --- /dev/null +++ b/apps/admin-dashboard/.env.observed @@ -0,0 +1 @@ +VITE_API_URL=http://localhost:8090 diff --git a/apps/admin-dashboard/package.json b/apps/admin-dashboard/package.json index c5db5bd..a8d19d2 100644 --- a/apps/admin-dashboard/package.json +++ b/apps/admin-dashboard/package.json @@ -5,6 +5,7 @@ "type": "module", "scripts": { "dev": "vite", + "dev:observed": "vite --mode observed", "build": "tsc -b && vite build", "preview": "vite preview" }, diff --git a/apps/backend/src/app.module.ts b/apps/backend/src/app.module.ts index 10b3ca3..257d03f 100644 --- a/apps/backend/src/app.module.ts +++ b/apps/backend/src/app.module.ts @@ -1,5 +1,4 @@ import { Module } from '@nestjs/common'; -import { ConfigModule } from '@nestjs/config'; import { EventEmitterModule } from '@nestjs/event-emitter'; import { MongooseModule } from '@nestjs/mongoose'; import { FleetManagementModule } from './apis/fleet-management/fleet-management.module'; @@ -10,7 +9,6 @@ import { VehiclesModule } from './apis/vehicles/vehicles.module'; @Module({ imports: [ - ConfigModule.forRoot({ isGlobal: true }), EventEmitterModule.forRoot(), MongooseModule.forRoot(process.env.MONGODB_URI!), HealthModule, diff --git a/apps/operator-dashboard/.env.observed b/apps/operator-dashboard/.env.observed new file mode 100644 index 0000000..dc27dbc --- /dev/null +++ b/apps/operator-dashboard/.env.observed @@ -0,0 +1 @@ +VITE_API_URL=http://localhost:8090 diff --git a/apps/operator-dashboard/package.json b/apps/operator-dashboard/package.json index 9fe803b..ed71605 100644 --- a/apps/operator-dashboard/package.json +++ b/apps/operator-dashboard/package.json @@ -5,6 +5,7 @@ "type": "module", "scripts": { "dev": "vite", + "dev:observed": "vite --mode observed", "build": "tsc -b && vite build", "preview": "vite preview" }, diff --git a/package.json b/package.json index e121018..0da864b 100644 --- a/package.json +++ b/package.json @@ -5,26 +5,24 @@ "scripts": { "prepare": "husky", "format": "prettier --write \"apps/**/*.{ts,tsx,json,md,css,html}\"", - "install:all": "npm install && npm --prefix apps/backend install && npm --prefix apps/operator-dashboard install && npm --prefix apps/admin-dashboard install", + "dev": "npm run docker:up && concurrently -k -n backend,operator,admin -c blue,magenta,cyan \"npm run backend:dev\" \"npm run operator:dev\" \"npm run admin:dev\"", "docker:up": "docker compose up -d --wait", "docker:down": "docker compose down", - "docker:reset": "docker compose down -v && docker compose up -d --wait", - "cluster:up": "docker compose --profile cluster up -d --wait --build", - "cluster:down": "docker compose --profile cluster down", - "cluster:logs": "docker compose --profile cluster logs -f nginx backend-1 backend-2", - "cluster:reset": "docker compose --profile cluster down -v && docker compose --profile cluster up -d --wait --build", - "monitoring:up": "docker compose --profile monitoring up -d --wait", - "monitoring:down": "docker compose --profile monitoring down", - "monitoring:reset": "docker compose --profile monitoring down -v && docker compose --profile monitoring up -d --wait", - "observed:up": "docker compose --profile cluster --profile monitoring up -d --wait --build", - "observed:down": "docker compose --profile cluster --profile monitoring down", + "full:install": "npm --prefix apps/operator-dashboard install && npm --prefix apps/admin-dashboard install", + "full:dev": "npm run full:up && concurrently -k -n operator,admin -c magenta,cyan \"npm run operator:dev:full\" \"npm run admin:dev:full\"", + "full:up": "docker compose --profile cluster --profile monitoring up -d --wait --build", + "full:down": "docker compose --profile cluster --profile monitoring down", + "full:logs": "docker compose --profile cluster logs -f nginx backend-1 backend-2", + "backend:dev": "npm --prefix apps/backend run start:dev", "backend:test": "npm --prefix apps/backend test", "backend:lint": "npm --prefix apps/backend run lint", "operator:dev": "npm --prefix apps/operator-dashboard run dev", + "operator:dev:full": "npm --prefix apps/operator-dashboard run dev:observed", "operator:build": "npm --prefix apps/operator-dashboard run build", "admin:dev": "npm --prefix apps/admin-dashboard run dev", + "admin:dev:full": "npm --prefix apps/admin-dashboard run dev:observed", "admin:build": "npm --prefix apps/admin-dashboard run build" }, "devDependencies": { diff --git a/static/images/grafana.png b/static/images/grafana.png new file mode 100644 index 0000000..a0c8dc1 Binary files /dev/null and b/static/images/grafana.png differ diff --git a/static/images/operator-dashboard.png b/static/images/operator-dashboard.png new file mode 100644 index 0000000..769b934 Binary files /dev/null and b/static/images/operator-dashboard.png differ diff --git a/static/images/swagger.png b/static/images/swagger.png new file mode 100644 index 0000000..29038ca Binary files /dev/null and b/static/images/swagger.png differ