transport

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Jun 17, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SchemeWS   = "ws"
	SchemeHTTP = "http"
)

Transport schemes supported by the CLI.

Variables

View Source
var ErrNoAPIKey = errors.New("no API key configured")

ErrNoAPIKey is returned when no API key is present in the local configuration.

Functions

func IsAuthError

func IsAuthError(err error) bool

IsAuthError reports whether err is an authentication or authorisation error.

func IsRetryable

func IsRetryable(code ErrorCode) bool

IsRetryable reports whether the given error code represents a transient failure that may succeed if the request is retried.

func ValidTransport added in v0.10.0

func ValidTransport(s string) bool

ValidTransport reports whether s names a supported transport scheme. Matching is case-insensitive, consistent with output format validation.

func ValidTransports added in v0.10.0

func ValidTransports() []string

ValidTransports returns the list of supported transport schemes.

Types

type APIResponse

type APIResponse struct {
	Data   []json.RawMessage `json:"data"`
	Errors []RunwareError    `json:"errors,omitempty"`
}

APIResponse is the top-level envelope returned by the Runware API.

type ErrorCode

type ErrorCode string

ErrorCode is a stable category for a RunwareError. Use it for switch/if statements.

const (
	CodeValidation  ErrorCode = "validation"
	CodeAuth        ErrorCode = "auth"
	CodeQuota       ErrorCode = "quota"
	CodeRateLimit   ErrorCode = "rateLimit"
	CodeSafety      ErrorCode = "safety"
	CodeProvider    ErrorCode = "provider"
	CodeTimeout     ErrorCode = "timeout"
	CodeNotFound    ErrorCode = "notFound"
	CodeServerError ErrorCode = "serverError"
	CodeConnection  ErrorCode = "connection"
	CodeAborted     ErrorCode = "aborted"
	CodeUnknown     ErrorCode = "unknown"
)

func DeriveCode

func DeriveCode(raw string) ErrorCode

DeriveCode maps a raw server-side error code string to a stable ErrorCode. The mapping mirrors the TypeScript SDK's deriveCode function.

type HTTPTransport

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

HTTPTransport implements Transport using the Runware REST API.

func DialHTTP

func DialHTTP(_ context.Context, apiKey, baseURL string, logger *slog.Logger, opts ...HTTPTransportOption) (*HTTPTransport, error)

DialHTTP creates an HTTP transport for the given API key and base URL. The ctx argument is accepted for interface symmetry but is not used — HTTP is stateless and requires no connection handshake. Default timeout is 120s. Use WithTimeout or WithHTTPClient to override.

func (*HTTPTransport) Close

func (t *HTTPTransport) Close() error

Close is a no-op for HTTP; the transport is stateless.

func (*HTTPTransport) Send

func (t *HTTPTransport) Send(ctx context.Context, tasks []any) ([]json.RawMessage, error)

Send marshals tasks, POSTs to the API, and returns the response data items. API-level errors are converted to Go errors before returning.

type HTTPTransportOption

type HTTPTransportOption func(*httpTransportOptions)

HTTPTransportOption is a functional option for DialHTTP.

func WithHTTPClient

func WithHTTPClient(c *http.Client) HTTPTransportOption

WithHTTPClient replaces the default HTTP client entirely. When provided, WithTimeout has no effect — the caller is responsible for the client's timeout.

func WithTimeout

func WithTimeout(d time.Duration) HTTPTransportOption

WithTimeout sets the HTTP client timeout. Ignored if WithHTTPClient is also provided.

type RunwareError

type RunwareError struct {
	// Code is a stable category for this error. Use it for switch/if statements.
	Code ErrorCode
	// RawCode is the original error code string from the API.
	RawCode string
	// Message is the human-readable error description.
	Message string
	// Retryable is true if retrying the same request might succeed.
	Retryable bool
	// Parameter is the request field that caused the error, if applicable.
	Parameter string
	// AllowedValues lists the accepted values for Parameter, if provided.
	AllowedValues []string
	// TaskType is the task type of the request that failed.
	TaskType string
	// TaskUUID is the unique identifier of the failed request.
	TaskUUID string
	// Documentation is a link to relevant documentation, if available.
	Documentation string
	// StatusCode is the HTTP status code when the error originated from an HTTP response.
	StatusCode int
}

RunwareError is a structured error returned by the Runware API or transport layer.

func CreateRunwareError

func CreateRunwareError(rawCode, message string, details RunwareErrorDetails) *RunwareError

CreateRunwareError constructs a RunwareError from a raw code, message, and optional details.

func ParseAPIError

func ParseAPIError(raw json.RawMessage, statusCode int) *RunwareError

ParseAPIError parses a raw API response body into a RunwareError. It handles three JSON shapes:

[{...}]                        — array of error items; first element is used
{"errors":[{...}]}             — standard API envelope; errors[0] is used
{"error":{...},"taskUUID":"..."} — pre-stream HTTP error; inner object is used

