work

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 22 Imported by: 1 module, 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.

Documentation

Overview

Package work is the unit of work of contract.md section 4: one wide event per CLI command run (command.run) and per handled request (request.handled, from the HTTP middleware or from Request for a socket or RPC server), a span that continues the caller's trace, attributes gathered while the unit runs, TRACEPARENT for child processes and job.progress for long jobs. It works without lifecycle.Run and without tracing.Setup; with tracing off the span is a no-op and the line carries no trace ids of its own.

ctx, end := work.Command(ctx, log, "index rebuild", flags)
work.Add(ctx, "index.size", n)
end(err)

srv := &http.Server{Handler: work.HTTP(log)(mux)}

ctx, end := work.Request(ctx, log, req.Op, work.Traceparent(req.Traceparent), work.Caller(req.CallerID))
data, err := handle(ctx, req)
end(err)

Outgoing calls pass the trace on without a wrapper of this library: an HTTP client uses go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp,

client := &http.Client{Transport: otelhttp.NewTransport(http.DefaultTransport)}

and a child process gets Env(ctx) appended to its environment.

Index

Constants

View Source
const (
	OutcomeOK        = "ok"
	OutcomeError     = "error"
	OutcomeCancelled = "cancelled"
)

Outcome values of command.run and request.handled.

View Source
const (
	EnvTraceparent = "TRACEPARENT"
	EnvTracestate  = "TRACESTATE"
)

Trace context travels between processes in these variables (W3C traceparent and tracestate, upper case as environment names).

View Source
const CallerIDHeader = "Caller-Id"

CallerIDHeader is the request header whose value becomes caller.id on every line of the request and on request.handled.

View Source
const ProgressInterval = 10 * time.Second

ProgressInterval is the longest silence between two job.progress lines while Done is called.

Variables

This section is empty.

Functions

func Add

func Add(ctx context.Context, key string, value any)

Add puts one attribute on the current unit of work: every later line written with ctx and the final event carry it. Outside a unit it does nothing.

func AddAll

func AddAll(ctx context.Context, attrs ...slog.Attr)

AddAll puts attrs on the current unit of work. See Add.

func Command

func Command(ctx context.Context, log *slog.Logger, name string, flags []string) (context.Context, func(err error))

Command opens the unit of work of one CLI command run. name is the subcommand path ("index rebuild"); flags are the flag names given, logged as args.flags. The span continues the trace of a parent span in ctx, else of TRACEPARENT in the environment, else it is a root. The returned context carries the span, command and args.flags, and the attribute set Add writes to. end writes command.run and ends the span; a second call does nothing. A nil log uses the logger in ctx (logging.FromContext).

func Env

func Env(ctx context.Context) []string

Env returns TRACEPARENT= (and TRACESTATE= when set) for a child process:

cmd.Env = append(os.Environ(), work.Env(ctx)...)

It returns nil when ctx has no valid span.

func HTTP

func HTTP(log *slog.Logger) func(http.Handler) http.Handler

HTTP returns the request middleware: it continues the trace of the traceparent header, opens a server span, puts caller.id from the Caller-Id header on the request's attribute set, recovers a panic into a 500, and writes request.handled with http.request.method, http.route, http.response.status_code, duration_ms and outcome. outcome is error for a status of 500 or more or a panic (ERROR), cancelled when the client went away before the handler finished or the handler panicked with http.ErrAbortHandler (WARN), ok otherwise (INFO). A nil log uses the logger in the request context.

http.route is the matched pattern: r.Pattern after the handler ran (net/http ServeMux sets it on the request the middleware passed), else what the handler side reported with SetRoute. A router that clones the request before matching (chi) hides its r.Pattern from a middleware outside it; inside such a router, or from a handler, call SetRoute.

A panic is written as request.handled with exception.* and ends the span. When the response had not started, the client gets a 500. When it had, the connection is aborted after the line is written (the middleware panics with http.ErrAbortHandler), so the client sees a cut response, not a complete one. http.ErrAbortHandler itself is passed on the same way after its line.

func Request

func Request(ctx context.Context, log *slog.Logger, method string, opts ...RequestOption) (context.Context, func(err error))

Request opens the unit of work of one request a non-HTTP server handles (a socket or RPC request). method is the operation's name ("get-plot"): it names the span and is rpc.method on every line of the request. The span continues the trace of Traceparent; without one, or with one that does not parse, it is a root, whatever span ctx carries. The returned context carries the span, rpc.method, caller.id from Caller, and the attribute set Add writes to. end writes request.handled with rpc.method, duration_ms, outcome (ok, error, cancelled, by the error's class as Command classes it: INFO, ERROR, WARN), error.type when err is not nil and exception.* on outcome error, and ends the span; a second call does nothing. A nil log uses the logger in ctx.

The outcome is the app's reading of the request: a refusal the app answers with its own code is end(nil) with the code added through Add. Request recovers no panic; the reply to the client on a panic is the app's.

func SetRoute

func SetRoute(ctx context.Context, pattern string)

SetRoute reports the matched route pattern of the request whose context is ctx, for routers that do not set r.Pattern on the request the middleware sees. Report in a defer, so a panicking handler still gets its route on the line. From a chi router:

r.Use(func(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer func() { work.SetRoute(r.Context(), chi.RouteContext(r.Context()).RoutePattern()) }()
		next.ServeHTTP(w, r)
	})
})

Outside a request handled by HTTP it does nothing.

Types

type PanicError

type PanicError struct {
	Value any
	Stack string
}

PanicError is the error a recovered panic becomes: exception.type work.PanicError, exception.message "panic: <value>", exception.stacktrace the goroutine's stack at recovery.

func NewPanicError

func NewPanicError(value any) *PanicError

NewPanicError wraps a recovered panic value with the current stack.

func (*PanicError) Error

func (e *PanicError) Error() string

func (*PanicError) StackTrace

func (e *PanicError) StackTrace() string

StackTrace gives the handler exception.stacktrace.

func (*PanicError) Unwrap

func (e *PanicError) Unwrap() error

Unwrap exposes a panic value that is itself an error.

type Progress

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

Progress writes job.progress for one job run: every N items (N is total/20, at least 1), when ProgressInterval has passed since the last line, and when the count reaches total. With a total of 0 (unknown) only the interval rule applies and job.items_total is omitted.

func NewProgress

func NewProgress(ctx context.Context, log *slog.Logger, jobName string, total int) *Progress

NewProgress starts a job run named jobName with total items (0 when unknown). job.id is a ULID for this run. A nil log uses the logger in ctx.

func (*Progress) Done

func (p *Progress) Done(n int)

Done adds n finished items and writes job.progress when a rule says so. Safe for concurrent use.

func (*Progress) ID

func (p *Progress) ID() string

ID returns the job.id of this run, for the app's own lines.

type RequestOption

type RequestOption func(*requestOptions)

RequestOption configures Request.

func Caller

func Caller(id string) RequestOption

Caller puts caller.id on every line of the request and on request.handled. Empty adds nothing.

func Traceparent

func Traceparent(s string) RequestOption

Traceparent continues the trace of the W3C traceparent string the request carried. Empty or malformed, the request starts a root span and the value is dropped.

Jump to

Keyboard shortcuts

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