Module: Cohere::Transcribe::Internal::InterruptibleNativeCall

Defined in:
lib/cohere/transcribe/internal/interruptible_native_call.rb

Overview

Runs a blocking foreign call on a dedicated worker so the caller remains interruptible. Callbacks are retained only for this invocation; callers remain responsible for supplying non-poisoning cancellation behavior.

Class Method Summary collapse

Class Method Details

.run(cancel:, join_interval:, missing_outcome:, thread_name: nil) ⇒ Object

Raises:

  • (ArgumentError)


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/cohere/transcribe/internal/interruptible_native_call.rb', line 12

def run(cancel:, join_interval:, missing_outcome:, thread_name: nil)
  raise ArgumentError, "an operation block is required" unless block_given?

  outcome = Queue.new
  worker = nil
  Thread.handle_interrupt(Object => :on_blocking) do
    worker = Thread.new do
      outcome << [:returned, yield]
    rescue Exception => e # rubocop:disable Lint/RescueException -- transfer native cancellation intact
      outcome << [:raised, e]
    end
    worker.name = thread_name if thread_name && worker.respond_to?(:name=)
    worker.report_on_exception = false
    worker.join
  ensure
    if worker&.alive?
      Thread.handle_interrupt(Object => :never) do
        cancel_and_hard_join(worker, cancel, join_interval)
      end
    end
  end

  status, value = begin
    outcome.pop(true)
  rescue ThreadError
    raise missing_outcome
  end
  raise value if status == :raised

  value
end