Class: RText::Service

Inherits:
Object
  • Object
show all
Includes:
MessageHelper
Defined in:
lib/rtext/service.rb

Constant Summary collapse

PortRangeStart =
9001
PortRangeEnd =
9100
FlushInterval =
1
ProtocolVersion =
1

Instance Method Summary collapse

Methods included from MessageHelper

#each_json_object_string, #escape_all_strings, #extract_message, #serialize_message, #unescape_all_strings

Methods included from JsonInterface

#json_to_object, #object_to_json, set_j2o_converter, set_o2j_converter

Constructor Details

#initialize(service_provider, options = {}) ⇒ Service

Creates an RText backend service. Options:

:timeout
  idle time in seconds after which the service will terminate itself

:logger
  a logger object on which the service will write its logging output

:on_startup:
  a Proc which is called right after the service has started up
  can be used to output version information


33
34
35
36
37
38
39
40
41
# File 'lib/rtext/service.rb', line 33

def initialize(service_provider, options={})
  @service_provider = service_provider
  @timeout = options[:timeout] || 60
  @logger = options[:logger]
  @on_startup = options[:on_startup]
  @lock_file_path = options[:lock_file_path] || File.expand_path('.rtext.lock')
  @config_file_path = options[:config_file_path] || File.expand_path('.rtext.config')
  @lock_file = nil
end

Instance Method Details

#message_received(sock, obj) ⇒ Object



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/rtext/service.rb', line 113

def message_received(sock, obj)
  if check_request(obj) 
    request_start = Time.now
    @logger.debug("request: "+obj.inspect) if @logger
    response = { "type" => "response", "invocation_id" => obj["invocation_id"] }
    case obj["command"]
    when "version"
      version(sock, obj, response)  
    when "load_model"
      load_model(sock, obj, response)
    when "content_complete"
      content_complete(sock, obj, response)
    when "link_targets" 
      link_targets(sock, obj, response)
    when "find_elements"
      find_elements(sock, obj, response)
    when "stop"
      @logger.info("RText service, stopping now (stop requested)") if @logger
      @stop_requested = true
    else
      @logger.warn("unknown command #{obj["command"]}") if @logger
      response["type"] = "unknown_command_error"
      response["command"] = obj["command"] 
    end
    @logger.debug("response: "+truncate_response_for_debug_output(response).inspect) \
      if response && @logger
    send_response(sock, response)
    @logger.info("request complete (#{Time.now-request_start}s)")
  end
end

#runObject



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/rtext/service.rb', line 43

def run
  Filelock @lock_file_path, :timeout => 0, :wait => 1 do
    server = create_server 
    puts "RText service, listening on port #{server.addr[1]}"
    @logger.debug('Server started') if @logger
    File.write(@config_file_path, YAML.dump({'port' => server.addr[1], 'pid' => Process.pid}))
    begin
      @on_startup.call if @on_startup
      $stdout.flush
    
      last_access_time = Time.now
      last_flush_time = Time.now
      @stop_requested = false
      sockets = []
      request_data = {}
      while !@stop_requested
        begin
          sock = server.accept_nonblock
          sock.sync = true
          sockets << sock
          @logger.info "accepted connection" if @logger
        rescue Errno::EAGAIN, Errno::ECONNABORTED, Errno::EPROTO, Errno::EINTR, Errno::EWOULDBLOCK
        rescue Exception => e
          @logger.warn "unexpected exception during socket accept: #{e.class}"
        end
        sockets.dup.each do |sock|
          data = nil
          begin
            data = sock.read_nonblock(100000)
            @logger.debug('Got data') if @logger
          rescue Errno::EWOULDBLOCK
          rescue IOError, EOFError, Errno::ECONNRESET, Errno::ECONNABORTED
            sock.close
            request_data[sock] = nil
            sockets.delete(sock)
          rescue Exception => e
            # catch Exception to make sure we don't crash due to unexpected exceptions
            @logger.warn "unexpected exception during socket read: #{e.class}"
            sock.close
            request_data[sock] = nil
            sockets.delete(sock)
          end
          if data
            last_access_time = Time.now
            request_data[sock] ||= ""
            request_data[sock].concat(data)
            @logger.debug("Data available: #{request_data[sock]}") if @logger
            while obj = extract_message(request_data[sock])
              @logger.debug("Got message #{obj.inspect}") if @logger
              message_received(sock, obj)
            end
          end
        end
        IO.select([server] + sockets, [], [], 1)
        if Time.now > last_access_time + @timeout
          @logger.info("RText service, stopping now (timeout)") if @logger
          break 
        end
        if Time.now > last_flush_time + FlushInterval
          $stdout.flush
          last_flush_time = Time.now
        end
      end
    ensure
      @logger.warn("Config file doesn't exist, but lock is acquired, it could be a bug") unless File.exist?(@config_file_path)
      File.unlink(@config_file_path) if File.exist?(@config_file_path)
    end
  end
end