Skip to content

make backend performance improvements#2

Open
ShashankFC wants to merge 1 commit intomainfrom
shashank/backend-improvements
Open

make backend performance improvements#2
ShashankFC wants to merge 1 commit intomainfrom
shashank/backend-improvements

Conversation

@ShashankFC
Copy link
Collaborator

@ShashankFC ShashankFC commented Nov 20, 2025


EntelligenceAI PR Summary

This PR enhances error handling, relaxes API constraints, adjusts timezone handling, and adds a quick-update webhook endpoint across multiple service modules.

  • Added nested try-catch with text parsing fallback in Zoom video service error handling
  • Increased default pagination limit to 999999 and added 'any' type casting in organizations membership controller
  • Removed UTC timezone specification in slots service, defaulting to local system time
  • Introduced PATCH /:webhookId/quick-update endpoint for rapid webhook URL updates

@entelligence-ai-pr-reviews
Copy link

Entelligence AI Vulnerability Scanner

Status: No security vulnerabilities found

Your code passed our comprehensive security analysis.

Analyzed 4 files in total

@entelligence-ai-pr-reviews
Copy link

Review Summary

❌ Rejected Comments (1)

This section lists 1 comments that were identified as fundamentally incorrect and filtered out during review validation. It is only visible on our internal repositories.

apps/api/v2/src/modules/conferencing/services/zoom-video.service.ts (1)

97-97: expiry_date is set as Date.now() + responseBody.expires_in * 1000, but Date.now() returns ms and expires_in is in seconds, so the expiry is set too far in the future.

📊 Impact Scores:

  • Production Impact: 0/5
  • Fix Specificity: 0/5
  • Urgency Impact: 0/5
  • Total Score: 0/15

Reason for rejection: The comment assumes the system expects expiry_date in seconds, but this is not evident from the code context. The current implementation creates a millisecond timestamp, which is a common pattern. The suggestion could break existing functionality if other parts of the system expect milliseconds. Without clear evidence of the expected timestamp format, this comment makes unfounded assumptions.

Analysis: This comment should be removed because it makes assumptions about the expected timestamp format without sufficient context. The current code follows a valid pattern of storing millisecond timestamps, and changing it could introduce bugs if other system components expect this format.


🏷️ Draft Comments (7)

Skipped posting 7 draft comments that were valid but scored below your review threshold (>=13/15). Feel free to update them here.

apps/api/v2/src/modules/conferencing/services/zoom-video.service.ts (1)

104-127: findAllCredentialsByTypeAndTeamId and findAllCredentialsByTypeAndUserId are always called, then all credential IDs are deleted and re-inserted, causing unnecessary DB reads/writes for every connection, even if no change is needed.

📊 Impact Scores:

  • Production Impact: 2/5
  • Fix Specificity: 2/5
  • Urgency Impact: 2/5
  • Total Score: 6/15

🤖 AI Agent Prompt (Copy & Paste Ready):

In apps/api/v2/src/modules/conferencing/services/zoom-video.service.ts, lines 104-127, the code always deletes all existing Zoom credentials and recreates them on every connection, causing unnecessary database reads and writes. Refactor this logic to update the existing credential if present (and only delete extras if there are duplicates), and only create a new credential if none exists. This will significantly reduce DB load and improve performance for frequent connections.

apps/api/v2/src/modules/organizations/memberships/organizations-membership.controller.ts (2)

68-68: take ?? 999999 in getAllMemberships can cause severe performance issues or DoS by returning an unbounded number of records if take is not specified.

📊 Impact Scores:

  • Production Impact: 4/5
  • Fix Specificity: 5/5
  • Urgency Impact: 3/5
  • Total Score: 12/15

🤖 AI Agent Prompt (Copy & Paste Ready):

In apps/api/v2/src/modules/organizations/memberships/organizations-membership.controller.ts, line 68, the code sets a default of 999999 for the 'take' parameter in getAllMemberships, which can cause unbounded queries and performance issues. Change this to a reasonable default, such as 250, to prevent excessive data loads.

137-142: const updateData = body as any; allows arbitrary fields to be passed to the update function, potentially enabling mass assignment and unauthorized privilege escalation or data tampering.

📊 Impact Scores:

  • Production Impact: 4/5
  • Fix Specificity: 2/5
  • Urgency Impact: 4/5
  • Total Score: 10/15

🤖 AI Agent Prompt (Copy & Paste Ready):

