Documentation
¶
Overview ¶
Package core provides the shared HTTP client, error types, polling, and retry logic used by all RunAPI service packages.
Index ¶
- Constants
- func CLIUserAgent(version string) string
- func CompactParams(params any) map[string]any
- func DecodeResponse[T any](payload json.RawMessage) (*T, error)
- func ErrorFromResponse(response *http.Response, body []byte) error
- func FormatError(err error) string
- func GetJSON[T any](ctx context.Context, httpClient HTTPClient, path string, ...) (*T, error)
- func IsAuthentication(err error) bool
- func IsConflict(err error) bool
- func IsIdempotentMethod(method string) bool
- func IsInsufficientCredits(err error) bool
- func IsNetwork(err error) bool
- func IsNotFound(err error) bool
- func IsRateLimit(err error) bool
- func IsRetryableStatus(status int) bool
- func IsServer(err error) bool
- func IsServiceUnavailable(err error) bool
- func IsTaskFailed(err error) bool
- func IsTaskTimeout(err error) bool
- func IsTimeout(err error) bool
- func IsValidation(err error) bool
- func NormalizeStatus(status string) string
- func ParseRetryAfter(header string) time.Duration
- func PollUntilComplete[T TaskResponse](ctx context.Context, fetcher func(context.Context) (T, error), ...) (T, error)
- func PostJSON[T any](ctx context.Context, httpClient HTTPClient, path string, body any, ...) (*T, error)
- func ResourcePath(basePath, id string) string
- func RetryDelay(attempt int, baseDelay, maxDelay time.Duration) time.Duration
- func RunAsync[T TaskResponse](ctx context.Context, create func(context.Context) (*TaskCreateResponse, error), ...) (*T, error)
- func SDKUserAgent(version string) string
- type CallConfig
- type CallOption
- type ClientOptions
- type Error
- type ErrorCode
- type HTTPClient
- type HTTPRequestOptions
- type PollingOptions
- type RequestOptions
- type TaskCreateResponse
- type TaskResponse
Constants ¶
Variables ¶
This section is empty.
Functions ¶
func CLIUserAgent ¶
func CompactParams ¶
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 ¶
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 ¶
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 ¶
IsAuthentication reports whether err is an authentication error.
func IsConflict ¶
IsConflict reports whether err is a conflict error.
func IsIdempotentMethod ¶
IsIdempotentMethod reports whether the HTTP method is safe to retry.
func IsInsufficientCredits ¶
IsInsufficientCredits reports whether err is an insufficient credits error.
func IsNotFound ¶
IsNotFound reports whether err is a not found error.
func IsRateLimit ¶
IsRateLimit reports whether err is a rate limit error.
func IsRetryableStatus ¶
IsRetryableStatus reports whether the HTTP status code is retryable (429 or 5xx).
func IsServiceUnavailable ¶
IsServiceUnavailable reports whether err is a service unavailable error.
func IsTaskFailed ¶
IsTaskFailed reports whether err is a task failed error.
func IsTaskTimeout ¶
IsTaskTimeout reports whether err is a task polling timeout error.
func IsValidation ¶
IsValidation reports whether err is a validation error.
func NormalizeStatus ¶
NormalizeStatus maps backend status strings to "completed", "failed", or "processing".
func ParseRetryAfter ¶
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 ¶
ResourcePath joins a base API path with a resource ID.
func RetryDelay ¶
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 ¶
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.
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 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 ¶
TaskResponse is implemented by async task result types.