Skip to content

feat(m3): Socket.io Real-time Layer & Notification Service#15

Merged
codeRisshi25 merged 2 commits intomainfrom
feature/m3-socketio-realtime
Feb 25, 2026
Merged

feat(m3): Socket.io Real-time Layer & Notification Service#15
codeRisshi25 merged 2 commits intomainfrom
feature/m3-socketio-realtime

Conversation

@codeRisshi25
Copy link
Copy Markdown
Owner

@codeRisshi25 codeRisshi25 commented Feb 25, 2026

Overview

Implements Issue #8 — adds Socket.io real-time WebSocket communication and a packages/notifications abstraction layer for cross-process event delivery.

Changes

packages/common — Socket Events Catalog

  • New events/index.ts with 8 SOCKET_EVENTS constants (ride:offer, ride:accepted, ride:driver-location, etc.)

packages/notifications — New Workspace

  • NotificationChannel interface (pluggable: SocketChannel now, SMS/push later)
  • SocketChannel emits via Socket.io + Redis adapter (enables cross-process pub/sub from ride-worker in M4+)
  • NotificationService with helpers: notifyDriver(), notifyRider(), notifyRide()
  • createNotificationService(channels) factory

apps/api-gateway — Socket.io Server

  • Refactor src/index.ts: http.createServer(app) + server.listen() (Socket.io shares same port as REST)
  • sockets/index.ts: Socket.io init, Redis adapter for horizontal scalability
  • sockets/auth.ts: JWT middleware (accepts auth.token or Authorization: Bearer)
  • sockets/handlers/driver.ts: driver:go-online, driver:go-offline, driver:location-update
  • sockets/handlers/rider.ts: rider:subscribe-driver-location (with trip ownership validation), rider:unsubscribe-driver-location

Room Strategy

  • driver:{driverId} — personal room, auto-joined on connect
  • rider:{riderId} — personal room, auto-joined on connect
  • ride:{tripId} — shared room, rider joins to get live location

Tests

14 new tests added:

  • sockets/__tests__/auth.test.ts — 5 tests (no token, invalid, valid via auth.token, Bearer fallback, malformed header)
  • sockets/__tests__/driver-handler.test.ts — 4 tests (room join, go-online, go-offline, location-update)
  • sockets/__tests__/rider-handler.test.ts — 5 tests (room join, subscribe with/without ownership, unsubscribe)

Verification

✓ src/sockets/__tests__/auth.test.ts           (5 tests)
✓ src/sockets/__tests__/driver-handler.test.ts  (4 tests)
✓ src/sockets/__tests__/rider-handler.test.ts   (5 tests)

Test Files 3 passed | Tests 14 passed
TypeScript: api-gateway OK | notifications OK

Depends on

  • M1 (Redis client, driver service for GEO)
  • M2 (ride-worker exists)

Blocks

  • M4 (ride-worker calls notifyDriver() to send ride offers)
  • M5 (live driver location streaming to riders via ride:{tripId} room)

Closes #8

Summary by CodeRabbit

Release Notes

  • New Features

    • Added real-time socket communication infrastructure for instant driver and rider updates
    • Implemented driver location tracking and status synchronization (online/offline)
    • Enabled secure JWT-based authentication for real-time connections
    • Introduced centralized notification system for event-driven communications
  • Tests

    • Added comprehensive test coverage for authentication and event handlers
  • Chores

    • Updated build and configuration to support new real-time services

- Add packages/notifications workspace with NotificationChannel abstraction
  - SocketChannel emits via Socket.io + Redis adapter (cross-process support)
  - NotificationService with notifyDriver/notifyRider/notifyRide helpers
  - Designed for future SMS/push channels

- Add SOCKET_EVENTS constants to packages/common
  (ride:offer, ride:offer-expired, ride:accepted, ride:started,
   ride:completed, ride:cancelled, ride:driver-location, ride:otp)

- Add Socket.io server to api-gateway
  - Refactor index.ts: http.createServer + server.listen (same port as REST)
  - sockets/index.ts: init with Redis adapter for horizontal scalability
  - sockets/auth.ts: JWT middleware (auth.token and Bearer header)
  - sockets/handlers/driver.ts: go-online, go-offline, location-update
  - sockets/handlers/rider.ts: subscribe/unsubscribe driver location (with trip ownership validation)

- Install socket.io, @socket.io/redis-adapter in api-gateway
- Add vitest.config.ts to scope tests to src/ only

Tests: 14 passed (5 auth, 4 driver handler, 5 rider handler)
TypeScript: api-gateway OK, notifications OK