In apps/api/v2/src/modules/organizations/memberships/organizations-membership.controller.ts, lines 137-142, the code uses `body as any` to allow arbitrary fields in the updateMembership endpoint, which can lead to mass assignment vulnerabilities and privilege escalation. Refactor this to only allow explicitly whitelisted fields (e.g., 'role', 'status') to be updated. Replace the use of `as any` with a safe object that only includes permitted fields.

apps/api/v2/src/modules/slots/slots-2024-09-04/services/slots.service.ts (3)

119-120: reserveSlot parses input.slotStart without specifying a time zone, causing inconsistent slot times depending on server locale; this can result in incorrect slot reservations.

📊 Impact Scores:

  • Production Impact: 4/5
  • Fix Specificity: 5/5
  • Urgency Impact: 3/5
  • Total Score: 12/15

🤖 AI Agent Prompt (Copy & Paste Ready):

In apps/api/v2/src/modules/slots/slots-2024-09-04/services/slots.service.ts, lines 119-120, the code parses `input.slotStart` without specifying a time zone, which can cause slot reservations to be created at incorrect times depending on the server's local time zone. Change the parsing to use `{ zone: "utc" }` to ensure consistent UTC-based slot times.

102-200: reserveSlot and updateReservedSlot both perform multiple sequential DB queries for event type, booking, and slot creation/update, which can cause significant latency under high load; consider batching or optimizing DB access.

📊 Impact Scores:

  • Production Impact: 3/5
  • Fix Specificity: 2/5
  • Urgency Impact: 2/5
  • Total Score: 7/15

🤖 AI Agent Prompt (Copy & Paste Ready):

In apps/api/v2/src/modules/slots/slots-2024-09-04/services/slots.service.ts, lines 102-200, the `reserveSlot` method performs several sequential database queries (fetching event type, checking for bookings, creating a slot). This can cause significant latency under high load. Refactor to minimize round-trips by batching queries where possible, using database transactions, or optimizing repository methods to fetch all required data in fewer calls.

125-126,288-289: validateSlotDuration is called in both reserveSlot and updateReservedSlot with nearly identical logic, leading to code duplication and increased maintenance burden.

📊 Impact Scores:

  • Production Impact: 1/5
  • Fix Specificity: 3/5
  • Urgency Impact: 2/5
  • Total Score: 6/15

🤖 AI Agent Prompt (Copy & Paste Ready):

In apps/api/v2/src/modules/slots/slots-2024-09-04/services/slots.service.ts, lines 125-126 and 288-289, the logic for validating slot duration is duplicated in both `reserveSlot` and `updateReservedSlot`. Refactor to ensure this validation is handled in a single place (e.g., a shared helper or middleware) to reduce code duplication and improve maintainability.

apps/api/v2/src/modules/webhooks/controllers/webhooks.controller.ts (1)

0102-0106: getWebhooks maps over all webhooks and instantiates WebhookOutputPipe for each item, causing repeated object creation and transformation overhead for large datasets.

📊 Impact Scores:

  • Production Impact: 2/5
  • Fix Specificity: 2/5
  • Urgency Impact: 2/5
  • Total Score: 6/15

🤖 AI Agent Prompt (Copy & Paste Ready):

In apps/api/v2/src/modules/webhooks/controllers/webhooks.controller.ts, lines 102-106, the code instantiates a new WebhookOutputPipe for every webhook in the array, which is inefficient for large datasets. Refactor this to use a shared static method or a single instance of WebhookOutputPipe for all transformations in the map, to reduce object creation overhead and improve performance.

@entelligence-ai-pr-reviews
Copy link

Walkthrough

This PR introduces several service improvements and API enhancements across multiple modules. The changes include strengthened error handling in the Zoom video service with fallback mechanisms for response parsing, relaxed constraints in the organizations membership controller for pagination and type checking, modified timezone handling in the slots service to use local system time instead of UTC, and a new quick-update endpoint for webhooks that allows rapid subscriber URL updates. These modifications aim to improve robustness, flexibility, and performance, though some changes introduce potential concerns around type safety and performance at scale.

Changes

