Top Level Namespace

Defined Under Namespace

Classes: BlestError, HttpClient, Router

Instance Method Summary collapse

Instance Method Details

#create_request_handler(routes) ⇒ Object

Raises:

  • (ArgumentError)


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
# File 'lib/blest.rb', line 258

def create_request_handler(routes)
  raise ArgumentError, 'A routes object is required' unless routes.is_a?(Hash)

  my_routes = {}

  routes.each do |key, route|
    route_error = validate_route(key, false)
    raise ArgumentError, "#{route_error}: #{key}" if route_error

    if route.is_a?(Array)
      raise ArgumentError, "Route has no handlers: #{key}" if route.empty?

      route.each do |handler|
        raise ArgumentError, "All route handlers must be functions: #{key}" unless handler.is_a?(Proc)
      end

      my_routes[key] = { handler: route }
    elsif route.is_a?(Hash)
      unless route.key?(:handler)
        raise ArgumentError, "Route has no handlers: #{key}"
      end

      if route[:handler].is_a?(Array)
        route[:handler].each do |handler|
          raise ArgumentError, "All route handlers must be functions: #{key}" unless handler.is_a?(Proc)
        end

        my_routes[key] = route
      elsif route[:handler].is_a?(Proc)
        my_routes[key] = { **route, handler: [route[:handler]] }
      else
        raise ArgumentError, "Route handler is not valid: #{key}"
      end
    elsif route.is_a?(Proc)
      my_routes[key] = { handler: [route] }
    else
      raise ArgumentError, "Route is missing handler: #{key}"
    end
  end

  handler = lambda do |requests, context = {}|
    handle_request(my_routes, requests, context)
  end

  return handler
end

#filter_object(obj, arr) ⇒ Object



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
# File 'lib/blest.rb', line 574

def filter_object(obj, arr)
  if arr.is_a?(Array)
    filtered_obj = {}
    arr.each do |key|
      if key.is_a?(String)
        if obj.key?(key.to_sym)
          filtered_obj[key.to_sym] = obj[key.to_sym]
        end
      elsif key.is_a?(Array)
        nested_obj = obj[key[0].to_sym]
        nested_arr = key[1]
        if nested_obj.is_a?(Array)
          filtered_arr = []
          nested_obj.each do |nested_item|
            filtered_nested_obj = filter_object(nested_item, nested_arr)
            if filtered_nested_obj.keys.length > 0
              filtered_arr << filtered_nested_obj
            end
          end
          if filtered_arr.length > 0
            filtered_obj[key[0].to_sym] = filtered_arr
          end
        elsif nested_obj.is_a?(Hash)
          filtered_nested_obj = filter_object(nested_obj, nested_arr)
          if filtered_nested_obj.keys.length > 0
            filtered_obj[key[0].to_sym] = filtered_nested_obj
          end
        end
      end
    end
    return filtered_obj
  end
  return obj
end

#get_value(hash, key) ⇒ Object



248
249
250
251
252
253
254
# File 'lib/blest.rb', line 248

def get_value(hash, key)
  if hash.key?(key.to_sym)
    hash[key.to_sym]
  elsif hash.key?(key.to_s)
    hash[key.to_s]
  end
end

#handle_error(status, message) ⇒ Object



434
435
436
437
438
439
# File 'lib/blest.rb', line 434

def handle_error(status, message)
  return nil, {
    'status' => status,
    'message' => message
  }
end

#handle_request(routes, requests, context = {}) ⇒ 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
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
# File 'lib/blest.rb', line 351

def handle_request(routes, requests, context = {})
  if requests.nil? || !requests.is_a?(Array)
    return handle_error(400, 'Request should be an array')
  end

  batch_id = SecureRandom.uuid()
  unique_ids = []
  promises = []

  requests.each do |request|
    request_length = request.length
    if !request.is_a?(Array)
      return handle_error(400, 'Request item should be an array')
    end

    id = request[0] || nil
    route = request[1] || nil
    body = request[2] || nil
    headers = request[3] || nil

    if id.nil? || !id.is_a?(String)
      return handle_error(400, 'Request item should have an ID')
    end

    if route.nil? || !route.is_a?(String)
      return handle_error(400, 'Request items should have a route')
    end

    if body && !body.is_a?(Hash)
      return handle_error(400, 'Request item body should be an object')
    end

    if headers && !headers.is_a?(Hash)
      return handle_error(400, 'Request item headers should be an object')
    end

    if unique_ids.include?(id)
      return handle_error(400, 'Request items should have unique IDs')
    end

    unique_ids << id
    this_route = routes[route]
    route_handler = nil
    timeout = nil

    if this_route.is_a?(Hash)
      route_handler = this_route[:handler] || this_route['handler'] || method(:route_not_found)
      timeout = this_route[:timeout] || this_route['timeout'] || nil
    else
      route_handler = this_route || method(:route_not_found)
    end

    request_object = {
      id: id,
      route: route,
      body: body || {},
      headers: headers
    }

    request_context = {}
    if context.is_a?(Hash)
      request_context = request_context.merge(context)
    end
    request_context["batch_id"] = batch_id
    request_context["request_id"] = id
    request_context["route"] = route
    request_context["headers"] = headers

    promises << Thread.new { route_reducer(route_handler, request_object, request_context, timeout) }
  end

  results = promises.map(&:value)
  return handle_result(results)
