Add activity tracking system for backend events#170
Conversation
📝 WalkthroughWalkthroughThis PR introduces a new Changes
Sequence Diagram(s)sequenceDiagram
actor Client
participant CreateRoom as create-room
participant TrackActivity as track-activity
participant Appwrite as Appwrite
participant LiveKit as LiveKit
Client->>CreateRoom: POST request with room data
CreateRoom->>CreateRoom: parseBody() & validate
CreateRoom->>Appwrite: Create room document
CreateRoom->>LiveKit: Create LiveKit room & token
CreateRoom->>TrackActivity: POST activity tracking<br/>(ROOM_CREATED event)
TrackActivity->>TrackActivity: Validate & log activity
TrackActivity-->>CreateRoom: 200 success response
CreateRoom-->>Client: 200 response with room details
sequenceDiagram
actor Client
participant JoinRoom as join-room
participant TrackActivity as track-activity
participant LiveKit as LiveKit
Client->>JoinRoom: POST request with join data
JoinRoom->>TrackActivity: POST activity tracking<br/>(USER_JOINED event)
Note over JoinRoom: Unhandled fetch call<br/>(no error handling)
JoinRoom->>JoinRoom: parseBody() & validate
JoinRoom->>LiveKit: Generate access token
JoinRoom-->>Client: 200 response with token
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Suggested labels
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
Hi @M4dhav This will include creating a new function and integrating it into key flows like room creation, joining, and deletion. Please let me know if this approach looks good 👍 |
There was a problem hiding this comment.
Actionable comments posted: 8
🧹 Nitpick comments (1)
functions/track-activity/src/utils.js (1)
1-27: Extract the parsing/validation helpers once.
throwIfMissingandparseBodyare now copied intofunctions/create-room/src/utils.js,functions/delete-room/src/utils.js,functions/database-cleaner/src/utils.js, and this file. That will drift quickly the next time validation changes; move them into one shared module and import from there.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@functions/track-activity/src/utils.js` around lines 1 - 27, Create a single shared helper module that exports the validation/parsing utilities (export throwIfMissing and parseBody from one central file) and remove the duplicated definitions in the other modules; then update the modules that currently define throwIfMissing and parseBody to import them from the new shared module instead of redeclaring them. Ensure the shared module preserves the same behavior/signature (throwIfMissing(obj, keys) and parseBody(body)) and update any import references in create-room, delete-room, database-cleaner and this file to use the shared export.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@functions/create-room/src/main.js`:
- Around line 75-85: The fetch call to "http://localhost/track-activity" inside
the main try block (the awaited call that sends eventType: "ROOM_CREATED" with
adminUid and appwriteRoomId) can throw and cause the whole function to return a
500; change it to fire-and-forget so tracking failures don't block room
creation: remove the await and invoke the fetch in a detached promise (or call
fetch(...).catch(...)) and log any error (e.g., console.error or
processLogger.error) so the primary operations (Appwrite/LiveKit room creation
and response) always succeed even if tracking fails.
In `@functions/database-cleaner/src/main.js`:
- Around line 7-24: Add MASTER_DATABASE_ID to the env validation and tighten
checks so blank strings are rejected and RETENTION_PERIOD_DAYS is a positive
integer: update the throwIfMissing usage (or add a small loop) to include
"MASTER_DATABASE_ID" and to treat empty string values in process.env as missing,
and add an explicit parse/validation for process.env.RETENTION_PERIOD_DAYS (use
Number.parseInt and ensure it's > 0 and a valid number) before proceeding; when
validation fails, return the same error response via res.json with a clear
message (same pattern as current catch) so cleanup doesn't start with malformed
envs.
- Around line 28-55: The cleanup currently logs errors from
appwrite.cleanParticipantsCollection, appwrite.cleanActivePairsCollection, and
appwrite.clearOldOTPs but always returns res.json({ success: true, ... });
change the logic to track failures (e.g., a boolean or an errors array) inside
the try/catch blocks for the three steps (references:
cleanParticipantsCollection, cleanActivePairsCollection, clearOldOTPs), push or
mark errors when a catch runs, and then when returning via res.json include
success: false and the collected error info if any step failed (otherwise
success: true). Ensure the response reflects partial failure and include enough
error details in the returned message for callers.
In `@functions/delete-room/src/main.js`:
- Around line 104-114: The room-deletion handler currently awaits the tracking
POST inside the main try so tracking failures can cause a 500 even after
successful deletion; change the tracking call that posts { eventType:
"ROOM_DELETED", userId: roomAdminUid, metadata: { roomId: appwriteRoomDocId } }
to be fire-and-forget (do not await) and isolate its errors by wrapping the
fetch in its own async IIFE or separate try/catch so any fetch/network error is
logged but cannot alter the handler’s success response from the delete routine
(refer to the fetch call that posts ROOM_DELETED and variables roomAdminUid and
appwriteRoomDocId).
In `@functions/join-room/src/main.js`:
- Around line 11-21: Move the request parsing/destructuring so userId and
roomName are extracted from the incoming request body before calling fetch;
specifically destructure userId and roomName from the parsed body ahead of the
activity POST. Also wrap the fetch("http://localhost/track-activity", ...) call
in its own try/catch so tracking failures are logged but do not throw (do not
abort token generation/validation); ensure the main token generation path still
runs even if the tracking fetch fails. Reference: variables userId and roomName,
and the tracking fetch to "http://localhost/track-activity".
In `@functions/join-room/src/utils.js`:
- Around line 1-13: throwIfMissing currently treats only undefined/null as
missing so empty strings slip through; update the function (throwIfMissing) to
optionally reject empty strings by adding a third parameter (e.g., nonEmpty or
options) and, when enabled, treat any string with zero length or only whitespace
(typeof value === 'string' && value.trim() === '') as missing; keep existing
undefined/null checks and ensure call sites that require non-empty values (e.g.,
validations for roomName, uid, eventType, userId) pass the nonEmpty flag so
those empty-string values are collected in missing and an error is thrown.
In `@functions/track-activity/README.md`:
- Around line 12-19: The JSON code fence in the README example (the
triple-backtick starting before the JSON object) is not closed, causing the
remainder of the file to render as code; add the terminating triple-backtick
(```) immediately after the JSON block (after the closing brace) to close the
fenced code block so the rest of functions/track-activity/README.md renders
correctly.
In `@functions/track-activity/src/main.js`:
- Around line 19-42: The catch block after constructing the activity object is
unreachable; remove the surrounding try/catch and the unused error() call, and
just build the activity object, call log("[ACTIVITY_TRACKED]", activity) and
return res.json({ success: true, message: "Activity tracked successfully", data:
activity }); if you plan to add persistence later, instead keep the try/catch
but move the database/write logic into the try and on failure use error(...) and
return res.status(500).json({ success: false, message: "Failed to track
activity" }); ensure references to activity, log(), error(), and
res.json/res.status are updated accordingly.
---
Nitpick comments:
In `@functions/track-activity/src/utils.js`:
- Around line 1-27: Create a single shared helper module that exports the
validation/parsing utilities (export throwIfMissing and parseBody from one
central file) and remove the duplicated definitions in the other modules; then
update the modules that currently define throwIfMissing and parseBody to import
them from the new shared module instead of redeclaring them. Ensure the shared
module preserves the same behavior/signature (throwIfMissing(obj, keys) and
parseBody(body)) and update any import references in create-room, delete-room,
database-cleaner and this file to use the shared export.
🪄 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
Run ID: bcb8d560-8fe3-4942-b64d-328a7c4b81cd
⛔ Files ignored due to path filters (2)
functions/package-lock.jsonis excluded by!**/package-lock.jsonfunctions/track-activity/package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (12)
functions/create-room/src/main.jsfunctions/create-room/src/utils.jsfunctions/database-cleaner/src/main.jsfunctions/database-cleaner/src/utils.jsfunctions/delete-room/src/main.jsfunctions/delete-room/src/utils.jsfunctions/join-room/src/main.jsfunctions/join-room/src/utils.jsfunctions/track-activity/README.mdfunctions/track-activity/package.jsonfunctions/track-activity/src/main.jsfunctions/track-activity/src/utils.js
Addressed Issues:
Fixes #169
✨ Feature Added: Activity Tracking
Changes
track-activityfor capturing backend eventsBenefits
Note
Changes are minimal and do not affect existing functionality.
AI Usage Disclosure:
We encourage contributors to use AI tools responsibly when creating Pull Requests. While AI can be a valuable aid, it is essential to ensure that your contributions meet the task requirements, build successfully, include relevant tests, and pass all linters. Submissions that do not meet these standards may be closed without warning to maintain the quality and integrity of the project. Please take the time to understand the changes you are proposing and their impact. AI slop is strongly discouraged and may lead to banning and blocking. Do not spam our repos with AI slop.
Check one of the checkboxes below:
I have used the following AI models and tools: TODO
Checklist
Summary by CodeRabbit
New Features
Bug Fixes
Improvements
Documentation