Documentation
¶
Overview ¶
Package phase provides a context-aware mechanism to coordinate shutdown of subsystems in a deterministic, hierarchical order.
A phase begins with a call to `phase.Next`, which takes a parent context and returns a `Phaser` and `error`. A `Phaser` implements `context.Context` and can be used anywhere a standard context is expected. If a non-nil error is returned the parent context or phase has ended. The function should clean up and return.
The owner of a `Phaser` is responsible for coordinating its shutdown. This means waiting on child phases to terminate then calling `phaser.Close`.
A phase ends when both of the following conditions are met:
- its context is canceled (as for other contexts, `<-p.Done()`)
- it has no remaining children (similar to above, `<-p.ChildrenDone()`)
Once the phase has ended a function may perform any necessary cleanup and then call `p.Close()` to signal its own termination to a parent phase.
Phase is able to discover parent phases through the context chain, even if intermediate code is not Phase aware. This means you can safely mix packages which do or don't support phases.
Example ¶
func doSomething(ctx context.Context) {
ctx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
ctx = phase.Next(ctx)
defer ctx.Close() // Ensure the phase ends
select {
case <-ctx.Done():
slog.Info("context ended")
case <-time.NewTicker(time.Second).C:
slog.Info("ticker fired")
}
// Wait for any child phases before returning
<-ctx.ChildrenDone()
}
Phase Lifecycle ¶
A phase is created by calling `phase.Next(ctx)`, which returns a Phaser context and an error value. A non-nil error indicates the phase cannot be started and the function should terminate. This can occur if the parent phase is waiting on children at the time the caller is attempting to create a new phase.
The Phaser context can be passed freely to downstream functions as with any other `context.Context`. Additional phases created will register as child phases of the nearest ancestor `Phaser`.
A phase ends with cancellation of the parent context. In this state the owning func should wait on its children to terminate, perform cleanup and then Close the Phaser.
In order, the following occurs:
- context cancellation is propagated immediately to all child phases
- the phase owner waits for all children to complete
- the phase owner marks its own phase as done, and returns
The call to `phase.Close` is usually a deferred call.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Phaser ¶
A Phaser is a context.Context that participates in coordinated shutdown. It tracks child phases created via Next, and ensures they are all properly terminated before the phase itself is considered closed.
Example ¶
package main
import (
"context"
"fmt"
"time"
"github.com/aelse/phase"
)
func main() {
f := func(ctx context.Context) {
next, _ := phase.Next(ctx)
select {
case <-next.Done():
fmt.Println("context ended")
case <-time.NewTicker(10 * time.Millisecond).C:
fmt.Println("ticker fired")
}
// Wait until child phases end.
// There are none in this example but we demonstrate correct behaviour.
<-next.ChildrenDone()
// Signal that our phase has ended.
next.Close()
}
ctx := context.Background()
f(ctx)
ctx, cancel := context.WithCancel(ctx)
cancel()
f(ctx)
}
Output: ticker fired context ended
Example (Contexts) ¶
package main
import (
"context"
"fmt"
"time"
"github.com/aelse/phase"
)
func main() {
// Create a top lever phaser which will be cancelled at end of main.
ctx, cancel := context.WithCancel(context.Background())
p0, _ := phase.Next(ctx)
defer p0.Close()
go func(ctx context.Context) {
fmt.Println("started p0 func")
p1, _ := phase.Next(ctx)
defer p1.Close()
type ctxStr string
// Run some other goroutines which take an ordinary context.
for i := range 5 {
// Phasers can be used like any other context. Let's set a value.
ctx := context.WithValue(p1, ctxStr("goroutine"), i)
go func(ctx context.Context) {
//nolint:forcetypeassert
num := ctx.Value(ctxStr("goroutine")).(int)
fmt.Printf("goroutine(%d) started\n", num)
<-ctx.Done()
fmt.Printf("goroutine(%d) finished\n", num)
}(ctx)
}
// Wait for our initiating context cancellation to perform cleanup.
<-ctx.Done()
fmt.Println("Waiting for descendent phases to end (none in this example)")
<-p1.ChildrenDone()
// There is no guarantee on order of completion for the goroutines
// as they only deal in contexts not Phasers. I can try to manage this
// in some other way.
fmt.Println("Waiting a few seconds for goroutines to finish")
time.Sleep(3 * time.Second)
}(p0)
fmt.Println("Shutdown in 5 seconds")
time.Sleep(5 * time.Second)
cancel()
fmt.Println("Waiting on children")
<-p0.ChildrenDone() // Wait until everything has finished.
fmt.Println("Bye!")
}
Output:
Example (FuncTree) ¶
package main
import (
"context"
"fmt"
"time"
"github.com/aelse/phase"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
phaser, _ := phase.Next(ctx)
defer phaser.Close()
type recursiveFunc func(f recursiveFunc, ctx context.Context, i, depth int)
f := func(f recursiveFunc, ctx context.Context, i, depth int) {
if i >= depth {
return
}
// Create a phase to cover this function scope, and defer Close.
p, _ := phase.Next(ctx)
defer p.Close()
// Create child funcs up to depth.
go f(f, p, i+1, depth)
// Wait on phase to be done, either due to propagated cancelation
// or a call to phase.Cancel targeting `p` (n/a in this example).
fmt.Printf("func<%d> doing work, waiting for context end\n", i)
<-p.Done()
// Child phases must return first
<-p.ChildrenDone()
fmt.Printf("func<%d> returning\n", i)
}
go f(f, phaser, 0, 5)
// Top level context timeout propagates down and we wait on the phaser.
<-ctx.Done()
fmt.Println("Waiting on top level phaser to complete")
<-phaser.ChildrenDone()
fmt.Println("Top level phaser ended. Bye!")
}
Output:
Example (OrderedShutdown) ¶
package main
import (
"context"
"fmt"
"github.com/aelse/phase"
)
func main() {
f := func(p phase.Phaser, message string) {
defer p.Close()
<-p.Done()
<-p.ChildrenDone()
fmt.Println(message)
}
ctx, cancel := context.WithCancel(context.Background())
phaser, _ := phase.Next(ctx)
defer phaser.Close()
p0, _ := phase.Next(phaser)
p1, _ := phase.Next(p0)
p2, _ := phase.Next(p1)
go f(p0, "p0 ended")
go f(p1, "p1 ended")
go f(p2, "p2 ended")
// We expect contexts to end in order: p2, p1, p0.
// Cancel Phaser chain
cancel()
<-phaser.ChildrenDone()
fmt.Println("finished!")
}
Output: p2 ended p1 ended p0 ended finished!
Example (PhaserDI) ¶
package main
import (
"context"
"fmt"
"time"
"github.com/aelse/phase"
)
func main() {
// Simulate any component that needs to perform cleanup at end of context.
// The first are is a phase.Phaser rather than context.Context so that the
// programmer knows to deal with handling the phase.
// This is a hint to the programmer, not a difference in implementation.
component := func(phaser phase.Phaser, name string) {
defer phaser.Close()
fmt.Printf("%s started\n", name)
<-phaser.Done()
// There might be child phases, so call Wait
<-phaser.ChildrenDone()
fmt.Printf("%s shutting down\n", name)
time.Sleep(time.Second)
}
// Create a top level phase which will be cancelled at end of main.
ctx, cancel := context.WithCancel(context.Background())
p0, _ := phase.Next(ctx)
defer p0.Close()
// Create a tree of phasers from the root and use dependency injection to pass it
// to each component.
p1, _ := phase.Next(p0)
go component(p1, "db")
p2, _ := phase.Next(p1)
go component(p2, "data pipeline")
p3, _ := phase.Next(p2)
go component(p3, "web server")
fmt.Println("Shutdown in 2 seconds")
time.Sleep(2 * time.Second)
// Cancel this context, which cascades down.
cancel()
// Wait until everything has finished.
<-p0.ChildrenDone()
fmt.Println("Bye!")
}
Output: