Skip to content

Commit

Permalink
Try to prevent a deadlock when a reservation ends and starts within a…
Browse files Browse the repository at this point in the history
… second and in the wrong order
  • Loading branch information
Arie committed Nov 18, 2023
1 parent fad4ef0 commit 975ca00
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
15 changes: 13 additions & 2 deletions app/services/reservation_manager.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,13 @@ def initialize(reservation)
end

def start_reservation
reservation.reservation_statuses.create!(status: 'Starting')
manage_reservation(:start)
if previous_reservation_ended_fully?
reservation.reservation_statuses.create!(status: 'Starting')
manage_reservation(:start)
else
reservation.update_attribute(:start_instantly, false)
reservation.reservation_statuses.create!(status: 'Waiting for other reservation on server to end fully')
end
end

def end_reservation
Expand All @@ -28,4 +33,10 @@ def update_reservation
def manage_reservation(action)
ReservationWorker.perform_async(reservation.id, action.to_s)
end

private

def previous_reservation_ended_fully?
Reservation.where.not(id: reservation.id).where(server_id: reservation.server_id, ended: false).where('reservations.ends_at > ?', 15.minutes.ago).none?
end
end
10 changes: 10 additions & 0 deletions spec/models/reservation_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,16 @@
ReservationWorker.should_receive(:perform_async).with(reservation.id, 'start')
reservation.start_reservation
end

it 'should wait if a previous reservation is not fully ended' do
previous_reservation = create(:reservation)
previous_reservation.update_attribute(:server_id, reservation.server_id)
previous_reservation.update_attribute(:ends_at, 1.minute.ago)

reservation.start_reservation

expect(reservation.reservation_statuses.map(&:status)).to include 'Waiting for other reservation on server to end fully'
end
end

describe '#update_reservation' do
Expand Down

0 comments on commit 975ca00

Please sign in to comment.