pg_eventstore 1.13.2 → 1.13.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +11 -3
  3. data/lib/pg_eventstore/event.rb +2 -0
  4. data/lib/pg_eventstore/queries/event_queries.rb +4 -3
  5. data/lib/pg_eventstore/queries/partition_queries.rb +71 -6
  6. data/lib/pg_eventstore/query_builders/events_filtering.rb +1 -5
  7. data/lib/pg_eventstore/query_builders/partitions_filtering.rb +26 -16
  8. data/lib/pg_eventstore/sql_builder.rb +30 -12
  9. data/lib/pg_eventstore/subscriptions/callback_handlers/events_processor_handlers.rb +8 -3
  10. data/lib/pg_eventstore/subscriptions/callback_handlers/subscription_runner_handlers.rb +9 -0
  11. data/lib/pg_eventstore/subscriptions/events_processor.rb +7 -3
  12. data/lib/pg_eventstore/subscriptions/queries/service_queries.rb +73 -0
  13. data/lib/pg_eventstore/subscriptions/queries/subscription_queries.rb +1 -0
  14. data/lib/pg_eventstore/subscriptions/subscription.rb +11 -1
  15. data/lib/pg_eventstore/subscriptions/subscription_feeder.rb +7 -1
  16. data/lib/pg_eventstore/subscriptions/subscription_position_evaluation.rb +195 -0
  17. data/lib/pg_eventstore/subscriptions/subscription_runner.rb +18 -2
  18. data/lib/pg_eventstore/subscriptions/subscription_runners_feeder.rb +1 -1
  19. data/lib/pg_eventstore/subscriptions/subscriptions_manager.rb +13 -1
  20. data/lib/pg_eventstore/subscriptions/synchronized_array.rb +41 -0
  21. data/lib/pg_eventstore/version.rb +1 -1
  22. data/lib/pg_eventstore/web/paginator/events_collection.rb +1 -1
  23. data/lib/pg_eventstore/web/paginator/stream_ids_collection.rb +2 -2
  24. data/rbs_collection.lock.yaml +9 -1
  25. data/rbs_collection.yaml +2 -0
  26. data/sig/manifest.yaml +3 -0
  27. data/sig/pg_eventstore/event.rbs +3 -1
  28. data/sig/pg_eventstore/queries/partition_queries.rbs +5 -1
  29. data/sig/pg_eventstore/query_builders/partitions_filtering.rbs +9 -5
  30. data/sig/pg_eventstore/sql_builder.rbs +8 -2
  31. data/sig/pg_eventstore/subscriptions/callback_handlers/events_processor_handlers.rbs +2 -1
  32. data/sig/pg_eventstore/subscriptions/callback_handlers/subscription_runner_handlers.rbs +3 -0
  33. data/sig/pg_eventstore/subscriptions/queries/service_queries.rbs +15 -0
  34. data/sig/pg_eventstore/subscriptions/subscription.rbs +2 -0
  35. data/sig/pg_eventstore/subscriptions/subscription_feeder.rbs +2 -0
  36. data/sig/pg_eventstore/subscriptions/subscription_position_evaluation.rbs +53 -0
  37. data/sig/pg_eventstore/subscriptions/subscription_runner.rbs +3 -2
  38. data/sig/pg_eventstore/subscriptions/subscriptions_manager.rbs +2 -0
  39. data/sig/pg_eventstore/subscriptions/synchronized_array.rbs +4 -0
  40. metadata +8 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 5411bc50e9e33cb1e75d41e3e0955ea68b2f4964a431a039a773727e14575840
4
- data.tar.gz: cb0d9c313a28ea13be313bd6c7f7760513b85ad3f4a660ab66588ef2fc1a6441
3
+ metadata.gz: 94443dc3aa36701d5e126573a5babdd4585932d803b766b06b94c861f6b4ef5a
4
+ data.tar.gz: 86fcca21a3a2d3da35f3c760542b23cc97ae93ce97bae7b9baf011a957a9ffea
5
5
  SHA512:
