Skip to content

fix(bot): extractor errors, dynamic node path, race and timeout guards - #548

Merged
LucasSantana-Dev merged 2 commits into
mainfrom
fix/extractor-reliability
Apr 11, 2026
Merged

LucasSantana-Dev merged 2 commits into
mainfrom
fix/extractor-reliability

Conversation

@LucasSantana-Dev

@LucasSantana-Dev LucasSantana-Dev commented Apr 11, 2026 •

Copy link
Copy Markdown
Owner

Changes (Phase 1+2 of complete analysis plan)

playerFactory.ts

Extractor errors now visible
void player.extractors.loadMulti() + void initPlayDlAndRegisterYoutubei() silently swallowed all errors. Replaced with try/catch + errorLog and .catch(errorLog) — failures now appear in Sentry and logs.

Dynamic Node.js path for yt-dlp
--js-runtimes node:/usr/local/bin/node was hardcoded and fails on any system without Node.js at that exact path. Replaced with process.execPath (the actual running Node.js binary) — works on all platforms/deployments.

settled guard for close-before-data race
If yt-dlp crashes before emitting any output, proc.once('close') fires before proc.stdout.once('data'). Without the guard, the promise could be double-settled or resolve with a broken stream. Added let settled = false flag checked in all three listeners.

errorHandlers.ts

10s timeout on YouTube recovery search
queue.player.search() had no timeout — if the YouTube API doesn't respond, the player hangs indefinitely. Wrapped in Promise.race([search, timeoutAfter(10s)]), which resolves null on timeout and falls through to warnLog + skip.

Tests

  • Updated --js-runtimes assertion to use process.execPath
  • 1872 tests, 0 failures

Summary by CodeRabbit

  • Bug Fixes

    • Added a 10-second timeout for stream recovery to avoid indefinite waits.
    • Improved initialization error handling so failures are logged and don't block startup.
    • Fixed a race condition in stream processing to prevent double-settling and unexpected behavior.
    • Enhanced error logging and user notification when recovery fails.
  • Tests

    • Updated tests to use dynamic runtime paths and added coverage for timeout/recovery scenarios.

@vercel

vercel Bot commented Apr 11, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
lucky Ready Ready Preview, Comment Apr 11, 2026 0:26am

Request Review

@coderabbitai

coderabbitai Bot commented Apr 11, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Adds defensive handling around player streaming and extractor initialization: a 10s timeout for YouTube recovery searches, try/catch logging for extractor and bridge initialization, replaces a hardcoded yt-dlp JS runtime path with process.execPath, and prevents double-settlement in yt-dlp stream handling.

Changes

Cohort / File(s) Summary
Stream Recovery Timeout
packages/bot/src/handlers/player/errorHandlers.ts
Wraps the YouTube recovery search in a 10s Promise.race; on timeout or null result it logs a warning, notifies the channel, and calls queue.node.skip().
Extractor & Bridge Init Error Handling
packages/bot/src/handlers/player/playerFactory.ts
Surrounds player.extractors.loadMulti(...) and bridge init calls with try/catch; failures are logged with errorLog and no longer block async initialization.
yt-dlp Subprocess Args & Settlement Guard
packages/bot/src/handlers/player/playerFactory.ts, packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
Changes --js-runtimes to node:${process.execPath} and adds a settled guard to ensure the yt-dlp stream promise resolves/rejects only once; updates tests to expect dynamic process.execPath and adds a race-case test for early close vs late stdout.
Tests for Recovery Timeout
packages/bot/src/handlers/player/errorHandlers.spec.ts
Adds a unit test simulating the YouTube recovery returning null to exercise the timeout branch, asserting a skip and channel notification occur.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes all three main changes: extractor error handling, dynamic Node path resolution, and race/timeout guards.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/extractor-reliability

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.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/bot/src/handlers/player/playerFactory.ts (1)

184-187: ⚠️ Potential issue | 🔴 Critical

streamViaYtDlp can hang when process closes cleanly before first data chunk.

With the new settled guard, if close fires first with code === 0, Line 223 condition is false, timeout is cleared, and the Promise never resolves/rejects.

🛠️ Suggested fix
-        const timeout = setTimeout(() => {
-            proc.kill()
-            reject(new Error('yt-dlp: timed out waiting for stream start'))
-        }, 15_000)
+        const timeout = setTimeout(() => {
+            if (settled) return
+            settled = true
+            proc.kill()
+            reject(new Error('yt-dlp: timed out waiting for stream start'))
+        }, 15_000)
...
         proc.once('close', (code) => {
             if (settled) return
             settled = true
             clearTimeout(timeout)
-            if (code && code !== 0) {
-                const stderr = Buffer.concat(stderrChunks).toString().trim()
-                const reason = stderr ? ` — ${stderr.split('\n')[0]}` : ''
-                reject(new Error(`yt-dlp exited with code ${code}${reason}`))
-            }
+            const stderr = Buffer.concat(stderrChunks).toString().trim()
+            const reason = stderr ? ` — ${stderr.split('\n')[0]}` : ''
+            if (code && code !== 0) {
+                reject(new Error(`yt-dlp exited with code ${code}${reason}`))
+                return
+            }
+            reject(new Error(`yt-dlp exited before emitting stream data${reason}`))
         })

