orfeas_lyra 1.0.0 → 1.0.1
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 +4 -4
- data/CHANGELOG.md +387 -0
- data/README.md +20 -8
- data/Rakefile +1 -1
- data/lib/generators/lyra/install/install_generator.rb +49 -0
- data/lib/generators/lyra/install/templates/create_lyra_tables.rb.tt +163 -0
- data/lib/generators/lyra/install/templates/initializer.rb.tt +22 -0
- data/lib/lyra/associations/habtm_links.rb +4 -0
- data/lib/lyra/bypass_events.rb +37 -5
- data/lib/lyra/command_handler.rb +5 -0
- data/lib/lyra/configuration.rb +32 -3
- data/lib/lyra/dual_view.rb +5 -2
- data/lib/lyra/effect_check.rb +52 -0
- data/lib/lyra/engine.rb +13 -0
- data/lib/lyra/erasure.rb +4 -4
- data/lib/lyra/event_store_adapter.rb +59 -0
- data/lib/lyra/genesis.rb +16 -4
- data/lib/lyra/interceptors/crud_interceptor.rb +70 -8
- data/lib/lyra/interceptors/lazy_reads.rb +54 -1
- data/lib/lyra/mode_sync.rb +86 -0
- data/lib/lyra/mode_transition.rb +96 -3
- data/lib/lyra/projections/async_checkpoint.rb +14 -1
- data/lib/lyra/projections/cached_relation.rb +194 -3
- data/lib/lyra/projections/lazy_projection.rb +496 -68
- data/lib/lyra/projections/model_projection.rb +12 -5
- data/lib/lyra/projections/rebuild.rb +163 -6
- data/lib/lyra/projections/unique_indexes.rb +193 -13
- data/lib/lyra/projections/uniqueness.rb +65 -2
- data/lib/lyra/repair.rb +3 -1
- data/lib/lyra/stream_heads.rb +309 -0
- data/lib/lyra/strict_data_access.rb +12 -4
- data/lib/lyra/verification/async_lock_order_net.rb +327 -0
- data/lib/lyra/verification/bypass_workflow.rb +3 -2
- data/lib/lyra/verification/concurrent_writers_net.rb +350 -0
- data/lib/lyra/verification/gate_settle_net.rb +208 -0
- data/lib/lyra/verification/lazy_catch_up_net.rb +228 -0
- data/lib/lyra/verification/lazy_lock_order_net.rb +221 -0
- data/lib/lyra/verification/multi_record_lock_net.rb +271 -0
- data/lib/lyra/verification/template_invariants.rb +71 -0
- data/lib/lyra/verification/trace_replay.rb +85 -0
- data/lib/lyra/version.rb +1 -1
- data/lib/lyra.rb +19 -0
- data/lib/tasks/lyra_projections.rake +9 -3
- metadata +14 -1
|
@@ -45,6 +45,13 @@ module Lyra
|
|
|
45
45
|
def _update_record(*args)
|
|
46
46
|
lyra_genesis_first_use
|
|
47
47
|
return super unless lyra_takes_over_write_here?
|
|
48
|
+
|
|
49
|
+
# The key names the record's stream: a change of it would be recorded
|
|
50
|
+
# on another record's stream (Hypothesis H, Lyra::StreamHeads).
|
|
51
|
+
pk = self.class.primary_key
|
|
52
|
+
if pk.is_a?(String) && will_save_change_to_attribute?(pk)
|
|
53
|
+
Lyra::StreamHeads.refuse_key_change!(self.class, attribute_in_database(pk), read_attribute(pk))
|
|
54
|
+
end
|
|
48
55
|
return lyra_hijack_with_row_write { lyra_hijack_update ? super(*args) : false } if lyra_hijack_atomically?
|
|
49
56
|
return false unless lyra_hijack_mode? ? lyra_hijack_update : lyra_prepare_event_source_update
|
|
50
57
|
|
|
@@ -196,6 +203,12 @@ module Lyra
|
|
|
196
203
|
after_update :lyra_finalize_event_source, if: :lyra_event_sourcing_mode?
|
|
197
204
|
after_destroy :lyra_finalize_event_source, if: :lyra_event_sourcing_mode?
|
|
198
205
|
|
|
206
|
+
# H2, opt-in (config.check_effects): the row as written against its
|
|
207
|
+
# events, after the row write and in its transaction (Lyra::EffectCheck).
|
|
208
|
+
after_create :lyra_check_effect, if: :lyra_checks_effects?
|
|
209
|
+
after_update :lyra_check_effect, if: :lyra_checks_effects?
|
|
210
|
+
after_destroy :lyra_check_effect, if: :lyra_checks_effects?
|
|
211
|
+
|
|
199
212
|
# Sampled DualView verification after commit (Lyra::DualViewSampler);
|
|
200
213
|
# off unless config.dual_view_sample_rate is above 0.
|
|
201
214
|
after_commit :lyra_sample_dual_view, if: :lyra_events_enabled?
|
|
@@ -589,6 +602,12 @@ module Lyra
|
|
|
589
602
|
define_method(name) do |*args, **kwargs, &block|
|
|
590
603
|
return super(*args, **kwargs, &block) unless lyra_read_from_events? && current_scope.nil?
|
|
591
604
|
|
|
605
|
+
# Inside where(...).scoping { } (ES-NoProj keeps that scope itself,
|
|
606
|
+
# so current_scope is nil): through the scoped relation, whose rows
|
|
607
|
+
# take its attributes, as Active Record's InsertAll gives them.
|
|
608
|
+
scoped = Lyra::Projections::CachedRelation.scoped_for(self)
|
|
609
|
+
return scoped.public_send(name, *args, **kwargs, &block) if scoped
|
|
610
|
+
|
|
592
611
|
begin
|
|
593
612
|
previous = Thread.current[:lyra_bypass_read_override]
|
|
594
613
|
Thread.current[:lyra_bypass_read_override] = true
|
|
@@ -713,6 +732,15 @@ module Lyra
|
|
|
713
732
|
lyra_monitored? && Lyra.event_sourcing_mode?
|
|
714
733
|
end
|
|
715
734
|
|
|
735
|
+
def lyra_checks_effects?
|
|
736
|
+
lyra_monitored? && Lyra::EffectCheck.applies?
|
|
737
|
+
end
|
|
738
|
+
|
|
739
|
+
def lyra_check_effect
|
|
740
|
+
Lyra::EffectCheck.verify!(self)
|
|
741
|
+
end
|
|
742
|
+
|
|
743
|
+
|
|
716
744
|
def lyra_takes_over_write?
|
|
717
745
|
lyra_hijack_mode? || lyra_event_sourcing_mode?
|
|
718
746
|
end
|
|
@@ -738,6 +766,20 @@ module Lyra
|
|
|
738
766
|
rows, @lyra_rows_updated = @lyra_rows_updated, nil
|
|
739
767
|
return if rows == 0 || previous_changes.empty?
|
|
740
768
|
|
|
769
|
+
# A changed primary key: the table now holds the record under the new
|
|
770
|
+
# key, so the log records what the table did, the old key's record
|
|
771
|
+
# destroyed and the new key's created (from 1.0.1; 1.0.0 recorded an
|
|
772
|
+
# update on the new key's stream, which had no create).
|
|
773
|
+
pk = self.class.primary_key
|
|
774
|
+
if pk.is_a?(String) && saved_change_to_attribute?(pk) && Lyra::StreamHeads.enabled?
|
|
775
|
+
old_key = attribute_before_last_save(pk)
|
|
776
|
+
gone = Lyra::EventData.build(self.class, old_key, :destroyed, attributes: {}, changes: {})
|
|
777
|
+
.merge(metadata: { source: "lyra_interceptor" }.merge(lyra_event_metadata(:destroyed)))
|
|
778
|
+
publish_event(:destroyed, gone, stream_name: Lyra.stream_name(self.class, old_key))
|
|
779
|
+
publish_event(:created, build_event_data(:created))
|
|
780
|
+
return
|
|
781
|
+
end
|
|
782
|
+
|
|
741
783
|
event_data = build_event_data(:updated)
|
|
742
784
|
publish_event(:updated, event_data)
|
|
743
785
|
ensure
|
|
@@ -751,10 +793,15 @@ module Lyra
|
|
|
751
793
|
# deleted the row) and one of a record that was not persisted (a new
|
|
752
794
|
# one, or a copy destroyed twice), which runs no DELETE (WriteHooks#
|
|
753
795
|
# destroy sets 0). A second Destroyed makes the stream ill-formed. nil
|
|
754
|
-
# means no count was taken:
|
|
755
|
-
#
|
|
796
|
+
# means no count was taken: the destroy callbacks ran without Active
|
|
797
|
+
# Record's destroy, a soft delete (paranoia's paranoia_destroy, which
|
|
798
|
+
# keeps the row). It records nothing itself from 1.0.1: what it writes
|
|
799
|
+
# (deleted_at, through update_columns or a save) is recorded as the
|
|
800
|
+
# update it is, so the stream follows the row, which is still there.
|
|
801
|
+
# 1.0.0 recorded a Destroyed, and the record's stream ended while its
|
|
802
|
+
# row stayed.
|
|
756
803
|
rows, @lyra_rows_deleted = @lyra_rows_deleted, nil
|
|
757
|
-
return if @lyra_hijacked || rows == 0
|
|
804
|
+
return if @lyra_hijacked || rows == 0 || (rows.nil? && !destroyed?)
|
|
758
805
|
|
|
759
806
|
event_data = build_event_data(:destroyed)
|
|
760
807
|
publish_event(:destroyed, event_data)
|
|
@@ -881,7 +928,12 @@ module Lyra
|
|
|
881
928
|
def lyra_lock_aggregate_before_validation
|
|
882
929
|
return unless persisted? && Lyra::Projections::Uniqueness.reads_events?(self.class)
|
|
883
930
|
return unless Lyra.config.lock_aggregate_before_append
|
|
884
|
-
|
|
931
|
+
# Only for a validation no unique index covers (Uniqueness.index_covered?):
|
|
932
|
+
# one an index covers takes no value lock, so there is nothing to order.
|
|
933
|
+
return unless self.class.validators.any? do |validator|
|
|
934
|
+
validator.is_a?(ActiveRecord::Validations::UniquenessValidator) &&
|
|
935
|
+
validator.attributes.any? { !Lyra::Projections::Uniqueness.index_covered?(self.class, _1, validator.options) }
|
|
936
|
+
end
|
|
885
937
|
|
|
886
938
|
self.class.with_connection do |connection|
|
|
887
939
|
next unless connection.transaction_open?
|
|
@@ -1052,7 +1104,7 @@ module Lyra
|
|
|
1052
1104
|
|
|
1053
1105
|
changed = changed_attribute_names_to_save
|
|
1054
1106
|
# Nothing built for an update that sets no indexed column.
|
|
1055
|
-
return nil unless changed.intersect?(Lyra::Projections::UniqueIndexes.
|
|
1107
|
+
return nil unless changed.intersect?(Lyra::Projections::UniqueIndexes.watched_columns(self.class))
|
|
1056
1108
|
|
|
1057
1109
|
written = changed.to_h { |name| [name, read_attribute(name)] }
|
|
1058
1110
|
Lyra::Projections::UniqueIndexes.update_claims(self.class, id_in_database, written)
|
|
@@ -1170,7 +1222,17 @@ module Lyra
|
|
|
1170
1222
|
# under REPEATABLE READ). It now fails the write, as Monitor's INSERT
|
|
1171
1223
|
# or UPDATE fails it.
|
|
1172
1224
|
def lyra_run_sync_projection(operation, result)
|
|
1173
|
-
Lyra::Projections::ModelProjection.project(self.class, operation, result, INTERNAL)
|
|
1225
|
+
projected = Lyra::Projections::ModelProjection.project(self.class, operation, result, INTERNAL)
|
|
1226
|
+
# The table's primary key, as Monitor's INSERT meets it: a row already
|
|
1227
|
+
# holds the key, so the create is refused with its event, in the same
|
|
1228
|
+
# transaction (from 1.0.1; 1.0.0 skipped the insert and kept the event).
|
|
1229
|
+
# The stream heads refuse a live key before this; this catches a row
|
|
1230
|
+
# with no live stream (one written around Lyra).
|
|
1231
|
+
if operation == :create && projected == :key_taken && Lyra::StreamHeads.enabled?
|
|
1232
|
+
raise Lyra::StreamHeads::LiveKeyError, "Lyra: #{self.class.name} #{id}: a row already holds this key; the create is refused"
|
|
1233
|
+
end
|
|
1234
|
+
|
|
1235
|
+
projected
|
|
1174
1236
|
rescue ActiveRecord::StatementInvalid
|
|
1175
1237
|
raise
|
|
1176
1238
|
rescue => e
|
|
@@ -1313,7 +1375,7 @@ module Lyra
|
|
|
1313
1375
|
end
|
|
1314
1376
|
end
|
|
1315
1377
|
|
|
1316
|
-
def publish_event(operation, data)
|
|
1378
|
+
def publish_event(operation, data, stream_name: lyra_stream_name)
|
|
1317
1379
|
# Extract metadata from data and pass separately to RailsEventStore
|
|
1318
1380
|
metadata = Lyra::Privacy.stamp(self.class, data, data.delete(:metadata) || {})
|
|
1319
1381
|
# The CRUD event, or the domain events the model's rules choose
|
|
@@ -1325,7 +1387,7 @@ module Lyra
|
|
|
1325
1387
|
event_id: lyra_take_own_event_id
|
|
1326
1388
|
)
|
|
1327
1389
|
|
|
1328
|
-
Lyra.append_events(events, stream_name:
|
|
1390
|
+
Lyra.append_events(events, stream_name: stream_name)
|
|
1329
1391
|
lyra_own_event_appended!
|
|
1330
1392
|
rescue => e
|
|
1331
1393
|
# Its event is not in the log, so the writes made next do not name it
|
|
@@ -16,7 +16,19 @@ module Lyra
|
|
|
16
16
|
module Querying
|
|
17
17
|
def _query_by_sql(*args, **kwargs, &block)
|
|
18
18
|
Lyra::Projections::LazyProjection.before_read(self)
|
|
19
|
-
super
|
|
19
|
+
result = super
|
|
20
|
+
# A locking read (lock, lock!, with_lock): the catch-up above ran
|
|
21
|
+
# before the lock was granted, and the lock's previous holder may have
|
|
22
|
+
# committed events the row does not have yet. Under the row lock and
|
|
23
|
+
# the records' stream heads, which no writer of the records can pass,
|
|
24
|
+
# the records behind their streams are replayed, and the read runs
|
|
25
|
+
# again (from 1.0.1; 1.0.0 returned the row as the catch-up before the
|
|
26
|
+
# lock left it, and an update made under the lock could be lost).
|
|
27
|
+
if !kwargs[:async] && Lyra::Projections::LazyProjection.locked_read?(args[1]) &&
|
|
28
|
+
Lyra::Projections::LazyProjection.bring_locked_up_to_date(self, args[0], result).positive?
|
|
29
|
+
result = super
|
|
30
|
+
end
|
|
31
|
+
result
|
|
20
32
|
end
|
|
21
33
|
end
|
|
22
34
|
|
|
@@ -35,11 +47,52 @@ module Lyra
|
|
|
35
47
|
Lyra::Projections::LazyProjection.before_read(klass)
|
|
36
48
|
super
|
|
37
49
|
end
|
|
50
|
+
|
|
51
|
+
# Model.lock.find(ids): the records' aggregate locks before the row
|
|
52
|
+
# locks the query takes, the order ES-Lazy's writers take them in (the
|
|
53
|
+
# aggregate lock, then the row, then the stream head; the lock-order
|
|
54
|
+
# net, Lyra::Verification::LazyLockOrderNet).
|
|
55
|
+
def find(*args, &block)
|
|
56
|
+
if lock_value && Lyra::Projections::LazyProjection.orders_locking_reads?
|
|
57
|
+
ids = args.flatten
|
|
58
|
+
Lyra::Projections::LazyProjection.take_aggregate_locks(klass, ids) if ids.all? { _1.is_a?(Integer) || _1.is_a?(String) }
|
|
59
|
+
end
|
|
60
|
+
super
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
private
|
|
64
|
+
|
|
65
|
+
# Any other locking load (Model.lock.where(...), lock with a join): the
|
|
66
|
+
# keys it selects are read first without the lock, their aggregate
|
|
67
|
+
# locks taken (LazyProjection.lock_selection), and then the locking
|
|
68
|
+
# query runs. Eager loads and selections without the primary key run
|
|
69
|
+
# as before (the CHANGELOG's known issues).
|
|
70
|
+
def exec_main_query(async: false)
|
|
71
|
+
return super if async || !lock_value || Thread.current[:lyra_locking_selection] || eager_loading?
|
|
72
|
+
return super unless klass.respond_to?(:lyra_monitored) && klass.lyra_monitored
|
|
73
|
+
return super unless Lyra::Projections::LazyProjection.orders_locking_reads?
|
|
74
|
+
return super unless (pk = klass.primary_key).is_a?(String) && klass.with_connection(&:transaction_open?)
|
|
75
|
+
|
|
76
|
+
Lyra::Projections::LazyProjection.lock_selection(klass, pk, -> { unscope(:lock).pluck(pk) }) { super(async: false) }
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
# A record's lock! (and with_lock, which calls it): its aggregate lock
|
|
81
|
+
# before the row lock, as for Relation#find above; in ES-NoProj before
|
|
82
|
+
# the reload reads its stream (CachedRelation#find for lock.find).
|
|
83
|
+
module Locking
|
|
84
|
+
def lock!(*args, **kwargs)
|
|
85
|
+
if persisted? && Lyra::Projections::LazyProjection.orders_locking_reads?
|
|
86
|
+
Lyra::Projections::LazyProjection.take_aggregate_locks(self.class, [id])
|
|
87
|
+
end
|
|
88
|
+
super
|
|
89
|
+
end
|
|
38
90
|
end
|
|
39
91
|
|
|
40
92
|
def self.install!
|
|
41
93
|
ActiveRecord::Base.singleton_class.prepend(Querying) unless ActiveRecord::Base.singleton_class.ancestors.include?(Querying)
|
|
42
94
|
ActiveRecord::Relation.prepend(Relation) unless ActiveRecord::Relation.ancestors.include?(Relation)
|
|
95
|
+
ActiveRecord::Locking::Pessimistic.prepend(Locking) unless ActiveRecord::Locking::Pessimistic.ancestors.include?(Locking)
|
|
43
96
|
end
|
|
44
97
|
end
|
|
45
98
|
end
|
data/lib/lyra/mode_sync.rb
CHANGED
|
@@ -31,12 +31,20 @@ module Lyra
|
|
|
31
31
|
# process's own in-process changes through the raw config.mode = setter
|
|
32
32
|
# (tests, benchmark harnesses) are left alone.
|
|
33
33
|
#
|
|
34
|
+
# A process whose boot check did not run (a rake task; any process with the
|
|
35
|
+
# gate off) has not looked when it boots, and may have booted in a stale
|
|
36
|
+
# mode: at its first check it adopts the application's, unless it has set
|
|
37
|
+
# its mode since boot (any mode, the one it booted in too) and the switch is
|
|
38
|
+
# older than the boot (remember_boot!). The configuration applied again by a
|
|
39
|
+
# code reload is not a set.
|
|
40
|
+
#
|
|
34
41
|
# config.mode_sync: nil (default) follows the Mode Transition Safety gate
|
|
35
42
|
# (on everywhere but the test environment); true; false.
|
|
36
43
|
module ModeSync
|
|
37
44
|
@mutex = Mutex.new
|
|
38
45
|
@last_seen_id = nil
|
|
39
46
|
@checked_at = nil
|
|
47
|
+
@boot = nil
|
|
40
48
|
|
|
41
49
|
class << self
|
|
42
50
|
attr_reader :last_seen_id
|
|
@@ -103,6 +111,12 @@ module Lyra
|
|
|
103
111
|
return nil
|
|
104
112
|
end
|
|
105
113
|
|
|
114
|
+
# After the two touch checks, which must hold whatever set the mode.
|
|
115
|
+
if set_since_boot?(row)
|
|
116
|
+
@last_seen_id = row[:id]
|
|
117
|
+
return nil
|
|
118
|
+
end
|
|
119
|
+
|
|
106
120
|
if (refusal = ModeTransition.adoption_refusal(row))
|
|
107
121
|
@last_seen_id = row[:id]
|
|
108
122
|
Rails.logger.error("Lyra: did not adopt the application's mode #{row[:config]}; this process stays in " \
|
|
@@ -127,15 +141,79 @@ module Lyra
|
|
|
127
141
|
end
|
|
128
142
|
end
|
|
129
143
|
|
|
144
|
+
# At the end of initialization (Engine), where the boot check marked
|
|
145
|
+
# nothing seen: the latest applied id then, from which on the process's
|
|
146
|
+
# own sets are its own (mode_set!). Not seen!: a process that merely
|
|
147
|
+
# booted still adopts that row.
|
|
148
|
+
# It creates no table and keeps no connection it opened (db:drop needs
|
|
149
|
+
# the database free of sessions). When the database cannot be read,
|
|
150
|
+
# nothing is remembered, and the first check adopts as it finds.
|
|
151
|
+
def remember_boot! # :nodoc:
|
|
152
|
+
@boot = nil
|
|
153
|
+
return if @last_seen_id || !enabled?
|
|
154
|
+
|
|
155
|
+
id = latest_id_at_boot
|
|
156
|
+
# Assigned last: loading Active Record may run the application's
|
|
157
|
+
# configuration, which is not a set.
|
|
158
|
+
@boot = { id: id, set: false }
|
|
159
|
+
rescue StandardError => e
|
|
160
|
+
Rails.logger&.debug("Lyra: the applied mode not read at boot (#{e.class}: #{e.message})")
|
|
161
|
+
end
|
|
162
|
+
|
|
163
|
+
def forget_boot! # :nodoc:
|
|
164
|
+
@boot = nil
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
# The process set its mode (Configuration's mode setters), unless the
|
|
168
|
+
# code reload in progress on this thread applies the configuration again.
|
|
169
|
+
def mode_set! # :nodoc:
|
|
170
|
+
boot = @boot
|
|
171
|
+
return if boot.nil? || boot[:set] || Thread.current[:lyra_reapplying_configuration]
|
|
172
|
+
|
|
173
|
+
@boot = boot.merge(set: true)
|
|
174
|
+
end
|
|
175
|
+
|
|
176
|
+
# Around the reloader's prepare! (a code reload's to_prepare blocks).
|
|
177
|
+
def reapplying_configuration # :nodoc:
|
|
178
|
+
previous = Thread.current[:lyra_reapplying_configuration]
|
|
179
|
+
Thread.current[:lyra_reapplying_configuration] = true
|
|
180
|
+
yield
|
|
181
|
+
ensure
|
|
182
|
+
Thread.current[:lyra_reapplying_configuration] = previous
|
|
183
|
+
end
|
|
184
|
+
|
|
130
185
|
def reset!
|
|
131
186
|
@mutex.synchronize do
|
|
132
187
|
@last_seen_id = nil
|
|
133
188
|
@checked_at = nil
|
|
189
|
+
@boot = nil
|
|
134
190
|
end
|
|
135
191
|
end
|
|
136
192
|
|
|
137
193
|
private
|
|
138
194
|
|
|
195
|
+
# Whether this process set its mode after a boot that +row+ predates.
|
|
196
|
+
def set_since_boot?(row)
|
|
197
|
+
@boot && @boot[:set] && row[:id] <= @boot[:id]
|
|
198
|
+
end
|
|
199
|
+
|
|
200
|
+
# 0 without a table or a row.
|
|
201
|
+
def latest_id_at_boot
|
|
202
|
+
pool = ActiveRecord::Base.connection_pool
|
|
203
|
+
connected = pool.connected?
|
|
204
|
+
# SQLite creates the file on connecting, and db:create would find it.
|
|
205
|
+
db = pool.db_config
|
|
206
|
+
return 0 if !connected && db.adapter == "sqlite3" && !File.exist?(File.expand_path(db.database, Rails.root))
|
|
207
|
+
|
|
208
|
+
pool.with_connection do |c|
|
|
209
|
+
next 0 unless c.table_exists?(ModeTransition::TABLE)
|
|
210
|
+
|
|
211
|
+
c.select_value("SELECT MAX(id) FROM #{ModeTransition::TABLE} WHERE kind = 'applied'").to_i
|
|
212
|
+
end
|
|
213
|
+
ensure
|
|
214
|
+
pool.disconnect if connected == false
|
|
215
|
+
end
|
|
216
|
+
|
|
139
217
|
def due_in
|
|
140
218
|
return 0 unless @checked_at
|
|
141
219
|
|
|
@@ -158,6 +236,14 @@ module Lyra
|
|
|
158
236
|
end
|
|
159
237
|
end
|
|
160
238
|
|
|
239
|
+
# Prepended onto the application's reloader: a code reload applies the
|
|
240
|
+
# configuration again, which is no set of the process's own.
|
|
241
|
+
module Reloads
|
|
242
|
+
def prepare!
|
|
243
|
+
ModeSync.reapplying_configuration { super }
|
|
244
|
+
end
|
|
245
|
+
end
|
|
246
|
+
|
|
161
247
|
# Rack middleware: adopt a switch made elsewhere before each request.
|
|
162
248
|
class Middleware
|
|
163
249
|
def initialize(app)
|
data/lib/lyra/mode_transition.rb
CHANGED
|
@@ -55,6 +55,10 @@ module Lyra
|
|
|
55
55
|
end
|
|
56
56
|
end
|
|
57
57
|
|
|
58
|
+
# Rolls a rebuilding check's transaction back (check).
|
|
59
|
+
class DiscardRebuild < StandardError; end
|
|
60
|
+
private_constant :DiscardRebuild
|
|
61
|
+
|
|
58
62
|
Discrepancy = Struct.new(:model, :id, :problem, :details, keyword_init: true) do
|
|
59
63
|
def to_s = "#{model} #{id}: #{problem}#{" (#{details})" if details}"
|
|
60
64
|
end
|
|
@@ -129,6 +133,9 @@ module Lyra
|
|
|
129
133
|
# refused). TouchRegistry.serialize.
|
|
130
134
|
id = TouchRegistry.serialize(to) do
|
|
131
135
|
refuse_unrecorded_touches!(from, to)
|
|
136
|
+
# A switch is the application's: if recording it fails, ModeSync
|
|
137
|
+
# does not keep it as this process's own change.
|
|
138
|
+
ModeSync.forget_boot!
|
|
132
139
|
apply(mode, projection_mode)
|
|
133
140
|
# forced: the gate was required and the operator overrode it.
|
|
134
141
|
record_applied(to, from: from, forced: force && gate_enabled? && gate_required?(from, to),
|
|
@@ -216,16 +223,56 @@ module Lyra
|
|
|
216
223
|
|
|
217
224
|
# Compare every monitored record's row with its events. Returns a
|
|
218
225
|
# Report; stores a certificate when it is clean.
|
|
226
|
+
#
|
|
227
|
+
# With rebuild: true, leaving a mode whose tables lag the log, the
|
|
228
|
+
# tables are rebuilt from the log (Rebuild.rebuild, which refuses to
|
|
229
|
+
# clear a table whose rows the log cannot all restore) and then
|
|
230
|
+
# compared, in one transaction (a savepoint inside the caller's) that
|
|
231
|
+
# is rolled back unless the check is clean: a check that fails, or
|
|
232
|
+
# raises, leaves the tables as they were (from 1.0.1; before, the
|
|
233
|
+
# rebuild committed first). A clean check keeps the rebuilt tables and
|
|
234
|
+
# its certificate.
|
|
219
235
|
def check(to:, from: current, models: Lyra.config.monitored_models, rebuild: false, batch_size: 1_000)
|
|
220
236
|
# With record_touches false DualView takes timestamp-only differences
|
|
221
237
|
# as agreement, and a process that leaves touches out moves rows its
|
|
222
238
|
# events do not show: no certificate may come of either.
|
|
223
239
|
refuse_unrecorded_touches!(from, to)
|
|
240
|
+
return run_check(to, from, models, false, batch_size) unless rebuild && LAGGING.include?(from)
|
|
241
|
+
|
|
242
|
+
report = nil
|
|
243
|
+
begin
|
|
244
|
+
in_transactions([ActiveRecord::Base, *models]) do
|
|
245
|
+
report = run_check(to, from, models, true, batch_size)
|
|
246
|
+
raise DiscardRebuild unless report.clean?
|
|
247
|
+
end
|
|
248
|
+
rescue DiscardRebuild
|
|
249
|
+
report.rebuilt = 0
|
|
250
|
+
rescue Lyra::Projections::Rebuild::Refused => e
|
|
251
|
+
raise Refused, "Lyra refuses to check #{from} -> #{to} with rebuild: true; no table was changed. #{e.message} " \
|
|
252
|
+
"The check's rebuild takes neither option: rebuild the tables first (rake " \
|
|
253
|
+
"lyra:projections:rebuild with TRUNCATE=false or FORCE=1), then check without REBUILD."
|
|
254
|
+
end
|
|
255
|
+
report
|
|
256
|
+
end
|
|
257
|
+
|
|
258
|
+
# A transaction on each database +models+ use (each a savepoint inside
|
|
259
|
+
# a transaction already open), around the block.
|
|
260
|
+
private def in_transactions(models, &block)
|
|
261
|
+
one_per_pool = models.select { _1.respond_to?(:connection_pool) }.uniq(&:connection_pool)
|
|
262
|
+
one_per_pool.reverse.reduce(block) { |inner, model| -> { model.transaction(requires_new: true) { inner.call } } }.call
|
|
263
|
+
end
|
|
264
|
+
|
|
265
|
+
# check, once it has decided whether to rebuild.
|
|
266
|
+
private def run_check(to, from, models, rebuild, batch_size)
|
|
224
267
|
started_at = Time.current
|
|
225
|
-
|
|
268
|
+
discrepancies = []
|
|
269
|
+
# The position the re-check starts from, settled before anything is
|
|
270
|
+
# read: an event below it that was not yet visible has committed (or
|
|
271
|
+
# rolled back) by the time the catch-up and the comparison run.
|
|
272
|
+
position, settled = settled_position
|
|
273
|
+
in_flight!(discrepancies, position, "check") unless settled
|
|
226
274
|
imported = 0
|
|
227
275
|
rebuilt = 0
|
|
228
|
-
discrepancies = []
|
|
229
276
|
unrepresentable = 0
|
|
230
277
|
|
|
231
278
|
# A row its model cannot represent refuses the model's import (nothing
|
|
@@ -259,6 +306,12 @@ module Lyra
|
|
|
259
306
|
end
|
|
260
307
|
end
|
|
261
308
|
|
|
309
|
+
# The position the certificate keeps, settled the same way before the
|
|
310
|
+
# re-check reads what changed since the first one.
|
|
311
|
+
final_position, settled = settled_position
|
|
312
|
+
in_flight!(discrepancies, final_position, "check") unless settled
|
|
313
|
+
# What those writes appended, ES-Lazy applies now, as it did at the start.
|
|
314
|
+
Lyra::Projections::LazyProjection.catch_up!(force: true) if from == "event_sourcing/lazy"
|
|
262
315
|
changed = changed_since(models - refused, position, started_at)
|
|
263
316
|
changed.each do |model, ids|
|
|
264
317
|
discrepancies.reject! { |d| d.model == model.name && ids.include?(d.id.to_s) }
|
|
@@ -267,7 +320,7 @@ module Lyra
|
|
|
267
320
|
|
|
268
321
|
report = Report.new(from: from, to: to, checked: checked, rechecked: changed.values.sum(&:size),
|
|
269
322
|
imported: imported, rebuilt: rebuilt, discrepancies: discrepancies, unrepresentable: unrepresentable,
|
|
270
|
-
position:
|
|
323
|
+
position: final_position, started_at: started_at, finished_at: Time.current)
|
|
271
324
|
# A process may have begun leaving touches out while the check ran: the
|
|
272
325
|
# last look and the certificate under the registry's lock.
|
|
273
326
|
TouchRegistry.serialize(to) do
|
|
@@ -431,8 +484,12 @@ module Lyra
|
|
|
431
484
|
return nil if certified_at < Time.current - Lyra.config.mode_transition_certificate_ttl
|
|
432
485
|
|
|
433
486
|
models = Lyra.config.monitored_models
|
|
487
|
+
# Writes in flight now end first, so the re-check sees what they
|
|
488
|
+
# committed (the certificate's own position is settled: run_check).
|
|
489
|
+
_, settled = settled_position
|
|
434
490
|
changed = changed_since(models, row["position"].to_i, certified_at)
|
|
435
491
|
discrepancies = changed.flat_map { |model, ids| ids.filter_map { |id| compare(model, id) } }
|
|
492
|
+
in_flight!(discrepancies, row["position"].to_i, "switch") unless settled
|
|
436
493
|
Report.new(from: from, to: to, checked: 0, rechecked: changed.values.sum(&:size), imported: 0, rebuilt: 0,
|
|
437
494
|
discrepancies: discrepancies, position: event_position, started_at: certified_at,
|
|
438
495
|
finished_at: Time.current, certificate_id: row["id"].to_i)
|
|
@@ -556,6 +613,42 @@ module Lyra
|
|
|
556
613
|
def event_position
|
|
557
614
|
sql(:select_value, "SELECT COALESCE(MAX(id), 0) FROM event_store_events").to_i
|
|
558
615
|
end
|
|
616
|
+
|
|
617
|
+
# The event store's position, settled (from 1.0.1): read, then, on
|
|
618
|
+
# PostgreSQL, every writing transaction of this database running at that
|
|
619
|
+
# moment (pg_stat_activity.backend_xid) waited for, at most
|
|
620
|
+
# config.mode_transition_settle_timeout seconds. A transaction Lyra writes in
|
|
621
|
+
# holds a transaction id before its first event takes an id (it writes the
|
|
622
|
+
# record's stream head first), so an event below the position that was not
|
|
623
|
+
# yet visible belongs to one of them, and a read after this one sees it
|
|
624
|
+
# (1.0.0 read the position alone, and a write in flight across the check was
|
|
625
|
+
# never re-checked). Returns [position, whether they all ended].
|
|
626
|
+
def settled_position
|
|
627
|
+
position = event_position
|
|
628
|
+
return [position, true] unless postgres?
|
|
629
|
+
|
|
630
|
+
running = sql(:select_values,
|
|
631
|
+
"SELECT backend_xid::text FROM pg_stat_activity WHERE datname = current_database() " \
|
|
632
|
+
"AND backend_xid IS NOT NULL AND pid <> pg_backend_pid()")
|
|
633
|
+
return [position, true] if running.empty?
|
|
634
|
+
|
|
635
|
+
list = running.map { q(_1) }.join(", ")
|
|
636
|
+
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + Lyra.config.mode_transition_settle_timeout
|
|
637
|
+
loop do
|
|
638
|
+
still = sql(:select_value, "SELECT count(*) FROM pg_stat_activity WHERE backend_xid::text IN (#{list})").to_i
|
|
639
|
+
return [position, true] if still.zero?
|
|
640
|
+
return [position, false] if Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline
|
|
641
|
+
|
|
642
|
+
sleep 0.05
|
|
643
|
+
end
|
|
644
|
+
end
|
|
645
|
+
|
|
646
|
+
def in_flight!(discrepancies, position, at)
|
|
647
|
+
discrepancies << Discrepancy.new(model: "(event store)", id: position, problem: "a write in flight at the #{at} did not end",
|
|
648
|
+
details: "waited #{Lyra.config.mode_transition_settle_timeout} s")
|
|
649
|
+
end
|
|
650
|
+
|
|
651
|
+
def postgres? = ActiveRecord::Base.with_connection { _1.adapter_name.match?(/postg/i) }
|
|
559
652
|
|
|
560
653
|
# Created on first use, so the gate needs no migration. False when the
|
|
561
654
|
# database cannot be reached (assets precompilation, a first setup).
|
|
@@ -55,12 +55,25 @@ module Lyra
|
|
|
55
55
|
connection.select_values(<<~SQL.squish, "Lyra ES-Async rows behind")
|
|
56
56
|
SELECT DISTINCT s.stream FROM event_store_events_in_streams s
|
|
57
57
|
LEFT JOIN #{TABLE} c ON c.stream = s.stream
|
|
58
|
-
LEFT JOIN event_store_events_in_streams cs ON cs.stream = c.stream AND
|
|
58
|
+
LEFT JOIN event_store_events_in_streams cs ON cs.stream = c.stream AND #{event_match(connection)}
|
|
59
59
|
WHERE s.stream IN (#{list}) AND (cs.id IS NULL OR s.id > cs.id)
|
|
60
60
|
SQL
|
|
61
61
|
end
|
|
62
62
|
end
|
|
63
63
|
|
|
64
|
+
# The checkpoint's event in the store: event_id is a string column in
|
|
65
|
+
# Rails Event Store's default schema and a uuid in some (Solidus's), and
|
|
66
|
+
# PostgreSQL compares no uuid with a string column (from 1.0.1, when a
|
|
67
|
+
# locking read in ES-Async came to run this query: Lyra::StreamHeads
|
|
68
|
+
# matches its event the same way).
|
|
69
|
+
def event_match(connection)
|
|
70
|
+
@event_match ||= {}
|
|
71
|
+
@event_match[connection.pool.db_config.name] ||= begin
|
|
72
|
+
column = connection.columns("event_store_events_in_streams").find { _1.name == "event_id" }
|
|
73
|
+
column&.type == :uuid ? "cs.event_id = c.event_id::uuid" : "cs.event_id = c.event_id"
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
|
|
64
77
|
# Forget every checkpoint (tests; after the tables were truncated).
|
|
65
78
|
def reset!(connection = nil)
|
|
66
79
|
return ActiveRecord::Base.with_connection { |c| reset!(c) } unless connection
|