public
Description: A new revision of Fuzed, the Erlang-based frontend for web apps. Check out the mailing list at http://groups.google.com/group/fuzed
Clone URL: git://github.com/KirinDave/fuzed.git
fuzed / rlibs / chassis.rb
100644 648 lines (531 sloc) 16.471 kb
1
2
3
4
5
6
7
8
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
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
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
151
152
153
154
155
156
157
158
159
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
218
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
require 'rubygems'
require 'optparse'
require 'erlectricity'
require 'json' unless $rails_json # prevent from clashing with Rails' built-in json library
 
class Chassis
  class << self
    attr_accessor :signatures, :node_kind, :pkgs, :tags, :roles, :extra_config, :exception_handler, :exit_after_current_dispatch
  end
  
  self.signatures = {}
  self.node_kind = nil
  self.pkgs = []
  self.tags = []
  self.roles = []
  self.extra_config = nil
  self.exception_handler = nil
  self.exit_after_current_dispatch = false
  
  # Define a handler method
  # +method+ is the Symbol method name
  # +names+ is a list of required parameters
  #
  # Returns nothing
  def self.handle(method, *names, &block)
    Chassis.signatures[method] = names.sort { |a, b| a.to_s <=> b.to_s }
    
    define_method("handle_proxy_#{method}", &block)
    
    define_method("handle_#{method}".to_sym) do |iargs|
      args = self.convert_args(iargs)
      self.verify_args(method, args)
      
      self.send("handle_proxy_#{method}", args)
    end
  end
  
  # Specify this handler's kind
  # +name+ is a String identifier
  #
  # Returns nothing
  def self.kind(name)
    Chassis.node_kind = name
  end
  
  # Specify details that will be used for matching incoming requests
  # +details+ is a Hash of primitives
  #
  # Returns nothing
  def self.details(details)
    raise("details() has already been called") unless Chassis.pkgs.empty?
    
    Chassis.pkgs = details.to_a
  end
  
  def self.config(&block)
    Chassis.extra_config = block.call
  end
  
  # Specify a block that takes an Exception as its single argument
  # to be called when an exception is not handled inside a handler
  # +block+ is the block to execute
  #
  # Block should
  # Raise -or-
  # Return one of:
  # [:result, <jsonified result>]
  # [:error, <error string>]
  #
  # Returns nothing
  def self.handle_exception(&block)
    Chassis.exception_handler = block
  end
  
  # Limit version number to 9999 max
  # +version+ is the verstion number to limit
  #
  # Returns Integer
  def self.limit_version(version)
    version.map { |x| x > 9999 ? 9999 : x }
  end
  
  # Convert Erlang-style args to Ruby-style args
  # +iargs+ is the Erlang-style arg structure
  #
  # Returns Hash (converted args)
  def convert_args(iargs)
    args = HashWithIndifferentAccess.new
    iargs.each do |a|
      args[a[0]] = self.convert_args_node(a[1])
    end
    args
  end
  
  # Helper for +convert_args+. Recursively converts a node in
  # Erlang-style to a node in Ruby-style
  # +node+ is the Erlang-style node
  #
  # Returns String|Symbol|Hash|Array
  # Raises if an invalid node is encountered
  def convert_args_node(node)
    if node.kind_of?(String) || node.kind_of?(Symbol) || node.kind_of?(Numeric) ||
       node.kind_of?(TrueClass) || node.kind_of?(FalseClass) || node.kind_of?(NilClass)
      node
    elsif node.instance_of?(Array)
      if node[0] == :struct
        node[1].inject(HashWithIndifferentAccess.new) do |acc, x|
          acc[x[0]] = convert_args_node(x[1]); acc
        end
      elsif node[0] == :array
        node[1].inject([]) do |acc, x|
          acc << convert_args_node(x)
        end
      else
        raise "Invalid tagged node: #{node.inspect}"
      end
    else
      raise "Invalid node, must be an instance of String, Symbol, Numeric, True, False, Nil, or Array: #{node.inspect} (#{node.class.inspect})"
    end
  end
  
  # Verify that the required args are met for the given method call
  # +method+ is the Symbol representing the method name
  # +args+ is the Ruby-style args to check
  #
  # Returns nothing
  # Raises on verification failure
  def verify_args(method, args)
    matches = Chassis.signatures[method].select do |key|
      args[key]
    end
    
    misses = Chassis.signatures[method] - matches
    
    unless misses.empty?
      raise "Required arguments missing for '#{method}': #{misses.join(", ")}"
    end
  end
  
  # Dispatch a method by its name
  # +method+ is the Symbol representing the method name
  # +retype+ is the response type Symbol (:json | :pure)
  # +args+ is the Erlang-stle args for the call
  #
  # Returns one of:
  # [:result, <jsonified result>]
  # [:error, <error string>]
  def dispatch(method, retype, args)
    result = self.send("handle_#{method}".to_sym, args)
    result_key = Chassis.exit_after_current_dispatch ? :last_result : :result
    case retype
      when :json
        [result_key, [:raw, result.to_json]]
      when :pure
        [result_key, result]
      else
        raise "Unknown response type: #{retype}"
    end
  rescue Exception => e
    if e.instance_of?(SystemExit)
      exit
    elsif Chassis.exception_handler
      begin
        Chassis.exception_handler.call(e)
      rescue Exception => e2
        [:error, e2.message + "\n\n" + e2.backtrace.join("\n")]
      end
    else
      [:error, e.message + "\n\n" + e.backtrace.join("\n")]
    end
  end
  
  # The API structure of this Chassis, sorted alphabetically by method name
  #
  # Returns Array (Erlang-style nested structure)
  # e.g.
  # [[:meth1, []],
  # [:meth2, [:arg1, :arg2]]]
  def api
    api = Chassis.signatures.to_a.sort { |a, b| a.first.to_s <=> b.first.to_s }
    api
  end
  
  # Construct the config (aka details)
  #
  # Returns Array (config)
  def config
    details = Chassis.pkgs.dup
    details << ["tags"] + Chassis.tags unless Chassis.tags.empty?
    details << ["roles"] + Chassis.roles unless Chassis.roles.empty?
    details << ["kind"] + [Chassis.node_kind] if Chassis.node_kind
    details << Chassis.extra_config if Chassis.extra_config
    details
  end
  
  # Start the Erlectricity recieve/respond loop
  #
  # Never returns
  def start
    receive(IO.new(3), IO.new(4)) do |f|
      f.when(:call, Array) do |args|
        method = args[0]
        retype = args[1]
        args = args[2..-1]
        f.send! self.dispatch(method, retype, args)
        exit if Chassis.exit_after_current_dispatch
        f.receive_loop
      end
      
      f.when(:config) do
        f.send! :result, self.config
        f.receive_loop
      end
      
      f.when(:api) do
        f.send! :result, self.api
        f.receive_loop
      end
      
      f.when(:ping) do
        f.send! :pong
        f.receive_loop
      end
      
      f.when(:quit) do
        exit(0)
      end
    end
  end
  
  def self.pull_cli_args
    Chassis.tags = []
    Chassis.roles = []
    
    # parse the options
    opts = OptionParser.new
    opts.on("--tags x,y,z", Array) do |val|
      Chassis.tags = val
    end
    opts.on("--roles x,y,z", Array) do |val|
      Chassis.roles = val
    end
    opts.parse(ARGV)
    
    # grab the extras
    extras = []
    dashdash = ARGV.index('--')
    if dashdash
      extras = ARGV[(dashdash + 1)..-1]
    end
    
    # ramrod the extras into ARGV
    ARGV.clear
    ARGV.concat(extras)
  end
  
  def self.start
    # get any handlers
    handlers = []
    ObjectSpace.each_object(Class) do |o|
      handlers << o if o < Chassis
    end
    
    if $!
      raise $!
    end
    
    # check that one and only one exist
    if handlers.size != 1
      raise "There must be exactly one class that extends Chassis, but there are #{handlers.size}"
    end
    
    # check that a kind has been set
    unless Chassis.node_kind
      raise "A kind must be specified"
    end
    
    h = handlers.first.new
    h.start
  end
  
  def return_and_exit(data)
    Chassis.exit_after_current_dispatch = true
    data
  end