Also applies to: 194-197, 219-227

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bot/src/handlers/player/playerFactory.ts` around lines 184 - 187, In
streamViaYtDlp, the added "settled" guard lets the 15_000ms timeout be cleared
when the child 'close' event fires with code===0, leaving the promise neither
resolved nor rejected; update the 'close' handler logic so that when proc emits
'close' before any data has been emitted you still settle the promise (e.g.,
call reject(new Error('yt-dlp: closed before stream start')) or resolve with an
empty/failed sentinel) and ensure you clearTimeout(timeout) only after settling;
refer to the timeout variable, the 'close' event handler and the settled flag in
streamViaYtDlp to implement this consistent settle path (apply same fix to the
other similar blocks around lines handling timeout/close).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/bot/src/handlers/player/errorHandlers.ts`:
- Around line 236-247: The timeout created as searchTimeout (setTimeout) is
never cleared when queue.player.search(...) resolves first, leaving dangling
timers; change the logic to capture the timer id (e.g., timeoutId =
setTimeout(...)) and ensure you clearTimeout(timeoutId) when the search promise
resolves (or in a finally on the raced promise), so when
queue.player.search(...) wins the race you cancel the pending timeout; update
usage around searchTimeout, queue.player.search and searchResult accordingly to
avoid orphaned timers.

In `@packages/bot/src/handlers/player/playerFactory.ts`:
- Around line 38-42: The call to player.extractors.loadMulti(DefaultExtractors)
is async and its rejection is currently discarded by using void inside a
try/catch; change it to use
Promise.resolve(player.extractors.loadMulti(DefaultExtractors)).catch(err => {
... }) so both sync throws and async rejections are handled, and log failures
via infoLog/error logger similar to the existing initPlayDlAndRegisterYoutubei()
pattern; ensure you still proceed without throwing so one bad extractor doesn't
stop others.

---

