rails_failover 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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 307c740884b5d0f566b0013a076133f2e951cf2c3b24336f83ff8e9510ccf95f
4
+ data.tar.gz: 8a4cc918de939e67c6665c45416b05a4230f79bef9b9efa9f5520cd880e2c3f2
5
+ SHA512:
6
+ metadata.gz: ec87d7a536a603645d5b4d1c509f1203156c39b1b2bdeb023629727bf73255b46fda97f3d4bd0e363a01871287cc5571653b1d4a53fc1052759c565dab68d441
7
+ data.tar.gz: 4b104f60e06dafd0c8c1170c289113fb844bc3b48b6af74c3eedb09fae1814e0cc0421f29949d7f93322e8edf9fa9779a958de3538940f45ce6418bc8a1cfb0c
data/.gitignore ADDED
@@ -0,0 +1,16 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
12
+
13
+ .byebug_history
14
+
15
+ # Redis database files
16
+ *.rdb
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --color
2
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,5 @@
1
+ inherit_gem:
2
+ rubocop-discourse: default.yml
3
+
4
+ Discourse:
5
+ Enabled: false
data/.travis.yml ADDED
@@ -0,0 +1,6 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 2.6.2
6
+ before_install: gem install bundler -v 2.1.4
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at gxtan1990@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [https://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: https://contributor-covenant.org
74
+ [version]: https://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+ source "https://rubygems.org"
3
+
4
+ # Specify your gem's dependencies in rails_failover.gemspec
5
+ gemspec
6
+
7
+ gem "rake", "~> 12.0"
8
+ gem "rspec", "~> 3.0"
9
+
10
+ group :development do
11
+ gem 'rubocop-discourse'
12
+ gem 'byebug'
13
+ end
data/Gemfile.lock ADDED
@@ -0,0 +1,59 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ rails_failover (0.1.0)
5
+ redis (~> 4)
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ ast (2.4.0)
11
+ byebug (11.1.3)
12
+ diff-lcs (1.3)
13
+ parallel (1.19.1)
14
+ parser (2.7.1.2)
15
+ ast (~> 2.4.0)
16
+ rainbow (3.0.0)
17
+ rake (12.3.3)
18
+ redis (4.1.4)
19
+ rexml (3.2.4)
20
+ rspec (3.9.0)
21
+ rspec-core (~> 3.9.0)
22
+ rspec-expectations (~> 3.9.0)
23
+ rspec-mocks (~> 3.9.0)
24
+ rspec-core (3.9.2)
25
+ rspec-support (~> 3.9.3)
26
+ rspec-expectations (3.9.2)
27
+ diff-lcs (>= 1.2.0, < 2.0)
28
+ rspec-support (~> 3.9.0)
29
+ rspec-mocks (3.9.1)
30
+ diff-lcs (>= 1.2.0, < 2.0)
31
+ rspec-support (~> 3.9.0)
32
+ rspec-support (3.9.3)
33
+ rubocop (0.83.0)
34
+ parallel (~> 1.10)
35
+ parser (>= 2.7.0.1)
36
+ rainbow (>= 2.2.2, < 4.0)
37
+ rexml
38
+ ruby-progressbar (~> 1.7)
39
+ unicode-display_width (>= 1.4.0, < 2.0)
40
+ rubocop-discourse (2.1.2)
41
+ rubocop (>= 0.69.0)
42
+ rubocop-rspec (>= 1.39.0)
43
+ rubocop-rspec (1.39.0)
44
+ rubocop (>= 0.68.1)
45
+ ruby-progressbar (1.10.1)
46
+ unicode-display_width (1.7.0)
47
+
48
+ PLATFORMS
49
+ ruby
50
+
51
+ DEPENDENCIES
52
+ byebug
53
+ rails_failover!
54
+ rake (~> 12.0)
55
+ rspec (~> 3.0)
56
+ rubocop-discourse
57
+
58
+ BUNDLED WITH
59
+ 2.1.4
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020 Alan Tan
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,59 @@
1
+ # RailsFailover
2
+
3
+ * Automatic failover and recovery for simple master-replica Redis setup
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'rails_failover'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle install
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install rails_failover
20
+
21
+ ## Usage
22
+
23
+ ### Redis
24
+
25
+ ```
26
+ Redis.new(host: "127.0.0.1", port: 6379, replica_host: "127.0.0.1", replica_port: 6380, connector: RailsFailover::Redis::Connector))
27
+ ```
28
+
29
+ Callbacks can be registered when the master connection is down and when it is up.
30
+
31
+
32
+ ```
33
+ RailsFailover::Redis.register_master_up_callback do
34
+ # Switch site to read-only mode
35
+ end
36
+
37
+ RailsFailover::Redis.register_master_down_callback do
38
+ # Switch site out of read-only mode
39
+ end
40
+ ```
41
+
42
+ ## Development
43
+
44
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `make test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
45
+
46
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
47
+
48
+ ## Contributing
49
+
50
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/rails_failover. 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/[USERNAME]/rails_failover/blob/master/CODE_OF_CONDUCT.md).
51
+
52
+
53
+ ## License
54
+
55
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
56
+
57
+ ## Code of Conduct
58
+
59
+ Everyone interacting in the RailsFailover project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/rails_failover/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
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
+ task default: :spec
data/bin/console ADDED
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "rails_failover"
6
+ require 'redis'
7
+
8
+ # You can add fixtures and/or initialization code here to make experimenting
9
+ # with your gem easier. You can also use a different console, if you like.
10
+
11
+ # (If you use this, don't forget to add pry to your Gemfile!)
12
+ # require "pry"
13
+ # Pry.start
14
+
15
+ require "irb"
16
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails_failover/version"
4
+ require "rails_failover/redis"
5
+
6
+ module RailsFailover
7
+ class Error < StandardError; end
8
+ end
@@ -0,0 +1,39 @@
1
+ require_relative 'redis/connector'
2
+
3
+ module RailsFailover
4
+ class Redis
5
+ def self.logger=(logger)
6
+ @logger = logger
7
+ end
8
+
9
+ def self.logger
10
+ @logger
11
+ end
12
+
13
+ def self.verify_master_frequency_seconds=(seconds)
14
+ @verify_master_frequency_seconds = seconds
15
+ end
16
+
17
+ def self.verify_master_frequency_seconds
18
+ @verify_master_frequency_seconds || 5
19
+ end
20
+
21
+ def self.register_master_down_callback(&block)
22
+ @master_down_callbacks ||= []
23
+ @master_down_callbacks.push(block)
24
+ end
25
+
26
+ def self.master_down_callbacks
27
+ @master_down_callbacks || []
28
+ end
29
+
30
+ def self.register_master_up_callback(&block)
31
+ @master_up_callbacks ||= []
32
+ @master_up_callbacks.push(block)
33
+ end
34
+
35
+ def self.master_up_callbacks
36
+ @master_up_callbacks || []
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+ require_relative 'fallback_handler'
3
+
4
+ module RailsFailover
5
+ class Redis
6
+ class Connector
7
+ def initialize(options)
8
+ options[:original_driver] = options[:driver]
9
+
10
+ options[:driver] = Class.new(options[:driver]) do
11
+ def self.connect(options)
12
+ super(options)
13
+ rescue Timeout::Error,
14
+ SocketError,
15
+ Errno::EADDRNOTAVAIL,
16
+ Errno::ECONNREFUSED,
17
+ Errno::EHOSTDOWN,
18
+ Errno::EHOSTUNREACH,
19
+ Errno::ENETUNREACH,
20
+ Errno::ENOENT,
21
+ Errno::ETIMEDOUT,
22
+ Errno::EINVAL => e
23
+
24
+ FallbackHandler.instance.master = false
25
+ FallbackHandler.instance.verify_master(options.dup)
26
+ raise e
27
+ end
28
+ end
29
+
30
+ options.delete(:connector)
31
+ @options = options.dup
32
+ @replica_options = replica_options(options)
33
+ end
34
+
35
+ def resolve
36
+ FallbackHandler.instance.master ? @options : @replica_options
37
+ end
38
+
39
+ def check(client)
40
+ FallbackHandler.instance.register_client(client)
41
+ end
42
+
43
+ private
44
+
45
+ def replica_options(options)
46
+ opts = options.dup
47
+ opts[:host] = opts.delete(:replica_host)
48
+ opts[:port] = opts.delete(:replica_port)
49
+ opts[:driver] = opts.delete(:original_driver)
50
+ opts
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,95 @@
1
+ # frozen_string_literal: true
2
+ require 'monitor'
3
+ require 'singleton'
4
+
5
+ module RailsFailover
6
+ class Redis
7
+ class FallbackHandler
8
+ include Singleton
9
+ include MonitorMixin
10
+
11
+ MASTER_ROLE_STATUS = "role:master"
12
+ MASTER_LOADED_STATUS = "loading:0"
13
+
14
+ def initialize
15
+ @master = true
16
+ @clients = []
17
+
18
+ super() # Monitor#initialize
19
+ end
20
+
21
+ def verify_master(options)
22
+ mon_synchronize do
23
+ return if @thread&.alive?
24
+
25
+ RailsFailover::Redis.master_down_callbacks.each { |callback| callback.call }
26
+
27
+ @thread = Thread.new do
28
+ loop do
29
+ thread = Thread.new { initiate_fallback_to_master(options) }
30
+ thread.join
31
+ break if mon_synchronize { @master }
32
+ sleep (RailsFailover::Redis.verify_master_frequency_seconds + (Time.now.to_i % RailsFailover::Redis.verify_master_frequency_seconds))
33
+ ensure
34
+ thread.kill
35
+ end
36
+ end
37
+ end
38
+ end
39
+
40
+ def initiate_fallback_to_master(options)
41
+ info = nil
42
+
43
+ begin
44
+ master_client = ::Redis::Client.new(options.dup)
45
+ log "#{log_prefix}: Checking connection to master server..."
46
+ info = master_client.call([:info])
47
+ rescue => e
48
+ log "#{log_prefix}: Connection to Master server failed with '#{e.message}'"
49
+ ensure
50
+ master_client&.disconnect
51
+ end
52
+
53
+ if info && info.include?(MASTER_LOADED_STATUS) && info.include?(MASTER_ROLE_STATUS)
54
+ self.master = true
55
+ log "#{log_prefix}: Master server is active, disconnecting clients from replica"
56
+ disconnect_clients
57
+ RailsFailover::Redis.master_up_callbacks.each { |callback| callback.call }
58
+ end
59
+ end
60
+
61
+ def register_client(client)
62
+ mon_synchronize do
63
+ @clients << client
64
+ end
65
+ end
66
+
67
+ def master
68
+ mon_synchronize { @master }
69
+ end
70
+
71
+ def master=(args)
72
+ mon_synchronize { @master = args }
73
+ end
74
+
75
+ private
76
+
77
+ def disconnect_clients
78
+ mon_synchronize do
79
+ @clients.each(&:disconnect)
80
+ @clients.clear
81
+ end
82
+ end
83
+
84
+ def log(message)
85
+ if logger = RailsFailover::Redis.logger
86
+ logger.warn(message)
87
+ end
88
+ end
89
+
90
+ def log_prefix
91
+ "#{self.class}"
92
+ end
93
+ end
94
+ end
95
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RailsFailover
4
+ VERSION = "0.1.0"
5
+ end
data/makefile ADDED
@@ -0,0 +1,31 @@
1
+ PORT := 6381
2
+ PID_PATH := /tmp/redis.pid
3
+ SOCKET_PATH := /tmp/redis.sock
4
+ DBFILENAME := master.rdb
5
+ replica_port := 6382
6
+ REPLICA_PID_PATH := /tmp/redis_replica.pid
7
+ REPLICA_SOCKET_PATH := /tmp/redis_replica.sock
8
+ REPLICA_DBFILENAME := replica.rdb
9
+
10
+ default:
11
+ @make -s all
12
+
13
+ all: start test stop
14
+
15
+ test:
16
+ bundle exec rspec
17
+
18
+ start: start_master start_replica
19
+ stop: stop_replica stop_master
20
+
21
+ stop_master:
22
+ @redis-cli -p ${PORT} shutdown
23
+
24
+ start_master:
25
+ @redis-server --daemonize yes --pidfile ${PID_PATH} --port ${PORT} --unixsocket ${SOCKET_PATH} --dbfilename ${DBFILENAME} --logfile /dev/null
26
+
27
+ stop_replica:
28
+ @redis-cli -p ${replica_port} shutdown
29
+
30
+ start_replica:
31
+ @redis-server --daemonize yes --pidfile ${REPLICA_PID_PATH} --port ${replica_port} --unixsocket ${REPLICA_SOCKET_PATH} --replicaof 127.0.0.1 ${PORT} --dbfilename ${REPLICA_DBFILENAME} --logfile /dev/null
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/rails_failover/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "rails_failover"
7
+ spec.version = RailsFailover::VERSION
8
+ spec.authors = ["Alan Tan"]
9
+ spec.email = ["tgx@discourse.org"]
10
+
11
+ spec.summary = %q{Failover for PostgreSQL and Redis}
12
+ spec.license = "MIT"
13
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
14
+
15
+ # Specify which files should be added to the gem when it is released.
16
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
17
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
18
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
19
+ end
20
+ spec.bindir = "exe"
21
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
22
+ spec.require_paths = ["lib"]
23
+
24
+ spec.add_dependency('redis', '~> 4')
25
+ end
metadata ADDED
@@ -0,0 +1,76 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rails_failover
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Alan Tan
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2020-05-20 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: redis
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '4'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '4'
27
+ description:
28
+ email:
29
+ - tgx@discourse.org
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - ".gitignore"
35
+ - ".rspec"
36
+ - ".rubocop.yml"
37
+ - ".travis.yml"
38
+ - CODE_OF_CONDUCT.md
39
+ - Gemfile
40
+ - Gemfile.lock
41
+ - LICENSE.txt
42
+ - README.md
43
+ - Rakefile
44
+ - bin/console
45
+ - bin/setup
46
+ - lib/rails_failover.rb
47
+ - lib/rails_failover/redis.rb
48
+ - lib/rails_failover/redis/connector.rb
49
+ - lib/rails_failover/redis/fallback_handler.rb
50
+ - lib/rails_failover/version.rb
51
+ - makefile
52
+ - rails_failover.gemspec
53
+ homepage:
54
+ licenses:
55
+ - MIT
56
+ metadata: {}
57
+ post_install_message:
58
+ rdoc_options: []
59
+ require_paths:
60
+ - lib
61
+ required_ruby_version: !ruby/object:Gem::Requirement
62
+ requirements:
63
+ - - ">="
64
+ - !ruby/object:Gem::Version
65
+ version: 2.3.0
66
+ required_rubygems_version: !ruby/object:Gem::Requirement
67
+ requirements:
68
+ - - ">="
69
+ - !ruby/object:Gem::Version
70
+ version: '0'
71
+ requirements: []
72
+ rubygems_version: 3.0.3
73
+ signing_key:
74
+ specification_version: 4
75
+ summary: Failover for PostgreSQL and Redis
76
+ test_files: []