freddy 0.3.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 2db3000f993c822db69070b9f68a96af43fee7fc
4
+ data.tar.gz: dfb430e314b3626e5c65b06f4932fcfd691fffa6
5
+ SHA512:
6
+ metadata.gz: 0654512ddf983cb2aef3bda80f46c01ec302cd728fc53e519f67971ac25f7c1ba3cc2170bd5778bfda6d3460acb1aa365851c21b37c3331a481c855621b7ac8c
7
+ data.tar.gz: ca4e0785cf2f79ce58158a42d6cfda05d81d4c201e0753182d870c5976303eca45a84bf73e016082df020d214115499304b75be3290f2d7abe0bb7ad36c44772
@@ -0,0 +1 @@
1
+ .bundle/
@@ -0,0 +1,8 @@
1
+ .git*
2
+ .rspec
3
+ .ruby*
4
+ Gemfile*
5
+ *.gemspec
6
+ spec/
7
+ *.rb
8
+ lib/messaging
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --color
2
+ --format progress
@@ -0,0 +1 @@
1
+ sm-messaging
@@ -0,0 +1 @@
1
+ ruby-2.1
@@ -0,0 +1,8 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.1.0
4
+ services:
5
+ - rabbitmq
6
+ before_script:
7
+ - bundle
8
+ script: bundle exec rspec
data/Gemfile ADDED
@@ -0,0 +1,8 @@
1
+ source "https://rubygems.org"
2
+
3
+ group :test, :development do
4
+ gem 'rspec'
5
+ gem 'pry'
6
+ end
7
+
8
+ gemspec
@@ -0,0 +1,49 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ freddy (0.3.0)
5
+ bunny (= 1.6.3)
6
+ hamster (~> 1.0.1.pre.rc3)
7
+ symbolizer
8
+
9
+ GEM
10
+ remote: https://rubygems.org/
11
+ specs:
12
+ amq-protocol (1.9.2)
13
+ atomic (1.1.16)
14
+ bunny (1.6.3)
15
+ amq-protocol (>= 1.9.2)
16
+ coderay (1.1.0)
17
+ diff-lcs (1.2.5)
18
+ hamster (1.0.1.pre.rc3)
19
+ atomic (~> 1.1)
20
+ method_source (0.8.2)
21
+ pry (0.10.1)
22
+ coderay (~> 1.1.0)
23
+ method_source (~> 0.8.1)
24
+ slop (~> 3.4)
25
+ rake (10.3.2)
26
+ rspec (3.1.0)
27
+ rspec-core (~> 3.1.0)
28
+ rspec-expectations (~> 3.1.0)
29
+ rspec-mocks (~> 3.1.0)
30
+ rspec-core (3.1.7)
31
+ rspec-support (~> 3.1.0)
32
+ rspec-expectations (3.1.2)
33
+ diff-lcs (>= 1.2.0, < 2.0)
34
+ rspec-support (~> 3.1.0)
35
+ rspec-mocks (3.1.3)
36
+ rspec-support (~> 3.1.0)
37
+ rspec-support (3.1.2)
38
+ slop (3.6.0)
39
+ symbolizer (0.0.1)
40
+
41
+ PLATFORMS
42
+ ruby
43
+
44
+ DEPENDENCIES
45
+ bundler (~> 1.3)
46
+ freddy!
47
+ pry
48
+ rake
49
+ rspec
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2013-2015 SaleMove Inc.
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,163 @@
1
+ # Messaging API supporting acknowledgements and request-response
2
+
3
+ [![Build Status](https://travis-ci.org/salemove/node-freddy.svg?branch=master)](https://travis-ci.org/salemove/node-freddy)
4
+ [![Code Climate](https://codeclimate.com/github/salemove/freddy/badges/gpa.svg)](https://codeclimate.com/github/salemove/freddy)
5
+
6
+ ## Setup
7
+
8
+ * Inject the appropriate logger and set up connection parameters:
9
+
10
+ ```ruby
11
+ logger = Logger.new(STDOUT)
12
+ freddy = Freddy.build(logger, host: 'localhost', port: 5672, user: 'guest', pass: 'guest')
13
+ ```
14
+
15
+ ## Delivering messages
16
+
17
+ ### Simple delivery
18
+
19
+ #### Send and forget
20
+ Sends a `message` to the given `destination`. If there is no consumer then the
21
+ message stays in the queue until somebody consumes it.
22
+ ```ruby
23
+ freddy.deliver(destination, message)
24
+ ```
25
+
26
+ #### Expiring messages
27
+ Sends a `message` to the given `destination`. If nobody consumes the message in
28
+ `timeout` seconds then the message is discarded. This is useful for showing
29
+ notifications that must happen in a certain timeframe but where we don't really
30
+ care if it reached the destination or not.
31
+ ```ruby
32
+ freddy.deliver(destination, message, timeout: 5)
33
+ ```
34
+
35
+ ### Request delivery
36
+ #### Expiring messages
37
+ Sends a `message` to the given `destination`. Has a default timeout of 3 and
38
+ discards the message from the queue if a response hasn't been returned in that
39
+ time.
40
+ ```ruby
41
+ response = freddy.deliver_with_response(destination, message)
42
+ ```
43
+
44
+ #### Persistant messages
45
+ Sends a `message` to the given `destination`. Keeps the message in the queue if
46
+ a timeout occurs.
47
+ ```ruby
48
+ response = freddy.deliver_with_response(destination, message, timeout: 4, delete_on_timeout: false)
49
+ ```
50
+
51
+ #### Errors
52
+ `deliver_with_response` raises an error if an error is returned. This can be handled by rescuing from `Freddy::ErrorResponse` as:
53
+ ```ruby
54
+ begin
55
+ response = freddy.deliver_with_response 'Q', {}
56
+ # ...
57
+ rescue Freddy::ErrorResponse => e
58
+ e.response # => { error: 'Timed out waiting for response' }
59
+ ```
60
+
61
+ ## Responding to messages
62
+ ```ruby
63
+ freddy.respond_to destination do |message, msg_handler|
64
+ # ...
65
+ end
66
+ ```
67
+
68
+ The callback is called with 2 arguments
69
+ * the parsed message (note that in the message all keys are symbolized)
70
+ * the `MessageHandler` (described further down)
71
+
72
+ ## The MessageHandler
73
+
74
+ When responding to messages the MessageHandler is given as the second argument.
75
+
76
+ The following operations are supported:
77
+
78
+ * responding with a successful response
79
+ ```ruby
80
+ msg_handler.success(response = nil)
81
+ ```
82
+
83
+ * responding with an error response
84
+ ```ruby
85
+ msg_handler.error(error: "Couldn't process message")
86
+ ```
87
+
88
+ ## Tapping into messages
89
+ When it's necessary to receive messages but not consume them, consider tapping.
90
+
91
+ ```ruby
92
+ freddy.tap_into pattern do |message, destination|
93
+ ```
94
+
95
+ * `destination` refers to the destination that the message was sent to
96
+ * Note that it is not possible to respond to the message while tapping.
97
+ * When tapping the following wildcards are supported in the `pattern` :
98
+ * `#` matching 0 or more words
99
+ * `*` matching exactly one word
100
+
101
+ Examples:
102
+
103
+ ```ruby
104
+ freddy.tap_into "i.#.free"
105
+ ```
106
+
107
+ receives messages that are delivered to `"i.want.to.break.free"`
108
+
109
+ ```ruby
110
+ freddy.tap_into "somebody.*.love"
111
+ ```
112
+
113
+ receives messages that are delivered to `somebody.to.love` but doesn't receive messages delivered to `someboy.not.to.love`
114
+
115
+ ## The ResponderHandler
116
+
117
+ When responding to a message or tapping the ResponderHandler is returned.
118
+ ```ruby
119
+ responder_handler = freddy.respond_to ....
120
+ ```
121
+
122
+ The following operations are supported:
123
+
124
+ * stop responding
125
+ ```ruby
126
+ responder_handler.cancel
127
+ ```
128
+
129
+ * join the current thread to the responder thread
130
+ ```ruby
131
+ responder_handler.join
132
+ ```
133
+
134
+ * delete the destination
135
+ ```ruby
136
+ responder_handler.destroy_destination
137
+ ```
138
+
139
+ * Primary use case is in tests to not leave dangling destinations. It deletes the destination even if there are responders for the same destination in other parts of the system. Use with caution in production code.
140
+
141
+
142
+ ## Notes about concurrency
143
+
144
+ The underlying bunny implementation uses 1 responder thread by default. This means that if there is a time-consuming process or a sleep call in a responder then other responders will not receive messages concurrently.
145
+
146
+ This is especially devious when using `deliver_with_response` in a responder because `deliver_with_response` creates a new anonymous responder which will not receive the response if the parent responder uses a sleep call.
147
+
148
+ To resolve this problem *freddy* uses 4 responder threads by default (configurable by `responder_thread_count`). Note that this means that ordered message processing is not guaranteed by default. Read more from <http://rubybunny.info/articles/concurrency.html>.
149
+
150
+ ## Credits
151
+
152
+ **freddy** was originally written by [Urmas Talimaa] as part of SaleMove development team.
153
+
154
+ ![SaleMove Inc. 2012][SaleMove Logo]
155
+
156
+ **freddy** is maintained and funded by [SaleMove, Inc].
157
+
158
+ The names and logos for **SaleMove** are trademarks of SaleMove, Inc.
159
+
160
+ [Urmas Talimaa]: https://github.com/urmastalimaa?source=c "Urmas"
161
+ [SaleMove, Inc]: http://salemove.com/ "SaleMove Website"
162
+ [SaleMove Logo]: http://app.salemove.com/assets/logo.png "SaleMove Inc. 2012"
163
+ [Apache License]: http://choosealicense.com/licenses/apache/ "Apache License"
@@ -0,0 +1,7 @@
1
+ require "bundler/gem_tasks"
2
+
3
+ require "rspec/core/rake_task"
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task ci: :spec
7
+ task default: :spec
@@ -0,0 +1,25 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "freddy"
7
+ spec.version = '0.3.0'
8
+ spec.authors = ["Urmas Talimaa"]
9
+ spec.email = ["urmas.talimaa@gmail.com"]
10
+ spec.description = %q{Messaging API}
11
+ spec.summary = %q{API for inter-application messaging supporting acknowledgements and request-response}
12
+ spec.license = "Private"
13
+
14
+ spec.files = `git ls-files`.split($/)
15
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
16
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
17
+ spec.require_paths = ["lib"]
18
+
19
+ spec.add_development_dependency "bundler", "~> 1.3"
20
+ spec.add_development_dependency "rake"
21
+
22
+ spec.add_dependency "bunny", "1.6.3"
23
+ spec.add_dependency "symbolizer"
24
+ spec.add_dependency "hamster", "~> 1.0.1.pre.rc3"
25
+ end
@@ -0,0 +1,86 @@
1
+ require 'bunny'
2
+ require 'json'
3
+ require 'symbolizer'
4
+
5
+ require_relative 'freddy/consumer'
6
+ require_relative 'freddy/producer'
7
+ require_relative 'freddy/request'
8
+
9
+ class Freddy
10
+ class ErrorResponse < StandardError
11
+ attr_reader :response
12
+
13
+ def initialize(response)
14
+ @response = response
15
+ super('Use #response to get the error response')
16
+ end
17
+ end
18
+
19
+ FREDDY_TOPIC_EXCHANGE_NAME = 'freddy-topic'.freeze
20
+
21
+ def self.format_backtrace(backtrace)
22
+ backtrace.map{ |x|
23
+ x.match(/^(.+?):(\d+)(|:in `(.+)')$/);
24
+ [$1,$2,$4]
25
+ }.join "\n"
26
+ end
27
+
28
+ def self.format_exception(exception)
29
+ "#{exception.exception}\n#{format_backtrace(exception.backtrace)}"
30
+ end
31
+
32
+ def self.notify(name, message, parameters={})
33
+ if defined? Airbrake
34
+ Airbrake.notify_or_ignore({
35
+ error_class: name,
36
+ error_message: message,
37
+ cgi_data: ENV.to_hash,
38
+ parameters: parameters
39
+ })
40
+ end
41
+ end
42
+
43
+ def self.notify_exception(exception, parameters={})
44
+ if defined? Airbrake
45
+ Airbrake.notify_or_ignore(exception, cgi_data: ENV.to_hash, parameters: parameters)
46
+ end
47
+ end
48
+
49
+ def self.build(logger = Logger.new(STDOUT), bunny_config)
50
+ bunny = Bunny.new(bunny_config)
51
+ bunny.start
52
+
53
+ channel = bunny.create_channel(nil, bunny_config[:responder_thread_count] || 4)
54
+ new(channel, logger)
55
+ end
56
+
57
+ attr_reader :channel, :consumer, :producer, :request
58
+
59
+ def initialize(channel, logger)
60
+ @channel = channel
61
+ @consumer = Consumer.new channel, logger
62
+ @producer = Producer.new channel, logger
63
+ @request = Request.new channel, logger
64
+ end
65
+
66
+ def respond_to(destination, &callback)
67
+ @request.respond_to destination, &callback
68
+ end
69
+
70
+ def tap_into(pattern, &callback)
71
+ @consumer.tap_into pattern, &callback
72
+ end
73
+
74
+ def deliver(destination, payload, timeout: 0)
75
+ opts = {}
76
+ opts[:expiration] = (timeout * 1000).to_i if timeout > 0
77
+
78
+ @producer.produce destination, payload, opts
79
+ end
80
+
81
+ def deliver_with_response(destination, payload, timeout: 3, delete_on_timeout: true)
82
+ @request.sync_request destination, payload, {
83
+ timeout: timeout, delete_on_timeout: delete_on_timeout
84
+ }
85
+ end
86
+ end
@@ -0,0 +1,64 @@
1
+ require_relative 'responder_handler'
2
+ require_relative 'message_handler'
3
+ require_relative 'request'
4
+ require_relative 'delivery'
5
+
6
+ class Freddy
7
+ class Consumer
8
+
9
+ class EmptyConsumer < Exception
10
+ end
11
+
12
+ def initialize(channel, logger)
13
+ @channel, @logger = channel, logger
14
+ @topic_exchange = @channel.topic Freddy::FREDDY_TOPIC_EXCHANGE_NAME
15
+ end
16
+
17
+ def consume(destination, options = {}, &block)
18
+ raise EmptyConsumer unless block
19
+ consume_from_queue create_queue(destination), options, &block
20
+ end
21
+
22
+ def consume_from_queue(queue, options = {}, &block)
23
+ consumer = queue.subscribe options do |delivery_info, properties, payload|
24
+ parsed_payload = parse_payload(payload)
25
+ log_receive_event(queue.name, parsed_payload)
26
+ block.call parsed_payload, Delivery.new(delivery_info, properties)
27
+ end
28
+ @logger.debug "Consuming messages on #{queue.name}"
29
+ ResponderHandler.new consumer, @channel
30
+ end
31
+
32
+ def tap_into(pattern, &block)
33
+ queue = @channel.queue("", exclusive: true).bind(@topic_exchange, routing_key: pattern)
34
+ consumer = queue.subscribe do |delivery_info, properties, payload|
35
+ block.call parse_payload(payload), delivery_info.routing_key
36
+ end
37
+ @logger.debug "Tapping into messages that match #{pattern}"
38
+ ResponderHandler.new consumer, @channel
39
+ end
40
+
41
+ private
42
+
43
+ def parse_payload(payload)
44
+ if payload == 'null'
45
+ {}
46
+ else
47
+ Symbolizer.symbolize(JSON(payload))
48
+ end
49
+ end
50
+
51
+ def create_queue(destination)
52
+ @channel.queue(destination)
53
+ end
54
+
55
+ def log_receive_event(queue_name, payload)
56
+ if defined?(Logasm) && @logger.is_a?(Logasm)
57
+ @logger.info "Received message", queue: queue_name
58
+ @logger.debug "Received message", queue: queue_name, payload: payload
59
+ else
60
+ @logger.debug "Received message on #{queue_name} with payload #{payload}"
61
+ end
62
+ end
63
+ end
64
+ end