Outside diff comments:
In `@packages/bot/src/handlers/player/playerFactory.ts`:
- Around line 184-187: In streamViaYtDlp, the added "settled" guard lets the
15_000ms timeout be cleared when the child 'close' event fires with code===0,
leaving the promise neither resolved nor rejected; update the 'close' handler
logic so that when proc emits 'close' before any data has been emitted you still
settle the promise (e.g., call reject(new Error('yt-dlp: closed before stream
start')) or resolve with an empty/failed sentinel) and ensure you
clearTimeout(timeout) only after settling; refer to the timeout variable, the
'close' event handler and the settled flag in streamViaYtDlp to implement this
consistent settle path (apply same fix to the other similar blocks around lines
handling timeout/close).
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 19faee52-dd60-4a04-8e5a-3f82c2fabf13

📥 Commits

Reviewing files that changed from the base of the PR and between e9f7cef and ecc8cce.

📒 Files selected for processing (3)
  • packages/bot/src/handlers/player/errorHandlers.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/playerFactory.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Quality Gates
  • GitHub Check: SonarCloud Scan
🧰 Additional context used
📓 Path-based instructions (15)
**/*.{js,jsx,ts,tsx,vue,html}

📄 CodeRabbit inference engine (.cursor/rules/accessibility-openness.mdc)

Provide accessible UI components using semantic HTML and ARIA attributes where necessary

Files:

  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/errorHandlers.ts
  • packages/bot/src/handlers/player/playerFactory.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/dependency-injection.mdc)

**/*.{ts,tsx,js,jsx}: Prefer constructor injection for classes that require dependencies
Avoid global mutable singletons unless necessary
Use explicit interfaces for external dependencies to make testing easier

**/*.{ts,tsx,js,jsx}: Include required references in PRs/code for non-trivial logic: TypeScript (official docs), MDN (JavaScript reference), and official docs for any runtime/framework/libraries used (e.g., Node.js, React) as applicable.
Before assuming behavior of an API, include the doc link and a ≤25-word quote when the change relies on it.

**/*.{ts,tsx,js,jsx}: Prefer named exports for clear usage and easier refactors in TypeScript/JavaScript
Keep import order consistent: external first, then internal modules
Remove dead code and unused imports

**/*.{ts,tsx,js,jsx}: Use PascalCase naming convention for React/UI components
Use camelCase naming convention for variables and functions
Use UPPER_SNAKE_CASE naming convention for constants
Maintain consistent import grouping and ordering within the project, keeping third-party imports separate from local imports
For external data sources (HTTP, database), always validate and sanitize input using type guards or schema validators

Implement TypeScript typecheck and linter in CI quality checks

**/*.{ts,tsx,js,jsx}: Use TypeScript for enhanced type safety
Implement error handling and error logging
Avoid commenting code unless extremely necessary - code should explain itself with descriptive names
Leave NO todos, placeholders or missing pieces in the code
Variables and functions must use camelCase
Constants must use UPPER_SNAKE_CASE
Use arrow functions for methods and computed properties
Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements
Maintain consistent import grouping/order: external imports first, then internal modules
Use named exports for clear usage and easier refactors
Always validate and sanitize external data (HTTP, DB) at the boundary using type guards ...

Files:

  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/errorHandlers.ts
  • packages/bot/src/handlers/player/playerFactory.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/error-handling.mdc)

**/*.{js,jsx,ts,tsx}: Never throw strings. Throw Error (or typed subclasses) with descriptive messages
Include causal error as cause when available for better debugging
Define clear, stable error codes (e.g., ERR_AUTH_EXPIRED, ERR_NETWORK_TIMEOUT)
Provide optional metadata (e.g., details, retryable, status, correlationId) in error objects
Use domain error classes per area (e.g., AuthenticationError, ValidationError, NetworkError)
Log errors with structure (message, code, stack, cause, correlationId, user context where appropriate)
Mark retryable vs nonRetryable errors where helpful for operations
Set timeouts and handle aborts/cancellations; avoid dangling requests in API/network code
Implement backoff for transient failures; avoid infinite retries
Map HTTP status → domain errors; 4xx vs 5xx behave differently (e.g., retry for 5xx/network)

**/*.{js,jsx,ts,tsx}: Use functional components with hooks in React/React Native. Avoid class components.
Keep components focused on a single responsibility; extract complex logic into custom hooks.
Keep state local when possible. Use Context/Zustand/Redux only when necessary for state management.
If props or state traverse more than 3 levels, consider using context or a feature-scoped store instead of prop drilling.
Use performance optimization techniques: React.memo, useMemo, useCallback, Suspense (web), and virtualization for long lists; avoid unnecessary re-renders.
Web accessibility: use semantic HTML, labels, focus management, keyboard navigation, and aria-* attributes as needed.
React Native accessibility: use accessibility props (accessible, accessibilityLabel), proper roles and labels.
Identify and extract repetitive UI components proactively to components/ with clear props and minimal coupling.
Web styles: prefer co-located styles or design system tokens; avoid global style leakage.
React Native styles: prefer StyleSheet.create, design tokens, and theme providers; avoid in...

Files:

  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/errorHandlers.ts
  • packages/bot/src/handlers/player/playerFactory.ts
**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/frontend.mdc)

**/*.{test,spec}.{js,jsx,ts,tsx}: Test behavior, not implementation. Prefer Testing Library utilities for testing React/React Native components.
For React Native tests: mock native modules and test component interactions and accessibility labels.

Files:

  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)

Introduce interfaces at module boundaries to enable testing and substitutions

**/*.{ts,tsx}: Avoid using any type in TypeScript. If unavoidable, use unknown with type guards and justify with a code comment
Prefer interface for defining public object shapes in TypeScript, use type for unions and utility types
Use TypeScript utility types such as Partial, Pick, Omit, Readonly, and Record when appropriate
Use I{Name} naming convention for interfaces in TypeScript
Use T{Name} naming convention for type aliases and utility types in TypeScript

**/*.{ts,tsx}: Prefer types over interfaces for most cases
Don't ever use any - type safety always
Avoid enums; use const objects instead
For complex types, create a separate file to declare them and import them
Avoid using any type; if unavoidable, use unknown with type guards and justify with code comment
Prefer interface for public API shapes; use type for unions and utility types
Use TypeScript utility types (Partial, Pick, Omit, Readonly, Record)

Files:

  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/errorHandlers.ts
  • packages/bot/src/handlers/player/playerFactory.ts
**/*.{test,spec}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)

**/*.{test,spec}.{ts,tsx,js,jsx}: Test behavior, not implementation details
Prefer unit tests for core logic; add integration tests at meaningful boundaries

Files:

  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
**/*.{test,spec}.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/testing-quality.mdc)

**/*.{test,spec}.{js,ts,jsx,tsx}: Use Jest + a React testing library for unit and component tests as applicable
Test behavior, not implementation details

Files:

  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/documentation.mdc)

**/*.{js,ts,tsx,jsx}: Minimize comments in code; explain the 'why' when non-obvious, let code express the 'what' through clear naming
Document trade-offs briefly when deviating from ideal patterns

