Skip to content

Commit

Permalink
Request the project ID from the metadata server only once
Browse files Browse the repository at this point in the history
If there is an error such as "no route to host", which comes up during
development, every request will slow down. Now the server is only
contacted once. This will speed up requests in production as well by
removing the call to the metadata server from all but the first request.
  • Loading branch information
mtraver committed Nov 15, 2022
1 parent e4e6f12 commit 1ad78d6
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion gaelog.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"net/http"
"os"
"strings"
"sync"
"time"

"cloud.google.com/go/compute/metadata"
Expand All @@ -31,6 +32,22 @@ const (
traceContextHeaderName = "X-Cloud-Trace-Context"
)

var (
metadataOnce sync.Once

metadataProjectID string
metadataProjectIDErr error
)

// projectIDFromMetadataService fetches the project ID from the metadata server,
// memoizing the result for use on all but the first call.
func projectIDFromMetadataService() (string, error) {
metadataOnce.Do(func() {
metadataProjectID, metadataProjectIDErr = metadata.ProjectID()
})
return metadataProjectID, metadataProjectIDErr
}

func traceID(projectID, trace string) string {
return fmt.Sprintf("projects/%s/traces/%s", projectID, trace)
}
Expand Down Expand Up @@ -64,7 +81,7 @@ func newServiceInfo() (serviceInfo, error) {
}

// Try the metadata service for the project ID.
crProjectID, err := metadata.ProjectID()
crProjectID, err := projectIDFromMetadataService()
if err != nil {
return serviceInfo{}, err
}
Expand Down

0 comments on commit 1ad78d6

Please sign in to comment.