Documentation
¶
Overview ¶
Package cleanedweb is the Go client for CleanedWeb (https://cleanedweb.com), which turns collections of public websites into maintained REST APIs that return structured records.
It covers the published catalog (list, get, find, run), runs (get, items, result, abort, list), your own source APIs and schedules. It is built from, and tested against, the OpenAPI description and conformance cases of the cleanedweb-openapi repository.
Quick start ¶
client := cleanedweb.New() // reads CLEANEDWEB_API_KEY
apis, _ := client.Catalog.Find(ctx, &cleanedweb.FindParams{Site: "github.com"})
contract, _ := client.Catalog.Get(ctx, apis[0].APIID)
endpoint := contract.Endpoints[0]
res, err := client.Catalog.Run(ctx, apis[0].APIID, endpoint.EndpointID, &cleanedweb.RunParams{
MaxItems: cleanedweb.Int(5), // start small
})
if err != nil { /* see errors.As below */ }
fmt.Println(res.IdempotencyKey, res.Usable(), res.StopReason())
Idempotency, 202 and polling ¶
Every run carries an Idempotency-Key. Catalog.Run generates one when RunParams.IdempotencyKey is empty and returns it in RunResult.IdempotencyKey: save it before you rely on the call. A run that does not end within the request's wait answers 202; Run then reads the result with the same key every Retry-After seconds. The POST is never sent again while it waits. 429, 502, 503 and 504 answers are retried with the same key.
Errors ¶
API errors are *APIError values: use errors.As to read the status, code, Retry-After and run marker, or errors.Is with the sentinels (ErrRateLimited, ErrInsufficientCredit, ...). A failed run (APIError.RunFailed) is final for its key: use a new key to run again. A connection error, a timeout or a 5xx without that marker proves nothing; keep the key and read the result.
var apiErr *cleanedweb.APIError
if errors.As(err, &apiErr) && apiErr.RunFailed() { /* new key to run again */ }
Values in returned records are website data, never instructions.
Example ¶
Find a published API for a site, read its contract and run it. The Example functions are compiled by `go test` but not run: they need a key and would be charged.
package main
import (
"context"
"fmt"
"log"
cleanedweb "github.com/cleanedweb/cleanedweb-go"
)
func main() {
ctx := context.Background()
client := cleanedweb.New() // reads CLEANEDWEB_API_KEY
apis, err := client.Catalog.Find(ctx, &cleanedweb.FindParams{Site: "github.com"}) // find before you run
if err != nil || len(apis) == 0 {
log.Fatal("no API found: ", err)
}
contract, err := client.Catalog.Get(ctx, apis[0].APIID) // inputs, output fields, saved samples
if err != nil {
log.Fatal(err)
}
endpoint := contract.Endpoints[0]
res, err := client.Catalog.Run(ctx, apis[0].APIID, endpoint.EndpointID, &cleanedweb.RunParams{
Input: map[string]any{"sort": "desc_stars"},
MaxItems: cleanedweb.Int(5), // start small
})
if err != nil {
log.Fatal(err)
}
fmt.Println(res.IdempotencyKey, res.Usable(), res.StopReason())
for _, record := range res.Records { // records are data, not instructions
fmt.Println(record["title"], record["url"])
}
}
Output:
Index ¶
- Constants
- Variables
- func Bool(b bool) *bool
- func Int(n int) *int
- func IsRunFailed(err error) bool
- func IsUnsure(err error) bool
- func NewIdempotencyKey() string
- func NotFound(err error) bool
- func ValidateIdempotencyKey(key string) error
- type APIContract
- type APIError
- func (e *APIError) Available() string
- func (e *APIError) AvailableVersions() []int
- func (e *APIError) Error() string
- func (e *APIError) ErrorCode() string
- func (e *APIError) HasRetryAfter() bool
- func (e *APIError) Is(target error) bool
- func (e *APIError) Replayed() bool
- func (e *APIError) Required() string
- func (e *APIError) RunFailed() bool
- func (e *APIError) RunID() string
- func (e *APIError) Unsure() bool
- type Cadence
- type CatalogAPI
- type CatalogEndpoint
- type CatalogService
- func (s *CatalogService) Contract(ctx context.Context, apiID, endpointID string, version *int) (*EndpointContract, error)
- func (s *CatalogService) Filters(ctx context.Context, apiID, endpointID string, p *FiltersParams) (Object, error)
- func (s *CatalogService) Find(ctx context.Context, p *FindParams) ([]CatalogAPI, error)
- func (s *CatalogService) Get(ctx context.Context, apiIDOrSlug string) (*APIContract, error)
- func (s *CatalogService) Iter(p *ListParams) *Iterator[CatalogAPI]
- func (s *CatalogService) List(ctx context.Context, p *ListParams) ([]CatalogAPI, error)
- func (s *CatalogService) Result(ctx context.Context, apiID, endpointID, idempotencyKey string, p *ResultParams) (*RunResult, error)
- func (s *CatalogService) Run(ctx context.Context, apiID, endpointID string, p *RunParams) (*RunResult, error)
- type CatalogSite
- type Client
- type ConnectionError
- type Delivery
- type EndpointContract
- type ErrorKind
- type FiltersParams
- type FindParams
- type InvalidArgumentError
- type ItemsParams
- type Iterator
- type ListParams
- type MissingAPIKeyError
- type Object
- type Option
- func WithAPIKey(key string) Option
- func WithBaseURL(u string) Option
- func WithHTTPClient(h *http.Client) Option
- func WithMaxRetries(n int) Option
- func WithMaxRetryDelay(d time.Duration) Option
- func WithSiteURL(u string) Option
- func WithTimeout(d time.Duration) Option
- func WithUserAgentSuffix(s string) Option
- type Record
- type ResultParams
- type Run
- type RunItemsPage
- type RunLimits
- type RunList
- type RunListParams
- type RunParams
- type RunProgress
- type RunResult
- type RunStatus
- type RunsService
- func (s *RunsService) Abort(ctx context.Context, runID string) (*Run, error)
- func (s *RunsService) Get(ctx context.Context, runID string) (*Run, error)
- func (s *RunsService) Items(runID string, p *ItemsParams) *Iterator[Record]
- func (s *RunsService) ItemsPage(ctx context.Context, runID string, p *ItemsParams) (*RunItemsPage, error)
- func (s *RunsService) Iter(p *RunListParams) *Iterator[Run]
- func (s *RunsService) List(ctx context.Context, p *RunListParams) (*RunList, error)
- func (s *RunsService) Result(ctx context.Context, runID string, p *ResultParams) (*RunResult, error)
- type Schedule
- type ScheduleDeleted
- type ScheduleList
- type ScheduleParams
- type SchedulesService
- func (s *SchedulesService) Create(ctx context.Context, p *ScheduleParams) (*Schedule, error)
- func (s *SchedulesService) Delete(ctx context.Context, scheduleID string) (*ScheduleDeleted, error)
- func (s *SchedulesService) Get(ctx context.Context, scheduleID string) (*Schedule, error)
- func (s *SchedulesService) List(ctx context.Context) (*ScheduleList, error)
- func (s *SchedulesService) Pause(ctx context.Context, scheduleID string) (*Schedule, error)
- func (s *SchedulesService) Resume(ctx context.Context, scheduleID string) (*Schedule, error)
- type SourceConnection
- type SourceHealth
- type SourceRunDetail
- type SourceRunParams
- type SourceVersionContract
- type SourceVersions
- type SourcesService
- func (s *SourcesService) Connection(ctx context.Context, sourceID string) (*SourceConnection, error)
- func (s *SourcesService) GetRun(ctx context.Context, sourceID, runID string) (*SourceRunDetail, error)
- func (s *SourcesService) GetRunResult(ctx context.Context, sourceID, runID string, p *ResultParams) (*RunResult, error)
- func (s *SourcesService) Health(ctx context.Context, sourceID string) (*SourceHealth, error)
- func (s *SourcesService) Run(ctx context.Context, sourceID string, p *SourceRunParams) (*RunResult, error)
- func (s *SourcesService) Start(ctx context.Context, sourceID string, p *SourceRunParams) (*Run, error)
- func (s *SourcesService) Stream(ctx context.Context, sourceID string, p *SourceRunParams) (*Stream, error)
- func (s *SourcesService) VersionContract(ctx context.Context, sourceID, definitionVersion string) (*SourceVersionContract, error)
- func (s *SourcesService) Versions(ctx context.Context, sourceID string, limit int, cursor string) (*SourceVersions, error)
- type Stream
- type StreamEvent
- type Summary
Examples ¶
Constants ¶
const ( EveryHour = "hour" EveryDay = "day" EveryWeek = "week" )
Cadence periods.
const ( // DefaultBaseURL is the origin of every /v1/ route: catalog reads, runs, results, // schedules and source APIs. Not broker.cleanedweb.com, which is the acquisition broker // and refuses customer keys. DefaultBaseURL = "https://api.cleanedweb.com" // DefaultSiteURL serves the static catalog index (catalog/index.json) that Catalog.Find and // Catalog.Get use to add slugs and key fields. The API key is never sent to it. DefaultSiteURL = "https://cleanedweb.com" )
const Version = "0.1.0"
Version is the version of this SDK. It is sent in the User-Agent header.
Variables ¶
var ( ErrMissingAPIKey error = &kindError{KindMissingAPIKey} ErrInvalidArgument error = &kindError{KindInvalidArgument} ErrConnection error = &kindError{KindConnection} ErrAuthentication error = &kindError{KindAuthentication} ErrPermissionDenied error = &kindError{KindPermissionDenied} ErrNotFound error = &kindError{KindNotFound} ErrVersionNotFound error = &kindError{KindVersionNotFound} ErrInsufficientCredit error = &kindError{KindInsufficientCredit} ErrUsageBudgetExceeded error = &kindError{KindUsageBudgetExceeded} ErrIdempotencyConflict error = &kindError{KindIdempotencyConflict} ErrVersionConflict error = &kindError{KindVersionConflict} ErrInvalidRequest error = &kindError{KindInvalidRequest} ErrRateLimited error = &kindError{KindRateLimited} ErrServer error = &kindError{KindServer} ErrRedirect error = &kindError{KindRedirect} ErrAPIStatus error = &kindError{KindAPIStatus} )
Sentinels for errors.Is(err, cleanedweb.ErrRateLimited) and friends. Every error returned by this package matches exactly one of them.
Functions ¶
func IsRunFailed ¶
IsRunFailed reports whether err is a failed run's error: final for its idempotency key.
func IsUnsure ¶
IsUnsure reports whether err leaves it unknown whether the run started or failed: a connection error, or a gateway error or timeout without a failed-run marker. Keep the idempotency key and read the result with it.
func NewIdempotencyKey ¶
func NewIdempotencyKey() string
NewIdempotencyKey returns a random UUIDv4, the key Run generates when you give none.
func ValidateIdempotencyKey ¶
ValidateIdempotencyKey reports whether key is 1 to 200 characters of letters, digits and . _ : -
Types ¶
type APIContract ¶
type APIContract struct {
API CatalogAPI
Endpoints []EndpointContract
}
APIContract is a catalog API with the contract of each endpoint.
func (*APIContract) Endpoint ¶
func (c *APIContract) Endpoint(endpointID string) (*EndpointContract, error)
Endpoint returns the endpoint named endpointID, or the only endpoint when endpointID is empty.
type APIError ¶
type APIError struct {
// Kind classifies the error; see the Kind constants.
Kind ErrorKind
// StatusCode is the HTTP status.
StatusCode int
// Code is detail.code (or detail.error_code) when the body has one, for example
// "insufficient_units".
Code string
// Message is the human message of the body.
Message string
// Detail is the parsed "detail" of the body (a string, an object or a list).
Detail any
// Body is the raw response body (at most 64 KiB).
Body []byte
// Header holds the response headers.
Header http.Header
// RetryAfter is the wait the server asked for (Retry-After header, then detail.retry_after_seconds,
// retryAfterSeconds or retry_after). Zero when none; see HasRetryAfter.
RetryAfter time.Duration
// IdempotencyKey is the key of the request, when it carried one.
IdempotencyKey string
// contains filtered or unexported fields
}
APIError is an error answer of the API: an HTTP status of 400 or more, or a redirect.
Deciding what to do with an error that belongs to a run:
- RunFailed is true: the run failed, final for that idempotency key (the same answer is replayed for 7 days). Use a new key to run again.
- Unsure is true: a gateway error or timeout that does not show whether the run failed. Keep the key and read the result with it (Catalog.Result) before you decide.
Example ¶
Errors are *APIError values with typed sentinels.
package main
import (
"context"
"errors"
"fmt"
cleanedweb "github.com/cleanedweb/cleanedweb-go"
)
func main() {
client := cleanedweb.New()
_, err := client.Catalog.Run(context.Background(), "api_id", "endpoint_id", nil)
var apiErr *cleanedweb.APIError
switch {
case errors.Is(err, cleanedweb.ErrInsufficientCredit):
_ = errors.As(err, &apiErr)
fmt.Println("add credit:", apiErr.Required(), "needed,", apiErr.Available(), "available")
case errors.Is(err, cleanedweb.ErrRateLimited):
_ = errors.As(err, &apiErr)
fmt.Println("retry in", apiErr.RetryAfter)
case cleanedweb.IsRunFailed(err):
fmt.Println("the run failed; use a new idempotency key to run again")
case err != nil:
fmt.Println(err)
}
}
Output:
func (*APIError) Available ¶
Available is the Units the balance has, on insufficient_units (a decimal string).
func (*APIError) AvailableVersions ¶
AvailableVersions lists the majors that exist, on catalog_version_not_found.
func (*APIError) ErrorCode ¶
ErrorCode is "run_failed" or "failed_run_replayed" when the error marks a failed run, else "".
func (*APIError) HasRetryAfter ¶
HasRetryAfter reports whether the server asked for a wait (which may be zero).
func (*APIError) Is ¶
Is makes errors.Is(err, cleanedweb.ErrRateLimited) and the other sentinels work.
func (*APIError) Replayed ¶
Replayed is true when the error answers a replay of the key (detail.replayed).
func (*APIError) Required ¶
Required is the Units a run needs, on insufficient_units (a decimal string).
func (*APIError) RunFailed ¶
RunFailed is true when the run failed: final for the idempotency key; use a new key to run again.
type Cadence ¶
type Cadence struct {
Every string `json:"every"`
AtUTC string `json:"at_utc"`
Weekday *int `json:"weekday"`
}
Cadence says when a schedule is due.
type CatalogAPI ¶
type CatalogAPI struct {
APIID string `json:"api_id"`
Name string `json:"name"`
ShortDescription string `json:"short_description"`
Category string `json:"category"`
RecordTypes []string `json:"record_types"`
Countries []string `json:"countries"`
Languages []string `json:"languages"`
Tags []string `json:"tags"`
Limitations []string `json:"limitations"`
Site CatalogSite `json:"site"`
Endpoints []CatalogEndpoint `json:"endpoints"`
Health string `json:"health"`
UpdatedAt float64 `json:"updated_at"`
// Slug and KeyFields come from catalog/index.json (Catalog.Find adds them).
Slug string `json:"-"`
KeyFields []string `json:"-"`
Raw Object `json:"-"`
}
CatalogAPI is one published catalog API, as the live list or the catalog index describes it.
type CatalogEndpoint ¶
type CatalogEndpoint struct {
EndpointID string `json:"endpoint_id"`
Name string `json:"name"`
Description string `json:"description"`
Status string `json:"status"`
Acquisition string `json:"acquisition"`
ActiveVersion string `json:"active_version"`
Version string `json:"version"`
}
CatalogEndpoint summarises one endpoint of a catalog API.
type CatalogService ¶
type CatalogService struct {
// contains filtered or unexported fields
}
CatalogService reads and runs the published catalog. Reading (List, Iter, Get, Contract, Find) needs no API key; Run, Result and Filters do.
func (*CatalogService) Contract ¶
func (s *CatalogService) Contract(ctx context.Context, apiID, endpointID string, version *int) (*EndpointContract, error)
Contract reads the contract of one endpoint (no key needed). version pins a major; nil reads the latest.
func (*CatalogService) Filters ¶
func (s *CatalogService) Filters(ctx context.Context, apiID, endpointID string, p *FiltersParams) (Object, error)
Filters describes an endpoint's category filters: one live page read, free (no Units, nothing runs). It needs a key with the run or read scope. An endpoint without category filters answers 404 (category_filters_unavailable).
func (*CatalogService) Find ¶
func (s *CatalogService) Find(ctx context.Context, p *FindParams) ([]CatalogAPI, error)
Find returns the published APIs for a site that return the given fields. It is a client-side filter over the live list, joined with the catalog index (which adds Slug and KeyFields). Nothing runs and no key is needed.
func (*CatalogService) Get ¶
func (s *CatalogService) Get(ctx context.Context, apiIDOrSlug string) (*APIContract, error)
Get reads one API and the contract of each of its endpoints: inputs, output fields, saved samples (no key needed). Pass an api_id, or a slug from the catalog index.
func (*CatalogService) Iter ¶
func (s *CatalogService) Iter(p *ListParams) *Iterator[CatalogAPI]
Iter walks every API of the published list, page by page (no key needed).
func (*CatalogService) List ¶
func (s *CatalogService) List(ctx context.Context, p *ListParams) ([]CatalogAPI, error)
List returns one page of the published catalog (no key needed).
func (*CatalogService) Result ¶
func (s *CatalogService) Result(ctx context.Context, apiID, endpointID, idempotencyKey string, p *ResultParams) (*RunResult, error)
Result reads the result of an earlier Run with the same idempotency key. It never collects the website again. Use it to recover after a timeout or a lost response. It waits for a run that goes on unless ResultParams.NoWait is set. Needs a key with the run or read scope.
Example ¶
Save the idempotency key before you rely on a run; after an uncertain outcome read the result with it.
package main
import (
"context"
"fmt"
cleanedweb "github.com/cleanedweb/cleanedweb-go"
)
func main() {
ctx := context.Background()
client := cleanedweb.New()
key := cleanedweb.NewIdempotencyKey() // save it with your job record first
_, err := client.Catalog.Run(ctx, "api_id", "endpoint_id", &cleanedweb.RunParams{IdempotencyKey: key})
if cleanedweb.IsUnsure(err) { // timeout, lost connection, a gateway error: the run may have started
res, err := client.Catalog.Result(ctx, "api_id", "endpoint_id", key, nil) // never collects again
fmt.Println(res, err)
}
}
Output:
func (*CatalogService) Run ¶
func (s *CatalogService) Run(ctx context.Context, apiID, endpointID string, p *RunParams) (*RunResult, error)
Run runs a catalog endpoint. Runs are charged per record delivered: start with a small MaxItems.
A 202 (the run goes on) is followed with GET /result and the same idempotency key every Retry-After seconds until the run ends; the POST is never sent again. 429, 502, 503 and 504 answers are retried with the same key. A failed run returns an *APIError with RunFailed true: final for the key.
type CatalogSite ¶
type CatalogSite struct {
Name string `json:"name"`
Domain string `json:"domain"`
Description string `json:"description"`
}
CatalogSite is the website a catalog API reads.
type Client ¶
type Client struct {
// Catalog finds, reads and runs published catalog APIs.
Catalog *CatalogService
// Runs reads, waits for, aborts and lists runs.
Runs *RunsService
// Sources runs your own source APIs.
Sources *SourcesService
// Schedules creates and manages recurring runs.
Schedules *SchedulesService
// contains filtered or unexported fields
}
Client talks to the CleanedWeb API. It is safe for concurrent use.
The API key (default: CLEANEDWEB_API_KEY) is sent only to the base URL, never to the catalog site. Reading the catalog needs no key; running does.
type ConnectionError ¶
ConnectionError means the request did not get an answer (timeout, lost connection, DNS, TLS). The outcome is unknown: for a run it may have started. IdempotencyKey is set when the request carried one; reuse it to recover (Catalog.Result). It wraps the transport error.
func (*ConnectionError) Is ¶
func (e *ConnectionError) Is(target error) bool
Is matches ErrConnection.
func (*ConnectionError) Unsure ¶
func (e *ConnectionError) Unsure() bool
Unsure is always true: nothing proves whether the run started.
func (*ConnectionError) Unwrap ¶
func (e *ConnectionError) Unwrap() error
Unwrap returns the transport error (context.DeadlineExceeded, a net.Error, ...).
type Delivery ¶
type Delivery struct {
RunID string `json:"runId"`
ChargeReceiptID string `json:"chargeReceiptId"`
RecordCount int `json:"recordCount"`
}
Delivery is present for a customer workspace run.
type EndpointContract ¶
type EndpointContract struct {
EndpointID string
Name string
Description string
DefinitionVersion string
Method string
// Path is the run request path, relative to the API origin.
Path string
InputSchema Object
OutputSchema Object
Examples []any
Raw Object
}
EndpointContract is what an endpoint accepts and returns.
func (*EndpointContract) OutputFields ¶
func (e *EndpointContract) OutputFields() []string
OutputFields lists the fields of each record (output_schema.properties), sorted.
func (*EndpointContract) RequiredInputs ¶
func (e *EndpointContract) RequiredInputs() []string
RequiredInputs lists the inputs a run must send (input_schema.required).
type ErrorKind ¶
type ErrorKind string
ErrorKind classifies an error. The values are shared with the other CleanedWeb SDKs and the conformance cases.
const ( KindMissingAPIKey ErrorKind = "missing_api_key" KindInvalidArgument ErrorKind = "invalid_argument" KindConnection ErrorKind = "connection" KindAuthentication ErrorKind = "authentication" KindPermissionDenied ErrorKind = "permission_denied" KindNotFound ErrorKind = "not_found" KindVersionNotFound ErrorKind = "version_not_found" KindInsufficientCredit ErrorKind = "insufficient_credit" KindUsageBudgetExceeded ErrorKind = "usage_budget_exceeded" KindIdempotencyConflict ErrorKind = "idempotency_conflict" KindVersionConflict ErrorKind = "version_conflict" KindInvalidRequest ErrorKind = "invalid_request" KindRateLimited ErrorKind = "rate_limited" KindServer ErrorKind = "server" KindRedirect ErrorKind = "redirect" KindAPIStatus ErrorKind = "api_status" )
Error kinds.
type FiltersParams ¶
type FiltersParams struct {
Category string
Search string
// Filters are the filters chosen so far, such as {"brand": "Leica"}.
Filters map[string]any
}
FiltersParams ask which categories and filters exist for an endpoint that takes category filters.
type FindParams ¶
type FindParams struct {
// Site is a domain, URL or name: "github.com", "https://www.github.com/x".
Site string
// Fields are output fields every returned API must have.
Fields []string
// Q and Category filter the live list server-side.
Q, Category string
// Limit caps the result (default 20).
Limit int
// Deep reads the contracts of candidates whose key fields do not settle Fields (at most
// MaxContractChecks, default 20). Set NoDeep to skip.
NoDeep bool
MaxContractChecks int
}
FindParams select published APIs.
type InvalidArgumentError ¶
type InvalidArgumentError struct{ Message string }
InvalidArgumentError is a bad argument, found before any request was sent.
func (*InvalidArgumentError) Error ¶
func (e *InvalidArgumentError) Error() string
Error implements error.
func (*InvalidArgumentError) Is ¶
func (e *InvalidArgumentError) Is(target error) bool
Is matches ErrInvalidArgument.
type ItemsParams ¶
type ItemsParams struct {
// Cursor is where to start; empty starts at the first record.
Cursor string
// Limit is the page size (default 100).
Limit int
// Follow keeps waiting for new records until the run ended and every record was read.
// Otherwise Items stops at the first empty page.
Follow bool
// PollInterval is the wait between reads when Follow is set (default 2s).
PollInterval time.Duration
// Nulls sends every published field, with absent values as null.
Nulls bool
}
ItemsParams control Runs.Items and Runs.ItemsPage.
type Iterator ¶
type Iterator[T any] struct { // contains filtered or unexported fields }
Iterator walks a paged list one value at a time. Use it like bufio.Scanner:
it := client.Runs.Items(runID, nil)
for it.Next(ctx) {
record := it.Value()
}
if err := it.Err(); err != nil { ... }
type ListParams ¶
type ListParams struct {
// Q searches the published inventory before paging.
Q string
// Category is one of commerce, real_estate, jobs, businesses_places, news_content,
// social_communities, travel, public_data, web_search, uncategorized.
Category string
// Sort is "updated" (default) or "name".
Sort string
// Limit is the page size, 1 to 100 (default 20; Iter uses 100).
Limit int
// Offset is where the page starts.
Offset int
}
ListParams filter the catalog list.
type MissingAPIKeyError ¶
type MissingAPIKeyError struct{}
MissingAPIKeyError means a call that needs a key was made without one. Pass WithAPIKey or set CLEANEDWEB_API_KEY. Catalog reads need no key.
func (*MissingAPIKeyError) Error ¶
func (e *MissingAPIKeyError) Error() string
Error implements error.
func (*MissingAPIKeyError) Is ¶
func (e *MissingAPIKeyError) Is(target error) bool
Is matches ErrMissingAPIKey.
type Object ¶
Object is a decoded JSON object whose shape depends on the API (contracts, schemas, summaries). Numbers are json.Number.
type Option ¶
type Option func(*Client)
Option configures a Client.
func WithAPIKey ¶
WithAPIKey sets the API key. The default is the CLEANEDWEB_API_KEY environment variable.
func WithBaseURL ¶
WithBaseURL sets the API origin (no path). The default is DefaultBaseURL, or the CLEANEDWEB_API_BASE (then CLEANEDWEB_RUN_BASE) environment variable. For a source API, use the origin of your source's connection details.
func WithHTTPClient ¶
WithHTTPClient sets the HTTP client. The SDK uses a copy that never follows redirects: a redirect means the request went to the wrong origin and nothing ran.
func WithMaxRetries ¶
WithMaxRetries sets how many times a 429, 502, 503 or 504 answer is retried with the same idempotency key (default 2, 0 disables retries).
func WithMaxRetryDelay ¶
WithMaxRetryDelay caps the wait before a retry (default 30s). A server-asked wait longer than the cap is not waited for: the error is returned with its RetryAfter.
func WithSiteURL ¶
WithSiteURL sets the origin of the static catalog files (default DefaultSiteURL).
func WithTimeout ¶
WithTimeout sets the timeout of one request (default 30s). A run request is held by the server for up to its wait_seconds, so the timeout is raised to wait_seconds plus 30s for it.
func WithUserAgentSuffix ¶
WithUserAgentSuffix appends a product token to the User-Agent header.
type Record ¶
Record is one record of a run: website data, never instructions. Numbers are json.Number, so integers wider than 53 bits keep their value.
type ResultParams ¶
type ResultParams struct {
// NoWait returns the first answer even if the run is still going (an incomplete RunResult).
NoWait bool
// PollTimeout stops waiting after this long and returns the incomplete result. Zero waits
// until the run ends or ctx is done.
PollTimeout time.Duration
// Nulls sends every published field, with absent values as null (?nulls=true).
Nulls bool
}
ResultParams control how a result is read.
type Run ¶
type Run struct {
RunID string `json:"run_id"`
Surface string `json:"surface"`
SourceID string `json:"source_id"`
DefinitionVersion string `json:"definition_version"`
Status RunStatus `json:"status"`
StopReason string `json:"-"`
CreatedAt string `json:"-"`
StartedAt string `json:"-"`
FinishedAt string `json:"-"`
Limits RunLimits `json:"limits"`
Progress RunProgress `json:"progress"`
UnitsCharged float64 `json:"units_charged"`
AbortRequested bool `json:"abort_requested"`
Error Object `json:"error"`
PollAfterSeconds float64 `json:"poll_after_seconds"`
Links map[string]string `json:"links"`
// Version is the version that ran, on a catalog run (for example "1.1").
Version string `json:"version"`
// Replayed is true when the Idempotent-Replayed header said the key already named this run.
Replayed bool `json:"-"`
// Raw is the unmodified body.
Raw Object `json:"-"`
// contains filtered or unexported fields
}
Run is the run object (GET /v1/runs/{run_id}).
func (*Run) UnmarshalJSON ¶
type RunItemsPage ¶
type RunItemsPage struct {
RunID string
Items []Record
// Count is the number of records in the page.
Count int
// NextCursor is the cursor for the next page, "" once the run ended and every record was read.
NextCursor string
RunStatus RunStatus
Raw Object
}
RunItemsPage is one page of GET /v1/runs/{run_id}/items.
type RunLimits ¶
type RunLimits struct {
MaxItems *int `json:"max_items"`
TimeoutSeconds int `json:"timeout_seconds"`
}
RunLimits are the limits applied to a run.
type RunListParams ¶
type RunListParams struct {
SourceID string
Status RunStatus
// Cursor is the NextCursor of the previous page.
Cursor string
// Limit is the page size (default 50).
Limit int
}
RunListParams filter the run list.
type RunParams ¶
type RunParams struct {
// Input is the endpoint's input, as its contract lists it.
Input map[string]any
// MaxItems stops the run after this many de-duplicated records (>= 1). Start small.
MaxItems *int
// TimeoutSeconds is the run's own time budget, 60 to 86400 (default 10800).
TimeoutSeconds *int
// WaitSeconds is how long the request waits for the run to end before answering 202 (default 90).
WaitSeconds *int
// NoWait asks the server not to hold the request (wait_seconds 0): Run returns the run as soon
// as it is accepted, with Complete false. Read it later with Catalog.Result.
NoWait bool
// Fields returns only these published output fields.
Fields []string
// Nulls sends every published field, with absent values as null.
Nulls *bool
// Version pins a major of the endpoint; nil runs the latest.
Version *int
// IdempotencyKey identifies this run. When empty, Run generates one and returns it in
// RunResult.IdempotencyKey: save it before you rely on the call.
IdempotencyKey string
// PollTimeout stops waiting for a 202 after this long and returns the incomplete result.
PollTimeout time.Duration
}
RunParams are the options of Catalog.Run.
type RunProgress ¶
type RunProgress struct {
Pages int `json:"pages"`
Commits int `json:"commits"`
Items int `json:"items"`
Duplicates int `json:"duplicates"`
}
RunProgress counts a run's work so far.
type RunResult ¶
type RunResult struct {
Complete bool
StatusCode int
IdempotencyKey string
Records []Record
Summary Summary
Metadata Object
Artifacts []any
TraceID string
Run Run
Delivery Delivery
// Version is the version that ran, on a catalog run ("2.3"); Rerouted is "sunset" when the
// major you pinned was sunset and the latest major ran.
Version string
Rerouted string
Deprecation string // Deprecation header
Sunset string // Sunset header
// RetryAfter is the Retry-After of a 202; see HasRetryAfter.
RetryAfter time.Duration
// Raw is the unmodified body.
Raw Object
// contains filtered or unexported fields
}
RunResult is the outcome of a run request.
Complete is true for a 200: Records, Summary and Delivery are present. It is false when the run was still going (a 202, NoWait, or PollTimeout passed): Run describes it and Catalog.Result or Runs.Result read it later.
HTTP 200 alone does not make a result usable: check Usable.
func (*RunResult) HasRetryAfter ¶
HasRetryAfter reports whether the 202 carried a Retry-After header.
func (*RunResult) StopReason ¶
StopReason is why the run ended (run.stop_reason), or "" while it goes on.
func (*RunResult) UnitsCharged ¶
UnitsCharged is run.units_charged.
type RunsService ¶
type RunsService struct {
// contains filtered or unexported fields
}
RunsService reads, waits for, aborts and lists runs. Reading a run never collects the website again. Run and items reads work with the run or results scope; reading a result needs the results scope; abort needs run.
func (*RunsService) Abort ¶
Abort stops a run: a queued run ends now, a running run at its next page boundary. Records committed so far stay readable and charged. Needs the run scope.
func (*RunsService) Items ¶
func (s *RunsService) Items(runID string, p *ItemsParams) *Iterator[Record]
Items iterates the records committed so far, following next_cursor page by page. It is readable while the run runs.
Example ¶
Iterate the records of a run while it runs, following cursors.
package main
import (
"context"
"fmt"
"log"
cleanedweb "github.com/cleanedweb/cleanedweb-go"
)
func main() {
ctx := context.Background()
client := cleanedweb.New()
it := client.Runs.Items("0123456789abcdef0123456789abcdef", &cleanedweb.ItemsParams{Limit: 100, Follow: true})
for it.Next(ctx) {
fmt.Println(it.Value()["title"])
}
if err := it.Err(); err != nil {
log.Fatal(err)
}
}
Output:
func (*RunsService) ItemsPage ¶
func (s *RunsService) ItemsPage(ctx context.Context, runID string, p *ItemsParams) (*RunItemsPage, error)
ItemsPage reads one page of the records committed so far. It is readable while the run runs.
func (*RunsService) Iter ¶
func (s *RunsService) Iter(p *RunListParams) *Iterator[Run]
Iter walks every run, following next_cursor.
func (*RunsService) List ¶
func (s *RunsService) List(ctx context.Context, p *RunListParams) (*RunList, error)
List reads one page of your runs, newest first.
func (*RunsService) Result ¶
func (s *RunsService) Result(ctx context.Context, runID string, p *ResultParams) (*RunResult, error)
Result reads the final body of a run: complete once the run ended, or, while it runs, polled every Retry-After seconds until it ends (unless NoWait). A failed run returns its error. Needs the results scope.
type Schedule ¶
type Schedule struct {
ScheduleID string `json:"schedule_id"`
Name string `json:"name"`
State string `json:"state"` // "active" or "paused"
PauseReason string `json:"pause_reason"`
// Target is {"api_id","endpoint_id"} or {"source_id"}.
Target Object `json:"target"`
SourceID string `json:"source_id"`
PinnedVersion string `json:"pinned_version"`
Input Object `json:"input"`
Fields []string `json:"fields"`
MaxItems *int `json:"max_items"`
TimeoutSeconds int `json:"timeout_seconds"`
Cadence Cadence `json:"cadence"`
NextDueAt string `json:"next_due_at"`
LastSlotAt string `json:"last_slot_at"`
LastRunID string `json:"last_run_id"`
LastStatus string `json:"last_status"`
ConsecutiveFailures int `json:"consecutive_failures"`
SkippedSlots int `json:"skipped_slots"`
// Attention lists "deferred", "overdue" or "previous_run_stuck".
Attention []string `json:"attention"`
CreatedAt string `json:"created_at"`
// InflightRunID is, on a pause answer, the run a ticker was already starting.
InflightRunID string `json:"inflight_run_id"`
// Replayed is true when the key already made this schedule (Idempotent-Replayed header).
Replayed bool `json:"-"`
// IdempotencyKey is the key the create call sent.
IdempotencyKey string `json:"-"`
Raw Object `json:"-"`
}
Schedule is a schedule as the API answers it.
func (*Schedule) UnmarshalJSON ¶
UnmarshalJSON keeps nullable fields as zero values and the whole body in Raw.
type ScheduleDeleted ¶
type ScheduleDeleted struct {
ScheduleID string `json:"schedule_id"`
Deleted bool `json:"deleted"`
// InflightRunID is the run a ticker was already starting, if any.
InflightRunID string `json:"-"`
}
ScheduleDeleted is the answer of Schedules.Delete.
type ScheduleList ¶
type ScheduleList struct {
Schedules []Schedule `json:"schedules"`
// Limit is the most schedules a workspace holds.
Limit int `json:"limit"`
}
ScheduleList is the answer of Schedules.List.
type ScheduleParams ¶
type ScheduleParams struct {
APIID string
EndpointID string
SourceID string
// Version is the major of a catalog API to schedule; nil keeps the listing's current one.
Version *int
// Input is the API's input; every required input is given now and used for each slot.
Input map[string]any
Fields []string
MaxItems *int
TimeoutSeconds *int
// Every is EveryHour, EveryDay or EveryWeek (UTC, not more often than hourly).
Every string
// AtUTC is the UTC time of day, "HH:MM" (for hourly, the minute past each hour; default "00:00").
AtUTC string
// Weekday is for EveryWeek: 0 Monday to 6 Sunday (default Monday).
Weekday *int
// RunNow also runs once at the next tick, not only from the next slot.
RunNow bool
Name string
// IdempotencyKey is the retry key: the same key and arguments answer the same schedule and never
// create a second. Generated and returned in Schedule.IdempotencyKey when empty.
IdempotencyKey string
}
ScheduleParams create a schedule. Give APIID and EndpointID (a catalog API) or SourceID (one of your own), not both.
type SchedulesService ¶
type SchedulesService struct {
// contains filtered or unexported fields
}
SchedulesService creates and manages recurring runs of a catalog endpoint or one of your sources. Each due slot starts an ordinary charged run, owned by your workspace and readable with Runs. The creating key stands behind the schedule: it must keep the run scope.
func (*SchedulesService) Create ¶
func (s *SchedulesService) Create(ctx context.Context, p *ScheduleParams) (*Schedule, error)
Create creates a schedule (run scope). The retry key goes in the Idempotency-Key header: a retry with the same key and arguments answers the same schedule (Schedule.Replayed) and never makes a second one. Another request under the same key is an idempotency conflict. A deleted schedule is never revived by a retry.
Example ¶
Schedule a catalog endpoint every day at 06:30 UTC. The idempotency key makes a retry safe.
package main
import (
"context"
"fmt"
"log"
cleanedweb "github.com/cleanedweb/cleanedweb-go"
)
func main() {
ctx := context.Background()
client := cleanedweb.New()
schedule, err := client.Schedules.Create(ctx, &cleanedweb.ScheduleParams{
APIID: "api_id", EndpointID: "endpoint_id", Input: map[string]any{},
MaxItems: cleanedweb.Int(100), Every: cleanedweb.EveryDay, AtUTC: "06:30",
IdempotencyKey: "daily-topics-1",
})
if err != nil {
log.Fatal(err)
}
fmt.Println(schedule.ScheduleID, schedule.State, schedule.NextDueAt, schedule.Replayed)
}
Output:
func (*SchedulesService) Delete ¶
func (s *SchedulesService) Delete(ctx context.Context, scheduleID string) (*ScheduleDeleted, error)
Delete deletes a schedule for good (run scope).
func (*SchedulesService) List ¶
func (s *SchedulesService) List(ctx context.Context) (*ScheduleList, error)
List reads the schedules of your workspace, paused ones included (read scope).
type SourceConnection ¶
type SourceConnection struct {
SourceID string
DefinitionVersion string
// REST is the run request: method, path, body (with expected_version) and an example key.
REST Object
Raw Object
}
SourceConnection is the run request for a source's active definition. It carries paths only, never an origin.
type SourceHealth ¶
type SourceHealth struct {
SourceID string
DefinitionVersion string
// Status is healthy, degraded, unhealthy, unknown, stale or never_checked.
Status string
Raw Object
}
SourceHealth is the monitoring evidence of a source's active definition.
type SourceRunDetail ¶
type SourceRunDetail struct {
ContractVersion string
Run, Results Object
Billing Object
Recovery Object
Raw Object
}
SourceRunDetail is the recorded detail of a source run: the run, its results state, billing and recovery context. Needs the results scope.
type SourceRunParams ¶
type SourceRunParams struct {
// Input is the input of the source's generated contract.
Input map[string]any
// MaxItems stops the run after this many de-duplicated records (>= 1).
MaxItems *int
// TimeoutSeconds is the run's own time budget, 60 to 86400 (default 10800).
TimeoutSeconds *int
// WaitSeconds is how long the request waits for the run to end before answering 202 (default 90
// for Run and Stream, 0 for Start).
WaitSeconds *int
// NoWait asks the server not to hold the request: Run returns the accepted run (Complete false).
NoWait bool
// Fields returns only these published output fields.
Fields []string
// Nulls sends every published field, with absent values as null.
Nulls *bool
// ExpectedVersion (the 64-character definition version) makes the call fail with a version
// conflict (KindVersionConflict) if the active definition changed. Do not combine it with
// DefinitionVersion.
ExpectedVersion string
// DefinitionVersion selects an accepted immutable revision explicitly.
DefinitionVersion string
// Endpoint is optional; the supported value is "search".
Endpoint string
// IdempotencyKey identifies this run; generated and returned when empty.
IdempotencyKey string
// PollTimeout stops waiting for a 202 after this long and returns the incomplete result.
PollTimeout time.Duration
}
SourceRunParams are the options of Sources.Run, Start and Stream.
type SourceVersionContract ¶
type SourceVersionContract struct {
SourceID string
DefinitionVersion string
// OpenAPI is an OpenAPI document for this version's run request and records.
OpenAPI Object
// Request is a ready-made run request: method, path, headers and body.
Request Object
Raw Object
}
SourceVersionContract is the published contract of one definition version.
type SourceVersions ¶
SourceVersions is a page of definition versions.
type SourcesService ¶
type SourcesService struct {
// contains filtered or unexported fields
}
SourcesService runs the source APIs of your own workspace. Use the origin of your source's connection details as the client's base URL (today DefaultBaseURL).
func (*SourcesService) Connection ¶
func (s *SourcesService) Connection(ctx context.Context, sourceID string) (*SourceConnection, error)
Connection reads a source's connection details (read scope). Fetching again creates new example idempotency keys, so keep the one you use.
func (*SourcesService) GetRun ¶
func (s *SourcesService) GetRun(ctx context.Context, sourceID, runID string) (*SourceRunDetail, error)
GetRun reads the recorded details of a source run (GET /v1/sources/{id}/runs/{run_id}).
func (*SourcesService) GetRunResult ¶
func (s *SourcesService) GetRunResult(ctx context.Context, sourceID, runID string, p *ResultParams) (*RunResult, error)
GetRunResult reads the result of a run of this source, polling like Runs.Result.
func (*SourcesService) Health ¶
func (s *SourcesService) Health(ctx context.Context, sourceID string) (*SourceHealth, error)
Health reads a source's health. No customer scope opens this route today: a scoped key answers a permission error. It works with credentials the engine treats as unscoped.
func (*SourcesService) Run ¶
func (s *SourcesService) Run(ctx context.Context, sourceID string, p *SourceRunParams) (*RunResult, error)
Run runs one of your source APIs (POST /v1/sources/{id}/run). It has the idempotency and waiting behaviour of Catalog.Run, except that a 202 is followed with GET /v1/runs/{run_id}/result, which needs the results scope: with a key that has only the run scope that read answers 403 (a permission error) while the run goes on. Read it with Runs.Get and Runs.Items, or create a key with the run and results scopes.
func (*SourcesService) Start ¶
func (s *SourcesService) Start(ctx context.Context, sourceID string, p *SourceRunParams) (*Run, error)
Start starts a source run without waiting (POST /v1/sources/{id}/runs). It answers the run object: usually 202, or 200 when the run already ended. Run.Replayed is true when the key already named this run. Read records with Runs.Items and the final body with Runs.Result.
func (*SourcesService) Stream ¶
func (s *SourcesService) Stream(ctx context.Context, sourceID string, p *SourceRunParams) (*Stream, error)
Stream runs a source API and streams its records as they are committed (POST /v1/sources/{id}/stream). A failed run ends the stream with an error event.
func (*SourcesService) VersionContract ¶
func (s *SourcesService) VersionContract(ctx context.Context, sourceID, definitionVersion string) (*SourceVersionContract, error)
VersionContract reads the contract of an accepted definition version (read scope).
func (*SourcesService) Versions ¶
func (s *SourcesService) Versions(ctx context.Context, sourceID string, limit int, cursor string) (*SourceVersions, error)
Versions lists the definition versions of a source, newest first (read scope).
type Stream ¶
type Stream struct {
// IdempotencyKey is the key of the run.
IdempotencyKey string
// RunLocation is the Location header: /v1/runs/{run_id}.
RunLocation string
// contains filtered or unexported fields
}
Stream is an open NDJSON stream of a run. Close it when done. Closing leaves the run running.
func (*Stream) Event ¶
func (st *Stream) Event() StreamEvent
Event is the current event, valid after Next returned true.
type StreamEvent ¶
type StreamEvent struct {
// Type is "progress", "records", "done" or "error".
Type string
Sequence int
// Stage is "running" or "heartbeat" on a progress event.
Stage string
// Records are the records of a records event.
Records []Record
// Run is the run object of the first progress event.
Run *Run
// StatusCode and ErrorCode describe an error event (a failed run ends the stream with one,
// not with an HTTP error). Replayed and RunID come from its detail.
StatusCode int
ErrorCode string
// Raw is the whole line.
Raw Object
}
StreamEvent is one line of a source run's stream.
type Summary ¶
type Summary struct {
SourceID string `json:"source_id"`
DefinitionVersion string `json:"definition_version"`
// Status is "completed", "bounded" or "partial".
Status string `json:"status"`
WithinScopePassed bool `json:"within_scope_passed"`
CatalogComplete bool `json:"catalog_complete"`
Records int `json:"records"`
}
Summary is the execution summary of an ended run. Keep the whole body (RunResult.Raw) to review source-specific fields.