client

package
v0.0.0-...-2fa33bc Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 23 Imported by: ? modules, 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 client is the Go client of the TaskFlow API.

Use New to create a client for tasks, steps, workspaces, approval callbacks, system status, terminal administration, and resumable uploads. Use Client.DialStream for subscriptions and calls over the shared WebSocket, or Client.OpenShell for an interactive terminal session.

Index

Constants

This section is empty.

Variables

View Source
var ErrStreamClosed = errors.New("client: stream closed")

ErrStreamClosed is reported by calls and subscriptions once the Stream is closed, or when it lost the connection and reconnecting is disabled.

Functions

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err is a server answer meaning "no such thing".

Types

type APIError

type APIError struct {
	// Status is the HTTP status; zero for errors that arrived over the stream.
	Status int
	// Code is the TaskFlow code from the envelope; zero if none was sent.
	Code    api.Code
	Message string
}

APIError is returned when the server reports a failure: either a non-2xx HTTP answer or a response envelope / stream frame with a failing code.

func (*APIError) Error

func (e *APIError) Error() string

type Action

type Action string

Action is a control action for a task or a step.

const (
	ActionKill   Action = "kill"
	ActionPause  Action = "pause"
	ActionResume Action = "resume"
)

type Client

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

Client talks to one TaskFlow server. It is safe for concurrent use.

func New

func New(baseURL string, opts ...Option) (*Client, error)

New returns a client for the server at baseURL, e.g. "http://host:2376". A path prefix is kept, so a server mounted behind a reverse proxy works too.

func (*Client) ApprovalCallback

func (c *Client) ApprovalCallback(ctx context.Context, decision iproto.ApprovalDecision) error

ApprovalCallback reports the decision of an external approval platform, as the platform itself would POST it to the callback URL.

func (*Client) CreateTask

func (c *Client) CreateTask(ctx context.Context, task *iproto.STaskReq) (*iproto.STaskCreateRes, error)

CreateTask submits a task definition.

func (*Client) CreateTaskYAML

func (c *Client) CreateTaskYAML(ctx context.Context, definition []byte) (*iproto.STaskCreateRes, error)

CreateTaskYAML submits a task definition written as YAML.

func (*Client) CreateUpload

func (c *Client) CreateUpload(ctx context.Context, opts UploadOptions) (*Upload, error)

CreateUpload registers a new upload on the server without sending data.

func (*Client) DeleteTask

func (c *Client) DeleteTask(ctx context.Context, task string) error

DeleteTask removes a task and its records.

func (*Client) DeleteWorkspace

func (c *Client) DeleteWorkspace(ctx context.Context, task string, paths ...string) error

DeleteWorkspace removes files or directories (recursively) from the task workspace. The server validates all paths first and reports the paths that could not be removed in the error.

func (*Client) DialStream

func (c *Client) DialStream(ctx context.Context, opts ...StreamOption) (*Stream, error)

DialStream connects the multiplexed stream. The first connection attempt is synchronous, so a wrong address or credentials fail here.

func (*Client) DisconnectSession

func (c *Client) DisconnectSession(ctx context.Context, id string) error

DisconnectSession forcibly closes a live WebShell session.

func (*Client) DownloadWorkspaceFile

func (c *Client) DownloadWorkspaceFile(ctx context.Context, task, path string) (*Download, error)

DownloadWorkspaceFile streams a file of the task workspace. It has no request timeout other than the context.

func (*Client) DumpTask

func (c *Client) DumpTask(ctx context.Context, task string) (string, error)

DumpTask exports the task definition as YAML that CreateTaskYAML accepts.

func (*Client) GetStep

func (c *Client) GetStep(ctx context.Context, task, step string) (*Result[*iproto.SStepRes], error)

GetStep returns one step. The result code is the run state of the step.

func (*Client) GetTask

func (c *Client) GetTask(ctx context.Context, task string) (*Result[*iproto.STaskRes], error)

GetTask returns a task. The result code is the run state of the task.

func (*Client) Healthz

func (c *Client) Healthz(ctx context.Context) (*iproto.SHealthyz, error)

Healthz returns the server health report.

func (*Client) Heartbeat