Closes #8
@codeRisshi25 codeRisshi25 force-pushed the feature/m3-socketio-realtime branch from ebd3e9c to d208947 Compare February 25, 2026 16:44
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Feb 25, 2026

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c80c3d9 and 635813c.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (20)
  • apps/api-gateway/package.json
  • apps/api-gateway/src/index.ts
  • apps/api-gateway/src/sockets/__tests__/auth.test.ts
  • apps/api-gateway/src/sockets/__tests__/driver-handler.test.ts
  • apps/api-gateway/src/sockets/__tests__/rider-handler.test.ts
  • apps/api-gateway/src/sockets/auth.ts
  • apps/api-gateway/src/sockets/handlers/driver.ts
  • apps/api-gateway/src/sockets/handlers/rider.ts
  • apps/api-gateway/src/sockets/index.ts
  • apps/api-gateway/vitest.config.ts
  • packages/common/events/index.ts
  • packages/common/index.ts
  • packages/notifications/package.json
  • packages/notifications/src/channels/index.ts
  • packages/notifications/src/channels/socket.channel.ts
  • packages/notifications/src/index.ts
  • packages/notifications/src/service.ts
  • packages/notifications/src/types/index.ts
  • packages/notifications/tsconfig.json
  • tsconfig.json

📝 Walkthrough

Walkthrough

This pull request introduces Socket.IO real-time communication to the API gateway with JWT authentication, role-based event handlers for drivers and riders, and a new shared notification service package. The Socket.IO server is attached to an HTTP server, uses Redis adapter for horizontal scalability, and integrates with a notification abstraction layer. Event constants are centralized in the common package.

Changes

Cohort / File(s) Summary
Socket.IO Server Infrastructure
apps/api-gateway/src/index.ts, src/sockets/index.ts, package.json
Refactored entry point from app.listen to http.createServer(app) with Socket.IO server initialization; added socket.io and @socket.io/redis-adapter dependencies; initialized Socket.IO server with Redis adapter configuration and role-based handler routing on connection.
Socket.IO Authentication
apps/api-gateway/src/sockets/auth.ts
Implemented JWT authentication middleware extracting token from socket.handshake.auth.token or Authorization header, verifying via existing JWT utility, and attaching decoded payload to socket.data.user.
Socket Event Handlers
apps/api-gateway/src/sockets/handlers/driver.ts, ...riders.ts
Added role-specific event handlers: drivers auto-join personal rooms and handle driver:go-online, driver:go-offline, and driver:location-update events; riders auto-join personal rooms and handle rider:subscribe-driver-location and rider:unsubscribe-driver-location with trip ownership validation via Prisma.
Socket Handler Tests
apps/api-gateway/src/sockets/__tests__/auth.test.ts, ...driver-handler.test.ts, ...rider-handler.test.ts
Added comprehensive unit test suites (213 total lines) covering authentication middleware, driver event flows (online/offline/location-update), and rider subscription flows with error scenarios and mocked dependencies.
Test Configuration
apps/api-gateway/vitest.config.ts
Updated Vitest configuration to exclude dist and node_modules, expanded coverage scope to include src/sockets/**, and improved test file patterns.
Notification Service Package
packages/notifications/...
Created new workspace package with NotificationChannel abstraction, SocketChannel implementation using Socket.IO Redis adapter, NotificationService orchestration class, and type definitions; includes proper TypeScript and package.json configuration.
Event Constants & Common Exports
packages/common/events/index.ts, packages/common/index.ts
Centralized Socket.IO event name constants (RIDE_OFFER, RIDE_ACCEPTED, RIDE_STARTED, etc.) with type-safe SocketEventName type; re-exported from common package for shared use.
Workspace Configuration
packages/notifications/tsconfig.json, tsconfig.json
Added TypeScript configuration for notifications package with common project reference; updated root tsconfig to include notifications in project references.

Sequence Diagram

sequenceDiagram
    participant Client as WebSocket Client
    participant Gateway as api-gateway<br/>Socket.IO Server
    participant Auth as JWT Auth<br/>Middleware
    participant Handler as Handler<br/>(Driver/Rider)
    participant Service as Driver/Rider<br/>Service
    participant Prisma as Prisma<br/>Database
    participant Redis as Redis Adapter

    Client->>Gateway: Connect with auth token
    Gateway->>Auth: socketAuthMiddleware()
    Auth->>Auth: Extract token from handshake
    Auth->>Auth: verifyToken()
    Auth->>Gateway: Attach socket.data.user
    
    alt Authentication Success
        Gateway->>Handler: registerHandlers()
        Handler->>Gateway: Auto-join personal room
        Handler->>Gateway: Listen for events
    else Authentication Failure
        Gateway->>Client: Reject connection
    end

    Client->>Gateway: Emit event (e.g., driver:go-online)
    Gateway->>Handler: Route to handler
    Handler->>Service: Call service method
    Service->>Prisma: Update database
    Prisma-->>Service: Acknowledge
    Service-->>Handler: Return result
    Handler->>Gateway: Emit acknowledgment
    Gateway->>Redis: Publish via Redis adapter
    Redis->>Client: Deliver event
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐰 Hops through WebSockets bright and true,
Real-time channels, connections new!
Redis whispers, sockets dance,
Drivers, riders get their chance. 🚗
Notifications flow like streams of light,
APIs humming through the night!

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/m3-socketio-realtime

Comment @coderabbitai help to get the list of available commands and usage tips.

@codeRisshi25 codeRisshi25 merged commit 0e2d6a4 into main Feb 25, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[M3] Socket.io Real-time Layer & Notification Service

1 participant