Class: Riddl::Server

Inherits:
Object
  • Object
show all
Includes:
Daemonism
Defined in:
lib/ruby/riddl/server.rb

Defined Under Namespace

Classes: Execution

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(riddl, opts = {}, &blk) ⇒ Server

{{{



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
# File 'lib/ruby/riddl/server.rb', line 48

def initialize(riddl,opts={},&blk)# {{{
  @riddl_opts = DAEMONISM_DEFAULT_OPTS.merge({
    :bind         => '0.0.0.0',
    :host         => 'localhost',
    :port         => 9292,
    :secure       => false,
    :verbose      => false,
    :http_only    => false,
    :runtime_opts => [
      ["--port [PORT]", "-p [PORT]", "Specify http port.", ->(p){
        @riddl_opts[:port] = p.to_i
        @riddl_opts[:pidfile] = @riddl_opts[:pidfile].gsub(/\.pid/,'') + '-' + @riddl_opts[:port].to_s + '.pid'
      }],
      ["--http-only", "-s", "Only http, no other protocols.", ->(){ @riddl_opts[:http_only] = true }]
    ],
    :runtime_cmds => [],
    :runtime_proc => Proc.new { |opts|
      @riddl_opts[:cmdl_info] = (@riddl_opts[:secure] ? 'https://' : 'http://') + @riddl_opts[:host] + ':' + @riddl_opts[:port].to_s
      @riddl_opts[:url] ||= @riddl_opts[:cmdl_info]
    }
  }).merge(opts)

  @riddl_logger             = nil
  @riddl_process_out        = true
  @riddl_cross_site_xhr     = false
  @accessible_description   = false
  @riddl_description_string = ''
  @riddl_paths              = []

  @riddl_at_exit            = nil

  @riddl_interfaces         = {}

  daemonism @riddl_opts, &blk

  @riddl = Riddl::Wrapper.new(riddl,@accessible_description)
  if @riddl.description?
    raise SpecificationError, 'RIDDL description does not conform to specification' unless @riddl.validate!
    @riddl_description_string = @riddl.description.xml
  elsif @riddl.declaration?
    raise SpecificationError, 'RIDDL declaration does not conform to specification' unless @riddl.validate!
    @riddl_description_string = @riddl.declaration.description_xml
  else
    raise SpecificationError, 'Not a RIDDL file'
  end

  @riddl.load_necessary_handlers!
  @riddl_paths = @riddl.paths
end

Instance Attribute Details

#riddl_logObject (readonly)

Returns the value of attribute riddl_log.



46
47
48
# File 'lib/ruby/riddl/server.rb', line 46

def riddl_log
  @riddl_log
end

#riddl_methodObject (readonly)

Returns the value of attribute riddl_method.



46
47
48
# File 'lib/ruby/riddl/server.rb', line 46

def riddl_method
  @riddl_method
end

#riddl_pinfoObject (readonly)

Returns the value of attribute riddl_pinfo.



46
47
48
# File 'lib/ruby/riddl/server.rb', line 46

def riddl_pinfo
  @riddl_pinfo
end

#riddl_statusObject (readonly)

Returns the value of attribute riddl_status.



46
47
48
# File 'lib/ruby/riddl/server.rb', line 46

def riddl_status
  @riddl_status
end

Instance Method Details

#__callObject

}}}



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/ruby/riddl/server.rb', line 160

