Skip to content

Commit

Permalink
Merge pull request #6 from jbowes/timeout-opt
Browse files Browse the repository at this point in the history
Introduce a timeout option
  • Loading branch information
jbowes committed Aug 11, 2021
2 parents 6960925 + 461969a commit 96a1f35
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
5 changes: 0 additions & 5 deletions impl/github.go
Expand Up @@ -9,7 +9,6 @@ import (
"encoding/json"
"fmt"
"net/http"
"time"
)

// GitHubReleaser is the default Releaser used in whatsnew.
Expand All @@ -30,10 +29,6 @@ func (g *GitHubReleaser) Get(ctx context.Context, etag string) ([]Release, strin
req.Header.Set("If-None-Match", etag)
}

// TODO: configurable timeout? relying on ctx doesn't seem like a great API
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()

req = req.WithContext(ctx)

c := g.Client
Expand Down
27 changes: 26 additions & 1 deletion whatsnew.go
Expand Up @@ -26,6 +26,13 @@ import (
// releases if no override is given. It is one week.
const DefaultFrequency = 7 * 24 * time.Hour

// Timeout values used as options to Check, controlling how long the
// Check is allowed to run.
const (
DefaultTimeout = 5 * time.Second
NoTimeout = time.Duration(-1)
)

type result struct {
v string
err error
Expand Down Expand Up @@ -56,9 +63,17 @@ type Options struct {
Cache string // A full file path to store the cache. Should end in `.json`
Version string // The current semver version of the program to check.

// Optional. if not provided DefaultFrequency is used.
// Optional. Controls how often to run a release check.
// If not provided, DefaultFrequency is used.
Frequency time.Duration

// Optional. Sets a maximum duration to run the check before
// timing out and returning either the cached value, or no update.
// If not provided, DefaultTimeout is used. Set to NoTimeout (-1)
// to disable the timeout. Context cancelation is honored, so you
// may further restrict the deadline with the provided context.
Timeout time.Duration

// Slots to override cacher and Releaser
Cacher impl.Cacher // If provided, Cache is ignored.
Releaser impl.Releaser // If provided, Slug is ignored.
Expand Down Expand Up @@ -94,6 +109,10 @@ func (o *Options) resolve() error {
o.Frequency = DefaultFrequency
}

if o.Timeout == 0 {
o.Timeout = DefaultTimeout
}

return nil
}

Expand Down Expand Up @@ -123,6 +142,12 @@ func doWork(ctx context.Context, opts *Options) (string, error) {
return "", err
}

if opts.Timeout > 0 {
var cancel func()
ctx, cancel = context.WithTimeout(ctx, opts.Timeout)
defer cancel()
}

i, err := opts.Cacher.Get(ctx)
if err != nil {
i = &impl.Info{}
Expand Down

0 comments on commit 96a1f35

Please sign in to comment.