From 4fc8976aa9c0129ef47641de1cdeaf86fd0fd51e Mon Sep 17 00:00:00 2001 From: Zulfiqar Ali Date: Sun, 14 Jan 2024 22:26:05 -0500 Subject: [PATCH] entities can only be written to by events by default --- .gitignore | 1 + CHANGELOG.md | 5 + Gemfile.lock | 8 +- README.md | 18 ++++ eventsimple.gemspec | 1 + lib/eventsimple/entity.rb | 11 +++ lib/eventsimple/event.rb | 2 + lib/eventsimple/version.rb | 2 +- .../user_component/events/created_spec.rb | 10 +- .../events/rescued_invalid_transition_spec.rb | 10 +- ...ed_invalid_transition_with_reraise_spec.rb | 10 +- spec/dummy/spec/factories/user.rb | 11 +++ spec/dummy/spec/rails_helper.rb | 64 ------------- spec/dummy/spec/spec_helper.rb | 93 ------------------- spec/lib/eventsimple/entity_spec.rb | 35 +++++-- spec/lib/eventsimple/event_spec.rb | 2 + spec/spec_helper.rb | 27 +++++- 17 files changed, 113 insertions(+), 197 deletions(-) create mode 100644 spec/dummy/spec/factories/user.rb delete mode 100644 spec/dummy/spec/rails_helper.rb delete mode 100644 spec/dummy/spec/spec_helper.rb diff --git a/.gitignore b/.gitignore index 10ffaaca9..5e770dbc0 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ /doc/ /log/*.log /pkg/ +/spec/examples.txt /spec/reports/ /tmp/ .idea diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a6210a57..bba1096c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Unreleased +## 1.3.0 - 2024-01-14 +### Changed +- Prevent manual write access to the entity table by default. This is to prevent + accidental writes to the entity table. Use entity.enable_writes! to enable writes. + ## 1.2.3 - 2024-01-11 ### Changed - Fix rendering of deleted events diff --git a/Gemfile.lock b/Gemfile.lock index 989e152b8..00a5d85b1 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,7 +1,7 @@ PATH remote: . specs: - eventsimple (1.2.3) + eventsimple (1.3.0) dry-struct (~> 1.6) dry-types (~> 1.7) pg (~> 1.4) @@ -125,6 +125,11 @@ GEM dry-logic (~> 1.4) zeitwerk (~> 2.6) erubi (1.12.0) + factory_bot (6.4.5) + activesupport (>= 5.0.0) + factory_bot_rails (6.4.3) + factory_bot (~> 6.4) + railties (>= 5.0.0) ffi (1.16.3) formatador (1.1.0) fuubar (2.5.1) @@ -358,6 +363,7 @@ PLATFORMS DEPENDENCIES bundle-audit eventsimple! + factory_bot_rails fuubar git guard-rspec diff --git a/README.md b/README.md index adff70af3..75c34acbc 100644 --- a/README.md +++ b/README.md @@ -342,6 +342,24 @@ Create a rake task to run the consumer ## Helper methods Some convenience methods are provided to help with common use cases. +**`#enable_writes!`** +Write access on entities is disabled by default outside of writes via events. Use this method to enable writes on an entity. + +```ruby + user = User.find_by(canonical_id: 'user-123') + user.enable_writes! do + user.reproject + user.save! + end +``` + +If you are using FactoryBot, you can add the following in your rails_helper.rb to enable writes on the entity: +```ruby +FactoryBot.define do + after(:build) { |model| model.enable_writes! if model.class.ancestors.include?(Eventsimple::Entity::InstanceMethods) } +end +`` + **`#reproject(at: nil)`** Reproject an entity from events (rebuilds in memory but does not persist the entity). diff --git a/eventsimple.gemspec b/eventsimple.gemspec index 27ea42be4..758d9452f 100644 --- a/eventsimple.gemspec +++ b/eventsimple.gemspec @@ -30,6 +30,7 @@ Gem::Specification.new do |spec| spec.add_runtime_dependency 'retriable', '~> 3.1' spec.add_development_dependency 'bundle-audit' + spec.add_development_dependency 'factory_bot_rails' spec.add_development_dependency 'fuubar' spec.add_development_dependency 'git' spec.add_development_dependency 'guard-rspec' diff --git a/lib/eventsimple/entity.rb b/lib/eventsimple/entity.rb index 0464dfe71..cb8d6a56d 100644 --- a/lib/eventsimple/entity.rb +++ b/lib/eventsimple/entity.rb @@ -11,6 +11,8 @@ def event_driven_by(event_klass, aggregate_id:, filter_attributes: []) autosave: false, validate: false + after_initialize :readonly! + class_attribute :ignored_for_projection, default: [] class_attribute :_filter_attributes @@ -32,6 +34,15 @@ def projection_matches_events? attributes == reprojected.attributes end + def enable_writes!(&block) + @readonly = false + + if block_given? + yield + @readonly = true + end + end + def reproject(at: nil) event_history = at ? events.where('created_at <= ?', at).load : events.load ignore_props = (DEFAULT_IGNORE_PROPS + ignored_for_projection).map(&:to_s) diff --git a/lib/eventsimple/event.rb b/lib/eventsimple/event.rb index ea31734a5..6090bfce8 100644 --- a/lib/eventsimple/event.rb +++ b/lib/eventsimple/event.rb @@ -90,7 +90,9 @@ def apply_and_persist apply(aggregate) # Persist! + aggregate.enable_writes! aggregate.save! + aggregate.readonly! self.aggregate = aggregate end diff --git a/lib/eventsimple/version.rb b/lib/eventsimple/version.rb index 6ffc5fbd2..76ba3dec7 100644 --- a/lib/eventsimple/version.rb +++ b/lib/eventsimple/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Eventsimple - VERSION = '1.2.3' + VERSION = '1.3.0' end diff --git a/spec/dummy/spec/components/user_component/events/created_spec.rb b/spec/dummy/spec/components/user_component/events/created_spec.rb index 500dfc41b..553b6cb0f 100644 --- a/spec/dummy/spec/components/user_component/events/created_spec.rb +++ b/spec/dummy/spec/components/user_component/events/created_spec.rb @@ -33,15 +33,7 @@ end context 'when can_apply? check fails' do - let(:user) { - User.create( - canonical_id: canonical_id, - username: 'test-user', - email: 'test@example.com', - created_at: Time.current, - updated_at: Time.current, - ) - } + let(:user) { create(:user, canonical_id: canonical_id) } it_behaves_like 'an event in invalid state' end diff --git a/spec/dummy/spec/components/user_component/events/rescued_invalid_transition_spec.rb b/spec/dummy/spec/components/user_component/events/rescued_invalid_transition_spec.rb index e443d58d8..7cc50f2ac 100644 --- a/spec/dummy/spec/components/user_component/events/rescued_invalid_transition_spec.rb +++ b/spec/dummy/spec/components/user_component/events/rescued_invalid_transition_spec.rb @@ -29,15 +29,7 @@ end context 'when can_apply? check fails' do - let(:user) { - User.create( - canonical_id: canonical_id, - username: 'test-user', - email: 'test@example.com', - created_at: Time.current, - updated_at: Time.current, - ) - } + let(:user) { create(:user, canonical_id: canonical_id) } it_behaves_like 'an event in invalid state that is rescued' end diff --git a/spec/dummy/spec/components/user_component/events/rescued_invalid_transition_with_reraise_spec.rb b/spec/dummy/spec/components/user_component/events/rescued_invalid_transition_with_reraise_spec.rb index 9b6c9c61e..8091f8d82 100644 --- a/spec/dummy/spec/components/user_component/events/rescued_invalid_transition_with_reraise_spec.rb +++ b/spec/dummy/spec/components/user_component/events/rescued_invalid_transition_with_reraise_spec.rb @@ -28,15 +28,7 @@ end context 'when can_apply? check fails' do - let(:user) { - User.create( - canonical_id: canonical_id, - username: 'test-user', - email: 'test@example.com', - created_at: Time.current, - updated_at: Time.current, - ) - } + let(:user) { create(:user, canonical_id: canonical_id) } it_behaves_like 'an event in invalid state' end diff --git a/spec/dummy/spec/factories/user.rb b/spec/dummy/spec/factories/user.rb new file mode 100644 index 000000000..75eb49720 --- /dev/null +++ b/spec/dummy/spec/factories/user.rb @@ -0,0 +1,11 @@ +# frozen_string_literal: true + +FactoryBot.define do + factory :user do + canonical_id { SecureRandom.uuid } + username { 'test-user' } + email { 'test@example.com' } + created_at { Time.current } + updated_at { Time.current } + end +end diff --git a/spec/dummy/spec/rails_helper.rb b/spec/dummy/spec/rails_helper.rb deleted file mode 100644 index 7de8d29c4..000000000 --- a/spec/dummy/spec/rails_helper.rb +++ /dev/null @@ -1,64 +0,0 @@ -# This file is copied to spec/ when you run 'rails generate rspec:install' -require 'spec_helper' -ENV['RAILS_ENV'] ||= 'test' -require_relative '../config/environment' -# Prevent database truncation if the environment is production -abort("The Rails environment is running in production mode!") if Rails.env.production? -require 'rspec/rails' -# Add additional requires below this line. Rails is not loaded until this point! - -# Requires supporting ruby files with custom matchers and macros, etc, in -# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are -# run as spec files by default. This means that files in spec/support that end -# in _spec.rb will both be required and run as specs, causing the specs to be -# run twice. It is recommended that you do not name files matching this glob to -# end with _spec.rb. You can configure this pattern with the --pattern -# option on the command line or in ~/.rspec, .rspec or `.rspec-local`. -# -# The following line is provided for convenience purposes. It has the downside -# of increasing the boot-up time by auto-requiring all files in the support -# directory. Alternatively, in the individual `*_spec.rb` files, manually -# require only the support files necessary. -# -# Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f } - -# Checks for pending migrations and applies them before tests are run. -# If you are not using ActiveRecord, you can remove these lines. -begin - ActiveRecord::Migration.maintain_test_schema! -rescue ActiveRecord::PendingMigrationError => e - puts e.to_s.strip - exit 1 -end -RSpec.configure do |config| - # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures - config.fixture_path = Rails.root.join("spec/fixtures") - - # If you're not using ActiveRecord, or you'd prefer not to run each of your - # examples within a transaction, remove the following line or assign false - # instead of true. - config.use_transactional_fixtures = true - - # You can uncomment this line to turn off ActiveRecord support entirely. - # config.use_active_record = false - - # RSpec Rails can automatically mix in different behaviours to your tests - # based on their file location, for example enabling you to call `get` and - # `post` in specs under `spec/controllers`. - # - # You can disable this behaviour by removing the line below, and instead - # explicitly tag your specs with their type, e.g.: - # - # RSpec.describe UsersController, type: :controller do - # # ... - # end - # - # The different available types are documented in the features, such as in - # https://relishapp.com/rspec/rspec-rails/docs - config.infer_spec_type_from_file_location! - - # Filter lines from Rails gems in backtraces. - config.filter_rails_from_backtrace! - # arbitrary gems may also be filtered via: - # config.filter_gems_from_backtrace("gem name") -end diff --git a/spec/dummy/spec/spec_helper.rb b/spec/dummy/spec/spec_helper.rb deleted file mode 100644 index 032df7e07..000000000 --- a/spec/dummy/spec/spec_helper.rb +++ /dev/null @@ -1,93 +0,0 @@ -# This file was generated by the `rails generate rspec:install` command. Conventionally, all -# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. -# The generated `.rspec` file contains `--require spec_helper` which will cause -# this file to always be loaded, without a need to explicitly require it in any -# files. -# -# Given that it is always loaded, you are encouraged to keep this file as -# light-weight as possible. Requiring heavyweight dependencies from this file -# will add to the boot time of your test suite on EVERY test run, even for an -# individual file that may not need all of that loaded. Instead, consider making -# a separate helper file that requires the additional dependencies and performs -# the additional setup, and require it from the spec files that actually need -# it. -# -# See https://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration -RSpec.configure do |config| - # rspec-expectations config goes here. You can use an alternate - # assertion/expectation library such as wrong or the stdlib/minitest - # assertions if you prefer. - config.expect_with :rspec do |expectations| - # This option will default to `true` in RSpec 4. It makes the `description` - # and `failure_message` of custom matchers include text for helper methods - # defined using `chain`, e.g.: - # be_bigger_than(2).and_smaller_than(4).description - # # => "be bigger than 2 and smaller than 4" - # ...rather than: - # # => "be bigger than 2" - expectations.include_chain_clauses_in_custom_matcher_descriptions = true - end - - # rspec-mocks config goes here. You can use an alternate test double - # library (such as bogus or mocha) by changing the `mock_with` option here. - config.mock_with :rspec do |mocks| - # Prevents you from mocking or stubbing a method that does not exist on - # a real object. This is generally recommended, and will default to - # `true` in RSpec 4. - mocks.verify_partial_doubles = true - end - - # This option will default to `:apply_to_host_groups` in RSpec 4 (and will - # have no way to turn it off -- the option exists only for backwards - # compatibility in RSpec 3). It causes shared context metadata to be - # inherited by the metadata hash of host groups and examples, rather than - # triggering implicit auto-inclusion in groups with matching metadata. - config.shared_context_metadata_behavior = :apply_to_host_groups - - # The settings below are suggested to provide a good initial experience - # with RSpec, but feel free to customize to your heart's content. - - # This allows you to limit a spec run to individual examples or groups - # you care about by tagging them with `:focus` metadata. When nothing - # is tagged with `:focus`, all examples get run. RSpec also provides - # aliases for `it`, `describe`, and `context` that include `:focus` - # metadata: `fit`, `fdescribe` and `fcontext`, respectively. - config.filter_run_when_matching :focus - - # Allows RSpec to persist some state between runs in order to support - # the `--only-failures` and `--next-failure` CLI options. We recommend - # you configure your source control system to ignore this file. - config.example_status_persistence_file_path = "spec/examples.txt" - - # Limits the available syntax to the non-monkey patched syntax that is - # recommended. For more details, see: - # https://relishapp.com/rspec/rspec-core/docs/configuration/zero-monkey-patching-mode - config.disable_monkey_patching! - - # Many RSpec users commonly either run the entire suite or an individual - # file, and it's useful to allow more verbose output when running an - # individual spec file. - if config.files_to_run.one? - # Use the documentation formatter for detailed output, - # unless a formatter has already been configured - # (e.g. via a command-line flag). - config.default_formatter = "doc" - end - - # Print the 10 slowest examples and example groups at the - # end of the spec run, to help surface which specs are running - # particularly slow. - config.profile_examples = 10 - - # Run specs in random order to surface order dependencies. If you find an - # order dependency and want to debug it, you can fix the order by providing - # the seed, which is printed after each run. - # --seed 1234 - config.order = :random - - # Seed global randomization in this process using the `--seed` CLI option. - # Setting this allows you to use `--seed` to deterministically reproduce - # test failures related to randomization by passing the same `--seed` value - # as the one that triggered the failure. - Kernel.srand config.seed -end diff --git a/spec/lib/eventsimple/entity_spec.rb b/spec/lib/eventsimple/entity_spec.rb index 2732c29dc..7a1049d11 100644 --- a/spec/lib/eventsimple/entity_spec.rb +++ b/spec/lib/eventsimple/entity_spec.rb @@ -13,10 +13,12 @@ module Eventsimple end describe '#projection_matches_events?' do - it 'returns true if the entity matches its events' do + it 'returns false if the entity no longer matches state from events' do expect(user.projection_matches_events?).to be true - user.update!(username: 'changed', updated_at: 1.day.ago) + user.enable_writes! do + user.update!(username: 'changed', updated_at: 1.day.ago) + end expect(user.projection_matches_events?).to be false end @@ -29,11 +31,13 @@ module Eventsimple original_user = User.find_by(id: user.id) - user.update!(username: 'changed', updated_at: 1.day.ago) + user.enable_writes! do + user.update!(username: 'changed', updated_at: 1.day.ago) - user.reproject - expect(user.changes.keys).to eq(['username', 'updated_at']) - user.save! + user.reproject + expect(user.changes.keys).to eq(['username', 'updated_at']) + user.save! + end expect( original_user.attributes.except(*Entity::DEFAULT_IGNORE_PROPS), @@ -42,5 +46,24 @@ module Eventsimple ) end end + + describe '#enable_writes!' do + it 'allows writes to the entity' do + expect(user.readonly?).to be true + + user.enable_writes! + expect(user.readonly?).to be false + end + + context 'when enabled with a block' do + it 'disables writes after the block' do + user.enable_writes! do + expect(user.readonly?).to be false + end + + expect(user.readonly?).to be true + end + end + end end end diff --git a/spec/lib/eventsimple/event_spec.rb b/spec/lib/eventsimple/event_spec.rb index 2a8461437..74a9969a0 100644 --- a/spec/lib/eventsimple/event_spec.rb +++ b/spec/lib/eventsimple/event_spec.rb @@ -18,6 +18,7 @@ it 'retries and successfully writes the event' do stale_user = User.find_by(canonical_id: user_canonical_id) + user.enable_writes! user.touch event = UserComponent::Events::Deleted.create!(user: stale_user) @@ -29,6 +30,7 @@ it 'raised stale object error with details' do stale_user = User.find_by(canonical_id: user_canonical_id) + user.enable_writes! user.touch expect { diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 065d10d13..7f9514ed1 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -6,16 +6,27 @@ require 'retriable' RSpec.configure do |config| - # Enable flags like --only-failures and --next-failure - config.example_status_persistence_file_path = ".rspec_status" + config.expect_with :rspec do |expectations| + expectations.include_chain_clauses_in_custom_matcher_descriptions = true + end + + config.mock_with :rspec do |mocks| + mocks.verify_partial_doubles = true + end - # Disable RSpec exposing methods globally on `Module` and `main` + config.shared_context_metadata_behavior = :apply_to_host_groups + config.filter_run_when_matching :focus + config.example_status_persistence_file_path = "spec/examples.txt" config.disable_monkey_patching! - config.expect_with :rspec do |c| - c.syntax = :expect + if config.files_to_run.one? + config.default_formatter = "doc" end + config.order = :random + + Kernel.srand config.seed + require File.expand_path('../spec/dummy/config/environment.rb', __dir__) ENV['RAILS_ROOT'] ||= "#{File.dirname(__FILE__)}../../../spec/dummy" @@ -33,4 +44,10 @@ c.contexts[context][:base_interval] = 0 end end + + FactoryBot.define do + after(:build) { |model| model.enable_writes! if model.class.ancestors.include? Eventsimple::Entity::InstanceMethods } + end + + config.include FactoryBot::Syntax::Methods end