Class: EasyServe::Service

Inherits:
Object
  • Object
show all
Defined in:
lib/easy-serve/service.rb,
lib/easy-serve/service/tunnelled.rb

Overview

Refers to a named service. Use the #serve method to start the service. Encapsulates current location and identity, including pid and address. A Service object can be serialized to a remote process so it can #connect to the service.

Direct Known Subclasses

TCPService, UNIXService

Constant Summary collapse

SERVICE_CLASS =
{}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Service

Returns a new instance of Service.



18
19
20
# File 'lib/easy-serve/service.rb', line 18

def initialize name
  @name = name
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



7
8
9
# File 'lib/easy-serve/service.rb', line 7

def name
  @name
end

#pidObject (readonly)

Returns the value of attribute pid.



8
9
10
# File 'lib/easy-serve/service.rb', line 8

def pid
  @pid
end

Class Method Details

.for(name, proto, **opts) ⇒ Object



12
13
14
15
16
# File 'lib/easy-serve/service.rb', line 12

def self.for name, proto, **opts
  sc = SERVICE_CLASS[proto] or
    raise ArgumentError, "Unknown socket protocol: #{proto.inspect}"
  sc.new name, **opts
end

Instance Method Details

#cleanupObject



50
51
52
53
# File 'lib/easy-serve/service.rb', line 50

def cleanup
  Process.kill "TERM", pid
  Process.waitpid pid
end

#connectObject

Returns the client socket.



23
24
25
26
27
28
# File 'lib/easy-serve/service.rb', line 23

def connect
  try_connect
rescue => ex
  ex.message << "; #{inspect}"
  raise
end

#serve(max_tries: 1, log: (raise ArgumentError, "missing log")) ⇒ Object

Returns the server socket.



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/easy-serve/service.rb', line 31

def serve max_tries: 1, log: (raise ArgumentError, "missing log")
  tries = 1
  begin
    try_serve.tap do
      @pid = Process.pid
    end

  rescue Errno::EADDRINUSE => ex
    raise if tries >= max_tries
    log.warn {"#{ex}; #{inspect} (#{tries}/#{max_tries} tries)"}
    tries += 1; bump!
    log.info {"Trying: #{inspect}"}
    retry
  end
rescue => ex
  ex.message << "; #{inspect}"
  raise
end

#tunnelledObject



5
6
7
# File 'lib/easy-serve/service/tunnelled.rb', line 5

def tunnelled(*)
  [self, nil]
end