def __call #{{{
  @riddl_message = @riddl.io_messages(@riddl_matching_path[0],@riddl_method,@riddl_parameters,@riddl_headers)
  if @riddl_message.nil?
    if @riddl_info[:env].has_key?('HTTP_ORIGIN') && @riddl_cross_site_xhr && @riddl_method == 'options'
      @riddl_res['Access-Control-Allow-Origin'] = '*'
      @riddl_res['Access-Control-Allow-Methods'] = 'GET, POST, PUT, PATCH, DELETE, OPTIONS'
      @riddl_res['Access-Control-Allow-Headers'] = @riddl_info[:env]['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'] if @riddl_info[:env]['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']
      @riddl_res['Access-Control-Max-Age'] = '0'
      @riddl_res['Content-Length'] = '0'
      @riddl_status = 200
    else
      @riddl_log.write "501: the #{@riddl_method} parameters are not matching anything in the description.\n"
      @riddl_status = 501 # not implemented?!
    end
  else
    if !@riddl_message.nil? && @accessible_description && @riddl_message.in.name == 'riddl-description-request' && @riddl_method == 'get' &&  '/' + @riddl_info[:s].join('/') == '/'
      run Riddl::Utils::Description::RDR, @riddl_description_string
    elsif !@riddl_message.nil? && @accessible_description && @riddl_message.in.name == 'riddl-resource-description-request' && @riddl_method == 'get'
      @riddl_path = File.dirname('/' + @riddl_info[:s].join('/')).gsub(/\/+/,'/')
      on resource File.basename('/' + @riddl_info[:s].join('/')).gsub(/\/+/,'/') do
        run Riddl::Utils::Description::RDR, @riddl.resource_description(@riddl_matching_path[0])
      end
    else
      if @riddl.description?
        instance_exec(@riddl_info, &@riddl_interfaces[nil])
      elsif @riddl.declaration?
        mess = @riddl_message
        @riddl_message.route_to_a.each do |m|
          @riddl_message = m
          @riddl_path = '/'
          if m.interface.base.nil?
            if @riddl_interfaces.key? m.interface.name
              @riddl_info[:r] = m.interface.real_path(@riddl_pinfo).sub(/^\//,'').split('/')
              @riddl_info[:h]['RIDDL_DECLARATION_PATH'] = @riddl_pinfo
              @riddl_info[:h]['RIDDL_DECLARATION_RESOURCE'] = m.interface.top
              @riddl_info[:s] = m.interface.sub.sub(/\//,'').split('/')
              @riddl_info.merge!(:match => matching_path)
              instance_exec(@riddl_info, &@riddl_interfaces[m.interface.name])
            else
              @riddl_log.write "501: not implemented (for remote: add @location in declaration; for local: add to Riddl::Server).\n"
              @riddl_status = 501 # not implemented?!
              break
            end
          else
            run Riddl::Utils::Description::Call, @riddl_exe, @riddl_pinfo, m.interface.top, m.interface.base, m.interface.real_path(@riddl_pinfo)
          end
          break if @riddl_status < 200 || @riddl_status >= 300
          @riddl_info.merge!(:h => @riddl_exe.headers, :p => @riddl_exe.response)
        end
        @riddl_message = mess
      end
    end
    if @riddl_info[:env].has_key?('HTTP_ORIGIN') && @riddl_cross_site_xhr
      @riddl_res['Access-Control-Allow-Origin'] = '*'
      @riddl_res['Access-Control-Max-Age'] = '0'
    end
  end
end

#__http_call(env) ⇒ Object

}}}



219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
# File 'lib/ruby/riddl/server.rb', line 219

