@@ -13,11 +13,15 @@ package Slim::Networking::Async::DNS;
1313use strict;
1414
1515use AnyEvent::DNS;
16+ use List::Util qw( max) ;
1617use Tie::Cache::LRU;
1718
1819use Slim::Utils::Log;
1920use Slim::Utils::Misc;
2021
22+ use constant DEFAULT_CACHE_TTL => 3600; # 1 hour
23+ use constant MIN_CACHE_TTL => 300; # 5 minutes
24+
2125# Cached lookups
2226tie my %cache , ' Tie::Cache::LRU' , 100;
2327
@@ -46,15 +50,19 @@ sub resolve {
4650 $args -> {cb }-> ( $addr , @{ $args -> {pt } || [] } );
4751 return ;
4852 }
49- else {
50- delete $cache { $host };
51- }
5253 }
5354
5455 AnyEvent::DNS::resolver-> resolve( $host => ' a' , sub {
5556 my $res = shift ;
5657
57- if ( !$res ) {
58+ if ( !$res && (my $cached = $cache { $host }) ) {
59+ my $addr = $cached -> {addr };
60+ main::DEBUGLOG && $log -> is_debug && $log -> debug( " Lookup failed - falling back to cached DNS response $addr for $host " );
61+
62+ $args -> {cb }-> ( $addr , @{ $args -> {pt } || [] } );
63+ return ;
64+ }
65+ elsif ( !$res ) {
5866 # Lookup failed
5967 main::DEBUGLOG && $log -> is_debug && $log -> debug(" Lookup failed for $host " );
6068
@@ -71,17 +79,15 @@ sub resolve {
7179 }
7280
7381 my $addr = $res -> [3];
74- my $ttl = $res -> [4];
82+ my $ttl = max( $res -> [4] || DEFAULT_CACHE_TTL, MIN_CACHE_TTL ) ;
7583
7684 main::DEBUGLOG && $log -> is_debug && $log -> debug( " Got DNS response $addr for $host (ttl $ttl )" );
7785
7886 # cache lookup for ttl
79- if ( $ttl ) {
80- $cache {$host } = {
81- addr => $addr ,
82- expires => AnyEvent-> now + $ttl ,
83- };
84- }
87+ $cache {$host } = {
88+ addr => $addr ,
89+ expires => AnyEvent-> now + $ttl ,
90+ };
8591
8692 $args -> {cb }-> ( $addr , @{ $args -> {pt } || [] } );
8793 } );
0 commit comments