Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 81 additions & 25 deletions bootstrap/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ import (
"io"
"net/http"
"net/url"
"sync"
"time"

"github.com/openrdap/rdap/bootstrap/cache"
Expand Down Expand Up @@ -162,6 +163,11 @@ type Client struct {
Verbose func(text string)

registries map[RegistryType]Registry

// mu guards registries, the Cache and lazy initialisation, so one Client
// can be shared by many goroutines. It is never held across network I/O
// or while calling Verbose.
mu sync.Mutex
}

// A Registry implements bootstrap lookups.
Expand All @@ -187,6 +193,10 @@ func (c *Client) init() {
if c.BaseURL == nil {
c.BaseURL, _ = url.Parse(DefaultBaseURL)
}

if c.Verbose == nil {
c.Verbose = func(text string) {}
}
}

// Download downloads a single bootstrap registry file.
Expand All @@ -200,18 +210,24 @@ func (c *Client) Download(registry RegistryType) error {
//
// On success, the relevant Registry is refreshed. Use the matching accessor (ASN(), DNS(), IPv4(), or IPv6()) to access it.
func (c *Client) DownloadWithContext(ctx context.Context, registry RegistryType) error {
c.mu.Lock()
c.init()
c.mu.Unlock()
return c.downloadAndStore(ctx, registry)
}

var json []byte
var s Registry

// downloadAndStore fetches a registry file without holding mu, so a slow
// download never blocks other callers, then stores it under mu.
func (c *Client) downloadAndStore(ctx context.Context, registry RegistryType) error {
json, s, err := c.download(ctx, registry)
if err != nil {
return err
}

err = c.Cache.Save(c.filenameFor(registry), json)
if err != nil {
c.mu.Lock()
defer c.mu.Unlock()

if err := c.Cache.Save(c.filenameFor(registry), json); err != nil {
return err
}

Expand Down Expand Up @@ -319,62 +335,92 @@ func newRegistry(registry RegistryType, json []byte) (Registry, error) {
}

// Lookup returns the RDAP base URLs for the bootstrap question |question|.
//
// Verbose messages go to c.Verbose. Lookup is safe for concurrent use.
func (c *Client) Lookup(question *Question) (*Answer, error) {
return c.LookupVerbose(question, nil)
}

// LookupVerbose is Lookup with verbose messages sent to verbose. A nil verbose
// falls back to c.Verbose. Verbose is never called with a lock held, so it may
// call the registry accessors such as DNS(). Unlike writing c.Verbose, it does
// not modify the Client, so one Client may serve several callers at once.
func (c *Client) LookupVerbose(question *Question, verbose func(text string)) (*Answer, error) {
c.mu.Lock()
c.init()
if c.Verbose == nil {
c.Verbose = func(text string) {}
if verbose == nil {
verbose = c.Verbose
}
c.mu.Unlock()

c.Verbose(" bootstrap: Looking up...")
c.Verbose(fmt.Sprintf(" bootstrap: Question type : %s", question.RegistryType))
c.Verbose(fmt.Sprintf(" bootstrap: Question query: %s", question.Query))
verbose(" bootstrap: Looking up...")
verbose(fmt.Sprintf(" bootstrap: Question type : %s", question.RegistryType))
verbose(fmt.Sprintf(" bootstrap: Question query: %s", question.Query))

registry := question.RegistryType

state := c.Cache.State(c.filenameFor(registry))
c.Verbose(fmt.Sprintf(" bootstrap: Cache state: %s: %s", c.filenameFor(registry), state))
c.mu.Lock()
filename := c.filenameFor(registry)
state := c.Cache.State(filename)
c.mu.Unlock()
verbose(fmt.Sprintf(" bootstrap: Cache state: %s: %s", filename, state))

// An expired file is refreshed even if it's already parsed into memory.
forceDownload := state == cache.Expired

c.mu.Lock()
var loadErr error
if c.shouldLoadFromCache(registry, state) {
if err := c.reloadFromCache(registry); err != nil {
if loadErr = c.reloadFromCache(registry); loadErr != nil {
forceDownload = true

c.Verbose(fmt.Sprintf(" bootstrap: Cache load error (%s), downloading...", err))
}
}
c.mu.Unlock()
if loadErr != nil {
verbose(fmt.Sprintf(" bootstrap: Cache load error (%s), downloading...", loadErr))
}

if c.registries[registry] == nil || forceDownload {
c.Verbose(fmt.Sprintf(" bootstrap: Downloading %s", registry.Filename()))
c.mu.Lock()
needDownload := c.registries[registry] == nil || forceDownload

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Performance & Scalability · Quick win

Recheck expiry before starting a refresh.

Caller A can record Expired, then pause in the verbose callback. Caller B can refresh the registry during that pause. When A resumes, its old forceDownload=true still forces another download despite the fresh registry.

Recheck cache state under mu before the download decision. Keep cache-load failure as a separate refresh reason. This avoids a second network wait after a successful refresh.

c.mu.Unlock()

if err := c.DownloadWithContext(question.Context(), registry); err != nil {
if needDownload {
verbose(fmt.Sprintf(" bootstrap: Downloading %s", registry.Filename()))

if err := c.downloadAndStore(question.Context(), registry); err != nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Performance & Scalability · Heavy lift

Share one in-flight refresh per registry.

With an empty cache, all 16 concurrent lookups can pass Line 384 before any download completes. Each then downloads the same registry. Bootstrap traffic grows with request concurrency. This violates the documented once-per-24-hours cache behavior. (raw.githubusercontent.com)

Reserve the registry refresh under mu. Let other callers wait outside mu, with their own contexts. Clear the reservation on success and failure. Add a concurrent cold-cache test that counts bootstrap requests.

// Service Registry files change rarely, so an expired copy still
// answers most queries. Prefer one to failing the lookup.
c.mu.Lock()
if c.registries[registry] == nil {
if cacheErr := c.reloadFromCache(registry); cacheErr != nil {
c.mu.Unlock()
return nil, err
}
}
c.mu.Unlock()

c.Verbose(fmt.Sprintf(" bootstrap: Download failed (%s), using expired Service Registry file", err))
verbose(fmt.Sprintf(" bootstrap: Download failed (%s), using expired Service Registry file", err))
}
} else {
c.Verbose(" bootstrap: Using cached Service Registry file")
verbose(" bootstrap: Using cached Service Registry file")
}

answer, err := c.registries[registry].Lookup(question)
c.mu.Lock()
reg := c.registries[registry]
c.mu.Unlock()

answer, err := reg.Lookup(question)

if answer != nil {
c.Verbose(fmt.Sprintf(" bootstrap: Looked up '%s'", answer.Query))
verbose(fmt.Sprintf(" bootstrap: Looked up '%s'", answer.Query))
if answer.Entry != "" {
c.Verbose(fmt.Sprintf(" bootstrap: Matching entry '%s'", answer.Entry))
verbose(fmt.Sprintf(" bootstrap: Matching entry '%s'", answer.Entry))
} else {
c.Verbose(" bootstrap: No match")
verbose(" bootstrap: No match")
}

for i, url := range answer.URLs {
c.Verbose(fmt.Sprintf(" bootstrap: Service URL #%d: '%s'", i+1, url))
verbose(fmt.Sprintf(" bootstrap: Service URL #%d: '%s'", i+1, url))
}
}

Expand All @@ -385,6 +431,8 @@ func (c *Client) Lookup(question *Question) (*Answer, error) {
//
// This function never initiates a network transfer.
func (c *Client) ASN() *ASNRegistry {
c.mu.Lock()
defer c.mu.Unlock()
c.init()
c.freshenFromCache(ASN)

Expand All @@ -396,6 +444,8 @@ func (c *Client) ASN() *ASNRegistry {
//
// This function never initiates a network transfer.
func (c *Client) DNS() *DNSRegistry {
c.mu.Lock()
defer c.mu.Unlock()
c.init()
c.freshenFromCache(DNS)

Expand All @@ -407,6 +457,8 @@ func (c *Client) DNS() *DNSRegistry {
//
// This function never initiates a network transfer.
func (c *Client) IPv4() *NetRegistry {
c.mu.Lock()
defer c.mu.Unlock()
c.init()
c.freshenFromCache(IPv4)

Expand All @@ -418,6 +470,8 @@ func (c *Client) IPv4() *NetRegistry {
//
// This function never initiates a network transfer.
func (c *Client) IPv6() *NetRegistry {
c.mu.Lock()
defer c.mu.Unlock()
c.init()
c.freshenFromCache(IPv6)

Expand All @@ -429,6 +483,8 @@ func (c *Client) IPv6() *NetRegistry {
//
// This function never initiates a network transfer.
func (c *Client) ServiceProvider() *ServiceProviderRegistry {
c.mu.Lock()
defer c.mu.Unlock()
c.init()
c.freshenFromCache(ServiceProvider)

Expand Down
68 changes: 68 additions & 0 deletions bootstrap/concurrency_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package bootstrap

import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
)

func newDNSServer(t *testing.T) *url.URL {
t.Helper()
var srv *httptest.Server
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/dns.json") {
fmt.Fprintf(w, `{"version":"1.0","publication":"2024-01-01T00:00:00Z","services":[[["com"],["%s/rdap/"]]]}`, srv.URL)
return
}
http.NotFound(w, r)
}))
t.Cleanup(srv.Close)
base, _ := url.Parse(srv.URL + "/")
return base
}

// Verbose may call back into the client. Before, Lookup held the lock while
// calling Verbose, so this deadlocked.
func TestLookupVerboseMayCallAccessors(t *testing.T) {
base := newDNSServer(t)
b := &Client{BaseURL: base}

var calls int
answer, err := b.LookupVerbose(&Question{RegistryType: DNS, Query: "example.com"}, func(string) {
calls++
_ = b.DNS()
})
if err != nil {
t.Fatal(err)
}
if answer == nil || len(answer.URLs) == 0 {
t.Fatalf("no answer: %#v", answer)
}
if calls == 0 {
t.Fatal("verbose was not called")
}
}

// Concurrent lookups with their own verbose callbacks share one client. Run
// with -race.
func TestLookupVerboseSharedClient(t *testing.T) {
base := newDNSServer(t)
b := &Client{BaseURL: base}

var wg sync.WaitGroup
for i := range 16 {
wg.Add(1)
go func(i int) {
defer wg.Done()
_, err := b.LookupVerbose(&Question{RegistryType: DNS, Query: "example.com"}, func(string) {})
if err != nil {
t.Errorf("lookup %d: %v", i, err)
}
}(i)
}
wg.Wait()
}
18 changes: 11 additions & 7 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"io"
"net/http"
"strings"
"sync"
"time"

"github.com/openrdap/rdap/bootstrap"
Expand Down Expand Up @@ -84,6 +85,10 @@ type Client struct {
// Service Provider support is now always enabled.
// This field is ignored.
ServiceProviderExperiment bool

// mu guards lazy initialisation, so one Client can be shared by many
// goroutines. It is never held across network I/O.
mu sync.Mutex
}

// Do runs the RDAP request req and returns its Response.
Expand All @@ -104,6 +109,7 @@ func (c *Client) Do(req *Request) (*Response, error) {
}
}

c.mu.Lock()
// Init HTTP client?
if c.HTTP == nil {
c.HTTP = &http.Client{}
Expand All @@ -118,6 +124,7 @@ func (c *Client) Do(req *Request) (*Response, error) {
if c.Verbose == nil {
c.Verbose = func(text string) {}
}
c.mu.Unlock()

c.Verbose("")
c.Verbose("client: Running...")
Expand Down Expand Up @@ -145,12 +152,6 @@ func (c *Client) Do(req *Request) (*Response, error) {
}
}

origBootstrapVerbose := c.Bootstrap.Verbose
c.Bootstrap.Verbose = c.Verbose
defer func() {
c.Bootstrap.Verbose = origBootstrapVerbose
}()

question := &bootstrap.Question{
RegistryType: *bootstrapType,
Query: req.Query,
Expand All @@ -160,7 +161,10 @@ func (c *Client) Do(req *Request) (*Response, error) {
var answer *bootstrap.Answer
var err error

answer, err = c.Bootstrap.Lookup(question)
// Verbose is passed per call rather than set on the bootstrap client,
// which may be shared with other Clients. The lookup runs without mu,
// so a slow registry download does not block other requests.
answer, err = c.Bootstrap.LookupVerbose(question, c.Verbose)
resp.BootstrapAnswer = answer

if err != nil {
Expand Down
Loading