postgres: return an empty list of addresses on dns errors (#3637)

This commit is contained in:
Caleb Doxsey 2022-09-30 12:00:40 -06:00 committed by GitHub
parent 3fec00f2a8
commit 3b2cc6720a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 36 additions and 1 deletions

View file

@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"net"
"sync"
"time"
@ -320,7 +321,7 @@ func (backend *Backend) init(ctx context.Context) (serverVersion uint64, pool *p
return serverVersion, pool, nil
}
config, err := pgxpool.ParseConfig(backend.dsn)
config, err := ParseConfig(backend.dsn)
if err != nil {
return serverVersion, nil, err
}
@ -374,3 +375,23 @@ func (backend *Backend) doPeriodically(f func(ctx context.Context) error, dur ti
}
}
}
// ParseConfig parses a DSN into a pgxpool.Config.
func ParseConfig(dsn string) (*pgxpool.Config, error) {
config, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, err
}
config.ConnConfig.LookupFunc = lookup
return config, nil
}
func lookup(ctx context.Context, host string) (addrs []string, err error) {
addrs, err = net.DefaultResolver.LookupHost(ctx, host)
// ignore no such host errors
if e := new(net.DNSError); errors.As(err, &e) && e.IsNotFound {
addrs = nil
err = nil
}
return addrs, err
}

View file

@ -184,3 +184,17 @@ func TestBackend(t *testing.T) {
return nil
}))
}
func TestLookup(t *testing.T) {
t.Parallel()
ctx, clearTimeout := context.WithTimeout(context.Background(), time.Second*10)
t.Cleanup(clearTimeout)
cfg, err := ParseConfig("host=localhost")
assert.NoError(t, err)
addrs, err := cfg.ConnConfig.LookupFunc(ctx, "test.unknown")
assert.NoError(t, err)
assert.Empty(t, addrs)
}