Last active
August 2, 2019 21:03
-
-
Save 0legovich/3ad4b6be6eb5b8ab2d83d88397a3b82f to your computer and use it in GitHub Desktop.
Пример использования ActionController::Live для проверка статуса выполнения асинхронной джобы.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
class AsyncJobController < ApplicationController # :nodoc: | |
include ActionController::Live | |
before_action :initialize_job_id, only: :status_live | |
JOB_DATA_KEYS = %i[pct_complete status message].freeze | |
PCT_FINISHED = 100 | |
STATUS_FINISHED = 'complete' | |
def status_live | |
return render status: 404 if !@job_id || job_info.blank? | |
response.headers['Content-Type'] = 'text/event-stream' | |
sse = SSE.new(response.stream, event: "job_id_#{@job_id}", id: @job_id) | |
loop do | |
if job_info[:status] == STATUS_FINISHED && job_info[:pct_complete].to_i == PCT_FINISHED | |
sse.write(job_info) | |
return sse.close | |
end | |
sse.write(job_info) | |
sleep 1 | |
end | |
rescue ActionController::Live::ClientDisconnected | |
ensure | |
sse.close if sse | |
end | |
private | |
def initialize_job_id | |
@job_id = params[:job_id] == 'null' ? nil : params[:job_id] | |
end | |
def job_info | |
Sidekiq::Status::get_all(@job_id).symbolize_keys.reject { |key| JOB_DATA_KEYS.exclude? key } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment