event_sourcery-postgres 0.3.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 75bff88c421cb623d91957ca0afec6054a835f2a
4
+ data.tar.gz: dd7c0cd3eaf82c26bb328fbbcdd80e810a38b45b
5
+ SHA512:
6
+ metadata.gz: 016f2f36b96fef639e26584458ec2798649d3d81f54ce39a398fb4eec5645a31c278d680134630239cf3efba9ee76cccca5117dd98d56b59d8a8a6ce5b6c2efc
7
+ data.tar.gz: c033c7b72cb9ea7c31de75aca7c51c168397ea1eb18703eae709a2262a4f9a84893b740195acb5023fab05433fdaa9db26780232ef4ec416d579d3795cc00884
data/.gitignore ADDED
@@ -0,0 +1,13 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ /vendor/
11
+
12
+ # rspec failure tracking
13
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --require spec_helper
2
+ --format documentation
3
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,12 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.2
5
+ - 2.3
6
+ - 2.4
7
+ before_install:
8
+ - gem install bundler
9
+ before_script:
10
+ - psql -c 'create database event_sourcery_test;' -U postgres
11
+ addons:
12
+ postgresql: 9.4
data/CHANGELOG.md ADDED
@@ -0,0 +1,32 @@
1
+ # Change Log
2
+ All notable changes to this project will be documented in this file.
3
+
4
+ The format is based on [Keep a Changelog](http://keepachangelog.com/)
5
+ and this project adheres to [Semantic Versioning](http://semver.org/).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.3.0] - 2017-6-16
10
+ ### Changed
11
+ - The event store persists the event `correlation_id` and `causation_id`.
12
+ To facilitate this `correlation_id` and `causation_id` columns have been
13
+ added to the `events` table and the `write_events` function has been
14
+ altered. Event Sourcery apps will need to ensure these DB changes have
15
+ been applied to use this version of Event Sourcery.
16
+
17
+ ## [0.2.0] - 2017-6-1
18
+ ### Changed
19
+ - Make `EventSourcery::Postgres::OptimisedEventPollWaiter#shutdown` private
20
+ - Updated `EventSourcery::Postgres::OptimisedEventPollWaiter#poll` to ensure that `#shutdown!` is run when an error is raised
21
+ or when the loop stops
22
+ - Remove dynamic emit events methods from reactors (e.g. emit_item_added)
23
+ - The emit_events method now accepts typed events instead of symbols
24
+
25
+ ### Added
26
+ - Configure projector tracker table name via `EventSourcery::Postgres.configure`
27
+
28
+ ## [0.1.0] - 2017-5-26
29
+ ### Changed
30
+ - Imported code from the [event_sourcery](https://github.com/envato/event_sourcery).
31
+ - Postgres related configuration is through `EventSourcery::Postgres.configure`
32
+ instead of `EventSourcery.configure`.
@@ -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 odindutton@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 [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,5 @@
1
+ source 'https://rubygems.org'
2
+
3
+ ruby '>= 2.2.0'
4
+
5
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 Envato
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.
data/README.md ADDED
@@ -0,0 +1,102 @@
1
+ # EventSourcery::Postgres
2
+
3
+ [![Build Status](https://travis-ci.org/envato/event_sourcery-postgres.svg?branch=master)](https://travis-ci.org/envato/event_sourcery-postgres)
4
+
5
+ ## Development Status
6
+
7
+ EventSourcery is currently being used in production by multiple apps but we
8
+ haven't finalized the API yet and things are still moving rapidly. Until we
9
+ release a 1.0 things may change without first being deprecated.
10
+
11
+ ## Installation
12
+
13
+ Add this line to your application's Gemfile:
14
+
15
+ ```ruby
16
+ gem 'event_sourcery-postgres'
17
+ ```
18
+
19
+ ## Configure
20
+
21
+ ```ruby
22
+ EventSourcery::Postgres.configure do |config|
23
+ config.event_store_database = Sequel.connect(...)
24
+ config.projections_database = Sequel.connect(...)
25
+ config.use_optimistic_concurrency = true
26
+ config.write_events_function_name = 'writeEvents'
27
+ config.events_table_name = :events
28
+ config.aggregates_table_name = :aggregates
29
+ config.callback_interval_if_no_new_events = 60
30
+ end
31
+ ```
32
+
33
+ ## Usage
34
+
35
+
36
+ ### Event Store
37
+
38
+ ```ruby
39
+ ItemAdded = EventSourcery::Event
40
+
41
+ EventSourcery::Postgres.event_store.sink(ItemAdded.new(aggregate_id: uuid, body: { }}))
42
+ EventSourcery::Postgres.event_store.get_next_from(0).each do |event|
43
+ puts event.inspect
44
+ end
45
+ ```
46
+
47
+ ### Projectors & Reactors
48
+
49
+ ```ruby
50
+ class ItemProjector
51
+ include EventSourcery::Postgres::Projector
52
+
53
+ table :items do
54
+ column :item_uuid, 'UUID NOT NULL'
55
+ column :title, 'VARCHAR(255) NOT NULL'
56
+ end
57
+
58
+ project ItemAdded do |event|
59
+ table(:items).insert(item_uuid: event.aggregate_id,
60
+ title: event.body.fetch('title'))
61
+ end
62
+ end
63
+
64
+ class UserEmailer
65
+ include EventSourcery::Postgres::Reactor
66
+
67
+ emits_events SignUpEmailSent
68
+
69
+ process UserSignedUp do |event|
70
+ emit_event SignUpEmailSent.new(user_id: event.aggregate_id) do
71
+ UserMailer.signed_up(...).deliver
72
+ end
73
+ end
74
+ end
75
+
76
+ EventSourcery::EventProcessing::ESPRunner.new(
77
+ event_processors: [item_projector, user_emailer],
78
+ event_store: EventSourcery::Postgres.config.event_store,
79
+ stop_on_failure: true,
80
+ ).start!
81
+ ```
82
+
83
+
84
+ ## Development
85
+
86
+ After checking out the repo, run `bin/setup` to install dependencies. (This will install dependencies and recreate the test database.) Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
87
+
88
+ To install this gem onto your local machine, run `bundle exec rake install`.
89
+
90
+ To release a new version:
91
+
92
+ 1. Update the version number in `lib/event_sourcery/postgres/version.rb`
93
+ 2. Get this change onto master via the normal PR process
94
+ 3. Run `gem_push=false be rake release`,
95
+ this will create a git tag for the version,
96
+ push tags up to GitHub, and package the code in a `.gem` file.
97
+ 4. Manually upload the generated gem file (`pkg/event_sourcery-postgres-#{version}.gem`) to
98
+ [rubygems.envato.com](https://rubygems.envato.com).
99
+
100
+ ## Contributing
101
+
102
+ Bug reports and pull requests are welcome on GitHub at https://github.com/envato/event_sourcery-postgres.
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "event_sourcery/postgres"
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
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ echo
9
+ echo "--- Preparing test databases"
10
+ echo
11
+
12
+ dropdb event_sourcery_test || echo 0
13
+ createdb event_sourcery_test
14
+
15
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,33 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'event_sourcery/postgres/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "event_sourcery-postgres"
8
+ spec.version = EventSourcery::Postgres::VERSION
9
+ # TODO: update authors
10
+ spec.authors = ["Steve Hodgkiss"]
11
+ spec.email = ["steve@hodgkiss.me"]
12
+
13
+ spec.summary = %q{Postgres event store for use with EventSourcery}
14
+ spec.homepage = "https://github.com/envato/event_sourcery-postgres"
15
+
16
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
17
+ f.match(%r{^(test|spec|features)/})
18
+ end
19
+ spec.bindir = "exe"
20
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
21
+ spec.require_paths = ["lib"]
22
+
23
+ spec.required_ruby_version = '>= 2.2.0'
24
+
25
+ spec.add_dependency 'sequel', '~> 4.38'
26
+ spec.add_dependency 'pg'
27
+ spec.add_dependency 'event_sourcery', '>= 0.10.0'
28
+ spec.add_development_dependency "bundler", "~> 1.10"
29
+ spec.add_development_dependency "rake", "~> 10.0"
30
+ spec.add_development_dependency "rspec", "~> 3.0"
31
+ spec.add_development_dependency "pry"
32
+ spec.add_development_dependency "benchmark-ips"
33
+ end
@@ -0,0 +1,28 @@
1
+ require 'sequel'
2
+
3
+ Sequel.extension :pg_json
4
+ Sequel.default_timezone = :utc
5
+
6
+ require 'event_sourcery'
7
+ require 'event_sourcery/postgres/version'
8
+ require 'event_sourcery/postgres/config'
9
+ require 'event_sourcery/postgres/queue_with_interval_callback'
10
+ require 'event_sourcery/postgres/schema'
11
+ require 'event_sourcery/postgres/optimised_event_poll_waiter'
12
+ require 'event_sourcery/postgres/event_store'
13
+ require 'event_sourcery/postgres/table_owner'
14
+ require 'event_sourcery/postgres/projector'
15
+ require 'event_sourcery/postgres/reactor'
16
+ require 'event_sourcery/postgres/tracker'
17
+
18
+ module EventSourcery
19
+ module Postgres
20
+ def self.configure
21
+ yield config
22
+ end
23
+
24
+ def self.config
25
+ @config ||= Config.new
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,47 @@
1
+ module EventSourcery
2
+ module Postgres
3
+ class Config
4
+ attr_accessor :event_store_database,
5
+ :lock_table_to_guarantee_linear_sequence_id_growth,
6
+ :write_events_function_name,
7
+ :events_table_name,
8
+ :aggregates_table_name,
9
+ :tracker_table_name,
10
+ :callback_interval_if_no_new_events,
11
+ :auto_create_projector_tracker,
12
+ :event_tracker,
13
+ :projections_database,
14
+ :event_store,
15
+ :event_source,
16
+ :event_sink
17
+
18
+ def initialize
19
+ @lock_table_to_guarantee_linear_sequence_id_growth = true
20
+ @write_events_function_name = 'writeEvents'
21
+ @events_table_name = :events
22
+ @aggregates_table_name = :aggregates
23
+ @tracker_table_name = :projector_tracker
24
+ @callback_interval_if_no_new_events = 10
25
+ @event_store_database = nil
26
+ @auto_create_projector_tracker = true
27
+ end
28
+
29
+ def event_store
30
+ @event_store ||= EventStore.new(event_store_database)
31
+ end
32
+
33
+ def event_source
34
+ @event_source ||= ::EventSourcery::EventStore::EventSource.new(event_store)
35
+ end
36
+
37
+ def event_sink
38
+ @event_sink ||= ::EventSourcery::EventStore::EventSink.new(event_store)
39
+ end
40
+
41
+ def projections_database=(sequel_connection)
42
+ @projections_database = sequel_connection
43
+ @event_tracker = Postgres::Tracker.new(sequel_connection)
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,144 @@
1
+ module EventSourcery
2
+ module Postgres
3
+ class EventStore
4
+ include EventSourcery::EventStore::EachByRange
5
+
6
+ def initialize(pg_connection,
7
+ events_table_name: EventSourcery::Postgres.config.events_table_name,
8
+ lock_table: EventSourcery::Postgres.config.lock_table_to_guarantee_linear_sequence_id_growth,
9
+ write_events_function_name: EventSourcery::Postgres.config.write_events_function_name,
10
+ event_builder: EventSourcery.config.event_builder)
11
+ @pg_connection = pg_connection
12
+ @events_table_name = events_table_name
13
+ @write_events_function_name = write_events_function_name
14
+ @lock_table = lock_table
15
+ @event_builder = event_builder
16
+ end
17
+
18
+ def sink(event_or_events, expected_version: nil)
19
+ events = Array(event_or_events)
20
+ aggregate_ids = events.map(&:aggregate_id).uniq
21
+ raise AtomicWriteToMultipleAggregatesNotSupported unless aggregate_ids.count == 1
22
+ sql = write_events_sql(aggregate_ids.first, events, expected_version)
23
+ @pg_connection.run(sql)
24
+ log_events_saved(events)
25
+ true
26
+ rescue Sequel::DatabaseError => e
27
+ if e.message =~ /Concurrency conflict/
28
+ raise ConcurrencyError, "expected version was not #{expected_version}. Error: #{e.message}"
29
+ else
30
+ raise
31
+ end
32
+ end
33
+
34
+ def get_next_from(id, event_types: nil, limit: 1000)
35
+ query = events_table.
36
+ order(:id).
37
+ where(Sequel.lit('id >= ?', id)).
38
+ limit(limit)
39
+ if event_types
40
+ query = query.where(type: event_types)
41
+ end
42
+ query.map do |event_row|
43
+ build_event(event_row)
44
+ end
45
+ end
46
+
47
+ def latest_event_id(event_types: nil)
48
+ latest_event = events_table
49
+ if event_types
50
+ latest_event = latest_event.where(type: event_types)
51
+ end
52
+ latest_event = latest_event.order(:id).last
53
+ if latest_event
54
+ latest_event[:id]
55
+ else
56
+ 0
57
+ end
58
+ end
59
+
60
+ def get_events_for_aggregate_id(aggregate_id)
61
+ events_table.where(aggregate_id: aggregate_id.to_str).order(:version).map do |event_hash|
62
+ build_event(event_hash)
63
+ end
64
+ end
65
+
66
+ def subscribe(from_id:, event_types: nil, after_listen: nil, subscription_master:, &block)
67
+ poll_waiter = OptimisedEventPollWaiter.new(pg_connection: @pg_connection, after_listen: after_listen)
68
+ args = {
69
+ poll_waiter: poll_waiter,
70
+ event_store: self,
71
+ from_event_id: from_id,
72
+ event_types: event_types,
73
+ events_table_name: @events_table_name,
74
+ subscription_master: subscription_master,
75
+ on_new_events: block
76
+ }
77
+ EventSourcery::EventStore::Subscription.new(args).tap do |s|
78
+ s.start
79
+ end
80
+ end
81
+
82
+ private
83
+
84
+ def events_table
85
+ @pg_connection[@events_table_name]
86
+ end
87
+
88
+ def build_event(data)
89
+ @event_builder.build(data)
90
+ end
91
+
92
+ def write_events_sql(aggregate_id, events, expected_version)
93
+ bodies = sql_literal_array(events, 'json', &:body)
94
+ types = sql_literal_array(events, 'varchar', &:type)
95
+ created_ats = sql_literal_array(events, 'timestamp without time zone', &:created_at)
96
+ event_uuids = sql_literal_array(events, 'uuid', &:uuid)
97
+ correlation_ids = sql_literal_array(events, 'uuid', &:correlation_id)
98
+ causation_ids = sql_literal_array(events, 'uuid', &:causation_id)
99
+ <<-SQL
100
+ select #{@write_events_function_name}(
101
+ #{sql_literal(aggregate_id.to_str, 'uuid')},
102
+ #{types},
103
+ #{sql_literal(expected_version, 'int')},
104
+ #{bodies},
105
+ #{created_ats},
106
+ #{event_uuids},
107
+ #{correlation_ids},
108
+ #{causation_ids},
109
+ #{sql_literal(@lock_table, 'boolean')}
110
+ );
111
+ SQL
112
+ end
113
+
114
+ def sql_literal_array(events, type, &block)
115
+ sql_array = events.map do |event|
116
+ to_sql_literal(block.call(event))
117
+ end.join(', ')
118
+ "array[#{sql_array}]::#{type}[]"
119
+ end
120
+
121
+ def sql_literal(value, type)
122
+ "#{to_sql_literal(value)}::#{type}"
123
+ end
124
+
125
+ def to_sql_literal(value)
126
+ return 'null' unless value
127
+ wrapped_value = if Time === value
128
+ value.iso8601(6)
129
+ elsif Hash === value
130
+ Sequel.pg_json(value)
131
+ else
132
+ value
133
+ end
134
+ @pg_connection.literal(wrapped_value)
135
+ end
136
+
137
+ def log_events_saved(events)
138
+ events.each do |event|
139
+ EventSourcery.logger.debug { "Saved event: #{event.inspect}" }
140
+ end
141
+ end
142
+ end
143
+ end
144
+ end