-
Notifications
You must be signed in to change notification settings - Fork 104
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
change: move caching logic to separate class
- Loading branch information
Showing
5 changed files
with
231 additions
and
200 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
module ValidEmail2 | ||
class DnsRecordsCache | ||
MAX_CACHE_SIZE = 1_000 | ||
|
||
def initialize | ||
# Cache structure: { domain (String): { records: [], cached_at: Time, ttl: Integer } } | ||
@cache = {} | ||
end | ||
|
||
def fetch(domain, &block) | ||
prune(@cache) if @cache.size > MAX_CACHE_SIZE | ||
|
||
cache_entry = @cache[domain] | ||
|
||
if cache_entry && (Time.now - cache_entry[:cached_at]) < cache_entry[:ttl] | ||
return cache_entry[:records] | ||
else | ||
@cache.delete(domain) | ||
end | ||
|
||
records = block.call | ||
|
||
if records.any? | ||
ttl = records.map(&:ttl).min | ||
@cache[domain] = { records: records, cached_at: Time.now, ttl: ttl } | ||
end | ||
|
||
records | ||
end | ||
|
||
def prune(cache) | ||
entries_sorted_by_cached_at_asc = (cache.sort_by { |_domain, data| data[:cached_at] }).flatten | ||
entries_to_remove = entries_sorted_by_cached_at_asc.first(cache.size - MAX_CACHE_SIZE) | ||
entries_to_remove.each { |domain| cache.delete(domain) } | ||
end | ||
end | ||
end |
Oops, something went wrong.