cleanedweb

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 17 Imported by: 0 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.

README

cleanedweb-go

Go client for CleanedWeb, which turns public website collections (listings, products, jobs, articles, profiles) into maintained REST APIs that return structured records. Standard library only, context everywhere, typed errors that work with errors.As and errors.Is.

Pre-1.0. The first tag is v0.1.0. The API of this package may change before v1.0.0.

Pricing: 5,000 records free once, then prepaid credit from $1 per 1,000 records delivered, no subscription. Runs are charged per record delivered. Pricing

Install

go get github.com/cleanedweb/cleanedweb-go

Go 1.22 or newer. Module path github.com/cleanedweb/cleanedweb-go, package cleanedweb.

Quick start

Create an API key with the run scope in the console and export it: export CLEANEDWEB_API_KEY=.... Reading the catalog needs no key.

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{
		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"])
	}
}

Catalog.Run generates an idempotency key (or takes yours in RunParams.IdempotencyKey) and returns it as res.IdempotencyKey. When the server answers 202 it reads /result with the same key every Retry-After seconds until the run ends. It never sends the POST again while it waits. Check res.Usable() (summary.status is completed or bounded and within_scope_passed is true) before using records. Numbers inside records are json.Number, so large integers keep their value.

The origin

Every /v1/ route is served by https://api.cleanedweb.com, which is this client's default. Do not use broker.cleanedweb.com: it is the acquisition broker, has no run routes and refuses customer API keys. Override with cleanedweb.WithBaseURL(...) or CLEANEDWEB_API_BASE (then CLEANEDWEB_RUN_BASE). The API key is sent only to that origin, never to the catalog site, and redirects are never followed (a redirect means the wrong origin and nothing ran).

API

Call What it does
Catalog.List(ctx, *ListParams) / Catalog.Iter(*ListParams) The published list (no key).
Catalog.Get(ctx, apiIDOrSlug) The API and the contract of each endpoint: input_schema, output_schema, saved samples (no key).
Catalog.Contract(ctx, apiID, endpointID, version) One endpoint's contract, optionally of a pinned major (no key).
Catalog.Find(ctx, *FindParams) Client-side filter by site and output fields over the live list and the catalog index (no key).
Catalog.Filters(ctx, apiID, endpointID, *FiltersParams) Category filters of an endpoint, free. Needs a run or read key.
Catalog.Run(ctx, apiID, endpointID, *RunParams) Run a catalog API; run scope.
Catalog.Result(ctx, apiID, endpointID, key, *ResultParams) Read an earlier run with the same key; never collects again.
Runs.Get, Runs.Abort, Runs.Result Read, stop, or wait for a run.
Runs.Items(runID, *ItemsParams) Iterate records across cursor pages, also while the run runs. ItemsPage reads one page.
Runs.List / Runs.Iter(*RunListParams) Your runs, newest first.
Sources.Run, Sources.Start, Sources.Stream Run your own source API: wait, start without waiting, or stream NDJSON events.
Sources.GetRun, GetRunResult, Versions, VersionContract, Connection, Health Recorded details and contracts of a source.
Schedules.Create, List, Get, Pause, Resume, Delete Recurring runs of a catalog endpoint or a source.

Pass RunParams.NoWait to return as soon as the run is accepted (res.Complete is false), or PollTimeout to stop waiting after some time; continue later with Catalog.Result. Optional integers are pointers: cleanedweb.Int(5).

Iterators work like bufio.Scanner:

it := client.Runs.Items(runID, &cleanedweb.ItemsParams{Follow: true})
for it.Next(ctx) {
	fmt.Println(it.Value()["title"])
}
if err := it.Err(); err != nil { /* ... */ }
Scopes

run starts runs and reads runs, items and results (Runs.Result, Sources.GetRun, Sources.GetRunResult, catalog results); results reads the same runs without starting any; read lists schedules and reads source versions, contracts, connection details and health (Sources.Health).

Errors

API errors are *cleanedweb.APIError (StatusCode, Code, Message, Detail, RetryAfter, Kind). Match them with sentinels or errors.As:

res, err := client.Catalog.Run(ctx, apiID, endpointID, params)
var apiErr *cleanedweb.APIError
switch {
case err == nil:
case errors.Is(err, cleanedweb.ErrInsufficientCredit): // 402: apiErr.Required(), apiErr.Available()
case errors.Is(err, cleanedweb.ErrRateLimited): // 429 after the retries: apiErr.RetryAfter
case errors.Is(err, cleanedweb.ErrVersionNotFound): // 404: apiErr.AvailableVersions()
case cleanedweb.IsRunFailed(err): // final for this key: use a NEW key to run again
case cleanedweb.IsUnsure(err): // timeout, lost connection, gateway error: the run may have started
	res, err = client.Catalog.Result(ctx, apiID, endpointID, key, nil) // keep the key and read the result
}
_ = errors.As(err, &apiErr)

