runnable

package module
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2022 License: MIT Imports: 11 Imported by: 16

README

Runnable

GoDoc Go Report Card

Tooling to manage the execution of a process based on a Runnable interface:

type Runnable interface {
	Run(context.Context) error
}

And a simpler RunnableFunc interface:

type RunnableFunc func(context.Context) error

Example of an implementation of the command "yes":

func main() {
	runnable.RunFunc(run)
}

func run(ctx context.Context) error {
	for {
		if ctx.Err() != nil {
			return ctx.Err()
		}
		fmt.Println("y")
	}
}

HTTP Server

package main

import (
	"net/http"

	"github.com/pior/runnable"
)

func main() {
	server := &http.Server{
		Addr:    "127.0.0.1:8000",
		Handler: http.RedirectHandler("https://go.dev", http.StatusPermanentRedirect),
	}

	runnable.Run(runnable.HTTPServer(server))
}

Manager: run multiple runnables with dependencies

The Manager starts and stops all runnables while respecting dependencies between them. Components with dependencies will be stopped before their dependencies.

package main

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"github.com/pior/runnable"
)

func main() {
	jobs := NewStupidJobQueue()

	server := &http.Server{
		Addr: "localhost:8000",
		Handler: http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
			jobs.Perform(r.URL.Path)
			fmt.Fprintln(rw, "Job enqueued!")
		}),
	}
	serverRunner := runnable.HTTPServer(server)

	monitor := runnable.Func(func(ctx context.Context) error {
		fmt.Printf("Task executed: %d\n", jobs.Executed())
		return nil
	})
	monitor = runnable.Periodic(runnable.PeriodicOptions{
		Period: 3 * time.Second,
	}, monitor)

	g := runnable.Manager(nil)
	g.Add(jobs)
	g.Add(serverRunner, jobs) // jobs is a dependency
	g.Add(monitor)

	runnable.Run(g.Build())
}
package main

import (
	"context"
	"fmt"
	"sync/atomic"
)

type StupidJobQueue struct {
	queue    chan string
	executed int64
}

func NewStupidJobQueue() *StupidJobQueue {
	return &StupidJobQueue{queue: make(chan string)}
}

func (s *StupidJobQueue) Perform(url string) {
	s.queue <- url
}

func (s *StupidJobQueue) Executed() int64 {
	return atomic.LoadInt64(&s.executed)
}

func (s *StupidJobQueue) Run(ctx context.Context) error {
	for {
		select {
		case <-ctx.Done():
			return ctx.Err()
		case url := <-s.queue:
			fmt.Printf("Job from %s\n", url)
			atomic.AddInt64(&s.executed, 1)
		}
	}
}

Output:

$ go run ./cmd/example
[RUNNABLE] 2020/10/22 22:42:26 INFO manager: main.StupidJobQueue started
[RUNNABLE] 2020/10/22 22:42:26 INFO manager: runnable.httpServer started
[RUNNABLE] 2020/10/22 22:42:26 INFO manager: periodic(func(runnable.RunnableFunc)) started
Task executed: 0
Job from /
Job from /favicon.ico
Task executed: 2
^C[RUNNABLE] 2020/10/22 22:42:34 INFO signal: received signal interrupt
[RUNNABLE] 2020/10/22 22:42:34 INFO manager: starting shutdown (context cancelled)
[RUNNABLE] 2020/10/22 22:42:34 INFO manager: runnable.httpServer cancelled
[RUNNABLE] 2020/10/22 22:42:34 INFO manager: periodic(func(runnable.RunnableFunc)) cancelled
[RUNNABLE] 2020/10/22 22:42:34 INFO manager: periodic(func(runnable.RunnableFunc)) stopped
[RUNNABLE] 2020/10/22 22:42:34 INFO manager: runnable.httpServer stopped
[RUNNABLE] 2020/10/22 22:42:34 INFO manager: main.StupidJobQueue cancelled
[RUNNABLE] 2020/10/22 22:42:34 INFO manager: main.StupidJobQueue stopped
[RUNNABLE] 2020/10/22 22:42:34 INFO manager: shutdown complete

License

The MIT License (MIT)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ContextValues added in v0.10.0

func ContextValues(parent context.Context) context.Context

ContextValues returns a new context.Context with the values from the parent, without propagating the cancellation. Useful when you want to protect an operation that should not be cancelled. Often used with context.WithTimeout() or context.WithDeadline().

