github.com/opentofu/opentofu@v1.7.1/internal/helper/slowmessage/slowmessage.go (about)

     1  // Copyright (c) The OpenTofu Authors
     2  // SPDX-License-Identifier: MPL-2.0
     3  // Copyright (c) 2023 HashiCorp, Inc.
     4  // SPDX-License-Identifier: MPL-2.0
     5  
     6  package slowmessage
     7  
     8  import (
     9  	"time"
    10  )
    11  
    12  // SlowFunc is the function that could be slow. Usually, you'll have to
    13  // wrap an existing function in a lambda to make it match this type signature.
    14  type SlowFunc func() error
    15  
    16  // CallbackFunc is the function that is triggered when the threshold is reached.
    17  type CallbackFunc func()
    18  
    19  // Do calls sf. If threshold time has passed, cb is called. Note that this
    20  // call will be made concurrently to sf still running.
    21  func Do(threshold time.Duration, sf SlowFunc, cb CallbackFunc) error {
    22  	// Call the slow function
    23  	errCh := make(chan error, 1)
    24  	go func() {
    25  		errCh <- sf()
    26  	}()
    27  
    28  	// Wait for it to complete or the threshold to pass
    29  	select {
    30  	case err := <-errCh:
    31  		return err
    32  	case <-time.After(threshold):
    33  		// Threshold reached, call the callback
    34  		cb()
    35  	}
    36  
    37  	// Wait an indefinite amount of time for it to finally complete
    38  	return <-errCh
    39  }