fix(discover): upsert DiscoveryAlbum so re-processing a week doesn't lose records

Production showed 24 unique-constraint violations on
DiscoveryAlbum(userId, weekStartDate, rgMbid) in 18h: the scan-completion and
reconciliation paths can both create Discovery records for the same album in
the same week, so the second create threw, rolled back the transaction, and
dropped that album's DiscoveryTrack records. Upsert makes it idempotent --
an existing record is left untouched and the track loop fills any gaps.
This commit is contained in:
chevron7
2026-06-16 13:50:52 -05:00
parent baa7ecd0bc
commit 690778fd5f
+19 -3
View File
@@ -1647,9 +1647,24 @@ export class DiscoverWeeklyService {
try {
await prisma.$transaction(async (tx) => {
// Create DiscoveryAlbum
const discoveryAlbum = await tx.discoveryAlbum.create({
data: {
// Upsert DiscoveryAlbum -- the scan-completion and
// reconciliation paths can both reach this for the same
// album in the same week. A plain create then violates the
// (userId, weekStartDate, rgMbid) unique constraint, throws,
// and rolls back the whole transaction -- losing the
// DiscoveryTrack records too. Upsert makes it idempotent;
// an existing record is left as-is (don't reset the user's
// status/downloadedAt) and the track loop below fills any
// missing tracks.
const discoveryAlbum = await tx.discoveryAlbum.upsert({
where: {
userId_weekStartDate_rgMbid: {
userId: batch.userId,
weekStartDate: batch.weekStart,
rgMbid: album.rgMbid,
},
},
create: {
userId: batch.userId,
rgMbid: album.rgMbid,
artistName: album.artist.name,
@@ -1662,6 +1677,7 @@ export class DiscoverWeeklyService {
downloadedAt: new Date(),
status: "ACTIVE",
},
update: {},
});
// Create DiscoveryTrack for each track