Module: NetworkResiliency

Extended by:
NetworkResiliency
Included in:
NetworkResiliency
Defined in:
lib/network_resiliency.rb,
lib/network_resiliency/stats.rb,
lib/network_resiliency/syncer.rb,
lib/network_resiliency/version.rb,
lib/network_resiliency/refinements.rb,
lib/network_resiliency/adapter/http.rb,
lib/network_resiliency/stats_engine.rb,
lib/network_resiliency/adapter/mysql.rb,
lib/network_resiliency/adapter/redis.rb,
lib/network_resiliency/adapter/faraday.rb,
lib/network_resiliency/adapter/postgres.rb

Defined Under Namespace

Modules: Adapter, Refinements, StatsEngine Classes: Stats, Syncer

Constant Summary collapse

MODE =
[ :observe, :resilient ].freeze
RESILIENCY_SIZE_THRESHOLD =
1_000
IP_ADDRESS_REGEX =
Regexp.new(/\d{1,3}(\.\d{1,3}){3}/)
VERSION =
"0.6.2"

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#redisObject

Returns the value of attribute redis.



23
24
25
# File 'lib/network_resiliency.rb', line 23

def redis
  @redis
end

#statsdObject

Returns the value of attribute statsd.



23
24
25
# File 'lib/network_resiliency.rb', line 23

def statsd
  @statsd
end

Instance Method Details

#configure {|_self| ... } ⇒ Object

Yields:

  • (_self)

Yield Parameters:



25
26
27
28
29
# File 'lib/network_resiliency.rb', line 25

def configure
  yield self if block_given?

  Syncer.start(redis) if redis
end

#disable!Object



80
81
82
83
84
85
86
87
# File 'lib/network_resiliency.rb', line 80

def disable!
  original = @enabled
  thread_state["enabled"] = false

  yield if block_given?
ensure
  thread_state.delete("enabled") if block_given?
end

#enable!Object



71
72
73
74
75
76
77
78
# File 'lib/network_resiliency.rb', line 71

def enable!
  original = @enabled
  thread_state["enabled"] = true

  yield if block_given?
ensure
  thread_state.delete("enabled") if block_given?
end

#enabled=(enabled) ⇒ Object



63
64
65
66
67
68
69
# File 'lib/network_resiliency.rb', line 63

def enabled=(enabled)
  unless [ true, false ].include?(enabled) || enabled.is_a?(Proc)
    raise ArgumentError
  end

  @enabled = enabled
end

#enabled?(adapter) ⇒ Boolean

Returns:

  • (Boolean)


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

def enabled?(adapter)
  return thread_state["enabled"] if thread_state.key?("enabled")
  return true if @enabled.nil?

  if @enabled.is_a?(Proc)
    # prevent recursive calls
    enabled = @enabled
    disable! { !!enabled.call(adapter) }
  else
    @enabled
  end
rescue
  false
end

#ignore_destination?(adapter, action, destination) ⇒ Boolean

Returns:

  • (Boolean)


204
205
206
207
# File 'lib/network_resiliency.rb', line 204

def ignore_destination?(adapter, action, destination)
  # filter raw IP addresses
  IP_ADDRESS_REGEX.match?(destination)
end

#modeObject



94
95
96
# File 'lib/network_resiliency.rb', line 94

def mode
  @mode || :observe
end

#mode=(mode) ⇒ Object



98
99
100
101
102
103
104
# File 'lib/network_resiliency.rb', line 98

def mode=(mode)
  unless MODE.include?(mode)
    raise ArgumentError, "invalid NetworkResiliency mode: #{mode}"
  end

  @mode = mode
end

#patch(*adapters) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/network_resiliency.rb', line 31

def patch(*adapters)
  adapters.each do |adapter|
    case adapter
    when :http
      Adapter::HTTP.patch
    when :redis
      Adapter::Redis.patch
    when :mysql
      Adapter::Mysql.patch
    when :postgres
      Adapter::Postgres.patch
    else
      raise NotImplementedError
    end
  end
end

#record(adapter:, action:, destination:, duration:, error:, timeout:, attempts: 1) ⇒ Object

private



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/network_resiliency.rb', line 108

