Class: Services::Hl7InboundService

Inherits:
ServiceImplementation show all
Defined in:
app/models/services/hl7_inbound_service.rb

Instance Attribute Summary

Attributes inherited from ServiceImplementation

#service_definition

Instance Method Summary collapse

Methods inherited from ServiceImplementation

#account_map, #initialize, #server_credentials

Constructor Details

This class inherits a constructor from Services::ServiceImplementation

Instance Method Details

#invokeObject

Invoke, in this case will create the service loop on the socket server port and just hang out and handle the stuff



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'app/models/services/hl7_inbound_service.rb', line 9

def invoke
  server = TCPServer.open(service_definition.hostname, service_definition.port)
  loop do  # Servers run forever
    #
    # We put the accepted client in a separate thread to manage a high volume of
    # calls better. The AcceptHl7MessageContext call saves the Hl7Message
    # and puts the processing into beanstalk, so we shouldn't be in this
    # separate thread for long.
    #
    # Note that we fail fast if the message coming in doesn't have the
    # API key we are expecting. We don't save the incoming message in that
    # case because we don't know what we're getting. Could be evil.
    #
    Thread.start(server.accept) do |client|
      begin
        key = client.gets('|').chop # Don't want the last character '|'
        creds = service_definition.credentials.last
        if creds.present? && creds.token == key
          message_type = client.gets('|').chop
          raw_message = client.gets('|').chop
          AcceptHl7MessageContext.call(message_type, raw_message)
          client.puts( { status: 'accepted' }.to_json )
        else
          client.puts({ status: 'error', message: 'invalid key' }.to_json )
        end
      rescue Exception => ex
        puts ex.inspect
        client.puts( { status: 'error', errors: [ ex.message ] } )
      ensure
        client.close                # Disconnect from the client
      end
    end
  end
  
end