core

package
v0.2.4 Latest Latest
Warning

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

Go to latest
Published: May 22, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package core provides the shared HTTP client, error types, polling, and retry logic used by all RunAPI service packages.

Index

Constants

View Source
const (
	DefaultBaseURL        = "https://runapi.ai"
	DefaultTimeout        = 15 * time.Minute
	DefaultMaxRetries     = 2
	DefaultRetryBaseDelay = 500 * time.Millisecond
	DefaultRetryMaxDelay  = 5 * time.Second
	DefaultPollInterval   = 2 * time.Second
	DefaultMaxWait        = 15 * time.Minute
)

Variables

This section is empty.

Functions

func CLIUserAgent

func CLIUserAgent(version string) string

func CompactParams

func CompactParams(params any) map[string]any

CompactParams converts a struct to a flat map, removing nil values and empty strings.

func DecodeResponse

func DecodeResponse[T any](payload json.RawMessage) (*T, error)

DecodeResponse unmarshals a JSON payload into T.

func ErrorFromResponse

func ErrorFromResponse(response *http.Response, body []byte) error

ErrorFromResponse constructs an appropriate Error from an HTTP response. It maps status codes to error codes and extracts error messages from the body.

func FormatError

func FormatError(err error) string

FormatError returns a human-readable error message, including retry-after info for rate limits.

func GetJSON

func GetJSON[T any](ctx context.Context, httpClient HTTPClient, path string, requestOptions RequestOptions) (*T, error)

GetJSON sends a GET request and decodes the response into T.

func IsAuthentication

func IsAuthentication(err error) bool

IsAuthentication reports whether err is an authentication error.

func IsConflict

func IsConflict(err error) bool

IsConflict reports whether err is a conflict error.

func IsIdempotentMethod

func IsIdempotentMethod(method string) bool

IsIdempotentMethod reports whether the HTTP method is safe to retry.

func IsInsufficientCredits

func IsInsufficientCredits(err error) bool

IsInsufficientCredits reports whether err is an insufficient credits error.

func IsNetwork

func IsNetwork(err error) bool

IsNetwork reports whether err is a network error.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err is a not found error.

func IsRateLimit

func IsRateLimit(err error) bool

IsRateLimit reports whether err is a rate limit error.

func IsRetryableStatus

func IsRetryableStatus(status int) bool

IsRetryableStatus reports whether the HTTP status code is retryable (429 or 5xx).

func IsServer

func IsServer(err error) bool

IsServer reports whether err is a server error.

func IsServiceUnavailable

func IsServiceUnavailable(err error) bool

IsServiceUnavailable reports whether err is a service unavailable error.

func IsTaskFailed

func IsTaskFailed(err error) bool

IsTaskFailed reports whether err is a task failed error.

func IsTaskTimeout

func IsTaskTimeout(err error) bool

IsTaskTimeout reports whether err is a task polling timeout error.

func IsTimeout

func IsTimeout(err error) bool

IsTimeout reports whether err is an HTTP request timeout error.

func IsValidation

func IsValidation(err error) bool

IsValidation reports whether err is a validation error.

func NormalizeStatus

func NormalizeStatus(status string) string

NormalizeStatus maps backend status strings to "completed", "failed", or "processing".

func ParseRetryAfter

func ParseRetryAfter(header string) time.Duration

ParseRetryAfter parses the Retry-After header value as seconds or HTTP-date.

func PollUntilComplete

func PollUntilComplete[T TaskResponse](ctx context.Context, fetcher func(context.Context) (T, error), opts PollingOptions) (T, error)

PollUntilComplete repeatedly calls fetcher until the task completes, fails, or times out.

func PostJSON

func PostJSON[T any](ctx context.Context, httpClient HTTPClient, path string, body any, requestOptions RequestOptions) (*T, error)

PostJSON sends a POST request with a JSON body and decodes the response into T.

func ResourcePath

func ResourcePath(basePath, id string) string

ResourcePath joins a base API path with a resource ID.

func RetryDelay

func RetryDelay(attempt int, baseDelay, maxDelay time.Duration) time.Duration

RetryDelay computes an exponential backoff delay with jitter for the given attempt.

func RunAsync

func RunAsync[T TaskResponse](ctx context.Context, create func(context.Context) (*TaskCreateResponse, error), get func(context.Context, string) (*T, error), pollingOptions PollingOptions) (*T, error)

RunAsync creates an async task and polls until completion.

func SDKUserAgent

func SDKUserAgent(version string) string

Types

type CallConfig

type CallConfig struct {
	Request RequestOptions
	Polling PollingOptions
}

CallConfig holds resolved request and polling options for a single API call.

func ResolveCallOptions

func ResolveCallOptions(options ...CallOption) CallConfig

ResolveCallOptions applies the given options to a CallConfig with default polling settings.

type CallOption

type CallOption interface {
	ApplyCall(*CallConfig)
}

CallOption is implemented by options that configure per-call behavior.

type ClientOptions