**/*.{js,ts,tsx,jsx}: Store secrets, ports, and hosts in environment variables (.env, .env.example) and never hardcode them
Avoid redundant or decorative AI comments; code should be self-explanatory and only commented when logic is non-obvious; prefer refactoring over lengthy comments

Files:

  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/errorHandlers.ts
  • packages/bot/src/handlers/player/playerFactory.ts
packages/bot/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-discord-bot.mdc)

packages/bot/**/*.{ts,tsx}: Use useMainPlayer() from discord-player to access the player instance; do not instantiate player directly
Do not duplicate queue or player state outside Discord Player; use shared services from @lucky/shared for persistent data like track history and session information
Use errorLog and debugLog from @lucky/shared/utils for logging throughout the bot package
Use embed and reply utilities from @lucky/shared for consistent message formatting and error sanitization across the bot
Use services from @lucky/shared (DatabaseService, Redis client) for database and cache access; do not instantiate Prisma or Redis directly in the bot package

Files:

  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/errorHandlers.ts
  • packages/bot/src/handlers/player/playerFactory.ts
packages/bot/src/handlers/player/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-discord-bot.mdc)

Track handling, errors, and lifecycle must be managed through dedicated handlers in packages/bot/src/handlers/player/ (trackHandlers, errorHandlers, lifecycleHandlers)

Files:

  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/errorHandlers.ts
  • packages/bot/src/handlers/player/playerFactory.ts
packages/bot/**

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

The bot package depends on shared and contains Discord bot commands and player handlers using Discord.js and Discord Player

Files:

  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/errorHandlers.ts
  • packages/bot/src/handlers/player/playerFactory.ts
**/*.{js,mjs,ts,mts}

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

Use Node.js version ≥22 with ESM (ECMAScript modules) only; no CommonJS

Files:

  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/errorHandlers.ts
  • packages/bot/src/handlers/player/playerFactory.ts
**/*.{spec,test}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/quality.mdc)

**/*.{spec,test}.{ts,tsx,js,jsx}: Use Jest for unit and integration tests
Test behavior, not implementation details
Run unit, integration tests, and coverage report in CI quality checks

Files:

  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