func (c *Client) Heartbeat(ctx context.Context) error

Heartbeat succeeds when the server answers its liveness probe.

func (*Client) ListReplays

func (c *Client) ListReplays(ctx context.Context, limit, offset int) (*iproto.ReplayList, error)

ListReplays lists the recorded sessions, newest first. limit is 1..100 (0 = server default 50).

func (*Client) ListSessions

func (c *Client) ListSessions(ctx context.Context) ([]iproto.WebShellSession, error)

ListSessions returns the live WebShell sessions.

func (*Client) ListSteps

func (c *Client) ListSteps(ctx context.Context, task string) (*Result[iproto.SStepsRes], error)

ListSteps returns the steps of a task. The result code is the task state.

func (*Client) ListTasks

ListTasks returns one page of tasks.

func (*Client) ListWorkspace

func (c *Client) ListWorkspace(ctx context.Context, task, path string) (*iproto.SFileListRes, error)

ListWorkspace lists a directory of the task workspace; an empty path is the workspace root.

func (*Client) ManageStep

func (c *Client) ManageStep(ctx context.Context, task, step string, action Action, pauseFor time.Duration) error

ManageStep kills, pauses or resumes one step; see ManageTask for pauseFor.

func (*Client) ManageTask

func (c *Client) ManageTask(ctx context.Context, task string, action Action, pauseFor time.Duration) error

ManageTask kills, pauses or resumes a task. pauseFor only applies to ActionPause: a positive value resumes the task by itself after that long, zero waits for an explicit resume.

func (*Client) OpenReplay

func (c *Client) OpenReplay(ctx context.Context, id string) (io.ReadCloser, error)

OpenReplay streams a recording as asciinema v2 NDJSON; the first line is the header. The caller closes the returned reader.

func (*Client) OpenShell

func (c *Client) OpenShell(ctx context.Context, size ShellSize) (*Shell, error)

OpenShell opens an interactive shell. The server's {"zmodem":true} greeting is consumed here.

func (*Client) ResumeUpload

func (c *Client) ResumeUpload(ctx context.Context, uploadURL string) (*Upload, error)

ResumeUpload attaches to an existing upload and reads its current offset.

func (*Client) StepLog

func (c *Client) StepLog(ctx context.Context, task, step string) (*Result[iproto.SStepLogsRes], error)

StepLog returns a snapshot of the step output. The result code is the run state of the step; use Stream.WatchStepLog to follow a running step.

func (*Client) System

func (c *Client) System(ctx context.Context) (*iproto.SSystemConfig, error)

System returns the worker pool size and the host resource metrics. Resizing the pool is a stream call: see Stream.ResizePool.

func (*Client) UploadFile

func (c *Client) UploadFile(ctx context.Context, opts UploadOptions, r io.Reader) (*Upload, error)

UploadFile creates an upload and sends r in one go. For resumable behaviour use CreateUpload / ResumeUpload and Upload.Send directly.

func (*Client) Version

func (c *Client) Version(ctx context.Context) (*iproto.SVersion, error)

Version returns the server build information.

func (*Client) WatchSession

func (c *Client) WatchSession(ctx context.Context, id string) (*Lines, error)

WatchSession follows the output of a live session over plain HTTP as asciinema v2 NDJSON lines. Keep-alive blank lines are skipped. Next returns io.EOF when the session ends. For a multiplexed alternative see Stream.WatchTerminalSession.

type Download

type Download struct {
	// Name is the file name announced by the server.
	Name        string
	ContentType string
	// Size is the content length, or -1 when unknown.
	Size int64
	io.ReadCloser
}

Download is a workspace file being downloaded. Close it when done.

type Event

type Event struct {
	// Seq is the position in the event stream; a jump means events were dropped.
	Seq uint64 `json:"seq"`
	// Text is the event line, e.g. "<task> <step> Execute".
	Text string `json:"text"`
}

Event is one worker event.

type Feed

type Feed[T any] struct {
	// contains filtered or unexported fields
}

Feed is a typed subscription.

func (*Feed[T]) All

func (f *Feed[T]) All(ctx context.Context) iter.Seq2[Update[T], error]