end

#handle_result(result) ⇒ Object



428
429
430
# File 'lib/blest.rb', line 428

def handle_result(result)
  return result, nil
end

#route_not_found(_, _) ⇒ Object

Raises:

  • (error)


460
461
462
463
464
465
# File 'lib/blest.rb', line 460

def route_not_found(_, _)
  error = BlestError.new
  error.status = 404
  error.stack = nil
  raise error, 'Not Found'
end

#route_reducer(handler, request, context, timeout = nil) ⇒ Object



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
# File 'lib/blest.rb', line 469

def route_reducer(handler, request, context, timeout = nil)
  safe_context = Marshal.load(Marshal.dump(context))
  route = request[:route]
  result = nil
  error = nil

  target = -> do
    my_result = nil
    if handler.is_a?(Array)
      handler.each do |h|
        break if error
        temp_result = nil
        if h.respond_to?(:call)
          temp_result = Concurrent::Promises.future do
            begin
              h.call(request[:body], safe_context)
            rescue => e
              error = e
            end
          end.value
        else
          puts "Tried to resolve route '#{route}' with handler of type '#{h.class}'"
          raise StandardError
        end

        if temp_result && temp_result != nil
          if my_result && my_result != nil
            puts result
            puts temp_result
            puts "Multiple handlers on the route '#{route}' returned results"
            raise StandardError
          else
            my_result = temp_result
          end
        end
      end
    else
      if handler.respond_to?(:call)
        my_result = Concurrent::Promises.future do
          begin
            handler.call(request[:body], safe_context)
          rescue => e
            error = e
          end
        end.value
      else
        puts "Tried to resolve route '#{route}' with handler of type '#{handler.class}'"
        raise StandardError
      end
    end

    if error
      raise error
    end

    my_result
  end

  begin
    if timeout && timeout > 0
      begin
        result = Timeout.timeout(timeout / 1000.0) { target.call }
      rescue Timeout::Error
        puts "The route '#{route}' timed out after #{timeout} milliseconds"
        return [request[:id], request[:route], nil, { 'message' => 'Internal Server Error', 'status' => 500 }]
      end
    else
      result = target.call
    end

    if result.nil? || !result.is_a?(Hash)
      puts "The route '#{route}' did not return a result object"
      return [request[:id], request[:route], nil, { 'message' => 'Internal Server Error', 'status' => 500 }]
    end

    # if request[:selector]
    #   result = filter_object(result, request[:selector])
    # end

    [request[:id], request[:route], result, nil]
  rescue => error
    puts error.backtrace
    response_error = {
      'message' => error.message || 'Internal Server Error',
      'status' => error.respond_to?(:status) ? error.status : 500
    }

    if error.respond_to?(:code) && error.code.is_a?(String)
      response_error['code'] = error.code
    end

    if error.respond_to?(:data) && error.data.is_a?(Hash)
      response_error['data'] = error.data
    end

    if ENV['ENVIRONMENT'] != 'production' && ENV['APP_ENV'] != 'production' && ENV['RACK_ENV'] != 'production' && ENV['RAILS_ENV'] != 'production' && !error.respond_to?(:stack)
      response_error['stack'] = error.backtrace
    end

    [request[:id], request[:route], nil, response_error]
  end
end

#validate_route(route, system) ⇒ Object



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
# File 'lib/blest.rb', line 307

def validate_route(route, system)
  route_regex = /^[a-zA-Z][a-zA-Z0-9_\-\/]*[a-zA-Z0-9]$/
  system_route_regex = /^_[a-zA-Z][a-zA-Z0-9_\-\/]*[a-zA-Z0-9]$/
  if route.nil? || route.empty?
    return 'Route is required'
  elsif system && !(route =~ system_route_regex)
    route_length = route.length
    if route_length < 3
      return 'System route should be at least three characters long'
    elsif route[0] != '_'
      return 'System route should start with an underscore'
    elsif !(route[-1] =~ /^[a-zA-Z0-9]/)
      return 'System route should end with a letter or a number'
    else
      return 'System route should contain only letters, numbers, dashes, underscores, and forward slashes'
    end
  elsif !system && !(route =~ route_regex)
    route_length = route.length
    if route_length < 2
      return 'Route should be at least two characters long'
    elsif !(route[0] =~ /^[a-zA-Z]/)
      return 'Route should start with a letter'
    elsif !(route[-1] =~ /^[a-zA-Z0-9]/)
      return 'Route should end with a letter or a number'
    else
      return 'Route should contain only letters, numbers, dashes, underscores, and forward slashes'
    end
  elsif route =~ /\/[^a-zA-Z]/
    return 'Sub-routes should start with a letter'
  elsif route =~ /[^a-zA-Z0-9]\//
    return 'Sub-routes should end with a letter or a number'
  elsif route =~ /\/[a-zA-Z0-9_\-]{0,1}\//
    return 'Sub-routes should be at least two characters long'
  elsif route =~ /\/[a-zA-Z0-9_\-]$/
    return 'Sub-routes should be at least two characters long'
  elsif route =~ /^[a-zA-Z0-9_\-]\//
    return 'Sub-routes should be at least two characters long'
  end

  return nil
end