def record(adapter:, action:, destination:, duration:, error:, timeout:, attempts: 1)
  return if ignore_destination?(adapter, action, destination)

  NetworkResiliency.statsd&.distribution(
    "network_resiliency.#{action}",
    duration,
    tags: {
      adapter: adapter,
      destination: destination,
      error: error,
      attempts: (attempts if attempts > 1),
    }.compact,
  )

  NetworkResiliency.statsd&.distribution(
    "network_resiliency.#{action}.magnitude",
    duration.order_of_magnitude(ceil: true),
    tags: {
      adapter: adapter,
      destination: destination,
      error: error,
    }.compact,
  )

  NetworkResiliency.statsd&.gauge(
    "network_resiliency.#{action}.timeout",
    timeout,
    tags: {
      adapter: adapter,
      destination: destination,
    },
  ) if timeout && timeout > 0

  if error
    NetworkResiliency.statsd&.distribution(
      "network_resiliency.#{action}.time_saved",
      timeout - duration,
      tags: {
        adapter: adapter,
        destination: destination,
      },
    ) if timeout && timeout > 0
  else
    # track successful retries
    NetworkResiliency.statsd&.increment(
      "network_resiliency.#{action}.resilient",
      tags: {
        adapter: adapter,
        destination: destination,
        attempts: attempts,
      },
    ) if attempts > 1

    # record stats
    key = [ adapter, action, destination ].join(":")
    stats = StatsEngine.add(key, duration)
    tags = {
      adapter: adapter,
      destination: destination,
      n: stats.n.order_of_magnitude,
    }

    NetworkResiliency.statsd&.distribution(
      "network_resiliency.#{action}.stats.n",
      stats.n,
      tags: tags,
    )

    NetworkResiliency.statsd&.distribution(
      "network_resiliency.#{action}.stats.avg",
      stats.avg,
      tags: tags,
    )

    NetworkResiliency.statsd&.distribution(
      "network_resiliency.#{action}.stats.stdev",
      stats.stdev,
      tags: tags,
    )
  end

  nil
rescue => e
  NetworkResiliency.statsd&.increment(
    "network_resiliency.error",
    tags: {
      method: __method__,
      type: e.class,
    },
  )

  warn "[ERROR] NetworkResiliency: #{e.class}: #{e.message}"
end

#resetObject



291
292
293
294
295
296
297
# File 'lib/network_resiliency.rb', line 291

def reset
  @enabled = nil
  @mode = nil
  Thread.current["network_resiliency"] = nil
  StatsEngine.reset
  Syncer.stop
end

#thread_stateObject

private



301
302
303
# File 'lib/network_resiliency.rb', line 301

def thread_state
  Thread.current["network_resiliency"] ||= {}
end

#timeouts_for(adapter:, action:, destination:, max: nil, units: :ms) ⇒ Object



209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/network_resiliency.rb', line 209

def timeouts_for(adapter:, action:, destination:, max: nil, units: :ms)
  default = [ max ]

  return default if NetworkResiliency.mode == :observe

  key = [ adapter, action, destination ].join(":")
  stats = StatsEngine.get(key)

  return default unless stats.n >= RESILIENCY_SIZE_THRESHOLD

  tags = {
    adapter: adapter,
    action: action,
    destination: destination,
  }

  p99 = (stats.avg + stats.stdev * 3).power_ceil
  timeouts = []

  if max
    max *= 1_000 if units == :s || units == :seconds

    if p99 < max
      timeouts << p99

      # fallback attempt
      if max - p99 > p99
        # use remaining time for second attempt
        timeouts << max - p99
      else
        timeouts << max

        NetworkResiliency.statsd&.increment(
          "network_resiliency.timeout.raised",
          tags: tags,
        )
      end
    else
      # the specified timeout is less than our expected p99...awkward
      timeouts << max

      NetworkResiliency.statsd&.increment(
        "network_resiliency.timeout.too_low",
        tags: tags,
      )
    end
  else
    timeouts << p99

    # timeouts << p99 * 10 if NetworkResiliency.mode == :resolute

    # unbounded second attempt
    timeouts << nil

    NetworkResiliency.statsd&.increment(
      "network_resiliency.timeout.missing",
      tags: tags,
    )
  end

  case units
  when nil, :ms, :milliseconds
    timeouts
  when :s, :seconds
    timeouts.map { |t| t.to_f / 1_000 if t }
  else
    raise ArgumentError, "invalid units: #{units}"
  end
rescue => e
  NetworkResiliency.statsd&.increment(
    "network_resiliency.error",
    tags: {
      method: __method__,
      type: e.class,
    },
  )

  warn "[ERROR] NetworkResiliency: #{e.class}: #{e.message}"

  default
end

#timestampObject



89
90
91
92
# File 'lib/network_resiliency.rb', line 89

def timestamp
  # milliseconds
  Process.clock_gettime(Process::CLOCK_MONOTONIC) * 1_000
end