func (*RunwareError) Error

func (e *RunwareError) Error() string

func (*RunwareError) UnmarshalJSON

func (e *RunwareError) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler so RunwareError can be decoded directly from an API errors array element.

type RunwareErrorDetails

type RunwareErrorDetails struct {
	Parameter  string
	TaskType   string
	TaskUUID   string
	StatusCode int
}

RunwareErrorDetails carries optional context for CreateRunwareError.

type StreamSender added in v0.11.0

type StreamSender interface {
	// SendStream transmits a single task and invokes onFrame for every result
	// frame delivered for its taskUUID, until onFrame reports done or returns
	// an error. API error frames for the task are returned as Go errors.
	SendStream(ctx context.Context, task any, onFrame func(frame json.RawMessage) (done bool, err error)) error
}

StreamSender is implemented by transports that can deliver multiple result frames for a single task over a persistent connection (e.g. WebSocket). Tasks like modelUpload stream pipeline status frames that are not available via getResponse polling.

type Transport

type Transport interface {
	// Close tears down the connection and releases any associated resources.
	Close() error

	// Send transmits tasks to the API and returns the raw response data items,
	// with any API-level errors already converted to Go errors.
	Send(ctx context.Context, tasks []any) ([]json.RawMessage, error)
}

Transport handles the wire protocol for communicating with the Runware API. Implementations are responsible for connection lifecycle and request delivery.

func DialContext

func DialContext(ctx context.Context, scheme, apiKey, url string, logger *slog.Logger) (Transport, error)

DialContext dials a transport by scheme. scheme must be "ws" or "http" (case-insensitive). Returns an error if the scheme is not recognised.

type WSOption

type WSOption func(*WSTransport)

WSOption is a functional option for configuring a WSTransport.

func WithMaxReconnectAttempts

func WithMaxReconnectAttempts(n int) WSOption

WithMaxReconnectAttempts sets the maximum number of reconnection attempts before the transport gives up and fails all in-flight requests. Default is 10.

func WithPingInterval

func WithPingInterval(d time.Duration) WSOption

WithPingInterval overrides the keepAlive ping interval. Intended for testing; production code should rely on the default (30s).

func WithPollBurstWindow added in v0.11.0

func WithPollBurstWindow(d time.Duration) WSOption

WithPollBurstWindow overrides the idle window used to collect a getResponse poll reply (see wsPollBurstWindow). Intended for testing; production code should rely on the default. Values <= 0 are clamped to wsPollBurstWindow to prevent the getResponse path from blocking indefinitely.

func WithReconnectBaseDelay

func WithReconnectBaseDelay(d time.Duration) WSOption

WithReconnectBaseDelay overrides the base delay between reconnect attempts. Intended for testing; production code should rely on the default (1s).

type WSTransport

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

WSTransport implements Transport over a persistent WebSocket connection.

The first call to Send establishes the connection and authenticates with the API. Subsequent calls reuse the same connection.

On connection loss the transport reconnects automatically with exponential backoff. In-flight Send calls are preserved across reconnections; the server replays buffered results via the connectionSessionUUID mechanism. Only when the maximum reconnect attempts are exhausted are in-flight calls failed.

Close is terminal — the transport cannot be reused after Close.

func DialWS

func DialWS(ctx context.Context, apiKey, baseURL string, logger *slog.Logger, opts ...WSOption) (*WSTransport, error)

NewWSTransport creates a WebSocket transport for the given API key and base URL. Connect is deferred until the first Send (or an explicit Connect call). DialWS dials a WebSocket connection to the Runware API, performs the authentication handshake, and returns a ready-to-use transport. opts may be used to override reconnect behaviour, ping interval, etc.

func (*WSTransport) Close

func (t *WSTransport) Close() error

Close permanently shuts down the WebSocket connection and unblocks all in-flight Send calls. Close is terminal — the transport cannot be reused afterwards. Safe to call if DialWS succeeded but no Send has been issued yet.

func (*WSTransport) Send

func (t *WSTransport) Send(ctx context.Context, tasks []any) ([]json.RawMessage, error)

Send marshals tasks, writes them to the WebSocket connection, and waits for all expected results for each task UUID.

If a task carries a "numberResults" field (int > 1), Send collects that many result items before returning. All results for all tasks are returned as a flat slice in task order. Defaults to 1 result per task if the field is absent.

func (*WSTransport) SendStream added in v0.11.0

func (t *WSTransport) SendStream(ctx context.Context, task any, onFrame func(frame json.RawMessage) (done bool, err error)) error

SendStream implements StreamSender: it transmits a single task and dispatches every result frame received for its taskUUID to onFrame, until onFrame reports done or returns an error, the context is cancelled, or the transport shuts down. API error frames for the task are returned as Go errors. The in-flight entry survives reconnects, like Send.

Jump to

Keyboard shortcuts

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