Skip to content

Commit

Permalink
Add timeout on github client (#1290)
Browse files Browse the repository at this point in the history
* add timeout on github client

* implement linter recommendation
  • Loading branch information
neel-astro authored Jul 5, 2023
1 parent f6adffb commit e672f4c
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
6 changes: 4 additions & 2 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package cmd

import (
"fmt"
"net/http"
"os"
"time"

"github.com/astronomer/astro-cli/cmd/registry"

Expand Down Expand Up @@ -70,8 +72,8 @@ Welcome to the Astro CLI, the modern command line interface for data orchestrati
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
// Check for latest version
if config.CFG.UpgradeMessage.GetBool() {
// create github client
githubClient := github.NewClient(nil)
// create github client with 3 second timeout, setting an aggressive timeout since its not mandatory to get a response in each command execution
githubClient := github.NewClient(&http.Client{Timeout: 3 * time.Second})
// compare current version to latest
err = version.CompareVersions(githubClient, "astronomer", "astro-cli")
if err != nil {
Expand Down
36 changes: 36 additions & 0 deletions version/version_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package version

import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"

"github.com/google/go-github/v48/github"
"github.com/stretchr/testify/assert"
)

func TestGithubAPITimeout(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(5 * time.Second) // sleeping and doing nothing
}))
defer ts.Close()
githubURL, err := url.Parse(fmt.Sprintf("%s/", ts.URL))
assert.NoError(t, err)

githubClient := github.NewClient(&http.Client{Timeout: 1 * time.Second}) // client side timeout should be less than server side sleep defined above
githubClient.BaseURL = githubURL

start := time.Now()
release, err := getLatestRelease(githubClient, "test", "test")
elapsed := time.Since(start)
// assert time to get a response from the function is only slightly greater than client timeout
assert.GreaterOrEqual(t, elapsed, 1*time.Second)
assert.Less(t, elapsed, 2*time.Second)
// assert error returned is related to client timeout
assert.Nil(t, release)
assert.Error(t, err)
assert.Contains(t, err.Error(), "context deadline exceeded")
}

0 comments on commit e672f4c

Please sign in to comment.