Skip to content

fix(shared): handle last.fm unlink p2025 as successful cleanup - #470

Merged
LucasSantana-Dev merged 2 commits into
mainfrom
fix/lastfm-unlink-p2025
Apr 3, 2026
Merged

LucasSantana-Dev merged 2 commits into
mainfrom
fix/lastfm-unlink-p2025

Conversation

@LucasSantana-Dev

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

Copy link
Copy Markdown
Owner

Summary

  • treat Prisma P2025 during LastFmLinkService.unlink as an idempotent success case (record already absent)
  • stop escalating already-removed Last.fm links as hard unlink failures, reducing production error spam under invalid-session cleanup races
  • add focused unit coverage for unlink success, P2025 success path, and unexpected-error failure path

Verification

  • npm test --workspace=packages/shared -- src/services/LastFmLinkService/index.spec.ts
  • npm test --workspace=packages/bot -- src/handlers/externalScrobbler.spec.ts src/lastfm/lastFmApi.spec.ts
  • npm run type:check --workspace=packages/shared

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced Last.fm unlinking resilience to gracefully handle cases where the link is already absent, preventing repeated error messages during cleanup operations.
  • Tests

    • Added comprehensive test coverage for Last.fm unlinking behavior across success and failure scenarios.

@vercel

vercel Bot commented Apr 3, 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 3, 2026 4:49am

Request Review

@github-actions github-actions Bot added the shared label Apr 3, 2026
@coderabbitai

coderabbitai Bot commented Apr 3, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@LucasSantana-Dev has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 5 minutes and 32 seconds before requesting another review.

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 5 minutes and 32 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d65bae53-9cdf-42b9-9a37-f8e5adf91a6b

📥 Commits

Reviewing files that changed from the base of the PR and between 4348813 and 0b3f506.

📒 Files selected for processing (1)
  • packages/shared/src/services/LastFmLinkService/index.ts
📝 Walkthrough

Walkthrough

This PR enhances the Last.fm unlink operation to treat Prisma's P2025 error (record not found) as a successful cleanup path rather than a failure, reducing error spam during race conditions or already-removed records. Changes include implementation logic, test coverage, and changelog documentation.

Changes

Cohort / File(s) Summary
Documentation
CHANGELOG.md
Added unreleased fix entry documenting that Prisma P2025 errors are now treated as successful unlink/cleanup operations.
Implementation
packages/shared/src/services/LastFmLinkService/index.ts
Modified error handler in unlink() to extract error code and treat P2025 as a successful operation, returning true with debug logging instead of error logging.
Test Coverage
packages/shared/src/services/LastFmLinkService/index.spec.ts
New test file with three scenarios: successful deletion returns true, P2025 error returns true with "already absent" debug log, and other errors return false with error log.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Suggested labels

shared, size/s

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely summarizes the main change: handling Prisma P2025 errors as successful cleanup when unlinking Last.fm accounts.
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
  • Commit unit tests in branch fix/lastfm-unlink-p2025

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[bot]
coderabbitai Bot previously requested changes Apr 3, 2026

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

