sourcegraph/internal/goroutine/background.go
Joe Chen 2589fef13e
lib/background: upgrade Routine interface with context and errors (#62136)
This PR is a result/followup of the improvements we've made in the [SAMS repo](https://github.com/sourcegraph/sourcegraph-accounts/pull/199) that allows call sites to pass down a context (primarily to indicate deadline, and of course, cancellation if desired) and collects the error returned from `background.Routine`s `Stop` method.

Note that I did not adopt returning error from `Stop` method because I realize in monorepo, the more common (and arguably the desired) pattern is to hang on the call of `Start` method until `Stop` is called, so it is meaningless to collect errors from `Start` methods as return values anyway, and doing that would also complicate the design and semantics more than necessary.

All usages of the the `background.Routine` and `background.CombinedRoutines` are updated, I DID NOT try to interpret the code logic and make anything better other than fixing compile and test errors.

The only file that contains the core change is the [`lib/background/background.go`](https://github.com/sourcegraph/sourcegraph/pull/62136/files#diff-65c3228388620e91f8c22d91c18faac3f985fc67d64b08612df18fa7c04fafcd).
2024-05-24 10:04:55 -04:00

41 lines
1.5 KiB
Go

package goroutine
import (
"time"
"github.com/sourcegraph/sourcegraph/internal/env"
"github.com/sourcegraph/sourcegraph/lib/background"
)
var GracefulShutdownTimeout = env.MustGetDuration("SRC_GRACEFUL_SHUTDOWN_TIMEOUT", 10*time.Second, "Graceful shutdown timeout")
// BackgroundRoutine represents a component of a binary that consists of a long
// running process with a graceful shutdown mechanism.
//
// See
// https://docs-legacy.sourcegraph.com/dev/background-information/backgroundroutine
// for more information and a step-by-step guide on how to implement a
// BackgroundRoutine.
type BackgroundRoutine = background.Routine
// WaitableBackgroundRoutine enhances BackgroundRoutine with a Wait method that
// blocks until the value's Start method has returned.
type WaitableBackgroundRoutine interface {
BackgroundRoutine
Wait()
}
// MonitorBackgroundRoutines will start the given background routines in their own
// goroutine. If the given context is canceled or a signal is received, the Stop
// method of each routine will be called. This method blocks until the Stop methods
// of each routine have returned. Two signals will cause the app to shutdown
// immediately.
var MonitorBackgroundRoutines = background.Monitor
// CombinedRoutine is a list of routines which are started and stopped in unison.
type CombinedRoutine = background.CombinedRoutine
// NoopRoutine return a background routine that does nothing for start or stop.
// If the name is empty, it will default to "noop".
var NoopRoutine = background.NoopRoutine