Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions app/jobs/api_operation/callback_job.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# frozen_string_literal: true

# Sends the outcome of a finished ApiOperation to the calling system (i.e: Integration Hub). The
# operation queues it in the same transaction as its final status.
#
# It only reads the operation's stored status and errors (ApiOperation::CallbackPayload):
# retrying it never reruns a task. Once the calling system acknowledges the callback, the
# operation's response_delivered_at is set, and a job that finds it set sends nothing.
#
# The send and the timestamp are in one transaction, with the operation's row locked, so two runs
# never send at once and a run that fails sets nothing. Delivery is at least once: if the
# acknowledgement is lost, the callback is sent again.
# The payload and the Idempotency-Key header carry the operation's external_id, which is the
# same in every send, so the calling system can recognise a duplicate.
#
# With no callback URL configured, retrying cannot help: the job notifies PSD and ends,
# leaving the operation's response_delivered_at null.
#
# A failed send (an error, a timeout or a status other than 2xx) is retried by Delayed
# Job on the schedule of ApiOperation::RetrySchedule, the same as the coordinator job's.
# Each failed run adds a failed 'callback' event to the operation. When they run out, PSD is notified
# and the error is logged; response_delivered_at stays null.
class ApiOperation::CallbackJob
include ApiOperation::RetrySchedule

# @return [Integer] the ID of the operation whose outcome to send
attr_reader :api_operation_id

# @param api_operation_id [Integer] the ID of the operation whose outcome to send
def initialize(api_operation_id)
@api_operation_id = api_operation_id
end

# Delayed Job calls this to run the job.
#
# @return [void]
# @raise [Faraday::Error] if the callback is not acknowledged, so that Delayed Job retries it
def perform
deliver
rescue HTTPClients::ApiOperationCallbackClient::NotConfigured => e
record_failure
report_not_configured(e)
rescue StandardError
record_failure
raise
end

# Delayed Job calls this when its last run has failed, then deletes the job.
#
# @param job [Delayed::Job] the job's record
# @return [void]
def failure(job)
@delayed_job = job
message = "Callback retries ran out for ApiOperation #{api_operation_id}"
Rails.logger.error("#{message}: #{job.last_error}")
ExceptionNotifier.notify_exception(
job.error || RetriesExhausted.new(message), data: { message: message, api_operation_id: api_operation_id,
last_error: job.last_error }
)
end

private

def deliver
ApiOperation.transaction do
api_operation = ApiOperation.lock.find(api_operation_id)
next if api_operation.response_delivered_at? || !api_operation.finished?

HTTPClients::ApiOperationCallbackClient.new.deliver(ApiOperation::CallbackPayload.new(api_operation).to_h)
api_operation.update!(response_delivered_at: Time.current)
end
end

# Adds the failed run to the operation's events. It is done after the delivery's transaction has
# rolled back, so the event is kept.
def record_failure
ApiOperation.find_by(id: api_operation_id)&.record_callback_failure!
end

def report_not_configured(error)
Rails.logger.error("No callback URL to send ApiOperation #{api_operation_id}'s outcome to: #{error.message}")
ExceptionNotifier.notify_exception(error, data: { api_operation_id: })
end
end
7 changes: 7 additions & 0 deletions app/jobs/api_operation/coordinator_job.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@
#
# How it retries a task, and gives up on it, is in Retries.
#
# When the operation finishes, the job queues its CallbackJob to send the
# outcome to the calling system. The callback is only queued after all retries
# of the last task are exhausted, so it is not sent prematurely during a
# retry cycle.
#
# With the y26_283_sapio_reception feature flag off, it only logs that the
# operation is ready.
class ApiOperation::CoordinatorJob
Expand Down Expand Up @@ -118,6 +123,7 @@ def run_and_record(api_operation, task)
next false unless api_operation.next_task == task

record_outcome(api_operation, task, call_task(api_operation, task))
api_operation.enqueue_callback_if_finished!
true
end
end
Expand Down Expand Up @@ -159,6 +165,7 @@ def fail_after_unexpected_error(api_operation, task, error)
next unless api_operation.next_task == task

api_operation.fail_task!(task, [unexpected_error(task, error)])
api_operation.enqueue_callback_if_finished!
end
end

Expand Down
50 changes: 7 additions & 43 deletions app/jobs/api_operation/coordinator_job/retries.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
# which include such runs. Either way the operation's next task fails, with
# an error that asks for the request to be sent again, and PSD is notified.
module ApiOperation::CoordinatorJob::Retries
include ApiOperation::RetrySchedule

# Errors that a later run may not meet, as Rails' MySQL adapter raises
# them: a deadlock, a lock wait timeout, a lost connection, a failed
# attempt to connect, and a unique index clash with a record another
Expand All @@ -25,48 +27,6 @@ module ApiOperation::CoordinatorJob::Retries
ActiveRecord::RecordNotUnique
].freeze

