lnutils: add ContextFromQuit to bridge quit channels to contexts

In this commit, we add ContextFromQuit, a utility for bridging the quit
channel shutdown pattern to context.Context-based cancellation.

Several subsystems in lnd use a plain quit <-chan struct{} for
cooperative shutdown rather than a context.Context. When those
subsystems need to await a Future[error], which uses a context for
cancellation, they need a way to derive a context that is cancelled
when the quit channel closes.

ContextFromQuit does exactly that: it returns a context tied to
context.Background() plus a cancel function, and spins up a minimal
goroutine that cancels the context as soon as quit is closed. The
returned cancel must be called (deferred at the call site) so the
goroutine exits when the enclosing operation completes normally before
shutdown.

This is a pure utility with no policy and no default timeout, so
callers remain in full control of lifetime.
This commit is contained in:
Olaoluwa Osuntokun 2026-02-17 19:15:13 -08:00
parent 4e0992fa4e
commit eadea00aeb

22
lnutils/context.go Normal file
View file

@ -0,0 +1,22 @@
package lnutils
import "context"
// ContextFromQuit returns a context that is cancelled when the provided quit
// channel is closed. The returned cancel function MUST be called to avoid
// goroutine leaks.
func ContextFromQuit(quit <-chan struct{}) (context.Context,
context.CancelFunc) {
ctx, cancel := context.WithCancel(context.Background())
go func() {
select {
case <-quit:
cancel()
case <-ctx.Done():
}
}()
return ctx, cancel
}