6
- metadata.gz: 733b57829ff8883f24dd205b1aeb98ff39c2cf33c522ebcd11e9f1b984ee71844edf8cf907928a2cea729732f569b84b432461e8db264bf6d68e79d1f2b9a27b
7
- data.tar.gz: fc6bfb9d2acbd4dc8cc3e9f981d5280aecdc3ecd8527a24bf7704309c9b2a52aff08f416e77da2279682ee474ab2c0ecbe014690fcff6969eda7b6199fd404e3
6
+ metadata.gz: 4fb5ed37edce4c557082ba60cfa18f7209f795fa29b98dff9f848bb83b0b1cec889f4a7ca7f77bef5c0d9c6b4065d53765dcfcdf50dffe2628c3e3ffb57d26ad
7
+ data.tar.gz: 0bc33722f13c57c11888ac205873ac93a3610ef5218e8dccf7c3e64d671852757e9d755ffe17ea8176b238dbe1722df47db522b5252ddceed52e14534c164c45
data/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ## [1.13.4]
4
+
5
+ - Fix subscriptions potentially skipping events when multiple events are appended in concurrent transactions
6
+
7
+ ## [1.13.3]
8
+
9
+ - Reduce subscription delays for newly published events
10
+
3
11
  ## [1.13.2]
4
12
 
5
13
  - Fix a bug that prevents correct processing of CLI commands using public API
