Fix "context canceled" with partial

Make sure the context used for timeouts isn't created based on the incoming
context, as we have cases where this can cancel the context prematurely.

Fixes #10789
This commit is contained in:
Bjørn Erik Pedersen 2023-03-04 18:08:29 +01:00
parent 184a67ac47
commit 3bbeb5688c
5 changed files with 40 additions and 14 deletions

View file

@ -180,14 +180,15 @@ func (ini *Init) checkDone() {
}
func (ini *Init) withTimeout(ctx context.Context, timeout time.Duration, f func(ctx context.Context) (any, error)) (any, error) {
ctx, cancel := context.WithTimeout(ctx, timeout)
// Create a new context with a timeout not connected to the incoming context.
waitCtx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
c := make(chan verr, 1)
go func() {
v, err := f(ctx)
select {
case <-ctx.Done():
case <-waitCtx.Done():
return
default:
c <- verr{v: v, err: err}
@ -195,7 +196,7 @@ func (ini *Init) withTimeout(ctx context.Context, timeout time.Duration, f func(
}()
select {
case <-ctx.Done():
case <-waitCtx.Done():
return nil, errors.New("timed out initializing value. You may have a circular loop in a shortcode, or your site may have resources that take longer to build than the `timeout` limit in your Hugo config file.")
case ve := <-c:
return ve.v, ve.err

View file

@ -126,12 +126,6 @@ func TestInitAddWithTimeoutTimeout(t *testing.T) {
init := New().AddWithTimeout(100*time.Millisecond, func(ctx context.Context) (any, error) {
time.Sleep(500 * time.Millisecond)
select {
case <-ctx.Done():
return nil, nil
default:
}
t.Fatal("slept")
return nil, nil
})