Class: Wal::Replicator

Inherits:
Object
  • Object
show all
Includes:
PG::Replication::Protocol
Defined in:
lib/wal/replicator.rb

Overview

Responsible to hook into a Postgres logical replication slot and stream the changes to a specific Watcher. Also it supports inject "contexts" into the replication events.

Defined Under Namespace

Classes: Column, Table

Instance Method Summary collapse

Constructor Details

#initialize(replication_slot:, use_temporary_slot: false, db_config: ActiveRecord::Base.configurations.configs_for(name: "primary").configuration_hash) ⇒ Replicator

Returns a new instance of Replicator.



7
8
9
10
11
12
13
14
15
16
# File 'lib/wal/replicator.rb', line 7

def initialize(
  replication_slot:,
  use_temporary_slot: false,
  db_config: ActiveRecord::Base.configurations.configs_for(name: "primary").configuration_hash
)
  @db_config = db_config
  @replication_slot = replication_slot
  @use_temporary_slot = use_temporary_slot
  @primary_key_cache = {}
end

Instance Method Details

#closeObject



25
26
27
28
29
30
31
# File 'lib/wal/replicator.rb', line 25

def close
  @watch_conn&.stop_replication
  @watch_conn&.close
  @watch_conn = nil
  @metadata_conn&.close
  @metadata_conn = nil
end

#replicate(watcher, publications:) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/wal/replicator.rb', line 33

def replicate(watcher, publications:)
  @watch_conn = PG.connect(
    dbname: @db_config[:database],
    host: @db_config[:host],
    user: @db_config[:username],
    password: @db_config[:password].presence,
    port: @db_config[:port].presence,
    replication: "database",
  )

  @metadata_conn = 

  begin
    @watch_conn.query(<<~SQL)
      CREATE_REPLICATION_SLOT #{@replication_slot} #{@use_temporary_slot ? "TEMPORARY" : ""} LOGICAL "pgoutput"
    SQL
  rescue PG::DuplicateObject
    # We are fine, we already have created this slot in a previous run
  end

  tables = {}
  context = {}
  transaction_id = nil

  @watch_conn.start_pgoutput_replication_slot(@replication_slot, publications, messages: true).filter_map do |msg|
    case msg
    in XLogData(data: PG::Replication::PGOutput::Relation(oid:, name:, columns:, namespace:))
      tables[oid] = Table.new(
        primary_key_columns: fetch_primary_key_columns(namespace, name),
        schema: namespace,
        name:,
        columns: columns.map { |col| Column.new(oid: col.oid, name: col.name) },
      )
      next

    in XLogData(lsn:, data: PG::Replication::PGOutput::Begin(xid:, timestamp:, final_lsn:))
      transaction_id = xid
      context = {}
      BeginTransactionEvent.new(
        transaction_id:,
        lsn:,
        final_lsn:,
        timestamp:,
      ).tap { |event| watcher.on_event(event) }

    in XLogData(lsn:, data: PG::Replication::PGOutput::Commit(timestamp:))
      CommitTransactionEvent.new(
        transaction_id:,
        lsn:,
        context:,
        timestamp:,
      ).tap do |event|
        watcher.on_event(event)
        @watch_conn.standby_status_update(write_lsn: lsn)
      end

    in XLogData(lsn:, data: PG::Replication::PGOutput::Message(prefix: "wal_ping"))
      @watch_conn.standby_status_update(write_lsn: [@watch_conn.last_confirmed_lsn, lsn].compact.max)
      next

    in XLogData(data: PG::Replication::PGOutput::Message(prefix:, content:)) if watcher.valid_context_prefix? prefix
      begin
        context = JSON.parse(content).presence || {}
        next
      rescue JSON::ParserError
        # Invalid context received, just ignore
      end

    in XLogData(lsn:, data: PG::Replication::PGOutput::Insert(oid:, new:))
      table = tables[oid]
      next unless watcher.should_watch_table? table.full_table_name
      new_data = table.decode_row(new)
      record_id = table.primary_key(new_data)
      next unless record_id

      InsertEvent.new(
        transaction_id:,
        lsn:,
        context:,
        schema: table.schema,
        table: table.name,
        primary_key: record_id,
        new: new_data,
      ).tap { |event| watcher.on_event(event) }

    in XLogData(lsn:, data: PG::Replication::PGOutput::Update(oid:, new:, old:))
      table = tables[oid]
      next unless watcher.should_watch_table? table.full_table_name
      new_data = table.decode_row(new)
      old_data = table.decode_row(old, new_data)
      record_id = table.primary_key(new_data)
      next unless record_id

      UpdateEvent.new(
        transaction_id:,
        lsn:,
        context:,
        schema: table.schema,
        table: table.name,
        primary_key: record_id,
        old: old_data,
        new: new_data,
      ).tap { |event| watcher.on_event(event) }

    in XLogData(lsn:, data: PG::Replication::PGOutput::Delete(oid:, old:, key:))
      table = tables[oid]
      next unless watcher.should_watch_table? table.full_table_name
      old_data = table.decode_row(old.presence || key)
      record_id = table.primary_key(old_data)
      next unless record_id

      DeleteEvent.new(
        transaction_id:,
        lsn:,
        context:,
        schema: table.schema,
        table: table.name,
        primary_key: record_id,
        old: old_data,
      ).tap { |event| watcher.on_event(event) }

    else
      next
    end
  rescue
    close
    raise
  end
end

#replicate_forever(watcher, publications:) ⇒ Object



18
19
20
21
22
23
# File 'lib/wal/replicator.rb', line 18

def replicate_forever(watcher, publications:)
  replication = replicate(watcher, publications:)
  loop { replication.next }
rescue StopIteration
  nil
end