Class: SeoBatchResultsWorker

Inherits:
Object
  • Object
show all
Includes:
Sidekiq::Status::Worker, Sidekiq::Worker
Defined in:
app/workers/seo_batch_results_worker.rb

Overview

Phase 2c: Process results from a completed Batch API job.

Routes by provider (Gemini or Anthropic), parses each response,
extracts the JSON analysis, and saves it to:

  • SeoBatchItem#result (for auditing)
  • SiteMap#seo_report (the live analysis used by the CRM)

Usage:
SeoBatchResultsWorker.perform_async(batch_job_id)

Instance Method Summary collapse

Instance Method Details

#perform(batch_job_id) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'app/workers/seo_batch_results_worker.rb', line 19

def perform(batch_job_id)
  batch_job = SeoBatchJob.find(batch_job_id)

  unless batch_job.processing?
    log_info "Batch job #{batch_job_id} is #{batch_job.status} — skipping results"
    return
  end

  log_info "Processing results for batch #{batch_job.provider_batch_id}"

  stats = { succeeded: 0, errored: 0, expired: 0, canceled: 0, parse_errors: 0 }
  items_by_custom_id = batch_job.items.index_by(&:custom_id)

  if batch_job.gemini?
    process_gemini_results(batch_job, items_by_custom_id, stats)
    cleanup_gemini_cache(batch_job)
  else
    process_anthropic_results(batch_job, items_by_custom_id, stats)
  end

  batch_job.mark_completed!(
    succeeded: stats[:succeeded],
    errored: stats[:errored] + stats[:parse_errors],
    expired: stats[:expired] + stats[:canceled]
  )

  summary = "Results: #{stats[:succeeded]} succeeded, #{stats[:errored]} errored, " \
            "#{stats[:expired]} expired, #{stats[:parse_errors]} parse errors"
  log_info summary
  store info_message: summary
rescue Seo::GeminiBatchClient::BatchError, Seo::AnthropicBatchClient::BatchError => e
  log_error "Failed to fetch results: #{e.message}"
  batch_job.mark_failed!("Results fetch failed: #{e.message}")
end