phase

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: May 4, 2025 License: MIT Imports: 2 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:

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

🔧 Example

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/aelse/phase"
)

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

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

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

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

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

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

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

🔎 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`. 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:

  1. a call to `phase.Cancel(ctx)`
  2. cancellation of the parent context

Upon termination, the following occurs:

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

## A note on phase ownership

A function may begin a phase to cover the scope of its own activities, or to hand off to another function. In the simple case where a function begins a phase for itself (ensuring function fully terminates before parent phases end) it is clear that the programmer must Close the phase before returning.

When orchestrating the start of an application you may wish to create a number of phases and pass the relevant context to your application components (dependency injection) with the expectation the components will Close their phase before returning. If these phases are passed to those functions as a context.Context the requirement may be overlooked and so it is preferable to make the first argument to those functions a phase.Phaser to indicate the requirement and avoid confusion.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Cancel added in v0.0.3

func Cancel(ctx context.Context)

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.

func Close added in v0.0.3

func Close(ctx context.Context)

Close marks the phase as complete and removes it from its parent. This should be called after all child phases have completed, typically after a call to Wait.

Close will panic if the context does not contain a Phaser.

func Next added in v0.0.3

func Next(parent context.Context) (phaser *phaseCtx)

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.

func Wait added in v0.0.3

func Wait(ctx context.Context)

Wait blocks until all child phases of the identified phase have completed. It must be called before Close to ensure all nested work is finished.

Wait will panic if the context does not contain a Phaser.

Types

type Phaser

type Phaser interface {
	context.Context
	// contains filtered or unexported methods
}

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!")
}
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 phase.Close(phaser)

	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 phase.Close(p)

		// 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
		phase.Wait(p)
		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")
	phase.Wait(phaser)
	fmt.Println("Top level phaser ended. Bye!")
}
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 (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 phase.Close(phaser)
		fmt.Printf("%s started\n", name)
		<-phaser.Done()
		// There might be child phases, so call Wait
		phase.Wait(phaser)
		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 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.
	phase.Cancel(p0)
	// Wait until everything has finished.
	phase.Wait(p0)
	fmt.Println("Bye!")
}

Jump to

Keyboard shortcuts

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