# The wait after the job's first failed run. Each later wait is twice the
# one before, up to MAX_WAIT.
FIRST_WAIT = 30.seconds

# The longest wait between runs
MAX_WAIT = 1.hour

# How many times the job runs its tasks at most, the first run included
MAX_RUNS = 10

# Sent to PSD, not raised, when the job's runs are used up and no run's
# exception is at hand
class RetriesExhausted < StandardError
end

# Delayed Job calls this when a run raises, to schedule the next run: 30
# seconds, then 1, 2, 4, 8, 16 and 32 minutes, then 1 hour, so the last
# run starts about 3 hours after the first, plus the runs' own time.
#
# @param current_time [Time] when the run failed
# @param attempts [Integer] the number of failed runs so far, from 1
# @return [Time] when to run the job again
def reschedule_at(current_time, attempts)
current_time + [FIRST_WAIT * (2**(attempts - 1)), MAX_WAIT].min
end

# Delayed Job reads this to know how many runs to make.
#
# @return [Integer] the number of runs
def max_attempts
MAX_RUNS
end

# Delayed Job calls this before each run, with the job's record, which
# holds the last error for the notification when retries run out.
#
# @param job [Delayed::Job] the job's record
# @return [void]
def before(job)
@delayed_job = job
end

# Delayed Job calls this when its last run (max_attempts) has failed, then
# deletes the job. PSD is notified first, as the database may be what
# failed; then the operation's next task fails, unless it already has an
Expand All @@ -80,7 +40,10 @@ def failure(job)
ApiOperation.transaction do
api_operation = ApiOperation.lock.find(api_operation_id)
task = api_operation.next_task
api_operation.fail_task!(task, [retries_exhausted_error(task)]) if task
if task
api_operation.fail_task!(task, [retries_exhausted_error(task)])
api_operation.enqueue_callback_if_finished!
end
end
end

Expand All @@ -99,6 +62,7 @@ def runs_used_up?(api_operation)
def give_up(api_operation, task)
notify_retries_exhausted(task)
api_operation.fail_task!(task, [retries_exhausted_error(task)])
api_operation.enqueue_callback_if_finished!
end

# Notifies PSD that retries have run out. In the failure hook, the job's
Expand Down
47 changes: 47 additions & 0 deletions app/jobs/api_operation/retry_schedule.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# frozen_string_literal: true

# When Delayed Job runs an ApiOperation job again after a failed run, and how many
# runs it makes. It is shared by ApiOperation::CoordinatorJob and ApiOperation::CallbackJob.
module ApiOperation::RetrySchedule
# The wait after the job's first failed run. Each later wait is twice the
# one before, up to MAX_WAIT.
FIRST_WAIT = 30.seconds

# The longest wait between runs
MAX_WAIT = 1.hour

# How many times the job runs at most, the first run included
MAX_RUNS = 10

# Sent to PSD, not raised, when the job's runs are used up and no run's
# exception is at hand
class RetriesExhausted < StandardError
end

# Delayed Job calls this when a run raises, to schedule the next run: 30
# seconds, then 1, 2, 4, 8, 16 and 32 minutes, then 1 hour, so the last
# run starts about 3 hours after the first, plus the runs' own time.
#
# @param current_time [Time] when the run failed
# @param attempts [Integer] the number of failed runs so far, from 1
# @return [Time] when to run the job again
def reschedule_at(current_time, attempts)
current_time + [FIRST_WAIT * (2**(attempts - 1)), MAX_WAIT].min
end

# Delayed Job reads this to know how many runs to make.
#
# @return [Integer] the number of runs
def max_attempts
MAX_RUNS
end

# Delayed Job calls this before each run, with the job's record, which
# holds the last error for the notification when retries run out.
#
# @param job [Delayed::Job] the job's record
# @return [void]
def before(job)
@delayed_job = job
end
end
55 changes: 49 additions & 6 deletions app/models/api_operation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,12 @@
# Its CoordinatorJob runs the tasks of its operation type (TASKS) in order.
# The status names the last completed step: it starts as queued, becomes
# <task>_completed as each task completes, or <task>_failed if a task fails.
# response_delivered_at records when the response was delivered to the
# calling system, and is null until then.
# When the operation finishes (see #finished?), the CoordinatorJob queues its
# CallbackJob to send the outcome to the calling system. The callback is only
# queued after all retries of the last task are exhausted, so it is not sent
# prematurely during a retry cycle.
# response_delivered_at records when that was acknowledged, and is null until
# then.
class ApiOperation < ApplicationRecord
include Uuid::Uuidable

Expand All @@ -20,6 +24,15 @@ class ApiOperation < ApplicationRecord
# it here with its tasks; to add a task, see ApiOperation::Task.
TASKS = { 'reception_and_work_order' => %w[reception work_order] }.freeze

# The statuses at which an operation of each type is finished and its outcome is reported to
# the calling system: a task failed, or the last task completed. Add an entry with each new type.
FINISHED_STATUSES = {
'reception_and_work_order' => %w[reception_failed work_order_failed work_order_completed]
}.freeze

