Class: RSpec::Multicore::Channel

Inherits:
Object
  • Object
show all
Defined in:
lib/rspec/multicore/channel.rb

Overview

Transfers bounded plain-value frames over a local socket pair.

Constant Summary collapse

HEADER_SIZE =
4
MAX_FRAME_SIZE =
10 * 1024 * 1024
PLAIN_VALUES =
[NilClass, TrueClass, FalseClass, Integer, Float, String, Symbol].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(socket) ⇒ Channel

Returns a new instance of Channel.



17
18
19
20
# File 'lib/rspec/multicore/channel.rb', line 17

def initialize(socket)
  @socket = socket
  @write_lock = Mutex.new
end

Instance Attribute Details

#socketObject (readonly)

Returns the value of attribute socket.



13
14
15
# File 'lib/rspec/multicore/channel.rb', line 13

def socket
  @socket
end

Class Method Details

.pairObject



15
# File 'lib/rspec/multicore/channel.rb', line 15

def self.pair = UNIXSocket.pair.map { new(_1) }

Instance Method Details

#closeObject



49
50
51
52
53
# File 'lib/rspec/multicore/channel.rb', line 49

def close
  socket.close unless socket.closed?
rescue IOError, SystemCallError
  nil
end

#closed?Boolean

Returns:

  • (Boolean)


55
# File 'lib/rspec/multicore/channel.rb', line 55

def closed? = socket.closed?

#readObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/rspec/multicore/channel.rb', line 33

def read
  header = read_exactly(HEADER_SIZE)
  return if header.nil?

  length = header.unpack1("N")
  raise Error, "Invalid Channel frame size: #{length}" unless length.between?(1, MAX_FRAME_SIZE)

  payload = read_exactly(length, "frame")

  value = Marshal.load(payload)
  validate!(value)
  value
rescue TypeError, ArgumentError => e
  raise Error, "Invalid Channel frame: #{e.message}"
end

#write(value) ⇒ Object



22
23
24
25
26
27
28
29
30
31
# File 'lib/rspec/multicore/channel.rb', line 22

def write(value)
  validate!(value)
  payload = Marshal.dump(value)
  raise Error, "Channel frame exceeds #{MAX_FRAME_SIZE} bytes" if payload.bytesize > MAX_FRAME_SIZE

  @write_lock.synchronize { write_all([payload.bytesize].pack("N") + payload) }
  nil
rescue IOError, SystemCallError => e
  raise Error, "Channel write failed: #{e.message}"
end