From eadea00aebb45e04304380f1cccb8052da885725 Mon Sep 17 00:00:00 2001 From: Olaoluwa Osuntokun Date: Tue, 17 Feb 2026 19:15:13 -0800 Subject: [PATCH] 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. --- lnutils/context.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 lnutils/context.go diff --git a/lnutils/context.go b/lnutils/context.go new file mode 100644 index 000000000..5deeb7714 --- /dev/null +++ b/lnutils/context.go @@ -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 +}