@@ -114,7 +122,7 @@ subscriptions_manager.subscribe(
114
122
  ```
115
123
 
116
124
  ## [1.1.5]
117
- - Review the way to handle SubscriptionAlreadyLockedError error. This removes noise when attempting to lock an already locked subscription.
125
+ - Review the way to handle SubscriptionAlreadyLockedError error. This removes noise when attempting to lock an already locked subscription.
118
126
 
119
127
  ## [1.1.4]
120
128
  - Add rbs signatures
@@ -163,7 +171,7 @@ subscriptions_manager.subscribe(
163
171
 
164
172
  ## [0.10.2] - 2024-03-13
165
173
 
166
- - Review the approach to resolve link events
174
+ - Review the approach to resolve link events
167
175
  - Fix subscriptions restart interval option not being processed correctly
168
176
 
169
177
  ## [0.10.1] - 2024-03-12
@@ -226,7 +234,7 @@ subscriptions_manager.subscribe(
226
234
 
227
235
  ## [0.3.0] - 2024-01-24
228
236
 
229
- - Log SQL queries when `PgEvenstore.logger` is set and it is in `:debug` mode
237
+ - Log SQL queries when `PgEvenstore.logger` is set and it is in `:debug` mode
230
238
 
231
239
  ## [0.2.6] - 2023-12-20
232
240
 
@@ -6,6 +6,8 @@ module PgEventstore
6
6
 
7
7
  # @return [String] a type of link event
8
8
  LINK_TYPE = '$>'
9
+ # @return [String]
10
+ PRIMARY_TABLE_NAME = 'events'
9
11
 
10
12
  # @!attribute id
11
13
  # @return [String] UUIDv4 string
@@ -28,7 +28,8 @@ module PgEventstore
28
28
  def event_exists?(event)
29
29
  return false if event.id.nil? || event.stream.nil?
30
30
 
31
- sql_builder = SQLBuilder.new.select('1 as exists').from('events').where('id = ?', event.id).limit(1)
31
+ sql_builder = SQLBuilder.new.select('1 as exists').from(Event::PRIMARY_TABLE_NAME).where('id = ?', event.id)
32
+ sql_builder.limit(1)
32
33
  sql_builder.where(
33
34
  'context = ? and stream_name = ? and type = ?', event.stream.context, event.stream.stream_name, event.type
34
35
  )
@@ -42,7 +43,7 @@ module PgEventstore
42
43
  # @param events [Array<PgEventstore::Event>]
43
44
  # @return [Array<String>]
44
45
  def ids_from_db(events)
45
- sql_builder = SQLBuilder.new.from('events').select('id')
46
+ sql_builder = SQLBuilder.new.from(Event::PRIMARY_TABLE_NAME).select('id')
46
47
  partition_attrs = events.map { |event| [event.stream&.context, event.stream&.stream_name, event.type] }.uniq
47
48
  partition_attrs.each do |context, stream_name, event_type|
48
49
  sql_builder.where_or('context = ? and stream_name = ? and type = ?', context, stream_name, event_type)
@@ -57,7 +58,7 @@ module PgEventstore
57
58
  # @param stream [PgEventstore::Stream]
58
59
  # @return [Integer, nil]
59
60
  def stream_revision(stream)
60
- sql_builder = SQLBuilder.new.from('events').select('stream_revision')
61
+ sql_builder = SQLBuilder.new.from(Event::PRIMARY_TABLE_NAME).select('stream_revision')
61
62
  sql_builder.where('context = ? and stream_name = ? and stream_id = ?', *stream.to_a)
62
63
  sql_builder.order('stream_revision DESC').limit(1)
63
64
  connection.with do |conn|
@@ -178,14 +178,42 @@ module PgEventstore
178
178
 
179
179
  # @param stream_filters [Array<Hash[Symbol, String]>]
180
180
  # @param event_filters [Array<String>]
181
+ # @param scope [Symbol] what kind of partition we want to receive. Available options are :event_type, :context,
182
+ # :stream_name and :auto. In :auto mode the scope will be calculated based on stream_filters and event_filters.
181
183
  # @return [Array<PgEventstore::Partition>]
182
- def partitions(stream_filters, event_filters)
183
- partitions_filter = QueryBuilders::PartitionsFiltering.new
184
- stream_filters.each { |attrs| partitions_filter.add_stream_attrs(**attrs) }
185
- partitions_filter.add_event_types(event_filters)
186
- partitions_filter.with_event_types
184
+ def partitions(stream_filters, event_filters, scope: :event_type)
185
+ stream_filters = stream_filters.select { QueryBuilders::PartitionsFiltering.correct_stream_filter?(_1) }
186
+ sql_builder =
187
+ if event_filters.any?
188
+ # When event type filters are present - they apply constraints to any stream filter. Thus, we can't look up
189
+ # partitions by stream attributes separately.
190
+ filter = QueryBuilders::PartitionsFiltering.new
191
+ stream_filters.each { |attrs| filter.add_stream_attrs(**attrs) }
192
+ filter.add_event_types(event_filters)
193
+ set_partitions_scope(filter, stream_filters, event_filters, scope)
194
+ else
195
+ # When event type filters are absent - we can look up partitions by context and context/stream_name
196
+ # separately, thus potentially producing one-to-one mapping of filter-to-partition with :auto scope. For
197
+ # example, let's say we have stream attributes filter like
198
+ # [{ context: 'FooCtx', stream_name: 'Bar'}, { context: 'BarCtx' }], then we would be able to look up
199
+ # partitions by the exact match, returning only two of them according to the provided filters - stream
200
+ # partition for first filter and context partition for second filter.
201
+ builders = stream_filters.map do |attrs|
202
+ filter = QueryBuilders::PartitionsFiltering.new
203
+ filter.add_stream_attrs(**attrs)
204
+ set_partitions_scope(filter, [attrs], event_filters, scope)
205
+ end
206
+
207
+ sql_builder = SQLBuilder.union_builders(builders) if builders.any?
208
+ sql_builder ||
209
+ begin
210
+ builder = QueryBuilders::PartitionsFiltering.new
211
+ set_partitions_scope(builder, stream_filters, event_filters, scope)
212
+ end
213
+ end
214
+
187
215
  connection.with do |conn|
188
- conn.exec_params(*partitions_filter.to_exec_params)
216
+ conn.exec_params(*sql_builder.to_exec_params)
189
217
  end.map(&method(:deserialize))
190
218
  end
191
219
 
@@ -210,6 +238,43 @@ module PgEventstore
210
238
 
211
239
  private
212
240
 
241
+ # @param partitions_filter [PgEventstore::QueryBuilders::PartitionsFiltering]
242
+ # @param stream_filters [Array<Hash[Symbol, String]>]
243
+ # @param event_filters [Array<String>]
244
+ # @param scope [Symbol]
245
+ # @return [PgEventstore::SQLBuilder]
246
+ def set_partitions_scope(partitions_filter, stream_filters, event_filters, scope)
247
+ case scope
248
+ when :event_type
249
+ partitions_filter.with_event_types
250
+ when :stream_name
251
+ filter = QueryBuilders::PartitionsFiltering.new
252
+ filter.without_event_types
253
+ filter.with_stream_names
254
+ builder = filter.to_sql_builder
255
+ builder.where(
256
+ '(context, stream_name) in ?',
257
+ partitions_filter.to_sql_builder.unselect.select('context, stream_name').group('context, stream_name')
258
+ )
259
+ when :context
260
+ filter = QueryBuilders::PartitionsFiltering.new
261
+ filter.without_event_types
262
+ filter.without_stream_names
263
+ builder = filter.to_sql_builder
264
+ builder.where('context in ?', partitions_filter.to_sql_builder.unselect.select('context').group('context'))
265
+ when :auto
266
+ if event_filters.any?
267
+ set_partitions_scope(partitions_filter, stream_filters, event_filters, :event_type)
268
+ elsif stream_filters.any? { _1[:stream_name] }
269
+ set_partitions_scope(partitions_filter, stream_filters, event_filters, :stream_name)
270
+ else
271
+ set_partitions_scope(partitions_filter, stream_filters, event_filters, :context)
272
+ end
273
+ else
274
+ raise NotImplementedError, "Don't know how to handle #{scope.inspect} scope!"
275
+ end
276
+ end
277
+
213
278
  # @param attrs [Hash]
214
279
  # @return [PgEventstore::Partition]
215
280
  def deserialize(attrs)
@@ -4,10 +4,6 @@ module PgEventstore
4
4
  module QueryBuilders
5
5
  # @!visibility private
6
6
  class EventsFiltering < BasicFiltering
7
- # @return [String]
8
- TABLE_NAME = 'events'
9
- private_constant :TABLE_NAME
10
-
11
7
  # @return [Integer]
12
8
  DEFAULT_LIMIT = 1_000
13
9
  # @return [Hash<String => String, Symbol => String>]
@@ -107,7 +103,7 @@ module PgEventstore
107
103
 
108
104
  # @return [String]
109
105
  def to_table_name
110
- TABLE_NAME
106
+ Event::PRIMARY_TABLE_NAME
111
107
  end
112
108
 
113
109
  # @param context [String, nil]
@@ -28,6 +28,19 @@ module PgEventstore
28
28
  end
29
29
  streams || []
30
30
  end
31
+
32
+ # @param stream_attrs [Hash]
33
+ # @return [Boolean]
34
+ def correct_stream_filter?(stream_attrs)
35
+ result = (stream_attrs in { context: String, stream_name: String } | { context: String })
36
+ return true if result
37
+
38
+ PgEventstore.logger&.debug(<<~TEXT)
39
+ Ignoring unsupported stream filter format for grouped read #{stream_attrs.compact.inspect}. \
40
+ See docs/reading_events.md docs for supported formats.
41
+ TEXT
42
+ false
43
+ end
31
44
  end
32
45
 
33
46
  # @return [String]
@@ -37,10 +50,10 @@ module PgEventstore
37
50
 
38
51
  # @param context [String, nil]
39
52
  # @param stream_name [String, nil]
40
- # @return [void]
53
+ # @return [PgEventstore::SQLBuilder]
41
54
  def add_stream_attrs(context: nil, stream_name: nil)
42
55
  stream_attrs = { context: context, stream_name: stream_name }
43
- return unless correct_stream_filter?(stream_attrs)
56
+ return @sql_builder unless self.class.correct_stream_filter?(stream_attrs)
44
57
 
45
58
  stream_attrs.compact!
46
59
  sql = stream_attrs.map do |attr, _|
@@ -50,31 +63,28 @@ module PgEventstore
50
63
  end
51
64
 
52
65
  # @param event_types [Array<String>]
53
- # @return [void]
66
+ # @return [PgEventstore::SQLBuilder]
54
67
  def add_event_types(event_types)
55
- return if event_types.empty?
68
+ return @sql_builder if event_types.empty?
56
69
 
57
70
  @sql_builder.where("#{to_table_name}.event_type = ANY(?::varchar[])", event_types)
58
71
  end
59
72
 
60
- # @return [void]
73
+ # @return [PgEventstore::SQLBuilder]
61
74
  def with_event_types
62
75
  @sql_builder.where('event_type IS NOT NULL')
63
76
  end
64
77
 
65
- private
78
+ def with_stream_names
79
+ @sql_builder.where('stream_name IS NOT NULL')
80
+ end
66
81
 
67
- # @param stream_attrs [Hash]
68
- # @return [Boolean]
69
- def correct_stream_filter?(stream_attrs)
70
- result = (stream_attrs in { context: String, stream_name: String } | { context: String, stream_name: nil })
71
- return true if result
82
+ def without_event_types
83
+ @sql_builder.where('event_type IS NULL')
84
+ end
72
85
 
73
- PgEventstore.logger&.debug(<<~TEXT)
74
- Ignoring unsupported stream filter format for grouped read #{stream_attrs.compact.inspect}. \
75
- See docs/reading_events.md docs for supported formats.
76
- TEXT
77
- false
86
+ def without_stream_names
87
+ @sql_builder.where('stream_name IS NULL')
78
88
  end
79
89
  end
80
90
  end
@@ -64,7 +64,7 @@ module PgEventstore
64
64
  self
65
65
  end
66
66
 
67
- # @param table_name [String]
67
+ # @param table_name [String | SQLBuilder]
68
68
  # @return [self]
69
69
  def from(table_name)
70
70
  @from_value = table_name
@@ -132,7 +132,7 @@ module PgEventstore
132
132
  self
133
133
  end
134
134
 
135
- # @return [Array<String, Array<Object>>]
135
+ # @return [[String, Array<_>]]
136
136
  def to_exec_params
137
137
  @positional_values.clear
138
138
  @positional_values_size = 0
@@ -141,19 +141,27 @@ module PgEventstore
141
141
 
142
142
  protected
143
143
 
144
- # @return [Array<String, Array<Object>>]
144
+ # @return [[String, Array<_>]]
145
145
  def _to_exec_params
146
146
  return [single_query_sql, @positional_values] if @union_values.empty?
147
147
 
148
148
  [union_query_sql, @positional_values]
149
149
  end
150
150
 
151
+ # @return [String]
152
+ def from_sql
153
+ return @from_value if @from_value.is_a?(String)
154
+
155
+ sql = merge(@from_value)
156
+ "(#{sql}) #{@from_value.from_sql}"
157
+ end
158
+
151
159
  private
152
160
 
153
161
  # @return [String]
154
162
  def single_query_sql
155
163
  where_sql = [where_sql('OR'), where_sql('AND')].reject(&:empty?).map { |sql| "(#{sql})" }.join(' AND ')
156
- sql = "SELECT #{select_sql} FROM #{@from_value}"
164
+ sql = "SELECT #{select_sql} FROM #{from_sql}"
157
165
  sql += " #{join_sql}" unless @join_values.empty?
158
166
  sql += " WHERE #{where_sql}" unless where_sql.empty?
159
167
  sql += " GROUP BY #{@group_values.join(', ')}" unless @group_values.empty?
@@ -168,11 +176,7 @@ module PgEventstore
168
176
  sql = single_query_sql
169
177
  union_parts = ["(#{sql})"]
170
178
  union_parts += @union_values.map do |builder|
171
- builder.positional_values_size = @positional_values_size
172
- builder_sql, values = builder._to_exec_params
173
- @positional_values.push(*values)
174
- @positional_values_size += values.size
175
- "(#{builder_sql})"
179
+ "(#{merge(builder)})"
176
180
  end
177
181
  union_parts.join(' UNION ALL ')
178
182
  end
@@ -200,14 +204,28 @@ module PgEventstore
200
204
  @order_values.join(', ')
201
205
  end
202
206
 
207
+ # @param builder [PgEventstore::SQLBuilder]
208
+ # @return [String]
209
+ def merge(builder)
210
+ builder.positional_values_size = @positional_values_size
211
+ sql_query, positional_values = builder._to_exec_params
212
+ @positional_values.push(*positional_values)
213
+ @positional_values_size += positional_values.size
214
+ sql_query
215
+ end
216
+
203
217
  # Replaces "?" signs in the given string with positional variables and memorize positional values they refer to.
204
218
  # @param sql [String]
205
219
  # @return [String]
206
220
  def extract_positional_args(sql, *arguments)
207
221
  sql.gsub('?').each_with_index do |_, index|
208
- @positional_values.push(arguments[index])
209
- @positional_values_size += 1
210
- "$#{@positional_values_size}"
222
+ if arguments[index].is_a?(SQLBuilder)
223
+ "(#{merge(arguments[index])})"
224
+ else
225
+ @positional_values.push(arguments[index])
226
+ @positional_values_size += 1
227
+ "$#{@positional_values_size}"
228
+ end
211
229
  end
212
230
  end
213
231
  end
@@ -9,10 +9,15 @@ module PgEventstore
9
9
  # @param callbacks [PgEventstore::Callbacks]
10
10
  # @param handler [#call]
11
11
  # @param raw_events [Array<Hash>]
12
+ # @param raw_events_cond [MonitorMixin::ConditionVariable]
12
13
  # @return [void]
13
- def process_event(callbacks, handler, raw_events)
14
- raw_event = raw_events.shift
15
- return sleep 0.5 if raw_event.nil?
14
+ def process_event(callbacks, handler, raw_events, raw_events_cond)
15
+ raw_event = nil
16
+ raw_events.synchronize do
17
+ raw_events_cond.wait(0.5) if raw_events.empty?
18
+ raw_event = raw_events.shift
19
+ end
20
+ return if raw_event.nil?
16
21
 
17
22
  callbacks.run_callbacks(:process, Utils.original_global_position(raw_event)) do
18
23
  handler.call(raw_event)
@@ -52,6 +52,15 @@ module PgEventstore
52
52
  def update_subscription_state(subscription, state)
53
53
  subscription.update(state: state)
54
54
  end
55
+
56
+ # @param subscription_position_evaluation [PgEventstore::SubscriptionPositionEvaluation]
57
+ # @param state [String]
58
+ # @return [void]
59
+ def stop_position_evaluation(subscription_position_evaluation, state)
60
+ return if state == 'running'
61
+
62
+ subscription_position_evaluation.stop_evaluation
63
+ end
55
64
  end
56
65
  end
57
66
  end
@@ -16,7 +16,8 @@ module PgEventstore
16
16
  # @param recovery_strategies [Array<PgEventstore::RunnerRecoveryStrategy>]
17
17
  def initialize(handler, graceful_shutdown_timeout:, recovery_strategies: [])
18
18
  @handler = handler
19
- @raw_events = []
19
+ @raw_events = SynchronizedArray.new
20
+ @raw_events_cond = @raw_events.new_cond
20
21
  @basic_runner = BasicRunner.new(
21
22
  run_interval: 0,
22
23
  async_shutdown_time: graceful_shutdown_timeout,
@@ -32,7 +33,10 @@ module PgEventstore
32
33
 
33
34
  within_state(:running) do
34
35
  callbacks.run_callbacks(:feed, Utils.original_global_position(raw_events.last))
35
- @raw_events.push(*raw_events)
36
+ @raw_events.synchronize do
37
+ @raw_events.push(*raw_events)
38
+ @raw_events_cond.broadcast
39
+ end
36
40
  end
37
41
  end
38
42
 
@@ -52,7 +56,7 @@ module PgEventstore
52
56
  def attach_runner_callbacks
53
57
  @basic_runner.define_callback(
54
58
  :process_async, :before,
55
- EventsProcessorHandlers.setup_handler(:process_event, @callbacks, @handler, @raw_events)
59
+ EventsProcessorHandlers.setup_handler(:process_event, @callbacks, @handler, @raw_events, @raw_events_cond)
56
60
  )
57
61
 
58
62
  @basic_runner.define_callback(
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PgEventstore
4
+ # @!visibility private
5
+ class ServiceQueries
6
+ # @param connection [PgEventstore::Connection]
7
+ def initialize(connection)
8
+ @connection = connection
9
+ end
10
+
11
+ # @param relation_oids [Array<Integer>]
12
+ # @return [Array<String>]
13
+ def relation_transaction_ids(relation_oids)
14
+ result = @connection.with do |conn|
15
+ # Look up transactions that change table's content
16
+ conn.exec_params(
17
+ <<~SQL,
18
+ SELECT virtualtransaction AS trx_id FROM pg_locks
19
+ WHERE relation = ANY($1::oid[]) AND mode = 'RowExclusiveLock'
20
+ SQL
21
+ [relation_oids]
22
+ )
23
+ end
24
+ result.map { _1['trx_id'] }
25
+ end
26
+
27
+ # @param relation_ids [Array<Integer>]
28
+ # @param transaction_ids [Array<String>]
29
+ # @return [Boolean]
30
+ def transactions_in_progress?(relation_ids:, transaction_ids:)
31
+ result = @connection.with do |conn|
32
+ conn.exec_params(
33
+ <<~SQL,
34
+ SELECT 1 as one FROM pg_locks
35
+ WHERE virtualtransaction = ANY($1) AND relation = ANY($2::oid[]) AND mode = 'RowExclusiveLock'
36
+ LIMIT 1
37
+ SQL
38
+ [transaction_ids, relation_ids]
39
+ )
40
+ end
41
+ result.any?
42
+ end
43
+
44
+ # @param table_names [Array<String>] existing table names
45
+ # @return [Integer]
46
+ def max_global_position(table_names)
47
+ return 0 if table_names.empty?
48
+
49
+ partition_builds = table_names.map do |table_name|
50
+ SQLBuilder.new.select("MAX(#{table_name}.global_position) AS global_position").from(table_name)
51
+ end
52
+ sql, positional_values = SQLBuilder.union_builders(partition_builds).to_exec_params
53
+ result = @connection.with do |conn|
54
+ conn.exec_params("SELECT MAX(global_position) AS max_pos FROM (#{sql}) pos", positional_values)
55
+ end
56
+ result.first['max_pos'] || 0
57
+ end
58
+
59
+ # @param table_names [Array<String>]
60
+ # @return [Hash<String, Integer>]
61
+ def relation_ids_by_names(table_names)
62
+ result = @connection.with do |conn|
63
+ conn.exec_params(
64
+ <<~SQL,
65
+ SELECT relname, oid FROM pg_class WHERE relname = ANY($1::varchar[])
66
+ SQL
67
+ [table_names]
68
+ )
69
+ end
70
+ result.each_with_object({}) { |attrs, res| res[attrs['relname']] = attrs['oid'] }
71
+ end
72
+ end
73
+ end
@@ -177,6 +177,7 @@ module PgEventstore
177
177
  # @return [PgEventstore::SQLBuilder]
178
178
  def query_builder(id, options)
179
179
  builder = PgEventstore::QueryBuilders::EventsFiltering.subscriptions_events_filtering(options).to_sql_builder
180
+ builder.where('global_position <= ?', options[:to_position]) if options[:to_position]
180
181
  builder.select("#{id} as runner_id")
181
182
  end
182
183
 
@@ -6,6 +6,16 @@ module PgEventstore
6
6
  include Extensions::UsingConnectionExtension
7
7
  include Extensions::OptionsExtension
8
8
 
9
+ # Determines the minimal allowed value of events pull frequency of the particular subscription. You can find similar
10
+ # constant - SubscriptionFeeder::EVENTS_PULL_INTERVAL. Unlike it - this one is responsible to detect whether the
11
+ # subscription should be included in the subscriptions list to query next chunk of events. Thus, this setting only
12
+ # determines whether it is time to make a request, but how frequent would be the actual request - determines
13
+ # SubscriptionFeeder::EVENTS_PULL_INTERVAL.
14
+ # @see PgEventstore::SubscriptionFeeder::EVENTS_PULL_INTERVAL
15
+ # @return [Float]
16
+ MIN_EVENTS_PULL_INTERVAL = 0.2
17
+ private_constant :MIN_EVENTS_PULL_INTERVAL
18
+
9
19
  # @return [Time]
10
20
  DEFAULT_TIMESTAMP = Time.at(0).utc.freeze
11
21
 
@@ -167,7 +177,7 @@ module PgEventstore
167
177
  restart_count: 0,
168
178
  last_restarted_at: nil,
169
179
  max_restarts_number: max_restarts_number,
170
- chunk_query_interval: chunk_query_interval,
180
+ chunk_query_interval: [chunk_query_interval, MIN_EVENTS_PULL_INTERVAL].max,
171
181
  last_chunk_fed_at: DEFAULT_TIMESTAMP,
172
182
  last_chunk_greatest_position: nil,
173
183
  last_error: nil,
@@ -7,6 +7,12 @@ module PgEventstore
7
7
  class SubscriptionFeeder
8
8
  extend Forwardable
9
9
 
10
+ # Determines how often to fetch events from the event store.
11
+ # @see PgEventstore::Subscription::MIN_EVENTS_PULL_INTERVAL
12
+ # @return [Float]
13
+ EVENTS_PULL_INTERVAL = 0.1 # seconds
14
+ private_constant :EVENTS_PULL_INTERVAL
15
+
10
16
  attr_reader :config_name
11
17
 
12
18
  def_delegators :@basic_runner, :start, :stop, :restore, :state, :wait_for_finish, :stop_async, :running?
@@ -17,7 +23,7 @@ module PgEventstore
17
23
  def initialize(config_name:, subscriptions_set_lifecycle:, subscriptions_lifecycle:)
18
24
  @config_name = config_name
19
25
  @basic_runner = BasicRunner.new(
20
- run_interval: 0.2,
26
+ run_interval: EVENTS_PULL_INTERVAL,
21
27
  async_shutdown_time: 0,
22
28
  recovery_strategies: recovery_strategies(config_name, subscriptions_set_lifecycle)
23
29
  )