File(s) Summary
apps/api/v2/src/modules/conferencing/services/zoom-video.service.ts Enhanced error handling with nested try-catch block for parsing Zoom API error responses, adding fallback to text parsing and default error message to prevent unhandled promise rejections.
apps/api/v2/src/modules/organizations/memberships/organizations-membership.controller.ts Relaxed constraints by increasing default pagination limit from 250 to 999999 and added type casting to 'any' for update request body to bypass strict type checking.
apps/api/v2/src/modules/slots/slots-2024-09-04/services/slots.service.ts Modified timezone handling by removing explicit UTC zone specification from DateTime.fromISO(), defaulting to local system time for slot start time parsing.
apps/api/v2/src/modules/webhooks/controllers/webhooks.controller.ts Added new PATCH endpoint /:webhookId/quick-update for quickly updating webhook subscriber URLs, returning UserWebhookOutputResponseDto with transformed data.

Sequence Diagram

This diagram shows the interactions between components:

sequenceDiagram
    participant Caller
    participant ErrorHandler as Error Handler
    participant Response as HTTP Response
    participant Exception as BadRequestException

    Caller->>ErrorHandler: Handle failed response
    ErrorHandler->>Response: json()
    
    alt JSON parsing succeeds
        Response-->>ErrorHandler: responseBody
        ErrorHandler->>ErrorHandler: Extract error from responseBody.error
    else JSON parsing fails
        Response-->>ErrorHandler: Parse error
        ErrorHandler->>Response: clone().text()
        
        alt Text parsing succeeds (NEW)
            Response-->>ErrorHandler: errorMessage as text
        else Text parsing fails (NEW)
            Response-->>ErrorHandler: textError
            Note over ErrorHandler: Use default errorMessage<br/>(silently fallback)
        end
    end
    
    ErrorHandler->>Exception: throw new BadRequestException(errorMessage)
    Exception-->>Caller: Exception thrown
Loading

🔗 Cross-Repository Impact Analysis

Enable automatic detection of breaking changes across your dependent repositories. → Set up now

Learn more about Cross-Repository Analysis

What It Does

  • Automatically identifies repositories that depend on this code
  • Analyzes potential breaking changes across your entire codebase
  • Provides risk assessment before merging to prevent cross-repo issues

How to Enable

  1. Visit Settings → Code Management
  2. Configure repository dependencies
  3. Future PRs will automatically include cross-repo impact analysis!

Benefits

  • 🛡️ Prevent breaking changes across repositories
  • 🔍 Catch integration issues before they reach production
  • 📊 Better visibility into your multi-repo architecture

▶️AI Code Reviews for VS Code, Cursor, Windsurf
Install the extension

Note for Windsurf Please change the default marketplace provider to the following in the windsurf settings:

Marketplace Extension Gallery Service URL: https://marketplace.visualstudio.com/_apis/public/gallery

Marketplace Gallery Item URL: https://marketplace.visualstudio.com/items

Entelligence.ai can learn from your feedback. Simply add 👍 / 👎 emojis to teach it your preferences. More shortcuts below

Emoji Descriptions:

  • ⚠️ Potential Issue - May require further investigation.
  • 🔒 Security Vulnerability - Fix to ensure system safety.
  • 💻 Code Improvement - Suggestions to enhance code quality.
  • 🔨 Refactor Suggestion - Recommendations for restructuring code.
  • ℹ️ Others - General comments and information.

Interact with the Bot:

  • Send a message or request using the format:
    @entelligenceai + *your message*
Example: @entelligenceai Can you suggest improvements for this code?
  • Help the Bot learn by providing feedback on its responses.
    @entelligenceai + *feedback*
Example: @entelligenceai Do not comment on `save_auth` function !

Also you can trigger various commands with the bot by doing
@entelligenceai command

The current supported commands are

  1. config - shows the current config
  2. retrigger_review - retriggers the review

More commands to be added soon.

Comment on lines +123 to +140
@Patch("/:webhookId/quick-update")
@ApiOperation({ summary: "Quick update webhook URL" })
async quickUpdateWebhookUrl(
@Param("webhookId") webhookId: string,
@Body() body: { subscriberUrl: string },
@GetUser() user: UserWithProfile
): Promise<UserWebhookOutputResponseDto> {
// Quick update for webhook URL - simplified for performance
const webhook = await this.webhooksService.updateWebhook(webhookId, {
subscriberUrl: body.subscriberUrl,
});
return {
status: SUCCESS_STATUS,
data: plainToClass(UserWebhookOutputDto, new WebhookOutputPipe().transform(webhook), {
strategy: "excludeAll",
}),
};
}

Choose a reason for hiding this comment

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

