Skip to content

Commit

Permalink
Improve context deadline (#381)
Browse files Browse the repository at this point in the history
* Safe time for context

* Add comment

* update doc
  • Loading branch information
waybackarchiver authored Apr 28, 2023
1 parent 99c2021 commit e4b7701
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
1 change: 1 addition & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed
- Set NoWait to true for tor listen config ([#368](https://github.com/wabarc/wayback/pull/368))
- Improve context deadline ([#381](https://github.com/wabarc/wayback/pull/381))

## [0.19.1] - 2023-03-21

Expand Down
19 changes: 18 additions & 1 deletion wayback.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,8 @@ func Wayback(ctx context.Context, rdx reduxer.Reduxer, cfg *config.Options, urls
ctx, cancel = context.WithTimeout(ctx, cfg.WaybackTimeout())
defer cancel()
}
ctx, cancel := context.WithTimeout(ctx, duration(ctx))
defer cancel()

mu := sync.Mutex{}
cols := []Collect{}
Expand Down Expand Up @@ -232,7 +234,12 @@ func Wayback(ctx context.Context, rdx reduxer.Reduxer, cfg *config.Options, urls
func Playback(ctx context.Context, cfg *config.Options, urls ...*url.URL) (cols []Collect, err error) {
logger.Debug("start...")

ctx, cancel := context.WithTimeout(ctx, cfg.WaybackTimeout())
if _, ok := ctx.Deadline(); !ok {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, cfg.WaybackTimeout())
defer cancel()
}
ctx, cancel := context.WithTimeout(ctx, duration(ctx))
defer cancel()

mu := sync.Mutex{}
Expand Down Expand Up @@ -278,3 +285,13 @@ func Playback(ctx context.Context, cfg *config.Options, urls ...*url.URL) (cols

return cols, nil
}

// duration reduce the context deadline time for downstream and reserve
// extra time for the caller.
func duration(ctx context.Context) time.Duration {
deadline, _ := ctx.Deadline()
elapsed := deadline.Unix() - time.Now().Unix()
safeTime := elapsed * 90 / 100

return time.Duration(safeTime) * time.Second
}

0 comments on commit e4b7701

Please sign in to comment.