event_people 1.0.1

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
+ SHA256:
3
+ metadata.gz: 2b1e5ca203068a90528dffe028e28ff159fea2be235a8cb7124a27d65d9e994a
4
+ data.tar.gz: '06552910da1f09062cd1a0056c9a048a05ced2fe48e8f29759c2d41dce1ea847'
5
+ SHA512:
6
+ metadata.gz: 81234ed5232c88a4231c49d1bc0675ae9c637f99acc53e917d6fb193ddf8a6bbd0e0a9db1980009aad8abf16dc32be24d62afb455de8fd0bcfab2cdc0018c425
7
+ data.tar.gz: d529f3a44d8a53f05c81a024a73ca8217e42cac3b338b58ed8015322b4c3dbe49788730560e044380fe46d2ad7e8cca42bbee36a67ad0b94e058cf62ee37f471
@@ -0,0 +1,49 @@
1
+ # Ruby CircleCI 2.0 configuration file
2
+ #
3
+ # Check https://circleci.com/docs/2.1/language-ruby/ for more details
4
+ #
5
+ version: 2.1
6
+ jobs:
7
+ validate:
8
+ docker:
9
+ # specify the version you desire here
10
+ - image: cimg/ruby:3.1
11
+
12
+ steps:
13
+ - checkout
14
+
15
+ # Download and cache dependencies
16
+ - restore_cache:
17
+ keys:
18
+ - pin-people-event-people-deps-{{ checksum "Gemfile.lock" }}
19
+ - pin-people-event-people-deps-
20
+
21
+ - run:
22
+ name: install dependencies
23
+ command: |
24
+ gem install bundler
25
+ bundle config set path 'vendor/bundle'
26
+ bundle config set jobs '4'
27
+ bundle config set retry '3'
28
+ bundle install
29
+
30
+ - save_cache:
31
+ paths:
32
+ - ./vendor/bundle
33
+ key: pin-people-event-people-deps-{{ checksum "Gemfile.lock" }}
34
+
35
+ # run tests!
36
+ - run:
37
+ name: run tests
38
+ environment:
39
+ DATABASE_URL: "postgres://ubuntu@localhost:5432/core_test"
40
+ command: |
41
+ cp .env.example .env
42
+
43
+ RUBYOPT='-W:no-deprecated -W:no-experimental' bundle exec rspec --format progress
44
+
45
+ workflows:
46
+ version: 2.1
47
+ validate:
48
+ jobs:
49
+ - validate
data/.env.example ADDED
@@ -0,0 +1,4 @@
1
+ RABBIT_URL=amqp://guest:guest@localhost:5672
2
+ RABBIT_EVENT_PEOPLE_APP_NAME=app_name
3
+ RABBIT_EVENT_PEOPLE_VHOST=event_people
4
+ RABBIT_EVENT_PEOPLE_TOPIC_NAME=event_people
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ .env*
11
+ !.env.example
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --require spec_helper
2
+ --color
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 3.1.1
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in event_people.gemspec
4
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,65 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ event_people (1.0.1)
5
+ bunny (~> 2.7)
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ amq-protocol (2.3.2)
11
+ awesome_print (1.9.2)
12
+ bunny (2.19.0)
13
+ amq-protocol (~> 2.3, >= 2.3.1)
14
+ sorted_set (~> 1, >= 1.0.2)
15
+ byebug (11.1.3)
16
+ coderay (1.1.3)
17
+ diff-lcs (1.5.0)
18
+ method_source (1.0.0)
19
+ pry (0.13.1)
20
+ coderay (~> 1.1)
21
+ method_source (~> 1.0)
22
+ pry-byebug (3.9.0)
23
+ byebug (~> 11.0)
24
+ pry (~> 0.13.0)
25
+ pry-meta (0.0.10)
26
+ awesome_print
27
+ pry
28
+ pry-byebug
29
+ pry-remote
30
+ pry-remote (0.1.8)
31
+ pry (~> 0.9)
32
+ slop (~> 3.0)
33
+ rake (13.0.6)
34
+ rbtree (0.4.5)
35
+ rspec (3.11.0)
36
+ rspec-core (~> 3.11.0)
37
+ rspec-expectations (~> 3.11.0)
38
+ rspec-mocks (~> 3.11.0)
39
+ rspec-core (3.11.0)
40
+ rspec-support (~> 3.11.0)
41
+ rspec-expectations (3.11.0)
42
+ diff-lcs (>= 1.2.0, < 2.0)
43
+ rspec-support (~> 3.11.0)
44
+ rspec-mocks (3.11.1)
45
+ diff-lcs (>= 1.2.0, < 2.0)
46
+ rspec-support (~> 3.11.0)
47
+ rspec-support (3.11.0)
48
+ set (1.0.2)
49
+ slop (3.6.0)
50
+ sorted_set (1.0.3)
51
+ rbtree
52
+ set (~> 1.0)
53
+
54
+ PLATFORMS
55
+ arm64-darwin-21
56
+
57
+ DEPENDENCIES
58
+ bundler
59
+ event_people!
60
+ pry-meta
61
+ rake
62
+ rspec
63
+
64
+ BUNDLED WITH
65
+ 2.3.15
data/LICENSE.txt ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
data/README.md ADDED
@@ -0,0 +1,239 @@
1
+ # EventPeople
2
+
3
+ [![CircleCI](https://dl.circleci.com/status-badge/img/gh/pin-people/event_people_ruby/tree/main.svg?style=svg)](https://dl.circleci.com/status-badge/redirect/gh/pin-people/event_people_ruby/tree/main)
4
+
5
+ EventPeople is a tool to simplify the communication of services based on events. It is an extension of the [EventBus](https://github.com/EmpregoLigado/event_bus_rb) gem.
6
+
7
+ The main idea is to provide a tool that can emit or consume events based on its names, the event name has 4 words (`resource.origin.action.destiny`) which defines some important info about what kind of event it is, where it comes from and who is eligible to consume it:
8
+
9
+ - **resource:** Defines which resource this event is related like a `user`, a `product`, `company` or anything that you want;
10
+ - **origin:** Defines the name of the system which emitted the event;
11
+ - **action:** What action is made on the resource like `create`, `delete`, `update`, etc. PS: *It is recommended to use the Semple Present tense for actions*;
12
+ - **destiny (Optional):** This word is optional and if not provided EventPeople will add a `.all` to the end of the event name. It defines which service should consume the event being emitted, so if it is defined and there is a service whith the given name only this service will receive it. It is very helpful when you need to re-emit some events. Also if it is `.all` all services will receive it.
13
+
14
+ As of today EventPeople uses RabbitMQ as its datasource, but there are plans to add support for other Brokers in the future.
15
+
16
+ ## Installation
17
+
18
+ Add this line to your application's Gemfile:
19
+
20
+ ```ruby
21
+ gem 'event_people'
22
+ ```
23
+
24
+ And then execute:
25
+
26
+ $ bundle
27
+
28
+ Or install it yourself as:
29
+
30
+ $ gem install event_people
31
+
32
+ And set env vars:
33
+ ```ruby
34
+ ENV['RABBIT_URL'] = 'amqp://guest:guest@localhost:5672'
35
+ ENV['RABBIT_EVENT_PEOPLE_APP_NAME'] = 'service_name'
36
+ ENV['RABBIT_EVENT_PEOPLE_VHOST'] = 'event_people'
37
+ ENV['RABBIT_EVENT_PEOPLE_TOPIC_NAME'] = 'event_people'
38
+ ````
39
+
40
+ ## Usage
41
+
42
+ ### Events
43
+
44
+ The main component of `EventPeople` is the `EventPeople::Event` class which wraps all the logic of an event and whenever you receive or want to send an event you will use it.
45
+
46
+ It has 2 attributes `name` and `payload`:
47
+
48
+ - **name:** The name must follow our conventions, being it 3 (`resource.origin.action`) or 4 words (`resource.origin.action.destiny`);
49
+ - **payload:** It is the body of the massage, it should be a Hash object for simplicity and flexibility.
50
+
51
+ ```ruby
52
+ require 'event_people'
53
+
54
+ event_name = 'user.users.create'
55
+ body = { id: 42, name: 'John Doe', age: 35 }
56
+ event = EventPeople::Event.new(event_name, body)
57
+ ```
58
+
59
+ There are 3 main interfaces to use `EventPeople` on your project:
60
+
61
+ - Calling `EventPeople::Emitter.trigger(event)` inside your project;
62
+ - Calling `EventPeople::Listener.on(event_name)` inside your project;
63
+ - Or extending `EventPeople::Listeners::Base` and use it as a daemon.
64
+
65
+ ### Using the Emitter
66
+ You can emit events on your project passing an `EventPeople::Event` instance to the `EventPeople::Emitter.trigger` method. Doing this other services that are subscribed to these events will receive it.
67
+
68
+ ```ruby
69
+ require 'event_people'
70
+
71
+ event_name = 'receipt.payments.pay.users'
72
+ body = { amount: 350.76 }
73
+ event = EventPeople::Event.new(event_name, body)
74
+
75
+ EventPeople::Emitter.trigger(event)
76
+
77
+ # Don't forget to close the connection!!!
78
+ EventPeople::Config.broker.close_connection
79
+ ```
80
+ [See more details](https://github.com/pin-people/event_people_ruby/blob/master/examples/emitter.rb)
81
+
82
+ ### Listeners
83
+
84
+ You can subscribe to events based on patterns for the event names you want to consume or you can use the full name of the event to consume single events.
85
+
86
+ We follow the RabbitMQ pattern matching model, so given each word of the event name is separated by a dot (`.`), you can use the following symbols:
87
+
88
+ - `* (star):` to match exactly one word. Example `resource.*.*.all`;
89
+ - `# (hash):` to match zero or more words. Example `resource.#.all`.
90
+
91
+ Other important aspect of event consumming is the result of the processing we provide 3 methods so you can inform the Broker what to do with the event next:
92
+
93
+ - `success!:` should be called when the event was processed successfuly and the can be discarded;
94
+ - `fail!:` should be called when an error ocurred processing the event and the message should be requeued;
95
+ - `reject!:` should be called whenever a message should be discarded without being processed.
96
+
97
+ Given you want to consume a single event inside your project you can use the `EventPeople::Listener.on` method. It consumes a single event, given there are events available to be consumed with the given name pattern.
98
+
99
+ ```ruby
100
+ require 'event_people'
101
+
102
+ # 3 words event names will be replaced by its 4 word wildcard
103
+ # counterpart: 'payment.payments.pay.all'
104
+ event_name = 'payment.payments.pay'
105
+
106
+ EventPeople::Listener.on(event_name) do |event, _delivery_info|
107
+ puts ""
108
+ puts " - Received the "#{event.name}" message from #{event.origin}:"
109
+ puts " Message: #{event.body}"
110
+ puts ""
111
+ success!
112
+ end
113
+
114
+ EventPeople::Config.broker.close_connection
115
+ ```
116
+
117
+ You can also receive all available messages using a loop:
118
+
119
+ ```ruby
120
+ require 'event_people'
121
+
122
+ event_name = 'payment.payments.pay.all'
123
+ has_events = true
124
+
125
+ while has_events do
126
+ has_events = false
127
+
128
+ EventPeople::Listener.on(event_name) do |event, _delivery_info|
129
+ has_events = true
130
+ puts ""
131
+ puts " - Received the "#{event.name}" message from #{event.origin}:"
132
+ puts " Message: #{event.body}"
133
+ puts ""
134
+ success!
135
+ end
136
+ end
137
+
138
+ EventPeople::Config.broker.close_connection
139
+ ```
140
+ [See more details](https://github.com/pin-people/event_people_ruby/blob/master/examples/listener.rb)
141
+
142
+ #### Multiple events routing
143
+
144
+ If your project needs to handle lots of events you can extend `EventPeople::Listeners::Base` class to bind how many events you need to instance methods, so whenever an event is received the method will be called automatically.
145
+
146
+ ```ruby
147
+ require 'event_people'
148
+
149
+ class CustomEventListener < EventPeople::Listeners::Base
150
+ bind :pay, 'resource.custom.pay'
151
+ bind :receive, 'resource.custom.receive'
152
+ bind :private_channel, 'resource.custom.private.service'
153
+
154
+ def pay(event)
155
+ puts "Paid #{event.body['amount']} for #{event.body['name']} ~> #{event.name}"
156
+
157
+ success!
158
+ end
159
+
160
+ def receive(event)
161
+ if event.body['amount'] > 500
162
+ puts "Received #{event.body['amount']} from #{event.body['name']} ~> #{event.name}"
163
+ else
164
+ puts '[consumer] Got SKIPPED message'
165
+ return reject!
166
+ end
167
+
168
+ success!
169
+ end
170
+
171
+ def private_channel(event)
172
+ puts "[consumer] Got a private message: \"#{event.body['message']}\" ~> #{event.name}"
173
+
174
+ success!
175
+ end
176
+ end
177
+ ```
178
+ [See more details](https://github.com/pin-people/event_people_ruby/blob/master/examples/daemon.rb)
179
+
180
+ #### Creating a Daemon
181
+
182
+ If you have the need to create a deamon to consume messages on background you can use the `EventPeople::Daemon.start` to do so with ease. Just remember to define or import all the event bindings before starting the daemon.
183
+
184
+ ```ruby
185
+ require 'event_people'
186
+
187
+ class CustomEventListener < EventPeople::Listeners::Base
188
+ bind :pay, 'resource.custom.pay'
189
+ bind :receive, 'resource.custom.receive'
190
+ bind :private_channel, 'resource.custom.private.service'
191
+
192
+ def pay(event)
193
+ puts "Paid #{event.body['amount']} for #{event.body['name']} ~> #{event.name}"
194
+
195
+ success!
196
+ end
197
+
198
+ def receive(event)
199
+ if event.body['amount'] > 500
200
+ puts "Received #{event.body['amount']} from #{event.body['name']} ~> #{event.name}"
201
+ else
202
+ puts '[consumer] Got SKIPPED message'
203
+
204
+ return reject!
205
+ end
206
+
207
+ success!
208
+ end
209
+
210
+ def private_channel(event)
211
+ puts "[consumer] Got a private message: \"#{event.body['message']}\" ~> #{event.name}"
212
+
213
+ success!
214
+ end
215
+ end
216
+
217
+ puts '****************** Daemon Ready ******************'
218
+
219
+ EventPeople::Daemon.start
220
+ ```
221
+ [See more details](https://github.com/pin-people/event_people_ruby/blob/master/examples/daemon.rb)
222
+
223
+ ## Development
224
+
225
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `bundle exec rspec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
226
+
227
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
228
+
229
+ ## Contributing
230
+
231
+ - Fork it
232
+ - Create your feature branch (`git checkout -b my-new-feature`)
233
+ - Commit your changes (`git commit -am 'Add some feature'`)
234
+ - Push to the branch (`git push origin my-new-feature`)
235
+ - Create new Pull Request
236
+
237
+ ## License
238
+
239
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
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
@@ -0,0 +1,34 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'event_people/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'event_people'
8
+ spec.version = EventPeople::VERSION
9
+ spec.authors = ['Pin People']
10
+ spec.email = ['contato@pinpeople.com.br']
11
+
12
+ spec.summary = 'Expose an api to produce and consume events.'
13
+ spec.description = 'Tool to produce and consume events to a distributed and async architecture'
14
+ spec.homepage = 'https://github.com/pin-people/event_people_ruby'
15
+ spec.license = 'GNU LESSER GENERAL PUBLIC LICENSE V3'
16
+
17
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
18
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
19
+ raise 'RubyGems 2.0 or newer is required to protect against public gem pushes.' unless spec.respond_to?(:metadata)
20
+
21
+ spec.metadata['allowed_push_host'] = 'https://rubygems.org'
22
+
23
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
24
+ spec.bindir = 'exe'
25
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
26
+ spec.require_paths = ['lib']
27
+
28
+ spec.add_development_dependency 'bundler'
29
+ spec.add_development_dependency 'pry-meta'
30
+ spec.add_development_dependency 'rake'
31
+ spec.add_development_dependency 'rspec'
32
+
33
+ spec.add_dependency 'bunny', '~> 2.7'
34
+ end
@@ -0,0 +1,48 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ ENV['RABBIT_URL'] = 'amqp://guest:guest@localhost:5672'
4
+ ENV['RABBIT_EVENT_PEOPLE_APP_NAME'] = 'EventPeopleExampleApp'
5
+ ENV['RABBIT_EVENT_PEOPLE_VHOST'] = 'event_people'
6
+ ENV['RABBIT_EVENT_PEOPLE_TOPIC_NAME'] = 'event_people'
7
+
8
+ $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
9
+
10
+ require 'rubygems'
11
+ require 'bundler'
12
+ Bundler.require(:default, 'development')
13
+
14
+ require_relative '../lib/event_people'
15
+
16
+ class CustomEventListener < EventPeople::Listeners::Base
17
+ bind :pay, 'resource.custom.pay'
18
+ bind :receive, 'resource.custom.receive'
19
+ bind :private_channel, 'resource.custom.private.service'
20
+
21
+ def pay(event)
22
+ puts "Paid #{event.body['amount']} for #{event.body['name']} ~> #{event.name}"
23
+
24
+ success!
25
+ end
26
+
27
+ def receive(event)
28
+ if event.body['amount'] > 500
29
+ puts "Received #{event.body['amount']} from #{event.body['name']} ~> #{event.name}"
30
+ else
31
+ puts '[consumer] Got SKIPPED message'
32
+
33
+ return reject!
34
+ end
35
+
36
+ success!
37
+ end
38
+
39
+ def private_channel(event)
40
+ puts "[consumer] Got a private message: \"#{event.body['message']}\" ~> #{event.name}"
41
+
42
+ success!
43
+ end
44
+ end
45
+
46
+ puts '****************** Daemon Ready ******************'
47
+
48
+ EventPeople::Daemon.start
@@ -0,0 +1,56 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ ENV['RABBIT_URL'] = 'amqp://guest:guest@localhost:5672'
4
+ ENV['RABBIT_EVENT_PEOPLE_APP_NAME'] = 'EventPeopleExampleApp'
5
+ ENV['RABBIT_EVENT_PEOPLE_VHOST'] = 'event_people'
6
+ ENV['RABBIT_EVENT_PEOPLE_TOPIC_NAME'] = 'event_people'
7
+
8
+ $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
9
+
10
+ require 'rubygems'
11
+ require 'bundler'
12
+ Bundler.require(:default, 'development')
13
+
14
+ require_relative '../lib/event_people'
15
+
16
+ events = []
17
+
18
+ event_name = 'resource.custom.pay'
19
+ body = { amount: 1500, name: 'John' }
20
+
21
+ events.push(EventPeople::Event.new(event_name, body))
22
+
23
+ event_name = 'resource.custom.receive'
24
+ body = { amount: 35, name: 'Peter' }
25
+
26
+ events.push(EventPeople::Event.new(event_name, body))
27
+
28
+ event_name = 'resource.custom.receive'
29
+ body = { amount: 350, name: 'George' }
30
+
31
+ events.push(EventPeople::Event.new(event_name, body))
32
+
33
+ event_name = 'resource.custom.receive'
34
+ body = { amount: 550, name: 'James' }
35
+
36
+ events.push(EventPeople::Event.new(event_name, body))
37
+
38
+ event_name = 'resource.custom.private.service'
39
+ body = { message: 'Secret' }
40
+
41
+ events.push(EventPeople::Event.new(event_name, body))
42
+
43
+ event_name = 'resource.origin.action'
44
+ body = { bo: 'dy' }
45
+ schema_version = 4.2
46
+
47
+ event = EventPeople::Event.new(event_name, body, schema_version)
48
+
49
+ p 'Sending messsages.'
50
+
51
+ EventPeople::Emitter.trigger(event)
52
+ EventPeople::Emitter.trigger(events)
53
+
54
+ p 'Mesages sent!'
55
+
56
+ EventPeople::Config.broker.close_connection
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ ENV['RABBIT_URL'] = 'amqp://guest:guest@localhost:5672'
4
+ ENV['RABBIT_EVENT_PEOPLE_APP_NAME'] = 'EventPeopleExampleApp'
5
+ ENV['RABBIT_EVENT_PEOPLE_VHOST'] = 'event_people'
6
+ ENV['RABBIT_EVENT_PEOPLE_TOPIC_NAME'] = 'event_people'
7
+
8
+ $LOAD_PATH.unshift File.expand_path('../../lib', __dir__)
9
+
10
+ require 'rubygems'
11
+ require 'bundler'
12
+ Bundler.require(:default, 'development')
13
+
14
+ require_relative '../lib/event_people'
15
+
16
+ event_name = 'resource.origin.action'
17
+
18
+ puts 'Start receiving messages'
19
+
20
+ EventPeople::Listener.on(event_name) do |event|
21
+ puts ''
22
+ puts " - Received a message from #{event.name}:"
23
+ puts " Message: #{event.body}"
24
+ puts ''
25
+ end
26
+
27
+ puts 'Stop receiving messages'
28
+
29
+ EventPeople::Config.broker.close_connection
@@ -0,0 +1,37 @@
1
+ module EventPeople
2
+ module Broker
3
+ class Base
4
+ @@connection = nil
5
+
6
+ def self.consumers
7
+ @consumers ||= {}
8
+ end
9
+
10
+ def connection
11
+ raise NotImplementedError.new('Must be implemented')
12
+ end
13
+
14
+ def self.close_connection
15
+ raise NotImplementedError.new('Must be implemented')
16
+ end
17
+
18
+ def self.consume(event_name, &block)
19
+ consumers[event_name] ||= begin
20
+ new.consume(event_name, &block)
21
+ end
22
+ end
23
+
24
+ def consume(event_name, &block)
25
+ raise NotImplementedError.new('Must be implemented')
26
+ end
27
+
28
+ def self.produce(events)
29
+ new.produce(events)
30
+ end
31
+
32
+ def produce(events)
33
+ raise NotImplementedError.new('Must be implemented')
34
+ end
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,49 @@
1
+ module EventPeople
2
+ module Broker
3
+ class Rabbit::Queue
4
+ def initialize(channel)
5
+ @channel = channel
6
+ @channel.prefetch(1)
7
+ end
8
+
9
+ def self.subscribe(channel, routing_key, &block)
10
+ new(channel).subscribe(routing_key, &block)
11
+ end
12
+
13
+ def subscribe(routing_key, &block)
14
+ base_name = routing_key.split('.')[0..2].join('.')
15
+ name = queue_name("#{base_name}.all")
16
+
17
+ channel.queue(name, queue_options)
18
+ .bind(topic, routing_key: routing_key)
19
+ .subscribe(manual_ack: true) do |delivery_info, properties, payload|
20
+ callback(delivery_info, properties, payload, &block)
21
+ end
22
+ end
23
+
24
+ private
25
+
26
+ attr_reader :channel
27
+
28
+ def callback(delivery_info, properties, payload, &block)
29
+ event_name = delivery_info.routing_key
30
+
31
+ event = EventPeople::Event.new(event_name, payload)
32
+
33
+ block.call(event, channel, delivery_info)
34
+ end
35
+
36
+ def topic
37
+ Rabbit::Topic.topic(channel)
38
+ end
39
+
40
+ def queue_options
41
+ { durable: true }
42
+ end
43
+
44
+ def queue_name(routing_key)
45
+ "#{EventPeople::Config::APP_NAME.downcase}-#{routing_key.downcase}"
46
+ end
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,34 @@
1
+ module EventPeople
2
+ module Broker
3
+ class Rabbit::Topic
4
+ def initialize(channel)
5
+ @channel = channel
6
+ end
7
+
8
+ def self.topic(channel)
9
+ new(channel).topic
10
+ end
11
+
12
+ def topic
13
+ @topic ||= channel.topic(EventPeople::Config::TOPIC, topic_options)
14
+ end
15
+
16
+ def self.produce(channel, event)
17
+ new(channel).produce(event)
18
+ end
19
+
20
+ def produce(event)
21
+ topic.publish(event.payload, routing_key: event.name,
22
+ content_type: 'application/json')
23
+ end
24
+
25
+ private
26
+
27
+ attr_reader :channel
28
+
29
+ def topic_options
30
+ { passive: true }
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,41 @@
1
+ module EventPeople
2
+ module Broker
3
+ class Rabbit < Base
4
+ def connection
5
+ @@connection ||= session
6
+ end
7
+
8
+ def consume(event_name, &block)
9
+ Queue.subscribe(channel, event_name, &block)
10
+ end
11
+
12
+ def produce(events)
13
+ events.each do |event|
14
+ Topic.produce(channel, event)
15
+ end
16
+ end
17
+
18
+ def self.close_connection
19
+ @@connection.close
20
+ end
21
+
22
+ private
23
+
24
+ def channel
25
+ @@channel ||= connection.create_channel
26
+ @@channel = connection.create_channel if @@channel.closed?
27
+ @@channel
28
+ end
29
+
30
+ def session
31
+ Bunny.new(url).tap do |session|
32
+ session.start
33
+ end
34
+ end
35
+
36
+ def url
37
+ EventPeople::Config::FULL_URL
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,13 @@
1
+ module EventPeople
2
+ class Config
3
+ APP_NAME = ENV['RABBIT_EVENT_PEOPLE_APP_NAME']
4
+ TOPIC = ENV['RABBIT_EVENT_PEOPLE_TOPIC_NAME']
5
+ VHOST = ENV['RABBIT_EVENT_PEOPLE_VHOST']
6
+ URL = ENV['RABBIT_URL']
7
+ FULL_URL = "#{ENV['RABBIT_URL']}/#{ENV['RABBIT_EVENT_PEOPLE_VHOST']}"
8
+
9
+ def self.broker
10
+ EventPeople::Broker::Rabbit
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,34 @@
1
+ module EventPeople
2
+ class Daemon
3
+ INTERRUPTION_SIGNALS = %w(TERM INT)
4
+
5
+ def self.start
6
+ Listeners::Manager.bind_all_listeners
7
+
8
+ bind_signals
9
+ end
10
+
11
+ def self.stop
12
+ EventPeople::Config.broker.close_connection
13
+
14
+ exit
15
+ end
16
+
17
+ def self.bind_signals
18
+ read, write = IO.pipe
19
+
20
+ INTERRUPTION_SIGNALS.each do |signal|
21
+ Signal.trap(signal) { write.puts(signal) }
22
+ end
23
+
24
+ begin
25
+ while io = IO.select([read])
26
+ signal = io.first[0].gets.strip
27
+ raise Interrupt if INTERRUPTION_SIGNALS.include?(signal)
28
+ end
29
+ rescue Interrupt
30
+ stop
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,23 @@
1
+ require 'json'
2
+
3
+ module EventPeople
4
+ # Public: An class which decorates el-rabbit topic creation.
5
+ #
6
+ class Emitter
7
+ # Public: Produces a event on the Broker.
8
+ #
9
+ # event - The event to be produced.
10
+ #
11
+ # Returns the Event.
12
+ def self.trigger(*events)
13
+ events.flatten.each_with_index do |event, index|
14
+ raise(MissingAttributeError, "Event on position #{index} must have a body") unless event.body?
15
+ raise(MissingAttributeError, "Event on position #{index} must have a name") unless event.name?
16
+ end
17
+
18
+ EventPeople::Config.broker.produce(events.flatten)
19
+
20
+ events
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,56 @@
1
+ module EventPeople
2
+ class Event
3
+ attr_reader :name, :headers, :body, :schema_version
4
+
5
+ def initialize(name, body, schema_version = 1.0)
6
+ @name = name
7
+ @body = body.is_a?(String) ? JSON.parse(body) : body
8
+ @schema_version = @body&.dig('headers', 'schemaVersion') || schema_version
9
+
10
+ if name?
11
+ generate_headers
12
+ fix_name
13
+ end
14
+
15
+ build_payload if @body&.key?('headers')
16
+ end
17
+
18
+ def payload
19
+ { headers:, body: }.to_json
20
+ end
21
+
22
+ def body?
23
+ body && !body.empty?
24
+ end
25
+
26
+ def name?
27
+ name && !name.empty?
28
+ end
29
+
30
+ private
31
+
32
+ def build_payload
33
+ @headers = body['headers']
34
+ @body = body['body']
35
+ end
36
+
37
+ def generate_headers
38
+ header_spec = name&.split('.')
39
+
40
+ @headers = {
41
+ appName: EventPeople::Config::APP_NAME,
42
+ resource: header_spec[0],
43
+ origin: header_spec[1],
44
+ action: header_spec[2],
45
+ destiny: header_spec[3] || 'all',
46
+ schemaVersion: schema_version
47
+ }
48
+ end
49
+
50
+ def fix_name
51
+ return if name.split('.').size != 3
52
+
53
+ @name = "#{@name}.all"
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,23 @@
1
+ require 'bunny'
2
+
3
+ module EventPeople
4
+ class Listener
5
+ def self.on(event_name, &block)
6
+ new.on(event_name, &block)
7
+ end
8
+
9
+ def on(event_name, &block)
10
+ raise(MissingAttributeError, 'Event name must be present') unless event_name&.size&.positive?
11
+
12
+ event_name = consumed_event_name(event_name)
13
+
14
+ EventPeople::Config.broker.consume(event_name, &block)
15
+ end
16
+
17
+ private
18
+
19
+ def consumed_event_name(event_name)
20
+ event_name.split('.').size == 3 ? "#{event_name}.all" : event_name
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,60 @@
1
+ module EventPeople
2
+ module Listeners
3
+ class Base
4
+ attr_reader :channel, :delivery_info
5
+
6
+ def initialize(channel, delivery_info)
7
+ @channel = channel
8
+ @delivery_info = delivery_info
9
+ end
10
+
11
+ def callback(method_name, event)
12
+ send method_name, event
13
+ end
14
+
15
+ def success!
16
+ channel.ack(delivery_info.delivery_tag, false)
17
+ end
18
+
19
+ def fail!
20
+ channel.nack(delivery_info.delivery_tag, false, true)
21
+ end
22
+
23
+ def reject!
24
+ channel.reject(delivery_info.delivery_tag, false)
25
+ end
26
+
27
+ def self.bind(method, event_name)
28
+ app_name = ENV['RABBIT_EVENT_PEOPLE_APP_NAME'].downcase
29
+
30
+ Manager.register_listener_configuration(
31
+ {
32
+ listener_class: self,
33
+ method:,
34
+ routing_key: fixed_event_name(event_name, 'all')
35
+ }
36
+ )
37
+ Manager.register_listener_configuration(
38
+ {
39
+ listener_class: self,
40
+ method:,
41
+ routing_key: fixed_event_name(event_name, app_name)
42
+ }
43
+ )
44
+ end
45
+
46
+ def self.fixed_event_name(event_name, postfix)
47
+ case event_name&.split('.')&.size
48
+ when 4
49
+ parts = event_name.split('.')
50
+
51
+ "#{parts[0..2].join('.')}.#{postfix}"
52
+ when nil
53
+ event_name
54
+ else
55
+ "#{event_name}.#{postfix}"
56
+ end
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,26 @@
1
+ # Module responsible for managing all listeners
2
+ module EventPeople
3
+ module Listeners
4
+ module Manager
5
+ class << self
6
+ def bind_all_listeners
7
+ listener_configurations.each do |config|
8
+ EventPeople::Listener.on(config[:routing_key]) do |event, channel, delivery_info|
9
+ config[:listener_class].new(channel, delivery_info).callback(config[:method], event)
10
+ end
11
+ end
12
+ end
13
+
14
+ def register_listener_configuration(configuration)
15
+ listener_configurations.push(configuration)
16
+ end
17
+
18
+ private
19
+
20
+ def listener_configurations
21
+ @listener_configurations ||= []
22
+ end
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,3 @@
1
+ module EventPeople
2
+ VERSION = '1.0.1'
3
+ end
@@ -0,0 +1,16 @@
1
+ require 'event_people/version'
2
+ require 'event_people/daemon'
3
+ require 'event_people/event'
4
+ require 'event_people/config'
5
+ require 'event_people/emitter'
6
+ require 'event_people/listener'
7
+ require 'event_people/listeners/base'
8
+ require 'event_people/listeners/manager'
9
+ require 'event_people/broker/base'
10
+ require 'event_people/broker/rabbit'
11
+ require 'event_people/broker/rabbit/queue'
12
+ require 'event_people/broker/rabbit/topic'
13
+
14
+ module EventPeople
15
+ class MissingAttributeError < StandardError; end
16
+ end
metadata ADDED
@@ -0,0 +1,141 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: event_people
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Pin People
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2022-08-13 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: '0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: pry-meta
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rspec
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '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.7'
76
+ type: :runtime
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '2.7'
83
+ description: Tool to produce and consume events to a distributed and async architecture
84
+ email:
85
+ - contato@pinpeople.com.br
86
+ executables: []
87
+ extensions: []
88
+ extra_rdoc_files: []
89
+ files:
90
+ - ".circleci/config.yml"
91
+ - ".env.example"
92
+ - ".gitignore"
93
+ - ".rspec"
94
+ - ".ruby-version"
95
+ - Gemfile
96
+ - Gemfile.lock
97
+ - LICENSE.txt
98
+ - README.md
99
+ - Rakefile
100
+ - event_people.gemspec
101
+ - examples/daemon.rb
102
+ - examples/emitter.rb
103
+ - examples/listener.rb
104
+ - lib/event_people.rb
105
+ - lib/event_people/broker/base.rb
106
+ - lib/event_people/broker/rabbit.rb
107
+ - lib/event_people/broker/rabbit/queue.rb
108
+ - lib/event_people/broker/rabbit/topic.rb
109
+ - lib/event_people/config.rb
110
+ - lib/event_people/daemon.rb
111
+ - lib/event_people/emitter.rb
112
+ - lib/event_people/event.rb
113
+ - lib/event_people/listener.rb
114
+ - lib/event_people/listeners/base.rb
115
+ - lib/event_people/listeners/manager.rb
116
+ - lib/event_people/version.rb
117
+ homepage: https://github.com/pin-people/event_people_ruby
118
+ licenses:
119
+ - GNU LESSER GENERAL PUBLIC LICENSE V3
120
+ metadata:
121
+ allowed_push_host: https://rubygems.org
122
+ post_install_message:
123
+ rdoc_options: []
124
+ require_paths:
125
+ - lib
126
+ required_ruby_version: !ruby/object:Gem::Requirement
127
+ requirements:
128
+ - - ">="
129
+ - !ruby/object:Gem::Version
130
+ version: '0'
131
+ required_rubygems_version: !ruby/object:Gem::Requirement
132
+ requirements:
133
+ - - ">="
134
+ - !ruby/object:Gem::Version
135
+ version: '0'
136
+ requirements: []
137
+ rubygems_version: 3.3.7
138
+ signing_key:
139
+ specification_version: 4
140
+ summary: Expose an api to produce and consume events.
141
+ test_files: []