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/power_stats.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/rails.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: PowerStats, Stats, Syncer

Constant Summary collapse

ACTIONS =
[ :connect, :request ].freeze
ADAPTERS =
[ :http, :faraday, :redis, :mysql, :postgres, :rails ].freeze
DEFAULT_TIMEOUT_MIN =

ms

10
MODE =
[ :observe, :resilient ].freeze
RESILIENCY_THRESHOLD =
100
SAMPLE_RATE =
{
  timeout: 0.1,
  stats: 0.1,
  sync: 0.1,
}
IP_ADDRESS_REGEX =
/\d{1,3}(\.\d{1,3}){3}/
VERSION =
"0.8.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#redisObject

Returns the value of attribute redis.



33
34
35
# File 'lib/network_resiliency.rb', line 33

def redis
  @redis
end

#statsdObject

Returns the value of attribute statsd.



33
34
35
# File 'lib/network_resiliency.rb', line 33

def statsd
  @statsd
end

Instance Method Details

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

Yields:

  • (_self)

Yield Parameters:



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

def configure
  yield self if block_given?

  unless @patched
    # patch everything that's available
    ADAPTERS.each do |adapter|
      patch(adapter)
    rescue LoadError, NotImplementedError
    end
  end
end

#deadlineObject



175
176
177
# File 'lib/network_resiliency.rb', line 175

def deadline
  thread_state["deadline"]
end

#deadline=(ts) ⇒ Object



179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/network_resiliency.rb', line 179

def deadline=(ts)
  thread_state["deadline"] = case ts
  when Numeric
    Time.now + ts
  when Time
    ts
  when nil
    nil
  else
    raise ArgumentError, "invalid deadline: #{ts}"
  end

  # warn or raise if we're already past the deadline?
end

#disable!Object



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

def disable!
  thread_state["enabled"] = false

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

#enable!Object



90
91
92
93
94
95
96
# File 'lib/network_resiliency.rb', line 90

def enable!
  thread_state["enabled"] = true

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

#enabled=(enabled) ⇒ Object



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

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

  @enabled = enabled
end

#enabled?(adapter) ⇒ Boolean

Returns:

  • (Boolean)


68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/network_resiliency.rb', line 68

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
    disable! { !!@enabled.call(adapter) }
  else
    @enabled
  end
rescue
  false
end

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

Returns:

  • (Boolean)


320
321
322
323
# File 'lib/network_resiliency.rb', line 320

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

#mode(action) ⇒ Object



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/network_resiliency.rb', line 111

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

  return thread_state[:mode] if thread_state.key?(:mode)

  mode = if @mode.is_a?(Proc)
    # prevent recursion
    observe! { @mode.call(action) }
  elsif @mode
    @mode[action]
  end || :observe

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

  mode
rescue => e
  warn(__method__, e)

  :observe
end

#mode=(mode) ⇒ Object



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
# File 'lib/network_resiliency.rb', line 136

def mode=(mode)
  @mode = {}

  case mode
  when Proc
    @mode = mode
  when Hash
    invalid = mode.keys - ACTIONS

    unless invalid.empty?
      raise ArgumentError, "invalid actions for mode: #{invalid}"
    end

    mode.each do |action, mode|
      unless MODE.include?(mode)
        raise ArgumentError, "invalid NetworkResiliency mode for #{action}: #{mode}"
      end

      @mode[action] = mode
    end
  else
    unless MODE.include?(mode)
      raise ArgumentError, "invalid NetworkResiliency mode: #{mode}"
    end

    ACTIONS.each { |action| @mode[action] = mode }
  end

  @mode.freeze if @mode.is_a?(Hash)
end

#normalize_request(adapter, request = nil, **context, &block) ⇒ Object



194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/network_resiliency.rb', line 194

def normalize_request(adapter, request = nil, **context, &block)
  unless ADAPTERS.include?(adapter)
    raise ArgumentError, "invalid adapter: #{adapter}"
  end

  if request && block_given?
    raise ArgumentError, "specify request or block, but not both"
  end

  if request.nil? && !context.empty?
    raise ArgumentError, "can not speficy context without request"
  end

  @normalize_request ||= {}
  @normalize_request[adapter] ||= []
  @normalize_request[adapter] << block if block_given?

  if request
    @normalize_request[adapter].reduce(request) do |req, block|
      block.call(req, **context)
    end
  else
    @normalize_request[adapter]
  end
end

#observe!Object



167
168
169
170
171
172
173
# File 'lib/network_resiliency.rb', line 167

def observe!
  thread_state[:mode] = :observe

  yield if block_given?
ensure
  thread_state.delete(:mode) if block_given?
end