All iterates over the updates until the feed ends or ctx is cancelled. An abnormal end is yielded once as a final error.

func (*Feed[T]) Close

func (f *Feed[T]) Close(ctx context.Context) error

Close unsubscribes.

func (*Feed[T]) Err

func (f *Feed[T]) Err() error

Err is why the feed ended; nil for a normal end.

func (*Feed[T]) Next

func (f *Feed[T]) Next(ctx context.Context) (u Update[T], ok bool, err error)

Next returns the next update. ok is false once the feed is over, with err set if it ended abnormally.

func (*Feed[T]) Subscription

func (f *Feed[T]) Subscription() *Subscription

Subscription exposes the raw subscription.

type Frame

type Frame struct {
	ID      string         `json:"id"`
	Topic   string         `json:"topic"`
	Event   string         `json:"event"`
	Code    api.Code       `json:"code"`
	Message string         `json:"message"`
	Data    jsontext.Value `json:"data"`
}

Frame is one server frame with the payload left undecoded.

type Lines

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

Lines reads a NDJSON stream line by line. It is not safe for concurrent use.

func (*Lines) Close

func (l *Lines) Close() error

Close releases the connection.

func (*Lines) Next

func (l *Lines) Next() ([]byte, error)

Next returns the next non-empty line without its newline.

type ListTasksOptions

type ListTasksOptions struct {
	Page   int64
	Size   int64
	Prefix string
}

ListTasksOptions pages the task list. Page -1 disables paging; zero values use the server defaults (page 1, 15 per page).

type Option

type Option func(*Client)

Option configures a Client.

func WithBasicAuth

func WithBasicAuth(user, password string) Option

WithBasicAuth sends HTTP basic credentials with every request.

func WithBearerToken

func WithBearerToken(token string) Option

WithBearerToken sends "Authorization: Bearer <token>" with every request.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient replaces the default http.Client, e.g. to set TLS or proxy options. Do not set http.Client.Timeout on it: it would also cut streaming responses; use WithRequestTimeout instead.

func WithHeader

func WithHeader(key, value string) Option

WithHeader adds a header to every request, including WebSocket handshakes.

func WithRequestTimeout

func WithRequestTimeout(d time.Duration) Option

WithRequestTimeout bounds every non-streaming request whose context has no deadline of its own. Zero disables the bound. The default is 30 seconds.

func WithRetries

func WithRetries(n int) Option

WithRetries retries idempotent requests (GET, HEAD, DELETE) up to n more times after a transport error or a 502/503/504 answer, with exponential backoff.

func WithUserAgent

func WithUserAgent(ua string) Option

WithUserAgent overrides the User-Agent header.

type Result

type Result[T any] struct {
	Code    api.Code
	Message string
	Data    T
}

Result is a response whose Code is meaningful even on success: it carries the run state of a task or step (running, pending, paused, failed, ...).

type SessionList

type SessionList struct {
	Sessions []iproto.WebShellSession `json:"sessions"`
}

SessionList is the payload of the terminal-sessions topic.

type Shell

type Shell struct {

	// ZModem reports whether the server announced ZMODEM support. It is known
	// after Open returns.
	ZModem bool
	// contains filtered or unexported fields
}

Shell is an interactive terminal session (/api/v1/terminal). Read, Write and Resize may be used from different goroutines, but each of them is not safe for concurrent use with itself.

func (*Shell) Close

func (s *Shell) Close() error

Close ends the session normally.

func (*Shell) Read

func (s *Shell) Read(ctx context.Context) ([]byte, error)

Read returns the next chunk of terminal output. It returns io.EOF-like close errors (see websocket.CloseStatus) when the shell exits.

func (*Shell) Resize

func (s *Shell) Resize(ctx context.Context, cols, rows int) error

Resize changes the terminal size (each dimension 1..1000).

func (*Shell) Write

func (s *Shell) Write(ctx context.Context, p []byte) error

Write sends keyboard input to the shell.

func (*Shell) WriteTransfer

func (s *Shell) WriteTransfer(ctx context.Context, p []byte) error

WriteTransfer sends ZMODEM protocol data (e.g. the sender side of an rz upload) to the shell's PTY.

