Module: Socketry::Timeout

Included in:
Socketry::TCP::Server, Socketry::TCP::Socket, UDP::Socket
Defined in:
lib/socketry/timeout.rb

Overview

Timeout subsystem

Constant Summary collapse

DEFAULT_TIMER =
Hitimes::Interval
DEFAULT_TIMEOUTS =

Default timeouts (in seconds)

{
  read:    5,
  write:   5,
  connect: 5
}.freeze

Instance Method Summary collapse

Instance Method Details

#clear_timeout(timeout) ⇒ Object

Clear an already-set timeout

Parameters:

  • timeout (Numeric)

    to gauge whether the timeout actually needs to be cleared

Raises:



56
57
58
59
60
# File 'lib/socketry/timeout.rb', line 56

def clear_timeout(timeout)
  return unless timeout
  raise Socketry::InternalError, "no deadline set" unless @deadline
  @deadline = nil
end

#lifetimeFloat

Return how long since the timer has been started

Returns:

  • (Float)

    number of seconds since the timer has been started

Raises:



34
35
36
37
# File 'lib/socketry/timeout.rb', line 34

def lifetime
  raise Socketry::InternalError, "timer not started" unless @timer
  @timer.to_f
end

#set_timeout(timeout) ⇒ Float

Set a timeout. Only one timeout may be active at a given time for a given object.

Parameters:

  • timeout (Numeric)

    number of seconds until the timeout is reached

Returns:

  • (Float)

    deadline (relative to #lifetime) at which the timeout is reached

Raises:



44
45
46
47
48
49
50
# File 'lib/socketry/timeout.rb', line 44

def set_timeout(timeout)
  raise Socketry::InternalError, "deadline already set" if @deadline
  return unless timeout
  raise Socketry::TimeoutError, "time expired" if timeout < 0

  @deadline = lifetime + timeout
end

#start_timer(timer = DEFAULT_TIMER_CLASS.new) ⇒ true

Start a timer in the included object

Parameters:

  • timer (#start, #to_f) (defaults to: DEFAULT_TIMER_CLASS.new)

    a timer object (ideally monotonic)

Returns:

  • (true)

    timer started successfully

Raises:



20
21
22
23
24
25
26
27
28
# File 'lib/socketry/timeout.rb', line 20

def start_timer(timer = DEFAULT_TIMER_CLASS.new)
  raise Socketry::InternalError, "timer already started" if defined?(@timer)
  raise Socketry::InternalError, "deadline already set"  if defined?(@deadline)

  @deadline = nil
  @timer = timer
  @timer.start
  true
end

#time_remaining(timeout) ⇒ Float

Calculate number of seconds remaining until we hit the timeout

Parameters:

  • timeout (Numeric)

    to gauge whether a timeout needs to be calculated

Returns:

  • (Float)

    number of seconds remaining until we hit the timeout

Raises:



68
69
70
71
72
73
74
# File 'lib/socketry/timeout.rb', line 68

def time_remaining(timeout)
  return unless timeout
  raise Socketry::InternalError, "no deadline set" unless @deadline
  remaining = @deadline - lifetime
  raise Socketry::TimeoutError, "time expired" if remaining <= 0
  remaining
end