Class: Protobuf::Rpc::Services::Base

Inherits:
Protobuf::Rpc::Service
  • Object
show all
Defined in:
lib/protobuf/rpc/services/base.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.define_rpc(method, req = ::Protobuf::Rpc::Messages::RpcCompressedMessage, res = ::Protobuf::Rpc::Messages::RpcCompressedMessage) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
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
# File 'lib/protobuf/rpc/services/base.rb', line 30

def self.define_rpc(method, req = ::Protobuf::Rpc::Messages::RpcCompressedMessage, res = ::Protobuf::Rpc::Messages::RpcCompressedMessage)
  self.rpc method, req, res

  define_method(method) do
    class_name = method.to_s.camelize.gsub('!', 'Bang').gsub('?', 'QuestionMark')
    result = nil
    req = Serializer.load(request)

    logger.debug(req.to_hash)

    begin
      interaction = "#{self.class.namespace}::Interactions::#{self.class.name.demodulize}::#{class_name}".constantize
    rescue LoadError, NameError => e
      logger.error(e)
      NewRelic::Agent.notice_error(e) if defined?(NewRelic::Agent)
      result = ::Protobuf::Rpc::MethodNotFound.new("host: #{::Socket.gethostname}, message: #{e.message}")
      result.set_backtrace(e.backtrace)
    else
      begin
        result = interaction.run!(req.to_hash)
        case result
          when ::Protobuf::Message
            result
          when ::ActiveRecord::Base, ::ActiveRecord::Relation
            result = result.to_proto(deprecated: false, except: interaction.except_attributes, include: interaction.include_attributes)
          else
            result.respond_to?(:to_proto) ? result.to_proto : result
        end
      rescue => e
        logger.error(e)
        NewRelic::Agent.notice_error(e) if defined?(NewRelic::Agent)
        result = e
      end
    end

    compress_with result
  end

  add_transaction_tracer method
end

.inherit_rpcs!Object



26
27
28
# File 'lib/protobuf/rpc/services/base.rb', line 26

def self.inherit_rpcs!
  superclass.rpcs.keys.each { |x| define_rpc(x) }
end

.inherited(subclass) ⇒ Object



16
17
18
19
20
# File 'lib/protobuf/rpc/services/base.rb', line 16

def self.inherited(subclass)
  require 'new_relic/agent'
  subclass.include ::NewRelic::Agent::Instrumentation::ControllerInstrumentation
  subclass.inherit_rpcs!
end

.namespaceObject



22
23
24
# File 'lib/protobuf/rpc/services/base.rb', line 22

def self.namespace
  self.name.deconstantize.deconstantize
end

Instance Method Details

#compress_with(msg, serializer: :MSGPACK) ⇒ Object



9
10
11
12
13
14
# File 'lib/protobuf/rpc/services/base.rb', line 9

def compress_with(msg, serializer: :MSGPACK)
  if msg.is_a?(StandardError)
    msg = ::Protobuf::Rpc::Messages::Error.new(error_class: msg.class.name, error_message: msg.message, error_backtrace: msg.backtrace)
  end
  respond_with Serializer.dump(msg, serializer: serializer)
end