phase

package module
v0.0.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 12, 2025 License: MIT Imports: 3 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Tests Lint codecov License GoDoc

Phase

Phase helps Go applications perform graceful, ordered shutdown — giving you explicit control over how subsystems wind down.

Use Phase to ensure resources are released in the right order: servers stop accepting connections before pipelines drain, and pipelines complete before writing to the database ends.


🚦 Why Phase?

Imagine your app has this data flow:

[ Web API Request ] -> [ Transform Data ] -> [ Persist to DB ]

During shutdown, you want:

  1. The web server to stop accepting new requests
  2. Outstanding work in the transformation queue to finish
  3. Final transformed data to be persisted to the database
  4. The program to exit cleanly

But standard context.Context cancels everything immediately downstream, making it hard to enforce this order. You’d need to manually coordinate dependent goroutines — a recipe for bugs and complexity.

Phase solves this by chaining context lifecycles with parent-child awareness. Shutdown proceeds in reverse order of creation, giving you fine-grained control with a simple API.


🧠 Background

Go’s context.Context is often used to manage cancellation. However, it wasn’t designed for ordered shutdown of interdependent goroutines.

Phase extends this concept by introducing a Phaser — a context with awareness of its children. It gives you a simple interface to create, cancel, wait, and close contexts in a reliable, deterministic order.


✨ Features

  • ✅ Works anywhere a context.Context is accepted
  • 📚 Automatically tracks child phases
  • ⛓ Graceful teardown in reverse order of creation
  • 🧹 Guarantees that cleanup completes before parent exits

🚀 Getting Started

Install:

go get github.com/aelse/phase

Create a root Phaser from any context:

phaser := phase.FromContext(context.Background())

Spawn child phases using Next():

child := phaser.Next()

Cancel and wait for shutdown in reverse order:

phase.Cancel(child)
phase.Wait(child)
phase.Close(child)

🔧 Example

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/aelse/phase"
)

func main() {
	// Create root phaser
	ph := phase.Next(context.Background())
	defer phase.Close(ph)

	// Each subsystem is a child of the previous
	web := phase.Next(ph)
	go component(web, "Web Server")

	pipeline := phase.Next(web)
	go component(pipeline, "Data Pipeline")

	db := phase.Next(pipeline)
	go component(db, "Database")

	fmt.Println("Shutting down in 5 seconds...")
	time.Sleep(5 * time.Second)

	// Start shutdown from root
	phase.Cancel(ph)
	// Wait for all phases to complete
	phase.Wait(ph)
	fmt.Println("All systems shut down.")
}

func component(p phase.Phaser, name string) {
	defer phase.Close(p)
	fmt.Printf("[%s] started\n", name)
	<-p.Done()
	fmt.Printf("[%s] shutting down (wait for children)\n", name)
	phase.Wait(p)
	fmt.Printf("[%s] shutting down (cleanup)\n", name)
	time.Sleep(time.Second)
	fmt.Printf("[%s] shutting down\n", name)
}

🔎 See the godoc examples for more complete use cases.

🔁 Alternatives

Projects with similar goals:

  • ash2k/stager
  • skovtunenko/graterm
  • icholy/killable
  • tomb

🪪 License

This project is licensed under the MIT License. See LICENSE for details.

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:

  1. context cancellation is propagated immediately to all child phases
  2. the phase owner waits for all children to complete
  3. 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

func Next added in v0.0.3

func Next(ctx context.Context) (phaser *phaseCtx, err error)

Next creates a new phase derived from the provided context. It returns a new Phaser, which implements context.Context.

Calling Next is the starting point for phase coordination.

Types

type Phaser

type Phaser interface {
	context.Context
	ChildrenDone() <-chan struct{}
	Close()
}

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!")
}
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!")
}
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!")
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL