Class: Sequent::Core::RecordSessions::ReplayEventsSession

Inherits:
Object
  • Object
show all
Defined in:
lib/sequent/core/record_sessions/replay_events_session.rb

Overview

Session objects are used to update view state

The ReplayEventsSession is optimized for bulk loading records in a Postgres database using CSV import.

After lot of experimenting this turned out to be the fastest way to to bulk inserts in the database. You can tweak the amount of records in the CSV via insert_with_csv_size before it flushes to the database to gain (or loose) speed.

It is highly recommended to create indices on the in memory record_store to speed up the processing. By default all records are indexed by aggregate_id if they have such a property.

Example:

class InvoiceEventHandler < Sequent::Core::Projector
  on RecipientMovedEvent do |event|
    update_all_records InvoiceRecord, recipient_id: event.recipient.aggregate_id do |record|
      record.recipient_street = record.recipient.street
    end
  end
end

In this case it is wise to create an index on InvoiceRecord on the recipient_id like you would in the database.

Example:

ReplayEventsSession.new(
  50,
  {InvoiceRecord => [[:recipient_id]]}
)

Defined Under Namespace

Modules: InitStruct Classes: Index

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(insert_with_csv_size = 50, indices = {}) ⇒ ReplayEventsSession

insert_with_csv_size number of records to insert in a single batch

indices Hash of indices to create in memory. Greatly speeds up the replaying.

Key corresponds to the name of the 'Record'
Values contains list of lists on which columns to index. E.g. [[:first_index_column], [:another_index, :with_to_columns]]


147
148
149
150
151
# File 'lib/sequent/core/record_sessions/replay_events_session.rb', line 147

def initialize(insert_with_csv_size = 50, indices = {})
  @insert_with_csv_size = insert_with_csv_size
  @record_store = Hash.new { |h, k| h[k] = Set.new }
  @record_index = Index.new(indices)
end

Instance Attribute Details

#insert_with_csv_sizeObject

Returns the value of attribute insert_with_csv_size.



41
42
43
# File 'lib/sequent/core/record_sessions/replay_events_session.rb', line 41

def insert_with_csv_size
  @insert_with_csv_size
end

#record_storeObject (readonly)

Returns the value of attribute record_store.



40
41
42
# File 'lib/sequent/core/record_sessions/replay_events_session.rb', line 40

def record_store
  @record_store
end

Class Method Details

.struct_cacheObject



43
44
45
# File 'lib/sequent/core/record_sessions/replay_events_session.rb', line 43

def self.struct_cache
  @struct_cache ||= {}
end

Instance Method Details

#clearObject



332
333
334
335
# File 'lib/sequent/core/record_sessions/replay_events_session.rb', line 332

def clear
  @record_store.clear
  @record_index.clear
end

#commitObject



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/sequent/core/record_sessions/replay_events_session.rb', line 285

