runtime

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Mar 10, 2026 License: AGPL-3.0 Imports: 11 Imported by: 0

README

Runtime Library

The runtime library provides context-based goroutine management and signal handling for Go programs. It is designed to facilitate graceful shutdowns and handle specific signals like SIGPIPE when running as a systemd service.

Features

  • Context-based Goroutine Management: Manage goroutines with a base context that can be canceled, ensuring all goroutines are properly cleaned up.
  • Signal Handling: Handle SIGPIPE signals to prevent program crashes when running as a systemd service.
  • Graceful Shutdown: Provides mechanisms to gracefully stop and cancel running goroutines.

Installation

To install the runtime library, add it to your go.mod file:

go get github.com/yourusername/runtime

Usage

Example of using the runtime for gracefully shutting down goroutines with a default Environment

package main

import (
	"context"
	"github.com/imunhatep/runtime"
	"log"
)

func main() {
	// If a goroutine started by Go returns non-nil error,
	// the framework calls env.Cancel(err) to signal other
	// goroutines to stop soon.
	runtime.Go(func(ctx context.Context) error {
        // Simulate work
        <-ctx.Done()
        log.Println("Goroutine stopped")
        return nil
	})

	// Stop declares no more Go is called.
	// This is optional if env.Cancel will be called
	// at some point (or by a signal).
	runtime.Stop()

	// Wait returns when all goroutines return.
	runtime.Wait()
}
Creating an Environment

Create a new Environment to manage goroutines:

package main

import (
    "context"
    "github.com/yourusername/runtime"
)

func main() {
    env := runtime.NewEnvironment(context.Background())
    // Use the environment to manage goroutines
}
Starting Goroutines

Use the Go method to start a goroutine within the environment:

env.Go(func(ctx context.Context) error {
    // Your goroutine logic here
    <-ctx.Done() // Watch for cancellation
    return nil
})
Graceful Shutdown

To gracefully stop all goroutines, call the Stop or Cancel methods:

// Stop the environment (no new goroutines will be started)
env.Stop()

// Cancel the environment with an error
env.Cancel(nil)

// Wait for all goroutines to finish
err := env.Wait()
if err != nil {
    // Handle the error
}
Example with environment

Here is a complete example demonstrating the usage of the runtime library:

package main

import (
    "context"
    "github.com/imunhatep/runtime"
    "log"
)

func main() {
    env := runtime.NewEnvironment(context.Background())

    env.Go(func(ctx context.Context) error {
        // Simulate work
        <-ctx.Done()
        log.Println("Goroutine stopped")
        return nil
    })

    // Simulate a signal to stop the environment
    env.Stop()

    // Wait for all goroutines to finish
    if err := env.Wait(); err != nil {
        log.Fatalf("Error: %v", err)
    }

    log.Println("All goroutines have finished")
}

Documentation

Index

Constants

View Source
const (
	// RequestIDContextKey is a context key for request ID.
	RequestIDContextKey contextKey = "request_id"
)

Variables

This section is empty.

Functions

func BackgroundWithID

func BackgroundWithID(ctx context.Context) context.Context

BackgroundWithID returns a new background context with an existing request ID in ctx, if any.

func Cancel

func Cancel(err error) bool

Cancel cancels the base context of the global environment.

Passed err will be returned by Wait(). Once canceled, Go() will not start new goroutines.

Note that calling Cancel(nil) is perfectly valid. Unlike Stop(), Cancel(nil) cancels the base context and can gracefully stop goroutines started by Server.Serve or HTTPServer.ListenAndServe.

This returns true if the caller is the first that calls Cancel. For second and later calls, Cancel does nothing and returns false.

func Go

func Go(f func(ctx context.Context) error)

Go starts a goroutine that executes f in the global environment.

f takes a drived context from the base context. The context will be canceled when f returns.

Goroutines started by this function will be waited for by Wait until all such goroutines return.

If f returns non-nil error, Cancel is called immediately with that error.

f should watch ctx.Done() channel and return quickly when the channel is closed.

func IsSignaled

func IsSignaled(err error) bool

IsSignaled returns true if err returned by Wait indicates that the program has received SIGINT or SIGTERM.

func Logger added in v0.1.2

func Logger(logger zerolog.Logger)

Logger sets zerolog Logger instance to default Environment

func Stop

func Stop()

Stop just declares no further Go will be called.

Calling Stop is optional if and only if Cancel is guaranteed to be called at some point. For instance, if the program runs until SIGINT or SIGTERM, Stop is optional.

func Wait

func Wait() error

Wait waits for Stop or Cancel, and for all goroutines started by Go to finish.

The returned err is the one passed to Cancel, or nil. err can be tested by IsSignaled to determine whether the program got SIGINT or SIGTERM.

func WithRequestID

func WithRequestID(ctx context.Context, reqid string) context.Context

WithRequestID returns a new context with a request ID as a value.

Types

type Environment

type Environment struct {
	// contains filtered or unexported fields
}

Environment implements context-based goroutine management.

func NewEnvironment

func NewEnvironment(ctx context.Context, options ...EnvironmentOption) *Environment

NewEnvironment creates a new Environment.

This does *not* install signal handlers for SIGINT/SIGTERM for new environments. Only the global environment will be canceled on these signals.

func (*Environment) Cancel

func (e *Environment) Cancel(err error) bool

Cancel cancels the base context.

Passed err will be returned by Wait(). Once canceled, Go() will not start new goroutines.

Note that calling Cancel(nil) is perfectly valid. Unlike Stop(), Cancel(nil) cancels the base context and can gracefully stop goroutines started by Server.Serve or HTTPServer.ListenAndServe.

This returns true if the caller is the first that calls Cancel. For second and later calls, Cancel does nothing and returns false.

func (*Environment) Go

func (e *Environment) Go(f func(ctx context.Context) error)

Go starts a goroutine that executes f.

f takes a drived context from the base context. The context will be canceled when f returns.

Goroutines started by this function will be waited for by Wait until all such goroutines return.

If f returns non-nil error, Cancel is called immediately with that error.

f should watch ctx.Done() channel and return quickly when the channel is closed.

func (*Environment) GoWithID

func (e *Environment) GoWithID(f func(ctx context.Context) error)

GoWithID calls Go with a context having a new request tracking ID.

func (*Environment) Stop

func (e *Environment) Stop()

Stop just declares no further Go will be called.

Calling Stop is optional if and only if Cancel is guaranteed to be called at some point. For instance, if the program runs until SIGINT or SIGTERM, Stop is optional.

func (*Environment) Wait

func (e *Environment) Wait() error

Wait waits for Stop or Cancel, and for all goroutines started by Go to finish.

The returned err is the one passed to Cancel, or nil. err can be tested by IsSignaled to determine whether the program got SIGINT or SIGTERM.

type EnvironmentOption added in v0.1.2

type EnvironmentOption func(*Environment)

EnvironmentOption configures Environment behavior.

func WithLogger added in v0.1.2

func WithLogger(logger zerolog.Logger) EnvironmentOption

WithLogger sets a custom logger for the Environment. If not provided, the global zerolog logger will be used.

Jump to

Keyboard shortcuts

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