diff --git a/internal/geo/geo.go b/internal/geo/geo.go index 17a2a8d..7b32e17 100644 --- a/internal/geo/geo.go +++ b/internal/geo/geo.go @@ -179,21 +179,38 @@ func (r *Resolver) Lookup(ip netip.Addr) Info { func (r *Resolver) lookupRaw(ip netip.Addr) Info { var in Info - if d := r.city.Load(); d != nil && d.r.acquire() { - if off, ok := d.r.find(ip); ok { - fillCity(d.r.dec, off, &in) + withDB(r.city.Load, func(rd *reader) { + if off, ok := rd.find(ip); ok { + fillCity(rd.dec, off, &in) } - d.r.release() - } - if d := r.asn.Load(); d != nil && d.r.acquire() { - if off, ok := d.r.find(ip); ok { - fillASN(d.r.dec, off, &in) + }) + withDB(r.asn.Load, func(rd *reader) { + if off, ok := rd.find(ip); ok { + fillASN(rd.dec, off, &in) } - d.r.release() - } + }) return in } +// withDB runs fn on the current database of a slot. A hot swap stores the new +// database before closing the old one, so when acquire fails (the pointer we +// loaded was closed in between) the slot already holds its replacement: load +// it again instead of returning an empty answer. Bounded, in case the slot is +// being closed for good (Close). +func withDB(load func() *db, fn func(*reader)) { + for attempt := 0; attempt < 8; attempt++ { + d := load() + if d == nil { + return + } + if d.r.acquire() { + fn(d.r) + d.r.release() + return + } + } +} + // fillCity extrai campos no layout GeoIP2-City; erros de decodificação // deixam o que já foi lido. func fillCity(d decoder, off uint, in *Info) {