#patch(*adapters) ⇒ Object



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

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
    when :rails
      Adapter::Rails.patch
    else
      raise NotImplementedError
    end
  end

  @patched = true
end

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

private



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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/network_resiliency.rb', line 234

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,
      mode: mode(action),
      attempts: (attempts if attempts > 1),
      deadline_exceeded: (Time.now >= deadline if deadline),
    }.compact,
  )

  NetworkResiliency.statsd&.distribution(
    "network_resiliency.#{action}.timeout",
    timeout,
    tags: {
      adapter: adapter,
      destination: destination,
    },
    sample_rate: SAMPLE_RATE[:timeout],
  ) if timeout && timeout > 0

  if error
    NetworkResiliency.statsd&.distribution(
      "network_resiliency.#{action}.time_saved",
      timeout - duration,
      tags: {
        adapter: adapter,
        destination: destination,
      },
    ) if timeout && timeout > duration
  else
    # record stats
    key = [ adapter, action, destination ].join(":")
    stats = StatsEngine.add(key, duration)

    if stats.n > RESILIENCY_THRESHOLD * 5
      # downsample to age out old stats
      stats.scale!(50)
    end

    tags = {
      adapter: adapter,
      destination: destination,
      n: stats.n.order_of_magnitude,
      sync: Syncer.syncing?,
    }

    # ensure Syncer is running
    Syncer.start

    if rand < SAMPLE_RATE[:stats]
      NetworkResiliency.statsd&.distribution(
        "network_resiliency.#{action}.stats.n",
        stats.n,
        tags: tags,
        sample_rate: SAMPLE_RATE[:stats],
      )

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

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

  nil
rescue => e
  warn(__method__, e)
end

#resetObject



427
428
429
430
431
432
433
434
435
436
# File 'lib/network_resiliency.rb', line 427

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

#thread_stateObject

private



440
441
442
# File 'lib/network_resiliency.rb', line 440

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

#timeout_minObject



228
229
230
# File 'lib/network_resiliency.rb', line 228

def timeout_min
  @timeout_min || DEFAULT_TIMEOUT_MIN
end

#timeout_min=(val) ⇒ Object



220
221
222
223
224
225
226
# File 'lib/network_resiliency.rb', line 220

def timeout_min=(val)
  unless val.nil? || val.is_a?(Numeric)
    raise ArgumentError, "invalid timeout_min: #{val}"
  end

  @timeout_min = val
end

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



325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
# File 'lib/network_resiliency.rb', line 325

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

  return default if NetworkResiliency.mode(action.to_sym) == :observe

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

  return default unless stats.n >= RESILIENCY_THRESHOLD

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

  p99 = (stats.avg + stats.stdev * 3)

  # add margin of error / normalize
  p99 = if stats.n >= RESILIENCY_THRESHOLD * 2
    p99.power_ceil
  else
    # larger margin of error
    p99.order_of_magnitude(ceil: true)
  end

  # enforce minimum timeout
  p99 = [ p99, timeout_min ].max

  timeouts = []

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

    if p99 < max
      timeouts << p99

      # make a second, more lenient attempt

      if p99 * 100 < max
        # max is excessively high
        timeouts << p99 * 100
      elsif p99 * 10 < max
        # use remaining time for second attempt
        timeouts << max - p99
      else
        # max is smallish
        timeouts << max

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

      NetworkResiliency.statsd&.increment(
        "network_resiliency.timeout.too_low",
        tags: tags,
        sample_rate: SAMPLE_RATE[:timeout],
      ) if rand < SAMPLE_RATE[:timeout]
    end
  else
    timeouts << p99

    # second attempt
    timeouts << p99 * 100

    NetworkResiliency.statsd&.increment(
      "network_resiliency.timeout.missing",
      tags: tags,
      sample_rate: SAMPLE_RATE[:timeout],
    ) if rand < SAMPLE_RATE[:timeout]
  end

  NetworkResiliency.statsd&.distribution(
    "network_resiliency.#{action}.timeout.dynamic",
    timeouts[0],
    tags: {
      adapter: adapter,
      destination: destination,
    },
    sample_rate: SAMPLE_RATE[:timeout],
  ) if rand < SAMPLE_RATE[:timeout]

  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
  warn(__method__, e)

  default
end

#timestampObject



106
107
108
109
# File 'lib/network_resiliency.rb', line 106

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

#warn(method, e) ⇒ Object



444
445
446
447
448
449
450
451
452
453
454
# File 'lib/network_resiliency.rb', line 444

def warn(method, e)
  NetworkResiliency.statsd&.increment(
    "network_resiliency.error",
    tags: {
      method: method,
      type: e.class,
    },
  )

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