diff --git a/.github/workflows/master.yml b/.github/workflows/master.yml new file mode 100644 index 00000000..4b9a1e67 --- /dev/null +++ b/.github/workflows/master.yml @@ -0,0 +1,40 @@ +name: Ruby + +on: + push: + branches: + - master + + pull_request: + +jobs: + build: + runs-on: ubuntu-latest + name: Ruby ${{ matrix.ruby }} + strategy: + matrix: + ruby: + - '2.7.8' + services: + postgres: + image: postgres:latest + env: + POSTGRES_USER: outboxer_tester + POSTGRES_PASSWORD: outboxer_password + POSTGRES_DB: outboxer_test + ports: ['5432:5432'] + options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 + steps: + - uses: actions/checkout@v3 + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + bundler-cache: true + - name: Check PostgreSQL + run: | + sudo apt-get -qq install -y postgresql-client + export PGPASSWORD=outboxer_password + psql -h localhost -U outboxer_tester -d outboxer_test -c 'SELECT version();' + - name: Run the default task + run: bundle exec rake diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..aa6a8513 --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +/.bundle/ +/doc +/.yardoc +/_yardoc/ +/coverage/ +/pkg/ +/spec/reports/ +/tmp/ + +*.gem + +vendor/bundle + +.rspec_status +.DS_Store \ No newline at end of file diff --git a/.rspec b/.rspec new file mode 100644 index 00000000..34c5164d --- /dev/null +++ b/.rspec @@ -0,0 +1,3 @@ +--format documentation +--color +--require spec_helper diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 00000000..068c63ca --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,229 @@ +AllCops: + NewCops: enable + TargetRubyVersion: 2.6 + SuggestExtensions: false + +Style/StringLiterals: + Enabled: true + EnforcedStyle: double_quotes + +Style/StringLiteralsInInterpolation: + Enabled: true + EnforcedStyle: double_quotes + +Layout/LineLength: + Max: 100 + +Style/Documentation: + Enabled: false + +Metrics/BlockLength: + Enabled: false + +Style/FrozenStringLiteralComment: + Enabled: false + +Metrics/MethodLength: + Max: 60 + +Layout/MultilineMethodCallBraceLayout: + EnforcedStyle: same_line + +Naming/RescuedExceptionsVariableName: + PreferredName: exception + +Layout/MultilineMethodCallIndentation: + EnforcedStyle: indented + +Gemspec/DeprecatedAttributeAssignment: # new in 1.30 + Enabled: true +Gemspec/DevelopmentDependencies: # new in 1.44 + Enabled: true +Gemspec/RequireMFA: # new in 1.23 + Enabled: true +Layout/LineContinuationLeadingSpace: # new in 1.31 + Enabled: true +Layout/LineContinuationSpacing: # new in 1.31 + Enabled: true +Layout/LineEndStringConcatenationIndentation: # new in 1.18 + Enabled: true +Layout/SpaceBeforeBrackets: # new in 1.7 + Enabled: true +Lint/AmbiguousAssignment: # new in 1.7 + Enabled: true +Lint/AmbiguousOperatorPrecedence: # new in 1.21 + Enabled: true +Lint/AmbiguousRange: # new in 1.19 + Enabled: true +Lint/ConstantOverwrittenInRescue: # new in 1.31 + Enabled: true +Lint/DeprecatedConstants: # new in 1.8 + Enabled: true +Lint/DuplicateBranch: # new in 1.3 + Enabled: true +Lint/DuplicateMagicComment: # new in 1.37 + Enabled: true +Lint/DuplicateMatchPattern: # new in 1.50 + Enabled: true +Lint/DuplicateRegexpCharacterClassElement: # new in 1.1 + Enabled: true +Lint/EmptyBlock: # new in 1.1 + Enabled: true +Lint/EmptyClass: # new in 1.3 + Enabled: true +Lint/EmptyInPattern: # new in 1.16 + Enabled: true +Lint/IncompatibleIoSelectWithFiberScheduler: # new in 1.21 + Enabled: true +Lint/LambdaWithoutLiteralBlock: # new in 1.8 + Enabled: true +Lint/MixedCaseRange: # new in 1.53 + Enabled: true +Lint/NoReturnInBeginEndBlocks: # new in 1.2 + Enabled: true +Lint/NonAtomicFileOperation: # new in 1.31 + Enabled: true +Lint/NumberedParameterAssignment: # new in 1.9 + Enabled: true +Lint/OrAssignmentToConstant: # new in 1.9 + Enabled: true +Lint/RedundantDirGlobSort: # new in 1.8 + Enabled: true +Lint/RedundantRegexpQuantifiers: # new in 1.53 + Enabled: true +Lint/RefinementImportMethods: # new in 1.27 + Enabled: true +Lint/RequireRangeParentheses: # new in 1.32 + Enabled: true +Lint/RequireRelativeSelfPath: # new in 1.22 + Enabled: true +Lint/SymbolConversion: # new in 1.9 + Enabled: true +Lint/ToEnumArguments: # new in 1.1 + Enabled: true +Lint/TripleQuotes: # new in 1.9 + Enabled: true +Lint/UnexpectedBlockArity: # new in 1.5 + Enabled: true +Lint/UnmodifiedReduceAccumulator: # new in 1.1 + Enabled: true +Lint/UselessRescue: # new in 1.43 + Enabled: true +Lint/UselessRuby2Keywords: # new in 1.23 + Enabled: true +Metrics/CollectionLiteralLength: # new in 1.47 + Enabled: true +Naming/BlockForwarding: # new in 1.24 + Enabled: true +Security/CompoundHash: # new in 1.28 + Enabled: true +Security/IoMethods: # new in 1.22 + Enabled: true +Style/ArgumentsForwarding: # new in 1.1 + Enabled: true +Style/ArrayIntersect: # new in 1.40 + Enabled: true +Style/CollectionCompact: # new in 1.2 + Enabled: true +Style/ComparableClamp: # new in 1.44 + Enabled: true +Style/ConcatArrayLiterals: # new in 1.41 + Enabled: true +Style/DataInheritance: # new in 1.49 + Enabled: true +Style/DirEmpty: # new in 1.48 + Enabled: true +Style/DocumentDynamicEvalDefinition: # new in 1.1 + Enabled: true +Style/EmptyHeredoc: # new in 1.32 + Enabled: true +Style/EndlessMethod: # new in 1.8 + Enabled: true +Style/EnvHome: # new in 1.29 + Enabled: true +Style/ExactRegexpMatch: # new in 1.51 + Enabled: true +Style/FetchEnvVar: # new in 1.28 + Enabled: true +Style/FileEmpty: # new in 1.48 + Enabled: true +Style/FileRead: # new in 1.24 + Enabled: true +Style/FileWrite: # new in 1.24 + Enabled: true +Style/HashConversion: # new in 1.10 + Enabled: true +Style/HashExcept: # new in 1.7 + Enabled: true +Style/IfWithBooleanLiteralBranches: # new in 1.9 + Enabled: true +Style/InPatternThen: # new in 1.16 + Enabled: true +Style/MagicCommentFormat: # new in 1.35 + Enabled: true +Style/MapCompactWithConditionalBlock: # new in 1.30 + Enabled: true +Style/MapToHash: # new in 1.24 + Enabled: true +Style/MapToSet: # new in 1.42 + Enabled: true +Style/MinMaxComparison: # new in 1.42 + Enabled: true +Style/MultilineInPatternThen: # new in 1.16 + Enabled: true +Style/NegatedIfElseCondition: # new in 1.2 + Enabled: true +Style/NestedFileDirname: # new in 1.26 + Enabled: true +Style/NilLambda: # new in 1.3 + Enabled: true +Style/NumberedParameters: # new in 1.22 + Enabled: true +Style/NumberedParametersLimit: # new in 1.22 + Enabled: true +Style/ObjectThen: # new in 1.28 + Enabled: true +Style/OpenStructUse: # new in 1.23 + Enabled: true +Style/OperatorMethodCall: # new in 1.37 + Enabled: true +Style/QuotedSymbols: # new in 1.16 + Enabled: true +Style/RedundantArgument: # new in 1.4 + Enabled: true +Style/RedundantArrayConstructor: # new in 1.52 + Enabled: true +Style/RedundantConstantBase: # new in 1.40 + Enabled: true +Style/RedundantCurrentDirectoryInPath: # new in 1.53 + Enabled: true +Style/RedundantDoubleSplatHashBraces: # new in 1.41 + Enabled: true +Style/RedundantEach: # new in 1.38 + Enabled: true +Style/RedundantFilterChain: # new in 1.52 + Enabled: true +Style/RedundantHeredocDelimiterQuotes: # new in 1.45 + Enabled: true +Style/RedundantInitialize: # new in 1.27 + Enabled: true +Style/RedundantLineContinuation: # new in 1.49 + Enabled: true +Style/RedundantRegexpArgument: # new in 1.53 + Enabled: true +Style/RedundantRegexpConstructor: # new in 1.52 + Enabled: true +Style/RedundantSelfAssignmentBranch: # new in 1.19 + Enabled: true +Style/RedundantStringEscape: # new in 1.37 + Enabled: true +Style/ReturnNilInPredicateMethodDefinition: # new in 1.53 + Enabled: true +Style/SelectByRegexp: # new in 1.22 + Enabled: true +Style/StringChars: # new in 1.12 + Enabled: true +Style/SwapValues: # new in 1.1 + Enabled: true +Style/YAMLFileRead: # new in 1.53 + Enabled: true diff --git a/.ruby-version b/.ruby-version new file mode 100644 index 00000000..8122ad01 --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +2.7.8 \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..1812e544 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,5 @@ +## [Unreleased] + +## [0.1.0] - 2023-07-30 + +- Initial release diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..bc342002 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,84 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement. All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of actions. + +**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, +available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. diff --git a/Gemfile b/Gemfile new file mode 100644 index 00000000..61829e78 --- /dev/null +++ b/Gemfile @@ -0,0 +1,12 @@ +source "https://rubygems.org" + +gemspec + +gem "pry-byebug", "~> 3.10" +gem "rake", "~> 13.0" +gem "rspec", "~> 3.12" +gem "rubocop", "~> 1.55" + +gem "yard", "~> 0.9.34" + +gem "pg", "~> 1.5" diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 00000000..533e4a66 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,93 @@ +PATH + remote: . + specs: + outboxer (0.1.11) + activerecord (~> 7.0) + +GEM + remote: https://rubygems.org/ + specs: + activemodel (7.0.6) + activesupport (= 7.0.6) + activerecord (7.0.6) + activemodel (= 7.0.6) + activesupport (= 7.0.6) + activesupport (7.0.6) + concurrent-ruby (~> 1.0, >= 1.0.2) + i18n (>= 1.6, < 2) + minitest (>= 5.1) + tzinfo (~> 2.0) + ast (2.4.2) + byebug (11.1.3) + coderay (1.1.3) + concurrent-ruby (1.2.2) + diff-lcs (1.5.0) + i18n (1.14.1) + concurrent-ruby (~> 1.0) + json (2.6.3) + language_server-protocol (3.17.0.3) + method_source (1.0.0) + minitest (5.19.0) + parallel (1.23.0) + parser (3.2.2.3) + ast (~> 2.4.1) + racc + pg (1.5.3) + pry (0.14.2) + coderay (~> 1.1) + method_source (~> 1.0) + pry-byebug (3.10.1) + byebug (~> 11.0) + pry (>= 0.13, < 0.15) + racc (1.7.1) + rainbow (3.1.1) + rake (13.0.6) + regexp_parser (2.8.1) + rexml (3.2.6) + rspec (3.12.0) + rspec-core (~> 3.12.0) + rspec-expectations (~> 3.12.0) + rspec-mocks (~> 3.12.0) + rspec-core (3.12.2) + rspec-support (~> 3.12.0) + rspec-expectations (3.12.3) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.12.0) + rspec-mocks (3.12.6) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.12.0) + rspec-support (3.12.1) + rubocop (1.55.1) + json (~> 2.3) + language_server-protocol (>= 3.17.0) + parallel (~> 1.10) + parser (>= 3.2.2.3) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 1.8, < 3.0) + rexml (>= 3.2.5, < 4.0) + rubocop-ast (>= 1.28.1, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 3.0) + rubocop-ast (1.29.0) + parser (>= 3.2.1.0) + ruby-progressbar (1.13.0) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + unicode-display_width (2.4.2) + yard (0.9.34) + +PLATFORMS + arm64-darwin-22 + x86_64-linux + +DEPENDENCIES + outboxer! + pg (~> 1.5) + pry-byebug (~> 3.10) + rake (~> 13.0) + rspec (~> 3.12) + rubocop (~> 1.55) + yard (~> 0.9.34) + +BUNDLED WITH + 2.4.17 diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 00000000..c6bbe10c --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2023 Adam Mikulasev + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 00000000..89f39b88 --- /dev/null +++ b/README.md @@ -0,0 +1,188 @@ +# Outboxer + +[![Gem Version](https://badge.fury.io/rb/outboxer.svg)](https://badge.fury.io/rb/outboxer) +![Ruby](https://github.com/fast-programmer/outboxer/actions/workflows/master.yml/badge.svg) + +## Background + +Outboxer helps teams migrate existing Ruby on Rails apps to event-driven architecture ASAP. + +It guarantees an eventual consistency model, where no events are lost even when updates span SQL and another database like Redis. + +## Problem + +To support an eventually consistent event driven architecture, an application service often needs to: + +1. create or update a `Model` row in an _SQL table_ +1. create an `Event` row in an _SQL table_ +2. queue a `Worker` entry in _Redis set_ + + +As these operations span multiple database types (_SQL_ and _Redis_) however, they can not be combined into a single atomic operation using a transaction. If either database fails, inconsistencies can occur. + +## Solution + +Outboxer is an `ActiveRecord` implementation of the [transactional outbox pattern](https://microservices.io/patterns/data/transactional-outbox.html): a well established solution to this problem. + +By creating an outboxer event in the same transaction as the event, we can publish this event out to another system _eventually_ even when there are failures. + +### Getting started + +### Installation + +#### add the outboxer gem to your application's Gemfile: + +``` +gem 'outboxer' +``` + +#### install the outboxer gem: + +``` +bundle install +``` + +### Usage + +#### 1. add events to your model + +##### a. migrate schema + +```bash +bin/rails g migration create_events +``` + +```ruby +class CreateEvents < ActiveRecord::Migration[6.1] + def change + create_table :events, force: true do |t| + t.text :type, null: false + t.jsonb :payload + + t.datetime :created_at, null: false + + t.references :eventable, polymorphic: true, null: false, index: true + end + + add_index :events, [:eventable_type, :eventable_id, :created_at], + name: 'index_events_on_eventable_and_created_at' + end +end +``` + +```bash +bin/rake db:migrate +``` + +##### b. add model + +```ruby +class Event < ActiveRecord::Base + self.inheritance_column = :_type_disabled + + attribute :created_at, :datetime, default: -> { Time.current } + + belongs_to :eventable, polymorphic: true + + validates :type, presence: true + validates :eventable, presence: true +end +``` + +#### 2. associate events with your existing models + +##### a. invoice + +```ruby +class Invoice < ActiveRecord::Base + has_many :events, + -> { order(created_at: :asc) }, + as: :eventable +end +``` + +##### b. contact + +```ruby +class Contact < ActiveRecord::Base + has_many :events, + -> { order(created_at: :asc) }, + as: :eventable +end +``` + +#### 3. integrate events with outboxer + +##### a. generate outboxer schema and publisher + +```bash +bin/rails generate outboxer:install +``` + +##### b. migrate outboxer schema + +```bash +bin/rake db:migrate +``` + +##### c. associate outboxer event with event + +```ruby +class Event < ActiveRecord::Base + # ... + + has_one :outboxer_event, + class_name: 'Outboxer::Models::Event', + as: :outboxer_eventable, + dependent: :destroy + + after_create -> { create_outboxer_event! } +end +``` + +#### 4. publish events + +##### a. update block to queue an event handler worker + +```ruby +loop do + Outboxer::Event.publish! do |outboxer_eventable| + EventHandlerWorker.perform_async({ 'event' => { 'id' => outboxer_eventable.id } }) + end +end +``` + +##### b. run the event publisher + +```bash +bin/event_publisher +``` + + +## Implementation + +To see all the parts working together in a single place, check out the [publisher_spec.rb](https://github.com/fast-programmer/outboxer/blob/master/spec/outboxer/publisher_spec.rb) + + +## Motivation + +Outboxer was created to help high growth SAAS companies transition to event driven architecture quickly. + +Specifically this means: + +1. fast integration into existing Ruby on Rails applications (< 1 hour) +2. comprehensive documentation +3. high reliability in production environments +4. forever free to use in commerical applications (MIT licence) + +## Contributing + +Bug reports and pull requests are welcome on GitHub at https://github.com/fast-programmer/outboxer. 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/fast-programmer/outboxer/blob/main/CODE_OF_CONDUCT.md). + +## License + +The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT). + +## Code of Conduct + +Everyone interacting in the Outboxer project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/fast-programmer/outboxer/blob/main/CODE_OF_CONDUCT.md). diff --git a/Rakefile b/Rakefile new file mode 100644 index 00000000..80cc03e5 --- /dev/null +++ b/Rakefile @@ -0,0 +1,12 @@ +require "rspec/core/rake_task" + +RSpec::Core::RakeTask.new(:spec) + +require "pry" +require "rubocop/rake_task" + +RuboCop::RakeTask.new + +task default: %i[spec rubocop] + +load "lib/tasks/gem.rake" diff --git a/bin/console b/bin/console new file mode 100755 index 00000000..ca05fd64 --- /dev/null +++ b/bin/console @@ -0,0 +1,7 @@ +#!/usr/bin/env ruby + +require "bundler/setup" +require "outboxer" + +require "irb" +IRB.start(__FILE__) diff --git a/bin/rake b/bin/rake new file mode 100755 index 00000000..4eb7d7bf --- /dev/null +++ b/bin/rake @@ -0,0 +1,27 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'rake' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +bundle_binstub = File.expand_path("bundle", __dir__) + +if File.file?(bundle_binstub) + if File.read(bundle_binstub, 300).include?("This file was generated by Bundler") + load(bundle_binstub) + else + abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. +Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") + end +end + +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("rake", "rake") diff --git a/bin/rdoc b/bin/rdoc new file mode 100755 index 00000000..d2b6bcf8 --- /dev/null +++ b/bin/rdoc @@ -0,0 +1,27 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'rdoc' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +bundle_binstub = File.expand_path("bundle", __dir__) + +if File.file?(bundle_binstub) + if File.read(bundle_binstub, 300).include?("This file was generated by Bundler") + load(bundle_binstub) + else + abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. +Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") + end +end + +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("rdoc", "rdoc") diff --git a/bin/ri b/bin/ri new file mode 100755 index 00000000..72e25813 --- /dev/null +++ b/bin/ri @@ -0,0 +1,27 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'ri' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +bundle_binstub = File.expand_path("bundle", __dir__) + +if File.file?(bundle_binstub) + if File.read(bundle_binstub, 300).include?("This file was generated by Bundler") + load(bundle_binstub) + else + abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. +Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") + end +end + +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("rdoc", "ri") diff --git a/bin/rspec b/bin/rspec new file mode 100755 index 00000000..cb53ebe5 --- /dev/null +++ b/bin/rspec @@ -0,0 +1,27 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'rspec' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +bundle_binstub = File.expand_path("bundle", __dir__) + +if File.file?(bundle_binstub) + if File.read(bundle_binstub, 300).include?("This file was generated by Bundler") + load(bundle_binstub) + else + abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. +Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") + end +end + +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("rspec-core", "rspec") diff --git a/bin/rubocop b/bin/rubocop new file mode 100755 index 00000000..369a05be --- /dev/null +++ b/bin/rubocop @@ -0,0 +1,27 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'rubocop' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +bundle_binstub = File.expand_path("bundle", __dir__) + +if File.file?(bundle_binstub) + if File.read(bundle_binstub, 300).include?("This file was generated by Bundler") + load(bundle_binstub) + else + abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. +Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") + end +end + +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("rubocop", "rubocop") diff --git a/bin/setup b/bin/setup new file mode 100755 index 00000000..cf4ad25e --- /dev/null +++ b/bin/setup @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' +set -vx + +bundle install diff --git a/bin/yard b/bin/yard new file mode 100755 index 00000000..ea9daf5f --- /dev/null +++ b/bin/yard @@ -0,0 +1,27 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'yard' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +bundle_binstub = File.expand_path("bundle", __dir__) + +if File.file?(bundle_binstub) + if File.read(bundle_binstub, 300).include?("This file was generated by Bundler") + load(bundle_binstub) + else + abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. +Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") + end +end + +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("yard", "yard") diff --git a/bin/yardoc b/bin/yardoc new file mode 100755 index 00000000..e1324dc1 --- /dev/null +++ b/bin/yardoc @@ -0,0 +1,27 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'yardoc' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +bundle_binstub = File.expand_path("bundle", __dir__) + +if File.file?(bundle_binstub) + if File.read(bundle_binstub, 300).include?("This file was generated by Bundler") + load(bundle_binstub) + else + abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. +Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") + end +end + +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("yard", "yardoc") diff --git a/bin/yri b/bin/yri new file mode 100755 index 00000000..f968fde1 --- /dev/null +++ b/bin/yri @@ -0,0 +1,27 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'yri' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +bundle_binstub = File.expand_path("bundle", __dir__) + +if File.file?(bundle_binstub) + if File.read(bundle_binstub, 300).include?("This file was generated by Bundler") + load(bundle_binstub) + else + abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. +Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") + end +end + +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("yard", "yri") diff --git a/generators/outboxer/install_generator.rb b/generators/outboxer/install_generator.rb new file mode 100644 index 00000000..e3d212e0 --- /dev/null +++ b/generators/outboxer/install_generator.rb @@ -0,0 +1,30 @@ +module Outboxer + class InstallGenerator < Rails::Generators::Base + include Rails::Generators::Migration + + source_root File.expand_path("templates", __dir__) + + def self.next_migration_number(dirname) + next_number = Time.now.utc.strftime("%Y%m%d%H%M%S").to_i + + next_number += 1 while Dir.glob("#{dirname}/#{next_number}*").any? + + next_number.to_s + end + + def copy_bin_file + template "bin/event_publisher.rb", "bin/event_publisher" + run "chmod +x bin/event_publisher" + end + + def copy_migrations + migration_template( + "migrations/create_outboxer_events.rb", + "db/migrate/create_outboxer_events.rb") + + migration_template( + "migrations/create_outboxer_exceptions.rb", + "db/migrate/create_outboxer_exceptions.rb") + end + end +end diff --git a/generators/outboxer/templates/bin/event_publisher.rb b/generators/outboxer/templates/bin/event_publisher.rb new file mode 100755 index 00000000..e0056c21 --- /dev/null +++ b/generators/outboxer/templates/bin/event_publisher.rb @@ -0,0 +1,23 @@ +#!/usr/bin/env ruby + +require_relative '../config/environment' + +logger = Logger.new($stdout) +logger.level = Logger::INFO + +loop do + Outboxer::Event.publish! do |outboxer_eventable| + EventHandlerWorker.perform_async({ 'event' => { 'id' => outboxer_eventable.id } }) + end +rescue Interrupt + logger.warn "\nCTRL+C detected. Exiting gracefully..." + + break +rescue => Outboxer::Event::NotFound + sleep 1 +rescue => exception + logger.error("Exception raised: #{exception.class}: #{exception.message}\n" \ + "#{exception.backtrace.join("\n")}") + + sleep 1 +end diff --git a/generators/outboxer/templates/migrations/create_outboxer_events.rb b/generators/outboxer/templates/migrations/create_outboxer_events.rb new file mode 100644 index 00000000..60932579 --- /dev/null +++ b/generators/outboxer/templates/migrations/create_outboxer_events.rb @@ -0,0 +1,13 @@ +class CreateOutboxerEvents < ActiveRecord::Migration[6.1] + def change + create_table :outboxer_events do |t| + t.text :status, null: false + + t.references :outboxer_eventable, polymorphic: true, null: false + + t.timestamps + end + + add_index :outboxer_events, %i[status created_at] + end +end diff --git a/generators/outboxer/templates/migrations/create_outboxer_exceptions.rb b/generators/outboxer/templates/migrations/create_outboxer_exceptions.rb new file mode 100644 index 00000000..e1ba4ad4 --- /dev/null +++ b/generators/outboxer/templates/migrations/create_outboxer_exceptions.rb @@ -0,0 +1,15 @@ +class CreateOutboxerExceptions < ActiveRecord::Migration[6.1] + def change + create_table :outboxer_exceptions do |t| + t.references :outboxer_event, null: false, foreign_key: { to_table: :outboxer_events } + + t.text :class_name, null: false + t.text :message_text, null: false + t.column :backtrace, :text, array: true + + t.timestamps + end + + remove_column :outboxer_exceptions, :updated_at + end +end diff --git a/lib/outboxer.rb b/lib/outboxer.rb new file mode 100644 index 00000000..e046839a --- /dev/null +++ b/lib/outboxer.rb @@ -0,0 +1,11 @@ +require "active_support" + +require_relative "outboxer/version" +require_relative "outboxer/railtie" if defined?(Rails) + +require_relative "outboxer/models" + +require_relative "outboxer/event" + +module Outboxer +end diff --git a/lib/outboxer/event.rb b/lib/outboxer/event.rb new file mode 100644 index 00000000..5fef617b --- /dev/null +++ b/lib/outboxer/event.rb @@ -0,0 +1,127 @@ +require "logger" +require "active_record" + +module Outboxer + module Event + module_function + + class Error < StandardError; end; + class NotFound < Error; end + class InvalidTransition < Error; end + + # publish an unpublished outboxer eventable + # + # This method retrieves an unpublished event, set it to publishing and then yields it to + # the provided block. The event is marked as readonly to prevent modifications + # during processing. If an error occurs during the yield, the method rescues + # the exception, sets the event status to failed, and re-raises the exception. + # Upon successful processing, the event status is set to published. + # + # @yield [outboxer_eventable] Yields the polymorphically associated model. + # @yieldparam outboxer_eventable The readonly event from outboxer. + # + # @raise [Outboxer::Event::NotFound] If no unpublished event is found in the queue. + # @raise [StandardError] Reraises any exception that occurs during the yield. + # + # @example Publish event + # Outboxer::Event.publish! do |outboxer_eventable| + # EventHandlerWorker.perform_async({ 'event' => {'id' => outboxer_eventable.id } }) + # end + + def self.publish! + outboxer_event = unpublished! + + begin + yield outboxer_event.outboxer_eventable + rescue => exception + failed!(id: outboxer_event.id, exception: exception) + + raise + end + + published!(id: outboxer_event.id) + end + + def self.unpublished! + ActiveRecord::Base.connection_pool.with_connection do + ActiveRecord::Base.transaction do + outboxer_event = Models::Event + .includes(:outboxer_eventable) + .where(status: Models::Event::STATUS[:unpublished]) + .order(created_at: :asc) + .limit(1) + .lock("FOR UPDATE SKIP LOCKED") + .first + + outboxer_event.update!(status: Models::Event::STATUS[:publishing]) + + outboxer_event.outboxer_eventable.readonly! + + outboxer_event + end + end + rescue ActiveRecord::RecordNotFound => exception + raise NotFound.new(exception) + end + + def self.published!(id:) + ActiveRecord::Base.connection_pool.with_connection do + outboxer_event = Models::Event + .order(created_at: :asc) + .lock + .find_by!(id: id) + + if outboxer_event.status != Models::Event::STATUS[:publishing] + raise InvalidTransition, + "cannot transition outboxer event #{outboxer_event.id} " \ + "from #{outboxer_event.status} to (deleted)" + end + + outboxer_event.destroy! + end + end + + def self.failed!(id:, exception:) + ActiveRecord::Base.connection_pool.with_connection do + ActiveRecord::Base.transaction do + outboxer_event = Models::Event + .order(created_at: :asc) + .lock + .find_by!(id: id) + + if outboxer_event.status != Models::Event::STATUS[:publishing] + raise InvalidTransition, + "cannot transition outboxer event #{id} " \ + "from #{outboxer_event.status} to #{Models::Event::STATUS[:failed]}" + end + + outboxer_event.update!(status: Models::Event::STATUS[:failed]) + + outboxer_event.outboxer_exceptions.create!( + class_name: exception.class.name, + message_text: exception.message, + backtrace: exception.backtrace) + end + end + end + + def self.republish!(id:) + ActiveRecord::Base.connection_pool.with_connection do + outboxer_event = Models::Event + .order(created_at: :asc) + .lock + .find_by!(id: id) + + if outboxer_event.status != Models::Event::STATUS[:failed] + raise InvalidTransition, + "cannot transition outboxer event #{id} " \ + "from #{outboxer_event.status} to #{Models::Event::STATUS[:failed]}" + end + + outboxer_event.update!(status: Models::Event::STATUS[:unpublished]) + end + end + + private_class_method :unpublished! + end +end diff --git a/lib/outboxer/models.rb b/lib/outboxer/models.rb new file mode 100644 index 00000000..6e7ea24d --- /dev/null +++ b/lib/outboxer/models.rb @@ -0,0 +1,2 @@ +require_relative "models/exception" +require_relative "models/event" diff --git a/lib/outboxer/models/event.rb b/lib/outboxer/models/event.rb new file mode 100644 index 00000000..639ee3e3 --- /dev/null +++ b/lib/outboxer/models/event.rb @@ -0,0 +1,39 @@ +require "active_record" + +module Outboxer + module Models + # Represents a event in the outbox. + # + # @!attribute [r] id + # @return [Integer] The unique identifier for the event. + # @!attribute [r] outboxable_id + # @return [Integer] The ID of the associated polymorphic event. + # @!attribute [r] outboxable_type + # @return [String] The type of the associated polymorphic event. + # @!attribute status + # @return [String] The status of the event (see {STATUS}). + # @!attribute [r] created_at + # @return [Time] The timestamp when the record was created. + # @!attribute [r] updated_at + # @return [Time] The timestamp when the record was last updated. + class Event < ::ActiveRecord::Base + self.table_name = :outboxer_events + + STATUS = { + unpublished: "unpublished", + publishing: "publishing", + failed: "failed" + } + + attribute :status, default: -> { STATUS[:unpublished] } + + belongs_to :outboxer_eventable, polymorphic: true + + has_many :outboxer_exceptions, + -> { order(created_at: :asc) }, + foreign_key: 'outboxer_event_id', + class_name: "::Outboxer::Models::Exception", + dependent: :destroy + end + end +end diff --git a/lib/outboxer/models/exception.rb b/lib/outboxer/models/exception.rb new file mode 100644 index 00000000..55119656 --- /dev/null +++ b/lib/outboxer/models/exception.rb @@ -0,0 +1,25 @@ +require "active_record" + +module Outboxer + module Models + # Represents an exception associated with an {Outboxer::Event}. + # + # @!attribute [r] id + # @return [Integer] The unique identifier for the exception. + # @!attribute event_id + # @return [Integer] The ID of the associated {Outboxer::Event}. + # @!attribute class_name + # @return [String] The class name of the exception. + # @!attribute message_text + # @return [String] The exception's error message. + # @!attribute backtrace + # @return [Array] The exception's backtrace. + # @!attribute [r] created_at + # @return [Time] The timestamp when the record was created. + class Exception < ::ActiveRecord::Base + self.table_name = :outboxer_exceptions + + belongs_to :outboxer_event, class_name: "::Outboxer::Models::Event" + end + end +end diff --git a/lib/outboxer/railtie.rb b/lib/outboxer/railtie.rb new file mode 100644 index 00000000..71073bfa --- /dev/null +++ b/lib/outboxer/railtie.rb @@ -0,0 +1,12 @@ +require "outboxer" +require "rails" + +module Outboxer + class Railtie < Rails::Railtie + railtie_name :outboxer + + generators do + require_relative "../../generators/outboxer/install_generator" + end + end +end diff --git a/lib/outboxer/version.rb b/lib/outboxer/version.rb new file mode 100644 index 00000000..889c0512 --- /dev/null +++ b/lib/outboxer/version.rb @@ -0,0 +1,3 @@ +module Outboxer + VERSION = "0.1.11".freeze +end diff --git a/lib/tasks/gem.rake b/lib/tasks/gem.rake new file mode 100644 index 00000000..38d00621 --- /dev/null +++ b/lib/tasks/gem.rake @@ -0,0 +1,58 @@ +require "rake/packagetask" + +namespace :gem do + desc "Bump version number" + task :bump, [:type] do |_t, args| + args.with_defaults(type: "patch") + + unless %w[major minor patch].include?(args[:type]) + raise "Invalid version type - choose from major/minor/patch" + end + + version_file = File.expand_path("../../lib/outboxer/version.rb", __dir__) + version = "" + File.open(version_file, "r") do |file| + version = file.read.match(/VERSION = "(.*)"/)[1] + end + + version_parts = version.split(".").map(&:to_i) + case args[:type] + when "major" + version_parts[0] += 1 + version_parts[1] = 0 + version_parts[2] = 0 + when "minor" + version_parts[1] += 1 + version_parts[2] = 0 + when "patch" + version_parts[2] += 1 + end + + new_version = version_parts.join(".") + File.write(version_file, "module Outboxer\n VERSION = \"#{new_version}\".freeze\nend\n") + + puts "Gem version bumped to #{new_version}" + end + + desc "Build the gem" + task :build do + Outboxer.send(:remove_const, :VERSION) if Outboxer.const_defined?(:VERSION) + load "lib/outboxer/version.rb" + sh "gem build outboxer.gemspec" + + puts "Gem built successfully." + end + + desc "Push the gem to RubyGems" + task :push do + Outboxer.send(:remove_const, :VERSION) if Outboxer.const_defined?(:VERSION) + load "lib/outboxer/version.rb" + version = Outboxer::VERSION + sh "gem push outboxer-#{version}.gem" + + puts "Gem pushed to RubyGems." + end + + desc "Bump, build and push the gem to RubyGems" + task release: %i[bump build push] +end diff --git a/outboxer.gemspec b/outboxer.gemspec new file mode 100644 index 00000000..eca0e84f --- /dev/null +++ b/outboxer.gemspec @@ -0,0 +1,33 @@ +# rubocop:disable Layout/LineLength +require_relative "lib/outboxer/version" + +Gem::Specification.new do |spec| + spec.name = "outboxer" + spec.version = Outboxer::VERSION + spec.authors = ["Adam Mikulasev"] + spec.email = ["adam@fastprogrammer.co"] + + spec.summary = "Transactional outbox implementation for event driven Ruby on Rails applications that use SQL" + spec.homepage = "https://github.com/fast-programmer/outboxer" + spec.license = "MIT" + spec.required_ruby_version = ">= 2.6.0" + + spec.metadata["homepage_uri"] = spec.homepage + spec.metadata["source_code_uri"] = "https://github.com/fast-programmer/outboxer" + spec.metadata["documentation_uri"] = "https://rubydoc.info/github/fast-programmer/outboxer/master" + spec.metadata["changelog_uri"] = "https://github.com/fast-programmer/outboxer/blob/master/CHANGELOG.md" + spec.metadata["rubygems_mfa_required"] = "true" + + spec.files = Dir.chdir(__dir__) do + `git ls-files -z`.split("\x0").reject do |f| + (File.expand_path(f) == __FILE__) || + f.start_with?(*%w[bin/ test/ spec/ features/ .git .circleci appveyor Gemfile]) + end + end + spec.bindir = "exe" + spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) } + spec.require_paths = ["lib"] + + spec.add_dependency "activerecord", "~> 7.0" +end +# rubocop:enable Layout/LineLength diff --git a/sig/outboxer.rbs b/sig/outboxer.rbs new file mode 100644 index 00000000..a96a5705 --- /dev/null +++ b/sig/outboxer.rbs @@ -0,0 +1,19 @@ +module Outboxer + VERSION: String + + module Publisher + class Args + attr_reader message: untyped + attr_reader logger: Logger + + def initialize: (untyped message, Logger logger) -> void + end + + def self.publish: (?Integer poll, ?Proc[Integer, Integer] backoff) { (Args) -> untyped } -> void + def self.dequeue: ({ backoff: Proc[Integer, Integer] }) -> untyped + def self.published: ({ outboxer_message: untyped, backoff: Proc[Integer, Integer] }) -> void + def self.failed: ({ outboxer_message: untyped, exception: Exception, backoff: Proc[Integer, Integer] }) -> void + def self.retry_on_error: ({ backoff: Proc[Integer, Integer] }) { () -> untyped } -> untyped + def self.stop: () -> void + end +end diff --git a/spec/outboxer/event_spec.rb b/spec/outboxer/event_spec.rb new file mode 100644 index 00000000..3a761d49 --- /dev/null +++ b/spec/outboxer/event_spec.rb @@ -0,0 +1,209 @@ +require "spec_helper" +require 'pry-byebug' + +require_relative "../../generators/outboxer/templates/migrations/create_outboxer_events" +require_relative "../../generators/outboxer/templates/migrations/create_outboxer_exceptions" + +# psql -d postgres +# CREATE USER outboxer_tester WITH PASSWORD 'outboxer_tester'; +# CREATE DATABASE outboxer_test; +# GRANT ALL PRIVILEGES ON DATABASE outboxer_test TO outboxer_tester; + +# rubocop:disable Lint/ConstantDefinitionInBlock + +# ActiveRecord::Base.logger = Logger.new($stdout) + +RSpec.describe Outboxer::Event do + before(:each) do + ActiveRecord::Base.establish_connection( + host: "localhost", + adapter: "postgresql", + database: "outboxer_test", + username: "outboxer_tester", + password: "outboxer_password") + + existing_tables = %i[outboxer_exceptions outboxer_events events accounting_invoices].select do |table| + ActiveRecord::Base.connection.table_exists?(table) + end + + existing_tables.each do |existing_table| + ActiveRecord::Migration.drop_table(existing_table) + end + + ActiveRecord::Schema.define do + create_table :accounting_invoices, force: true do |t| + t.integer :lock_version, default: 0, null: false + + t.timestamps null: false + end + + create_table :events, force: true do |t| + t.text :type, null: false + t.jsonb :payload + + t.datetime :created_at, null: false + + t.references :eventable, polymorphic: true, null: false, index: true + end + + add_index :events, [:eventable_type, :eventable_id, :created_at], + name: 'index_events_on_eventable_and_created_at' + + CreateOutboxerEvents.new.change + CreateOutboxerExceptions.new.change + end + + class EventHandlerWorker + def self.perform_async(args) + # TODO: custom logic here + end + end + + module Models + class Event < ActiveRecord::Base + self.inheritance_column = :_type_disabled + + attribute :created_at, :datetime, default: -> { Time.current } + + belongs_to :eventable, polymorphic: true + + validates :type, presence: true + validates :eventable, presence: true + + # begin outboxer event integration + + has_one :outboxer_event, + class_name: 'Outboxer::Models::Event', + as: :outboxer_eventable, + dependent: :destroy + + after_create -> { create_outboxer_event! } + + # end outboxer event integration + end + end + + module Accounting + module Invoice + extend self + + def create! + ActiveRecord::Base.transaction do + invoice = Models::Invoice.create! + + + event = invoice.events.create!( + type: 'Accounting::Invoice::Created', + payload: { + 'invoice' => { + 'id' => invoice.id } }) + + [invoice, event] + end + end + end + + module Models + class Invoice < ActiveRecord::Base + self.table_name = 'accounting_invoices' + + has_many :events, + -> { order(created_at: :asc) }, + class_name: 'Models::Event', + as: :eventable + end + end + end + end + + describe ".publish!" do + context "when published" do + it "publishes events" do + published_events = [] + + invoice, created_event = Accounting::Invoice.create! + + expect(Models::Event.count).to eq(1) + expect(Outboxer::Models::Event.count).to eq(1) + + Outboxer::Event.publish! do |event| + EventHandlerWorker.perform_async({ 'event' => { 'id' => event.id } }) + + published_events << event + end + + expect(Models::Event.count).to eq(1) + expect(Outboxer::Models::Event.count).to eq(0) + + expect(published_events.count).to eq(1) + published_event = published_events.first + + expect(published_event).to eq(created_event) + expect(published_event.eventable).to eq(invoice) + expect(published_event.type).to eq('Accounting::Invoice::Created') + expect(published_event.payload['invoice']['id']).to eq(invoice.id) + end + end + + context "when publishing failed" do + it "updates outboxer event status to failed" do + _, event = Accounting::Invoice.create! + + expect(Models::Event.count).to eq(1) + expect(Outboxer::Models::Event.count).to eq(1) + + begin + Outboxer::Event.publish! do |_event| + raise StandardError, "dummy error" + end + rescue => exception + # no op + end + + expect(Models::Event.count).to eq(1) + expect(Outboxer::Models::Event.count).to eq(1) + + outboxer_event = Outboxer::Models::Event.find_by!(outboxer_eventable: event) + expect(outboxer_event.status).to eq(Outboxer::Models::Event::STATUS[:failed]) + expect(outboxer_event.outboxer_exceptions.count).to eq(1) + + last_outboxer_exception = outboxer_event.outboxer_exceptions.last + + expect(last_outboxer_exception.outboxer_event).to eq(outboxer_event) + expect(last_outboxer_exception.message_text).to eq("dummy error") + expect(last_outboxer_exception.class_name).to eq("StandardError") + expect(last_outboxer_exception.backtrace[1]).to include("lib/outboxer/event.rb") + expect(last_outboxer_exception.created_at).not_to be_nil + end + + it "can be republished" do + Accounting::Invoice.create! + + begin + Outboxer::Event.publish! do |_event| + raise StandardError, "dummy error" + end + rescue => exception + # no op + end + + failed_outboxer_events = Outboxer::Models::Event + .where(status: Outboxer::Models::Event::STATUS[:failed]) + + expect(failed_outboxer_events.count).to eq(1) + failed_outboxer_event = failed_outboxer_events.first + + Outboxer::Event.republish!(id: failed_outboxer_event.id) + + expect( + Outboxer::Models::Event + .where( + id: failed_outboxer_event.id, + status: Outboxer::Models::Event::STATUS[:unpublished]) + .count + ).to eq(1) + end + end + end +end +# rubocop:enable Lint/ConstantDefinitionInBlock diff --git a/spec/outboxer_spec.rb b/spec/outboxer_spec.rb new file mode 100644 index 00000000..a832d540 --- /dev/null +++ b/spec/outboxer_spec.rb @@ -0,0 +1,5 @@ +RSpec.describe Outboxer do + it "has a version number" do + expect(Outboxer::VERSION).not_to be nil + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 00000000..257dae20 --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,11 @@ +require "outboxer" + +RSpec.configure do |config| + config.example_status_persistence_file_path = ".rspec_status" + + config.disable_monkey_patching! + + config.expect_with :rspec do |c| + c.syntax = :expect + end +end