**/*.spec.ts

📄 CodeRabbit inference engine (.cursor/rules/quality.mdc)

Unit tests must use naming convention *.spec.ts

Files:

  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
packages/bot/src/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/subagent-discord.mdc)

Use @lucky/shared for database, Redis, logging, and embed utilities instead of implementing them locally

Files:

  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/errorHandlers.ts
  • packages/bot/src/handlers/player/playerFactory.ts
🔇 Additional comments (3)
packages/bot/src/handlers/player/playerFactory.bridge.spec.ts (1)

254-263: Good update to make the spawn assertion environment-agnostic.

Switching the expected runtime argument to node:${process.execPath} correctly tracks the production change and avoids host-specific test brittleness.

packages/bot/src/handlers/player/playerFactory.ts (2)

54-63: Nice: async extractor init failures are now observable.

Attaching .catch(errorLog) to initPlayDlAndRegisterYoutubei(player) removes silent failures and improves operational visibility.


175-179: Good portability fix for yt-dlp JS runtime.

Using node:${process.execPath} instead of a hardcoded absolute path is the right cross-platform/deployment-safe approach.

Comment on lines +236 to +247
// Timeout guard: if YouTube search hangs (no response in 10s), skip the
// track rather than blocking the player indefinitely.
const searchTimeout = new Promise<null>((resolve) =>
setTimeout(() => resolve(null), 10_000),
)
const searchResult = await Promise.race([
queue.player.search(currentTrack.title, {
requestedBy: requestedByUser,
searchEngine: QueryType.YOUTUBE_SEARCH,
}),
searchTimeout,
])

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Clear the timeout when search wins the race.

Line 238 creates a timer that isn’t canceled when queue.player.search(...) resolves first. That leaves unnecessary pending timers during recovery bursts.

🔧 Suggested fix
-    const searchTimeout = new Promise<null>((resolve) =>
-        setTimeout(() => resolve(null), 10_000),
-    )
-    const searchResult = await Promise.race([
-        queue.player.search(currentTrack.title, {
-            requestedBy: requestedByUser,
-            searchEngine: QueryType.YOUTUBE_SEARCH,
-        }),
-        searchTimeout,
-    ])
+    let timeoutId: ReturnType<typeof setTimeout> | undefined
+    const searchTimeout = new Promise<null>((resolve) => {
+        timeoutId = setTimeout(() => resolve(null), 10_000)
+    })
+    const searchResult = await Promise.race([
+        queue.player.search(currentTrack.title, {
+            requestedBy: requestedByUser,
+            searchEngine: QueryType.YOUTUBE_SEARCH,
+        }),
+        searchTimeout,
+    ]).finally(() => {
+        if (timeoutId) clearTimeout(timeoutId)
+    })
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bot/src/handlers/player/errorHandlers.ts` around lines 236 - 247,
The timeout created as searchTimeout (setTimeout) is never cleared when
queue.player.search(...) resolves first, leaving dangling timers; change the
logic to capture the timer id (e.g., timeoutId = setTimeout(...)) and ensure you
clearTimeout(timeoutId) when the search promise resolves (or in a finally on the
raced promise), so when queue.player.search(...) wins the race you cancel the
pending timeout; update usage around searchTimeout, queue.player.search and
searchResult accordingly to avoid orphaned timers.

Comment on lines +38 to +42
// Register DefaultExtractors synchronously (loadMulti is sync in this version).
// Errors are caught so a single bad extractor does not block the others.
try {
void player.extractors.loadMulti(DefaultExtractors)
infoLog({

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🌐 Web query:

In the discord-player version used by this repo, what is the return type/behavior of player.extractors.loadMulti(...)? Is it synchronous or Promise-based?

💡 Result:

In discord-player (latest version 7.2.0 as of 2026-03), player.extractors.loadMulti(...) is a Promise-based asynchronous method. It returns Promise<{ success: boolean; error: null }>. This is consistently shown in official documentation and API references, where it is always awaited in usage examples (e.g., await player.extractors.loadMulti(DefaultExtractors);). It loads multiple extractors from a bundle (array of extractor classes), optionally with per-extractor options, and returns a success indicator object after asynchronously registering and activating them.

Citations:


🏁 Script executed:

cd /tmp && find . -name "package.json" -type f 2>/dev/null | head -5

Repository: LucasSantana-Dev/Lucky

Length of output: 48


🏁 Script executed:

# Check for package.json files and discord-player version
if [ -f "package.json" ]; then
  echo "=== Root package.json ===" 
  cat package.json | grep -A2 -B2 "discord-player" || echo "discord-player not in root"
fi

# Check in packages/bot
if [ -f "packages/bot/package.json" ]; then
  echo "=== packages/bot/package.json ===" 
  cat packages/bot/package.json | grep -A2 -B2 "discord-player" || echo "discord-player not in bot"
fi

Repository: LucasSantana-Dev/Lucky

Length of output: 753


🏁 Script executed:

# Read playerFactory.ts lines 30-65 to see context
if [ -f "packages/bot/src/handlers/player/playerFactory.ts" ]; then
  echo "=== playerFactory.ts context (lines 30-65) ==="
  sed -n '30,65p' packages/bot/src/handlers/player/playerFactory.ts
fi

Repository: LucasSantana-Dev/Lucky

Length of output: 1266


🏁 Script executed:

# Search for unhandled rejection handlers or global error handlers
rg "unhandledRejection|on\(.error|process\.on\(" packages/bot/src --type ts -A3 | head -30

Repository: LucasSantana-Dev/Lucky

Length of output: 2400


loadMulti rejection bypasses try/catch — promise rejection can be unhandled.

Lines 38–42 wrap void player.extractors.loadMulti(DefaultExtractors) in try/catch. However, discord-player 7.1.0's loadMulti is Promise-based (async); it returns Promise<{ success: boolean; error: null }>. The void discards this Promise, and try/catch does not catch Promise rejections. Any extractor load failure is silently swallowed, degrading music features without logging.

Use Promise.resolve(loadResult).catch(...) to handle both sync throws and async rejections, consistent with the pattern already used for initPlayDlAndRegisterYoutubei() on lines 54–63.

🔧 Correct pattern (handles sync throw + async reject)
     try {
-        void player.extractors.loadMulti(DefaultExtractors)
+        const loadResult = player.extractors.loadMulti(DefaultExtractors)
+        void Promise.resolve(loadResult).catch((error) => {
+            errorLog({
+                message:
+                    'DefaultExtractors failed to load — music features degraded',
+                error,
+            })
+        })
         infoLog({
             message:
                 'Extractors: SoundCloud, Spotify, Apple Music, Vimeo, Attachments',
         })
     } catch (error) {
         errorLog({
             message:
                 'DefaultExtractors failed to load — music features degraded',
             error,
         })
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Register DefaultExtractors synchronously (loadMulti is sync in this version).
// Errors are caught so a single bad extractor does not block the others.
try {
void player.extractors.loadMulti(DefaultExtractors)
infoLog({
// Register DefaultExtractors synchronously (loadMulti is sync in this version).
// Errors are caught so a single bad extractor does not block the others.
try {
const loadResult = player.extractors.loadMulti(DefaultExtractors)
void Promise.resolve(loadResult).catch((error) => {
errorLog({
message:
'DefaultExtractors failed to load — music features degraded',
error,
})
})
infoLog({
message:
'Extractors: SoundCloud, Spotify, Apple Music, Vimeo, Attachments',
})
} catch (error) {
errorLog({
message:
'DefaultExtractors failed to load — music features degraded',
error,
})
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bot/src/handlers/player/playerFactory.ts` around lines 38 - 42, The
call to player.extractors.loadMulti(DefaultExtractors) is async and its
rejection is currently discarded by using void inside a try/catch; change it to
use Promise.resolve(player.extractors.loadMulti(DefaultExtractors)).catch(err =>
{ ... }) so both sync throws and async rejections are handled, and log failures
via infoLog/error logger similar to the existing initPlayDlAndRegisterYoutubei()
pattern; ensure you still proceed without throwing so one bad extractor doesn't
stop others.

@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.

🧹 Nitpick comments (1)
packages/bot/src/handlers/player/errorHandlers.spec.ts (1)

550-583: Test intent says “timeout”, but it currently only tests immediate null search result.

mockResolvedValue(null) skips validating the actual 10s Promise.race timeout path. Consider simulating a never-resolving search and advancing fake timers to assert true timeout behavior.

Suggested test adjustment
 it('skips and notifies when YouTube search times out (Promise.race null)', async () => {
-    // Search returns null (simulates timeout resolution) — recovery must
-    // treat it the same as no results.
+    jest.useFakeTimers()
     const { queueHandlers } = createPlayerWithHandlers()
     providerFromTrackMock.mockReturnValue('youtube')
     analyzeYouTubeErrorMock.mockReturnValue({ isParserError: false })
 
     const channelSendMock = jest.fn().mockResolvedValue({})
+    const never = new Promise<never>(() => {})
     const queue = {
       ...
-      // search returns null — simulates the timeout branch resolving null
-      player: { search: jest.fn().mockResolvedValue(null) },
+      // hangs forever; timeout branch should resolve recovery path
+      player: { search: jest.fn().mockReturnValue(never) },
       ...
     }
 
     ;(queueHandlers.playerError as PlayerErrorHandler)(
       queue as any,
       new Error('Could not extract stream'),
     )
-    await flushPromises()
+    await jest.advanceTimersByTimeAsync(10_000)
+    await flushPromises()
 
     expect(queue.node.skip).toHaveBeenCalled()
     expect(channelSendMock).toHaveBeenCalled()
+    jest.useRealTimers()
 })
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bot/src/handlers/player/errorHandlers.spec.ts` around lines 550 -
583, The test currently simulates a timeout by having queue.player.search return
null (mockResolvedValue(null)) but should simulate a never-resolving promise and
advance fake timers to exercise the actual Promise.race timeout path; change the
search mock in the "skips and notifies when YouTube search times out
(Promise.race null)" test to return new Promise(()=>{}) (e.g.,
mockImplementation(() => new Promise(()=>{}))), enable Jest fake timers
(jest.useFakeTimers()), advance timers by the timeout duration
(jest.advanceTimersByTime(10000) or the configured timeout), then await
flushPromises and restore timers (jest.useRealTimers()) before asserting that
queue.node.skip and channelSendMock were called, leaving the rest of the test
flow (providerFromTrackMock, analyzeYouTubeErrorMock, queueHandlers.playerError
invocation) unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/bot/src/handlers/player/errorHandlers.spec.ts`:
- Around line 550-583: The test currently simulates a timeout by having
queue.player.search return null (mockResolvedValue(null)) but should simulate a
never-resolving promise and advance fake timers to exercise the actual
Promise.race timeout path; change the search mock in the "skips and notifies
when YouTube search times out (Promise.race null)" test to return new
Promise(()=>{}) (e.g., mockImplementation(() => new Promise(()=>{}))), enable
Jest fake timers (jest.useFakeTimers()), advance timers by the timeout duration
(jest.advanceTimersByTime(10000) or the configured timeout), then await
flushPromises and restore timers (jest.useRealTimers()) before asserting that
queue.node.skip and channelSendMock were called, leaving the rest of the test
flow (providerFromTrackMock, analyzeYouTubeErrorMock, queueHandlers.playerError
invocation) unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 69a55dd2-ff5b-41c7-872b-dcea6f440b76

📥 Commits

Reviewing files that changed from the base of the PR and between ecc8cce and c94ca1d.

📒 Files selected for processing (3)
  • packages/bot/src/handlers/player/errorHandlers.spec.ts
  • packages/bot/src/handlers/player/errorHandlers.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/bot/src/handlers/player/errorHandlers.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: SonarCloud Scan
  • GitHub Check: Quality Gates
🧰 Additional context used
📓 Path-based instructions (15)
**/*.{js,jsx,ts,tsx,vue,html}