func Manager added in v0.4.0

func Manager(options *ManagerOptions) *managerBuilder

Manager returns a runnable that execute runnables in go routines. Runnables can declare a dependency on another runnable. Dependencies are started first and stopped last.

func Periodic added in v0.1.0

func Periodic(opts PeriodicOptions, runnable Runnable) *periodic

Periodic returns a runnable that will periodically run the runnable passed in argument.

func Run added in v0.4.0

func Run(runner Runnable)

Run runs a single runnable, and listen to SIGTERM/SIGINT

func RunFunc added in v0.5.0

func RunFunc(fn RunnableFunc)

RunFunc runs a runnable function, and listen to SIGTERM/SIGINT

func RunGroup added in v0.1.0

func RunGroup(runners ...Runnable)

RunGroup runs all runnables in a Group, and listen to SIGTERM/SIGINT

func SetLogger added in v0.9.0

func SetLogger(l Logger)

SetLogger replaces the default logger.

Types

type CloserOptions added in v0.4.0

type CloserOptions struct {
	Delay time.Duration
}

CloserOptions configures the behavior of a Closer runnable.

type Logger

type Logger interface {
	// Infof logs with an info level.
	Infof(format string, args ...interface{})

	// Debugf logs with a debug level.
	Debugf(format string, args ...interface{})
}

type ManagerOptions added in v0.4.0

type ManagerOptions struct {
	ShutdownTimeout time.Duration
}

ManagerOptions configures the behavior of a Manager.

type PanicError

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

func (*PanicError) Error

func (e *PanicError) Error() string

func (*PanicError) Unwrap

func (e *PanicError) Unwrap() error

type PeriodicOptions added in v0.1.0

type PeriodicOptions struct {
	Period time.Duration
}

PeriodicOptions configures the behavior of a Periodic runnable.

type RecoverRunner

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

func (*RecoverRunner) Run

func (r *RecoverRunner) Run(ctx context.Context) (err error)

type RestartOption added in v0.6.0

type RestartOption func(*restartConfig)

func RestartCrashDelayFn added in v0.6.0

func RestartCrashDelayFn(fn func(int) time.Duration) RestartOption

RestartCrashDelayFn sets the function that determine the backoff delay after a crash.

func RestartCrashLimit added in v0.6.0

func RestartCrashLimit(times int) RestartOption

RestartCrashLimit sets a limit on the number restart after a crash.

func RestartDelay added in v0.6.0

func RestartDelay(times time.Duration) RestartOption

RestartDelay sets the time waited before restarting the runnable after a successful execution.

func RestartLimit added in v0.6.0

func RestartLimit(times int) RestartOption

RestartLimit sets a limit on the number of restart after successful execution.

type Runnable

type Runnable interface {
	Run(context.Context) error
}

Runnable is the contract for anything that runs with a Go context, respects the concellation contract, and expects the caller to handle errors.

func Closer added in v0.4.0

func Closer(object io.Closer, opts *CloserOptions) Runnable

Closer returns a runnable that will close what is passed in argument.

func Func added in v0.5.0

func Func(fn RunnableFunc) Runnable

func HTTPServer added in v0.3.0

func HTTPServer(server ServerWithShutdown) Runnable

HTTPServer returns a runnable that runs a ServerWithShutdown (like *http.Server).

func Recover

func Recover(runnable Runnable) Runnable

Recover returns a runnable that recovers when a runnable panics and return an error to represent this panic.

func Restart

func Restart(runnable Runnable, opts ...RestartOption) Runnable

Restart returns a runnable that runs a runnable and restarts it when it fails, with some conditions.

func Signal

func Signal(runnable Runnable, signals ...os.Signal) Runnable

Signal returns a runnable that runs the runnable and cancels it when the process receives a POSIX signal.

type RunnableError added in v0.4.0

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

func (*RunnableError) Error added in v0.4.0

func (e *RunnableError) Error() string

func (*RunnableError) Unwrap added in v0.4.0

func (e *RunnableError) Unwrap() error

type RunnableFunc added in v0.5.0

type RunnableFunc func(context.Context) error

type ServerWithShutdown added in v0.3.0

type ServerWithShutdown interface {
	ListenAndServe() error
	Shutdown(ctx context.Context) error
}

Directories

Path Synopsis
cmd
crashing command
example command
http command
test command
yes command
examples
loggers module

Jump to

Keyboard shortcuts

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