def commit
  @record_store.each do |clazz, records|
    @column_cache ||= {}
    @column_cache[clazz.name] ||= clazz.columns.reduce({}) do |hash, column|
      hash.merge({ column.name => column })
    end
    if records.size > @insert_with_csv_size
      csv = CSV.new("")
      column_names = clazz.column_names.reject { |name| name == "id" }
      records.each do |obj|
        csv << column_names.map do |column_name|
          ActiveRecord::Base.connection.type_cast(obj[column_name], @column_cache[clazz.name][column_name])
        end
      end

      buf = ''
      conn = ActiveRecord::Base.connection.raw_connection
      copy_data = StringIO.new csv.string
      conn.transaction do
        conn.copy_data("COPY #{clazz.table_name} (#{column_names.join(",")}) FROM STDIN WITH csv") do
          while copy_data.read(1024, buf)
            conn.put_copy_data(buf)
          end
        end
      end
    else
      clazz.unscoped do
        inserts = []
        column_names = clazz.column_names.reject { |name| name == "id" }
        prepared_values = (1..column_names.size).map { |i| "$#{i}" }.join(",")
        records.each do |r|
          values = column_names.map do |column_name|
            ActiveRecord::Base.connection.type_cast(r[column_name.to_sym], @column_cache[clazz.name][column_name])
          end
          inserts << values
        end
        sql = %Q{insert into #{clazz.table_name} (#{column_names.join(",")}) values (#{prepared_values})}
        inserts.each do |insert|
          clazz.connection.raw_connection.async_exec(sql, insert)
        end
      end
    end
  end
ensure
  clear
end

#create_or_update_record(record_class, values, created_at = Time.now) {|record| ... } ⇒ Object

Yields:

  • (record)


206
207
208
209
210
211
212
213
214
# File 'lib/sequent/core/record_sessions/replay_events_session.rb', line 206

def create_or_update_record(record_class, values, created_at = Time.now)
  record = get_record(record_class, values)
  unless record
    record = create_record(record_class, values.merge(created_at: created_at))
  end
  yield record if block_given?
  @record_index.update(record_class, record)
  record
end

#create_record(record_class, values) {|record| ... } ⇒ Object

Yields:

  • (record)


164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/sequent/core/record_sessions/replay_events_session.rb', line 164

def create_record(record_class, values)
  column_names = record_class.column_names
  values = record_class.column_defaults.merge(values)
  values.merge!(updated_at: values[:created_at]) if column_names.include?("updated_at")
  struct_class_name = "#{record_class.to_s}Struct"
  if self.class.struct_cache.has_key?(struct_class_name)
    struct_class = self.class.struct_cache[struct_class_name]
  else
    # We create a struct on the fly.
    # Since the replay happens in memory we implement the ==, eql? and hash methods
    # to point to the same object. A record is the same if and only if they point to
    # the same object. These methods are necessary since we use Set instead of [].
    class_def=<<-EOD
      #{struct_class_name} = Struct.new(*#{column_names.map(&:to_sym)})
      class #{struct_class_name}
        include InitStruct
        def ==(other)
          self.equal?(other)
        end
        def hash
          self.object_id.hash
        end
      end
    EOD
    eval("#{class_def}")
    struct_class = ReplayEventsSession.const_get(struct_class_name)
    self.class.struct_cache[struct_class_name] = struct_class
  end
  record = struct_class.new.set_values(values)

  yield record if block_given?
  @record_store[record_class] << record

  @record_index.add(record_class, record)

  record
end

#create_records(record_class, array_of_value_hashes) ⇒ Object



202
203
204
# File 'lib/sequent/core/record_sessions/replay_events_session.rb', line 202

def create_records(record_class, array_of_value_hashes)
  array_of_value_hashes.each { |values| create_record(record_class, values) }
end

#delete_all_records(record_class, where_clause) ⇒ Object



227
228
229
230
231
# File 'lib/sequent/core/record_sessions/replay_events_session.rb', line 227

def delete_all_records(record_class, where_clause)
  find_records(record_class, where_clause).each do |record|
    delete_record(record_class, record)
  end
end

#delete_record(record_class, record) ⇒ Object



233
234
235
236
# File 'lib/sequent/core/record_sessions/replay_events_session.rb', line 233

def delete_record(record_class, record)
  @record_store[record_class].delete(record)
  @record_index.remove(record_class, record)
end

#do_with_record(record_class, where_clause) {|record| ... } ⇒ Object

Yields:

  • (record)


255
256
257
258
259
# File 'lib/sequent/core/record_sessions/replay_events_session.rb', line 255

def do_with_record(record_class, where_clause)
  record = get_record!(record_class, where_clause)
  yield record
  @record_index.update(record_class, record)
end

#do_with_records(record_class, where_clause) ⇒ Object



247
248
249
250
251
252
253
# File 'lib/sequent/core/record_sessions/replay_events_session.rb', line 247

def do_with_records(record_class, where_clause)
  records = find_records(record_class, where_clause)
  records.each do |record|
    yield record
    @record_index.update(record_class, record)
  end
end

#find_records(record_class, where_clause) ⇒ Object



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/sequent/core/record_sessions/replay_events_session.rb', line 261

def find_records(record_class, where_clause)
  if @record_index.use_index?(record_class, where_clause)
    @record_index.find(record_class, where_clause)
  else
    @record_store[record_class].select do |record|
      where_clause.all? do |k, v|
        expected_value = v.kind_of?(Symbol) ? v.to_s : v
        actual_value = record[k.to_sym]
        actual_value = actual_value.to_s if actual_value.kind_of? Symbol
        if expected_value.kind_of?(Array)
          expected_value.include?(actual_value)
        else
          actual_value == expected_value
        end
      end
    end
  end.dup
end

#get_record(record_class, where_clause) ⇒ Object



222
223
224
225
# File 'lib/sequent/core/record_sessions/replay_events_session.rb', line 222

def get_record(record_class, where_clause)
  results = find_records(record_class, where_clause)
  results.empty? ? nil : results.first
end

#get_record!(record_class, where_clause) ⇒ Object



216
217
218
219
220
# File 'lib/sequent/core/record_sessions/replay_events_session.rb', line 216

def get_record!(record_class, where_clause)
  record = get_record(record_class, where_clause)
  raise("record #{record_class} not found for #{where_clause}, store: #{@record_store[record_class]}") unless record
  record
end

#last_record(record_class, where_clause) ⇒ Object



280
281
282
283
# File 'lib/sequent/core/record_sessions/replay_events_session.rb', line 280

def last_record(record_class, where_clause)
  results = find_records(record_class, where_clause)
  results.empty? ? nil : results.last
end

#update_all_records(record_class, where_clause, updates) ⇒ Object



238
239
240
241
242
243
244
245
# File 'lib/sequent/core/record_sessions/replay_events_session.rb', line 238

def update_all_records(record_class, where_clause, updates)
  find_records(record_class, where_clause).each do |record|
    updates.each_pair do |k, v|
      record[k.to_sym] = v
    end
    @record_index.update(record_class, record)
  end
end

#update_record(record_class, event, where_clause = {aggregate_id: event.aggregate_id}, options = {}) {|record| ... } ⇒ Object

Yields:

  • (record)


153
154
155
156
157
158
159
160
161
162
# File 'lib/sequent/core/record_sessions/replay_events_session.rb', line 153

def update_record(record_class, event, where_clause = {aggregate_id: event.aggregate_id}, options = {}, &block)
  record = get_record!(record_class, where_clause)
  record.updated_at = event.created_at if record.respond_to?(:updated_at)
  yield record if block_given?
  @record_index.update(record_class, record)
  update_sequence_number = options.key?(:update_sequence_number) ?
                             options[:update_sequence_number] :
                             record.respond_to?(:sequence_number=)
  record.sequence_number = event.sequence_number if update_sequence_number
end