type ShellSize

type ShellSize struct{ Cols, Rows int }

ShellSize is the initial terminal size; zero values mean 80x24.

type Stream

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

Stream is the multiplexed WebSocket (/api/v1/ws): live subscriptions and one-shot calls over one connection that reconnects by itself and resubscribes. It is safe for concurrent use.

func (*Stream) Call

func (s *Stream) Call(ctx context.Context, method string, params, out any) error

Call invokes a server method and decodes its result into out (nil to discard). A failing call returns *APIError.

func (*Stream) Close

func (s *Stream) Close() error

Close ends the stream, all subscriptions and pending calls.

func (*Stream) CreateTask

func (s *Stream) CreateTask(ctx context.Context, task *iproto.STaskReq) (*iproto.STaskCreateRes, error)

CreateTask submits a task definition.

func (*Stream) CreateTaskYAML

func (s *Stream) CreateTaskYAML(ctx context.Context, definition string) (*iproto.STaskCreateRes, error)

CreateTaskYAML submits a task definition written as YAML.

func (*Stream) DeleteTask

func (s *Stream) DeleteTask(ctx context.Context, task string) error

DeleteTask removes a task.

func (*Stream) DisconnectSession

func (s *Stream) DisconnectSession(ctx context.Context, id string) error

DisconnectSession closes a live terminal session.

func (*Stream) Done

func (s *Stream) Done() <-chan struct{}

Done is closed when the stream has ended for good.

func (*Stream) DumpTask

func (s *Stream) DumpTask(ctx context.Context, task string) (string, error)

DumpTask exports a task definition as YAML.

func (*Stream) Err

func (s *Stream) Err() error

Err is why the stream ended, or nil while it runs.

func (*Stream) ListReplays

func (s *Stream) ListReplays(ctx context.Context, limit, offset int) (*iproto.ReplayList, error)

ListReplays lists recordings; limit is 1..100 (0 = 50).

func (*Stream) ManageStep

func (s *Stream) ManageStep(ctx context.Context, task, step string, action Action, pauseFor time.Duration) error

ManageStep kills, pauses or resumes a step.

func (*Stream) ManageTask

func (s *Stream) ManageTask(ctx context.Context, task string, action Action, pauseFor time.Duration) error

ManageTask kills, pauses or resumes a task; see Client.ManageTask.

func (*Stream) Ping

func (s *Stream) Ping(ctx context.Context) (time.Duration, error)

Ping measures the round trip over the application protocol.

func (*Stream) ResizePool

func (s *Stream) ResizePool(ctx context.Context, size int) error

ResizePool changes the worker pool size. Shrinking may wait for workers to finish their current task, so allow the context enough time.

func (*Stream) Subscribe

func (s *Stream) Subscribe(ctx context.Context, topic string, params any) (*Subscription, error)

Subscribe opens a subscription to a topic with the given params.

func (*Stream) WatchEvents

func (s *Stream) WatchEvents(ctx context.Context, since uint64) (*Feed[Event], error)

WatchEvents follows worker events. since replays what was emitted after that sequence number; after a reconnect the feed resumes from the last event it delivered.

func (*Stream) WatchStep

func (s *Stream) WatchStep(ctx context.Context, task, step string) (*Feed[*iproto.SStepRes], error)

WatchStep follows one step until it finishes.

func (*Stream) WatchStepLog

func (s *Stream) WatchStepLog(ctx context.Context, task, step string) (*Feed[iproto.SStepLogsRes], error)

WatchStepLog replays and follows the output of a step until it finishes. After a reconnect the log is replayed from its start.

func (*Stream) WatchSteps

func (s *Stream) WatchSteps(ctx context.Context, task string) (*Feed[iproto.SStepsRes], error)

WatchSteps follows the step list of a task until it finishes.

func (*Stream) WatchSystem

func (s *Stream) WatchSystem(ctx context.Context) (*Feed[iproto.SSystemConfig], error)

WatchSystem follows worker pool size and host metrics.

func (*Stream) WatchTask

func (s *Stream) WatchTask(ctx context.Context, task string) (*Feed[*iproto.STaskRes], error)

