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- IP_ADDRESS_REGEX =
/\d{1,3}(\.\d{1,3}){3}/- VERSION =
"0.8.2"
Instance Attribute Summary collapse
-
#redis ⇒ Object
Returns the value of attribute redis.
-
#statsd ⇒ Object
Returns the value of attribute statsd.
Instance Method Summary collapse
- #configure {|_self| ... } ⇒ Object
- #deadline ⇒ Object
- #deadline=(ts) ⇒ Object
- #disable! ⇒ Object
- #enable! ⇒ Object
- #enabled=(enabled) ⇒ Object
- #enabled?(adapter) ⇒ Boolean
- #ignore_destination?(adapter, action, destination) ⇒ Boolean
- #mode(action) ⇒ Object
- #mode=(mode) ⇒ Object
- #normalize_request(adapter, request = nil, **context, &block) ⇒ Object
- #observe! ⇒ Object
- #patch(*adapters) ⇒ Object
-
#record(adapter:, action:, destination:, duration:, error:, timeout:, attempts: 1) ⇒ Object
private.
- #reset ⇒ Object
-
#thread_state ⇒ Object
private.
- #timeout_min ⇒ Object
- #timeout_min=(val) ⇒ Object
- #timeouts_for(adapter:, action:, destination:, max: nil, units: :ms) ⇒ Object
- #timestamp ⇒ Object
- #warn(method, e) ⇒ Object
Instance Attribute Details
#redis ⇒ Object
Returns the value of attribute redis.
28 29 30 |
# File 'lib/network_resiliency.rb', line 28 def redis @redis end |
#statsd ⇒ Object
Returns the value of attribute statsd.
28 29 30 |
# File 'lib/network_resiliency.rb', line 28 def statsd @statsd end |
Instance Method Details
#configure {|_self| ... } ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/network_resiliency.rb', line 30 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 |
#deadline ⇒ Object
170 171 172 |
# File 'lib/network_resiliency.rb', line 170 def deadline thread_state["deadline"] end |
#deadline=(ts) ⇒ Object
174 175 176 177 178 179 180 181 182 183 184 185 186 187 |
# File 'lib/network_resiliency.rb', line 174 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
93 94 95 96 97 98 99 |
# File 'lib/network_resiliency.rb', line 93 def disable! thread_state["enabled"] = false yield if block_given? ensure thread_state.delete("enabled") if block_given? end |
#enable! ⇒ Object
85 86 87 88 89 90 91 |
# File 'lib/network_resiliency.rb', line 85 def enable! thread_state["enabled"] = true yield if block_given? ensure thread_state.delete("enabled") if block_given? end |
#enabled=(enabled) ⇒ Object
77 78 79 80 81 82 83 |
# File 'lib/network_resiliency.rb', line 77 def enabled=(enabled) unless [ true, false ].include?(enabled) || enabled.is_a?(Proc) raise ArgumentError end @enabled = enabled end |
#enabled?(adapter) ⇒ Boolean
63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/network_resiliency.rb', line 63 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
309 310 311 312 |
# File 'lib/network_resiliency.rb', line 309 def ignore_destination?(adapter, action, destination) # filter raw IP addresses IP_ADDRESS_REGEX.match?(destination) end |
#mode(action) ⇒ Object
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
# File 'lib/network_resiliency.rb', line 106 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
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 |
# File 'lib/network_resiliency.rb', line 131 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
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 |
# File 'lib/network_resiliency.rb', line 189 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
162 163 164 165 166 167 168 |
# File 'lib/network_resiliency.rb', line 162 def observe! thread_state[:mode] = :observe yield if block_given? ensure thread_state.delete(:mode) if block_given? end |
#patch(*adapters) ⇒ Object
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/network_resiliency.rb', line 42 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
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 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 |
# File 'lib/network_resiliency.rb', line 229 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, }, ) 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 = { adapter: adapter, destination: destination, n: stats.n.order_of_magnitude, sync: Syncer.syncing?, } # ensure Syncer is running Syncer.start NetworkResiliency.statsd&.distribution( "network_resiliency.#{action}.stats.n", stats.n, tags: , ) NetworkResiliency.statsd&.distribution( "network_resiliency.#{action}.stats.avg", stats.avg, tags: , ) NetworkResiliency.statsd&.distribution( "network_resiliency.#{action}.stats.stdev", stats.stdev, tags: , ) end nil rescue => e warn(__method__, e) end |
#reset ⇒ Object
410 411 412 413 414 415 416 417 418 419 |
# File 'lib/network_resiliency.rb', line 410 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_state ⇒ Object
private
423 424 425 |
# File 'lib/network_resiliency.rb', line 423 def thread_state Thread.current["network_resiliency"] ||= {} end |
#timeout_min ⇒ Object
223 224 225 |
# File 'lib/network_resiliency.rb', line 223 def timeout_min @timeout_min || DEFAULT_TIMEOUT_MIN end |
#timeout_min=(val) ⇒ Object
215 216 217 218 219 220 221 |
# File 'lib/network_resiliency.rb', line 215 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
314 315 316 317 318 319 320 321 322 323 324 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 |
# File 'lib/network_resiliency.rb', line 314 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 = { 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 timeouts << p99 * 100 elsif p99 * 10 < max # use remaining time for second attempt timeouts << max - p99 else timeouts << max NetworkResiliency.statsd&.increment( "network_resiliency.timeout.raised", tags: , ) end else # the specified timeout is less than our expected p99...awkward timeouts << max NetworkResiliency.statsd&.increment( "network_resiliency.timeout.too_low", tags: , ) end else timeouts << p99 # second attempt timeouts << p99 * 100 NetworkResiliency.statsd&.increment( "network_resiliency.timeout.missing", tags: , ) end NetworkResiliency.statsd&.distribution( "network_resiliency.#{action}.timeout.dynamic", timeouts[0], tags: { adapter: adapter, destination: destination, }, ) 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 |
#timestamp ⇒ Object
101 102 103 104 |
# File 'lib/network_resiliency.rb', line 101 def # milliseconds Process.clock_gettime(Process::CLOCK_MONOTONIC) * 1_000 end |
#warn(method, e) ⇒ Object
427 428 429 430 431 432 433 434 435 436 437 |
# File 'lib/network_resiliency.rb', line 427 def warn(method, e) NetworkResiliency.statsd&.increment( "network_resiliency.error", tags: { method: method, type: e.class, }, ) Kernel.warn "[ERROR] NetworkResiliency #{method}: #{e.class}: #{e.}" end |