type ClientOptions struct {
	// APIKey for authentication. Required.
	APIKey string
	// BaseURL for API requests. Defaults to "https://runapi.ai".
	BaseURL string
	// Timeout for each HTTP request. Defaults to 15 minutes.
	Timeout time.Duration
	// MaxRetries is the maximum number of retry attempts. Defaults to 2.
	MaxRetries int
	// RetryBaseDelay is the base delay between retries. Defaults to 500ms.
	RetryBaseDelay time.Duration
	// RetryMaxDelay is the maximum delay between retries. Defaults to 5s.
	RetryMaxDelay time.Duration
	// HTTPClient is an optional custom *http.Client. When set, Timeout is ignored.
	HTTPClient *http.Client
	// UserAgent overrides the default User-Agent header.
	UserAgent string
	// Headers are extra HTTP headers sent with every request.
	Headers map[string]string
}

ClientOptions configures the HTTP client shared across all service operations.

func DefaultClientOptions

func DefaultClientOptions() ClientOptions

DefaultClientOptions returns ClientOptions with production defaults.

type Error

type Error struct {
	Message    string
	Code       ErrorCode
	Status     int
	RequestID  string
	Details    any
	RetryAfter time.Duration
	Err        error
}

Error is the base error type for all RunAPI SDK errors. It includes HTTP status, request ID, and response details.

func NewError

func NewError(code ErrorCode, message string, status int, requestID string, details any, err error) *Error

NewError creates a new Error with the given fields.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type ErrorCode

type ErrorCode string

ErrorCode identifies the category of an API error.

const (
	// ErrAuthentication indicates a missing or invalid API key (HTTP 401).
	ErrAuthentication ErrorCode = "authentication"
	// ErrInsufficientCredits indicates the account has insufficient credits (HTTP 402).
	ErrInsufficientCredits ErrorCode = "insufficient_credits"
	// ErrNotFound indicates the requested resource does not exist (HTTP 404).
	ErrNotFound ErrorCode = "not_found"
	// ErrValidation indicates request validation failed (HTTP 400, 422).
	ErrValidation ErrorCode = "validation"
	// ErrConflict indicates the request conflicts with current resource state (HTTP 409).
	ErrConflict ErrorCode = "conflict"
	// ErrRateLimit indicates the rate limit was exceeded (HTTP 429).
	ErrRateLimit ErrorCode = "rate_limit"
	// ErrServiceUnavailable indicates the service is temporarily unavailable (HTTP 455, 503).
	ErrServiceUnavailable ErrorCode = "service_unavailable"
	// ErrServer indicates an internal server error (HTTP 5xx).
	ErrServer ErrorCode = "server"
	// ErrNetwork indicates a network connection failure.
	ErrNetwork ErrorCode = "network"
	// ErrTimeout indicates the HTTP request exceeded the configured timeout.
	ErrTimeout ErrorCode = "timeout"
	// ErrTaskTimeout indicates polling for task completion exceeded the maximum wait time.
	ErrTaskTimeout ErrorCode = "task_timeout"
	// ErrTaskFailed indicates the async task failed during processing.
	ErrTaskFailed ErrorCode = "task_failed"
)

type HTTPClient

type HTTPClient interface {
	Request(ctx context.Context, method, path string, opts *HTTPRequestOptions) (json.RawMessage, error)
}

HTTPClient is the interface for sending HTTP requests. Implement this to provide a custom HTTP transport.

func NewHTTPClient

func NewHTTPClient(options ClientOptions) (HTTPClient, error)

NewHTTPClient creates the default HTTP client from the given options. Returns an authentication error if no API key is provided.

type HTTPRequestOptions

type HTTPRequestOptions struct {
	Body    any
	Query   map[string]string
	Headers map[string]string
	Request RequestOptions
}

HTTPRequestOptions holds options for a single HTTP request.

type PollingOptions

type PollingOptions struct {
	// PollInterval is the delay between poll requests. Defaults to 2s.
	PollInterval time.Duration
	// MaxWait is the maximum total wait time. Defaults to 15 minutes.
	MaxWait time.Duration
}

PollingOptions controls async task polling behavior.

func DefaultPollingOptions

func DefaultPollingOptions() PollingOptions

DefaultPollingOptions returns PollingOptions with production defaults.

type RequestOptions

type RequestOptions struct {
	// Headers are additional HTTP headers merged with client-level headers.
	Headers map[string]string
	// Timeout overrides the client-level timeout for this request.
	Timeout time.Duration
	// MaxRetries overrides the client-level max retries for this request.
	MaxRetries *int
}

RequestOptions are per-request overrides that take precedence over client-level defaults.

type TaskCreateResponse

type TaskCreateResponse struct {
	// ID is the task ID for tracking and retrieval.
	ID string `json:"id"`
	// Status is the initial task status, typically "processing".
	Status string `json:"status,omitempty"`
}

TaskCreateResponse is the response returned when an async task is created.

func (TaskCreateResponse) GetError

func (r TaskCreateResponse) GetError() string

func (TaskCreateResponse) GetID

func (r TaskCreateResponse) GetID() string

func (TaskCreateResponse) GetStatus

func (r TaskCreateResponse) GetStatus() string

type TaskResponse

type TaskResponse interface {
	GetID() string
	GetStatus() string
	GetError() string
}

TaskResponse is implemented by async task result types.

Jump to

Keyboard shortcuts

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