runnable

package module
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2020 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")
	}
}

Example of an HTTP server with other in-process services:

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 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

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 {
	// Warnf logs with a warning level.
	Warnf(format string, args ...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