Documentation
¶
Overview ¶
Package funtask provides a Go library for building HTTP task workers.
A server hosts one or more named tasks that an orchestrator can trigger via HTTP. Task authors write functions that receive execution context and parameters, and return structured results.
Index ¶
- type ErrorCoder
- type Option
- func WithAuthToken(token string) Option
- func WithCallbackAllowlist(origins ...string) Option
- func WithCallbackRetries(n int) Option
- func WithCallbackTimeout(d time.Duration) Option
- func WithDashboard() Option
- func WithDeadLetterDir(path string) Option
- func WithHandler(pattern string, handler http.Handler) Option
- func WithMaxDuration(d time.Duration) Option
- func WithReadiness(fn func() error) Option
- func WithResultHistory(n int) Option
- func WithShutdownTimeout(d time.Duration) Option
- func WithSyncTimeout(d time.Duration) Option
- type ParamReader
- type Params
- func (p Params) Bool(key string) (bool, error)
- func (p Params) Float(key string) (float64, error)
- func (p Params) Int(key string) (int, error)
- func (p Params) Raw() map[string]any
- func (p Params) Reader() *ParamReader
- func (p Params) String(key string) (string, error)
- func (p Params) Time(key string) (time.Time, error)
- type Result
- type Run
- type Server
- type TaskDef
- type TaskFunc
- type UserMessager
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ErrorCoder ¶ added in v0.2.0
type ErrorCoder interface {
ErrorCode() string
}
ErrorCoder is implemented by errors that carry a machine-readable code. FailFromError uses this to extract the error code automatically.
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option configures a Server. Pass options to New.
func WithAuthToken ¶
WithAuthToken sets the bearer token for all endpoints.
func WithCallbackAllowlist ¶
WithCallbackAllowlist sets allowed callback URL origins.
func WithCallbackRetries ¶
WithCallbackRetries sets the number of callback delivery attempts. Default: 5.
func WithCallbackTimeout ¶
WithCallbackTimeout sets the per-attempt callback HTTP timeout. Default: 30s.
func WithDashboard ¶ added in v1.0.0
func WithDashboard() Option
WithDashboard enables the built-in developer dashboard at /dashboard. The dashboard shows task status, progress, errors, and allows triggering tasks. It uses Server-Sent Events via /events for live updates and handles authentication client-side by prompting for the bearer token. The /dashboard path becomes reserved when enabled and cannot be used by WithHandler.
func WithDeadLetterDir ¶
WithDeadLetterDir sets the dead letter directory path. Required.
func WithHandler ¶
WithHandler registers a custom HTTP handler on the server's mux. The pattern follows net/http.ServeMux syntax (e.g. "GET /api/orders"). Custom handlers are not protected by the server's bearer-token auth; apply your own middleware as needed. Patterns must not conflict with built-in routes (/run, /stop, /result, /health, /livez, /readyz).
func WithMaxDuration ¶
WithMaxDuration sets the maximum job duration. Default: no limit.
func WithReadiness ¶
WithReadiness sets a custom readiness check for /readyz.
func WithResultHistory ¶ added in v1.0.0
WithResultHistory sets the server-wide default for how many recent results to keep per task. Default: 10. Individual tasks can override this with TaskDef.KeepResults.
func WithShutdownTimeout ¶
WithShutdownTimeout sets the graceful shutdown timeout. Default: 30s.
func WithSyncTimeout ¶
WithSyncTimeout sets the sync-mode timeout. Default: 2m.
type ParamReader ¶
type ParamReader struct {
// contains filtered or unexported fields
}
ParamReader reads parameters and collects errors. After the first error, subsequent reads still execute and collect additional errors (returning zero values). This way Err reports all invalid parameters at once, not just the first one.
func (*ParamReader) Bool ¶
func (r *ParamReader) Bool(key string) bool
Bool returns the boolean parameter for the given key. If the key is missing or the value is not a bool, the error is collected and false is returned.
func (*ParamReader) Err ¶
func (r *ParamReader) Err() error
Err returns a combined error for all failed parameter reads, or nil if all reads succeeded. The error message lists all invalid parameters, e.g. "missing or invalid parameters: since (expected time), limit (expected int)".
func (*ParamReader) Float ¶
func (r *ParamReader) Float(key string) float64
Float returns the float64 parameter for the given key. If the key is missing or the value is not a number, the error is collected and zero is returned.
func (*ParamReader) Int ¶
func (r *ParamReader) Int(key string) int
Int returns the integer parameter for the given key. If the key is missing or the value is not an integer, the error is collected and zero is returned.
func (*ParamReader) String ¶
func (r *ParamReader) String(key string) string
String returns the string parameter for the given key. If the key is missing or the value is not a string, the error is collected and an empty string is returned.
type Params ¶
type Params struct {
// contains filtered or unexported fields
}
Params holds the input parameters from the orchestrator. Since params arrive as JSON, all numbers are float64 internally. The typed accessors handle conversion — e.g. Int("limit") accepts float64(500) from JSON and returns int(500). Non-integer floats like 3.7 are rejected by Int().
func TestParams ¶
TestParams creates a Params value from a map literal. Fails the test immediately if the map contains types that Params cannot represent (e.g., channels, functions).
func TestParamsRaw ¶
TestParamsRaw creates a Params value without validation. Use this to test parameter validation paths with bad inputs (e.g., wrong types, missing keys).
func (Params) Bool ¶
Bool returns the boolean parameter for the given key. It returns an error if the key is missing or the value is not a bool.
func (Params) Float ¶
Float returns the float64 parameter for the given key. It returns an error if the key is missing or the value is not a number.
func (Params) Int ¶
Int returns the integer parameter for the given key. JSON numbers arrive as float64, so this method accepts whole-number floats and converts them. Non-integer floats like 3.7 are rejected.
func (Params) Raw ¶
Raw returns the underlying parameter map. This is useful for custom parameter handling that goes beyond the typed accessors.
func (Params) Reader ¶
func (p Params) Reader() *ParamReader
Reader returns a ParamReader that collects errors from multiple parameter reads, avoiding repetitive if-err-nil blocks.
type Result ¶
type Result struct {
Success bool
Message string
ErrorCode string
Data map[string]any
LastStep string
// contains filtered or unexported fields
}
Result represents the outcome of a task execution. It carries a success flag, a human-readable message, an optional machine-readable error code, optional key-value data, and the last reported step for diagnostic context.
func Fail ¶
Fail creates a failure result with a machine-readable error code and a formatted human-readable message.
func FailFromError ¶ added in v0.2.0
FailFromError creates a failure result from a Go error. If the error implements ErrorCoder, its ErrorCode() is used; otherwise fallbackCode applies. If the error implements UserMessager, its UserMessage() becomes the result message; otherwise err.Error() is used. The original error is stored as the cause for server-side logging but never serialized.
func (Result) WithCause ¶ added in v0.2.0
WithCause returns a copy of the result with the given error attached as the underlying cause. The cause is logged server-side but never included in callback payloads or JSON serialization.
func (Result) WithData ¶
WithData returns a copy of the result with the given key-value pair added to its data map. Multiple calls can be chained. The original result is never modified.
Note: after JSON round-trip (e.g. callback payloads), numeric values become float64 per encoding/json conventions.
type Run ¶
Run is the execution context for a single job. It embeds context.Context so it works anywhere a context.Context is expected — pass it directly to database drivers, HTTP clients, etc.
func TestRun ¶
TestRun returns a *Run backed by the test's context. Cancelled when the test's deadline expires (if set via -timeout). Steps are recorded and logged via t.Log for debugging. Call TestRun(...).Steps() to retrieve the recorded steps for assertions.
func TestRunWithContext ¶
TestRunWithContext returns a *Run backed by a custom context. Use this to test cancellation handling.
func (*Run) Progress ¶
Progress reports structured progress for countable iterations. It updates the step description and records current/total/percent, all visible via GET /health. Use this instead of Step when iterating over a countable set of items.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server hosts one or more named tasks that an orchestrator can trigger via HTTP. Configure it with New and start it with ListenAndServe.
func (*Server) ListenAndServe ¶
ListenAndServe validates configuration, starts the HTTP server, and blocks until SIGTERM is received or the server fails. On SIGTERM the server enters draining state, cancels in-flight jobs, and shuts down the HTTP server gracefully.
type TaskDef ¶ added in v1.0.0
type TaskDef struct {
// contains filtered or unexported fields
}
TaskDef configures a named task. Create with Task, pass to New.
func (*TaskDef) Description ¶ added in v1.0.0
Description sets a human-readable description for the task.
func (*TaskDef) Example ¶ added in v1.0.0
Example sets example parameters for the task. The dashboard uses this to pre-fill the Params textarea and show a Params button. The map is copied immediately; later mutations to the original are safe.
func (*TaskDef) KeepResults ¶ added in v1.0.0
KeepResults sets the number of recent results to retain for this task. Overrides the server-wide default set by WithResultHistory.
type TaskFunc ¶
TaskFunc is the function signature for task implementations. The function receives a Run context for cancellation and progress reporting, and Params for typed parameter access. It must respect ctx cancellation — when ctx is cancelled (via /stop or shutdown), the function should return promptly.
type UserMessager ¶ added in v0.2.0
type UserMessager interface {
UserMessage() string
}
UserMessager is implemented by errors that carry a user-facing message separate from the technical error string. FailFromError uses this to extract a safe message for the result.