WatchTask follows one task until it finishes.

func (*Stream) WatchTasks

func (s *Stream) WatchTasks(ctx context.Context, page iproto.SPageReq) (*Feed[*iproto.STaskListDetailRes], error)

WatchTasks follows one page of the task list.

func (*Stream) WatchTerminalReplay

func (s *Stream) WatchTerminalReplay(ctx context.Context, id string) (*Feed[string], error)

WatchTerminalReplay streams a recording as chunks of NDJSON text.

func (*Stream) WatchTerminalSession

func (s *Stream) WatchTerminalSession(ctx context.Context, id string) (*Feed[jsontext.Value], error)

WatchTerminalSession follows the output of a live session read-only. Each update is one asciinema cast line.

func (*Stream) WatchTerminalSessions

func (s *Stream) WatchTerminalSessions(ctx context.Context) (*Feed[SessionList], error)

WatchTerminalSessions follows the list of live terminal sessions; every update is the complete list.

type StreamOption

type StreamOption func(*Stream)

StreamOption configures DialStream.

func WithConnectionHooks

func WithConnectionHooks(onConnect func(reconnect bool), onDisconnect func(error)) StreamOption

WithConnectionHooks installs callbacks for connection state changes. Both run on the connection goroutine and must not block.

func WithPingInterval

func WithPingInterval(d time.Duration) StreamOption

WithPingInterval sets how often the client probes the connection. Zero disables the probe; the default is 30 seconds.

func WithReconnect

func WithReconnect(minDelay, maxDelay time.Duration) StreamOption

WithReconnect sets the backoff between reconnect attempts. A max of zero disables reconnecting; the default is 500ms growing to 30s.

type Subscription

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

Subscription is a live topic subscription delivering raw frames. Use the typed Watch* methods unless you need the raw payload.

func (*Subscription) Close

func (sub *Subscription) Close(ctx context.Context) error

Close unsubscribes.

func (*Subscription) Err

func (sub *Subscription) Err() error

Err is why the subscription ended; nil for a normal end or while it runs.

func (*Subscription) Frames

func (sub *Subscription) Frames() <-chan Frame

Frames returns the delivery channel, closed when the subscription ended. Drain it promptly: a consumer that stalls blocks the whole connection.

type Update

type Update[T any] struct {
	Code    api.Code
	Message string
	Data    T
}

Update is one decoded subscription frame. Code carries the run state of what is watched (running, pending, paused, failed, ...).

type Upload

type Upload struct {
	// URL is the absolute upload URL (the Location the server returned). Keep it
	// to resume the upload later with Client.ResumeUpload.
	URL string
	// Offset is the number of bytes the server has stored.
	Offset int64
	// Length is the total size, or -1 if still deferred.
	Length int64
	// contains filtered or unexported fields
}

Upload is a resumable tus upload into a task workspace.

func (*Upload) Patch

func (u *Upload) Patch(ctx context.Context, chunk io.Reader, n int64, setLength int64) error

Patch appends one chunk at the current offset. setLength fixes a deferred total size with this request.

func (*Upload) Refresh

func (u *Upload) Refresh(ctx context.Context) error

Refresh reads the server-side offset and length (HEAD).

func (*Upload) Send

func (u *Upload) Send(ctx context.Context, r io.Reader, size, chunkSize int64) error

Send uploads r from the current offset to the end in chunks. r must be positioned at u.Offset (use io.Seeker or skip bytes before calling). size is the total length, or -1 if unknown (read until EOF, deferring the length).

func (*Upload) Terminate

func (u *Upload) Terminate(ctx context.Context) error

Terminate deletes the upload on the server.

type UploadOptions

type UploadOptions struct {
	// Task is the task whose workspace receives the file.
	Task string
	// Filename is the target path inside the workspace (forward slashes, local,
	// no ':' or '\\'). Empty uses the upload ID.
	Filename string
	// Size is the total size in bytes; negative defers it (the size is then
	// fixed with the last chunk).
	Size int64
	// ChunkSize is the PATCH size; default 8 MiB.
	ChunkSize int64
}

UploadOptions describes a new upload.

Jump to

Keyboard shortcuts

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