📄 CodeRabbit inference engine (.cursor/rules/accessibility-openness.mdc)

Provide accessible UI components using semantic HTML and ARIA attributes where necessary

Files:

  • packages/bot/src/handlers/player/errorHandlers.spec.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/dependency-injection.mdc)

**/*.{ts,tsx,js,jsx}: Prefer constructor injection for classes that require dependencies
Avoid global mutable singletons unless necessary
Use explicit interfaces for external dependencies to make testing easier

**/*.{ts,tsx,js,jsx}: Include required references in PRs/code for non-trivial logic: TypeScript (official docs), MDN (JavaScript reference), and official docs for any runtime/framework/libraries used (e.g., Node.js, React) as applicable.
Before assuming behavior of an API, include the doc link and a ≤25-word quote when the change relies on it.

**/*.{ts,tsx,js,jsx}: Prefer named exports for clear usage and easier refactors in TypeScript/JavaScript
Keep import order consistent: external first, then internal modules
Remove dead code and unused imports

**/*.{ts,tsx,js,jsx}: Use PascalCase naming convention for React/UI components
Use camelCase naming convention for variables and functions
Use UPPER_SNAKE_CASE naming convention for constants
Maintain consistent import grouping and ordering within the project, keeping third-party imports separate from local imports
For external data sources (HTTP, database), always validate and sanitize input using type guards or schema validators