end
 
class HashWithIndifferentAccess < Hash
  def initialize(constructor = {})
    if constructor.is_a?(Hash)
      super()
      update(constructor)
    else
      super(constructor)
    end
  end
 
  def default(key = nil)
    if key.is_a?(Symbol) && include?(key = key.to_s)
      self[key]
    else
      super
    end
  end
 
  alias_method :regular_writer, :[]= unless method_defined?(:regular_writer)
  alias_method :regular_update, :update unless method_defined?(:regular_update)
 
  def []=(key, value)
    regular_writer(convert_key(key), convert_value(value))
  end
 
  def update(other_hash)
    other_hash.each_pair { |key, value| regular_writer(convert_key(key), convert_value(value)) }
    self
  end
 
  alias_method :merge!, :update
 
  def key?(key)
    super(convert_key(key))
  end
 
  alias_method :include?, :key?
  alias_method :has_key?, :key?
  alias_method :member?, :key?
 
  def fetch(key, *extras)
    super(convert_key(key), *extras)
  end
 
  def values_at(*indices)
    indices.collect {|key| self[convert_key(key)]}
  end
 
  def dup
    HashWithIndifferentAccess.new(self)
  end
 
  def merge(hash)
    self.dup.update(hash)
  end
 
  def delete(key)
    super(convert_key(key))
  end
 
  def stringify_keys!; self end
  def symbolize_keys!; self end
  def to_options!; self end
 
  # Convert to a Hash with String keys.
  def to_hash
    Hash.new(default).merge(self)
  end
 
  protected
    def convert_key(key)
      key.kind_of?(Symbol) ? key.to_s : key
    end
 
    def convert_value(value)
      case value
      when Hash
        value.with_indifferent_access
      when Array
        value.collect { |e| e.is_a?(Hash) ? e.with_indifferent_access : e }
      else
        value
      end
    end
