Repository navigation
Description
Describe the bug
checkAndSyncUpcomingSlots runs on the first /api/upcoming-papers request after the daily cutoff, it reads lastSyncedDate rebuilds the list and then does deleteMany({}) followed by insertMany(...), redudant
| if (currentSlotDoc?.lastSyncedDate === today) { |
papers-codechef/src/lib/services/upcoming-sync.ts
Lines 89 to 103 in 6e3aa11
| await UpcomingSlot.findOneAndUpdate( | |
| {}, | |
| { $set: { slot: scheduledSlot, lastSyncedDate: today } }, | |
| { upsert: true, new: true, setDefaultsOnInsert: true }, | |
| ); | |
| await UpcomingSubject.deleteMany({}); | |
| if (ranked.length > 0) { | |
| await UpcomingSubject.insertMany( | |
| ranked.map((item) => ({ | |
| subject: item.subject, | |
| slots: item.slots, | |
| })), | |
| ); | |
| } |
Nothing stops two requests that arrive together from both seeing the old date and both running the sync, then:
- both delete and both insert, so every upcoming subject can appear twice or
- a request served between one syncs delete and its insert sees an empty list and gets a 404
To Reproduce
hard to hit by hand, Send several requests to /api/upcoming-papers at the same moment just after the cutoff on a day that hasnt synced yet, then check the upcomingsubjects collection for duplicates
Expected behavior
Only one request should run the sync. eg: claim the day atomically first with findOneAndUpdate({ lastSyncedDate: { $ne: today } }, { $set: { lastSyncedDate: today } }) and only sync if that update matched then replace the subjects in a transaction or with a bulk write
Activity