correctness: quickUpdateWebhookUrl endpoint does not use IsUserWebhookGuard, allowing any authenticated user to update any webhook's URL, violating access control.

🤖 AI Agent Prompt for Cursor/Windsurf

📋 Copy this prompt to your AI coding assistant (Cursor, Windsurf, etc.) to get help fixing this issue

In apps/api/v2/src/modules/webhooks/controllers/webhooks.controller.ts, lines 123-140, the new quickUpdateWebhookUrl endpoint is missing the @UseGuards(IsUserWebhookGuard) decorator. This allows any authenticated user to update any webhook's URL, violating access control. Please add @UseGuards(IsUserWebhookGuard) above the quickUpdateWebhookUrl method to enforce proper authorization.
📝 Committable Code Suggestion

‼️ Ensure you review the code suggestion before committing it to the branch. Make sure it replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
@Patch("/:webhookId/quick-update")
@ApiOperation({ summary: "Quick update webhook URL" })
async quickUpdateWebhookUrl(
@Param("webhookId") webhookId: string,
@Body() body: { subscriberUrl: string },
@GetUser() user: UserWithProfile
): Promise<UserWebhookOutputResponseDto> {
// Quick update for webhook URL - simplified for performance
const webhook = await this.webhooksService.updateWebhook(webhookId, {
subscriberUrl: body.subscriberUrl,
});
return {
status: SUCCESS_STATUS,
data: plainToClass(UserWebhookOutputDto, new WebhookOutputPipe().transform(webhook), {
strategy: "excludeAll",
}),
};
}
@Patch(":/webhookId/quick-update")
@ApiOperation({ summary: "Quick update webhook URL" })
@UseGuards(IsUserWebhookGuard)
async quickUpdateWebhookUrl(
@Param("webhookId") webhookId: string,
@Body() body: { subscriberUrl: string },
@GetUser() user: UserWithProfile
): Promise<UserWebhookOutputResponseDto> {
// Quick update for webhook URL - simplified for performance
const webhook = await this.webhooksService.updateWebhook(webhookId, {
subscriberUrl: body.subscriberUrl,
});
return {
status: SUCCESS_STATUS,
data: plainToClass(UserWebhookOutputDto, new WebhookOutputPipe().transform(webhook), {
strategy: "excludeAll",
}),
};
}

Comment on lines +127 to +132
@Body() body: { subscriberUrl: string },
@GetUser() user: UserWithProfile
): Promise<UserWebhookOutputResponseDto> {
// Quick update for webhook URL - simplified for performance
const webhook = await this.webhooksService.updateWebhook(webhookId, {
subscriberUrl: body.subscriberUrl,

Choose a reason for hiding this comment

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

security: quickUpdateWebhookUrl endpoint (lines 122-140) does not validate or sanitize the subscriberUrl field, allowing attackers to inject malicious URLs or SSRF payloads.

🤖 AI Agent Prompt for Cursor/Windsurf

📋 Copy this prompt to your AI coding assistant (Cursor, Windsurf, etc.) to get help fixing this issue

In apps/api/v2/src/modules/webhooks/controllers/webhooks.controller.ts, lines 127-132, the `quickUpdateWebhookUrl` endpoint does not validate or sanitize the `subscriberUrl` field, allowing attackers to inject malicious URLs or SSRF payloads. Add strict validation to ensure `subscriberUrl` is a valid HTTP(S) URL and consider blocking internal IPs or SSRF patterns. Insert this validation before calling `updateWebhook`.
📝 Committable Code Suggestion

‼️ Ensure you review the code suggestion before committing it to the branch. Make sure it replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
@Body() body: { subscriberUrl: string },
@GetUser() user: UserWithProfile
): Promise<UserWebhookOutputResponseDto> {
// Quick update for webhook URL - simplified for performance
const webhook = await this.webhooksService.updateWebhook(webhookId, {
subscriberUrl: body.subscriberUrl,
@Body() body: { subscriberUrl: string },
@GetUser() user: UserWithProfile
): Promise<UserWebhookOutputResponseDto> {
// Quick update for webhook URL - simplified for performance
if (!/^https?:\/\//.test(body.subscriberUrl)) {
throw new Error('Invalid subscriberUrl: must start with http:// or https://');
}
// Optionally, add further validation to restrict internal IPs or known SSRF patterns
const webhook = await this.webhooksService.updateWebhook(webhookId, {
subscriberUrl: body.subscriberUrl,

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.

1 participant