Class: Cohere::Transcribe::Internal::SessionOwnership

Inherits:
Object
  • Object
show all
Defined in:
lib/cohere/transcribe/internal/session_ownership.rb

Overview

Detached, thread-safe session state for explicit close and ObjectSpace finalization. The close callable must not retain the owner whose finalizer holds this object.

Constant Summary collapse

CLOSE_RUBY_SESSION =
:close.to_proc.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(close: CLOSE_RUBY_SESSION, installed_error: "Session ownership is already installed") ⇒ SessionOwnership

Returns a new instance of SessionOwnership.

Raises:

  • (ArgumentError)


18
19
20
21
22
23
24
25
# File 'lib/cohere/transcribe/internal/session_ownership.rb', line 18

def initialize(close: CLOSE_RUBY_SESSION, installed_error: "Session ownership is already installed")
  raise ArgumentError, "close must respond to call" unless close.respond_to?(:call)

  @close = close
  @installed_error = installed_error.freeze
  @mutex = Mutex.new
  @session = nil
end

Class Method Details

.finalizer_for(ownership) ⇒ Object



14
15
16
# File 'lib/cohere/transcribe/internal/session_ownership.rb', line 14

def self.finalizer_for(ownership)
  proc { |_object_id| ownership.finalize }
end

Instance Method Details

#closeObject



39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/cohere/transcribe/internal/session_ownership.rb', line 39

def close
  Thread.handle_interrupt(Object => :never) do
    session = @mutex.synchronize do
      current = @session
      @session = nil
      current
    end
    return unless session

    @close.call(session)
  end
  nil
end

#finalizeObject



53
54
55
56
57
# File 'lib/cohere/transcribe/internal/session_ownership.rb', line 53

def finalize
  close
rescue Exception # rubocop:disable Lint/RescueException -- finalizers must not escape during GC or shutdown
  nil
end

#install(session) ⇒ Object



31
32
33
34
35
36
37
# File 'lib/cohere/transcribe/internal/session_ownership.rb', line 31

def install(session)
  @mutex.synchronize do
    raise TranscriptionRuntimeError, @installed_error if @session

    @session = session
  end
end

#sessionObject



27
28
29
# File 'lib/cohere/transcribe/internal/session_ownership.rb', line 27

def session
  @mutex.synchronize { @session }
end