Repository navigation
Make Client safe for concurrent use #60
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -110,6 +110,7 @@ import ( | |
| "io" | ||
| "net/http" | ||
| "net/url" | ||
| "sync" | ||
| "time" | ||
|
|
||
| "github.com/openrdap/rdap/bootstrap/cache" | ||
|
|
@@ -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. | ||
|
|
@@ -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. | ||
|
|
@@ -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 | ||
| } | ||
|
|
||
|
|
@@ -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 | ||
| 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 { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 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 |
||
| // 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)) | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -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) | ||
|
|
||
|
|
@@ -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) | ||
|
|
||
|
|
@@ -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) | ||
|
|
||
|
|
@@ -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) | ||
|
|
||
|
|
@@ -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) | ||
|
|
||
|
|
||
| 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() | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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 oldforceDownload=truestill forces another download despite the fresh registry.Recheck cache state under
mubefore the download decision. Keep cache-load failure as a separate refresh reason. This avoids a second network wait after a successful refresh.