def __http_call(env) #{{{
  @riddl_env = env
  @riddl_env['rack.logger'] =  @riddl_logger if @riddl_logger
  @riddl_log = @riddl_logger || @riddl_env['rack.errors']
  @riddl_res = Rack::Response.new
  @riddl_status = 404

  @riddl_pinfo = @riddl_env["PATH_INFO"].gsub(/\/+/,'/')
  @riddl_matching_path = @riddl_paths.find{ |e| @riddl_pinfo.match(e[1]).to_s.length == @riddl_pinfo.length }

  if @riddl_matching_path
    @riddl_query_string = @riddl_env['QUERY_STRING']
    @riddl_raw = @riddl_env['rack.input']

    @riddl_headers = {}
    @riddl_env.each do |h,v|
      @riddl_headers[$1] = v if h =~ /^HTTP_(.*)$/
    end
    @riddl_parameters = Protocols::HTTP::Parser.new(
      @riddl_query_string,
      @riddl_raw,
      @riddl_env['CONTENT_TYPE'],
      @riddl_env['CONTENT_LENGTH'],
      @riddl_env['HTTP_CONTENT_DISPOSITION'],
      @riddl_env['HTTP_CONTENT_ID'],
      @riddl_env['HTTP_RIDDL_TYPE']
    ).params

    @riddl_method = @riddl_env['REQUEST_METHOD'].downcase
    @riddl_path = '/'
    @riddl_info = {
      :h => @riddl_headers,
      :p => @riddl_parameters,
      :r => @riddl_pinfo.sub(/^\//,'').split('/').map{|e|Protocols::Utils::unescape(e)},
      :s => @riddl_matching_path[0].sub(/\//,'').split('/'),
      :m => @riddl_method,
      :env => @riddl_env.reject{|k,v| k =~ /^rack\./}.merge({'riddl.transport' => 'http', 'custom_protocol' => @riddl_opts[:custom_protocol]}),
      :match => []
    }

    if @riddl_info[:env]['HTTP_CONNECTION'] =~ /Upgrade/ && @riddl_info[:env]['HTTP_UPGRADE'] =~ /\AWebSocket\z/i
      # TODO raise error when declaration and route or (not route and non-local interface)
      # raise SpecificationError, 'RIDDL description does not conform to specification' unless @riddl.validate!
      @riddl_info[:m] = @riddl_method = 'websocket'
      @riddl_message = @riddl.io_messages(@riddl_matching_path[0],'websocket',@riddl_parameters,@riddl_headers)
      if @riddl.description?
        instance_exec(@riddl_info, &@riddl_interfaces[nil])
      elsif @riddl.declaration?
        # one ws connection, no overlay
        unless @riddl_message.nil?
          if @riddl_interfaces.key? @riddl_message.interface.name
            @riddl_info[:r] = @riddl_message.interface.real_path(@riddl_pinfo).sub(/^\//,'').split('/')
            @riddl_info[:h]['RIDDL_DECLARATION_PATH'] = @riddl_pinfo
            @riddl_info[:h]['RIDDL_DECLARATION_RESOURCE'] = @riddl_message.interface.top
            @riddl_info[:s] = @riddl_message.interface.sub.sub(/\//,'').split('/')
            @riddl_info.merge!(:match => matching_path)
            instance_exec(@riddl_info, &@riddl_interfaces[@riddl_message.interface.name])
          end
        end
      end
      throw :async
    elsif @riddl_info[:env]['HTTP_ACCEPT'] == 'text/event-stream'
      @riddl_info[:m] = @riddl_method = 'sse'
      @riddl_message = @riddl.io_messages(@riddl_matching_path[0],'sse',@riddl_parameters,@riddl_headers)
      if @riddl.description?
        instance_exec(@riddl_info, &@riddl_interfaces[nil])
      elsif @riddl.declaration?
        # one ws connection, no overlay
        unless @riddl_message.nil?
          if @riddl_interfaces.key? @riddl_message.interface.name
            @riddl_info[:r] = @riddl_message.interface.real_path(@riddl_pinfo).sub(/^\//,'').split('/')
            @riddl_info[:h]['RIDDL_DECLARATION_PATH'] = @riddl_pinfo
            @riddl_info[:h]['RIDDL_DECLARATION_RESOURCE'] = @riddl_message.interface.top
            @riddl_info[:s] = @riddl_message.interface.sub.sub(/\//,'').split('/')
            @riddl_info.merge!(:match => matching_path)
            instance_exec(@riddl_info, &@riddl_interfaces[@riddl_message.interface.name])
          end
        end
      end
      throw :async
    else
      __call
    end
  else
    @riddl_log.write "404: this resource for sure does not exist.\n"
    @riddl_status = 404 # client requests wrong path
  end
  if @riddl_exe
    @riddl_res.write Protocols::HTTP::Generator.new(@riddl_exe.response,@riddl_res).generate.read
    @riddl_exe.headers.each do |n,h|
      @riddl_res[n] = h
    end
  end
  @riddl_res.status = @riddl_status
  @riddl_res.finish
end

#accessible_description(ad) ⇒ Object

}}}



325
326
327
# File 'lib/ruby/riddl/server.rb', line 325

def accessible_description(ad)# {{{
  @accessible_description = ad
end

#call(env) ⇒ Object

{{{



156
157
158
# File 'lib/ruby/riddl/server.rb', line 156

def call(env)# {{{
  dup.__http_call(env)
end

#cross_site_xhr(csxhr) ⇒ Object

}}}



319
320
321
# File 'lib/ruby/riddl/server.rb', line 319

def cross_site_xhr(csxhr)# {{{
  @riddl_cross_site_xhr = csxhr
end

#declaration_pathObject

}}}



416
417
418
# File 'lib/ruby/riddl/server.rb', line 416

def declaration_path #{{{
  @riddl_info[:h]['RIDDL_DECLARATION_PATH']
end

#declaration_resourceObject

}}}



419
420
421
# File 'lib/ruby/riddl/server.rb', line 419

def declaration_resource #{{{
  @riddl_info[:h]['RIDDL_DECLARATION_RESOURCE']
end

#delete(min = '*') ⇒ Object