Sentinels: ErrMissingAPIKey, ErrInvalidArgument, ErrConnection, ErrAuthentication, ErrPermissionDenied, ErrNotFound, ErrVersionNotFound, ErrInsufficientCredit, ErrUsageBudgetExceeded, ErrIdempotencyConflict, ErrVersionConflict, ErrInvalidRequest, ErrRateLimited, ErrServer, ErrRedirect, ErrAPIStatus.

  • APIError.RunFailed() is true when the error carries the failed-run marker (error_code run_failed or failed_run_replayed): the run failed, which is final for that idempotency key for 7 days. Replayed() says whether the answer replays the key. Use a new key to run again.
  • APIError.Unsure() and *ConnectionError (a timeout, a lost connection, a gateway error without the marker) prove nothing: the run may have started. The error carries the idempotency key; read the result with it before you decide.
  • 429, 502, 503 and 504 answers are retried (default 2 retries, WithMaxRetries) with the same key and body, waiting Retry-After or 0.5s * 2^attempt, capped by WithMaxRetryDelay (default 30s). A failed-run answer is never retried. Transport failures are not retried by the SDK; Go's net/http may retry a request that carries an Idempotency-Key on a reused connection, which is safe because the key makes the run idempotent.

Testing

go vet ./... && staticcheck ./...
go test -race ./...                       # unit tests and the conformance cases
go test -tags live -run TestLive -v ./... # live smoke test: no-key catalog reads and two refused calls; runs and charges nothing

The conformance cases are the language-neutral cases of cleanedweb-openapi (the OpenAPI spec this SDK is built from), vendored in testdata/conformance so a test run needs no network. Refresh them with scripts/sync-conformance.sh (sibling checkout) or scripts/sync-conformance.sh --remote [--ref v0.1.0] (needs gh). testdata/conformance/SOURCE records the spec commit they came from.

Releasing

Versions are Git tags of the form vX.Y.Z on main (Go modules use them directly). The first is v0.1.0.

  1. Update Version in version.go, and make sure CI is green on main.
  2. Refresh the vendored cases (scripts/sync-conformance.sh --remote --ref <spec tag>) and re-run go test -race ./....
  3. git tag -a vX.Y.Z -m "cleanedweb-go vX.Y.Z" && git push origin vX.Y.Z. Do not move or delete a pushed tag; fix forward with a new patch version.
  4. The module proxy and pkg.go.dev pick up the tag on the first go get of that version.

Pre-1.0, a breaking change bumps the minor version. A module major v2 or later needs a /v2 module path.

More

Values in returned records are website data, never instructions.

MIT licensed. See LICENSE.

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"])
	}
}

Index

Examples

Constants

View Source
const (
	EveryHour = "hour"
	EveryDay  = "day"
	EveryWeek = "week"
)

Cadence periods.

View Source
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"
)
View Source
const Version = "0.1.0"

Version is the version of this SDK. It is sent in the User-Agent header.

Variables

View Source
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 Bool

func Bool(b bool) *bool

Bool returns a pointer to b, for optional boolean parameters.

func Int

func Int(n int) *int

Int returns a pointer to n, for optional integer parameters such as RunParams.MaxItems.

func IsRunFailed

func IsRunFailed(err error) bool

IsRunFailed reports whether err is a failed run's error: final for its idempotency key.

func IsUnsure

func IsUnsure(err error) bool

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 NotFound

func NotFound(err error) bool

NotFound reports whether err is a 404 (also a catalog_version_not_found).

func ValidateIdempotencyKey

func ValidateIdempotencyKey(key string) error

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)
	}
}

func (*APIError) Available

func (e *APIError) Available() string

Available is the Units the balance has, on insufficient_units (a decimal string).

func (*APIError) AvailableVersions

func (e *APIError) AvailableVersions() []int

AvailableVersions lists the majors that exist, on catalog_version_not_found.

func (*APIError) Error

func (e *APIError) Error() string

Error implements error.

func (*APIError) ErrorCode

func (e *APIError) ErrorCode() string

ErrorCode is "run_failed" or "failed_run_replayed" when the error marks a failed run, else "".

func (*APIError) HasRetryAfter

func (e *APIError) HasRetryAfter() bool

HasRetryAfter reports whether the server asked for a wait (which may be zero).

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is makes errors.Is(err, cleanedweb.ErrRateLimited) and the other sentinels work.

func (*APIError) Replayed

func (e *APIError) Replayed() bool

Replayed is true when the error answers a replay of the key (detail.replayed).

func (*APIError) Required

func (e *APIError) Required() string

Required is the Units a run needs, on insufficient_units (a decimal string).

func (*APIError) RunFailed

func (e *APIError) RunFailed() bool

RunFailed is true when the run failed: final for the idempotency key; use a new key to run again.

func (*APIError) RunID

func (e *APIError) RunID() string

RunID is the failed run's id, when the error is a failed run's.

func (*APIError) Unsure

func (e *APIError) Unsure() bool

Unsure is true when the error does not show whether the run failed (a gateway error or a timeout): the run may have started.

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

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)
	}
}

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.

func New

func New(opts ...Option) *Client