Implement TypeScript typecheck and linter in CI quality checks

**/*.{ts,tsx,js,jsx}: Use TypeScript for enhanced type safety
Implement error handling and error logging
Avoid commenting code unless extremely necessary - code should explain itself with descriptive names
Leave NO todos, placeholders or missing pieces in the code
Variables and functions must use camelCase
Constants must use UPPER_SNAKE_CASE
Use arrow functions for methods and computed properties
Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements
Maintain consistent import grouping/order: external imports first, then internal modules
Use named exports for clear usage and easier refactors
Always validate and sanitize external data (HTTP, DB) at the boundary using type guards ...

Files:

  • packages/bot/src/handlers/player/errorHandlers.spec.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/error-handling.mdc)

**/*.{js,jsx,ts,tsx}: Never throw strings. Throw Error (or typed subclasses) with descriptive messages
Include causal error as cause when available for better debugging
Define clear, stable error codes (e.g., ERR_AUTH_EXPIRED, ERR_NETWORK_TIMEOUT)
Provide optional metadata (e.g., details, retryable, status, correlationId) in error objects
Use domain error classes per area (e.g., AuthenticationError, ValidationError, NetworkError)
Log errors with structure (message, code, stack, cause, correlationId, user context where appropriate)
Mark retryable vs nonRetryable errors where helpful for operations
Set timeouts and handle aborts/cancellations; avoid dangling requests in API/network code
Implement backoff for transient failures; avoid infinite retries
Map HTTP status → domain errors; 4xx vs 5xx behave differently (e.g., retry for 5xx/network)

**/*.{js,jsx,ts,tsx}: Use functional components with hooks in React/React Native. Avoid class components.
Keep components focused on a single responsibility; extract complex logic into custom hooks.
Keep state local when possible. Use Context/Zustand/Redux only when necessary for state management.
If props or state traverse more than 3 levels, consider using context or a feature-scoped store instead of prop drilling.
Use performance optimization techniques: React.memo, useMemo, useCallback, Suspense (web), and virtualization for long lists; avoid unnecessary re-renders.
Web accessibility: use semantic HTML, labels, focus management, keyboard navigation, and aria-* attributes as needed.
React Native accessibility: use accessibility props (accessible, accessibilityLabel), proper roles and labels.
Identify and extract repetitive UI components proactively to components/ with clear props and minimal coupling.
Web styles: prefer co-located styles or design system tokens; avoid global style leakage.
React Native styles: prefer StyleSheet.create, design tokens, and theme providers; avoid in...

Files:

  • packages/bot/src/handlers/player/errorHandlers.spec.ts
**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/frontend.mdc)

**/*.{test,spec}.{js,jsx,ts,tsx}: Test behavior, not implementation. Prefer Testing Library utilities for testing React/React Native components.
For React Native tests: mock native modules and test component interactions and accessibility labels.

Files:

  • packages/bot/src/handlers/player/errorHandlers.spec.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)

Introduce interfaces at module boundaries to enable testing and substitutions

