Class: Hyperloop::ServerOp

Inherits:
Operation show all
Extended by:
React::IsomorphicHelpers
Defined in:
lib/hyper-operation/server_op.rb

Direct Known Subclasses

ControllerOp

Constant Summary

Constants inherited from Operation

Operation::VERSION

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Operation

_Railway, _run, #abort!, #add_error, add_error, async, fail, failed, #has_errors?, inbound, inherited, #initialize, on_dispatch, outbound, param, #params, run, step, #succeed!, then, validate

Constructor Details

This class inherits a constructor from Hyperloop::Operation

Class Method Details

.descendants_map_cacheObject


47
48
49
50
# File 'lib/hyper-operation/server_op.rb', line 47

def descendants_map_cache
  # calling descendants alone may take 10ms in a complex app, so better cache it
  @cached_descendants ||= Hyperloop::ServerOp.descendants.map(&:to_s)
end

.deserialize_dispatch(hash) ⇒ Object


134
135
136
# File 'lib/hyper-operation/server_op.rb', line 134

def deserialize_dispatch(hash)
  hash
end

.deserialize_params(hash) ⇒ Object


118
119
120
# File 'lib/hyper-operation/server_op.rb', line 118

def deserialize_params(hash)
  hash
end

.deserialize_response(hash) ⇒ Object


126
127
128
# File 'lib/hyper-operation/server_op.rb', line 126

def deserialize_response(hash)
  hash
end

.dispatch_from_server(params_hash) ⇒ Object


161
162
163
164
# File 'lib/hyper-operation/server_op.rb', line 161

def dispatch_from_server(params_hash)
  params = _Railway.params_wrapper.new(deserialize_dispatch(params_hash)).lock
  _Railway.receivers.each { |receiver| receiver.call params }
end

.dispatch_to(*args, &regulation) ⇒ Object


138
139
140
# File 'lib/hyper-operation/server_op.rb', line 138

def dispatch_to(*args, &regulation)
  _dispatch_to(nil, args, &regulation) if RUBY_ENGINE != 'opal'
end

.handle_exception(e, operation, params) ⇒ Object


87
88
89
90
91
92
93
94
# File 'lib/hyper-operation/server_op.rb', line 87

def handle_exception(e, operation, params)
  if defined? ::Rails
    params.delete(:controller)
    ::Rails.logger.debug "\033[0;31;1mERROR: Hyperloop::ServerOp exception caught when running "\
                         "#{operation} with params \"#{params}\": #{e}\033[0;30;21m"
  end
  { json: { error: e }, status: 500 }
end

.remote(path, *args) ⇒ Object


97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/hyper-operation/server_op.rb', line 97

def remote(path, *args)
  promise = Promise.new
  uri = URI("#{path}execute_remote_api")
  http = Net::HTTP.new(uri.host, uri.port)
  request = Net::HTTP::Post.new(uri.path, 'Content-Type' => 'application/json')
  if uri.scheme == 'https'
    http.use_ssl = true
  end
  request.body = {
    operation: name,
    params: Hyperloop::Operation::ParamsWrapper.combine_arg_array(args)
  }.to_json
  promise.resolve http.request(request)
rescue Exception => e
  promise.reject e
end

.run_from_client(security_param, controller, operation, params) ⇒ Object


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
# File 'lib/hyper-operation/server_op.rb', line 52

def run_from_client(security_param, controller, operation, params)
  if Rails.env.production?
    # in production everything is eager loaded so ServerOp.descendants is filled and can be used to guard the .constantize
    unless Hyperloop::ServerOp.descendants_map_cache.include?(operation)
      Hyperloop::InternalPolicy.raise_operation_access_violation(:illegal_remote_op_call, "Operation: #{operation} (in production)")
    end
    # however ...
  else
    # ... in development things are autoloaded on demand, thus ServerOp.descendants can be empty or partially filled and above guard
    # would fail legal operations. To prevent this, the class has to be loaded first, what .const_get will take care of, and then
    # its guarded, to achieve similar behaviour as in production. Doing the const_get first, before the guard,
    # would not be safe for production and allow for potential remote code execution!
    begin
      const = Object.const_get(operation)
    rescue NameError
      Hyperloop::InternalPolicy.raise_operation_access_violation(:illegal_remote_op_call, "Operation: #{operation} (const not found)")
    end
    unless const < Hyperloop::ServerOp
      Hyperloop::InternalPolicy.raise_operation_access_violation(:illegal_remote_op_call, "Operation: #{operation} (not a ServerOp subclass)")
    end
  end
  operation.constantize.class_eval do
    if _Railway.params_wrapper.method_defined?(:controller)
      params[:controller] = controller
    elsif !_Railway.params_wrapper.method_defined?(security_param)
      raise AccessViolation
    end
    run(deserialize_params(params))
    .then { |r| return { json: { response: serialize_response(r) } } }
    .fail { |e| return handle_exception(e, operation, params) }
  end
rescue Exception => e
  handle_exception(e, operation, params)
end

.serialize_dispatch(hash) ⇒ Object


130
131
132
# File 'lib/hyper-operation/server_op.rb', line 130

def serialize_dispatch(hash)
  hash
end

.serialize_params(hash) ⇒ Object


114
115
116
# File 'lib/hyper-operation/server_op.rb', line 114

def serialize_params(hash)
  hash
end

.serialize_response(hash) ⇒ Object


122
123
124
# File 'lib/hyper-operation/server_op.rb', line 122

def serialize_response(hash)
  hash
end

Instance Method Details

#_dispatch_to(context, args = [], &regulation) ⇒ Object


142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/hyper-operation/server_op.rb', line 142

def _dispatch_to(context, args=[], &regulation)
  if args.count == 0 && regulation.nil?
    raise "must provide either a list of channel classes or a block to regulate_dispatch"
  elsif args.count > 0 && regulation
    raise "cannot provide both a list of channel classes and a block to regulate_dispatch"
  end
  regulation ||= proc { args }
  on_dispatch do |params, operation|
    operation.instance_variable_set(:@_dispatched_channels, []) unless operation.instance_variable_get(:@_dispatched_channels)
    serialized_params = serialize_dispatch(params.to_h)
    [operation.instance_exec(*context, &regulation)].flatten.compact.uniq.each do |channel|
      unless operation.instance_variable_get(:@_dispatched_channels).include?(channel)
        operation.instance_variable_set(:@_dispatched_channels, operation.instance_variable_get(:@_dispatched_channels) << channel)
        Hyperloop.dispatch(channel: Hyperloop::InternalPolicy.channel_to_string(channel), operation: operation.class.name, params: serialized_params)
      end
    end
  end
end

#run(*args) ⇒ Object


11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/hyper-operation/server_op.rb', line 11

def run(*args)
  hash = _Railway.params_wrapper.combine_arg_array(args)
  hash = serialize_params(hash)
  Hyperloop::HTTP.post(
    "#{`window.HyperloopEnginePath`}/execute_remote",
    payload: {json: {operation: name, params: hash}.to_json},
    headers: {'X-CSRF-Token' => Hyperloop::ClientDrivers.opts[:form_authenticity_token] }
    )
  .then do |response|
    deserialize_response response.json[:response]
  end
  .fail do |response|
    Exception.new response.json[:error]
  end
end