🤖 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/shared/src/services/LastFmLinkService/index.ts`:
- Around line 85-99: Add an inline comment above the P2025 check in
LastFmLinkService (the block that computes the local variable `code` from
`error` and the subsequent `if (code === 'P2025')` branch) that documents the
Prisma semantics: state that P2025 means "Record not found", include the Prisma
error reference URL (https://www.prisma.io/docs/orm/reference/error-reference),
and note that treating this as idempotent success is intentional when deleting a
non-existent Last.fm link; leave the existing `debugLog` and `return true`
behavior unchanged.
🪄 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: fde07b9b-812f-4ac1-bdcd-b1193e724fa9

📥 Commits

Reviewing files that changed from the base of the PR and between b0b1fe6 and 4348813.

📒 Files selected for processing (3)
  • CHANGELOG.md
  • packages/shared/src/services/LastFmLinkService/index.spec.ts
  • packages/shared/src/services/LastFmLinkService/index.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 (18)
**/*.{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/shared/src/services/LastFmLinkService/index.ts
  • packages/shared/src/services/LastFmLinkService/index.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

**/*.{ts,tsx,js,jsx}: Use Prettier with no semicolons, single quotes, 4-space indent, 80 character width
Files must not exceed 250 lines and this is enforced

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

Files:

  • packages/shared/src/services/LastFmLinkService/index.ts
  • packages/shared/src/services/LastFmLinkService/index.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/shared/src/services/LastFmLinkService/index.ts
  • packages/shared/src/services/LastFmLinkService/index.spec.ts
**/index.ts

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

Use index.ts only to re-export a small, intentional surface per module

Files:

  • packages/shared/src/services/LastFmLinkService/index.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}: Functions must be less than 50 lines with cyclomatic complexity less than 10
Do not use any types - ESLint enforces this at error level

**/*.{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/shared/src/services/LastFmLinkService/index.ts
  • packages/shared/src/services/LastFmLinkService/index.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

Never hardcode secrets, IPs, or ports; use .env and docs/ for required configuration variables

Files:

  • packages/shared/src/services/LastFmLinkService/index.ts
  • packages/shared/src/services/LastFmLinkService/index.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/shared/src/services/LastFmLinkService/index.ts
  • packages/shared/src/services/LastFmLinkService/index.spec.ts
{packages/shared/**,prisma/**}/**/*.{ts,js}

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

Use Prisma for PostgreSQL database and Redis for caching with shared client configuration

Files:

  • packages/shared/src/services/LastFmLinkService/index.ts
  • packages/shared/src/services/LastFmLinkService/index.spec.ts
packages/shared/**/*.ts

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

packages/shared/**/*.ts: Organize the Lucky Shared Package with the following directory structure: Config in packages/shared/src/config/ (environment, constants, feature toggles, YouTube config); Services in packages/shared/src/services/ (DatabaseService, Redis client/operations, FeatureToggleService, ReactionRoles, RoleManagement); Types in packages/shared/src/types/ (errors, commands, common, discord, music); Utils in packages/shared/src/utils/ (error handling, retry, embeds, log, monitoring, composables, prismaClient)
Do not add dependencies on bot or backend packages; shared is the foundational package used by both
Use the single Prisma client located at packages/shared/src/utils/database/prismaClient.ts; maintain schema in repo root at prisma/schema.prisma; run migrations from root using npm run db:migrate
Use Redis client and operations located in packages/shared/src/services/redis/; use for cache, sessions, and rate limits as defined by existing keys and types
Use typed errors from packages/shared/src/types/errors/ for domain failures; avoid using generic Error for application-specific failures
Use shared log and monitoring utils for logging and monitoring in production code paths; do not use direct console statements for production logging

Files:

  • packages/shared/src/services/LastFmLinkService/index.ts
  • packages/shared/src/services/LastFmLinkService/index.spec.ts
packages/shared/**/*

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

Shared client and services must be located in packages/shared

Files:

  • packages/shared/src/services/LastFmLinkService/index.ts
  • packages/shared/src/services/LastFmLinkService/index.spec.ts
{CHANGELOG.md,README.md}

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

ALWAYS update CHANGELOG.md and README.md as changes are made.

Files:

  • CHANGELOG.md
CHANGELOG.md

📄 CodeRabbit inference engine (.cursor/rules/templates-examples.mdc)

CHANGELOG.md must be updated with all changes in pull requests

Always update CHANGELOG.md with all code changes

Update CHANGELOG.md with all changes, include breaking changes documentation, and reference issues and PRs

Files:

  • CHANGELOG.md
{CHANGELOG.md,docs/**}

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

Update CHANGELOG.md and relevant docs/ files when behavior or setup changes

Files:

  • CHANGELOG.md
**/*.{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/shared/src/services/LastFmLinkService/index.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/shared/src/services/LastFmLinkService/index.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/shared/src/services/LastFmLinkService/index.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/shared/src/services/LastFmLinkService/index.spec.ts
**/*.spec.ts

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

Unit tests must use naming convention *.spec.ts

Files:

  • packages/shared/src/services/LastFmLinkService/index.spec.ts
🧠 Learnings (5)
📚 Learning: 2026-03-09T20:21:08.612Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-project.mdc:0-0
Timestamp: 2026-03-09T20:21:08.612Z
Learning: Applies to {packages/*/tests/**/*.test.{js,ts},tests/**/*.test.{js,ts}} : Add or adjust unit and integration tests when changing behavior; follow existing patterns in `packages/*/tests` and root `tests/` directories

Applied to files:

  • packages/shared/src/services/LastFmLinkService/index.spec.ts
📚 Learning: 2026-03-09T20:21:31.459Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/quality.mdc:0-0
Timestamp: 2026-03-09T20:21:31.459Z
Learning: Applies to **/*.{spec,test}.{ts,tsx,js,jsx} : Test behavior, not implementation details

Applied to files:

  • packages/shared/src/services/LastFmLinkService/index.spec.ts
📚 Learning: 2026-03-09T20:21:38.098Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-backend.mdc:0-0
Timestamp: 2026-03-09T20:21:38.098Z
Learning: Applies to packages/backend/tests/**/*.ts : Follow existing patterns for unit and integration tests in `packages/backend/tests/`

Applied to files:

  • packages/shared/src/services/LastFmLinkService/index.spec.ts
📚 Learning: 2026-03-09T20:21:31.459Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/quality.mdc:0-0
Timestamp: 2026-03-09T20:21:31.459Z
Learning: Applies to tests/**/*.test.{ts,tsx,js,jsx} : Add integration tests where appropriate

Applied to files:

  • packages/shared/src/services/LastFmLinkService/index.spec.ts
📚 Learning: 2026-03-15T21:57:49.951Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-03-15T21:57:49.951Z
Learning: When working on unit tests, Jest ESM mocks, or fixing disabled tests, use the `testing-lucky` skill

Applied to files:

  • packages/shared/src/services/LastFmLinkService/index.spec.ts
🔇 Additional comments (2)
CHANGELOG.md (1)

13-13: Changelog entry is clear and complete.

This documents the unlink idempotency behavior change and its operational intent well.

packages/shared/src/services/LastFmLinkService/index.spec.ts (1)

23-68: Solid behavioral coverage for the unlink contract change.

The suite cleanly validates all three relevant outcomes (success, P2025 idempotent success, and unexpected error failure).

Comment thread packages/shared/src/services/LastFmLinkService/index.ts
@LucasSantana-Dev
LucasSantana-Dev dismissed coderabbitai[bot]’s stale review April 3, 2026 04:45

Dismissed as stale after follow-up verification and all required checks passing.

@LucasSantana-Dev
LucasSantana-Dev enabled auto-merge (squash) April 3, 2026 04:45
@sonarqubecloud

sonarqubecloud Bot commented Apr 3, 2026

Copy link
Copy Markdown

@LucasSantana-Dev
LucasSantana-Dev merged commit 71ea9e8 into main Apr 3, 2026
12 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Apr 12, 2026
6 tasks
LucasSantana-Dev added a commit that referenced this pull request May 13, 2026
* fix(shared): treat missing last.fm link delete as successful cleanup

* docs(shared): document prisma p2025 unlink semantics
@LucasSantana-Dev
LucasSantana-Dev deleted the fix/lastfm-unlink-p2025 branch May 23, 2026 02:21

This branch was successfully deployed

1 active deployment
Preview — 0b3f5068 Deployed Apr 3, 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