Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

Fix #upsert_status race condition.

Pavel Balashouf296c54ee75c
diff --git a/modules/job_status/app/workers/job_status/application_job_with_status.rb b/modules/job_status/app/workers/job_status/application_job_with_status.rb
index e754700cde2..9aa2c8291b8 100644
--- a/modules/job_status/app/workers/job_status/application_job_with_status.rb
+++ b/modules/job_status/app/workers/job_status/application_job_with_status.rb
@@ -27,8 +27,7 @@
#++
module JobStatus
module ApplicationJobWithStatus
- # Delayed jobs can have a status:
- # Delayed::Job::Status
+ # Backgroun jobs can have a status JobStatus::Status
# which is related to the job via a reference which is an AR model instance.
def status_reference
nil
@@ -61,8 +60,6 @@ module JobStatus
##
# Update the status code for a given job
def upsert_status(status:, **args)
- # Can't use upsert, as we only want to insert the user_id once
- # and not update it repeatedly
resource = ::JobStatus::Status.find_or_initialize_by(job_id:)
if resource.new_record?
@@ -77,7 +74,16 @@ module JobStatus
resource.attributes = build_status_attributes(args.merge(status:))
end
+ # There is a possible race condition because of unique delayed_job_statuses.job_id
+ # Can't use upsert easily, because before updating we need to know user_id
+ # to set proper locale. Probably, it is possible to get it from
+ # a job's payload, then it would be possible to correctly prepare attributes before using upsert.
+ # Therefore, it is up to possible optimization in future. Now the race condition is handled with
+ # handling ActiveRecord::RecordNotUnique and trying again.
resource.save!
+ rescue ActiveRecord::RecordNotUnique
+ OpenProject.logger.info("Retrying ApplicationJobWithStatus#upsert_status.")
+ retry
end
protected