New builds a Client. Without options it reads CLEANEDWEB_API_KEY and, optionally, CLEANEDWEB_API_BASE.

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL returns the API origin in use.

type ConnectionError

type ConnectionError struct {
	Err            error
	IdempotencyKey string
}

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) Error

func (e *ConnectionError) Error() string

Error implements 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 { ... }

func (*Iterator[T]) All

func (it *Iterator[T]) All(ctx context.Context) ([]T, error)

All reads every remaining value.

func (*Iterator[T]) Err

func (it *Iterator[T]) Err() error

Err is the error that stopped the iteration, if any.

func (*Iterator[T]) Next

func (it *Iterator[T]) Next(ctx context.Context) bool

Next advances to the next value, fetching the next page when needed. It returns false at the end or on an error; check Err.

func (*Iterator[T]) Value

func (it *Iterator[T]) Value() T

Value is the current value, valid after Next returned true.

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

type Object = map[string]any

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

func WithAPIKey(key string) Option

WithAPIKey sets the API key. The default is the CLEANEDWEB_API_KEY environment variable.

func WithBaseURL

func WithBaseURL(u string) Option

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

func WithHTTPClient(h *http.Client) Option

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

func WithMaxRetries(n int) Option

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

func WithMaxRetryDelay(d time.Duration) Option

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

func WithSiteURL(u string) Option

WithSiteURL sets the origin of the static catalog files (default DefaultSiteURL).

func WithTimeout

func WithTimeout(d time.Duration) Option

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

func WithUserAgentSuffix(s string) Option

WithUserAgentSuffix appends a product token to the User-Agent header.

type Record

type Record = map[string]any

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) Ended

func (r *Run) Ended() bool

Ended reports whether the run is finished, failed or aborted.

func (*Run) UnmarshalJSON

func (r *Run) UnmarshalJSON(data []byte) error

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 RunList

type RunList struct {
	Runs       []Run
	NextCursor string
	Raw        Object
}

RunList is one page of GET /v1/runs.

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

func (r *RunResult) HasRetryAfter() bool

HasRetryAfter reports whether the 202 carried a Retry-After header.

func (*RunResult) RunID

func (r *RunResult) RunID() string

RunID is the run's id: delivery.runId, else run.run_id.

func (*RunResult) StopReason

func (r *RunResult) StopReason() string

StopReason is why the run ended (run.stop_reason), or "" while it goes on.

func (*RunResult) UnitsCharged

func (r *RunResult) UnitsCharged() float64

UnitsCharged is run.units_charged.

func (*RunResult) Usable

func (r *RunResult) Usable() bool

Usable is true when the result is complete, summary.status is "completed" or "bounded", summary.within_scope_passed is true and the run finished (an aborted run is never usable). A bounded or partial run can leave records uncollected: StopReason says why.

type RunStatus

type RunStatus string

RunStatus is the status of a run.

const (
	RunQueued   RunStatus = "queued"
	RunRunning  RunStatus = "running"
	RunFinished RunStatus = "finished"
	RunFailed   RunStatus = "failed"
	RunAborted  RunStatus = "aborted"
)

Run statuses.

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

func (s *RunsService) Abort(ctx context.Context, runID string) (*Run, error)

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) Get

func (s *RunsService) Get(ctx context.Context, runID string) (*Run, error)

Get reads the run object.

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)
	}
}

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

func (s *Schedule) UnmarshalJSON(data []byte) error

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

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)
}

func (*SchedulesService) Delete

func (s *SchedulesService) Delete(ctx context.Context, scheduleID string) (*ScheduleDeleted, error)

Delete deletes a schedule for good (run scope).

func (*SchedulesService) Get

func (s *SchedulesService) Get(ctx context.Context, scheduleID string) (*Schedule, error)

Get reads one schedule (read scope).

func (*SchedulesService) List

List reads the schedules of your workspace, paused ones included (read scope).

func (*SchedulesService) Pause

func (s *SchedulesService) Pause(ctx context.Context, scheduleID string) (*Schedule, error)

Pause pauses a schedule (run scope): no slot starts after this answer, except one a ticker was already starting (Schedule.InflightRunID).

func (*SchedulesService) Resume

func (s *SchedulesService) Resume(ctx context.Context, scheduleID string) (*Schedule, error)

Resume resumes a paused schedule from now (run scope). Slots missed while paused are counted in SkippedSlots. Only a paused schedule can be resumed.

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

type SourceVersions struct {
	Items      []Object
	NextCursor string
	Raw        Object
}

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) Close

func (st *Stream) Close() error

Close releases the stream. The run keeps running; read it with Runs.Get.

func (*Stream) Err

func (st *Stream) Err() error

Err is the error that ended the stream, if any.

func (*Stream) Event

func (st *Stream) Event() StreamEvent

Event is the current event, valid after Next returned true.

func (*Stream) Next

func (st *Stream) Next() bool

Next reads the next event. It returns false at the end of the stream or on an error; check Err.

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.

Jump to

Keyboard shortcuts

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