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`. A `Phaser` implements `context.Context` and can be used anywhere a standard context is expected.
The owner of a `Phaser` is responsible for coordinating its shutdown. This includes ensuring all child phases have completed before calling `phase.Close`.
A phase ends under either of the following conditions:
- its context is canceled (e.g., via `<-p.Done()`)
- `phase.Cancel(p)` is called explicitly
In either case, before closing the phase, you **must** call `phase.Wait(p)` to ensure all child phases have completed.
The following methods accept any `context.Context` as input:
- `phase.Next`
- `phase.Cancel`
- `phase.Close`
- `phase.Wait`
These functions will automatically locate the nearest `Phaser` in the context chain. If none is found, the call panics, indicating a programming error.
Example ¶
func doSomething(ctx context.Context) {
ctx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
ctx = phase.Next(ctx)
defer phase.Close(ctx) // 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
phase.Wait(ctx)
}
Phase Lifecycle ¶
A phase is created by calling `phase.Next(ctx)`, which returns a new context associated with the phase.
That context can be passed freely to downstream functions. If those functions create their own phases using the same context, they will register as child phases of the nearest ancestor `Phaser`.
A phase typically ends in response to one of:
- a call to `phase.Cancel(ctx)`
- cancellation of the parent context
Upon termination, the following occurs:
- cancellation is propagated to all child phases
- the phase waits for all children to complete
- the phase marks its own context as done
The function owning the phase can use this opportunity to perform final cleanup before calling `phase.Close`, usually via a deferred call.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Cancel ¶ added in v0.0.3
Cancel signals that the phase identified by the given context should end. This cancels the context and begins coordinated shutdown.
Cancel will panic if the context does not contain a Phaser.
Types ¶
type Phaser ¶
A Phaser is a context.Context that participates in coordinated phase shutdown.
A Phaser 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.
phase.Wait(next)
// Signal that our phase has ended.
phase.Close(next)
}
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.
p0 := phase.Next(context.Background())
defer phase.Close(p0)
go func(ctx context.Context) {
fmt.Println("started p0 func")
p1 := phase.Next(ctx)
defer phase.Close(p1)
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)")
phase.Wait(p1)
// 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)
phase.Cancel(p0)
fmt.Println("Waiting on children")
phase.Wait(p0) // Wait until everything has finished.
fmt.Println("Bye!")
}
Output:
Example (OrderedShutdown) ¶
package main
import (
"context"
"fmt"
"github.com/aelse/phase"
)
func main() {
f := func(ctx context.Context, message string) {
defer phase.Close(ctx)
<-ctx.Done()
phase.Wait(ctx)
fmt.Println(message)
}
p0 := phase.Next(context.Background())
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
phase.Cancel(p0)
phase.Wait(p0)
fmt.Println("finished!")
}
Output: p2 ended p1 ended p0 ended finished!
Example (SimpleDI) ¶
package main
import (
"context"
"fmt"
"time"
"github.com/aelse/phase"
)
func main() {
// simulate any component that needs to perform cleanup at end of context.
component := func(ctx context.Context, name string) {
defer phase.Close(ctx)
fmt.Printf("%s started\n", name)
<-ctx.Done()
// There might be child phases, so call Wait
phase.Wait(ctx)
fmt.Printf("%s shutting down\n", name)
time.Sleep(time.Second)
}
// Create a top level phase which will be cancelled at end of main.
p0 := phase.Next(context.Background())
defer phase.Close(p0)
// Create a tree of phasers from the root and use dependency injection to pass it
// to each components. The downside of this is that the components need to know
// they are responsible for cleaning up a phase that they didn't create.
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.
phase.Cancel(p0)
// Wait until everything has finished.
phase.Wait(p0)
fmt.Println("Bye!")
}
Output: