mysql_replicator 0.1.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.
Files changed (54) hide show
  1. checksums.yaml +7 -0
  2. data/.rspec +3 -0
  3. data/.rubocop.yml +79 -0
  4. data/CHANGELOG.md +5 -0
  5. data/CODE_OF_CONDUCT.md +132 -0
  6. data/LICENSE.txt +21 -0
  7. data/README.md +115 -0
  8. data/Rakefile +12 -0
  9. data/Steepfile +22 -0
  10. data/docker-compose.yml +13 -0
  11. data/lib/mysql_replicator/binlog_client.rb +201 -0
  12. data/lib/mysql_replicator/binlogs/column_parser.rb +425 -0
  13. data/lib/mysql_replicator/binlogs/constants.rb +74 -0
  14. data/lib/mysql_replicator/binlogs/event_parser.rb +134 -0
  15. data/lib/mysql_replicator/binlogs/format_description_event_parser.rb +24 -0
  16. data/lib/mysql_replicator/binlogs/json_parser.rb +335 -0
  17. data/lib/mysql_replicator/binlogs/query_event_parser.rb +69 -0
  18. data/lib/mysql_replicator/binlogs/rotate_event_parser.rb +37 -0
  19. data/lib/mysql_replicator/binlogs/rows_event_parser.rb +161 -0
  20. data/lib/mysql_replicator/binlogs/table_map_event_parser.rb +155 -0
  21. data/lib/mysql_replicator/binlogs/xid_event_parser.rb +25 -0
  22. data/lib/mysql_replicator/connection.rb +226 -0
  23. data/lib/mysql_replicator/connections/auth.rb +303 -0
  24. data/lib/mysql_replicator/connections/handshake.rb +132 -0
  25. data/lib/mysql_replicator/connections/query.rb +322 -0
  26. data/lib/mysql_replicator/error.rb +6 -0
  27. data/lib/mysql_replicator/logger.rb +43 -0
  28. data/lib/mysql_replicator/string_io_util.rb +199 -0
  29. data/lib/mysql_replicator/string_util.rb +106 -0
  30. data/lib/mysql_replicator/version.rb +6 -0
  31. data/lib/mysql_replicator.rb +51 -0
  32. data/sig/generated/mysql_replicator/binlog_client.rbs +52 -0
  33. data/sig/generated/mysql_replicator/binlogs/column_parser.rbs +134 -0
  34. data/sig/generated/mysql_replicator/binlogs/constants.rbs +69 -0
  35. data/sig/generated/mysql_replicator/binlogs/event_parser.rbs +35 -0
  36. data/sig/generated/mysql_replicator/binlogs/format_description_event_parser.rbs +13 -0
  37. data/sig/generated/mysql_replicator/binlogs/json_parser.rbs +101 -0
  38. data/sig/generated/mysql_replicator/binlogs/query_event_parser.rbs +14 -0
  39. data/sig/generated/mysql_replicator/binlogs/rotate_event_parser.rbs +14 -0
  40. data/sig/generated/mysql_replicator/binlogs/rows_event_parser.rbs +39 -0
  41. data/sig/generated/mysql_replicator/binlogs/table_map_event_parser.rbs +31 -0
  42. data/sig/generated/mysql_replicator/binlogs/xid_event_parser.rbs +13 -0
  43. data/sig/generated/mysql_replicator/connection.rbs +103 -0
  44. data/sig/generated/mysql_replicator/connections/auth.rbs +76 -0
  45. data/sig/generated/mysql_replicator/connections/handshake.rbs +21 -0
  46. data/sig/generated/mysql_replicator/connections/query.rbs +62 -0
  47. data/sig/generated/mysql_replicator/error.rbs +6 -0
  48. data/sig/generated/mysql_replicator/logger.rbs +26 -0
  49. data/sig/generated/mysql_replicator/string_io_util.rbs +75 -0
  50. data/sig/generated/mysql_replicator/string_util.rbs +45 -0
  51. data/sig/generated/mysql_replicator/types.rbs +19 -0
  52. data/sig/generated/mysql_replicator/version.rbs +5 -0
  53. data/sig/generated/mysql_replicator.rbs +16 -0
  54. metadata +124 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 1fc2f85268cd0a2187b97a8a62761ddaec7730c8d019fcb02b154600fbe00ddb
