active_record_proxy_adapters 0.2.6 → 0.3.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.
- checksums.yaml +4 -4
- data/.rspec +4 -0
- data/.rubocop.yml +16 -0
- data/CHANGELOG.md +41 -0
- data/CODE_OF_CONDUCT.md +132 -0
- data/Dockerfile +20 -0
- data/README.md +36 -7
- data/db/mysql_structure.sql +41 -0
- data/db/postgresql_structure.sql +86 -0
- data/docker/postgres_replica/cmd.sh +9 -0
- data/docker-compose.yml +98 -0
- data/lib/active_record/connection_adapters/mysql2_proxy_adapter.rb +39 -0
- data/lib/active_record/connection_adapters/postgresql_proxy_adapter.rb +1 -1
- data/lib/active_record/tasks/mysql2_proxy_database_tasks.rb +19 -0
- data/lib/active_record/tasks/postgresql_proxy_database_tasks.rb +3 -29
- data/lib/active_record_proxy_adapters/active_record_context.rb +0 -18
- data/lib/active_record_proxy_adapters/connection_handling.rb +26 -0
- data/lib/active_record_proxy_adapters/database_tasks.rb +39 -0
- data/lib/active_record_proxy_adapters/hijackable.rb +32 -3
- data/lib/active_record_proxy_adapters/mysql2_proxy.rb +9 -0
- data/lib/active_record_proxy_adapters/postgresql_proxy.rb +0 -2
- data/lib/active_record_proxy_adapters/primary_replica_proxy.rb +12 -61
- data/lib/active_record_proxy_adapters/version.rb +1 -1
- data/postgres_primary.dockerfile +34 -0
- data/postgres_replica.dockerfile +15 -0
- data/sig/active_record_proxy_adapters.rbs +4 -0
- metadata +23 -6
checksums.yaml
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
---
|
2
2
|
SHA256:
|
3
|
-
metadata.gz:
|
4
|
-
data.tar.gz:
|
3
|
+
metadata.gz: 1f614128aa280355a9bc8c83e29805fc36c81f8389c017489c848e075a5510c3
|
4
|
+
data.tar.gz: d28585b2d7d1f7645dfc89007890a2c35ee19c4acc6de1b850e4f3b792cc0c07
|
5
5
|
SHA512:
|
6
|
-
metadata.gz:
|
7
|
-
data.tar.gz:
|
6
|
+
metadata.gz: b3e36b3fe27bce5b1bdb9035fc399362f99d25062d97abc9024c02a30a8c6a328a2de3bdacda5682622c812f38f8b4a1da48d76e687131d3a6e07e44be4c6995
|
7
|
+
data.tar.gz: 053d2cfdea1db5699cd18404e8b22524a826012534eb0e077b307102021adeccde565f9e7b6417dbbe053669464a7220ab3e1e2cb3b92201cc0b296e8f23f5ce
|
data/.rspec
ADDED
data/.rubocop.yml
ADDED
@@ -0,0 +1,16 @@
|
|
1
|
+
require:
|
2
|
+
- rubocop-rspec
|
3
|
+
|
4
|
+
AllCops:
|
5
|
+
TargetRubyVersion: 3.1
|
6
|
+
NewCops: enable
|
7
|
+
|
8
|
+
Style/StringLiterals:
|
9
|
+
EnforcedStyle: double_quotes
|
10
|
+
|
11
|
+
Style/StringLiteralsInInterpolation:
|
12
|
+
EnforcedStyle: double_quotes
|
13
|
+
|
14
|
+
RSpec/NestedGroups:
|
15
|
+
Enabled: true
|
16
|
+
Max: 5
|
data/CHANGELOG.md
ADDED
@@ -0,0 +1,41 @@
|
|
1
|
+
## [Unreleased]
|
2
|
+
|
3
|
+
- Add Mysql2ProxyAdapter
|
4
|
+
|
5
|
+
## [0.2.2, 0.1.5] - 2025-01-02
|
6
|
+
|
7
|
+
- Handle PendingMigrationConnection introduced by Rails 7.2 and backported to Rails 7.1 https://github.com/Nasdaq/active_record_proxy_adapters/commit/793562694c05d554bad6e14637b34e5f9ffd2fc5
|
8
|
+
- Stick to same connection throughout request span https://github.com/Nasdaq/active_record_proxy_adapters/commit/789742fd7a33ecd555a995e8a1e1336455caec75
|
9
|
+
|
10
|
+
## [0.2.1] - 2025-01-02
|
11
|
+
|
12
|
+
- Fix replica connection pool getter when specific connection name is not found https://github.com/Nasdaq/active_record_proxy_adapters/commit/847e150dd21c5bc619745ee1d9d8fcaa9b8f2eea
|
13
|
+
|
14
|
+
## [0.2.0] - 2024-12-24
|
15
|
+
|
16
|
+
- Add custom log subscriber to tag queries based on the adapter being used https://github.com/Nasdaq/active_record_proxy_adapters/commit/68b8c1f4191388eb957bf12e0f84289da667e940
|
17
|
+
|
18
|
+
## [0.1.4] - 2025-01-02
|
19
|
+
|
20
|
+
- Fix replica connection pool getter when specific connection name is not found https://github.com/Nasdaq/active_record_proxy_adapters/commit/88b32a282b54d420e652f638656dbcf063ac8796
|
21
|
+
|
22
|
+
## [0.1.3] - 2024-12-24
|
23
|
+
|
24
|
+
- Fix replica connection pool getter when database configurations have multiple replicas https://github.com/Nasdaq/active_record_proxy_adapters/commit/ea5a33997da45ac073f166b3fbd2d12426053cd6
|
25
|
+
- Retrieve replica pool without checking out a connection https://github.com/Nasdaq/active_record_proxy_adapters/commit/6470ef58e851082ae1f7a860ecdb5b451ef903c8
|
26
|
+
|
27
|
+
## [0.1.2] - 2024-12-16
|
28
|
+
|
29
|
+
- Fix CTE regex matcher https://github.com/Nasdaq/active_record_proxy_adapters/commit/4b1d10bfd952fb1f5b102de8cc1a5bd05d25f5e9
|
30
|
+
|
31
|
+
## [0.1.1] - 2024-11-27
|
32
|
+
|
33
|
+
- Enable RubyGems MFA https://github.com/Nasdaq/active_record_proxy_adapters/commit/2a71b1f4354fb966cc0aa68231ca5837814e07ee
|
34
|
+
|
35
|
+
## [0.1.0] - 2024-11-19
|
36
|
+
|
37
|
+
- Add PostgreSQLProxyAdapter https://github.com/Nasdaq/active_record_proxy_adapters/commit/2b3bb9f7359139519b32af3018ceb07fed8c6b33
|
38
|
+
|
39
|
+
## [0.1.0.rc2] - 2024-10-28
|
40
|
+
|
41
|
+
- Add PostgreSQLProxyAdapter https://github.com/Nasdaq/active_record_proxy_adapters/commit/2b3bb9f7359139519b32af3018ceb07fed8c6b33
|
data/CODE_OF_CONDUCT.md
ADDED
@@ -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/Dockerfile
ADDED
@@ -0,0 +1,20 @@
|
|
1
|
+
ARG RUBY_VERSION=3.2.3
|
2
|
+
ARG DOCKER_REGISTRY=docker.io
|
3
|
+
FROM $DOCKER_REGISTRY/ruby:$RUBY_VERSION-alpine
|
4
|
+
ARG RAILS_VERSION="~> 6.1.0"
|
5
|
+
ENV RAILS_VERSION=$RAILS_VERSION
|
6
|
+
|
7
|
+
RUN apk --update add \
|
8
|
+
build-base \
|
9
|
+
git \
|
10
|
+
postgresql-dev \
|
11
|
+
postgresql17-client \
|
12
|
+
mariadb-client \
|
13
|
+
mariadb-dev
|
14
|
+
RUN gem install bundler -v 2.5.13
|
15
|
+
|
16
|
+
COPY . /app
|
17
|
+
WORKDIR /app
|
18
|
+
|
19
|
+
RUN bundle install
|
20
|
+
|
data/README.md
CHANGED
@@ -33,8 +33,19 @@ If bundler is not being used to manage dependencies, install the gem by executin
|
|
33
33
|
|
34
34
|
### On Rails
|
35
35
|
|
36
|
-
In `config/database.yml`, use `
|
36
|
+
In `config/database.yml`, use `{your_database_adapter}_proxy` as the adapter for the `primary` database, and keep `{your_database_adapter}` for the replica database.
|
37
37
|
|
38
|
+
Currently supported adapters:
|
39
|
+
|
40
|
+
- `postgresql`
|
41
|
+
- `mysql2`
|
42
|
+
|
43
|
+
Coming soon:
|
44
|
+
- `trilogy`
|
45
|
+
- `sqlite`
|
46
|
+
|
47
|
+
|
48
|
+
#### PostgreSQL
|
38
49
|
```yaml
|
39
50
|
# config/database.yml
|
40
51
|
development:
|
@@ -48,6 +59,20 @@ development:
|
|
48
59
|
# your replica credentials here
|
49
60
|
```
|
50
61
|
|
62
|
+
#### MySQL
|
63
|
+
```yaml
|
64
|
+
# config/database.yml
|
65
|
+
development:
|
66
|
+
primary:
|
67
|
+
adapter: mysql2_proxy
|
68
|
+
# your primary credentials here
|
69
|
+
|
70
|
+
primary_replica:
|
71
|
+
adapter: mysql2
|
72
|
+
replica: true
|
73
|
+
# your replica credentials here
|
74
|
+
```
|
75
|
+
|
51
76
|
```ruby
|
52
77
|
# app/models/application_record.rb
|
53
78
|
class ApplicationRecord < ActiveRecord::Base
|
@@ -90,7 +115,7 @@ end
|
|
90
115
|
|
91
116
|
## Configuration
|
92
117
|
|
93
|
-
The gem comes preconfigured out of the box. However, if default configuration does not suit your needs, you can modify
|
118
|
+
The gem comes preconfigured out of the box. However, if default configuration does not suit your needs, you can modify it by using a `.configure` block:
|
94
119
|
|
95
120
|
```ruby
|
96
121
|
# config/initializers/active_record_proxy_adapters.rb
|
@@ -239,6 +264,7 @@ end
|
|
239
264
|
|
240
265
|
# app/models/portal.rb
|
241
266
|
class Portal < ApplicationRecord
|
267
|
+
validates :name, uniqueness: true
|
242
268
|
end
|
243
269
|
|
244
270
|
# in rails console -e test
|
@@ -246,13 +272,17 @@ ActiveRecord::Base.logger.formatter = proc do |_severity, _time, _progname, msg|
|
|
246
272
|
"[#{Time.current.iso8601} THREAD #{Thread.current[:name]}] #{msg}\n"
|
247
273
|
end
|
248
274
|
|
275
|
+
ActiveRecordProxyAdapters.configure do |config|
|
276
|
+
config.proxy_delay = 2.seconds
|
277
|
+
end
|
278
|
+
|
249
279
|
def read_your_own_writes
|
250
280
|
proc do
|
251
281
|
Portal.all.count # should go to the replica
|
252
|
-
|
282
|
+
Portal.create(name: 'Read your own write')
|
253
283
|
|
254
284
|
5.times do
|
255
|
-
Portal.all.count # first one goes the primary, last
|
285
|
+
Portal.all.count # first one goes the primary, last 4 should go to the replica
|
256
286
|
sleep(3)
|
257
287
|
end
|
258
288
|
end
|
@@ -297,9 +327,8 @@ irb(main):051:0> test_multithread_queries
|
|
297
327
|
[2024-12-24T13:52:40-05:00 THREAD USE REPLICA] [PostgreSQL Replica] Portal Count (1.4ms) SELECT COUNT(*) FROM "portals"
|
298
328
|
[2024-12-24T13:52:40-05:00 THREAD READ YOUR OWN WRITES] [PostgreSQL Replica] Portal Count (0.4ms) SELECT COUNT(*) FROM "portals"
|
299
329
|
[2024-12-24T13:52:40-05:00 THREAD READ YOUR OWN WRITES] [PostgreSQLProxy Primary] TRANSACTION (0.5ms) BEGIN
|
300
|
-
[2024-12-24T13:52:40-05:00 THREAD READ YOUR OWN WRITES] [PostgreSQLProxy Primary] Portal Exists? (
|
301
|
-
[2024-12-24T13:52:40-05:00 THREAD READ YOUR OWN WRITES] [PostgreSQLProxy Primary] Portal
|
302
|
-
[2024-12-24T13:52:40-05:00 THREAD READ YOUR OWN WRITES] [PostgreSQLProxy Primary] Portal Create (0.8ms) INSERT INTO "portals" ("name", "slug", "logo", "created_at", "updated_at", "visible") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id" [["name", "Portal-e065948fbbee73d3b2c576b48c2b37e021115158edc6a92390d613640460e1d4"], ["slug", "portal-e065948fbbee73d3b2c576b48c2b37e021115158edc6a92390d613640460e1d4"], ["logo", nil], ["created_at", "2024-12-24 18:52:40.428383"], ["updated_at", "2024-12-24 18:52:40.428383"], ["visible", true]]
|
330
|
+
[2024-12-24T13:52:40-05:00 THREAD READ YOUR OWN WRITES] [PostgreSQLProxy Primary] Portal Exists? (0.4ms) SELECT 1 AS one FROM "portals" WHERE "portals"."name" = $1 LIMIT $2 [["name", "Read your own write"], ["LIMIT", 1]]
|
331
|
+
[2024-12-24T13:52:40-05:00 THREAD READ YOUR OWN WRITES] [PostgreSQLProxy Primary] Portal Create (0.8ms) INSERT INTO "portals" ("name", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["name", "Read your own write"], ["created_at", "2024-12-24 18:52:40.428383"], ["updated_at", "2024-12-24 18:52:40.428383"]]
|
303
332
|
[2024-12-24T13:52:40-05:00 THREAD READ YOUR OWN WRITES] [PostgreSQLProxy Primary] TRANSACTION (0.7ms) COMMIT
|
304
333
|
[2024-12-24T13:52:40-05:00 THREAD READ YOUR OWN WRITES] [PostgreSQLProxy Primary] Portal Count (0.6ms) SELECT COUNT(*) FROM "portals"
|
305
334
|
[2024-12-24T13:52:41-05:00 THREAD USE REPLICA] [PostgreSQL Replica] Portal Count (4.4ms) SELECT COUNT(*) FROM "portals"
|
@@ -0,0 +1,41 @@
|
|
1
|
+
/*M!999999\- enable the sandbox mode */
|
2
|
+
|
3
|
+
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
|
4
|
+
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
|
5
|
+
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
|
6
|
+
/*!40101 SET NAMES utf8mb4 */;
|
7
|
+
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
|
8
|
+
/*!40103 SET TIME_ZONE='+00:00' */;
|
9
|
+
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
|
10
|
+
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
|
11
|
+
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
|
12
|
+
/*M!100616 SET @OLD_NOTE_VERBOSITY=@@NOTE_VERBOSITY, NOTE_VERBOSITY=0 */;
|
13
|
+
DROP TABLE IF EXISTS `schema_migrations`;
|
14
|
+
/*!40101 SET @saved_cs_client = @@character_set_client */;
|
15
|
+
/*!40101 SET character_set_client = utf8 */;
|
16
|
+
CREATE TABLE `schema_migrations` (
|
17
|
+
`version` varchar(255) NOT NULL
|
18
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
|
19
|
+
/*!40101 SET character_set_client = @saved_cs_client */;
|
20
|
+
DROP TABLE IF EXISTS `users`;
|
21
|
+
/*!40101 SET @saved_cs_client = @@character_set_client */;
|
22
|
+
/*!40101 SET character_set_client = utf8 */;
|
23
|
+
CREATE TABLE `users` (
|
24
|
+
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
|
25
|
+
`name` text NOT NULL,
|
26
|
+
`email` text NOT NULL,
|
27
|
+
`created_at` timestamp NULL DEFAULT current_timestamp(),
|
28
|
+
`updated_at` timestamp NULL DEFAULT current_timestamp(),
|
29
|
+
PRIMARY KEY (`id`)
|
30
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
|
31
|
+
/*!40101 SET character_set_client = @saved_cs_client */;
|
32
|
+
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
|
33
|
+
|
34
|
+
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
|
35
|
+
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
|
36
|
+
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
|
37
|
+
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
|
38
|
+
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
|
39
|
+
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
40
|
+
/*M!100616 SET NOTE_VERBOSITY=@OLD_NOTE_VERBOSITY */;
|
41
|
+
|
@@ -0,0 +1,86 @@
|
|
1
|
+
SET statement_timeout = 0;
|
2
|
+
SET lock_timeout = 0;
|
3
|
+
SET idle_in_transaction_session_timeout = 0;
|
4
|
+
SET transaction_timeout = 0;
|
5
|
+
SET client_encoding = 'UTF8';
|
6
|
+
SET standard_conforming_strings = on;
|
7
|
+
SELECT pg_catalog.set_config('search_path', '', false);
|
8
|
+
SET check_function_bodies = false;
|
9
|
+
SET xmloption = content;
|
10
|
+
SET client_min_messages = warning;
|
11
|
+
SET row_security = off;
|
12
|
+
|
13
|
+
SET default_tablespace = '';
|
14
|
+
|
15
|
+
SET default_table_access_method = heap;
|
16
|
+
|
17
|
+
--
|
18
|
+
-- Name: schema_migrations; Type: TABLE; Schema: public; Owner: -
|
19
|
+
--
|
20
|
+
|
21
|
+
CREATE TABLE public.schema_migrations (
|
22
|
+
version character varying(255) NOT NULL
|
23
|
+
);
|
24
|
+
|
25
|
+
|
26
|
+
--
|
27
|
+
-- Name: users; Type: TABLE; Schema: public; Owner: -
|
28
|
+
--
|
29
|
+
|
30
|
+
CREATE TABLE public.users (
|
31
|
+
id integer NOT NULL,
|
32
|
+
name text NOT NULL,
|
33
|
+
email text NOT NULL,
|
34
|
+
created_at timestamp without time zone DEFAULT now() NOT NULL,
|
35
|
+
updated_at timestamp without time zone DEFAULT now() NOT NULL
|
36
|
+
);
|
37
|
+
|
38
|
+
|
39
|
+
--
|
40
|
+
-- Name: users_id_seq; Type: SEQUENCE; Schema: public; Owner: -
|
41
|
+
--
|
42
|
+
|
43
|
+
CREATE SEQUENCE public.users_id_seq
|
44
|
+
AS integer
|
45
|
+
START WITH 1
|
46
|
+
INCREMENT BY 1
|
47
|
+
NO MINVALUE
|
48
|
+
NO MAXVALUE
|
49
|
+
CACHE 1;
|
50
|
+
|
51
|
+
|
52
|
+
--
|
53
|
+
-- Name: users_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
|
54
|
+
--
|
55
|
+
|
56
|
+
ALTER SEQUENCE public.users_id_seq OWNED BY public.users.id;
|
57
|
+
|
58
|
+
|
59
|
+
--
|
60
|
+
-- Name: users id; Type: DEFAULT; Schema: public; Owner: -
|
61
|
+
--
|
62
|
+
|
63
|
+
ALTER TABLE ONLY public.users ALTER COLUMN id SET DEFAULT nextval('public.users_id_seq'::regclass);
|
64
|
+
|
65
|
+
|
66
|
+
--
|
67
|
+
-- Name: users users_pkey; Type: CONSTRAINT; Schema: public; Owner: -
|
68
|
+
--
|
69
|
+
|
70
|
+
ALTER TABLE ONLY public.users
|
71
|
+
ADD CONSTRAINT users_pkey PRIMARY KEY (id);
|
72
|
+
|
73
|
+
|
74
|
+
--
|
75
|
+
-- Name: unique_schema_migrations; Type: INDEX; Schema: public; Owner: -
|
76
|
+
--
|
77
|
+
|
78
|
+
CREATE UNIQUE INDEX unique_schema_migrations ON public.schema_migrations USING btree (version);
|
79
|
+
|
80
|
+
|
81
|
+
--
|
82
|
+
-- PostgreSQL database dump complete
|
83
|
+
--
|
84
|
+
|
85
|
+
SET search_path TO "$user", public;
|
86
|
+
|
@@ -0,0 +1,9 @@
|
|
1
|
+
until pg_basebackup --pgdata=/var/lib/postgresql/data -R --slot=$PRIMARY_REPLICATION_SLOT --host=$PRIMARY_DATABASE_HOST --port=$PRIMARY_DATABASE_PORT
|
2
|
+
do
|
3
|
+
echo 'Waiting for primary to connect...'
|
4
|
+
sleep 1s
|
5
|
+
done
|
6
|
+
|
7
|
+
echo 'Backup done, starting replica...'
|
8
|
+
chmod 0700 /var/lib/postgresql/data
|
9
|
+
postgres
|
data/docker-compose.yml
ADDED
@@ -0,0 +1,98 @@
|
|
1
|
+
name: active_record_proxy_adapters
|
2
|
+
|
3
|
+
x-postgres-common: &postgres-common
|
4
|
+
restart: always
|
5
|
+
user: postgres
|
6
|
+
healthcheck:
|
7
|
+
test: 'pg_isready -U postgres_primary_test --dbname=postgres'
|
8
|
+
interval: 10s
|
9
|
+
timeout: 5s
|
10
|
+
retries: 5
|
11
|
+
networks:
|
12
|
+
- postgres
|
13
|
+
|
14
|
+
services:
|
15
|
+
app:
|
16
|
+
build:
|
17
|
+
args:
|
18
|
+
- RUBY_VERSION=${RUBY_VERSION:-3.3.6}
|
19
|
+
- RAILS_VERSION=${RAILS_VERSION:-8.0.0}
|
20
|
+
container_name: app
|
21
|
+
image: active_record_proxy_adapters-app:${ENV_TAG:-latest}
|
22
|
+
tty: true
|
23
|
+
stdin_open: true
|
24
|
+
environment:
|
25
|
+
PGHOST: postgres_primary
|
26
|
+
PG_PRIMARY_USER: postgres_primary_test
|
27
|
+
PG_PRIMARY_PASSWORD: postgres_primary_test
|
28
|
+
PG_PRIMARY_HOST: postgres_primary
|
29
|
+
PG_PRIMARY_PORT: 5432
|
30
|
+
PG_REPLICA_USER: postgres_primary_test
|
31
|
+
PG_REPLICA_PASSWORD: postgres_primary_test
|
32
|
+
PG_REPLICA_HOST: postgres_replica
|
33
|
+
PG_REPLICA_PORT: 5432
|
34
|
+
MYSQL_PRIMARY_USER: root
|
35
|
+
MYSQL_PRIMARY_PASSWORD: mysql
|
36
|
+
MYSQL_PRIMARY_HOST: mysql_primary
|
37
|
+
MYSQL_PRIMARY_PORT: 3306
|
38
|
+
MYSQL_REPLICA_USER: root
|
39
|
+
MYSQL_REPLICA_PASSWORD: mysql
|
40
|
+
MYSQL_REPLICA_HOST: mysql_primary
|
41
|
+
MYSQL_REPLICA_PORT: 3306
|
42
|
+
depends_on:
|
43
|
+
- postgres_primary
|
44
|
+
- postgres_replica
|
45
|
+
- mariadb
|
46
|
+
networks:
|
47
|
+
- app
|
48
|
+
- postgres
|
49
|
+
- mariadb
|
50
|
+
volumes:
|
51
|
+
- .:/app
|
52
|
+
postgres_primary:
|
53
|
+
<<: *postgres-common
|
54
|
+
build:
|
55
|
+
context: .
|
56
|
+
dockerfile: postgres_primary.dockerfile
|
57
|
+
args:
|
58
|
+
- POSTGRES_LOGGING_COLLECTOR=${POSTGRES_LOGGING_COLLECTOR:-}
|
59
|
+
- POSTGRES_LOG_DESTINATION=${POSTGRES_LOG_DESTINATION:-}
|
60
|
+
- POSTGRES_LOG_STATEMENT=${POSTGRES_LOG_STATEMENT:-}
|
61
|
+
- REPLICA_USER=replicator
|
62
|
+
- REPLICA_PASSWORD=replicator
|
63
|
+
container_name: postgres_primary
|
64
|
+
environment:
|
65
|
+
POSTGRES_DB: postgres
|
66
|
+
POSTGRES_USER: postgres_primary_test
|
67
|
+
POSTGRES_PASSWORD: postgres_primary_test
|
68
|
+
POSTGRES_HOST_AUTH_METHOD: "scram-sha-256\nhost replication all 0.0.0.0/0 md5"
|
69
|
+
POSTGRES_INITDB_ARGS: "--auth-host=scram-sha-256"
|
70
|
+
|
71
|
+
postgres_replica:
|
72
|
+
<<: *postgres-common
|
73
|
+
build:
|
74
|
+
context: .
|
75
|
+
dockerfile: postgres_replica.dockerfile
|
76
|
+
container_name: postgres_replica
|
77
|
+
environment:
|
78
|
+
PGUSER: replicator
|
79
|
+
PGPASSWORD: replicator
|
80
|
+
PRIMARY_DATABASE_HOST: postgres_primary
|
81
|
+
depends_on:
|
82
|
+
- postgres_primary
|
83
|
+
# TODO: create mysql replica images
|
84
|
+
mariadb:
|
85
|
+
image: mariadb:11.4
|
86
|
+
container_name: mysql_primary
|
87
|
+
environment:
|
88
|
+
MARIADB_ROOT_PASSWORD: mysql
|
89
|
+
MARIADB_DATABASE: mysql
|
90
|
+
ports:
|
91
|
+
- "3306:3306"
|
92
|
+
networks:
|
93
|
+
- mariadb
|
94
|
+
|
95
|
+
networks:
|
96
|
+
app:
|
97
|
+
postgres:
|
98
|
+
mariadb:
|
@@ -0,0 +1,39 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require "active_record/tasks/mysql2_proxy_database_tasks"
|
4
|
+
require "active_record/connection_adapters/mysql2_adapter"
|
5
|
+
require "active_record_proxy_adapters/active_record_context"
|
6
|
+
require "active_record_proxy_adapters/hijackable"
|
7
|
+
require "active_record_proxy_adapters/mysql2_proxy"
|
8
|
+
|
9
|
+
module ActiveRecord
|
10
|
+
module ConnectionAdapters
|
11
|
+
# This adapter is a proxy to the original Mysql2Adapter, allowing the use of the
|
12
|
+
# ActiveRecordProxyAdapters::PrimaryReplicaProxy.
|
13
|
+
class Mysql2ProxyAdapter < Mysql2Adapter
|
14
|
+
include ActiveRecordProxyAdapters::Hijackable
|
15
|
+
|
16
|
+
ADAPTER_NAME = "Mysql2Proxy"
|
17
|
+
|
18
|
+
delegate_to_proxy :execute, :exec_query
|
19
|
+
|
20
|
+
def initialize(...)
|
21
|
+
@proxy = ActiveRecordProxyAdapters::Mysql2Proxy.new(self)
|
22
|
+
|
23
|
+
super
|
24
|
+
end
|
25
|
+
|
26
|
+
private
|
27
|
+
|
28
|
+
attr_reader :proxy
|
29
|
+
end
|
30
|
+
end
|
31
|
+
end
|
32
|
+
|
33
|
+
if ActiveRecordProxyAdapters::ActiveRecordContext.active_record_v7_2_or_greater?
|
34
|
+
ActiveRecord::ConnectionAdapters.register(
|
35
|
+
"mysql2_proxy",
|
36
|
+
"ActiveRecord::ConnectionAdapters::Mysql2ProxyAdapter",
|
37
|
+
"active_record/connection_adapters/mysql2_proxy_adapter"
|
38
|
+
)
|
39
|
+
end
|
@@ -15,7 +15,7 @@ module ActiveRecord
|
|
15
15
|
|
16
16
|
ADAPTER_NAME = "PostgreSQLProxy"
|
17
17
|
|
18
|
-
delegate_to_proxy
|
18
|
+
delegate_to_proxy :execute, :exec_query
|
19
19
|
|
20
20
|
unless ActiveRecordProxyAdapters::ActiveRecordContext.active_record_v8_0_or_greater?
|
21
21
|
delegate_to_proxy :exec_no_cache, :exec_cache
|
@@ -0,0 +1,19 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require "active_record_proxy_adapters/database_tasks"
|
4
|
+
|
5
|
+
module ActiveRecord
|
6
|
+
module Tasks
|
7
|
+
# Defines the mysql tasks for dropping, creating, loading schema and dumping schema.
|
8
|
+
# Bypasses all the proxy logic to send all requests to primary.
|
9
|
+
class Mysql2ProxyDatabaseTasks < MySQLDatabaseTasks
|
10
|
+
include ActiveRecordProxyAdapters::DatabaseTasks
|
11
|
+
end
|
12
|
+
end
|
13
|
+
end
|
14
|
+
|
15
|
+
# Allow proxy adapter to run rake tasks, i.e. db:drop, db:create, db:schema:load db:migrate, etc...
|
16
|
+
ActiveRecord::Tasks::DatabaseTasks.register_task(
|
17
|
+
/mysql2_proxy/,
|
18
|
+
"ActiveRecord::Tasks::Mysql2ProxyDatabaseTasks"
|
19
|
+
)
|
@@ -1,39 +1,13 @@
|
|
1
1
|
# frozen_string_literal: true
|
2
2
|
|
3
|
+
require "active_record_proxy_adapters/database_tasks"
|
4
|
+
|
3
5
|
module ActiveRecord
|
4
6
|
module Tasks
|
5
7
|
# Defines the postgresql tasks for dropping, creating, loading schema and dumping schema.
|
6
8
|
# Bypasses all the proxy logic to send all requests to primary.
|
7
9
|
class PostgreSQLProxyDatabaseTasks < PostgreSQLDatabaseTasks
|
8
|
-
|
9
|
-
sticking_to_primary { super }
|
10
|
-
end
|
11
|
-
|
12
|
-
def drop(...)
|
13
|
-
sticking_to_primary { super }
|
14
|
-
end
|
15
|
-
|
16
|
-
def structure_dump(...)
|
17
|
-
sticking_to_primary { super }
|
18
|
-
end
|
19
|
-
|
20
|
-
def structure_load(...)
|
21
|
-
sticking_to_primary { super }
|
22
|
-
end
|
23
|
-
|
24
|
-
def purge(...)
|
25
|
-
sticking_to_primary { super }
|
26
|
-
end
|
27
|
-
|
28
|
-
private
|
29
|
-
|
30
|
-
def sticking_to_primary(&)
|
31
|
-
ActiveRecord::Base.connected_to(role: context.writing_role, &)
|
32
|
-
end
|
33
|
-
|
34
|
-
def context
|
35
|
-
ActiveRecordProxyAdapters::ActiveRecordContext.new
|
36
|
-
end
|
10
|
+
include ActiveRecordProxyAdapters::DatabaseTasks
|
37
11
|
end
|
38
12
|
end
|
39
13
|
end
|
@@ -23,8 +23,6 @@ module ActiveRecordProxyAdapters
|
|
23
23
|
end
|
24
24
|
|
25
25
|
def connection_class_for(connection)
|
26
|
-
return connection.connection_descriptor.name.constantize if active_record_v8_0_2_or_greater?
|
27
|
-
|
28
26
|
connection.connection_class || ActiveRecord::Base
|
29
27
|
end
|
30
28
|
|
@@ -35,18 +33,6 @@ module ActiveRecordProxyAdapters
|
|
35
33
|
ActiveRecord
|
36
34
|
end
|
37
35
|
|
38
|
-
def hijackable_methods
|
39
|
-
hijackable = %i[execute exec_query]
|
40
|
-
|
41
|
-
hijackable << :internal_exec_query if active_record_v8_0_or_greater?
|
42
|
-
|
43
|
-
hijackable
|
44
|
-
end
|
45
|
-
|
46
|
-
def active_record_v7?
|
47
|
-
active_record_version >= Gem::Version.new("7.0") && active_record_version < Gem::Version.new("8.0")
|
48
|
-
end
|
49
|
-
|
50
36
|
def active_record_v7_1_or_greater?
|
51
37
|
active_record_version >= Gem::Version.new("7.1")
|
52
38
|
end
|
@@ -58,9 +44,5 @@ module ActiveRecordProxyAdapters
|
|
58
44
|
def active_record_v8_0_or_greater?
|
59
45
|
active_record_version >= Gem::Version.new("8.0")
|
60
46
|
end
|
61
|
-
|
62
|
-
def active_record_v8_0_2_or_greater?
|
63
|
-
active_record_version >= Gem::Version.new("8.0.2")
|
64
|
-
end
|
65
47
|
end
|
66
48
|
end
|
@@ -1,6 +1,7 @@
|
|
1
1
|
# frozen_string_literal: true
|
2
2
|
|
3
3
|
require "active_record/connection_adapters/postgresql_proxy_adapter"
|
4
|
+
require "active_record/connection_adapters/mysql2_proxy_adapter"
|
4
5
|
|
5
6
|
module ActiveRecordProxyAdapters
|
6
7
|
# Module to extend ActiveRecord::Base with the connection handling methods.
|
@@ -31,5 +32,30 @@ module ActiveRecordProxyAdapters
|
|
31
32
|
config
|
32
33
|
)
|
33
34
|
end
|
35
|
+
|
36
|
+
def mysql2_proxy_adapter_class
|
37
|
+
::ActiveRecord::ConnectionAdapters::Mysql2ProxyAdapter
|
38
|
+
end
|
39
|
+
|
40
|
+
# This method is a copy and paste from Rails' mysql2_connection,
|
41
|
+
# replacing Mysql2Adapter by Mysql2ProxyAdapter
|
42
|
+
# This is required by ActiveRecord versions <= 7.2.x to establish a connection using the adapter.
|
43
|
+
def mysql2_proxy_connection(config) # rubocop:disable Metrics/MethodLength
|
44
|
+
config = config.symbolize_keys
|
45
|
+
config[:flags] ||= 0
|
46
|
+
|
47
|
+
if config[:flags].is_a? Array
|
48
|
+
config[:flags].push "FOUND_ROWS"
|
49
|
+
else
|
50
|
+
config[:flags] |= Mysql2::Client::FOUND_ROWS
|
51
|
+
end
|
52
|
+
|
53
|
+
mysql2_proxy_adapter_class.new(
|
54
|
+
mysql2_proxy_adapter_class.new_client(config),
|
55
|
+
logger,
|
56
|
+
nil,
|
57
|
+
config
|
58
|
+
)
|
59
|
+
end
|
34
60
|
end
|
35
61
|
end
|
@@ -0,0 +1,39 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module ActiveRecordProxyAdapters
|
4
|
+
module DatabaseTasks # rubocop:disable Style/Documentation
|
5
|
+
extend ActiveSupport::Concern
|
6
|
+
|
7
|
+
included do
|
8
|
+
def create(...)
|
9
|
+
sticking_to_primary { super }
|
10
|
+
end
|
11
|
+
|
12
|
+
def drop(...)
|
13
|
+
sticking_to_primary { super }
|
14
|
+
end
|
15
|
+
|
16
|
+
def structure_dump(...)
|
17
|
+
sticking_to_primary { super }
|
18
|
+
end
|
19
|
+
|
20
|
+
def structure_load(...)
|
21
|
+
sticking_to_primary { super }
|
22
|
+
end
|
23
|
+
|
24
|
+
def purge(...)
|
25
|
+
sticking_to_primary { super }
|
26
|
+
end
|
27
|
+
|
28
|
+
private
|
29
|
+
|
30
|
+
def sticking_to_primary(&)
|
31
|
+
ActiveRecord::Base.connected_to(role: context.writing_role, &)
|
32
|
+
end
|
33
|
+
|
34
|
+
def context
|
35
|
+
ActiveRecordProxyAdapters::ActiveRecordContext.new
|
36
|
+
end
|
37
|
+
end
|
38
|
+
end
|
39
|
+
end
|
@@ -2,14 +2,13 @@
|
|
2
2
|
|
3
3
|
require "active_record/tasks/postgresql_proxy_database_tasks"
|
4
4
|
require "active_record/connection_adapters/postgresql_adapter"
|
5
|
-
require "active_record_proxy_adapters/primary_replica_proxy"
|
6
5
|
|
7
6
|
module ActiveRecordProxyAdapters
|
8
7
|
# Defines mixins to delegate specific methods from the proxy to the adapter.
|
9
8
|
module Hijackable
|
10
9
|
extend ActiveSupport::Concern
|
11
10
|
|
12
|
-
class_methods do
|
11
|
+
class_methods do # rubocop:disable Metrics/BlockLength
|
13
12
|
# Renames the methods from the original Adapter using the proxy suffix (_unproxied)
|
14
13
|
# and delegate the original method name to the proxy.
|
15
14
|
# Example: delegate_to_proxy(:execute) creates a method `execute_unproxied`,
|
@@ -32,10 +31,40 @@ module ActiveRecordProxyAdapters
|
|
32
31
|
delegate(*method_names, to: :proxy)
|
33
32
|
end
|
34
33
|
|
34
|
+
# Defines which methods should be hijacked from the original adapter and use the proxy
|
35
|
+
# @param method_names [Array<Symbol>] the list of method names from the adapter
|
36
|
+
def hijack_method(*method_names) # rubocop:disable Metrics/MethodLength
|
37
|
+
@hijacked_methods ||= Set.new
|
38
|
+
@hijacked_methods += Set.new(method_names)
|
39
|
+
|
40
|
+
method_names.each do |method_name|
|
41
|
+
define_method(method_name) do |*args, **kwargs, &block|
|
42
|
+
proxy_bypass_method = "#{method_name}#{unproxied_method_suffix}"
|
43
|
+
sql_string = coerce_query_to_string(args.first)
|
44
|
+
|
45
|
+
appropriate_connection(sql_string) do |conn|
|
46
|
+
method_to_call = conn == primary_connection ? proxy_bypass_method : method_name
|
47
|
+
|
48
|
+
conn.send(method_to_call, *args, **kwargs, &block)
|
49
|
+
end
|
50
|
+
end
|
51
|
+
end
|
52
|
+
end
|
53
|
+
|
54
|
+
def unproxied_method_suffix
|
55
|
+
"_unproxied"
|
56
|
+
end
|
57
|
+
|
35
58
|
private
|
36
59
|
|
37
60
|
def proxy_method_name_for(method_name)
|
38
|
-
:"#{method_name}#{
|
61
|
+
:"#{method_name}#{unproxied_method_suffix}"
|
62
|
+
end
|
63
|
+
end
|
64
|
+
|
65
|
+
included do
|
66
|
+
def unproxied_method_suffix
|
67
|
+
self.class.unproxied_method_suffix
|
39
68
|
end
|
40
69
|
end
|
41
70
|
end
|
@@ -0,0 +1,9 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require "active_record_proxy_adapters/primary_replica_proxy"
|
4
|
+
|
5
|
+
module ActiveRecordProxyAdapters
|
6
|
+
# Proxy to the original Mysql2Adapter, allowing the use of the ActiveRecordProxyAdapters::PrimaryReplicaProxy.
|
7
|
+
class Mysql2Proxy < PrimaryReplicaProxy
|
8
|
+
end
|
9
|
+
end
|
@@ -7,8 +7,6 @@ module ActiveRecordProxyAdapters
|
|
7
7
|
# Proxy to the original PostgreSQLAdapter, allowing the use of the ActiveRecordProxyAdapters::PrimaryReplicaProxy.
|
8
8
|
class PostgreSQLProxy < PrimaryReplicaProxy
|
9
9
|
# ActiveRecord::PostgreSQLAdapter methods that should be proxied.
|
10
|
-
hijack_method(*ActiveRecordContext.hijackable_methods)
|
11
|
-
|
12
10
|
hijack_method :exec_no_cache, :exec_cache unless ActiveRecordContext.active_record_v8_0_or_greater?
|
13
11
|
end
|
14
12
|
end
|
@@ -5,59 +5,32 @@ require "active_support/core_ext/module/delegation"
|
|
5
5
|
require "active_support/core_ext/object/blank"
|
6
6
|
require "concurrent-ruby"
|
7
7
|
require "active_record_proxy_adapters/active_record_context"
|
8
|
+
require "active_record_proxy_adapters/hijackable"
|
8
9
|
|
9
10
|
module ActiveRecordProxyAdapters
|
10
11
|
# This is the base class for all proxies. It defines the methods that should be proxied
|
11
12
|
# and the logic to determine which database to use.
|
12
13
|
class PrimaryReplicaProxy # rubocop:disable Metrics/ClassLength
|
14
|
+
include Hijackable
|
15
|
+
|
13
16
|
# All queries that match these patterns should be sent to the primary database
|
14
17
|
SQL_PRIMARY_MATCHERS = [
|
15
18
|
/\A\s*select.+for update\Z/i, /select.+lock in share mode\Z/i,
|
16
19
|
/\A\s*select.+(nextval|currval|lastval|get_lock|release_lock|pg_advisory_lock|pg_advisory_unlock)\(/i
|
17
20
|
].map(&:freeze).freeze
|
18
|
-
|
19
|
-
CTE_MATCHER = /\A\s*WITH\s+(?<CTE>\S+\s+AS\s+\(\s?[\s\S]*\))/i
|
20
21
|
# All queries that match these patterns should be sent to the replica database
|
21
|
-
SQL_REPLICA_MATCHERS
|
22
|
-
/\A\s*(select)\s/i,
|
23
|
-
/#{CTE_MATCHER.source}\s*select/i
|
24
|
-
].map(&:freeze).freeze
|
22
|
+
SQL_REPLICA_MATCHERS = [/\A\s*(select|with\s[\s\S]*\)\s*select)\s/i].map(&:freeze).freeze
|
25
23
|
# All queries that match these patterns should be sent to all databases
|
26
24
|
SQL_ALL_MATCHERS = [/\A\s*set\s/i].map(&:freeze).freeze
|
27
25
|
# Local sets queries should not be sent to all datbases
|
28
26
|
SQL_SKIP_ALL_MATCHERS = [/\A\s*set\s+local\s/i].map(&:freeze).freeze
|
29
27
|
# These patterns define which database statments are considered write statments, so we can shortly re-route all
|
30
28
|
# requests to the primary database so the replica has time to replicate
|
31
|
-
WRITE_STATEMENT_MATCHERS = [
|
32
|
-
|
33
|
-
/\ACOMMIT/i,
|
34
|
-
/INSERT\s[\s\S]*INTO\s[\s\S]*/i,
|
35
|
-
/UPDATE\s[\s\S]*/i,
|
36
|
-
/DELETE\s[\s\S]*FROM\s[\s\S]*/i,
|
37
|
-
/DROP\s/i
|
38
|
-
].map(&:freeze).freeze
|
39
|
-
|
40
|
-
UNPROXIED_METHOD_SUFFIX = "_unproxied"
|
29
|
+
WRITE_STATEMENT_MATCHERS = [/\ABEGIN/i, /\ACOMMIT/i, /INSERT\sINTO\s/i, /UPDATE\s/i, /DELETE\sFROM\s/i,
|
30
|
+
/DROP\s/i].map(&:freeze).freeze
|
41
31
|
|
42
|
-
#
|
43
|
-
|
44
|
-
def self.hijack_method(*method_names) # rubocop:disable Metrics/MethodLength
|
45
|
-
@hijacked_methods ||= Set.new
|
46
|
-
@hijacked_methods += Set.new(method_names)
|
47
|
-
|
48
|
-
method_names.each do |method_name|
|
49
|
-
define_method(method_name) do |*args, **kwargs, &block|
|
50
|
-
proxy_bypass_method = "#{method_name}#{UNPROXIED_METHOD_SUFFIX}"
|
51
|
-
sql_string = coerce_query_to_string(args.first)
|
52
|
-
|
53
|
-
appropriate_connection(sql_string) do |conn|
|
54
|
-
method_to_call = conn == primary_connection ? proxy_bypass_method : method_name
|
55
|
-
|
56
|
-
conn.send(method_to_call, *args, **kwargs, &block)
|
57
|
-
end
|
58
|
-
end
|
59
|
-
end
|
60
|
-
end
|
32
|
+
# Abstract adapter methods that should be proxied.
|
33
|
+
hijack_method :execute, :exec_query
|
61
34
|
|
62
35
|
def self.hijacked_methods
|
63
36
|
@hijacked_methods.to_a
|
@@ -77,22 +50,6 @@ module ActiveRecordProxyAdapters
|
|
77
50
|
delegate :connection_handler, to: :connection_class
|
78
51
|
delegate :reading_role, :writing_role, to: :active_record_context
|
79
52
|
|
80
|
-
# We need to call .verify! to ensure `configure_connection` is called on the instance before attempting to use it.
|
81
|
-
# This is necessary because the connection may have been lazily initialized and is an unintended side effect from a
|
82
|
-
# change in Rails to defer connection verification: https://github.com/rails/rails/pull/44576
|
83
|
-
# verify! cannot be called before the object is initialized and because of how the proxy hooks into the connection
|
84
|
-
# instance, it has to be done lazily (hence the memoization). Ideally, we shouldn't have to worry about this at all
|
85
|
-
# But there is tight coupling between methods in ActiveRecord::ConnectionAdapters::AbstractAdapter and
|
86
|
-
# its descendants which will require significant refactoring to be decoupled.
|
87
|
-
# See https://github.com/rails/rails/issues/51780
|
88
|
-
def verified_primary_connection
|
89
|
-
@verified_primary_connection ||= begin
|
90
|
-
connected_to(role: writing_role) { primary_connection.verify! }
|
91
|
-
|
92
|
-
primary_connection
|
93
|
-
end
|
94
|
-
end
|
95
|
-
|
96
53
|
def replica_pool_unavailable?
|
97
54
|
!replica_pool
|
98
55
|
end
|
@@ -163,8 +120,7 @@ module ActiveRecordProxyAdapters
|
|
163
120
|
end
|
164
121
|
|
165
122
|
def connection_for(role, sql_string)
|
166
|
-
connection =
|
167
|
-
|
123
|
+
connection = primary_connection if role == writing_role || replica_pool_unavailable?
|
168
124
|
connection ||= checkout_replica_connection
|
169
125
|
|
170
126
|
result = connected_to(role:) { yield connection }
|
@@ -198,21 +154,16 @@ module ActiveRecordProxyAdapters
|
|
198
154
|
# @return [TrueClass] if there has been a write within the last {#proxy_delay} seconds
|
199
155
|
# @return [TrueClass] if sql_string matches a write statement (i.e. INSERT, UPDATE, DELETE, SELECT FOR UPDATE)
|
200
156
|
# @return [FalseClass] if sql_string matches a read statement (i.e. SELECT)
|
201
|
-
def need_primary?(sql_string)
|
202
|
-
return true
|
157
|
+
def need_primary?(sql_string)
|
158
|
+
return true if recent_write_to_primary?
|
159
|
+
|
203
160
|
return true if in_transaction?
|
204
|
-
return true if cte_for_write?(sql_string)
|
205
161
|
return true if SQL_PRIMARY_MATCHERS.any?(&match_sql?(sql_string))
|
206
162
|
return false if SQL_REPLICA_MATCHERS.any?(&match_sql?(sql_string))
|
207
163
|
|
208
164
|
true
|
209
165
|
end
|
210
166
|
|
211
|
-
def cte_for_write?(sql_string)
|
212
|
-
CTE_MATCHER.match?(sql_string) &&
|
213
|
-
WRITE_STATEMENT_MATCHERS.any?(&match_sql?(sql_string))
|
214
|
-
end
|
215
|
-
|
216
167
|
def need_all?(sql_string)
|
217
168
|
return false if SQL_SKIP_ALL_MATCHERS.any?(&match_sql?(sql_string))
|
218
169
|
|
@@ -0,0 +1,34 @@
|
|
1
|
+
FROM docker.io/postgres:17-alpine
|
2
|
+
|
3
|
+
ARG REPLICA_USER=replicator
|
4
|
+
ARG REPLICA_PASSWORD=replicator
|
5
|
+
ARG REPLICATION_SLOT_NAME=replication_slot
|
6
|
+
ARG INIT_SQL=00_init.sql
|
7
|
+
ARG POSTGRES_LOGGING_COLLECTOR=
|
8
|
+
ARG POSTGRES_LOG_DESTINATION=
|
9
|
+
ARG POSTGRES_LOG_STATEMENT=
|
10
|
+
ENV CONF_SAMPLE="/usr/local/share/postgresql/postgresql.conf.sample"
|
11
|
+
|
12
|
+
WORKDIR /docker-entrypoint-initdb.d
|
13
|
+
|
14
|
+
USER root
|
15
|
+
|
16
|
+
RUN touch $INIT_SQL
|
17
|
+
RUN chown -R postgres:postgres $INIT_SQL
|
18
|
+
RUN echo "CREATE USER ${REPLICA_USER} WITH REPLICATION ENCRYPTED PASSWORD '${REPLICA_PASSWORD}';" > $INIT_SQL
|
19
|
+
RUN echo "SELECT pg_create_physical_replication_slot('${REPLICATION_SLOT_NAME}');" >> $INIT_SQL
|
20
|
+
|
21
|
+
# Enable logging collector if given
|
22
|
+
RUN if [[ ! -z "${POSTGRES_LOGGING_COLLECTOR}" ]]; then sed -i "s/#\(logging_collector = \)off\(.*\)/\1${POSTGRES_LOGGING_COLLECTOR}\2/" ${CONF_SAMPLE}; fi
|
23
|
+
|
24
|
+
# Override default log destination if given
|
25
|
+
RUN if [[ ! -z "${POSTGRES_LOG_DESTINATION}" ]]; then sed -i "s/#\(log_destination = \)'stderr'\(.*\)/\1'${POSTGRES_LOG_DESTINATION}'\2/" ${CONF_SAMPLE}; fi
|
26
|
+
|
27
|
+
# Override log statement if given
|
28
|
+
RUN if [[ ! -z "${POSTGRES_LOG_STATEMENT}" ]]; then sed -i "s/#\(log_statement = \)'none'\(.*\)/\1'${POSTGRES_LOG_STATEMENT}'\2/" ${CONF_SAMPLE}; fi
|
29
|
+
|
30
|
+
WORKDIR /
|
31
|
+
|
32
|
+
USER postgres
|
33
|
+
|
34
|
+
CMD ["postgres", "-c", "wal_level=replica", "-c", "hot_standby=on", "-c", "max_wal_senders=10", "-c", "max_replication_slots=10", "-c", "hot_standby_feedback=on" ]
|
@@ -0,0 +1,15 @@
|
|
1
|
+
FROM docker.io/postgres:17-alpine
|
2
|
+
|
3
|
+
ENV PRIMARY_DATABASE_HOST=localhost
|
4
|
+
ENV PRIMARY_DATABASE_PORT=5432
|
5
|
+
ENV PRIMARY_REPLICATION_SLOT=replication_slot
|
6
|
+
|
7
|
+
|
8
|
+
COPY docker/postgres_replica/cmd.sh cmd.sh
|
9
|
+
|
10
|
+
USER root
|
11
|
+
RUN chown -R postgres:postgres cmd.sh
|
12
|
+
USER postgres
|
13
|
+
RUN chmod u+x cmd.sh
|
14
|
+
|
15
|
+
CMD [ "./cmd.sh" ]
|
metadata
CHANGED
@@ -1,13 +1,14 @@
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
2
2
|
name: active_record_proxy_adapters
|
3
3
|
version: !ruby/object:Gem::Version
|
4
|
-
version: 0.
|
4
|
+
version: 0.3.0
|
5
5
|
platform: ruby
|
6
6
|
authors:
|
7
7
|
- Matt Cruz
|
8
|
+
autorequire:
|
8
9
|
bindir: exe
|
9
10
|
cert_chain: []
|
10
|
-
date: 2025-
|
11
|
+
date: 2025-01-18 00:00:00.000000000 Z
|
11
12
|
dependencies:
|
12
13
|
- !ruby/object:Gem::Dependency
|
13
14
|
name: activerecord
|
@@ -57,24 +58,38 @@ email:
|
|
57
58
|
- matt.cruz@nasdaq.com
|
58
59
|
executables: []
|
59
60
|
extensions: []
|
60
|
-
extra_rdoc_files:
|
61
|
-
- README.md
|
62
|
-
- LICENSE.txt
|
61
|
+
extra_rdoc_files: []
|
63
62
|
files:
|
63
|
+
- ".rspec"
|
64
|
+
- ".rubocop.yml"
|
65
|
+
- CHANGELOG.md
|
66
|
+
- CODE_OF_CONDUCT.md
|
67
|
+
- Dockerfile
|
64
68
|
- LICENSE.txt
|
65
69
|
- README.md
|
70
|
+
- db/mysql_structure.sql
|
71
|
+
- db/postgresql_structure.sql
|
72
|
+
- docker-compose.yml
|
73
|
+
- docker/postgres_replica/cmd.sh
|
74
|
+
- lib/active_record/connection_adapters/mysql2_proxy_adapter.rb
|
66
75
|
- lib/active_record/connection_adapters/postgresql_proxy_adapter.rb
|
76
|
+
- lib/active_record/tasks/mysql2_proxy_database_tasks.rb
|
67
77
|
- lib/active_record/tasks/postgresql_proxy_database_tasks.rb
|
68
78
|
- lib/active_record_proxy_adapters.rb
|
69
79
|
- lib/active_record_proxy_adapters/active_record_context.rb
|
70
80
|
- lib/active_record_proxy_adapters/configuration.rb
|
71
81
|
- lib/active_record_proxy_adapters/connection_handling.rb
|
82
|
+
- lib/active_record_proxy_adapters/database_tasks.rb
|
72
83
|
- lib/active_record_proxy_adapters/hijackable.rb
|
73
84
|
- lib/active_record_proxy_adapters/log_subscriber.rb
|
85
|
+
- lib/active_record_proxy_adapters/mysql2_proxy.rb
|
74
86
|
- lib/active_record_proxy_adapters/postgresql_proxy.rb
|
75
87
|
- lib/active_record_proxy_adapters/primary_replica_proxy.rb
|
76
88
|
- lib/active_record_proxy_adapters/railtie.rb
|
77
89
|
- lib/active_record_proxy_adapters/version.rb
|
90
|
+
- postgres_primary.dockerfile
|
91
|
+
- postgres_replica.dockerfile
|
92
|
+
- sig/active_record_proxy_adapters.rbs
|
78
93
|
homepage: https://github.com/Nasdaq/active_record_proxy_adapters
|
79
94
|
licenses:
|
80
95
|
- MIT
|
@@ -84,6 +99,7 @@ metadata:
|
|
84
99
|
source_code_uri: https://github.com/Nasdaq/active_record_proxy_adapters
|
85
100
|
changelog_uri: https://github.com/Nasdaq/active_record_proxy_adapters/blob/main/CHANGELOG.md
|
86
101
|
rubygems_mfa_required: 'true'
|
102
|
+
post_install_message:
|
87
103
|
rdoc_options: []
|
88
104
|
require_paths:
|
89
105
|
- lib
|
@@ -98,7 +114,8 @@ required_rubygems_version: !ruby/object:Gem::Requirement
|
|
98
114
|
- !ruby/object:Gem::Version
|
99
115
|
version: '0'
|
100
116
|
requirements: []
|
101
|
-
rubygems_version: 3.
|
117
|
+
rubygems_version: 3.5.11
|
118
|
+
signing_key:
|
102
119
|
specification_version: 4
|
103
120
|
summary: Read replica proxy adapters for ActiveRecord!
|
104
121
|
test_files: []
|