405
# File 'lib/ruby/riddl/server.rb', line 405

def delete(min='*'); return false if @riddl_message.nil?; @riddl_path == '/' + @riddl_info[:s].join('/') && @riddl_message.in && min == @riddl_message.in.name && @riddl_method == 'delete'    end

#get(min = '*') ⇒ Object



404
# File 'lib/ruby/riddl/server.rb', line 404

def get(min='*');    return false if @riddl_message.nil?; @riddl_path == '/' + @riddl_info[:s].join('/') && @riddl_message.in && min == @riddl_message.in.name && @riddl_method == 'get'       end

#interface(name, &block) ⇒ Object

}}}



328
329
330
# File 'lib/ruby/riddl/server.rb', line 328

def interface(name,&block) #{{{
  @riddl_interfaces[name] = block
end

#logger(lgr) ⇒ Object

}}}



322
323
324
# File 'lib/ruby/riddl/server.rb', line 322

def logger(lgr)# {{{
  @riddl_logger = lgr
end

#loop!Object

}}}



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
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
143
144
145
146
147
148
149
150
# File 'lib/ruby/riddl/server.rb', line 98

def loop! #{{{
  app = Rack::Builder.new self
  unless @riddl_logger.nil?
    app.use Rack::CommonLogger, @riddl_logger
  end

  server = Rack::Server.new(
    :app => app,
    :Host => @riddl_opts[:bind],
    :Port => @riddl_opts[:port],
    :environment => @riddl_opts[:verbose] ? 'deployment' : 'none',
    :server => 'thin',
    :signals => false
  )
  if @riddl_opts[:custom_protocol] && !@riddl_opts[:http_only]
    @riddl_opts[:custom_protocol] = @riddl_opts[:custom_protocol].new(@riddl_opts)
    puts @riddl_opts[:custom_protocol].support if @riddl_opts[:custom_protocol].support
  end
  begin
    EM.run do
      if @riddl_opts[:secure]
        server.start do |srv|
          srv.ssl = true
          srv.ssl_options = @riddl_opts[:secure_options]
        end
      else
        server.start
      end

      if @riddl_opts[:custom_protocol] && !@riddl_opts[:http_only]
        @riddl_opts[:custom_protocol].start
      end

      [:INT, :TERM].each do |signal|
        Signal.trap(signal) do
          EM.stop
        end
      end

      if @riddl_opts[:parallel]
        EM.defer do
          @riddl_opts[:parallel].call
        end
      end
    end

  rescue => e
    if @riddl_opts[:custom_protocol] && !@riddl_opts[:http_only]
      @riddl_opts[:custom_protocol].error_handling(e)
    end
    puts "Server (#{@riddl_opts[:cmdl_info]}) stopped due to connection error (PID:#{Process.pid})"
  end
end

#matching_pathObject

{{{



412
413
414
# File 'lib/ruby/riddl/server.rb', line 412

def matching_path #{{{
  @riddl_path.sub(/\//,'').split('/')
end

#method(what) ⇒ Object

}}}



395
396
397
398
399
400
401
402
# File 'lib/ruby/riddl/server.rb', line 395

def method(what)# {{{
  if !@riddl_message.nil? && what.class == Hash && what.length == 1
    met, min = what.first
    @riddl_path == @riddl_matching_path[0] && min == @riddl_message.in.name && @riddl_method == met.to_s.downcase
  else
    false
  end
end

#on(resource, &block) ⇒ Object

}}}



332
333
334
335
336
337
338
339
340
341
342
343
344
345
# File 'lib/ruby/riddl/server.rb', line 332

def on(resource, &block)# {{{
  if @riddl_paths.empty? # default interface, when a description and "on" syntax in server
    @riddl_interfaces[nil] = block
    return
  end

  @riddl_path << (@riddl_path == '/' ? resource : '/' + resource)

  ### only descend when there is a possibility that it holds the right path
  rp = @riddl_path.sub(/\//,'').split('/')

  block.call(@riddl_info.merge!(:match => matching_path)) if @riddl_info[:s][rp.length-1] == rp.last
  @riddl_path = File.dirname(@riddl_path).gsub(/\/+/,'/')
end

#parallel(&blk) ⇒ Object

}}}



152
153
154
# File 'lib/ruby/riddl/server.rb', line 152

def parallel(&blk)
  @riddl_opts[:parallel] = blk
end

#patch(min = '*') ⇒ Object