# The name the events of the callback to the calling system have as their task
CALLBACK = 'callback'

# Raised when a task is started, completed or failed out of order
class TaskOrderError < StandardError
end
Expand Down Expand Up @@ -59,6 +72,26 @@ def statuses
tasks.product(Event::OUTCOMES).map { |pair| pair.join('_') }
end

# @return [Boolean] true if the status is one of the type's FINISHED_STATUSES
def finished?
FINISHED_STATUSES.fetch(operation_type, []).include?(status)
end

# Records that a run of the callback job failed to deliver the outcome. It is not a task, so
# it doesn't change the status.
#
# @return [void]
def record_callback_failure!
events.create!(task: CALLBACK, outcome: Event::FAILED)
end

# The tasks of the operation's type, in order
#
# @return [Array<String>] the task names
def tasks
TASKS.fetch(operation_type)
end

# The first task not yet completed: the one to run next.
#
# @return [String, nil] the task, or nil when a task has failed or all
Expand Down Expand Up @@ -104,21 +137,31 @@ def fail_task!(task, errors)
error_details: { task:, errors: }.deep_stringify_keys)
end

# Queues the CallbackJob if the operation is finished.
# The CoordinatorJob calls this after completing or failing a task so the callback
# is sent only when the operation is truly finished (all tasks completed, retries
# exhausted, or non-retryable error).
#
# @return [void]
def enqueue_callback_if_finished!
Delayed::Job.enqueue(CallbackJob.new(id)) if finished?
end

private

# Adds the event and sets the status to match, in one transaction: the
# caller's if there is one, so the task's records commit with them.
#
# Ends the task with its outcome: sets the status and adds the event.
# The CoordinatorJob calls #enqueue_callback_if_finished! after this method
# to queue the callback only when the operation is truly finished.
def record_event!(task, outcome, **attributes)
transaction do
update!(status: "#{task}_#{outcome}", **attributes)
events.create!(task:, outcome:)
end
end

def tasks
TASKS.fetch(operation_type)
end

# The number of tasks completed so far
def completed_tasks
return 0 if status == 'queued'
Expand Down
28 changes: 28 additions & 0 deletions app/models/api_operation/callback_payload.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# frozen_string_literal: true

# The outcome of a finished ApiOperation, as sent to the calling system by
# ApiOperation::CallbackJob. It is built from the operation's stored status
# and error details alone, so sending it never reruns a task.
#
# { operation_type: 'reception_and_work_order',
# external_id: 'request-1', # the calling system's request ID, the same in every send
# status: 'work_order_failed', # the last completed or failed task, see ApiOperation
# errors: [{ 'pointer' => '/work_order/cost_code', 'detail' => '...' }] } # only when a task failed
class ApiOperation::CallbackPayload
# @param api_operation [ApiOperation] a finished operation
def initialize(api_operation)
@api_operation = api_operation
end

# @return [Hash] the payload, with symbol keys
def to_h
payload = {
operation_type: @api_operation.operation_type,
external_id: @api_operation.external_id,
status: @api_operation.status
}
errors = @api_operation.error_details&.fetch('errors', nil)
payload[:errors] = errors if errors.present?
payload
end
end
5 changes: 4 additions & 1 deletion app/models/api_operation/event.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@
# Something that happened to a task of an ApiOperation: a run of it started,
# or it completed or failed. An operation's events, in order, are its
# history, and its status is the latest completed or failed one
# (<task>_<outcome>). Events are added, not changed.
# (<task>_<outcome>). Events are added, not changed. A failed delivery of the
# callback (ApiOperation::CallbackJob) is a failed event of the task 'callback',
# which doesn't change the status.
class ApiOperation::Event < ApplicationRecord
# How a task can end
OUTCOMES = %w[completed failed].freeze
FAILED = 'failed'

# A run of a task started. It sets no status: a started event with no
# outcome after it is a run that didn't finish, because an error rolled
Expand Down
6 changes: 6 additions & 0 deletions config/config.rb
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,12 @@
configatron.integration_hub do |integration_hub|
integration_hub.auth_token_url = 'https://inthub-ppd.auth.eu-west-2.amazoncognito.com/oauth2/token'
integration_hub.base_url = 'https://ppd.integration-hub.sanger.ac.uk'
# Where ApiOperation::CallbackJob sends the outcome of an API operation. A placeholder until
# Integration Hub agrees the endpoint; set INTEGRATION_HUB_OPERATION_CALLBACK_URL to override it.
integration_hub.operation_callback_url =
ENV.fetch('INTEGRATION_HUB_OPERATION_CALLBACK_URL', "#{integration_hub.base_url}/sapio/operation-callbacks/v1")
integration_hub.operation_callback_open_timeout = 5 # seconds to connect
integration_hub.operation_callback_timeout = 15 # seconds to wait for the response
end

configatron.location_reports_fetch_count_max = 25000
Expand Down
Loading
Loading