From 90dd96e08fcac4c1d4e8761a108553d3e039f52a Mon Sep 17 00:00:00 2001 From: Daniel Friesel Date: Sat, 20 Jul 2019 20:58:28 +0200 Subject: Handle race condition when several workers are updating the same history entry --- lib/Travelynx.pm | 32 +++++++++++++++++++++++++------- 1 file changed, 25 insertions(+), 7 deletions(-) (limited to 'lib') diff --git a/lib/Travelynx.pm b/lib/Travelynx.pm index 3ef7011..2bc151d 100755 --- a/lib/Travelynx.pm +++ b/lib/Travelynx.pm @@ -1485,15 +1485,33 @@ sub startup { ); my $stats = $self->compute_journey_stats(@journeys); - $self->pg->db->insert( - 'journey_stats', + eval { + $self->pg->db->insert( + 'journey_stats', + { + user_id => $uid, + year => $year, + month => $month, + data => JSON->new->encode($stats), + } + ); + }; + if ( my $err = $@ ) { + if ( $err =~ m{duplicate key value violates unique constraint} ) { - user_id => $uid, - year => $year, - month => $month, - data => JSON->new->encode($stats), + # When a user opens the same history page several times in + # short succession, there is a race condition where several + # Mojolicious workers execute this helper, notice that there is + # no up-to-date history, compute it, and insert it using the + # statement above. This will lead to a uniqueness violation + # in each successive insert. However, this is harmless, and + # thus ignored. } - ); + else { + # Otherwise we probably have a problem. + die($@); + } + } return $stats; } -- cgit v1.2.3