407
# File 'lib/ruby/riddl/server.rb', line 407

def patch(min='*');  return false if @riddl_message.nil?; @riddl_path == '/' + @riddl_info[:s].join('/') && @riddl_message.in && min == @riddl_message.in.name && @riddl_method == 'patch'     end

#post(min = '*') ⇒ Object

}}}



403
# File 'lib/ruby/riddl/server.rb', line 403

def post(min='*');   return false if @riddl_message.nil?; @riddl_path == '/' + @riddl_info[:s].join('/') && @riddl_message.in && min == @riddl_message.in.name && @riddl_method == 'post'      end

#process_out(pout) ⇒ Object

}}}



316
317
318
# File 'lib/ruby/riddl/server.rb', line 316

def process_out(pout)# {{{
  @riddl_process_out = pout
end

#put(min = '*') ⇒ Object



406
# File 'lib/ruby/riddl/server.rb', line 406

def put(min='*');    return false if @riddl_message.nil?; @riddl_path == '/' + @riddl_info[:s].join('/') && @riddl_message.in && min == @riddl_message.in.name && @riddl_method == 'put'       end

#resource(rname = nil) ⇒ Object



410
# File 'lib/ruby/riddl/server.rb', line 410

def resource(rname=nil); return rname.nil? ? '{}' : rname end

#run(what, *args) ⇒ Object

}}}



351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
# File 'lib/ruby/riddl/server.rb', line 351

def run(what,*args)# {{{
  return if @riddl_path == ''
  if what.class == Class && what.superclass == Riddl::SSEImplementation
    data = Riddl::Protocols::SSE::ParserData.new
    data.request_path = @riddl_pinfo
    data.request_url = @riddl_pinfo + '?' + @riddl_query_string
    data.query_string = @riddl_query_string
    data.http_method = @riddl_env['REQUEST_METHOD']
    data.body = @riddl_env['rack.input'].read
    data.headers = Hash[
      @riddl_headers.map { |key, value|  [key.downcase.gsub('_','-'), value] }
    ]
    w = what.new(@riddl_info.merge!(:a => args, :match => matching_path))
    w.io = Riddl::Protocols::SSE.new(w, @riddl_env)
    w.io.dispatch(data, @riddl_cross_site_xhr)
  end
  if what.class == Class && what.superclass == Riddl::WebSocketImplementation
    data = Riddl::Protocols::WebSocket::ParserData.new
    data.request_path = @riddl_pinfo
    data.request_url = @riddl_pinfo + '?' + @riddl_query_string
    data.query_string = @riddl_query_string
    data.http_method = @riddl_env['REQUEST_METHOD']
    data.body = @riddl_env['rack.input'].read
    data.headers = Hash[
      @riddl_headers.map { |key, value|  [key.downcase.gsub('_','-'), value] }
    ]
    w = what.new(@riddl_info.merge!(:a => args, :version => @riddl_env['HTTP_SEC_WEBSOCKET_VERSION'], :match => matching_path))
    w.io = Riddl::Protocols::WebSocket.new(w, @riddl_env['thin.connection'])
    w.io.dispatch(data)
  end
  if what.class == Class && what.superclass == Riddl::Implementation
    w = what.new(@riddl_info.merge!(:a => args, :match => matching_path))
    @riddl_exe = Riddl::Server::Execution.new(w.response,w.headers)
    @riddl_status = w.status
    if @riddl_process_out && @riddl_status >= 200 && @riddl_status < 300
      unless @riddl.check_message(@riddl_exe.response,@riddl_exe.headers,@riddl_message.out)
        @riddl_log.write "500: the return for the #{@riddl_method} is not matching anything in the description.\n"
        @riddl_status = 500
        return
      end
    end
  end
end

#sseObject



409
# File 'lib/ruby/riddl/server.rb', line 409

def sse;             return false if @riddl_message.nil?; @riddl_path == '/' + @riddl_info[:s].join('/')                                                       && @riddl_method == 'sse'       end

#use(blk, *args) ⇒ Object

}}}



347
348
349
# File 'lib/ruby/riddl/server.rb', line 347

def use(blk,*args)# {{{
  instance_eval(&blk)
end

#websocketObject



408
# File 'lib/ruby/riddl/server.rb', line 408

def websocket;       return false if @riddl_message.nil?; @riddl_path == '/' + @riddl_info[:s].join('/')                                                       && @riddl_method == 'websocket' end