fleck 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 24b9067f1d101ff5cadc4166c022214fda4d9d13
4
+ data.tar.gz: 14863e29b01553bccc160a5e88f08bf39886f16f
5
+ SHA512:
6
+ metadata.gz: 823e39b13adf5a7d0843e61004eb3b9c44b34011a9fafce94fbee64c832d62f97dc21e0b095a493e65fc179ebf2eb8edf68bface5aedb61c287cdacde6241447
7
+ data.tar.gz: f7f5765eb76bf403a3edd7b5d0575747266c75d02435e9e50f2d373541c7d1eda534706f922d93f26cae3733a0a8ede3aa3e1c9a9cca9cc3213bbabab6a6a71d
data/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ /*.gem
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,4 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.2.1
4
+ before_install: gem install bundler -v 1.10.6
@@ -0,0 +1,13 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
4
+
5
+ We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion.
6
+
7
+ Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
8
+
9
+ Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
10
+
11
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
12
+
13
+ This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in fleck.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 Groza Sergiu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,118 @@
1
+ # Fleck
2
+
3
+ **Fleck** is a Ruby gem for comunication over RabbitMQ. It implements both `Fleck::Consumer` for messages consumption from RabbitMQ queues and
4
+ `Fleck::Client` for making RPC (Remote Procedure Call) and asynchronous calls.
5
+
6
+ ## Installation
7
+
8
+ Add this line to your application's Gemfile:
9
+
10
+ ```ruby
11
+ gem 'fleck'
12
+ ```
13
+
14
+ And then execute:
15
+
16
+ $ bundle
17
+
18
+ Or install it yourself as:
19
+
20
+ $ gem install fleck
21
+
22
+
23
+
24
+ ## Usage
25
+
26
+ Before using **Fleck** you might want to configure it. For doing that you could use as example the code below:
27
+
28
+ ```ruby
29
+ require 'fleck'
30
+
31
+ # configure defaults for fleck
32
+ Fleck.configure do |config|
33
+ config.loglevel = Logger::INFO # log level
34
+ config.logfile = STDOUT # the file where to write the logs
35
+ config.progname = 'MyApp' # the progname prefix to use in logs
36
+ config.default_host = '127.0.0.1' # default host to use for connections to RabbitMQ
37
+ config.default_port = 5672 # default port to use for connections to RabbitMQ
38
+ config.default_user = 'guest' # default user to use for connections to RabbitMQ
39
+ config.default_pass = 'guest' # default password to use for connections to RabbitMQ
40
+ config.default_vhost = '/' # default vhost to use for connections to RabbitMQ
41
+ config.default_queue = 'default' # default queue name to use in consumers, when not specified
42
+ end
43
+ ```
44
+
45
+ ### Fleck::Client
46
+
47
+ You could use **Fleck** for both making requests and consuming requests from the queues. Now we are going to see how to enqueue a request to a specific queue:
48
+
49
+ ```ruby
50
+ QUEUE = 'my.queue' # the name of the queue where to enqueue the request
51
+ HEADERS = {my_header: 'a header'} # the headers of the request
52
+ PARAMS = {parameter: 'a parameter'} # the parameters of the request
53
+ ASYNC = false # a flag to indicate if the request is async or not
54
+
55
+
56
+ connection = Fleck.connection(host: '127.0.0.1', port: 5672, user: 'guest', pass: 'guest', vhost: '/')
57
+ client = Fleck::Client.new(connection, QUEUE)
58
+ response = client.request(HEADERS, PARAMS, ASYNC)
59
+
60
+ response.status # => returns the status code of the response
61
+ response.headers # => returns the headers Hash of the response
62
+ response.body # => returns the body of the response
63
+ response.errors # => returns the Array of errors
64
+ ```
65
+
66
+ #### Request with block
67
+
68
+ You might want to process the response of asynchronous requests when the response is ready. In that case you could pass a block to the request,
69
+ so that the block is called when the response is completed:
70
+
71
+ ```ruby
72
+ client.request({}, {param1: 'myparam'}, true) do |request, response|
73
+ if response.status == 200
74
+ puts "#{response.status} #{response.body}"
75
+ else
76
+ puts "#{response.status} #{response.errors.join(", ")}"
77
+ end
78
+ end
79
+ ```
80
+
81
+ ### Fleck::Consumer
82
+
83
+ To use `Fleck::Consumer` all you need is to inherit it by an another class:
84
+
85
+ ```ruby
86
+ class MyConsumer < Fleck::Consumer
87
+ configure queue: 'my.queue', concurrency: 2
88
+
89
+ def on_message(request, response)
90
+ logger.debug "HEADERS: #{request.headers}"
91
+ logger.debug "PARAMS: #{request.params}"
92
+
93
+ if rand > 0.1
94
+ response.status = 200
95
+ response.body = {x: rand, y: rand}
96
+ else
97
+ response.render_error(500, 'Internal Server Error (just a joke)')
98
+ end
99
+ end
100
+ end
101
+ ```
102
+
103
+ This code will automatically automatically start `N` instances of MyConsumer in background (you don't have to do anything), that will start consuming
104
+ messages from `my.queue` and will respond with a 200 status when the randomly generated number is greater than `0.1` and with a 500 otherwise.
105
+
106
+ **NOTE**:
107
+
108
+
109
+ ## Contributing
110
+
111
+ Bug reports and pull requests are welcome on GitHub at https://github.com/serioja90/fleck. This project is intended to be a safe, welcoming space
112
+ for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct.
113
+
114
+
115
+ ## License
116
+
117
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
118
+
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "fleck"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
data/bin/setup ADDED
@@ -0,0 +1,7 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+
5
+ bundle install
6
+
7
+ # Do any other automated setup that you need to do here
data/example.rb ADDED
@@ -0,0 +1,54 @@
1
+ require 'fleck'
2
+
3
+ user = ENV['USER'] || 'guest'
4
+ pass = ENV['PASS'] || 'guest'
5
+
6
+ CONCURRENCY = (ENV['CONCURRENCY'] || 10).to_i
7
+ SAMPLES = (ENV['SAMPLES'] || 10_000).to_i
8
+
9
+ Fleck.configure do |config|
10
+ config.default_user = user
11
+ config.default_pass = pass
12
+ config.loglevel = Logger::DEBUG
13
+ end
14
+
15
+ connection = Fleck.connection(host: "127.0.0.1", port: 5672, user: user, pass: pass, vhost: "/")
16
+ client = Fleck::Client.new(connection, "example.queue")
17
+
18
+ count = 0
19
+ mutex = Mutex.new
20
+ lock = Mutex.new
21
+ condition = ConditionVariable.new
22
+
23
+ class First < Fleck::Consumer
24
+ configure queue: "example.queue", concurrency: CONCURRENCY.to_i
25
+
26
+ def on_message(request, response)
27
+ if request.action == "incr"
28
+ response.body = "#{request.params[:num].to_i + 1}. Hello, World!"
29
+ else
30
+ response.not_found
31
+ end
32
+ end
33
+ end
34
+
35
+ Thread.new do
36
+ SAMPLES.times do |i|
37
+ client.request({action: :incr}, {num: i}, true) do |request, response|
38
+ if response.status == 200
39
+ request.logger.debug response.body
40
+ else
41
+ request.logger.error "#{response.status} #{response.errors.join(", ")}"
42
+ end
43
+ mutex.synchronize do
44
+ count += 1
45
+ lock.synchronize { condition.signal } if count >= SAMPLES
46
+ end
47
+ end
48
+ end
49
+ end
50
+
51
+ lock.synchronize { condition.wait(lock) }
52
+
53
+ puts "Total: #{count}"
54
+ First.consumers.map(&:terminate)
data/fleck.gemspec ADDED
@@ -0,0 +1,35 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'fleck/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "fleck"
8
+ spec.platform = "ruby"
9
+ spec.version = Fleck::VERSION
10
+ spec.authors = ["Groza Sergiu"]
11
+ spec.email = ["serioja90@gmail.com"]
12
+
13
+ spec.summary = %q{A Ruby gem for syncronous and asyncronous communication via Message Queue services.}
14
+ spec.description = %q{
15
+ Fleck is a library for syncronous and asyncronous communication over Message Queues services. Unlike a common
16
+ HTTP communication, Fleck requests and responses are pure JSON messages.
17
+ }
18
+ spec.homepage = "https://github.com/serioja90/fleck"
19
+ spec.license = "MIT"
20
+
21
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
22
+ spec.bindir = "exe"
23
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
24
+ spec.require_paths = ["lib"]
25
+
26
+ spec.required_ruby_version = "~> 2.0"
27
+
28
+ spec.add_development_dependency "bundler", "~> 1.10"
29
+ spec.add_development_dependency "rake", "~> 10.0"
30
+ spec.add_development_dependency "rspec", "~> 3"
31
+ spec.add_dependency "rainbow", "~> 2.0"
32
+ spec.add_dependency "bunny", "~> 2.2"
33
+ spec.add_dependency "thread_safe", "~> 0.3"
34
+ spec.add_dependency "oj", "~> 2.14"
35
+ end
@@ -0,0 +1,55 @@
1
+
2
+ module Fleck
3
+ class Client::Request
4
+ include Fleck::Loggable
5
+
6
+ attr_reader :id, :response
7
+
8
+ def initialize(exchange, routing_key, reply_to, headers = {}, params = {}, &callback)
9
+ @id = SecureRandom.uuid
10
+ logger.progname += " #{@id}"
11
+
12
+ logger.debug "Preparing new request"
13
+
14
+ @exchange = exchange
15
+ @routing_key = routing_key
16
+ @reply_to = reply_to
17
+ @params = params
18
+ @headers = headers
19
+ @response = nil
20
+ @lock = Mutex.new
21
+ @condition = ConditionVariable.new
22
+ @callback = callback
23
+ @started_at = nil
24
+ @ended_at = nil
25
+
26
+ logger.debug "Request prepared"
27
+ end
28
+
29
+ def response=(value)
30
+ logger.debug "Response: #{value.inspect}"
31
+ raise ArgumentError.new("Invalid response type: #{value.class}") unless value.is_a?(Fleck::Client::Response)
32
+ @response = value
33
+ @callback.call(self, value) if @callback
34
+ return value
35
+ end
36
+
37
+ def send!(async = false)
38
+ @started_at = Time.now.to_f
39
+ data = Oj.dump({
40
+ headers: @headers,
41
+ params: @params
42
+ }, mode: :compat)
43
+ logger.debug("Sending request with data: #{data}")
44
+
45
+ @exchange.publish(data, routing_key: @routing_key, reply_to: @reply_to, correlation_id: @id)
46
+ @lock.synchronize { @condition.wait(@lock) } unless async
47
+ end
48
+
49
+ def complete!
50
+ @lock.synchronize { @condition.signal }
51
+ @ended_at = Time.now.to_f
52
+ logger.debug "Done in #{((@ended_at - @started_at).round(5) * 1000).round(2)} ms"
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,15 @@
1
+
2
+ module Fleck
3
+ class Client::Response
4
+ include Fleck::Loggable
5
+
6
+ attr_accessor :status, :headers, :body, :errors
7
+ def initialize(payload)
8
+ @data = Oj.load(payload).to_hash_with_indifferent_access
9
+ @status = @data["status"]
10
+ @headers = @data["headers"] || {}
11
+ @body = @data["body"]
12
+ @errors = @data["errors"] || []
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,56 @@
1
+
2
+ module Fleck
3
+ class Client
4
+ include Fleck::Loggable
5
+
6
+ def initialize(connection, queue_name)
7
+ @connection = connection
8
+ @queue_name = queue_name
9
+ @channel = @connection.create_channel
10
+ @exchange = @channel.default_exchange
11
+ @reply_queue = @channel.queue("", exclusive: true)
12
+ @requests = ThreadSafe::Hash.new
13
+
14
+ @reply_queue.subscribe do |delivery_info, metadata, payload|
15
+ begin
16
+ logger.debug "Response received: #{payload}"
17
+ request = @requests[metadata[:correlation_id]]
18
+ if request
19
+ request.response = Fleck::Client::Response.new(payload)
20
+ request.complete!
21
+ @requests.delete metadata[:correlation_id]
22
+ end
23
+ rescue => e
24
+ logger.error e.inspect + "\n" + e.backtrace.join("\n")
25
+ end
26
+ end
27
+
28
+ logger.debug("Client initialized!")
29
+
30
+ at_exit do
31
+ terminate
32
+ end
33
+ end
34
+
35
+ def request(headers = {}, payload = {}, async = false, &block)
36
+ request = Fleck::Client::Request.new(@exchange, @queue_name, @reply_queue.name, headers, payload, &block)
37
+ @requests[request.id] = request
38
+ request.send!(async)
39
+
40
+ return request.response
41
+ end
42
+
43
+ def terminate
44
+ @requests.each do |id, request|
45
+ begin
46
+ request.complete!
47
+ rescue => e
48
+ logger.error e.inspect + "\n" + e.backtrace.join("\n")
49
+ end
50
+ end
51
+ end
52
+ end
53
+ end
54
+
55
+ require "fleck/client/request"
56
+ require "fleck/client/response"
@@ -0,0 +1,108 @@
1
+
2
+ module Fleck
3
+ class Configuration
4
+
5
+ attr_reader :logfile, :loglevel, :progname
6
+ attr_accessor :default_user, :default_pass, :default_host, :default_port, :default_vhost, :default_queue
7
+
8
+ def initialize
9
+ @logfile = STDOUT
10
+ @loglevel = ::Logger::INFO
11
+ @progname = "Fleck"
12
+ @default_host = "127.0.0.1"
13
+ @default_port = 5672
14
+ @default_user = nil
15
+ @default_pass = nil
16
+ @default_vhost = "/"
17
+ @default_queue = "default"
18
+ end
19
+
20
+ def default_options
21
+ opts = {}
22
+ opts[:host] = @default_host
23
+ opts[:port] = @default_port
24
+ opts[:user] = @default_user
25
+ opts[:pass] = @default_pass
26
+ opts[:vhost] = @default_vhost
27
+ opts[:queue] = @default_queue
28
+
29
+ return opts
30
+ end
31
+
32
+ def logfile=(new_logfile)
33
+ if @logfile != new_logfile
34
+ @logfile = new_logfile
35
+ reset_logger
36
+ end
37
+
38
+ return @logfile
39
+ end
40
+
41
+ def loglevel=(new_loglevel)
42
+ @loglevel = new_loglevel
43
+ @logger.level = @loglevel if @logger
44
+
45
+ return @loglevel
46
+ end
47
+
48
+ def progname=(new_progname)
49
+ @progname = new_progname
50
+ @logger.progname = @progname if @logger
51
+
52
+ return @progname
53
+ end
54
+
55
+ def logger
56
+ return @logger || reset_logger
57
+ end
58
+
59
+ def logger=(new_logger)
60
+ if new_logger.nil?
61
+ @logger.close
62
+ @logger = ::Logger.new(nil)
63
+ else
64
+ @logger.close
65
+ @logger = new_logger.clone
66
+ @logger.formatter = formatter
67
+ @logger.progname = @progname
68
+ @logger.level = @loglevel
69
+ end
70
+
71
+ return @logger
72
+ end
73
+
74
+ def reset_logger
75
+ new_logger = ::Logger.new(@logfile)
76
+ new_logger.formatter = formatter
77
+ new_logger.progname = @progname
78
+ new_logger.level = @loglevel
79
+ @logger.close if @logger
80
+ @logger = new_logger
81
+
82
+ return @logger
83
+ end
84
+
85
+ def formatter
86
+ return @formatter if @formatter
87
+
88
+ @formatter = proc do |severity, datetime, progname, msg|
89
+ color = :blue
90
+ case severity
91
+ when 'DEBUG'
92
+ color = "#512DA8"
93
+ when 'INFO'
94
+ color = "#33691E"
95
+ when 'WARN'
96
+ color = "#E65100"
97
+ when 'ERROR', 'FATAL'
98
+ color = "#B71C1C"
99
+ else
100
+ color = "#00BCD4"
101
+ end
102
+ "[#{datetime.strftime('%F %T.%L')}]".color(:cyan) + (progname ? " #{progname}".color(:yellow) : "") + " #{severity} ".color(color) + "#{msg}\n"
103
+ end
104
+
105
+ return @formatter
106
+ end
107
+ end
108
+ end
@@ -0,0 +1,43 @@
1
+
2
+ module Fleck
3
+ class Consumer::Request
4
+ include Fleck::Loggable
5
+
6
+ attr_reader :id, :metadata, :payload, :data, :headers, :action, :params, :status, :errors
7
+
8
+ def initialize(metadata, payload)
9
+ @id = metadata.correlation_id
10
+ logger.progname += " #{@id}"
11
+
12
+ @metadata = metadata
13
+ @payload = payload
14
+ @data = {}
15
+ @headers = {}
16
+ @action = nil
17
+ @params = {}
18
+ @status = 200
19
+ @errors = []
20
+
21
+ parse_request!
22
+ end
23
+
24
+ protected
25
+
26
+ def parse_request!
27
+ logger.debug "Parsing request: #{@payload}"
28
+ @data = Oj.load(@payload).to_hash_with_indifferent_access
29
+ @headers = @data["headers"] || {}
30
+ @action = @headers["action"]
31
+ @params = @data["params"] || {}
32
+ rescue Oj::ParseError => e
33
+ logger.error(e.inspect + "\n" + e.backtrace.join("\n"))
34
+ @status = 400
35
+ @errors << "Bad Request"
36
+ @errors << e.inspect
37
+ rescue => e
38
+ logger.error(e.inspect + "\n" + e.backtrace.join("\n"))
39
+ @status = 500
40
+ @errors << "Internal Server Error"
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,52 @@
1
+
2
+ module Fleck
3
+ class Consumer::Response
4
+ include Fleck::Loggable
5
+
6
+ attr_accessor :id, :status, :errors, :headers, :body
7
+
8
+ def initialize(request_id)
9
+ @id = request_id
10
+ logger.progname += " #{@id}"
11
+
12
+ @status = 200
13
+ @errors = []
14
+ @headers = {}
15
+ @body = nil
16
+ end
17
+
18
+ def not_found(msg = nil)
19
+ @status = 404
20
+ @errors << 'Resource Not Found'
21
+ @errors << msg if msg
22
+ end
23
+
24
+ def render_error(status, msg = [])
25
+ @status = status.to_i
26
+ if msg.is_a?(Array)
27
+ @errors += msg
28
+ else
29
+ @errors << msg
30
+ end
31
+ end
32
+
33
+ def to_json
34
+ return Oj.dump({
35
+ "status" => @status,
36
+ "errors" => @errors,
37
+ "headers" => @headers,
38
+ "body" => @body
39
+ }, mode: :compat)
40
+ rescue => e
41
+ logger.error e.inspect + "\n" + e.backtrace.join("\n")
42
+ return Oj.dump({
43
+ "status" => 500,
44
+ "errors" => ['Internal Server Error', 'Failed to dump the response to JSON']
45
+ }, mode: :compat)
46
+ end
47
+
48
+ def to_s
49
+ return "#<#{self.class} #{self.to_json}>"
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,140 @@
1
+
2
+ module Fleck
3
+ class Consumer
4
+ class << self
5
+ attr_accessor :logger, :configs, :consumers
6
+ end
7
+
8
+ def self.inherited(subclass)
9
+ super
10
+ init_consumer(subclass)
11
+ autostart(subclass)
12
+ Fleck.register_consumer(subclass)
13
+ end
14
+
15
+ def self.configure(opts = {})
16
+ self.configs.merge!(opts)
17
+ logger.debug "Consumer configurations updated."
18
+ end
19
+
20
+ def self.init_consumer(subclass)
21
+ subclass.logger = Fleck.logger.clone
22
+ subclass.logger.progname = subclass.to_s
23
+
24
+ subclass.logger.debug "Setting defaults for #{subclass.to_s.color(:yellow)} consumer"
25
+
26
+ subclass.configs = Fleck.config.default_options
27
+ subclass.consumers = []
28
+ end
29
+
30
+ def self.autostart(subclass)
31
+ # Use TracePoint to autostart the consumer when ready
32
+ trace = TracePoint.new(:end) do |tp|
33
+ if tp.self == subclass
34
+ # disable tracing when we reach the end of the subclass
35
+ trace.disable
36
+ # create a new instance of the subclass, in order to start the consumer
37
+ [subclass.configs[:concurrency].to_i, 1].max.times do |i|
38
+ subclass.consumers << subclass.new(i)
39
+ end
40
+ end
41
+ end
42
+ trace.enable
43
+ end
44
+
45
+ def initialize(thread_id = nil)
46
+ @__thread_id = thread_id
47
+ @__connection = nil
48
+
49
+ @__host = configs[:host]
50
+ @__port = configs[:port]
51
+ @__user = configs[:user] || 'guest'
52
+ @__pass = configs[:password] || configs[:pass]
53
+ @__vhost = configs[:vhost] || "/"
54
+ @__queue_name = configs[:queue]
55
+
56
+ logger.info "Launching #{self.class.to_s.color(:yellow)} consumer ..."
57
+
58
+ connect!
59
+ create_channel!
60
+ subscribe!
61
+
62
+ at_exit do
63
+ terminate
64
+ end
65
+ end
66
+
67
+ def on_message(request, response)
68
+ raise NotImplementedError.new("You must implement #on_message(delivery_info, metadata, payload) method")
69
+ end
70
+
71
+ def terminate
72
+ unless @__channel.closed?
73
+ @__channel.close
74
+ logger.info "Consumer successfully terminated."
75
+ end
76
+ end
77
+
78
+ def logger
79
+ return @logger if @logger
80
+ @logger = self.class.logger.clone
81
+ @logger.progname = "#{self.class.name}" + (configs[:concurrency].to_i <= 1 ? "" : "[#{@__thread_id}]")
82
+
83
+ @logger
84
+ end
85
+
86
+ def configs
87
+ @configs ||= self.class.configs
88
+ end
89
+
90
+ protected
91
+
92
+ def connect!
93
+ @__connection = Fleck.connection(host: @__host, port: @__port, user: @__user, pass: @__pass, vhost: @__vhost)
94
+ end
95
+
96
+ def create_channel!
97
+ if @__channel && !@__channel.closed?
98
+ logger.info("Closing the opened channel...")
99
+ @__channel.close
100
+ end
101
+
102
+ logger.debug "Creating a new channel for #{self.class.to_s.color(:yellow)} consumer"
103
+ @__channel = @__connection.create_channel
104
+ @__channel.prefetch(1) # prevent from dispatching a new RabbitMQ message, until the previous message is not processed
105
+ @__queue = @__channel.queue(@__queue_name, auto_delete: false)
106
+ @__exchange = @__channel.default_exchange
107
+ end
108
+
109
+ def subscribe!
110
+ logger.debug "Consuming from queue: #{@__queue_name.color(:green)}"
111
+ @__subscription = @__queue.subscribe do |delivery_info, metadata, payload|
112
+ response = Fleck::Consumer::Response.new(metadata.correlation_id)
113
+ begin
114
+ request = Fleck::Consumer::Request.new(metadata, payload)
115
+ if request.errors.empty?
116
+ on_message(request, response)
117
+ else
118
+ response.status = request.status
119
+ response.errors += request.errors
120
+ end
121
+ rescue => e
122
+ logger.error e.inspect + "\n" + e.backtrace.join("\n")
123
+ response.status = 500
124
+ response.errors << 'Internal Server Error'
125
+ end
126
+
127
+ logger.debug "Sending response: #{response}"
128
+ @__exchange.publish(response.to_json, routing_key: metadata.reply_to, correlation_id: metadata.correlation_id)
129
+ end
130
+ end
131
+
132
+ def restart!
133
+ create_channel!
134
+ subscribe!
135
+ end
136
+ end
137
+ end
138
+
139
+ require "fleck/consumer/request"
140
+ require "fleck/consumer/response"
@@ -0,0 +1,48 @@
1
+
2
+ class HashWithIndifferentAccess < Hash
3
+ def initialize(original)
4
+ super
5
+ copy_from(original)
6
+ end
7
+
8
+ def []=(key, value)
9
+ super(key.to_s, self.class.convert_value(value))
10
+ end
11
+
12
+ def [](key)
13
+ super(key.to_s)
14
+ end
15
+
16
+ def fetch(key, *extras)
17
+ super(key.to_s, *extras)
18
+ end
19
+
20
+ def delete(key)
21
+ super(key.to_s)
22
+ end
23
+
24
+ def self.convert_value(value)
25
+ if value.is_a?(Hash)
26
+ value.to_hash_with_indifferent_access
27
+ elsif value.is_a?(Array)
28
+ value.map!{|item| item.is_a?(Hash) || item.is_a?(Array) ? HashWithIndifferentAccess.convert_value(item) : item }
29
+ else
30
+ value
31
+ end
32
+ end
33
+
34
+ protected
35
+
36
+ def copy_from(original)
37
+ original.each do |key, value|
38
+ self[key] = self.class.convert_value(value)
39
+ end
40
+ end
41
+ end
42
+
43
+
44
+ class Hash
45
+ def to_hash_with_indifferent_access
46
+ return HashWithIndifferentAccess.new(self)
47
+ end
48
+ end
@@ -0,0 +1,10 @@
1
+
2
+ module Fleck::Loggable
3
+ def logger
4
+ return @logger if @logger
5
+ @logger = Fleck.logger.clone
6
+ @logger.progname = self.class.name
7
+
8
+ @logger
9
+ end
10
+ end
@@ -0,0 +1,3 @@
1
+ module Fleck
2
+ VERSION = "0.1.0"
3
+ end
data/lib/fleck.rb ADDED
@@ -0,0 +1,74 @@
1
+ require "logger"
2
+ require "rainbow"
3
+ require "rainbow/ext/string"
4
+ require "bunny"
5
+ require "thread_safe"
6
+ require "securerandom"
7
+ require "oj"
8
+ require "fleck/version"
9
+ require "fleck/hash_with_indifferent_access"
10
+ require "fleck/configuration"
11
+ require "fleck/loggable"
12
+ require "fleck/consumer"
13
+ require "fleck/client"
14
+
15
+ module Fleck
16
+ @config = Configuration.new
17
+ @consumers = ThreadSafe::Array.new
18
+ @connections = ThreadSafe::Hash.new
19
+
20
+ at_exit do
21
+ Fleck.terminate
22
+ end
23
+
24
+ def self.configure
25
+ yield @config if block_given?
26
+ @config
27
+ end
28
+
29
+ def self.logger
30
+ @config.logger
31
+ end
32
+
33
+ def self.register_consumer(consumer_class)
34
+ unless @consumers.include?(consumer_class)
35
+ @consumers << consumer_class
36
+ end
37
+ end
38
+
39
+ def self.connection(options)
40
+ opts = Fleck.config.default_options.merge(options)
41
+ key = "ampq://#{opts[:user]}@#{opts[:host]}:#{opts[:port]}#{opts[:vhost]}"
42
+ conn = @connections[key]
43
+ if !conn || conn.closed?
44
+ opts[:logger] = Fleck.logger.clone
45
+ opts[:logger].progname += "::Bunny"
46
+ logger.info "New connection #{key}"
47
+ conn = Bunny.new(opts)
48
+ conn.start
49
+ @connections[key] = conn
50
+ end
51
+ return conn
52
+ end
53
+
54
+ def self.terminate
55
+ @connections.each do |key, connection|
56
+ begin
57
+ Fleck.logger.info "Closing connection #{key}"
58
+ connection.close
59
+ rescue => e
60
+ Fleck.logger.error e.inspect
61
+ end
62
+ end
63
+ @connections.clear
64
+
65
+ true
66
+ end
67
+
68
+ private
69
+
70
+ class << self
71
+ attr_reader :config
72
+ end
73
+
74
+ end
metadata ADDED
@@ -0,0 +1,169 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: fleck
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Groza Sergiu
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2016-02-16 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.10'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.10'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rainbow
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '2.0'
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '2.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: bunny
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '2.2'
76
+ type: :runtime
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '2.2'
83
+ - !ruby/object:Gem::Dependency
84
+ name: thread_safe
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '0.3'
90
+ type: :runtime
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '0.3'
97
+ - !ruby/object:Gem::Dependency
98
+ name: oj
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: '2.14'
104
+ type: :runtime
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: '2.14'
111
+ description: "\n Fleck is a library for syncronous and asyncronous communication
112
+ over Message Queues services. Unlike a common\n HTTP communication, Fleck requests
113
+ and responses are pure JSON messages.\n "
114
+ email:
115
+ - serioja90@gmail.com
116
+ executables: []
117
+ extensions: []
118
+ extra_rdoc_files: []
119
+ files:
120
+ - ".gitignore"
121
+ - ".rspec"
122
+ - ".travis.yml"
123
+ - CODE_OF_CONDUCT.md
124
+ - Gemfile
125
+ - LICENSE.txt
126
+ - README.md
127
+ - Rakefile
128
+ - bin/console
129
+ - bin/setup
130
+ - example.rb
131
+ - fleck.gemspec
132
+ - lib/fleck.rb
133
+ - lib/fleck/client.rb
134
+ - lib/fleck/client/request.rb
135
+ - lib/fleck/client/response.rb
136
+ - lib/fleck/configuration.rb
137
+ - lib/fleck/consumer.rb
138
+ - lib/fleck/consumer/request.rb
139
+ - lib/fleck/consumer/response.rb
140
+ - lib/fleck/hash_with_indifferent_access.rb
141
+ - lib/fleck/loggable.rb
142
+ - lib/fleck/version.rb
143
+ homepage: https://github.com/serioja90/fleck
144
+ licenses:
145
+ - MIT
146
+ metadata: {}
147
+ post_install_message:
148
+ rdoc_options: []
149
+ require_paths:
150
+ - lib
151
+ required_ruby_version: !ruby/object:Gem::Requirement
152
+ requirements:
153
+ - - "~>"
154
+ - !ruby/object:Gem::Version
155
+ version: '2.0'
156
+ required_rubygems_version: !ruby/object:Gem::Requirement
157
+ requirements:
158
+ - - ">="
159
+ - !ruby/object:Gem::Version
160
+ version: '0'
161
+ requirements: []
162
+ rubyforge_project:
163
+ rubygems_version: 2.4.6
164
+ signing_key:
165
+ specification_version: 4
166
+ summary: A Ruby gem for syncronous and asyncronous communication via Message Queue
167
+ services.
168
+ test_files: []
169
+ has_rdoc: