diff --git a/app/jobs/send_file_to_print_host_job.rb b/app/jobs/send_file_to_print_host_job.rb new file mode 100644 index 000000000..01de6fb9b --- /dev/null +++ b/app/jobs/send_file_to_print_host_job.rb @@ -0,0 +1,11 @@ +class SendFileToPrintHostJob < ApplicationJob + queue_as :low + unique :until_executed + + def perform(print_host:, file:) + service = print_host.service + # Check print host is OK before sending, otherwise raise an ArgumentError to try again later + raise PrintHost::NotReady unless service.ok? + service.upload(file: file, start_print: true) + end +end diff --git a/app/models/print_host.rb b/app/models/print_host.rb index c772d7ec1..9c70e4715 100644 --- a/app/models/print_host.rb +++ b/app/models/print_host.rb @@ -3,6 +3,9 @@ class PrintHost < ApplicationRecord PROTOCOLS = Print.constants.map { [const_get("Print::#{it}::PROTOCOL"), const_get("Print::#{it}")] }.to_h.freeze + class NotReady < RuntimeError + end + validates :name, presence: true validates :endpoint, presence: true validates :protocol, presence: true, inclusion: {in: PROTOCOLS.keys} diff --git a/spec/jobs/send_file_to_print_host_job_spec.rb b/spec/jobs/send_file_to_print_host_job_spec.rb new file mode 100644 index 000000000..76fd0bad8 --- /dev/null +++ b/spec/jobs/send_file_to_print_host_job_spec.rb @@ -0,0 +1,23 @@ +require "rails_helper" + +RSpec.describe SendFileToPrintHostJob do + let(:print_host) { create(:print_host) } + let(:file) { create(:model_file, filename: "test.gcode") } + + it "raises PrintHost::NotReady if printer is not ok" do + stub_service = instance_double(Print::MoonrakerService) + allow(stub_service).to receive(:ok?).and_return(false) + allow(print_host).to receive(:service).and_return(stub_service) + + expect { described_class.perform_now(print_host: print_host, file: file) }.to raise_error PrintHost::NotReady + end + + it "calls upload method in relevant print service" do # rubocop:disable RSpec/ExampleLength + stub_service = instance_double(Print::MoonrakerService) + allow(stub_service).to receive(:ok?).and_return(true) + allow(stub_service).to receive(:upload) + allow(print_host).to receive(:service).and_return(stub_service) + described_class.perform_now(print_host: print_host, file: file) + expect(stub_service).to have_received(:upload).with(file: file, start_print: true).once + end +end