Skip to content

Add activity tracking system for backend events#170

Open
Shweta-281 wants to merge 3 commits into
AOSSIE-Org:mainfrom
Shweta-281:feature/activity-tracking
Open

Add activity tracking system for backend events#170
Shweta-281 wants to merge 3 commits into
AOSSIE-Org:mainfrom
Shweta-281:feature/activity-tracking

Conversation

@Shweta-281

@Shweta-281 Shweta-281 commented Mar 28, 2026

Copy link
Copy Markdown

Addressed Issues:

Fixes #169

✨ Feature Added: Activity Tracking

Changes

  • Added new function track-activity for capturing backend events
  • Implemented safe parsing and validation using shared utilities
  • Integrated tracking into:
    • create-room
    • join-room
    • delete-room
  • Added structured logging for all tracked events

Benefits

  • Improves observability of backend actions
  • Enables future analytics and monitoring
  • Provides foundation for event-driven architecture

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:

  • This PR does not contain AI-generated code at all.
  • This PR contains AI-generated code. I have read the AI Usage Policy and this PR complies with this policy. I have tested the code locally and I am responsible for it.

I have used the following AI models and tools: TODO

Checklist

  • My PR addresses a single issue, fixes a single bug or makes a single improvement.
  • My code follows the project's code style and conventions
  • If applicable, I have made corresponding changes or additions to the documentation
  • If applicable, I have made corresponding changes or additions to tests
  • My changes generate no new warnings or errors
  • I have joined the Discord server and I will share a link to this PR with the project maintainers there
  • I have read the Contribution Guidelines
  • Once I submit my PR, CodeRabbit AI will automatically review it and I will address CodeRabbit's comments.
  • I have filled this PR template completely and carefully, and I understand that my PR may be closed without review otherwise.

Summary by CodeRabbit

  • New Features

    • Added activity tracking system to monitor room creation, user joins, and room deletion events.
  • Bug Fixes

    • Fixed concurrent participant deletion operation to execute sequentially.
  • Improvements

    • Enhanced error handling with structured JSON responses across all operations.
    • Standardized request validation and error messages with prefixed logging tags.
    • Updated response format to include success indicators and consistent message structure.
  • Documentation

    • Added documentation for the new activity tracking functionality.

@coderabbitai

coderabbitai Bot commented Mar 28, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR introduces a new track-activity backend function for centralized event logging and integrates it into existing room and user-related operations. Updates standardize request parsing via parseBody(), refine missing-field validation in throwIfMissing() to allow falsy values, and restructure error handling with JSON responses and prefixed log tags across multiple functions.

Changes

Cohort / File(s) Summary
New track-activity function
functions/track-activity/src/main.js, functions/track-activity/src/utils.js, functions/track-activity/package.json, functions/track-activity/README.md
Added new track-activity backend function to log structured activity events (eventType, userId, metadata). Includes request validation, standardized error/success JSON responses, and utilities for parsing request bodies and validating required fields.
Utils standardization across all functions
functions/create-room/src/utils.js, functions/delete-room/src/utils.js, functions/join-room/src/utils.js, functions/database-cleaner/src/utils.js
Updated throwIfMissing() to treat fields as missing only when undefined or null (allowing other falsy values like 0, false, ""). Added new parseBody(body) utility for safe JSON parsing with standardized error messages.
create-room integration
functions/create-room/src/main.js
Integrated parseBody() for request parsing, refactored validation/error handling with prefixed log tags ([VALIDATION_ERROR], [ENV_ERROR]), standardized JSON response format (success, message, data), and added activity tracking via HTTP POST to track-activity endpoint for ROOM_CREATED events.
delete-room integration
functions/delete-room/src/main.js
Integrated parseBody() and updated error handling with structured tags ([VALIDATION_ERROR], [ENV_ERROR], [AUTH_ERROR]), fixed async participant deletion using Promise.all(), standardized response format, and added activity tracking for ROOM_DELETED events.
join-room integration
functions/join-room/src/main.js
Added unhandled fetch() call to track-activity endpoint for USER_JOINED events before request validation. Call executes outside existing error handling.
database-cleaner updates
functions/database-cleaner/src/main.js
Added try/catch wrapper for environment validation with JSON error responses, replaced context-based logging with structured tags ([APPWRITE_ROOM_CREATED], etc.), and standardized success response to JSON format.

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
Loading
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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Suggested labels

enhancement, gsoc

Poem

🐰 A new function hops into the scene,
Tracking activities with logs pristine!
From rooms created to users who join,
Events now flow in structured coin—
Better parsing, safer calls, what a gain! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Add activity tracking system for backend events' accurately and concisely describes the main objective of the pull request.
Linked Issues check ✅ Passed The pull request fulfills all coding requirements from issue #169: creates track-activity function [#169], implements parseBody/throwIfMissing validation [#169], standardizes API responses [#169], and integrates tracking into create-room/join-room/delete-room [#169].
Out of Scope Changes check ✅ Passed All changes are aligned with issue #169 objectives: new track-activity function, validation improvements across utils files, logging enhancements, and integration into specified handlers.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

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

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.

❤️ Share

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

@Shweta-281

Copy link
Copy Markdown
Author

Hi @M4dhav
I would like to work on implementing a centralized activity tracking system for backend events.

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 👍

@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: 8

🧹 Nitpick comments (1)
functions/track-activity/src/utils.js (1)

1-27: Extract the parsing/validation helpers once.

throwIfMissing and parseBody are now copied into functions/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

📥 Commits

Reviewing files that changed from the base of the PR and between 795f29b and 55f5e81.

⛔ Files ignored due to path filters (2)
  • functions/package-lock.json is excluded by !**/package-lock.json
  • functions/track-activity/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (12)
  • functions/create-room/src/main.js
  • functions/create-room/src/utils.js
  • functions/database-cleaner/src/main.js
  • functions/database-cleaner/src/utils.js
  • functions/delete-room/src/main.js
  • functions/delete-room/src/utils.js
  • functions/join-room/src/main.js
  • functions/join-room/src/utils.js
  • functions/track-activity/README.md
  • functions/track-activity/package.json
  • functions/track-activity/src/main.js
  • functions/track-activity/src/utils.js

Comment thread functions/create-room/src/main.js
Comment thread functions/database-cleaner/src/main.js
Comment thread functions/database-cleaner/src/main.js
Comment thread functions/delete-room/src/main.js
Comment thread functions/join-room/src/main.js
Comment thread functions/join-room/src/utils.js
Comment thread functions/track-activity/README.md
Comment thread functions/track-activity/src/main.js
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.

[FEATURE]: Add centralized activity tracking for backend events

1 participant