Skip to content

feat: store & display real-time driver location via MongoDB telemetry (#571)#631

Merged
KanishJebaMathewM merged 4 commits into
KanishJebaMathewM:mainfrom
KaparthyReddy:feat/driver-location-mongodb-telemetry
Jun 21, 2026
Merged

feat: store & display real-time driver location via MongoDB telemetry (#571)#631
KanishJebaMathewM merged 4 commits into
KanishJebaMathewM:mainfrom
KaparthyReddy:feat/driver-location-mongodb-telemetry

Conversation

@KaparthyReddy

@KaparthyReddy KaparthyReddy commented Jun 20, 2026

Copy link
Copy Markdown
Contributor

Pull Request Description

This PR integrates a backend pipeline to store, update, and read real-time driver telemetry coordinates via MongoDB. It creates a scalable data model optimized for geospatial processing to support live tracking rendering across the app interface.

Closes #571


Type of Change

  • ✨ New feature (Integration / Backend Infrastructure)

Submission Checklist

  • Created Telemetry collection structure following explicit GeoJSON conventions [longitude, latitude]
  • Implemented atomic upsert optimization routines avoiding memory bloating loops
  • Created decoupled routing handlers (/api/telemetry/location)
  • Verified 2dsphere spatial indexing for future proximity mapping features

Architecture Breakdown

Model Token Format Spec Index Target
location.coordinates Array [Lng, Lat] 2dsphere
driverId ObjectId (Ref) Unique Primary Lookup Key
// Geo-spatial support enabled:
TelemetrySchema.index({ location: '2dsphere' });

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit

## Release Notes

* **New Features**
  * Real-time driver location tracking: Customers can now view live GPS updates of their delivery driver on the map during active orders
  * Automatic location syncing: Driver location updates continuously while online and actively on a delivery

* **Chores**
  * Added WebSocket communication dependency to support live location broadcasting
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

- Add Telemetry schema matching GeoJSON point geometry specifications
- Implement high-speed atomic update/upsert pipeline in telemetryController
- Add endpoints for polling or connecting active webhooks to map interfaces
- Establish 2dsphere indexing for efficient real-time distance calculations
Closes KanishJebaMathewM#571
@github-actions

Copy link
Copy Markdown
Contributor

🎉 Thank you for your contribution! Your pull request has been received and will be reviewed shortly.

If you enjoy the project, please consider giving the repository a ⭐. You can also follow my GitHub profile to stay updated on future open-source projects.

Thanks for being part of the community! 🚀

@coderabbitai

coderabbitai Bot commented Jun 20, 2026

Copy link
Copy Markdown

![Review Change Stack [link removed for security]]([link removed for security])

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

Implements end-to-end real-time driver location tracking. A new LocationService in the driver app streams GPS over WebSocket. The backend tracker normalizes coordinates, persists telemetry to MongoDB (with TTL and 2dsphere indexes), and broadcasts to Supabase Realtime. A new GET /:id/driver-location REST endpoint exposes the latest fix. The customer LiveTrackingScreen subscribes to live updates and fetches the initial position.

Changes

End-to-end real-time driver location tracking

Layer / File(s) Summary
MongoDB telemetry indexes and collection rename
backend/api/src/config/db.js, backend/api/src/sockets/tracker.js, backend/api/test/unit/tracker.test.js
Creates TTL (7-day) and 2dsphere indexes on the telemetry collection after MongoDB connect; renames the flush write target from live_gps_pings to telemetry; updates the flush test assertion.
Tracker: coordinate normalization, order resolution, multi-channel broadcast
backend/api/src/sockets/tracker.js
Accepts lat/lng aliases, validates coordinate bounds, resolves orderUUID/orderDisplayId from Supabase, enriches the telemetry buffer record, adjusts Redis cache, updates WebSocket broadcast payload to include order_display_id, and adds Supabase Realtime broadcast on driver-location:{orderUUID}.
REST endpoint: GET /:id/driver-location
backend/api/src/routes/orderRoutes.js
Imports mongoDb; adds GET /:id/driver-location with role-based authorization (customer ownership or driver assignment), queries the telemetry collection for the most recent record, returns lat/lng/timestamp or appropriate 4xx/5xx errors.
Driver app LocationService: GPS stream, WebSocket, heartbeat, reconnect
apps/driver/lib/services/location_service.dart, apps/driver/pubspec.yaml
New singleton LocationService with startTracking/stopTracking lifecycle, Geolocator high-accuracy stream, lazy WebSocket connection to /ws/tracking with auth token, location_ping payload with cached active order, 15-second heartbeat, and exponential backoff reconnect (capped 30s). Adds web_socket_channel: ^3.0.0 dependency.
Driver HomeScreen: online toggle wires tracking
apps/driver/lib/screens/home_screen.dart
Imports LocationService; starts tracking in _initLocation when already online; starts/stops tracking in _toggleOnlineState on online/offline transitions.
Customer LiveTrackingScreen: Supabase Realtime subscription and initial fetch
apps/customer/lib/screens/live_tracking_screen.dart, apps/customer/lib/services/order_service.dart
Adds _supabaseRealtimeChannel state, updates dispose() to clean up both channels, subscribes to driver-location:{orderUUID} broadcast on load, fetches initial coordinates via new OrderService.fetchDriverLocation(), and updates the truck marker on each incoming event.

Sequence Diagram(s)

sequenceDiagram
  rect rgba(100, 150, 200, 0.5)
    note over LocationService,BackendTracker: Driver Side
    LocationService->>BackendTracker: WebSocket location_ping {driver_id, orderId, lat, lng}
    BackendTracker->>Supabase: resolve orderUUID by id/order_display_id
    Supabase-->>BackendTracker: orderUUID, orderDisplayId
    BackendTracker->>MongoDB: buffer telemetry record {driver_id, order_id, lat, lng}
    BackendTracker->>Redis: cache {lat, lng}
    BackendTracker->>WSClients: broadcast {latitude, longitude, order_display_id}
    BackendTracker->>SupabaseRealtime: broadcast driver-location:{orderUUID} {lat, lng}
  end
  rect rgba(100, 200, 150, 0.5)
    note over LiveTrackingScreen,MongoDB: Customer Side (initial load)
    LiveTrackingScreen->>OrderService: fetchDriverLocation(orderId)
    OrderService->>BackendREST: GET /orders/:id/driver-location
    BackendREST->>MongoDB: find latest telemetry by driver_id
    MongoDB-->>BackendREST: {lat, lng, timestamp}
    BackendREST-->>OrderService: 200 {lat, lng}
    OrderService-->>LiveTrackingScreen: initial coordinates → _updateTruckPosition
  end
  rect rgba(200, 150, 100, 0.5)
    note over LiveTrackingScreen,SupabaseRealtime: Customer Side (live updates)
    LiveTrackingScreen->>SupabaseRealtime: subscribe driver-location:{orderUUID}
    SupabaseRealtime-->>LiveTrackingScreen: broadcast event {lat, lng}
    LiveTrackingScreen->>LiveTrackingScreen: _updateTruckPosition(lat, lng)
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

flutter, backend, customer-app, driver-app, type:api

Poem

🐇 Hop, hop — the driver's on the move,
A WebSocket ping in every groove.
MongoDB stores each lat and lng,
Supabase shouts it instantly!
The marker glides across the map,
No more mocked coords — close that gap. 🗺️

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: storing and displaying real-time driver location via MongoDB telemetry with clear, concise language.
Linked Issues check ✅ Passed The PR implements all major requirements from issue #571: MongoDB telemetry storage with TTL indexing, driver location API endpoint, Supabase Realtime broadcasting, customer app subscription, and driver app GPS transmission with authentication.
Out of Scope Changes check ✅ Passed All code changes directly support the stated objectives; no unrelated modifications detected. Changes span backend infrastructure, driver location services, and customer app integration as required.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

⚠️ Security Notice: Links posted by non-contributors have been automatically removed.

Comment thread server/controllers/telemetryController.js Fixed
Comment thread server/controllers/telemetryController.js Fixed
Comment thread server/routes/telemetryRoutes.js Fixed
Comment thread server/routes/telemetryRoutes.js Fixed

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@server/controllers/telemetryController.js`:
- Around line 24-25: The error responses in the telemetryController.js file
expose sensitive internal error details to clients through error.message,
creating a security vulnerability. Replace the error.message values in both
error response locations (around lines 24 and 39) with a generic client-safe
message such as "An error occurred" or "An error occurred while processing your
request". Log the actual error details (including error.message) server-side
using your logging mechanism so that debugging information is available to
developers but not exposed to clients.
- Around line 30-32: The code is missing validation for the driverId parameter
before passing it to Telemetry.findOne(), which causes MongoDB cast errors to
result in 500 responses instead of 400 errors for invalid client input. Add
validation logic after extracting driverId from req.params to check if the ID
format is valid (typically checking if it matches MongoDB ObjectId format), and
return a 400 response with an appropriate error message if the validation fails.
This validation should occur before the Telemetry.findOne() call to prevent
MongoDB from attempting to cast an invalid ID.
- Around line 5-13: The driverId extracted from req.body is used directly in the
Telemetry.findOneAndUpdate query filter without type validation, creating a
NoSQL injection vulnerability where an attacker could pass MongoDB operators
like $ne or $gt instead of a string. Add a type check to ensure driverId is a
string (or appropriate primitive type) and reject the request if it is an object
or contains unexpected properties before using it in the findOneAndUpdate filter
with { driverId }.
- Around line 14-20: The upsert operation is missing coordinate validation and
schema validators. Add validation checks after parsing longitude and latitude to
ensure they are finite numbers within valid geographic ranges (longitude: -180
to 180, latitude: -90 to 90) before using them in the location coordinates
array. Additionally, add the `runValidators: true` option to the second
parameter of the upsert call alongside the existing `upsert: true, new: true`
options to enable schema-level validation during the update operation.

In `@server/models/Telemetry.js`:
- Around line 16-19: The coordinates field in the Telemetry model currently
accepts any number array without validating GeoJSON structure or valid
geospatial ranges. Add a custom validator function to the coordinates field that
enforces: the array contains exactly two numbers (longitude and latitude),
longitude values are between -180 and 180, and latitude values are between -90
and 90. This application-level validation should be added before MongoDB
processes the data to catch invalid geospatial coordinates early rather than
failing at write time.
- Around line 4-24: The Telemetry schema is missing the orderId field that
tracker.js is buffering with order_display_id, causing data loss at write time.
Remove the unique: true constraint from the driverId field since telemetry is
time-series data requiring multiple location updates per driver, not a live
cache. Add an orderId field with a reference to the Order model to persist order
linkage. Finally, add a TTL index to the schema using the index method with
expireAfterSeconds to automatically expire old telemetry records according to
the architecture documentation requirements, ensuring that updatedAt field is
used as the TTL reference point.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: e8ea57d0-2e87-481e-af48-a47da0eb6db3

📥 Commits

Reviewing files that changed from the base of the PR and between 45dafc2 and c011ba4.

📒 Files selected for processing (3)
  • server/controllers/telemetryController.js
  • server/models/Telemetry.js
  • server/routes/telemetryRoutes.js

Comment thread server/controllers/telemetryController.js Outdated
Comment thread server/controllers/telemetryController.js Outdated
Comment thread server/controllers/telemetryController.js Outdated
Comment thread server/controllers/telemetryController.js Outdated
Comment thread server/models/Telemetry.js Outdated
Comment thread server/models/Telemetry.js Outdated
@KanishJebaMathewM
KanishJebaMathewM merged commit 19486a2 into KanishJebaMathewM:main Jun 21, 2026
5 of 7 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

🎉 Thank you for your contribution!

Your pull request has been merged successfully. We appreciate your work and look forward to your future contributions. 🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

# [INTEGRATION] Store & Display Real-Time Driver Location via MongoDB Telemetry

3 participants