4
+ data.tar.gz: 30977b5f6c98d581c73733b9d9c683802935079b1396b3bb01cfecc8ed140486
5
+ SHA512:
6
+ metadata.gz: b8ec42a9aa2f9fd13b765662777d9f3a68ea6a2551cf56bbeb52402a49a3b29e7b97a4f10971b97547133cd6093091c18271ac0a1ad05cb277db9deb3682d914
7
+ data.tar.gz: 94c2da74bc3eff4045590a6e30d9de8b2b38947d191fb779de5eaeb911819eeb89a9b3f0087cd1cb3e18af3239b24eb8092470feb3c6ee4f49d2e4f6195113b9
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,79 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.1
3
+ NewCops: enable
4
+ SuggestExtensions: false
5
+
6
+ Layout/ArgumentAlignment:
7
+ Enabled: false
8
+
9
+ Layout/EmptyLineAfterMagicComment:
10
+ Enabled: false
11
+
12
+ Layout/LeadingCommentSpace:
13
+ Enabled: false
14
+
15
+ Layout/LineLength:
16
+ Enabled: false
17
+
18
+ Metrics/AbcSize:
19
+ Enabled: false
20
+
21
+ Metrics/BlockLength:
22
+ Enabled: false
23
+
24
+ Metrics/BlockNesting:
25
+ Enabled: false
26
+
27
+ Metrics/ClassLength:
28
+ Enabled: false
29
+
30
+ Metrics/CyclomaticComplexity:
31
+ Enabled: false
32
+
33
+ Metrics/MethodLength:
34
+ Enabled: false
35
+
36
+ Metrics/ModuleLength:
37
+ Enabled: false
38
+
39
+ Metrics/ParameterLists:
40
+ Enabled: false
41
+
42
+ Metrics/PerceivedComplexity:
43
+ Enabled: false
44
+
45
+ Style/BitwisePredicate:
46
+ Enabled: false
47
+
48
+ Style/Documentation:
49
+ Enabled: false
50
+
51
+ Style/FormatStringToken:
52
+ Enabled: false
53
+
54
+ Style/IfUnlessModifier:
55
+ Enabled: false
56
+
57
+ Style/NumericPredicate:
58
+ Enabled: false
59
+
60
+ Style/OptionalBooleanParameter:
61
+ Enabled: false
62
+
63
+ Style/RescueStandardError:
64
+ Enabled: false
65
+
66
+ Style/StringConcatenation:
67
+ Enabled: false
68
+
69
+ Style/StringLiterals:
70
+ EnforcedStyle: single_quotes
71
+
72
+ Style/StringLiteralsInInterpolation:
73
+ EnforcedStyle: single_quotes
74
+
75
+ Style/UnpackFirst:
76
+ Enabled: false
77
+
78
+ Style/WordArray:
79
+ Enabled: false
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-08-11
4
+
5
+ - Initial release
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 yo_waka
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,115 @@
1
+ # MySQL Replicator
2
+
3
+ `MysqlReplicator` gem is a library for processing MySQL Binlog events using the MySQL replication protocol.
4
+
5
+ And also, this is lightweight because only depend on the Ruby standard library.
6
+
7
+ ## Installation
8
+
9
+ Install the gem and add to the application's Gemfile by executing:
10
+
11
+ ```bash
12
+ bundle add mysql_replicator
13
+ ```
14
+
15
+ You can of course add a gem call in your Gemfile yourself.
16
+
17
+ ```bash
18
+ gem 'mysql_replicator'
19
+ ```
20
+
21
+ If bundler is not being used to manage dependencies, install the gem by executing:
22
+
23
+ ```bash
24
+ gem install mysql_replicator
25
+ ```
26
+
27
+ ## Usage
28
+
29
+ ```rb
30
+ # Custom logger available
31
+ MysqlReplicator.logger = your_custom_logger
32
+
33
+ # Connect to MySQL server, and start to handle replication event
34
+ MysqlReplicator.run(
35
+ host: 'your_mysql_host', # default localhost
36
+ port: 3307, # default 3306
37
+ user: 'username', # default root
38
+ password: 'password', # default empty string
39
+ database: 'test' # default empty string
40
+ ) do |binlog_event|
41
+ # write code to process binlog event
42
+
43
+ puts binlog_event[:timestamp]
44
+ # => 2025-12-01 12:00:00
45
+
46
+ puts binlog_event[:event_type]
47
+ # => :WRITE_ROWS
48
+
49
+ puts binlog_event[:execution]
50
+ # => {
51
+ # table_id: 10,
52
+ # flags: 0,
53
+ # extra_data_length: 0,
54
+ # column_count: 2,
55
+ # rows: [
56
+ # {
57
+ # ordinal_position: 1,
58
+ # data_type: 'int',
59
+ # column_name: 'id',
60
+ # value: 1,
61
+ # primary_key: true
62
+ # },
63
+ # {
64
+ # ordinal_position: 2,
65
+ # data_type: 'varchar',
66
+ # column_name: 'name',
67
+ # value: 'alice',
68
+ # primary_key: false
69
+ # }
70
+ # ]
71
+ # }
72
+ end
73
+ ```
74
+
75
+ ## Development
76
+
77
+ Start MySQL server.
78
+ ```
79
+ $ docker compose up
80
+ ```
81
+
82
+ Start MysqlReplicator to check if local code works.
83
+ ```rb
84
+ irb(main):001> MysqlReplicator.run(database: 'test') { |evt| puts evt }
85
+ ```
86
+
87
+ Submit sample DDL and query to MySQL server.
88
+ Check `spec/supports/sql`.
89
+
90
+ Run spec for test.
91
+ ```
92
+ $ bundle exec rspec
93
+ ```
94
+
95
+ Run rubocop for linter.
96
+ ```
97
+ $ bundle exec rubocop
98
+ ```
99
+
100
+ Run steep for type check.
101
+ ```
102
+ $ bundle exec steep check
103
+ ```
104
+
105
+ ## Contributing
106
+
107
+ Bug reports and pull requests are welcome on GitHub at https://github.com/waka/mysql_replicator. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/waka/mysql_replicator/blob/main/CODE_OF_CONDUCT.md).
108
+
109
+ ## License
110
+
111
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
112
+
113
+ ## Code of Conduct
114
+
115
+ Everyone interacting in the MysqlReplicator project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/waka/mysql_replicator/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require 'rubocop/rake_task'
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/Steepfile ADDED
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ D = Steep::Diagnostic
4
+
5
+ target :lib do
6
+ signature 'sig'
7
+ ignore_signature 'sig/test'
8
+
9
+ check 'lib' # Directory name
10
+
11
+ library 'bigdecimal'
12
+ library 'digest'
13
+ library 'logger'
14
+ library 'openssl'
15
+ library 'socket'
16
+ library 'stringio'
17
+
18
+ configure_code_diagnostics(D::Ruby.strict)
19
+ configure_code_diagnostics do |hash|
20
+ hash[D::Ruby::UnannotatedEmptyCollection] = :information
21
+ end
22
+ end
@@ -0,0 +1,13 @@
1
+ services:
2
+ mysql:
3
+ image: mysql:8.0
4
+ environment:
5
+ - MYSQL_ROOT_PASSWORD=root
6
+ ports:
7
+ - "3306:3306"
8
+ volumes:
9
+ - mysql_data:/var/lib/mysql:delegated
10
+
11
+ volumes:
12
+ mysql_data:
13
+ driver: local
@@ -0,0 +1,201 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ module MysqlReplicator
5
+ # Binlog handler using MySQL Replication Protocol
6
+ class BinlogClient
7
+ # @rbs @connection: MysqlReplicator::Connection
8
+ # @rbs @server_id: Integer
9
+ # @rbs @checksum_type: String?
10
+ # @rbs @event_listener: ^(MysqlReplicator::Binlogs::EventParser::binlogEvent) -> untyped | nil
11
+
12
+ # @rbs! attr_reader connection: MysqlReplicator::Connection
13
+ attr_reader :connection
14
+
15
+ # @rbs connection: MysqlReplicator::Connection
16
+ # @rbs server_id: Integer
17
+ # @rbs return void
18
+ def initialize(connection, server_id = 1001)
19
+ @connection = connection
20
+ @server_id = server_id
21
+ @checksum_type = nil
22
+ end
23
+
24
+ # @rbs &block: { (MysqlReplicator::Binlogs::EventParser::binlogEvent) -> untyped | nil }
25
+ # @rbs return: void
26
+ def on(&block)
27
+ @event_listener = block
28
+ end
29
+
30
+ # @rbs return: void
31
+ def start_replication
32
+ @connection.connect unless @connection.connected?
33
+
34
+ binlog_info = master_status
35
+ binlog_file = binlog_info[:file]
36
+ binlog_position = binlog_info[:position]
37
+
38
+ configure_binlog_checksum if @checksum_type.nil?
39
+ register_as_slave
40
+ start_binlog_dump(binlog_file, binlog_position)
41
+
42
+ begin
43
+ handle_binlog_events
44
+ rescue Interrupt
45
+ stop_replication
46
+ rescue => e
47
+ MysqlReplicator::Logger.error \
48
+ "Unexpected error: #{e.message},\n" \
49
+ "Backtrace: #{e.backtrace.first(5).join("\n")}"
50
+
51
+ stop_replication
52
+ end
53
+ end
54
+
55
+ # @rbs return: void
56
+ def stop_replication
57
+ @connection.flush_socket_buffer
58
+ unregister_as_slave
59
+ @connection.close
60
+ end
61
+
62
+ # @rbs return: { file: String, position: Integer }
63
+ def master_status
64
+ result = @connection.query('SHOW MASTER STATUS')
65
+ row = result[:rows][0]
66
+ { file: row[:file].to_s, position: row[:position].to_i }
67
+ end
68
+
69
+ # @rbs return: void
70
+ def register_as_slave
71
+ @connection.reset_sequence_id
72
+
73
+ # Payload of COM_REGISTER_SLAVE packet
74
+ payload = [0x15].pack('C')
75
+ # Server ID (4 bytes)
76
+ payload += [@server_id].pack('V')
77
+ # Hostname (empty string but properly formatted)
78
+ hostname = ''
79
+ payload += [hostname.length].pack('C') + hostname
80
+ # Username (empty string but properly formatted)
81
+ username = ''
82
+ payload += [username.length].pack('C') + username
83
+ # Password (empty string but properly formatted)
84
+ password = ''
85
+ payload += [password.length].pack('C') + password
86
+ # MySQL port
87
+ payload += [@connection.port].pack('V')
88
+ # Replication rank = 0 (unused)
89
+ payload += [0].pack('V')
90
+ # Master ID = 0 (unused)
91
+ payload += [0].pack('V')
92
+
93
+ @connection.send_packet(payload)
94
+
95
+ response = @connection.read_packet
96
+ if response[:payload][0].unpack('C')[0] != 0x00
97
+ raise MysqlReplicator::Error,
98
+ 'Failed to register as slave ' \
99
+ "error code = #{response[:payload][1, 2].unpack('v')[0]}, " \
100
+ "error message = #{response[:payload][9..]}"
101
+ end
102
+
103
+ MysqlReplicator::Logger.info 'Successfully registered as slave'
104
+ end
105
+
106
+ # @rbs return: void
107
+ def unregister_as_slave
108
+ @connection.reset_sequence_id
109
+
110
+ # Payload of COM_UNREGISTER_SLAVE packet
111
+ payload = [0x1B].pack('C')
112
+ # Connection ID (4 bytes)
113
+ payload += [@connection.connection_id].pack('V')
114
+
115
+ @connection.send_packet(payload)
116
+
117
+ response = @connection.read_packet
118
+ if response[:payload][0].unpack('C')[0] != 0x00
119
+ raise MysqlReplicator::Error,
120
+ 'Failed to unregister as slave ' \
121
+ "error code = #{response[:payload][1, 2].unpack('v')[0]}, " \
122
+ "error message = #{response[:payload][9..]}"
123
+ end
124
+
125
+ MysqlReplicator::Logger.info 'Successfully unregistered as slave'
126
+ end
127
+
128
+ # @rbs return: void
129
+ def configure_binlog_checksum
130
+ result = @connection.query('SHOW VARIABLES LIKE "binlog_checksum"')
131
+ @checksum_type = result[:rows][0][:value]
132
+
133
+ case @checksum_type
134
+ when 'NONE'
135
+ # No checksum
136
+ MysqlReplicator::Logger.debug 'Set binlog checksum to NONE'
137
+ when 'CRC32'
138
+ @connection.query('SET @master_binlog_checksum = "CRC32"')
139
+ MysqlReplicator::Logger.debug 'Set binlog checksum to CRC32'
140
+ else
141
+ raise MysqlReplicator::Error, "Unknown binlog checksum type: #{@checksum_type}"
142
+ end
143
+ end
144
+
145
+ # @rbs binlog_file: String
146
+ # @rbs binlog_position: Integer
147
+ # @rbs return: void
148
+ def start_binlog_dump(binlog_file, binlog_position)
149
+ @connection.reset_sequence_id
150
+
151
+ # Payload of COM_BINLOG_DUMP packet
152
+ payload = [0x12].pack('C')
153
+ # Binlog position (4 bytes)
154
+ payload += [Integer(binlog_position)].pack('V')
155
+ # Flags (2 bytes)
156
+ payload += [0].pack('v')
157
+ # Slave server ID (4 bytes)
158
+ payload += [@server_id].pack('V')
159
+ # Binlog filename
160
+ payload += binlog_file
161
+
162
+ @connection.send_packet(payload)
163
+
164
+ MysqlReplicator::Logger.info \
165
+ "Started binlog dump from #{binlog_file} at position #{binlog_position}"
166
+ end
167
+
168
+ # @rbs return: void
169
+ def handle_binlog_events
170
+ event_parser = MysqlReplicator::Binlogs::EventParser.new
171
+
172
+ loop do
173
+ packet = @connection.read_packet
174
+ payload = packet[:payload]
175
+
176
+ first_byte = payload[0].unpack('C')[0]
177
+
178
+ case first_byte
179
+ when 0x00
180
+ binlog_event = event_parser.execute(payload[1..], @connection, @checksum_type == 'CRC32')
181
+
182
+ case binlog_event[:event_type]
183
+ when :QUERY, :WRITE_ROWS, :UPDATE_ROWS, :DELETE_ROWS
184
+ @event_listener&.call(binlog_event)
185
+ end
186
+ MysqlReplicator::Logger.debug "Binlog event: #{binlog_event}"
187
+ when 0xFF
188
+ MysqlReplicator::Logger.error \
189
+ "Binlog event error: #{payload[1, 2].unpack('v')[0]} - #{payload[3..]}"
190
+ break
191
+ when 0xFE
192
+ MysqlReplicator::Logger.error 'Received EOF packet - binlog stream ended'
193
+ break
194
+ else
195
+ MysqlReplicator::Logger.error "Unexpected packet type: 0x#{first_byte.to_s(16)}"
196
+ break
197
+ end
198
+ end
199
+ end
200
+ end
201
+ end