**/*.{ts,tsx}: Avoid using any type in TypeScript. If unavoidable, use unknown with type guards and justify with a code comment
Prefer interface for defining public object shapes in TypeScript, use type for unions and utility types
Use TypeScript utility types such as Partial, Pick, Omit, Readonly, and Record when appropriate
Use I{Name} naming convention for interfaces in TypeScript
Use T{Name} naming convention for type aliases and utility types in TypeScript

**/*.{ts,tsx}: Prefer types over interfaces for most cases
Don't ever use any - type safety always
Avoid enums; use const objects instead
For complex types, create a separate file to declare them and import them
Avoid using any type; if unavoidable, use unknown with type guards and justify with code comment
Prefer interface for public API shapes; use type for unions and utility types
Use TypeScript utility types (Partial, Pick, Omit, Readonly, Record)

Files:

  • packages/bot/src/handlers/player/errorHandlers.spec.ts
**/*.{test,spec}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)

**/*.{test,spec}.{ts,tsx,js,jsx}: Test behavior, not implementation details
Prefer unit tests for core logic; add integration tests at meaningful boundaries

Files:

  • packages/bot/src/handlers/player/errorHandlers.spec.ts
**/*.{test,spec}.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/testing-quality.mdc)

**/*.{test,spec}.{js,ts,jsx,tsx}: Use Jest + a React testing library for unit and component tests as applicable
Test behavior, not implementation details

Files:

  • packages/bot/src/handlers/player/errorHandlers.spec.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/documentation.mdc)

**/*.{js,ts,tsx,jsx}: Minimize comments in code; explain the 'why' when non-obvious, let code express the 'what' through clear naming
Document trade-offs briefly when deviating from ideal patterns

**/*.{js,ts,tsx,jsx}: Store secrets, ports, and hosts in environment variables (.env, .env.example) and never hardcode them
Avoid redundant or decorative AI comments; code should be self-explanatory and only commented when logic is non-obvious; prefer refactoring over lengthy comments

Files:

  • packages/bot/src/handlers/player/errorHandlers.spec.ts
packages/bot/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-discord-bot.mdc)

packages/bot/**/*.{ts,tsx}: Use useMainPlayer() from discord-player to access the player instance; do not instantiate player directly
Do not duplicate queue or player state outside Discord Player; use shared services from @lucky/shared for persistent data like track history and session information
Use errorLog and debugLog from @lucky/shared/utils for logging throughout the bot package
Use embed and reply utilities from @lucky/shared for consistent message formatting and error sanitization across the bot
Use services from @lucky/shared (DatabaseService, Redis client) for database and cache access; do not instantiate Prisma or Redis directly in the bot package

Files:

  • packages/bot/src/handlers/player/errorHandlers.spec.ts
packages/bot/src/handlers/player/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-discord-bot.mdc)

Track handling, errors, and lifecycle must be managed through dedicated handlers in packages/bot/src/handlers/player/ (trackHandlers, errorHandlers, lifecycleHandlers)

Files:

  • packages/bot/src/handlers/player/errorHandlers.spec.ts
packages/bot/**

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

The bot package depends on shared and contains Discord bot commands and player handlers using Discord.js and Discord Player

Files:

  • packages/bot/src/handlers/player/errorHandlers.spec.ts
**/*.{js,mjs,ts,mts}

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

Use Node.js version ≥22 with ESM (ECMAScript modules) only; no CommonJS

Files:

  • packages/bot/src/handlers/player/errorHandlers.spec.ts
**/*.{spec,test}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/quality.mdc)

**/*.{spec,test}.{ts,tsx,js,jsx}: Use Jest for unit and integration tests
Test behavior, not implementation details
Run unit, integration tests, and coverage report in CI quality checks

Files:

  • packages/bot/src/handlers/player/errorHandlers.spec.ts
**/*.spec.ts

📄 CodeRabbit inference engine (.cursor/rules/quality.mdc)

Unit tests must use naming convention *.spec.ts

Files:

  • packages/bot/src/handlers/player/errorHandlers.spec.ts
packages/bot/src/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/subagent-discord.mdc)

Use @lucky/shared for database, Redis, logging, and embed utilities instead of implementing them locally

Files:

  • packages/bot/src/handlers/player/errorHandlers.spec.ts

@sonarqubecloud

Copy link
Copy Markdown

@LucasSantana-Dev
LucasSantana-Dev merged commit 15baba5 into main Apr 11, 2026
12 checks passed
@LucasSantana-Dev
LucasSantana-Dev deleted the fix/extractor-reliability branch April 11, 2026 00:30
LucasSantana-Dev added a commit that referenced this pull request May 13, 2026
#548)

* fix(bot): extractor errors, dynamic node path, race and timeout guards

* test(bot): race guard, search timeout, timer unref for open handles

This branch was successfully deployed

1 active deployment
Preview — c94ca1de Deployed Apr 11, 2026 by vercel[bot]
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.

1 participant