Repository navigation
fix(bot): surface stream failures to discord and capture yt-dlp stderr - #546
Conversation
- errorHandlers: notify the discord text channel with an error embed when stream extraction fails and all recovery paths are exhausted. user previously saw nothing — the bot silently skipped the track. - playerFactory: capture yt-dlp stderr and include the first line in the rejection message. adds structured 'stages' array to bridge- exhausted error logs. - tests: add stderr to spawn mocks, test stderr inclusion in rejection.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Warning Rate limit exceeded
Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 6 minutes and 26 seconds. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughThis PR enhances error handling and logging in the player module. It adds Discord channel notifications when stream extraction fails, improves yt-dlp error reporting by capturing stderr output, and expands logging payloads to include more diagnostic details during stream recovery failures. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested labels
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 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 |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/bot/src/handlers/player/errorHandlers.ts (1)
4-4: Use shared embed utility in bot handlers for consistency.This handler now imports
createErrorEmbedfrom a local bot utility. In this package, embed/reply formatting should come from shared utilities for consistent sanitization/format across handlers.As per coding guidelines, "Use embed and reply utilities from
@lucky/sharedfor consistent message formatting and error sanitization across the bot."Also applies to: 36-39
🤖 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` at line 4, Replace the local embed import with the shared utility: remove the import from '../../utils/general/embeds' and import createErrorEmbed from '@lucky/shared' instead, then update the usages in this file (including the error handler usages around lines 36-39) to use that shared createErrorEmbed so formatting/sanitization comes from the shared embed/reply utilities rather than the local bot utility.
🤖 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 227-233: The notifyChannelStreamFailed call is awaited before
skipping which blocks recovery; change the order to call queue.node.skip()
immediately (use queue.node.skip() before notifyChannelStreamFailed), then fire
notifyChannelStreamFailed as a best-effort non-blocking operation (do not
await), wrapping it in a try/catch and apply a short timeout/AbortSignal to
bound network I/O; update all identical sites (the blocks around
notifyChannelStreamFailed, queue.node.skip, warnLog at the referenced ranges) so
skip is immediate and notification failures are handled/logged but do not
prevent playback recovery.
---
Nitpick comments:
In `@packages/bot/src/handlers/player/errorHandlers.ts`:
- Line 4: Replace the local embed import with the shared utility: remove the
import from '../../utils/general/embeds' and import createErrorEmbed from
'@lucky/shared' instead, then update the usages in this file (including the
error handler usages around lines 36-39) to use that shared createErrorEmbed so
formatting/sanitization comes from the shared embed/reply utilities rather than
the local bot utility.
🪄 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: a414adb4-f585-4111-b16f-aa4c0ca870f4
📒 Files selected for processing (3)
packages/bot/src/handlers/player/errorHandlers.tspackages/bot/src/handlers/player/playerFactory.bridge.spec.tspackages/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/errorHandlers.tspackages/bot/src/handlers/player/playerFactory.bridge.spec.tspackages/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 validatorsImplement 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.tspackages/bot/src/handlers/player/playerFactory.bridge.spec.tspackages/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. ThrowError(or typed subclasses) with descriptive messages
Include causal error ascausewhen 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)
MarkretryablevsnonRetryableerrors 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, andaria-*attributes as needed.
React Native accessibility: use accessibility props (accessible,accessibilityLabel), proper roles and labels.
Identify and extract repetitive UI components proactively tocomponents/with clear props and minimal coupling.
Web styles: prefer co-located styles or design system tokens; avoid global style leakage.
React Native styles: preferStyleSheet.create, design tokens, and theme providers; avoid in...
Files:
packages/bot/src/handlers/player/errorHandlers.tspackages/bot/src/handlers/player/playerFactory.bridge.spec.tspackages/bot/src/handlers/player/playerFactory.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)
Introduce interfaces at module boundaries to enable testing and substitutions
**/*.{ts,tsx}: Avoid usinganytype in TypeScript. If unavoidable, useunknownwith type guards and justify with a code comment
Preferinterfacefor defining public object shapes in TypeScript, usetypefor unions and utility types
Use TypeScript utility types such asPartial,Pick,Omit,Readonly, andRecordwhen appropriate
UseI{Name}naming convention for interfaces in TypeScript
UseT{Name}naming convention for type aliases and utility types in TypeScript
**/*.{ts,tsx}: Prefer types over interfaces for most cases
Don't ever useany- type safety always
Avoid enums; use const objects instead
For complex types, create a separate file to declare them and import them
Avoid usinganytype; if unavoidable, useunknownwith type guards and justify with code comment
Preferinterfacefor public API shapes; usetypefor unions and utility types
Use TypeScript utility types (Partial, Pick, Omit, Readonly, Record)
Files:
packages/bot/src/handlers/player/errorHandlers.tspackages/bot/src/handlers/player/playerFactory.bridge.spec.tspackages/bot/src/handlers/player/playerFactory.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.tspackages/bot/src/handlers/player/playerFactory.bridge.spec.tspackages/bot/src/handlers/player/playerFactory.ts
packages/bot/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/lucky-discord-bot.mdc)
packages/bot/**/*.{ts,tsx}: UseuseMainPlayer()fromdiscord-playerto access the player instance; do not instantiate player directly
Do not duplicate queue or player state outside Discord Player; use shared services from@lucky/sharedfor persistent data like track history and session information
UseerrorLoganddebugLogfrom@lucky/shared/utilsfor logging throughout the bot package
Use embed and reply utilities from@lucky/sharedfor 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.tspackages/bot/src/handlers/player/playerFactory.bridge.spec.tspackages/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/errorHandlers.tspackages/bot/src/handlers/player/playerFactory.bridge.spec.tspackages/bot/src/handlers/player/playerFactory.ts
packages/bot/**
📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)
The
botpackage depends onsharedand contains Discord bot commands and player handlers using Discord.js and Discord Player
Files:
packages/bot/src/handlers/player/errorHandlers.tspackages/bot/src/handlers/player/playerFactory.bridge.spec.tspackages/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/errorHandlers.tspackages/bot/src/handlers/player/playerFactory.bridge.spec.tspackages/bot/src/handlers/player/playerFactory.ts
packages/bot/src/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/subagent-discord.mdc)
Use
@lucky/sharedfor database, Redis, logging, and embed utilities instead of implementing them locally
Files:
packages/bot/src/handlers/player/errorHandlers.tspackages/bot/src/handlers/player/playerFactory.bridge.spec.tspackages/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
**/*.{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
**/*.{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
🔇 Additional comments (3)
packages/bot/src/handlers/player/playerFactory.bridge.spec.ts (1)
52-75: Good test coverage expansion for yt-dlp stderr diagnostics.These changes correctly model
stderrin spawn mocks and validate user-visible rejection behavior without over-coupling to implementation details.Also applies to: 308-318, 322-326
packages/bot/src/handlers/player/playerFactory.ts (2)
286-308: Structured bridge-exhaustion logging is a solid improvement.Including
cleanedTitle,url, and explicitstagesmaterially improves incident triage for stream fallback failures.
171-174: Bound stderr capture to the first line instead of buffering all chunks.The code currently accumulates full stderr, then uses only line 1. Capturing just the first line avoids unnecessary memory growth on noisy failures.
♻️ Proposed bounded capture
- const stderrChunks: Buffer[] = [] - proc.stderr!.on('data', (chunk: Buffer) => stderrChunks.push(chunk)) + let stderrFirstLine = '' + let stderrBuffer = '' + proc.stderr!.on('data', (chunk: Buffer) => { + if (stderrFirstLine) return + stderrBuffer += chunk.toString('utf8') + const newlineIndex = stderrBuffer.indexOf('\n') + if (newlineIndex >= 0) { + stderrFirstLine = stderrBuffer.slice(0, newlineIndex).trim() + return + } + if (stderrBuffer.length > 512) { + stderrFirstLine = stderrBuffer.slice(0, 512).trim() + } + }) @@ - const stderr = Buffer.concat(stderrChunks).toString().trim() - const reason = stderr ? ` — ${stderr.split('\n')[0]}` : '' + const reason = stderrFirstLine ? ` — ${stderrFirstLine}` : '' reject(new Error(`yt-dlp exited with code ${code}${reason}`))
| warnLog({ | ||
| message: 'Stream failed, skipping — no requestedBy to search with', | ||
| data: { title: currentTrack.title, guildId: queue.guild.id }, | ||
| }) | ||
| await notifyChannelStreamFailed(queue, currentTrack.title) | ||
| queue.node.skip() | ||
| return |
There was a problem hiding this comment.
Skip is blocked by channel notification I/O in recovery paths.
await notifyChannelStreamFailed(...) runs before queue.node.skip(). If Discord send is slow/fails late, recovery is delayed and playback can stall longer than needed.
⚡ Proposed fix (skip first, notify best-effort)
- await notifyChannelStreamFailed(queue, currentTrack.title)
- queue.node.skip()
+ queue.node.skip()
+ void notifyChannelStreamFailed(queue, currentTrack.title)
@@
- await notifyChannelStreamFailed(queue, currentTrack.title)
- queue.node.skip()
+ queue.node.skip()
+ void notifyChannelStreamFailed(queue, currentTrack.title)
@@
- await notifyChannelStreamFailed(queue, currentTrack.title)
- queue.node.skip()
+ queue.node.skip()
+ void notifyChannelStreamFailed(queue, currentTrack.title)
@@
- if (failedTrack) {
- await notifyChannelStreamFailed(queue, failedTrack.title)
- }
- queue.node.skip()
+ queue.node.skip()
+ if (failedTrack) {
+ void notifyChannelStreamFailed(queue, failedTrack.title)
+ }#!/bin/bash
# Verify all call sites where notification is awaited before skip.
rg -n -P --type ts 'await\s+notifyChannelStreamFailed\(queue,\s*[^)]*\)\s*\n\s*queue\.node\.skip\(\)' -C 1As per coding guidelines, "Set timeouts and handle aborts/cancellations; avoid dangling requests in API/network code."
Also applies to: 242-248, 270-277, 334-338
🤖 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 227 - 233,
The notifyChannelStreamFailed call is awaited before skipping which blocks
recovery; change the order to call queue.node.skip() immediately (use
queue.node.skip() before notifyChannelStreamFailed), then fire
notifyChannelStreamFailed as a best-effort non-blocking operation (do not
await), wrapping it in a try/catch and apply a short timeout/AbortSignal to
bound network I/O; update all identical sites (the blocks around
notifyChannelStreamFailed, queue.node.skip, warnLog at the referenced ranges) so
skip is immediate and notification failures are handled/logged but do not
prevent playback recovery.
|
#546) * fix(bot): surface stream failures to discord and capture yt-dlp stderr - errorHandlers: notify the discord text channel with an error embed when stream extraction fails and all recovery paths are exhausted. user previously saw nothing — the bot silently skipped the track. - playerFactory: capture yt-dlp stderr and include the first line in the rejection message. adds structured 'stages' array to bridge- exhausted error logs. - tests: add stderr to spawn mocks, test stderr inclusion in rejection. * test(bot): coverage for discord error notification on stream failure



Problems fixed
Silent failures (critical UX)
When
playerErrorfires and stream recovery exhausts all paths, the user saw nothing — no embed, no message. The bot silently skipped the track.Fix:
notifyChannelStreamFailedsends an error embed to the guild's text channel:Called from three recovery exit paths: no requestedBy, YouTube finds nothing, all alternatives already queued.
yt-dlp stderr not captured
Exit code 1 was logged as
"yt-dlp exited with code 1"— no context. The actual reason (bot detection, geo-restriction, unavailable video) was in stderr but discarded.Fix: Collect stderr chunks, include first line in rejection message:
Bridge exhaustion lacks context
Bridge: all stages exhaustedlog had onlytitle. AddedcleanedTitle,url, andstages[]array.Tests
stderrto all spawn mocksSummary by CodeRabbit