end
 
class Hash
  def with_indifferent_access
    hash = HashWithIndifferentAccess.new(self)
    hash.default = self.default
    hash
  end
end
 
at_exit do
  Chassis.start
end
 
Chassis.pull_cli_args
 
#############################################################################
# Tests
 
if $0 == __FILE__
  require 'test/unit'
  require 'mocha'
  
  class Chassis
    def self.start
      nil
    end
  end
  
  class Awesome < Chassis
    kind "awesome"
    
    details "failboat" => "sinking"
    
    config do
      ["grammar", "/tmp/awesome.lfg"]
    end
    
    handle(:alpha) do
      'alpha'
    end
    
    handle(:beta, :foo, :bar) do |args|
      helper(args[:foo], args[:bar])
    end
    
    handle(:gamma) do
      raise "once more unto the breach"
    end
    
    handle(:delta) do
      exit
    end
    
    handle(:epsilon) do
      return_and_exit('foo')
    end
    
    handle_exception do |e|
      raise "EBORKD"
    end
    
    def helper(x, y)
      "#{x}=#{y}"
    end
  end
  
  class TestChassis < Test::Unit::TestCase
    def setup
      @a = Awesome.new
    end
    
    # signatures
    
    def test_signatures_should_match_declaration
      sigs = {:gamma=>[], :alpha=>[], :delta=>[], :beta=>[:bar, :foo], :epsilon=>[]}
      assert_equal sigs, Chassis.signatures
    end
    
    # handler meta
    
    def test_handler_methods_should_exist
      assert @a.respond_to?(:handle_alpha)
      assert @a.respond_to?(:handle_beta)
    end
    
    def test_handler_methods_arity_should_always_be_one
      assert 1, @a.method(:handle_alpha).arity
      assert 1, @a.method(:handle_beta).arity
    end
    
    # convert_args
    
    def test_convert_args_should_convert_top_level_array_to_hash
      i = [[:foo, 'bar'], [:qux, 'quux']]
      o = {'foo' => 'bar', 'qux' => 'quux'}
      assert_equal o, @a.convert_args(i)
      
      i = [['foo', 'bar'], ['qux', 'quux']]
      o = {'foo' => 'bar', 'qux' => 'quux'}
      assert_equal o, @a.convert_args(i)
    end
    
    def test_convert_args_should_convert_structs_to_indifferent_hashes
      i = [[:foo, 'bar'], [:baz, [:struct, [[:qux, 'quux']]]]]
      o = {'foo' => 'bar', 'baz' => {'qux' => 'quux'}}
      assert_equal o, @a.convert_args(i)
      
      i = [[:foo, 'bar'], [:baz, [:struct, [[:qux, [:struct, [[:a, 'b']]]]]]]]
      o = {'foo' => 'bar', 'baz' => {'qux' => {'a' => 'b'}}}
      assert_equal o, @a.convert_args(i)
    end
    
    def test_convert_args_should_make_all_hashes_indifferent
      i = [[:foo, 'bar'], [:baz, [:struct, [[:qux, 'quux']]]]]
      # o = {'foo' => 'bar', 'baz' => {'qux' => 'quux'}}
      o = @a.convert_args(i)
      assert_equal 'bar', o[:foo]
      assert_equal 'bar', o['foo']
      
      assert_equal 'quux', o[:baz][:qux]
      assert_equal 'quux', o['baz']['qux']
    end
    
    def test_convert_args_should_convert_arrays_to_arrays
      i = [[:foo, 'bar'], [:baz, [:array, [:qux, 'quux']]]]
      o = {'foo' => 'bar', 'baz' => [:qux, 'quux']}
      assert_equal o, @a.convert_args(i)
      
      i = [[:foo, 'bar'], [:baz, [:array, [:qux, [:array, [:a, 'b']]]]]]
      o = {'foo' => 'bar', 'baz' => [:qux, [:a, 'b']]}
      assert_equal o, @a.convert_args(i)
    end
    
    # convert_args_node
    
    def test_convert_node_should_be_identity_for_strings
      assert_equal 'foo', @a.convert_args_node('foo')
    end
    
    def test_convert_node_should_be_identity_for_symbol
      assert_equal :foo, @a.convert_args_node(:foo)
    end
    
    def test_convert_node_should_be_identity_for_true
      assert_equal true, @a.convert_args_node(true)
    end
    
    def test_convert_node_should_be_identity_for_false
      assert_equal false, @a.convert_args_node(false)
    end
    
    def test_convert_node_should_be_identity_for_nil
      assert_equal nil, @a.convert_args_node(nil)
    end
    
    def test_convert_node_should_be_identity_for_numeric
      assert_equal 1, @a.convert_args_node(1)
      assert_equal 1.0, @a.convert_args_node(1.0)
      assert_equal 9999999999999999999, @a.convert_args_node(9999999999999999999)
    end
    
    def test_convert_node_should_convert_array
      assert_equal [1], @a.convert_args_node([:array, [1]])
      assert_equal [1, 2], @a.convert_args_node([:array, [1, 2]])
      assert_equal [1, 2, 3], @a.convert_args_node([:array, [1, 2, 3]])
    end
    
    def test_convert_node_should_convert_nested_array
      assert_equal [[1]], @a.convert_args_node([:array, [[:array, [1]]]])
    end
    
    def test_convert_node_should_convert_struct_to_hash
      i = [:struct, [[:foo, 'foo']]]
      o = {"foo" => 'foo'}
      assert_equal o, @a.convert_args_node(i)
    end