Class: MailerToGo::SPF::CachingResolver

Inherits:
Object
  • Object
show all
Defined in:
lib/mailertogo/spf/resolver.rb

Overview

Wraps any resolver in a small TTL cache.

Resolving an SPF chain is up to ten serial round-trips, and this runs in request paths ("check my domain" pages) where that is not acceptable twice. Failures (nil) are deliberately NOT cached: caching a timeout would pin a healthy domain into :unknown for the whole TTL.

Instance Method Summary collapse

Constructor Details

#initialize(resolver, ttl: 300, clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }) ⇒ CachingResolver

Returns a new instance of CachingResolver.



73
74
75
76
77
78
79
# File 'lib/mailertogo/spf/resolver.rb', line 73

def initialize(resolver, ttl: 300, clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) })
  @resolver = resolver
  @ttl = ttl
  @clock = clock
  @entries = {}
  @mutex = Mutex.new
end

Instance Method Details

#call(name) ⇒ Object



81
82
83
84
85
86
87
88
89
90
# File 'lib/mailertogo/spf/resolver.rb', line 81

def call(name)
  key = Record.normalize_name(name)
  now = @clock.call
  cached = @mutex.synchronize { @entries[key] }
  return cached[1] if cached && cached[0] > now

  answer = @resolver.call(key)
  @mutex.synchronize { @entries[key] = [now + @ttl, answer] } unless answer.nil?
  answer
end

#clearObject



92
93
94
# File 'lib/mailertogo/spf/resolver.rb', line 92

def clear
  @mutex.synchronize { @entries.clear }
end