event_router 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. checksums.yaml +7 -0
  2. data/.github/workflows/quality.yaml +16 -0
  3. data/.github/workflows/specs.yaml +23 -0
  4. data/.gitignore +14 -0
  5. data/.rspec +3 -0
  6. data/.rubocop.yml +16 -0
  7. data/.ruby-gemset +1 -0
  8. data/.ruby-version +1 -0
  9. data/CODE_OF_CONDUCT.md +74 -0
  10. data/Gemfile +6 -0
  11. data/Gemfile.lock +89 -0
  12. data/LICENSE.txt +21 -0
  13. data/README.md +113 -0
  14. data/Rakefile +8 -0
  15. data/bin/console +11 -0
  16. data/bin/setup +8 -0
  17. data/event_router.gemspec +38 -0
  18. data/examples/common.rb +6 -0
  19. data/examples/event_store/order_placed.rb +15 -0
  20. data/examples/notifications.rb +22 -0
  21. data/examples/order_placed.rb +21 -0
  22. data/examples/payment_received.rb +8 -0
  23. data/examples/sidekiq/config.yml +3 -0
  24. data/examples/sidekiq/run_console.rb +15 -0
  25. data/examples/sidekiq/run_server.rb +11 -0
  26. data/examples/sync/run_console.rb +9 -0
  27. data/lib/event_router.rb +35 -0
  28. data/lib/event_router/configuration.rb +71 -0
  29. data/lib/event_router/delivery_adapters/base.rb +27 -0
  30. data/lib/event_router/delivery_adapters/jobs/sidekiq_event_delivery_job.rb +29 -0
  31. data/lib/event_router/delivery_adapters/sidekiq.rb +36 -0
  32. data/lib/event_router/delivery_adapters/sync.rb +15 -0
  33. data/lib/event_router/destination.rb +48 -0
  34. data/lib/event_router/error.rb +5 -0
  35. data/lib/event_router/errors/required_option_error.rb +20 -0
  36. data/lib/event_router/errors/unsupported_option_error.rb +22 -0
  37. data/lib/event_router/event.rb +53 -0
  38. data/lib/event_router/publisher.rb +24 -0
  39. data/lib/event_router/serializer.rb +26 -0
  40. data/lib/event_router/serializers/base.rb +17 -0
  41. data/lib/event_router/serializers/json.rb +38 -0
  42. data/lib/event_router/serializers/oj.rb +19 -0
  43. data/lib/event_router/version.rb +5 -0
  44. metadata +186 -0
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 50b25ed1a6cbef8f2dc0b4b571d76118e987ed9b123de3f1a759e4393b7e801b
4
+ data.tar.gz: 8d2c80e151358fa7fe58a2eff3f0250f2f795eeda327c4248ca554452be5ff24
5
+ SHA512:
6
+ metadata.gz: 713cc074634b7af45b462e4f8f31bb8ea4515aaa3485fb70a7b04bd83fad6136d9924b2a5c33e641c615c10d51c8497d9cb91a1f27a8ea1b1e64de5d22d57112
7
+ data.tar.gz: cff521d40abfc0260d5e64e42e2bf7274919e84b0c80e2dcb49edd25e4a42b526099742de7973cf3fbc152b4c548cfe969aacab1dcb952aeda5bd35c9efeb016
@@ -0,0 +1,16 @@
1
+ name: Quality
2
+ on: push
3
+
4
+ jobs:
5
+ rubocop:
6
+ runs-on: ubuntu-latest
7
+
8
+ steps:
9
+ - uses: actions/checkout@v2
10
+
11
+ - uses: ruby/setup-ruby@v1
12
+ with:
13
+ bundler-cache: true
14
+
15
+ - run: bundle
16
+ - run: bundle exec rubocop
@@ -0,0 +1,23 @@
1
+ name: Specs
2
+ on: push
3
+
4
+ jobs:
5
+ specs:
6
+ runs-on: ${{ matrix.os }}-latest
7
+ strategy:
8
+ fail-fast: false
9
+ matrix:
10
+ os: [ubuntu, macos]
11
+ ruby: [2.5, 2.6, 2.7]
12
+
13
+ steps:
14
+ - uses: actions/checkout@v2
15
+
16
+ - uses: ruby/setup-ruby@v1
17
+ with:
18
+ ruby-version: ${{ matrix.ruby }}
19
+ bundler-cache: true
20
+
21
+ - run: bundle
22
+ - run: bundle exec rspec
23
+
@@ -0,0 +1,14 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
12
+
13
+ # Debug
14
+ .byebug_history
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,16 @@
1
+ AllCops:
2
+ NewCops: enable
3
+
4
+ Style/FrozenStringLiteralComment:
5
+ Exclude:
6
+ - spec/**/*
7
+ - bin/**/*
8
+
9
+ Metrics/BlockLength:
10
+ Exclude:
11
+ - spec/**/*
12
+
13
+ # [TODO] Turn on documentation rule
14
+ Style/Documentation:
15
+ Enabled: false
16
+
@@ -0,0 +1 @@
1
+ event_router
@@ -0,0 +1 @@
1
+ ruby-2.7.1
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at ahmad.elassuty@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [https://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: https://contributor-covenant.org
74
+ [version]: https://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ # Specify your gem's dependencies in event_router.gemspec
6
+ gemspec
@@ -0,0 +1,89 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ event_router (0.1.0)
5
+ activesupport
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ activesupport (6.0.3.2)
11
+ concurrent-ruby (~> 1.0, >= 1.0.2)
12
+ i18n (>= 0.7, < 2)
13
+ minitest (~> 5.1)
14
+ tzinfo (~> 1.1)
15
+ zeitwerk (~> 2.2, >= 2.2.2)
16
+ ast (2.4.1)
17
+ byebug (11.1.3)
18
+ coderay (1.1.3)
19
+ concurrent-ruby (1.1.7)
20
+ connection_pool (2.2.3)
21
+ diff-lcs (1.3)
22
+ i18n (1.8.5)
23
+ concurrent-ruby (~> 1.0)
24
+ method_source (1.0.0)
25
+ minitest (5.14.1)
26
+ oj (3.10.14)
27
+ parallel (1.19.2)
28
+ parser (2.7.1.4)
29
+ ast (~> 2.4.1)
30
+ pry (0.13.1)
31
+ coderay (~> 1.1)
32
+ method_source (~> 1.0)
33
+ pry-byebug (3.9.0)
34
+ byebug (~> 11.0)
35
+ pry (~> 0.13.0)
36
+ rack (2.2.3)
37
+ rainbow (3.0.0)
38
+ redis (4.2.1)
39
+ regexp_parser (1.7.1)
40
+ rexml (3.2.4)
41
+ rspec (3.9.0)
42
+ rspec-core (~> 3.9.0)
43
+ rspec-expectations (~> 3.9.0)
44
+ rspec-mocks (~> 3.9.0)
45
+ rspec-core (3.9.0)
46
+ rspec-support (~> 3.9.0)
47
+ rspec-expectations (3.9.0)
48
+ diff-lcs (>= 1.2.0, < 2.0)
49
+ rspec-support (~> 3.9.0)
50
+ rspec-mocks (3.9.0)
51
+ diff-lcs (>= 1.2.0, < 2.0)
52
+ rspec-support (~> 3.9.0)
53
+ rspec-support (3.9.1)
54
+ rubocop (0.89.1)
55
+ parallel (~> 1.10)
56
+ parser (>= 2.7.1.1)
57
+ rainbow (>= 2.2.2, < 4.0)
58
+ regexp_parser (>= 1.7)
59
+ rexml
60
+ rubocop-ast (>= 0.3.0, < 1.0)
61
+ ruby-progressbar (~> 1.7)
62
+ unicode-display_width (>= 1.4.0, < 2.0)
63
+ rubocop-ast (0.3.0)
64
+ parser (>= 2.7.1.4)
65
+ ruby-progressbar (1.10.1)
66
+ sidekiq (6.1.1)
67
+ connection_pool (>= 2.2.2)
68
+ rack (~> 2.0)
69
+ redis (>= 4.2.0)
70
+ thread_safe (0.3.6)
71
+ tzinfo (1.2.7)
72
+ thread_safe (~> 0.1)
73
+ unicode-display_width (1.7.0)
74
+ zeitwerk (2.4.0)
75
+
76
+ PLATFORMS
77
+ ruby
78
+
79
+ DEPENDENCIES
80
+ event_router!
81
+ oj
82
+ pry
83
+ pry-byebug
84
+ rspec (~> 3.0)
85
+ rubocop
86
+ sidekiq
87
+
88
+ BUNDLED WITH
89
+ 2.1.4
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020 Ahmad Elassuty
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.
@@ -0,0 +1,113 @@
1
+ # EventRouter
2
+
3
+ ![Specs](https://github.com/ahmad-elassuty/event_router/workflows/Specs/badge.svg)
4
+
5
+ One domain event can have multiple side-effects in your system, for example sending emails, creating notifications, tasks, audit logs, event store, updating other system resources async and many more.
6
+
7
+ EventRouter helps you organise your application domain events side-effects in a simple and intuitive way. No more bloated workers that does many actions, which violates Single responsiblity principle.
8
+
9
+ ## Installation
10
+
11
+ Add this line to your application's Gemfile:
12
+
13
+ ```ruby
14
+ gem 'event_router'
15
+ ```
16
+
17
+ And then execute:
18
+
19
+ $ bundle install
20
+
21
+ Or install it yourself as:
22
+
23
+ $ gem install event_router
24
+
25
+ EventRouter is already pre-configured with some defaults. Please check the wikis for more info on how to update the configurations.
26
+
27
+ ## Usage
28
+
29
+ ### Event
30
+
31
+ It is very easy to create a new domain event and deliver it to multiple destinations.
32
+
33
+ - Create your new domain event and define the destination:
34
+
35
+ ```ruby
36
+ class OrderPlaced < EventRouter::Event
37
+ deliver_to :email_notifier, handler: EmailNotifier
38
+ end
39
+ ```
40
+
41
+ - Create your handler:
42
+
43
+ ```ruby
44
+ class EmailNotifier
45
+ def self.order_placed(event, payload)
46
+ # [TODO] Handle the event here
47
+ end
48
+ end
49
+ ```
50
+
51
+ - Publish your event:
52
+
53
+ ```ruby
54
+ OrderPlaced.publish(order_id: 1, time: Time.now)
55
+ ```
56
+
57
+ And your are done! 🎉
58
+
59
+ ### Destinations
60
+
61
+ A single event can define multiple destinations, and each destination can have different set of options.
62
+
63
+ ```ruby
64
+ class OrderPlaced < EventRouter::Event
65
+ deliver_to :email_notifier, handler: EmailNotifier
66
+ deliver_to :event_store, handler: EventStore, handler_method: :custom_method
67
+ end
68
+ ```
69
+
70
+ For the full list of options, please check the wikis 📚.
71
+
72
+ ### Delivery Adapters
73
+
74
+ You can configure how your events are delivered to their destinations. EventRouter currently supports two different delivery adapters:
75
+
76
+ - Sync
77
+ - Sidekiq
78
+
79
+ The `sync` adapter is the default delivery adapter and does not require any dependencies. To asynchronously process your event, please use other backends, e.g Sidekiq.
80
+
81
+ To setup other adapters, please check the wikis 📚.
82
+
83
+ ### Serializers
84
+
85
+ Similarly, you can configure how events are serialized before they are handed to the delivery adapter. This is mainly to provide flexibility on how events are stored in the delivery backend and maintain the objects structure.
86
+
87
+ - Json
88
+ - Oj
89
+
90
+ The `json` adapter is the default serializer adapter and does not require any dependencies.
91
+
92
+ To setup other adapters, please check the wikis 📚.
93
+
94
+
95
+ ## Development
96
+
97
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
98
+
99
+ 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).
100
+
101
+ ## Contributing
102
+
103
+ Bug reports and pull requests are welcome on GitHub at https://github.com/ahmad-elassuty/event_router. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/ahmad-elassuty/event_router/blob/master/CODE_OF_CONDUCT.md).
104
+
105
+ Special thanks to [Ivan](https://github.com/idanci) for doing code review 🔍
106
+
107
+ ## License
108
+
109
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
110
+
111
+ ## Code of Conduct
112
+
113
+ Everyone interacting in the EventRouter project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/ahmad-elassuty/event_router/blob/master/CODE_OF_CONDUCT.md).
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'bundler/setup'
4
+ require 'event_router'
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
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/event_router/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'event_router'
7
+ spec.version = EventRouter::VERSION
8
+ spec.authors = ['Ahmad Elassuty']
9
+ spec.email = ['ahmad.elassuty@gmail.com']
10
+
11
+ spec.summary = 'Organise your application domain events side-effects in a simple and intuitive way.'
12
+ spec.homepage = 'https://github.com/ahmad-elassuty/event_router'
13
+ spec.license = 'MIT'
14
+ spec.required_ruby_version = Gem::Requirement.new('>= 2.5.0')
15
+
16
+ spec.metadata['homepage_uri'] = spec.homepage
17
+ spec.metadata['source_code_uri'] = spec.homepage
18
+
19
+ # Specify which files should be added to the gem when it is released.
20
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
21
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
22
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
23
+ end
24
+ spec.bindir = 'exe'
25
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
26
+ spec.require_paths = ['lib']
27
+
28
+ # Dependencies
29
+ spec.add_dependency 'activesupport'
30
+
31
+ # Development dependencies
32
+ spec.add_development_dependency 'oj'
33
+ spec.add_development_dependency 'pry'
34
+ spec.add_development_dependency 'pry-byebug'
35
+ spec.add_development_dependency 'rspec', '~> 3.0'
36
+ spec.add_development_dependency 'rubocop'
37
+ spec.add_development_dependency 'sidekiq'
38
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'event_store/order_placed'
4
+ require_relative 'notifications'
5
+ require_relative 'payment_received'
6
+ require_relative 'order_placed'
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Examples
4
+ module EventStore
5
+ class OrderPlaced
6
+ def self.handle(event:, payload:)
7
+ puts "#{'=' * 10} [EventStore] #{'=' * 10}"
8
+ puts 'Received order_placed'
9
+ puts event.inspect
10
+ puts payload.inspect
11
+ puts '=' * 32
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Examples
4
+ module Notifications
5
+ module_function
6
+
7
+ def order_placed(event:, payload:)
8
+ puts "#{'=' * 10} [Notifications] #{'=' * 10}"
9
+ puts 'Received order_placed'
10
+ puts event.inspect
11
+ puts payload.inspect
12
+ puts '=' * 35
13
+ end
14
+
15
+ def payment_received(event:, **_payload)
16
+ puts "#{'=' * 10} [Notifications] #{'=' * 10}"
17
+ puts 'Received payment_received'
18
+ puts event.inspect
19
+ puts '=' * 35
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Examples
4
+ class OrderPlaced < EventRouter::Event
5
+ deliver_to :notifications,
6
+ handler: Examples::Notifications
7
+
8
+ deliver_to :event_store,
9
+ handler: Examples::EventStore::OrderPlaced,
10
+ handler_method: :handle,
11
+ prefetch_payload: true,
12
+ payload_method: :store_payload
13
+
14
+ # Extra payload
15
+ def store_payload
16
+ {
17
+ id: SecureRandom.uuid
18
+ }
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Examples
4
+ class PaymentReceived < EventRouter::Event
5
+ deliver_to :notifications,
6
+ handler: Examples::Notifications
7
+ end
8
+ end
@@ -0,0 +1,3 @@
1
+ :concurrency: 1
2
+ :queues:
3
+ - [event_router, 1]
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/setup'
4
+ require 'event_router'
5
+ require 'pry'
6
+
7
+ require_relative '../common'
8
+
9
+ EventRouter.configure do |config|
10
+ config.register_delivery_adapter :sidekiq, queue: :event_router, retry: 5
11
+
12
+ config.delivery_adapter = :sidekiq
13
+ end
14
+
15
+ Pry.start
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'event_router'
4
+
5
+ require_relative '../common'
6
+
7
+ EventRouter.configure do |config|
8
+ config.register_delivery_adapter :sidekiq, queue: :event_router, retry: 5
9
+
10
+ config.delivery_adapter = :sidekiq
11
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/setup'
4
+ require 'event_router'
5
+
6
+ require_relative '../common'
7
+
8
+ require 'pry'
9
+ Pry.start
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'event_router/version'
4
+ require 'event_router/error'
5
+
6
+ require 'event_router/event'
7
+ require 'event_router/delivery_adapters/base'
8
+ require 'event_router/serializers/base'
9
+ require 'event_router/publisher'
10
+ require 'event_router/serializer'
11
+ require 'event_router/configuration'
12
+
13
+ module EventRouter
14
+ module_function
15
+
16
+ def publish(events, adapter: EventRouter.configuration.delivery_adapter)
17
+ EventRouter::Publisher.publish(events, adapter: adapter)
18
+ end
19
+
20
+ def serialize(event, adapter: EventRouter.configuration.serializer_adapter)
21
+ EventRouter::Serializer.serialize(event, adapter: adapter)
22
+ end
23
+
24
+ def deserialize(payload, adapter: EventRouter.configuration.serializer_adapter)
25
+ EventRouter::Serializer.deserialize(payload, adapter: adapter)
26
+ end
27
+
28
+ def configuration
29
+ @configuration ||= Configuration.new
30
+ end
31
+
32
+ def configure
33
+ yield configuration if block_given?
34
+ end
35
+ end
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'errors/unsupported_option_error'
4
+
5
+ module EventRouter
6
+ class Configuration
7
+ attr_reader :delivery_adapter, :delivery_adapters,
8
+ :serializer_adapter, :serializer_adapters
9
+
10
+ def initialize
11
+ @delivery_adapters = {}
12
+ @serializer_adapters = {}
13
+
14
+ register_delivery_adapter(:sync)
15
+ @delivery_adapter = :sync
16
+
17
+ register_serializer_adapter(:json)
18
+ @serializer_adapter = :json
19
+ end
20
+
21
+ def delivery_adapter=(adapter, _opts = {})
22
+ validate_inclusion!(:delivery_adapter, adapter, @delivery_adapters)
23
+
24
+ @delivery_adapter = adapter
25
+ end
26
+
27
+ def delivery_adapter_class(adapter)
28
+ @delivery_adapters[adapter]
29
+ end
30
+
31
+ def register_delivery_adapter(adapter, opts = {})
32
+ adapter_class = load_adapter_class(Publisher::ADAPTERS, adapter) || opts[:adapter_class]
33
+
34
+ adapter_class.options = opts
35
+ @delivery_adapters[adapter] = adapter_class
36
+ end
37
+
38
+ def serializer_adapter=(adapter)
39
+ validate_inclusion!(:serializer_adapter, adapter, @serializer_adapters)
40
+
41
+ @serializer_adapter = adapter
42
+ end
43
+
44
+ def serializer_adapter_class(adapter)
45
+ @serializer_adapters[adapter]
46
+ end
47
+
48
+ def register_serializer_adapter(adapter, opts = {})
49
+ adapter_class = load_adapter_class(Serializer::ADAPTERS, adapter) || opts[:adapter_class]
50
+
51
+ @serializer_adapters[adapter] = adapter_class
52
+ end
53
+
54
+ private
55
+
56
+ def load_adapter_class(adapters, adapter)
57
+ return nil unless adapters.key?(adapter)
58
+
59
+ require_relative adapters[adapter][:path]
60
+ Kernel.const_get(adapters[adapter][:adapter_class])
61
+ end
62
+
63
+ def validate_inclusion!(config, option, supported_options)
64
+ return if supported_options.include?(option)
65
+
66
+ raise Errors::UnsupportedOptionError.new(
67
+ config: config, option: option, supported_options: supported_options.keys
68
+ )
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../errors/required_option_error'
4
+
5
+ module EventRouter
6
+ module DeliveryAdapters
7
+ class Base
8
+ class << self
9
+ attr_reader :options
10
+
11
+ def options=(options)
12
+ validate_options!(options)
13
+
14
+ @options = options
15
+ end
16
+
17
+ def validate_options!(_options)
18
+ true
19
+ end
20
+
21
+ def deliver(_event)
22
+ raise NotImplementedError, "deliver method is not implemented for #{name}"
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../../serializer'
4
+ require 'sidekiq'
5
+
6
+ module EventRouter
7
+ module DeliveryAdapters
8
+ module Jobs
9
+ class SidekiqEventDeliveryJob
10
+ include ::Sidekiq::Worker
11
+
12
+ def perform(destination_name, serialized_event, serialized_payload)
13
+ event = EventRouter.deserialize(serialized_event)
14
+ destination = event.destinations[destination_name.to_sym]
15
+
16
+ return unless destination
17
+
18
+ payload = if destination.prefetch_payload?
19
+ EventRouter.deserialize(serialized_payload)
20
+ else
21
+ destination.extra_payload(event)
22
+ end
23
+
24
+ destination.process(event, payload)
25
+ end
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'jobs/sidekiq_event_delivery_job'
4
+
5
+ module EventRouter
6
+ module DeliveryAdapters
7
+ class Sidekiq < Base
8
+ REQUIRED_OPTIONS = %i[queue retry].freeze
9
+
10
+ class << self
11
+ def validate_options!(options)
12
+ missing_options = REQUIRED_OPTIONS - options.compact.keys
13
+
14
+ return true if missing_options.empty?
15
+
16
+ raise Errors::RequiredOptionError.new(options: missing_options, adapter: self)
17
+ end
18
+
19
+ def deliver(event)
20
+ serialized_event = EventRouter.serialize(event)
21
+
22
+ event.destinations.each do |name, destination|
23
+ if destination.prefetch_payload?
24
+ payload = destination.extra_payload(event)
25
+ serialized_payload = EventRouter.serialize(payload)
26
+ end
27
+
28
+ Jobs::SidekiqEventDeliveryJob
29
+ .set(queue: options[:queue], retry: options[:retry])
30
+ .perform_async(name, serialized_event, serialized_payload)
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module EventRouter
4
+ module DeliveryAdapters
5
+ class Sync < Base
6
+ def self.deliver(event)
7
+ event.destinations.each do |_name, destination|
8
+ payload = destination.extra_payload(event)
9
+
10
+ destination.process(event, payload)
11
+ end
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module EventRouter
4
+ class Destination
5
+ # Attributes
6
+ attr_reader :name, :handler, :handler_method,
7
+ :prefetch_payload, :payload_method
8
+
9
+ # Constants
10
+ DEFAULT_ATTRIBUTES = {
11
+ # Defaults to the event name, e.g "order_placed"
12
+ handler_method: nil,
13
+ # Defaults to not fetch before scheduling the job.
14
+ prefetch_payload: false,
15
+ # Defaults to destination name, e.g "#{name}_payload"
16
+ payload_method: nil
17
+ }.freeze
18
+
19
+ # Methods
20
+ def initialize(name, handler:, **opts)
21
+ opts = DEFAULT_ATTRIBUTES.merge(opts)
22
+
23
+ @name = name
24
+ @handler = handler
25
+ @handler_method = opts[:handler_method]
26
+ @prefetch_payload = opts[:prefetch_payload]
27
+ @payload_method = opts[:payload_method] || "#{name}_payload"
28
+ end
29
+
30
+ def process(event, payload)
31
+ handler.send(
32
+ handler_method || event.name,
33
+ event: event,
34
+ payload: payload
35
+ )
36
+ end
37
+
38
+ def prefetch_payload?
39
+ @prefetch_payload
40
+ end
41
+
42
+ def extra_payload(event)
43
+ return nil unless event.respond_to?(payload_method)
44
+
45
+ event.send(payload_method)
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module EventRouter
4
+ class Error < StandardError; end
5
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../error'
4
+
5
+ module EventRouter
6
+ module Errors
7
+ class RequiredOptionError < Error
8
+ def initialize(message: nil, options:, adapter:)
9
+ @options = options
10
+ @adapter = adapter
11
+
12
+ super(message || self.message)
13
+ end
14
+
15
+ def message
16
+ "#{@options} are required for #{@adapter} adapter."
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../error'
4
+
5
+ module EventRouter
6
+ module Errors
7
+ class UnsupportedOptionError < Error
8
+ def initialize(message: nil, config:, option:, supported_options:)
9
+ @config = config
10
+ @option = option
11
+ @supported_options = supported_options
12
+
13
+ super(message || self.message)
14
+ end
15
+
16
+ def message
17
+ "Unsupported #{@option} for #{@config} configuration. Currently supports #{@supported_options}. " \
18
+ 'Please consider registering the adapter before referencing it.'
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'securerandom'
4
+ require 'active_support/core_ext/class/attribute'
5
+ require 'active_support/core_ext/string/inflections'
6
+
7
+ require_relative 'destination'
8
+
9
+ module EventRouter
10
+ class Event
11
+ attr_reader :uid, :created_at, :payload
12
+ attr_accessor :correlation_id
13
+
14
+ class_attribute :destinations, default: {}, instance_writer: false
15
+
16
+ def initialize(uid: SecureRandom.uuid, correlation_id: SecureRandom.uuid, created_at: Time.now, **payload)
17
+ @uid = uid
18
+ @correlation_id = correlation_id
19
+ @created_at = created_at
20
+ @payload = payload
21
+ end
22
+
23
+ def to_hash
24
+ {
25
+ uid: uid,
26
+ correlation_id: correlation_id,
27
+ payload: payload,
28
+ created_at: created_at
29
+ }
30
+ end
31
+
32
+ alias to_h to_hash
33
+
34
+ def name
35
+ self.class.name.demodulize.underscore
36
+ end
37
+
38
+ class << self
39
+ def inherited(base)
40
+ base.destinations = destinations.dup
41
+ super
42
+ end
43
+
44
+ def deliver_to(name, opts = {})
45
+ destinations[name] = EventRouter::Destination.new(name, **opts)
46
+ end
47
+
48
+ def publish(**attrs)
49
+ EventRouter.publish(new(**attrs))
50
+ end
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module EventRouter
4
+ module Publisher
5
+ module_function
6
+
7
+ ADAPTERS = {
8
+ sync: { adapter_class: 'EventRouter::DeliveryAdapters::Sync', path: 'delivery_adapters/sync' },
9
+ sidekiq: { adapter_class: 'EventRouter::DeliveryAdapters::Sidekiq', path: 'delivery_adapters/sidekiq' }
10
+ }.freeze
11
+
12
+ def publish(events, adapter:)
13
+ adapter_class = delivery_adapter(adapter)
14
+
15
+ Array(events).each { |event| adapter_class.deliver(event) }
16
+ end
17
+
18
+ def delivery_adapter(adapter)
19
+ EventRouter.configuration.delivery_adapter_class(adapter)
20
+ end
21
+
22
+ private_class_method :delivery_adapter
23
+ end
24
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module EventRouter
4
+ module Serializer
5
+ module_function
6
+
7
+ ADAPTERS = {
8
+ json: { adapter_class: 'EventRouter::Serializers::Json', path: 'serializers/json' },
9
+ oj: { adapter_class: 'EventRouter::Serializers::Oj', path: 'serializers/oj' }
10
+ }.freeze
11
+
12
+ def serialize(payload, adapter:)
13
+ serializer_adapter(adapter).serialize(payload)
14
+ end
15
+
16
+ def deserialize(payload, adapter:)
17
+ serializer_adapter(adapter).deserialize(payload)
18
+ end
19
+
20
+ def serializer_adapter(adapter)
21
+ EventRouter.configuration.serializer_adapter_class(adapter)
22
+ end
23
+
24
+ private_class_method :serializer_adapter
25
+ end
26
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module EventRouter
4
+ module Serializers
5
+ class Base
6
+ class << self
7
+ def serialize(_object)
8
+ raise NotImplementedError, 'Sub-classes must implement serialize method.'
9
+ end
10
+
11
+ def deserialize(_string)
12
+ raise NotImplementedError, 'Sub-classes must implement serialize method.'
13
+ end
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+
5
+ module EventRouter
6
+ module Serializers
7
+ class Json < Base
8
+ EVENT_CLASS_ATTRIBUTE_NAME = 'er_class'
9
+
10
+ class << self
11
+ def serialize(object)
12
+ return JSON.generate(object) unless object.is_a?(EventRouter::Event)
13
+
14
+ attributes = object.to_h
15
+ attributes[EVENT_CLASS_ATTRIBUTE_NAME] = object.class.name
16
+
17
+ JSON.generate(attributes)
18
+ end
19
+
20
+ def deserialize(payload)
21
+ object = JSON.parse(payload)
22
+
23
+ return object unless object.is_a?(Hash)
24
+ return object unless object.key?(EVENT_CLASS_ATTRIBUTE_NAME)
25
+
26
+ event_class = object.delete(EVENT_CLASS_ATTRIBUTE_NAME)
27
+ event_instance = const_get(event_class).new
28
+
29
+ object.each do |attribute, value|
30
+ event_instance.instance_variable_set(:"@#{attribute}", value)
31
+ end
32
+
33
+ event_instance
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'oj'
4
+
5
+ module EventRouter
6
+ module Serializers
7
+ class Oj < Base
8
+ class << self
9
+ def serialize(object)
10
+ ::Oj.dump(object, mode: :object)
11
+ end
12
+
13
+ def deserialize(string)
14
+ ::Oj.load(string, mode: :object)
15
+ end
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module EventRouter
4
+ VERSION = '0.1.0'
5
+ end
metadata ADDED
@@ -0,0 +1,186 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: event_router
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Ahmad Elassuty
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-01-23 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
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: oj
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: pry
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: pry-byebug
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: rspec
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rubocop
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: sidekiq
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: '0'
111
+ description:
112
+ email:
113
+ - ahmad.elassuty@gmail.com
114
+ executables: []
115
+ extensions: []
116
+ extra_rdoc_files: []
117
+ files:
118
+ - ".github/workflows/quality.yaml"
119
+ - ".github/workflows/specs.yaml"
120
+ - ".gitignore"
121
+ - ".rspec"
122
+ - ".rubocop.yml"
123
+ - ".ruby-gemset"
124
+ - ".ruby-version"
125
+ - CODE_OF_CONDUCT.md
126
+ - Gemfile
127
+ - Gemfile.lock
128
+ - LICENSE.txt
129
+ - README.md
130
+ - Rakefile
131
+ - bin/console
132
+ - bin/setup
133
+ - event_router.gemspec
134
+ - examples/common.rb
135
+ - examples/event_store/order_placed.rb
136
+ - examples/notifications.rb
137
+ - examples/order_placed.rb
138
+ - examples/payment_received.rb
139
+ - examples/sidekiq/config.yml
140
+ - examples/sidekiq/run_console.rb
141
+ - examples/sidekiq/run_server.rb
142
+ - examples/sync/run_console.rb
143
+ - lib/event_router.rb
144
+ - lib/event_router/configuration.rb
145
+ - lib/event_router/delivery_adapters/base.rb
146
+ - lib/event_router/delivery_adapters/jobs/sidekiq_event_delivery_job.rb
147
+ - lib/event_router/delivery_adapters/sidekiq.rb
148
+ - lib/event_router/delivery_adapters/sync.rb
149
+ - lib/event_router/destination.rb
150
+ - lib/event_router/error.rb
151
+ - lib/event_router/errors/required_option_error.rb
152
+ - lib/event_router/errors/unsupported_option_error.rb
153
+ - lib/event_router/event.rb
154
+ - lib/event_router/publisher.rb
155
+ - lib/event_router/serializer.rb
156
+ - lib/event_router/serializers/base.rb
157
+ - lib/event_router/serializers/json.rb
158
+ - lib/event_router/serializers/oj.rb
159
+ - lib/event_router/version.rb
160
+ homepage: https://github.com/ahmad-elassuty/event_router
161
+ licenses:
162
+ - MIT
163
+ metadata:
164
+ homepage_uri: https://github.com/ahmad-elassuty/event_router
165
+ source_code_uri: https://github.com/ahmad-elassuty/event_router
166
+ post_install_message:
167
+ rdoc_options: []
168
+ require_paths:
169
+ - lib
170
+ required_ruby_version: !ruby/object:Gem::Requirement
171
+ requirements:
172
+ - - ">="
173
+ - !ruby/object:Gem::Version
174
+ version: 2.5.0
175
+ required_rubygems_version: !ruby/object:Gem::Requirement
176
+ requirements:
177
+ - - ">="
178
+ - !ruby/object:Gem::Version
179
+ version: '0'
180
+ requirements: []
181
+ rubygems_version: 3.1.2
182
+ signing_key:
183
+ specification_version: 4
184
+ summary: Organise your application domain events side-effects in a simple and intuitive
185
+ way.
186
+ test_files: []