github.com/cockroachdb/cockroachdb-parser@v0.23.3-0.20240213214944-911057d40c9a/pkg/util/timeutil/timeout.go (about)

     1  // Copyright 2021 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  package timeutil
    12  
    13  import (
    14  	"context"
    15  	"time"
    16  
    17  	"github.com/cockroachdb/errors"
    18  )
    19  
    20  // RunWithTimeout runs a function with a timeout, the same way you'd do with
    21  // context.WithTimeout. It improves the opaque error messages returned by
    22  // WithTimeout by augmenting them with the op string that is passed in.
    23  func RunWithTimeout(
    24  	ctx context.Context, op string, timeout time.Duration, fn func(ctx context.Context) error,
    25  ) error {
    26  	ctx, cancel := context.WithTimeout(ctx, timeout) // nolint:context
    27  	defer cancel()
    28  	start := Now()
    29  	err := fn(ctx)
    30  	if err != nil && errors.Is(ctx.Err(), context.DeadlineExceeded) {
    31  		err = &TimeoutError{
    32  			operation: op,
    33  			timeout:   timeout,
    34  			took:      Since(start),
    35  			cause:     err,
    36  		}
    37  	}
    38  	return err
    39  }