Module: Faulty::Patch::Mysql2

Includes:
Base
Included in:
Mysql2::Client
Defined in:
lib/faulty/patch/mysql2.rb

Overview

Patch Mysql2 to run connections and queries in a circuit

This module is not required by default

Pass a :faulty key into your MySQL connection options to enable circuit protection. See circuit_from_hash for the available options.

COMMIT, ROLLBACK, and RELEASE SAVEPOINT queries are intentionally not protected by the circuit. This is to allow open transactions to be closed if possible.

By default, all circuit errors raised by this patch inherit from ::Mysql2::Error::ConnectionError

Examples:

require 'faulty/patch/mysql2'

mysql = Mysql2::Client.new(host: '127.0.0.1', faulty: {})
mysql.query('SELECT * FROM users') # raises Faulty::CircuitError if connection fails

# If the faulty key is not given, no circuit is used
mysql = Mysql2::Client.new(host: '127.0.0.1')
mysql.query('SELECT * FROM users') # not protected by a circuit

See Also:

Constant Summary collapse

QUERY_WHITELIST =
[
  %r{\A(?:/\*.*?\*/)?\s*ROLLBACK}i,
  %r{\A(?:/\*.*?\*/)?\s*COMMIT}i,
  %r{\A(?:/\*.*?\*/)?\s*RELEASE\s+SAVEPOINT}i
].freeze

Instance Method Summary collapse

Methods included from Base

#faulty_run

Instance Method Details

#connect(*args) ⇒ Object

Protect the initial connnection



70
71
72
# File 'lib/faulty/patch/mysql2.rb', line 70

def connect(*args)
  faulty_run { super }
end

#initialize(opts = {}) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/faulty/patch/mysql2.rb', line 48

def initialize(opts = {})
  @faulty_circuit = Patch.circuit_from_hash(
    'mysql2',
    opts[:faulty],
    errors: [
      ::Mysql2::Error::ConnectionError,
      ::Mysql2::Error::TimeoutError
    ],
    patched_error_mapper: Faulty::Patch::Mysql2
  )

  super
end

#pingObject

Protect manual connection pings



63
64
65
66
67
# File 'lib/faulty/patch/mysql2.rb', line 63

def ping
  faulty_run { super }
rescue Faulty::Patch::Mysql2::FaultyError
  false
end

#query(*args) ⇒ Object

Protect queries unless they are whitelisted



75
76
77
78
79
# File 'lib/faulty/patch/mysql2.rb', line 75

def query(*args)
  return super if QUERY_WHITELIST.any? { |r| !r.match(args.first).nil? }

  faulty_run { super }
end