From 3356a7270c0f12933f75a154ad425a20b80a71b3 Mon Sep 17 00:00:00 2001 From: sabrine33 Date: Wed, 18 Nov 2026 15:30:43 +0000 Subject: [PATCH] Y26-285-callback --- app/jobs/api_operation/callback_job.rb | 84 +++++++++++ app/jobs/api_operation/coordinator_job.rb | 7 + .../api_operation/coordinator_job/retries.rb | 50 +------ app/jobs/api_operation/retry_schedule.rb | 47 +++++++ app/models/api_operation.rb | 55 +++++++- app/models/api_operation/callback_payload.rb | 28 ++++ app/models/api_operation/event.rb | 5 +- config/config.rb | 6 + .../api_operation_callback_client.rb | 56 ++++++++ spec/jobs/api_operation/callback_job_spec.rb | 132 ++++++++++++++++++ .../api_operation/coordinator_job_spec.rb | 19 +++ .../api_operation_callback_client_spec.rb | 41 ++++++ .../api_operation/callback_payload_spec.rb | 31 ++++ spec/models/api_operation_spec.rb | 38 ++++- spec/requests/api/v2/sapio/operations_spec.rb | 2 + .../v2/sapio/reception_and_work_order_spec.rb | 10 ++ .../sapio_reception_shared_context.rb | 1 + 17 files changed, 561 insertions(+), 51 deletions(-) create mode 100644 app/jobs/api_operation/callback_job.rb create mode 100644 app/jobs/api_operation/retry_schedule.rb create mode 100644 app/models/api_operation/callback_payload.rb create mode 100644 lib/http_clients/api_operation_callback_client.rb create mode 100644 spec/jobs/api_operation/callback_job_spec.rb create mode 100644 spec/lib/http_clients/api_operation_callback_client_spec.rb create mode 100644 spec/models/api_operation/callback_payload_spec.rb diff --git a/app/jobs/api_operation/callback_job.rb b/app/jobs/api_operation/callback_job.rb new file mode 100644 index 0000000000..67c4f9f3ea --- /dev/null +++ b/app/jobs/api_operation/callback_job.rb @@ -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 diff --git a/app/jobs/api_operation/coordinator_job.rb b/app/jobs/api_operation/coordinator_job.rb index 13feda9fe0..21b6fa3d66 100644 --- a/app/jobs/api_operation/coordinator_job.rb +++ b/app/jobs/api_operation/coordinator_job.rb @@ -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 @@ -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 @@ -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 diff --git a/app/jobs/api_operation/coordinator_job/retries.rb b/app/jobs/api_operation/coordinator_job/retries.rb index 79f65431b4..9fcba471b8 100644 --- a/app/jobs/api_operation/coordinator_job/retries.rb +++ b/app/jobs/api_operation/coordinator_job/retries.rb @@ -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 @@ -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 @@ -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 @@ -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 diff --git a/app/jobs/api_operation/retry_schedule.rb b/app/jobs/api_operation/retry_schedule.rb new file mode 100644 index 0000000000..1e42a983ac --- /dev/null +++ b/app/jobs/api_operation/retry_schedule.rb @@ -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 diff --git a/app/models/api_operation.rb b/app/models/api_operation.rb index e7a7371bfb..e6ba41a42a 100644 --- a/app/models/api_operation.rb +++ b/app/models/api_operation.rb @@ -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 # _completed as each task completes, or _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 @@ -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 @@ -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] 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 @@ -104,10 +137,24 @@ 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) @@ -115,10 +162,6 @@ def record_event!(task, outcome, **attributes) end end - def tasks - TASKS.fetch(operation_type) - end - # The number of tasks completed so far def completed_tasks return 0 if status == 'queued' diff --git a/app/models/api_operation/callback_payload.rb b/app/models/api_operation/callback_payload.rb new file mode 100644 index 0000000000..f406a63b13 --- /dev/null +++ b/app/models/api_operation/callback_payload.rb @@ -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 diff --git a/app/models/api_operation/event.rb b/app/models/api_operation/event.rb index 0582ca5e92..c3c439decb 100644 --- a/app/models/api_operation/event.rb +++ b/app/models/api_operation/event.rb @@ -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 -# (_). Events are added, not changed. +# (_). 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 diff --git a/config/config.rb b/config/config.rb index 34d8d6f14c..3e5eb7c13f 100644 --- a/config/config.rb +++ b/config/config.rb @@ -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 diff --git a/lib/http_clients/api_operation_callback_client.rb b/lib/http_clients/api_operation_callback_client.rb new file mode 100644 index 0000000000..9748ff07df --- /dev/null +++ b/lib/http_clients/api_operation_callback_client.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +module HTTPClients + # Sends the outcome of an API operation (ApiOperation::CallbackPayload) to calling system. + # + # The operation's external_id is also sent as the Idempotency-Key header, so Integration Hub can + # recognise a callback it has already received. + + # Configuration options (see config/config.rb): + # + # configatron + # .integration_hub + # .operation_callback_url + # .operation_callback_open_timeout + # .operation_callback_timeout + class ApiOperationCallbackClient < BaseClient + IDEMPOTENCY_KEY_HEADER = 'Idempotency-Key' + + # Raised when there is no callback URL to send to + class NotConfigured < StandardError + end + + # @param payload [Hash] the outcome, with the operation's :external_id + # @return [Faraday::Response] the acknowledgement + # @raise [NotConfigured] if no callback URL is configured + # @raise [Faraday::Error] if the request fails, times out, or is not answered with a 2xx status + def deliver(payload) + raise NotConfigured, 'integration_hub.operation_callback_url is not configured' if callback_url.blank? + + conn.post do |request| + request.headers[IDEMPOTENCY_KEY_HEADER] = payload.fetch(:external_id) + request.body = payload + end + end + + private + + def conn + @conn ||= + Faraday.new(url: callback_url, headers: default_headers, proxy: proxy) do |f| + f.request :json + f.response :raise_error + f.options.open_timeout = settings.operation_callback_open_timeout + f.options.timeout = settings.operation_callback_timeout + end + end + + def callback_url + settings.fetch(:operation_callback_url, nil) + end + + def settings + configatron.integration_hub + end + end +end diff --git a/spec/jobs/api_operation/callback_job_spec.rb b/spec/jobs/api_operation/callback_job_spec.rb new file mode 100644 index 0000000000..03bd0f9397 --- /dev/null +++ b/spec/jobs/api_operation/callback_job_spec.rb @@ -0,0 +1,132 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe ApiOperation::CallbackJob do + subject(:job) { described_class.new(api_operation.id) } + + let(:api_operation) { create(:api_operation, status: 'work_order_completed') } + let(:client) { instance_double(HTTPClients::ApiOperationCallbackClient, deliver: nil) } + + before { allow(HTTPClients::ApiOperationCallbackClient).to receive(:new).and_return(client) } + + describe '#perform' do + it 'sends the operation outcome' do + job.perform + expect(client).to have_received(:deliver).with(ApiOperation::CallbackPayload.new(api_operation).to_h) + end + + it 'sets the delivery timestamp once acknowledged' do + expect { job.perform }.to change { api_operation.reload.response_delivered_at }.from(nil) + end + + context 'when the delivery fails' do + before { allow(client).to receive(:deliver).and_raise(Faraday::TimeoutError) } + + it 'raises, so that Delayed Job retries' do + expect { job.perform }.to raise_error(Faraday::TimeoutError) + end + + it 'records each failed run as a failed callback event' do + 2.times { suppress(Faraday::TimeoutError) { job.perform } } + expect(api_operation.events.pluck(:task, :outcome)).to eq([%w[callback failed]] * 2) + end + + it 'leaves the status as it was' do + suppress(Faraday::TimeoutError) { job.perform } + expect(api_operation.reload.status).to eq('work_order_completed') + end + + it 'leaves the timestamp unset' do + suppress(Faraday::TimeoutError) { job.perform } + expect(api_operation.reload.response_delivered_at).to be_nil + end + + it 'does not run any task again' do + allow(ApiOperation::Task).to receive(:for) + suppress(Faraday::TimeoutError) { job.perform } + expect(ApiOperation::Task).not_to have_received(:for) + end + end + + context 'when no callback URL is configured' do + before do + allow(client).to receive(:deliver).and_raise(HTTPClients::ApiOperationCallbackClient::NotConfigured) + allow(ExceptionNotifier).to receive(:notify_exception) + end + + it 'records a failed callback event' do + job.perform + expect(api_operation.events.pluck(:task, :outcome)).to eq([%w[callback failed]]) + end + + it 'does not raise, so Delayed Job does not retry' do + expect { job.perform }.not_to raise_error + end + + it 'notifies PSD' do + job.perform + expect(ExceptionNotifier).to have_received(:notify_exception) + end + + it 'leaves the delivery timestamp unset' do + job.perform + expect(api_operation.reload.response_delivered_at).to be_nil + end + end + + context 'when the outcome was already delivered' do + before { api_operation.update!(response_delivered_at: 1.hour.ago) } + + it 'sends nothing' do + job.perform + expect(client).not_to have_received(:deliver) + end + + it 'keeps the timestamp' do + expect { job.perform }.not_to(change { api_operation.reload.response_delivered_at }) + end + end + + context 'when the operation has not finished' do + let(:api_operation) { create(:api_operation, status: 'reception_completed') } + + it 'sends nothing' do + job.perform + expect(client).not_to have_received(:deliver) + end + end + end + + describe 'retries' do + let(:now) { Time.zone.local(2026, 10, 29, 12) } + + it 'waits 30 seconds, doubling the wait after each failed run, up to an hour' do + waits = (1...described_class::MAX_RUNS).map { (job.reschedule_at(now, it) - now).seconds } + expect(waits).to eq([30.seconds, 1.minute, 2.minutes, 4.minutes, 8.minutes, 16.minutes, 32.minutes, 1.hour, + 1.hour]) + end + + it 'allows MAX_RUNS runs' do + expect(job.max_attempts).to eq(described_class::MAX_RUNS) + end + end + + describe '#failure' do + let(:delayed_job) { instance_double(Delayed::Job, error: RuntimeError.new('boom'), last_error: 'boom') } + + before do + allow(ExceptionNotifier).to receive(:notify_exception) + job.failure(delayed_job) + end + + it 'notifies PSD' do + expect(ExceptionNotifier).to have_received(:notify_exception) + .with(delayed_job.error, data: hash_including(api_operation_id: api_operation.id)) + end + + it 'leaves the delivery timestamp unset' do + expect(api_operation.reload.response_delivered_at).to be_nil + end + end +end diff --git a/spec/jobs/api_operation/coordinator_job_spec.rb b/spec/jobs/api_operation/coordinator_job_spec.rb index 0338e4bc1b..ff89d8abb6 100644 --- a/spec/jobs/api_operation/coordinator_job_spec.rb +++ b/spec/jobs/api_operation/coordinator_job_spec.rb @@ -119,6 +119,13 @@ def wait(attempts) 'detail' => 'Barcode in use' }] ) end + + it 'queues the callback job' do + perform + expect(Delayed::Job.last.payload_object) + .to have_attributes(class: ApiOperation::CallbackJob, + api_operation_id: api_operation.id) + end end context 'when the reception writes a record, then finds errors' do @@ -571,6 +578,12 @@ def add_started_events(count) expect(api_operation.reload.status).to eq('work_order_completed') end + it 'queues the callback job' do + expect(Delayed::Job.last.payload_object) + .to have_attributes(class: ApiOperation::CallbackJob, + api_operation_id: api_operation.id) + end + context 'when the work order finds errors' do let(:work_order_errors) { [{ pointer: '/work_order/cost_code', detail: 'cost_code is required' }] } @@ -581,6 +594,12 @@ def add_started_events(count) 'detail' => 'cost_code is required' }] } ) end + + it 'queues the callback job' do + expect(Delayed::Job.last.payload_object) + .to have_attributes(class: ApiOperation::CallbackJob, + api_operation_id: api_operation.id) + end end end end diff --git a/spec/lib/http_clients/api_operation_callback_client_spec.rb b/spec/lib/http_clients/api_operation_callback_client_spec.rb new file mode 100644 index 0000000000..f19c7d0eed --- /dev/null +++ b/spec/lib/http_clients/api_operation_callback_client_spec.rb @@ -0,0 +1,41 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe HTTPClients::ApiOperationCallbackClient do + let(:client) { described_class.new } + let(:url) { 'https://integration-hub.example.com/callbacks' } + let(:payload) do + { operation_type: 'reception_and_work_order', external_id: 'abc-123', status: 'work_order_completed' } + end + + around do |example| + original_url = configatron.integration_hub.operation_callback_url + configatron.integration_hub.operation_callback_url = url + example.run + ensure + configatron.integration_hub.operation_callback_url = original_url + end + + it 'posts the payload as JSON with the operation ID as the idempotency key' do + headers = { 'Content-Type' => 'application/json', 'Idempotency-Key' => 'abc-123' } + stub = stub_request(:post, url).with(body: payload.to_json, headers: headers).to_return(status: 202) + client.deliver(payload) + expect(stub).to have_been_requested + end + + it 'raises, without sending, when no callback URL is configured' do + configatron.integration_hub.operation_callback_url = '' + expect { client.deliver(payload) }.to raise_error(described_class::NotConfigured) + end + + it 'raises when Integration Hub does not acknowledge' do + stub_request(:post, url).to_return(status: 500) + expect { client.deliver(payload) }.to raise_error(Faraday::ServerError) + end + + it 'raises when the request times out' do + stub_request(:post, url).to_timeout + expect { client.deliver(payload) }.to raise_error(Faraday::ConnectionFailed) + end +end diff --git a/spec/models/api_operation/callback_payload_spec.rb b/spec/models/api_operation/callback_payload_spec.rb new file mode 100644 index 0000000000..c48f2b233a --- /dev/null +++ b/spec/models/api_operation/callback_payload_spec.rb @@ -0,0 +1,31 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe ApiOperation::CallbackPayload do + subject(:payload) { described_class.new(api_operation).to_h } + + let(:api_operation) { create(:api_operation, status:, error_details:) } + let(:error_details) { nil } + let(:identifiers) do + { operation_type: 'reception_and_work_order', external_id: api_operation.external_id } + end + + context 'when every task completed' do + let(:status) { 'work_order_completed' } + + it 'has the type, request ID and status, without errors' do + expect(payload).to eq(identifiers.merge(status: 'work_order_completed')) + end + end + + context 'when a task failed' do + let(:status) { 'work_order_failed' } + let(:errors) { [{ 'pointer' => '/work_order/cost_code', 'detail' => 'cost_code is required' }] } + let(:error_details) { { 'task' => 'work_order', 'errors' => errors } } + + it 'adds only the errors' do + expect(payload).to eq(identifiers.merge(status: 'work_order_failed', errors: errors)) + end + end +end diff --git a/spec/models/api_operation_spec.rb b/spec/models/api_operation_spec.rb index 291ba18510..9c393b2893 100644 --- a/spec/models/api_operation_spec.rb +++ b/spec/models/api_operation_spec.rb @@ -182,6 +182,10 @@ { 'reception_and_work_order' => %w[reception work_order] }) end + def callback_job_ids + Delayed::Job.all.map(&:payload_object).grep(ApiOperation::CallbackJob).map(&:api_operation_id) + end + it 'runs the first task while queued' do expect(api_operation.next_task).to eq('reception') end @@ -236,6 +240,7 @@ before do api_operation.complete_task!('reception') api_operation.complete_task!('work_order') + api_operation.enqueue_callback_if_finished! end it 'has no next task' do @@ -246,10 +251,41 @@ expect(api_operation.events.pluck(:task, :outcome)) .to eq([%w[reception completed], %w[work_order completed]]) end + + it 'is finished' do + expect(api_operation).to be_finished + end + + it 'queues one callback job' do + expect(callback_job_ids).to eq([api_operation.id]) + end + end + + context 'when only the first task completes' do + before { api_operation.complete_task!('reception') } + + it 'is not finished' do + expect(api_operation).not_to be_finished + end + + it 'queues no callback job' do + expect(callback_job_ids).to be_empty + end end context 'when a task fails' do - before { api_operation.fail_task!('reception', errors) } + before do + api_operation.fail_task!('reception', errors) + api_operation.enqueue_callback_if_finished! + end + + it 'is finished' do + expect(api_operation).to be_finished + end + + it 'queues one callback job' do + expect(callback_job_ids).to eq([api_operation.id]) + end it 'records the task as failed' do expect(api_operation.reload.status).to eq('reception_failed') diff --git a/spec/requests/api/v2/sapio/operations_spec.rb b/spec/requests/api/v2/sapio/operations_spec.rb index e16b8b76a5..043a099cd6 100644 --- a/spec/requests/api/v2/sapio/operations_spec.rb +++ b/spec/requests/api/v2/sapio/operations_spec.rb @@ -632,6 +632,8 @@ def post_request(api_key: nil, request_body: body) [->(p) { p.merge(labware: {}) }, '/labware'], 'a work order section that is not an object' => [->(p) { p.merge(work_order: []) }, '/work_order'], + 'a null work order section' => + [->(p) { p.merge(work_order: nil) }, '/work_order'], 'an unknown labware type' => [->(p) { p.merge(labware: [p[:labware].first.merge(type: 'vial')]) }, '/labware/0/type'] diff --git a/spec/requests/api/v2/sapio/reception_and_work_order_spec.rb b/spec/requests/api/v2/sapio/reception_and_work_order_spec.rb index 90fae663f3..339a1f34dc 100644 --- a/spec/requests/api/v2/sapio/reception_and_work_order_spec.rb +++ b/spec/requests/api/v2/sapio/reception_and_work_order_spec.rb @@ -35,6 +35,16 @@ expect([operation.reload.status, operation.error_details]).to eq(['work_order_completed', nil]) end + it 'sends the outcome to Integration Hub once' do + expect(a_request(:post, configatron.integration_hub.operation_callback_url) + .with(body: hash_including(external_id: operation.external_id, + status: 'work_order_completed'))).to have_been_made.once + end + + it 'records the delivery' do + expect(operation.reload.response_delivered_at).to be_present + end + it 'creates the submission of the work order' do expect(Submission.find_by!(name: 'WO-1').orders.map(&:study)).to eq([study]) end diff --git a/spec/shared_contexts/sapio_reception_shared_context.rb b/spec/shared_contexts/sapio_reception_shared_context.rb index de20d1d960..e3f8e6324c 100644 --- a/spec/shared_contexts/sapio_reception_shared_context.rb +++ b/spec/shared_contexts/sapio_reception_shared_context.rb @@ -26,6 +26,7 @@ before do # These specs are about the reception; the work order task is tested with the work order stub_const('ApiOperation::TASKS', { 'reception_and_work_order' => %w[reception] }) + stub_request(:post, configatron.integration_hub.operation_callback_url).to_return(status: 202) create(:input_plate_purpose, name: 'Library Stock Plate') allow(SampleManifestExcel.configuration) .to receive(:tag_group).and_return('Magic Tag Group')