batch

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: MIT Imports: 22 Imported by: ? 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

Zenrows Batch API Go SDK

This is the Go SDK for the Zenrows Batch API — an asynchronous, many-URL scraping service, separate from Fetch (different base URL, different auth header, and a job/run/task lifecycle instead of a single request/response).

Model

A Job is a template — a reusable submission with its configuration. A Run is one execution of that template; a job has 1+ runs over its lifetime. A Task is one URL within one run.

A job's Status is either:

  • JobStatusOpen — keeps accepting more tasks via AddTasks() until you call CloseJob(). Useful when you're streaming URLs in over time rather than knowing the full list upfront.
  • JobStatusClosed (the default when you submit tasks upfront) — a normal one-shot batch.

Installation

go get github.com/zenrows/zenrows-go-sdk/service/batch

Usage — resource handles

Client.Job(id) / Client.Run(jobID, runID) mint zero-network-call resource handles with chainable lifecycle operations — the same pattern as this SDK's Python counterpart. Prefer these over the raw Client.* methods below for anything beyond a one-off call.

import (
    "context"
    "fmt"
    "log"

    "github.com/zenrows/zenrows-go-sdk/service/batch"
)

client := batch.NewClient(batch.WithAPIKey("YOUR_API_KEY"))
ctx := context.Background()
check := func(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

// One-shot batch: every task known upfront.
job, err := client.SubmitRegular(ctx, batch.SubmitRegularOptions{
    Tasks: []batch.Task{{URL: "https://example.com/1"}, {URL: "https://example.com/2"}},
})
check(err)

// Streaming batch: keep the job open, add tasks as they arrive, close when done.
streaming, err := client.SubmitOpen(ctx, batch.SubmitOpenOptions{})
check(err)
_, err = streaming.AddTasks(ctx, []batch.Task{{URL: "https://example.com/3"}}, false)
check(err)
// With an Idempotency-Key, retrying a finished call with the same body (within 24 hours)
// replays its response instead of appending the tasks twice.
_, err = streaming.AddTasksWithOptions(ctx, []batch.Task{{URL: "https://example.com/4"}},
    batch.AddTasksOptions{IdempotencyKey: "orders-batch-4"})
check(err)
_, err = streaming.Close(ctx)
check(err)

// Scheduled: fire on a recurring or one-shot schedule. At/Rate/Calendar check their shape
// client-side; the API also rejects a rate more frequent than the account minimum (60 minutes
// by default).
rate, err := batch.NewRate(6, "hour")
check(err)
scheduled, err := client.SubmitScheduled(ctx, batch.SubmitScheduledOptions{
    Schedule: rate, Tasks: []batch.Task{{URL: "https://example.com/poll"}},
})
check(err)
_, err = scheduled.Schedule().Pause(ctx) // scheduled jobs only
check(err)

// Chainable navigation: job.Run() is the current-run facet, job.Schedule() the schedule facet.
// Wait blocks until the run is completed, stopped or failed. A paused run ends the wait with a
// RunPausedError, since it makes no progress until it is resumed.
run, err := job.Run().Wait(ctx, batch.WaitForRunOptions{})
check(err)
if run.Status() == batch.RunStatusFailed {
    // An account reason stopped the run: FailureReason is insufficient_credits,
    // subscription_inactive or api_key_cap_reached, and FailureDetail explains it.
    log.Fatalf("run failed: %s", run.Data.FailureReason)
}
for result, err := range run.Results(ctx, "") { // auto-paginated
    check(err)
    fmt.Println(result.TaskID, result.Status)
}
// Bulk downloads skip failed tasks and successful results past their retention window (14 days
// by default, counted from each row's UpdatedAt; a partial rerun resets UpdatedAt on the rows
// it copies). Expired rows come back as TaskStatusExpired; Skipped collects both kinds.
var skipped []batch.TaskResult
written, err := run.DownloadToDir(ctx, "./out", batch.DownloadToDirOptions{Skipped: &skipped})
check(err)
fmt.Println("downloaded", written, "skipped", len(skipped))

// Retry what failed. Every rerun's task rows are written in the background (the API answers
// 202); WaitForIngest returns once they are, so the new run's results pages are complete.
retry, err := job.RetryFailed(ctx, batch.RetryFailedOptions{IncludePending: true, WaitForIngest: true})
check(err)
fmt.Println("retrying in run", retry.RunID())

// Estimate credit cost before submitting (pure, no network call).
estimate := client.EstimateCost([]batch.Task{{URL: "https://example.com"}}, nil)
fmt.Println(estimate) // "1 credits (1 tasks)"

Webhooks

Set a job's webhook at submit time (Webhook in the submit options) or later with JobRef.SetWebhook(ctx, url, signature) / Client.SetJobWebhook(ctx, jobID, url, signature). The signing choice is a required argument, so changing only the URL can't turn signing off. Client.SetJobWebhookURL(ctx, jobID, url) changes only the URL and keeps the current signing choice (off when the job has no webhook yet). PutJobWebhook is deprecated: a WebhookConfig without Signature set sends false.

A job's webhook gets one event when a run completes or fails on its own (WebhookEventRunCompleted or WebhookEventRunFailed); stopping a run sends none. Each attempt times out after 10 seconds, and delivery is retried with backoff for up to 3 days, so an event can arrive more than once: dedupe on WebhookEvent.EventID (also the X-ZenRows-Event-Id header).

Verifying a signature

When signing is on, check the X-Signature header before trusting the body. Pass the body exactly as received, and the HMAC secret exactly as the API returned it when you created the key (a base64 string; VerifyWebhookSignature decodes it), keyed by its key id. Keep the old and new secrets during a key rotation.

func handleWebhook(w http.ResponseWriter, r *http.Request) {
    body, err := io.ReadAll(r.Body)
    if err != nil {
        http.Error(w, "bad body", http.StatusBadRequest)
        return
    }
    secrets := map[string]string{"YOUR_KEY_ID": "YOUR_BASE64_SECRET"}
    if err := batch.VerifyWebhookSignature(body, r.Header.Get(batch.SignatureHeader), secrets, batch.VerifyWebhookSignatureOptions{}); err != nil {
        http.Error(w, "invalid signature", http.StatusUnauthorized)
        return
    }
    var event batch.WebhookEvent
    if err := json.Unmarshal(body, &event); err != nil {
        http.Error(w, "bad json", http.StatusBadRequest)
        return
    }
    // Deliveries can repeat: dedupe on event.EventID.
    w.WriteHeader(http.StatusNoContent)
}

VerifyWebhookSignature rejects a signature whose timestamp is more than 5 minutes from now (VerifyWebhookSignatureOptions.Tolerance changes that, SkipTimestampCheck turns it off).

Extract in a batch

Set extract in ZenRowsParams to run tasks through Extract, which returns structured data instead of raw HTML. It works job-wide or per task; a task's params are merged over the job's, and the task's value wins on a collision. A task can't switch off a job-level extract, so to mix Extract and raw-HTML tasks in one job, set extract on just the tasks that need it:

job, err := client.SubmitRegular(ctx, batch.SubmitRegularOptions{
    Tasks: []batch.Task{
        // Runs through Extract.
        {URL: "https://example.com/products", ExternalID: "p1", ZenRowsParams: map[string]any{"extract": "auto"}},
        // Returns the raw page.
        {URL: "https://example.com/raw"},
    },
})
if err != nil {
    log.Fatal(err)
}
fmt.Println("submitted", job.JobID())

An Extract task's result carries two keys — html (the raw page) and parsed (the structured data). It costs the same as a regular task, so EstimateCost prices it correctly. extract_fields narrows the returned fields, as on a single Extract request.

Client Initialization

Configure the client with WithAPIKey or the ZENROWS_API_KEY environment variable, and optionally WithBaseURL (defaults to https://async.api.zenrows.com/v1), WithTimeout (how long one request may take; no limit unless set) and WithRetries (defaults to 3: transient failures, 429/502/503/504 and network errors, are retried on idempotent requests, and on POSTs that carry an Idempotency-Key, with jittered exponential backoff honoring Retry-After, capped at 30 seconds). A 429 quota_exceeded is an account limit, not a transient one, so it is returned at once.

Resource handles

  • JobRef (Client.Job(id), or returned by Submit*) — Load, Close, Delete, Rerun, RetryFailed, AddTasks/AddTasksWithOptions, Runs (paginated), AddFileInput, GetWebhook/SetWebhook/ DeleteWebhook, WaitForIngest, plus the Run() and Schedule() facets below. JobHandle adds a loaded .Data Job snapshot (from GetJob / IterJobs / mutating ops).
  • CurrentRun (jobRef.Run()) — Pause/Resume/Stop/Cancel, Wait, Results (paginated), TaskHistory, DownloadToDir/DownloadToMemory, StartExport, DownloadAllResults. Always resolves to the job's latest run.
  • ScheduleControls (jobRef.Schedule()) — Pause/Resume/Update (scheduled jobs only).
  • RunRef (Client.Run(jobID, runID)) — same shape as CurrentRun but for one specific (usually historical) run; no Pause/Stop (the API only suspends the current run). RunHandle adds .Data Run, .Status(), .Stats().
  • ExportRef (run.StartExport() / run.Export(id)) — Load, Wait, DownloadToPath. ExportHandle adds .Data Export, .Status().

Mutating handle methods always return a fresh handle carrying the server's new state — none of them mutate the receiver in place.

Client-level methods

Submit: SubmitJob (low-level), SubmitRegular, SubmitOpen, SubmitScheduled, EstimateCost. Jobs: ListJobs/IterJobs, GetJob, DeleteJob, AddTasks/AddTasksWithOptions, CloseJob, StopRun, Rerun, WaitForRun, WaitForIngest. Runs: ListRuns/IterRuns, GetRun, DeleteRun. Results: GetResults/IterResults (leave RunID empty for the latest run), GetTaskContent, GetTaskHistory. Downloads: DownloadToDir, DownloadToMemory (concurrency-limited, with max_files/max_bytes_per_file/max_count/max_total_bytes safety caps). Webhooks: GetJobWebhook/SetJobWebhook/SetJobWebhookURL/DeleteJobWebhook/TestWebhook (PutJobWebhook is deprecated), plus the package-level VerifyWebhookSignature and WebhookEvent for receivers. HMAC signing keys: ListHMACKeys/RotateHMACKey/FinalizeHMACKey/CancelHMACRotation. CSV task input: CreateJobInput/UploadCSV. Results export: StartResultsExport/GetResultsExport/ WaitForExport/DownloadAllResults.

Error Handling

  • NotConfiguredError: the client is missing an API key.

  • APIError: a non-2xx response. StatusCode carries the HTTP status; Detail carries the parsed RFC 9457 problem JSON body when the response could be decoded as such; .Code() returns the stable problem code, or "internal" if the body wasn't parseable. Compare it with the Code* constants (codes.go), keeping a default branch for codes added later:

    Code Status Meaning
    CodeUnauthenticated 401 Missing or invalid API key.
    CodeSubscriptionInactive 401 The key is valid but the subscription isn't active (for example past due). Check Billing.
    CodePaymentRequired 402 Out of credits.
    CodeAPIKeyCapReached 402 The API key reached one of its credit caps; Detail.Detail names the cap and when it resets (UTC).
    CodeQuotaExceeded 429 An account limit: 3 active jobs (shared with Crawl), 5 scheduled jobs, or an open job's 100,000-task cap. Not retried.
    CodeIdempotencyKeyConflict 409 The Idempotency-Key was reused with a different body, or the first call is still running.
    CodePartialRerunWindowExpired 409 A partial rerun came more than 10 days after the run it retries; a full rerun still works.
    CodeResultExpired 410 The task's result is past its retention window (14 days by default).
    CodeInvalidArgument 400 Validation failed; per-task reasons are in Detail.InvalidTasks.
  • A run that stops for an account reason ends RunStatusFailed (not an error from the waiter) with FailureReason (FailureReasonInsufficientCredits, FailureReasonSubscriptionInactive, FailureReasonAPIKeyCapReached) and a human-readable FailureDetail.

  • RunPausedError: a run waiter found the run paused. Resume it, or set WaitForRunOptions.WaitThroughPause to keep polling.

  • WaiterTimeoutError: a waiter ran out of its own timeout. The run itself is unaffected.

  • String enums on responses (JobStatus, RunStatus, TaskStatus, ResultType, IngestStatus, FailureReason, ExportStatus, RunTrigger) are extensible: the server may return values this SDK has no constant for. They decode without error, so always handle a default case; each type's IsKnown() reports whether a value is one this SDK version defines.

Examples

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package batch is a client for the Zenrows Batch API — an asynchronous batch web-scraping service. Submit a job containing many URLs; the API scrapes each one, tracks progress, and serves the results back to you.

A Job is a template — a reusable submission with its configuration. A Run is one execution of that template; a job has 1+ runs over its lifetime. A Task is one URL within one run.

The main entry point is Client (via NewClient). For most submissions prefer the type-specific SubmitRegular / SubmitOpen / SubmitScheduled over the low-level SubmitJob. Job(id) / Run(jobID, runID) mint zero-network-call resource handles with chainable lifecycle operations (Close, Rerun, AddTasks, Run().Pause(), Schedule().Update(), ...) — see resources.go. EstimateCost prices a job client-side before you submit it.

Index

Constants

View Source
const (

	// CodeInvalidArgument (400): the request failed validation. Per-task reasons, when there
	// are any, are in Problem.InvalidTasks.
	CodeInvalidArgument = "invalid_argument"
	// CodeNotFound (404): the job, run, task or export doesn't exist or isn't yours.
	CodeNotFound = "not_found"
	// CodeConflict (409): a generic state conflict.
	CodeConflict = "conflict"
	// CodeUnauthenticated (401): the API key is missing or invalid.
	CodeUnauthenticated = "unauthenticated"
	// CodeSubscriptionInactive (401): the key is valid, but the subscription isn't active
	// (for example past due). Paying fixes it.
	CodeSubscriptionInactive = "subscription_inactive"
	// CodePaymentRequired (402): the account is out of credits.
	CodePaymentRequired = "payment_required"
	// CodeAPIKeyCapReached (402): the API key reached one of its credit caps. The key works
	// again when the cap's window resets, or when the cap is raised.
	CodeAPIKeyCapReached = "api_key_cap_reached" //nolint:gosec // an error code, not a credential
	// CodePermissionDenied (403): the account can't use this feature.
	CodePermissionDenied = "permission_denied"
	// CodeQuotaExceeded (429): an account limit was reached: active jobs (shared with Crawl),
	// scheduled jobs, or the task cap of an open job. It clears only when a job finishes or is
	// deleted, so the client does not retry it.
	CodeQuotaExceeded = "quota_exceeded"
	// CodeInternal (500): a server error. APIError.Code() also returns it when the response
	// body wasn't a problem document.
	CodeInternal = "internal"
	// CodeNotImplemented (501): the operation isn't available in this deployment.
	CodeNotImplemented = "not_implemented"

	// CodeJobNotOpen (409): the job no longer accepts tasks.
	CodeJobNotOpen = "job_not_open"
	// CodeLastBatchReceived (409): the job's last batch was already sent.
	CodeLastBatchReceived = "last_batch_received"
	// CodeRunNotTerminal (409): the run must finish (or be stopped) first.
	CodeRunNotTerminal = "run_not_terminal"
	// CodeRunNotStoppable (409): the run is in a state that can't be stopped or paused.
	CodeRunNotStoppable = "run_not_stoppable"
	// CodeNoPriorRun (409): the job has no run to rerun.
	CodeNoPriorRun = "no_prior_run"
	// CodeNoMatchingTasks (409): a partial rerun's status filter matched no task.
	CodeNoMatchingTasks = "no_matching_tasks"
	// CodePartialRerunWindowExpired (409): a partial rerun (a Status filter) came more than 10
	// days after the start of the run it retries. A full rerun still works.
	CodePartialRerunWindowExpired = "partial_rerun_window_expired"
	// CodeRunHasDescendants (409): later runs still reuse this run's results.
	CodeRunHasDescendants = "run_has_descendants"
	// CodeIdempotencyKeyConflict (409): the Idempotency-Key was used with a different body, or
	// the first call with it is still running.
	CodeIdempotencyKeyConflict = "idempotency_key_conflict"
	// CodeTaskNotReady (409): the task has no result yet.
	CodeTaskNotReady = "task_not_ready"
	// CodeResultExpired (410): the task's result is past its retention window (14 days by
	// default). The row reads as TaskStatusExpired.
	CodeResultExpired = "result_expired"

	// CodeCandidatePending (409): a rotation is already staged; finalize or cancel it first.
	CodeCandidatePending = "candidate_pending"
	// CodeNoCandidate (409): there is no staged rotation to finalize or cancel.
	CodeNoCandidate = "no_candidate"

	CodeUnsupportedScheme  = "unsupported_scheme"
	CodeMalformedURL       = "malformed_url"
	CodeMissingHost        = "missing_host"
	CodeURLTooLong         = "url_too_long"
	CodeMetadataTooLarge   = "metadata_too_large"
	CodeMetadataKeyInvalid = "metadata_key_invalid"
	CodeInvalidExternalID  = "invalid_external_id"

	CodeUnsupportedMethod   = "unsupported_method"
	CodeBodyNotAllowed      = "body_not_allowed"
	CodeBodyTooLarge        = "body_too_large"
	CodeBodyMalformed       = "body_malformed"
	CodeMethodParamConflict = "method_param_conflict"

	CodeFileInputNotFound              = "file_input_not_found"
	CodeFileInputNotUploaded           = "file_input_not_uploaded"
	CodeFileInputUnsupportedForJobType = "file_input_unsupported_for_job_type"

	CodeCallbackURLMustBeHTTPS          = "callback_url_must_be_https"
	CodeCallbackURLUnresolvable         = "callback_url_unresolvable"
	CodeWebhookSigningRequiresActiveKey = "webhook_signing_requires_active_key"

	// CodeGatewayUnreachable: a task's scrape couldn't reach the scraping API.
	CodeGatewayUnreachable = "gateway_unreachable"
)

Error codes the Batch API sets in a problem's `code` member. Compare them with APIError.Code() (or Problem.Code, or an InvalidTasks entry's code). The API may add codes, so keep a default branch.

View Source
const (
	DefaultMaxFiles              = 100_000
	DefaultMaxBytesPerFile       = 50 * 1024 * 1024 // 50 MiB
	DefaultMaxCountInMemory      = 10_000
	DefaultMaxTotalBytesInMemory = 500 * 1024 * 1024 // 500 MiB

)

Safety caps. Deliberate, conservative defaults — bulk downloads of scraping jobs can easily reach gigabytes if not bounded.

View Source
const (
	BaseCredits         = 1
	JSCredits           = 5
	PremiumProxyCredits = 10
	JSAndProxyCredits   = 25
	AutoMinCredits      = 1
	AutoMaxCredits      = 25
)

Credits charged per billed request, by configuration. A successful request is billed, and so is a target that answers 404 or 410 (the task still ends as failed). mode=auto is charged after the fact, anywhere in the Auto range.

View Source
const (
	// WebhookEventRunCompleted is sent when a run finishes its tasks.
	WebhookEventRunCompleted = "run.completed"
	// WebhookEventRunFailed is sent when a run ends failed for an account reason; FailureReason
	// and FailureDetail say why.
	WebhookEventRunFailed = "run.failed"
	// WebhookEventTest is the synthetic event TestWebhook sends.
	WebhookEventTest = "webhook.test"
)

Webhook event types (WebhookEvent.EventType).

View Source
const DefaultWebhookTolerance = 5 * time.Minute

DefaultWebhookTolerance is how far a signature's timestamp may be from the current time before VerifyWebhookSignature rejects it as a possible replay.

View Source
const EventIDHeader = "X-ZenRows-Event-Id"

EventIDHeader carries a webhook delivery's event id. Deliveries can repeat (a retry after a slow or failed response), so dedupe on it.

View Source
const SignatureHeader = "X-Signature"

SignatureHeader is the request header that carries a signed webhook's signature, in the form "t=<unix seconds>,v1=<hex HMAC-SHA256>,kid=<key id>".

Variables

View Source
var (
	ErrWebhookSignatureMalformed  = errors.New("batch: webhook signature header is malformed")
	ErrWebhookUnknownKey          = errors.New("batch: webhook signed with a key id that has no secret")
	ErrWebhookSignatureMismatch   = errors.New("batch: webhook signature does not match the body")
	ErrWebhookTimestampOutOfRange = errors.New("batch: webhook signature timestamp is outside the tolerance")
	ErrWebhookSecretMalformed     = errors.New("batch: webhook secret is not a base64-encoded 32-byte key")
)

Errors VerifyWebhookSignature returns. Match them with errors.Is.

TerminalExportStatuses are the export statuses that don't transition again. The default target for WaitForExport.

TerminalRunStatuses are the statuses a run never transitions out of. The default target for WaitForRun. RunStatusFailed is an account-level auto-fail (e.g. FailureReasonAPIKeyCapReached); the waiter returns that run with its FailureReason and FailureDetail rather than polling until the timeout.

Functions

func VerifyWebhookSignature added in v1.1.0

func VerifyWebhookSignature(rawBody []byte, signatureHeader string, secrets map[string]string, opts VerifyWebhookSignatureOptions) error

VerifyWebhookSignature checks a signed webhook delivery. rawBody must be the request body exactly as received (before any JSON decoding), and signatureHeader the value of the X-Signature header. secrets maps each HMAC key id to its secret as the API returned it when the key was created (RotateHMACKey): a base64 string that decodes to 32 bytes. The secret is decoded before use; any other secret, including "", is rejected with ErrWebhookSecretMalformed and never verifies. Keep both the old and the new key during a rotation; the header's kid picks the one that signed. The signature is compared in constant time. Returns nil when the signature is valid, and otherwise an error that matches one of the ErrWebhook* sentinels under errors.Is.

Types

type APIError

type APIError struct {
	StatusCode int
	Detail     *ProblemDetail
	Body       []byte
}

APIError wraps a non-2xx response from the Batch API. The API returns RFC 7807 Problem JSON bodies; Detail carries the parsed body when it could be decoded as such (nil when the server returned something else, e.g. an edge-proxy HTML error page).

func (APIError) Code

func (e APIError) Code() string

Code is the RFC 7807 `code` member (e.g. "file_input_not_found", "idempotency_key_conflict"), or "internal" when the body couldn't be parsed as Problem JSON. Stable; safe to branch on.

func (APIError) Error

func (e APIError) Error() string

type AddTasksOptions added in v1.1.0

type AddTasksOptions struct {
	// LastBatch closes the job as part of this call.
	LastBatch bool
	// IdempotencyKey (up to 128 characters) makes the call safe to retry. Once the first call
	// has finished, a retry with the same key and the same body, within the key's 24-hour
	// lifetime, returns the original response instead of appending the tasks again. The API
	// checks the key right after confirming the job exists and is yours, before any check on
	// the job's state, so the replay comes back even if the job has since been closed. A retry
	// with a different body, or one sent while the first call is still running, gets a 409
	// idempotency_key_conflict. With a key set, transient failures are retried automatically.
	IdempotencyKey string
}

AddTasksOptions configures Client.AddTasksWithOptions / JobRef.AddTasksWithOptions.

type AddTasksResponse

type AddTasksResponse struct {
	AcceptedTasks int       `json:"accepted_tasks"`
	JobStatus     JobStatus `json:"job_status"`
	LatestRun     *Run      `json:"latest_run,omitempty"`
}

AddTasksResponse is the response for Client.AddTasks.

type At

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

At is a one-shot schedule fire at a specific wall-clock time. Build with NewAt.

func NewAt

func NewAt(at, timezone string) (At, error)

NewAt builds a one-shot schedule fire at a tz-naive ISO timestamp (no "Z", no offset — the timezone param is the single authoritative interpreter, which keeps DST transitions deterministic).

func NewAtTime

func NewAtTime(at time.Time, timezone string) (At, error)

NewAtTime is NewAt for a time.Time value — formatted as a naive ISO timestamp ("2006-01-02T15:04:05"), dropping any location info. Pass the wall-clock time you want in the schedule's timezone, not a UTC-converted one.

type CSVFields

type CSVFields struct {
	URL        any `json:"url"`
	ExternalID any `json:"external_id,omitempty"`
}

CSVFields maps canonical task fields to CSV columns — a column index (int) or column name (string, requires Header: true). Only URL (required) and ExternalID (optional) are accepted.

type CSVSpec

type CSVSpec struct {
	Delimiter string    `json:"delimiter,omitempty"`
	Quote     string    `json:"quote,omitempty"`
	Header    bool      `json:"header,omitempty"`
	Fields    CSVFields `json:"fields"`
}

CSVSpec configures how an uploaded CSV maps to task fields.

type Cadence

type Cadence interface {
	// contains filtered or unexported methods
}

Cadence is a Calendar schedule's day-selection policy — Daily, Weekly, or Monthly.

type Calendar

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

Calendar is a calendar-style schedule fire policy: a list of times-of-day on a daily/weekly/monthly cadence. Build with NewCalendar.

func NewCalendar

func NewCalendar(timesOfDay []string, cadence Cadence, timezone string) (Calendar, error)

NewCalendar builds a calendar schedule. timesOfDay are full-hour 24h strings ("09:00", not "09:30"); cadence is exactly one of Daily{}, a Weekly, or a Monthly; timezone is mandatory (IANA name).

type Client

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

Client is the Zenrows Batch API client.

func NewClient

func NewClient(opts ...Option) *Client

NewClient creates and returns a new Zenrows Batch API client.

func (*Client) AddTasks

func (c *Client) AddTasks(ctx context.Context, jobID string, tasks []Task, lastBatch bool) (*AddTasksResponse, error)

AddTasks appends tasks to an open job's initial run. Fails once the job has been closed. Pass lastBatch=true to close the job as part of this call.

func (*Client) AddTasksWithOptions added in v1.1.0

func (c *Client) AddTasksWithOptions(ctx context.Context, jobID string, tasks []Task, opts AddTasksOptions) (*AddTasksResponse, error)

AddTasksWithOptions is AddTasks with an Idempotency-Key. Without a key every call appends its tasks, so a call whose response was lost can't be retried safely.

func (*Client) CancelHMACRotation

func (c *Client) CancelHMACRotation(ctx context.Context) error

CancelHMACRotation discards the pending rotation candidate.

func (*Client) CloseJob

func (c *Client) CloseJob(ctx context.Context, jobID string) (*Job, error)

CloseJob signals that no more tasks are coming for an open job.

func (*Client) CreateJobInput

func (c *Client) CreateJobInput(ctx context.Context, req CreateJobInputRequest) (*CreateJobInputResponse, error)

CreateJobInput allocates a CSV upload slot (POST /job_inputs). Most callers want the higher-level UploadCSV instead.

func (*Client) DeleteJob

func (c *Client) DeleteJob(ctx context.Context, jobID string) error

DeleteJob deletes a job and all its artifacts. Deletion is asynchronous server-side.

func (*Client) DeleteJobWebhook

func (c *Client) DeleteJobWebhook(ctx context.Context, jobID string) error

DeleteJobWebhook clears the job's webhook config. Idempotent: succeeds whether or not one was set.

func (*Client) DeleteRun

func (c *Client) DeleteRun(ctx context.Context, jobID, runID string) error

DeleteRun deletes one run and its artifacts. Deletion is asynchronous server-side.

func (*Client) DownloadAllResults

func (c *Client) DownloadAllResults(ctx context.Context, jobID, runID, targetPath string, opts DownloadAllResultsOptions) (string, error)

DownloadAllResults is an end-to-end helper: start an export, wait for it, and save the zip to targetPath. Steps: (1) start the export, (2) poll until completed or failed, (3) on completed, stream the presigned URL to targetPath.

Returns a WaiterTimeoutError if the export doesn't reach a terminal state within WaitTimeout. Returns an APIError with the server's error message on status=failed. The server caps the total size of one export; for a run over the cap (or for one file per task), use DownloadToDir instead. It fetches each body client-side, so the export cap doesn't apply, at the cost of being slower; its own MaxFiles and MaxBytesPerFile limits (100,000 files and 50 MiB per file by default, both configurable) still do.

func (*Client) DownloadToDir

func (c *Client) DownloadToDir(ctx context.Context, jobID, targetDir string, opts DownloadToDirOptions) (int, error)

DownloadToDir streams every (matching) task's body into targetDir. Returns the count written. Failed and expired rows have no body and are skipped; see DownloadToDirOptions.Skipped. Concurrency parallelizes the body-fetch + write; with the default 1, behavior is exactly serial. Results are NOT guaranteed to be in any particular order when Concurrency > 1.

func (*Client) DownloadToMemory

func (c *Client) DownloadToMemory(ctx context.Context, jobID string, opts DownloadToMemoryOptions) ([]DownloadedResult, error)

DownloadToMemory loads every (matching) task body into a slice and returns it. Failed and expired rows have no body and are skipped; see DownloadToMemoryOptions.Skipped. Three independent caps that all return DownloadLimitExceededError: MaxCount (row count), MaxTotalBytes (running sum of body sizes), MaxBytesPerFile (any single oversize body aborts). Returned slice ordering is NOT guaranteed when Concurrency > 1.

func (*Client) EstimateCost

func (c *Client) EstimateCost(tasks []Task, zenrowsParams map[string]any) CostEstimate

EstimateCost estimates the credit cost of a job before submitting it, assuming every task succeeds once. Takes the same tasks/zenrowsParams you'd hand a submit call, so you estimate the exact job you're about to submit. Pure — no network call. See EstimateCost (the package-level function in estimate.go) for the exact rate card.

func (*Client) FinalizeHMACKey

func (c *Client) FinalizeHMACKey(ctx context.Context) (*HMACKeyFinalized, error)

FinalizeHMACKey promotes the pending rotation candidate to active.

func (*Client) GetJob

func (c *Client) GetJob(ctx context.Context, jobID string) (JobHandle, error)

GetJob fetches a job (template + latest_run projection) by id and returns a loaded JobHandle.

func (*Client) GetJobWebhook

func (c *Client) GetJobWebhook(ctx context.Context, jobID string) (*WebhookConfig, error)

GetJobWebhook returns the job's current webhook config. Returns an APIError (404) when none is set.

func (*Client) GetResults

func (c *Client) GetResults(ctx context.Context, jobID string, opts GetResultsOptions) (*GetResultsResponse, error)

GetResults pages through per-task results. Leave opts.RunID empty to page the job's latest run. For most uses prefer the auto-paginating IterResults.

func (*Client) GetResultsExport

func (c *Client) GetResultsExport(ctx context.Context, jobID, runID, exportID string) (ExportHandle, error)

GetResultsExport snapshots one export. Returns a loaded ExportHandle. A 404 covers both "no such id" and "TTL-swept".

func (*Client) GetRun

func (c *Client) GetRun(ctx context.Context, jobID, runID string) (RunHandle, error)

GetRun fetches one run of a job by id and returns a loaded RunHandle.

func (*Client) GetTaskContent

func (c *Client) GetTaskContent(ctx context.Context, jobID, taskID string, opts GetTaskContentOptions) ([]byte, error)

GetTaskContent fetches the scraped content for one task. Leave opts.RunID empty for the job's latest run. The returned bytes are the raw scraped content (HTML, JSON, etc.) — unlike other methods here, this is not decoded as JSON.

func (*Client) GetTaskHistory

func (c *Client) GetTaskHistory(ctx context.Context, jobID, taskID, runID string) (*TaskHistoryResponse, error)

GetTaskHistory returns the attempt history for one task. Leave runID empty for the job's latest run.

func (*Client) IterJobs

func (c *Client) IterJobs(ctx context.Context, opts ListJobsOptions) iter.Seq2[Job, error]

IterJobs auto-paginates ListJobs, yielding (Job, error) pairs. Stops (without yielding a further error) once the pages are exhausted; a non-nil error from the sequence should stop the range loop.

func (*Client) IterResults

func (c *Client) IterResults(ctx context.Context, jobID string, opts GetResultsOptions) iter.Seq2[TaskResult, error]

IterResults auto-paginates GetResults, yielding (TaskResult, error) pairs.

func (*Client) IterRuns

func (c *Client) IterRuns(ctx context.Context, jobID string, opts ListRunsOptions) iter.Seq2[Run, error]

IterRuns auto-paginates ListRuns for jobID, yielding (Run, error) pairs.

func (*Client) Job

func (c *Client) Job(jobID string) JobRef

Job returns a JobRef for an existing job with no network call. Lifecycle operations act on the id directly. Prefer this over GetJob when you just want to act on a known id.

func (*Client) ListHMACKeys

func (c *Client) ListHMACKeys(ctx context.Context) (*HMACKeyList, error)

ListHMACKeys lists the org's current HMAC key slots (active/candidate metadata — never the secret; that's only returned by RotateHMACKey).

func (*Client) ListJobs

func (c *Client) ListJobs(ctx context.Context, opts ListJobsOptions) (*ListJobsResponse, error)

ListJobs lists jobs for the authenticated caller, newest first. For most uses prefer the auto-paginating IterJobs.

func (*Client) ListRuns

func (c *Client) ListRuns(ctx context.Context, jobID string, opts ListRunsOptions) (*ListRunsResponse, error)

ListRuns lists runs of a job, newest first. For most uses prefer the auto-paginating IterRuns.

func (*Client) PutJobWebhook deprecated

func (c *Client) PutJobWebhook(ctx context.Context, jobID string, config WebhookConfig) (*WebhookConfig, error)

PutJobWebhook replaces the job's webhook config wholesale and always sends config.Signature, so a WebhookConfig without Signature set sends false and turns HMAC signing off. Returns the persisted config.

Deprecated: use SetJobWebhook (or JobRef.SetWebhook), which takes the signing choice as a required argument so it can't be left out by accident, or SetJobWebhookURL, which keeps the current signing choice.

func (*Client) Rerun

func (c *Client) Rerun(ctx context.Context, jobID string, opts RerunOptions) (*RerunJobResponse, error)

Rerun starts a new run of a job — a full replay (opts.Status == "") or a partial retry (opts.Status is a comma-separated status filter like "failed" or "failed,pending"). Every rerun is accepted asynchronously (202): the new run's task rows are written in the background, and until LatestRun.IngestStatus is done its results pages are partial. Set opts.WaitForIngest to return only once they are written. If that wait fails, the response is still returned with the error.

func (*Client) RotateHMACKey

func (c *Client) RotateHMACKey(ctx context.Context) (*HMACKeyCreated, error)

RotateHMACKey generates the initial key or stages a rotation candidate. Capture the returned Secret NOW — it is not revealed again.

func (*Client) Run

func (c *Client) Run(jobID, runID string) RunRef

Run returns a RunRef for an existing run with no network call — the run counterpart of Job. Addresses a specific historical run by (jobID, runID); for the current run use JobRef.Run().

func (*Client) SetJobWebhook added in v1.1.0

func (c *Client) SetJobWebhook(ctx context.Context, jobID, url string, signature bool) (*WebhookConfig, error)

SetJobWebhook replaces the job's webhook config wholesale. The API requires both the URL and the signing choice on a replace, so signature is a required argument: pass true to keep (or turn on) HMAC signing of deliveries, false to turn it off. Turning it on requires an active HMAC key (else a 400 webhook_signing_requires_active_key). Returns the persisted config.

func (*Client) SetJobWebhookURL added in v1.1.0

func (c *Client) SetJobWebhookURL(ctx context.Context, jobID, url string) (*WebhookConfig, error)

SetJobWebhookURL points the job's webhook at url and keeps its current signing choice: it reads the current config first (GetJobWebhook), and uses false when the job has none (404). Use SetJobWebhook to set both explicitly.

func (*Client) StartResultsExport

func (c *Client) StartResultsExport(ctx context.Context, jobID, runID string) (ExportRef, error)

StartResultsExport kicks off an async zip of every task body in the run. Returns an ExportRef carrying the just-issued export id; failure modes: 404 if the job/run is missing or not yours. The server fails the export (status=failed, error="results are larger than N gb") if the run's total body size exceeds its export size cap.

func (*Client) StopRun

func (c *Client) StopRun(ctx context.Context, jobID string) (*Run, error)

StopRun terminally stops the current run of a job.

func (*Client) SubmitJob

func (c *Client) SubmitJob(ctx context.Context, jobReq SubmitJobRequest) (*SubmitJobResponse, error)

SubmitJob submits a new scraping job. Nothing is created if the request fails validation — retrying is safe. Most callers prefer the type-specific SubmitRegular / SubmitOpen / SubmitScheduled, which build this request and return a JobRef.

func (*Client) SubmitOpen

func (c *Client) SubmitOpen(ctx context.Context, opts SubmitOpenOptions) (JobRef, error)

SubmitOpen submits a streaming-style job that stays open for more tasks. Created with status=open — Tasks can be empty and tasks added later via JobRef.AddTasks. Close the job with JobRef.Close once done. File-input upload is not supported here (the server only accepts CSV inputs for closed regular jobs and scheduled jobs).

func (*Client) SubmitRegular

func (c *Client) SubmitRegular(ctx context.Context, opts SubmitRegularOptions) (JobRef, error)

SubmitRegular submits a one-shot scraping job (closed, all tasks upfront). Tasks and FileInputID are mutually exclusive — exactly one must be set. The job is created with status=closed, so no further AddTasks calls are accepted; for the open-and-extend pattern see SubmitOpen.

func (*Client) SubmitScheduled

func (c *Client) SubmitScheduled(ctx context.Context, opts SubmitScheduledOptions) (JobRef, error)

SubmitScheduled submits a scheduled job. opts.Schedule is one of the typed builders (At, Rate, Calendar — see NewAt/NewRate/NewCalendar), which validate their inputs the same way the server does. Tasks and FileInputID are mutually exclusive, same as SubmitRegular. The submit creates no run, so the returned job has no latest run and there is nothing to wait for: the first fire creates run 1. Use JobRef.Run().Wait after a fire.

func (*Client) TestWebhook

func (c *Client) TestWebhook(ctx context.Context, req TestWebhookRequest) (*TestWebhookResponse, error)

TestWebhook dispatches a synthetic webhook.test event to a receiver URL and reports the outcome, without touching any job. Handy to verify a receiver before wiring it to a job. req.Signature defaults to false; set true to exercise the HMAC path (requires an active signing key, else a 400 webhook_signing_requires_active_key error).

func (*Client) UploadCSV

func (c *Client) UploadCSV(ctx context.Context, source any, opts UploadCSVOptions) (string, error)

UploadCSV allocates a CSV slot and PUTs the body to the presigned URL the server returns. Returns the file_input_id to pass to SubmitRegular/SubmitScheduled's FileInputID.

source may be a file path or an io.Reader. The presigned URL lives on a different host (object storage) — this deliberately uses a bare HTTP client so the API key never leaks there.

func (*Client) WaitForExport

func (c *Client) WaitForExport(ctx context.Context, jobID, runID, exportID string, opts WaitForExportOptions) (Export, error)

WaitForExport blocks until an export reaches a terminal state (defaults to {completed, failed}). Returns the Export snapshot — callers check .Status and (on completed) .DownloadURL. "failed" is NOT treated as an error here; the caller decides whether a failure (for example, Error saying the run's results are larger than the export size cap) is fatal or expected.

func (*Client) WaitForIngest

func (c *Client) WaitForIngest(ctx context.Context, jobID string, opts WaitForIngestOptions) (Job, error)

WaitForIngest blocks until the current run's async-carrier ingestion has finished writing task rows. Large submissions return 202 Accepted and stream task rows into storage off the request path; until that finishes, results pages may be partial and AddTasks on an open job is rejected with 409. Runs that never ingested asynchronously are done on the first poll. A run stopped mid-ingest is waited on until the API marks its ingestion done.

func (*Client) WaitForRun

func (c *Client) WaitForRun(ctx context.Context, jobID string, opts WaitForRunOptions) (Run, error)

WaitForRun blocks until a run reaches one of opts.TargetStatuses, polling with jittered exponential backoff. A paused run that hasn't reached a target status ends the wait at once: it returns that run with a RunPausedError (see WaitForRunOptions.WaitThroughPause).

type CostEstimate

type CostEstimate struct {
	TaskCount int
	Min       int
	Max       int
	Breakdown []CostLine
}

CostEstimate is the result of Client.EstimateCost — credits assuming every task succeeds once. Exact() is true when no task uses mode=auto.

func EstimateCost

func EstimateCost(tasks []Task, zenrowsParams map[string]any) CostEstimate

EstimateCost estimates the credit cost of a job before submitting it, assuming every task succeeds once. Pure and offline, no network call. Each task's params are the job-level zenrowsParams with the task's own ZenRowsParams merged over them (the task wins on a key collision), the same merge the API applies.

file_input_id-based jobs estimate as zero tasks (Tasks is empty) — the CSV row count isn't known client-side.

func (CostEstimate) AutoTasks

func (e CostEstimate) AutoTasks() int

AutoTasks is how many tasks use mode=auto — the only source of range.

func (CostEstimate) Exact

func (e CostEstimate) Exact() bool

Exact is true when the charge is a single number (no auto tasks).

func (CostEstimate) String added in v1.1.0

func (e CostEstimate) String() string

String renders the estimate on one line, e.g. "10 credits (2 tasks)", or "3-75 credits (3 tasks)" when auto tasks make it a range.

type CostLine

type CostLine struct {
	Tier    Tier
	Count   int
	UnitMin int
	UnitMax int
}

CostLine is one row of a CostEstimate's breakdown: all tasks sharing a tier, aggregated.

func (CostLine) Exact

func (l CostLine) Exact() bool

Exact is true when UnitMin == UnitMax (every task in this tier prices identically).

func (CostLine) SubtotalMax

func (l CostLine) SubtotalMax() int

SubtotalMax is Count * UnitMax.

func (CostLine) SubtotalMin

func (l CostLine) SubtotalMin() int

SubtotalMin is Count * UnitMin.

type CreateJobInputRequest

type CreateJobInputRequest struct {
	Type string   `json:"type"`
	CSV  *CSVSpec `json:"csv,omitempty"`
}

CreateJobInputRequest is the body for Client.CreateJobInput.

type CreateJobInputResponse

type CreateJobInputResponse struct {
	FileInputID string                `json:"file_input_id"`
	Upload      FileInputUploadTarget `json:"upload"`
	ExpiresAt   string                `json:"expires_at"`
}

CreateJobInputResponse is the response for Client.CreateJobInput.

type CurrentRun

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

CurrentRun holds operations on a job's current run, reached via JobRef.Run(). The pause/stop family only ever targets the latest run (the API's run-less endpoints resolve it server-side), which is why they live here and not on RunRef.

func (CurrentRun) Cancel

func (cr CurrentRun) Cancel(ctx context.Context) (RunHandle, error)

Cancel is an alias for Stop.

func (CurrentRun) DownloadAllResults

func (cr CurrentRun) DownloadAllResults(ctx context.Context, targetPath string, opts DownloadAllResultsOptions) (string, error)

DownloadAllResults starts an export of the current run's results, waits for it, and saves the zip to targetPath.

func (CurrentRun) DownloadTaskToFile

func (cr CurrentRun) DownloadTaskToFile(task TaskResult, targetPath string) error

DownloadTaskToFile downloads one task's body straight from its presigned result_url.

func (CurrentRun) DownloadTaskToMemory

func (cr CurrentRun) DownloadTaskToMemory(task TaskResult) ([]byte, error)

DownloadTaskToMemory downloads one task's body straight from its presigned result_url.

func (CurrentRun) DownloadToDir

func (cr CurrentRun) DownloadToDir(ctx context.Context, targetDir string, opts DownloadToDirOptions) (int, error)

DownloadToDir streams every (matching) task body of the current run into targetDir.

func (CurrentRun) DownloadToMemory

func (cr CurrentRun) DownloadToMemory(ctx context.Context, opts DownloadToMemoryOptions) ([]DownloadedResult, error)

DownloadToMemory loads every (matching) task body of the current run into memory.

func (CurrentRun) Load

func (cr CurrentRun) Load(ctx context.Context) (RunHandle, error)

Load fetches the latest run as a loaded RunHandle.

func (CurrentRun) Pause

func (cr CurrentRun) Pause(ctx context.Context) (RunHandle, error)

Pause reversibly suspends the current run: the dispatcher stops pulling its queue (in-flight tasks may still settle). Orthogonal to Status; undo with Resume. Returns the fresh loaded RunHandle.

func (CurrentRun) Results

func (cr CurrentRun) Results(ctx context.Context, status string) iter.Seq2[TaskResult, error]

Results auto-paginates task results from the current run.

func (CurrentRun) Resume

func (cr CurrentRun) Resume(ctx context.Context) (RunHandle, error)

Resume un-pauses the current run. Returns the fresh loaded handle.

func (CurrentRun) StartExport

func (cr CurrentRun) StartExport(ctx context.Context) (ExportRef, error)

StartExport kicks off an async zip of the current run's bodies. Resolves the current run id first (one GET), then returns an ExportRef.

func (CurrentRun) Stop

func (cr CurrentRun) Stop(ctx context.Context) (RunHandle, error)

Stop terminally stops the current run. Returns the fresh loaded handle.

func (CurrentRun) TaskHistory

func (cr CurrentRun) TaskHistory(ctx context.Context, taskID string) (*TaskHistoryResponse, error)

TaskHistory returns the current-run per-attempt event log for one task.

func (CurrentRun) Wait

Wait blocks until the current run reaches a target state. Returns a loaded RunHandle.

type Daily

type Daily struct{}

Daily fires every day. No knobs.

type DownloadAllResultsOptions

type DownloadAllResultsOptions struct {
	WaitTimeout  time.Duration // defaults to 600s
	PollInterval time.Duration // defaults to 2s
	ChunkSize    int           // defaults to 1 MiB
}

DownloadAllResultsOptions configures Client.DownloadAllResults.

type DownloadLimitExceededError

type DownloadLimitExceededError struct {
	LimitName string
	Limit     int64
	Observed  int64
}

DownloadLimitExceededError is returned when a download exceeds a configured cap.

func (DownloadLimitExceededError) Error

type DownloadToDirOptions

type DownloadToDirOptions struct {
	RunID           string // set internally by RunRef/CurrentRun; leave empty at the Client level for the job's latest run
	Status          string // defaults to "successful"
	NameFn          func(TaskResult) string
	UseExternalID   bool
	Concurrency     int // defaults to 1 (serial)
	MaxFiles        int // defaults to DefaultMaxFiles
	MaxBytesPerFile int // defaults to DefaultMaxBytesPerFile
	// Skipped, when non-nil, collects the matching rows that have no body to download: a
	// failed task, or a successful one whose stored body has expired (TaskStatusExpired).
	// Such rows are skipped, appended here, and don't count toward the row cap. Any other row
	// without a ResultURL (for example a successful row the API could not sign a URL for) is
	// still an error, so a successful result never goes missing silently.
	Skipped *[]TaskResult
}

DownloadToDirOptions configures Client.DownloadToDir / RunRef.DownloadToDir / CurrentRun.DownloadToDir.

type DownloadToMemoryOptions

type DownloadToMemoryOptions struct {
	RunID           string // set internally by RunRef/CurrentRun
	Status          string // defaults to "successful"
	Concurrency     int    // defaults to 1 (serial)
	MaxCount        int    // defaults to DefaultMaxCountInMemory
	MaxTotalBytes   int64  // defaults to DefaultMaxTotalBytesInMemory
	MaxBytesPerFile int    // defaults to DefaultMaxBytesPerFile
	// Skipped, when non-nil, collects the matching rows that have no body to download: a
	// failed task, or a successful one whose stored body has expired (TaskStatusExpired).
	// Such rows are skipped, appended here, and don't count toward the row cap. Any other row
	// without a ResultURL (for example a successful row the API could not sign a URL for) is
	// still an error, so a successful result never goes missing silently.
	Skipped *[]TaskResult
}

DownloadToMemoryOptions configures Client.DownloadToMemory / RunRef.DownloadToMemory / CurrentRun.DownloadToMemory.

type DownloadedResult

type DownloadedResult struct {
	TaskID      string
	ExternalID  string
	ContentType string
	Body        []byte
}

DownloadedResult is one row's worth of downloaded content held in memory.

type Export

type Export struct {
	ExportID    string       `json:"export_id"`
	Status      ExportStatus `json:"status"`
	Error       string       `json:"error,omitempty"`
	DownloadURL string       `json:"download_url,omitempty"`
	CreatedAt   string       `json:"created_at"`
	ExpiresAt   string       `json:"expires_at"`
}

Export is the polled view of a results export.

type ExportHandle

type ExportHandle struct {
	ExportRef
	Data Export
}

ExportHandle is an ExportRef plus a guaranteed, synchronous Data snapshot.

func (ExportHandle) Status

func (h ExportHandle) Status() ExportStatus

Status is this export's status. Shortcut for Data.Status.

type ExportRef

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

ExportRef is a reference to a results export by id. A results export is async: StartResultsExport returns immediately with a pending ref; the server zips the run in the background and it reaches completed (download URL ready) or failed (with an error message (e.g. the run is over the export size cap). Call Load / Wait for an ExportHandle with data.

func (ExportRef) DownloadToPath

func (r ExportRef) DownloadToPath(ctx context.Context, targetPath string) (string, error)

DownloadToPath streams the export zip to targetPath. The export must already be completed — call Wait first, or use Client.DownloadAllResults / RunRef.DownloadAllResults for the one-shot flow. Fetches once for a fresh presigned URL (the server signs a new URL per request).

func (ExportRef) ExportID

func (r ExportRef) ExportID() string

ExportID is this export's id.

func (ExportRef) Load

func (r ExportRef) Load(ctx context.Context) (ExportHandle, error)

Load fetches the export and returns a loaded ExportHandle.

func (ExportRef) StartResponse

func (r ExportRef) StartResponse() *StartExportResponse

StartResponse is the immediate wire response from StartResultsExport, if this ref came from there (nil otherwise).

func (ExportRef) Wait

Wait blocks until the export reaches a terminal state (defaults to {completed, failed}). Returns the loaded handle.

type ExportStatus

type ExportStatus string

ExportStatus is the lifecycle state of a results export. The server may add values not listed here, and they decode as-is; callers must handle unknown values (e.g. a default branch, or IsKnown) rather than assume the constants are exhaustive.

const (
	ExportStatusPending   ExportStatus = "pending"
	ExportStatusRunning   ExportStatus = "running"
	ExportStatusCompleted ExportStatus = "completed"
	ExportStatusFailed    ExportStatus = "failed"
)

func (ExportStatus) IsKnown

func (e ExportStatus) IsKnown() bool

IsKnown reports whether e is one of the ExportStatus constants this SDK version defines.

type FailureReason

type FailureReason string

FailureReason is the account-level cause of a run auto-failing. Present only when Run.Status == RunStatusFailed; Run.FailureDetail carries a human-readable explanation. The server may add values not listed here, and they decode as-is; callers must handle unknown values (e.g. a default branch, or IsKnown) rather than assume the constants are exhaustive.

const (
	FailureReasonInsufficientCredits  FailureReason = "insufficient_credits"
	FailureReasonSubscriptionInactive FailureReason = "subscription_inactive"
	// FailureReasonAPIKeyCapReached means the job's API key reached one of its credit caps
	// (day, week, month or billing period). It resolves when that cap's window resets or the
	// cap is raised; other keys on the account are unaffected.
	FailureReasonAPIKeyCapReached FailureReason = "api_key_cap_reached" //nolint:gosec // an enum value, not a credential
)

func (FailureReason) IsKnown

func (f FailureReason) IsKnown() bool

IsKnown reports whether f is one of the FailureReason constants this SDK version defines.

type FileInputUploadTarget

type FileInputUploadTarget struct {
	Method    string            `json:"method"`
	URL       string            `json:"url"`
	Headers   map[string]string `json:"headers,omitempty"`
	ExpiresAt string            `json:"expires_at"`
}

FileInputUploadTarget is the presigned PUT target returned by CreateJobInput.

type GetResultsOptions

type GetResultsOptions struct {
	// RunID pages results for a specific run. Leave empty to page the job's latest run.
	RunID  string
	Status string
	Cursor string
	// Deprecated: the results endpoint returns fixed-size pages (about 1000 rows) and
	// ignores a page size, so this is not sent.
	Limit int
}

GetResultsOptions selects which run to page results for, plus pagination and a status filter.

type GetResultsResponse

type GetResultsResponse struct {
	Results    []TaskResult `json:"results"`
	NextCursor string       `json:"next_cursor,omitempty"`
}

GetResultsResponse is the response for Client.GetResults.

type GetTaskContentOptions

type GetTaskContentOptions struct {
	// RunID fetches content from a specific run. Leave empty for the job's latest run.
	RunID string
}

GetTaskContentOptions selects which run a task's content is fetched from.

type HMACKeyCreated

type HMACKeyCreated struct {
	Kid       string `json:"kid"`
	Secret    string `json:"secret"` //nolint:gosec // this is the actual API response field carrying the rotated HMAC secret
	CreatedAt string `json:"created_at"`
}

HMACKeyCreated is the response to RotateHMACKey. Secret is base64-encoded raw key material and is returned ONLY here — capture it now.

type HMACKeyFinalized

type HMACKeyFinalized struct {
	ActiveKid string `json:"active_kid"`
	CreatedAt string `json:"created_at"`
}

HMACKeyFinalized is the response to FinalizeHMACKey.

type HMACKeyList

type HMACKeyList struct {
	Active    *HMACKeyMeta `json:"active,omitempty"`
	Candidate *HMACKeyMeta `json:"candidate,omitempty"`
}

HMACKeyList is the org's current HMAC key slots.

type HMACKeyMeta

type HMACKeyMeta struct {
	Kid       string `json:"kid"`
	CreatedAt string `json:"created_at"`
}

HMACKeyMeta is the public view of one HMAC key — id and creation time, never the secret.

type IngestStatus

type IngestStatus string

IngestStatus reports whether a large (202) submission's task rows have finished streaming into storage. Present only on runs created that way. The server may add values not listed here, and they decode as-is; callers must handle unknown values (e.g. a default branch, or IsKnown) rather than assume the constants are exhaustive.

const (
	IngestStatusPending IngestStatus = "pending"
	IngestStatusDone    IngestStatus = "done"
)

func (IngestStatus) IsKnown

func (i IngestStatus) IsKnown() bool

IsKnown reports whether i is one of the IngestStatus constants this SDK version defines.

type InvalidTask

type InvalidTask struct {
	Index  int    `json:"index"`
	Reason string `json:"reason"`
	Value  string `json:"value,omitempty"`
}

InvalidTask describes one rejected task on a validation error.

type Job

type Job struct {
	JobID            string         `json:"job_id"`
	Type             JobType        `json:"type"`
	Status           JobStatus      `json:"status"`
	ZenRowsParams    map[string]any `json:"zenrows_params,omitempty"`
	ExternalID       string         `json:"external_id,omitempty"`
	Name             string         `json:"name,omitempty"`
	Metadata         map[string]any `json:"metadata,omitempty"`
	Schedule         *JobSchedule   `json:"schedule,omitempty"`
	NextScheduledRun string         `json:"next_scheduled_run,omitempty"`
	ScheduleState    ScheduleState  `json:"schedule_state,omitempty"`
	Webhook          *WebhookConfig `json:"webhook,omitempty"`
	LatestRun        *Run           `json:"latest_run,omitempty"`
	// Format is the body format of the job's successful task results.
	Format    ResultType `json:"format,omitempty"`
	CreatedAt string     `json:"created_at"`
	UpdatedAt string     `json:"updated_at"`
}

Job is the reusable submission template plus a projection of its latest run.

type JobHandle

type JobHandle struct {
	JobRef
	Data Job
}

JobHandle is a JobRef plus a guaranteed, synchronous Data snapshot. Returned by GetJob / IterJobs and the ops that echo fresh state (Close, Schedule().Pause, ...).

type JobRef

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

JobRef is a reference to a job by id — job-template operations, plus the Run() and Schedule() sub-facets. Minted with no network call by Client.Job, and returned by the Submit* methods (with a submit response attached). Call Load for a JobHandle with data.

func (JobRef) AcceptedTasks

func (r JobRef) AcceptedTasks() int

AcceptedTasks is how many tasks landed at submit. Only known on refs returned by a Submit* call; returns 0 otherwise.

func (JobRef) AddFileInput

func (r JobRef) AddFileInput(ctx context.Context, source any, opts UploadCSVOptions) (string, error)

AddFileInput uploads a CSV that this job would consume on a future submission. Returns the file_input_id. (File inputs aren't tied to a job at create-time, but living off the handle keeps the call site discoverable.)

func (JobRef) AddTasks

func (r JobRef) AddTasks(ctx context.Context, tasks []Task, lastBatch bool) (*AddTasksResponse, error)

AddTasks appends to the open initial run.

func (JobRef) AddTasksWithOptions added in v1.1.0

func (r JobRef) AddTasksWithOptions(ctx context.Context, tasks []Task, opts AddTasksOptions) (*AddTasksResponse, error)

AddTasksWithOptions appends to the open initial run, with an optional Idempotency-Key so a retried call doesn't append the same tasks twice (see AddTasksOptions.IdempotencyKey for when a retry replays and when it conflicts).

func (JobRef) Close

func (r JobRef) Close(ctx context.Context) (JobHandle, error)

Close locks the job (no more AddTasks). Returns the fresh loaded handle.

func (JobRef) Delete

func (r JobRef) Delete(ctx context.Context) error

Delete async hard-deletes the job.

func (JobRef) DeleteWebhook

func (r JobRef) DeleteWebhook(ctx context.Context) error

DeleteWebhook clears this job's webhook config. Idempotent.

func (JobRef) GetWebhook

func (r JobRef) GetWebhook(ctx context.Context) (*WebhookConfig, error)

GetWebhook returns this job's current webhook config. Returns an APIError (404) when none is set.

func (JobRef) JobID

func (r JobRef) JobID() string

JobID is this ref's job id.

func (JobRef) Load

func (r JobRef) Load(ctx context.Context) (JobHandle, error)

Load fetches the full job and returns a loaded JobHandle.

func (JobRef) Rerun

func (r JobRef) Rerun(ctx context.Context, opts RerunOptions) (RunHandle, error)

Rerun starts a new run. Without opts.Status: full rerun of the previous run's tasks (or, for a scheduled job with no prior run, a manual fire from the template). With opts.Status (e.g. "failed" or "failed,pending"): partial retry. Returns a RunHandle for the new run. The new run's task rows are written in the background; set opts.WaitForIngest to return once they are (see Client.Rerun).

func (JobRef) RetryFailed

func (r JobRef) RetryFailed(ctx context.Context, opts RetryFailedOptions) (RunHandle, error)

RetryFailed starts a new run that re-executes only the previous run's failed tasks (shortcut for Rerun with Status: "failed"). Requires the previous run to be terminal; returns an APIError (409 run_not_terminal) otherwise, or (409 no_matching_tasks) when nothing matched.

func (JobRef) Run

func (r JobRef) Run() CurrentRun

Run returns the CurrentRun facet — operations on this job's current run (Pause/Resume/ Stop/Wait/Results/downloads/StartExport).

func (JobRef) Runs

Runs auto-paginates runs of this job, yielding (RunHandle, error) pairs. To address a specific run by id use Client.Run; for the current run use JobRef.Run().

func (JobRef) Schedule

func (r JobRef) Schedule() ScheduleControls

Schedule returns the ScheduleControls facet — operations on this job's schedule (scheduled jobs only).

func (JobRef) SetWebhook

func (r JobRef) SetWebhook(ctx context.Context, url string, signature bool) (*WebhookConfig, error)

SetWebhook replaces this job's webhook config. Both arguments are required, so a change of URL can't silently turn signing off. See Client.SetJobWebhook.

func (JobRef) Status

func (r JobRef) Status() JobStatus

Status is the job status from the submit response. Only known on refs returned by a Submit* call (zero value otherwise) — Load for a JobHandle whose .Status reads the fetched data.

func (JobRef) WaitForIngest

func (r JobRef) WaitForIngest(ctx context.Context, opts WaitForIngestOptions) (JobHandle, error)

WaitForIngest blocks until the current run's async-carrier ingestion has finished writing task rows. Returns the fresh loaded handle, so chains like job.WaitForIngest(ctx, opts).AddTasks(...) work. Or opt in at submit time via SubmitRegularOptions.WaitForIngest / SubmitOpenOptions.WaitForIngest.

type JobSchedule

type JobSchedule struct {
	At       string            `json:"at,omitempty"`
	Rate     *ScheduleRate     `json:"rate,omitempty"`
	Calendar *ScheduleCalendar `json:"calendar,omitempty"`
	Timezone string            `json:"timezone,omitempty"`
}

JobSchedule is the wire schedule block attached to type=scheduled jobs. Exactly one of At, Rate, or Calendar is set. Build one with the At/Rate/Calendar constructors rather than by hand — they validate the same rules the server enforces.

type JobStatus

type JobStatus string

JobStatus is the lifecycle state of a job. The server may add values not listed here, and they decode as-is; callers must handle unknown values (e.g. a default branch, or IsKnown) rather than assume the constants are exhaustive.

const (
	// JobStatusOpen keeps a job accepting more tasks via Client.AddTasks until Client.CloseJob is called.
	// Use this when you're streaming URLs in over time rather than knowing the full list upfront.
	JobStatusOpen    JobStatus = "open"
	JobStatusClosed  JobStatus = "closed"
	JobStatusDeleted JobStatus = "deleted"
)

func (JobStatus) IsKnown

func (j JobStatus) IsKnown() bool

IsKnown reports whether j is one of the JobStatus constants this SDK version defines.

type JobType

type JobType string

JobType is the kind of job being submitted.

const (
	JobTypeRegular   JobType = "regular"
	JobTypeScheduled JobType = "scheduled"
)

type ListJobsOptions

type ListJobsOptions struct {
	Status JobStatus
	Type   JobType
	Limit  int
	Cursor string
}

ListJobsOptions filters/paginates Client.ListJobs.

type ListJobsResponse

type ListJobsResponse struct {
	Jobs       []Job  `json:"jobs"`
	NextCursor string `json:"next_cursor,omitempty"`
}

ListJobsResponse is the response for Client.ListJobs.

type ListRunsOptions

type ListRunsOptions struct {
	Limit  int
	Cursor string
}

ListRunsOptions paginates Client.ListRuns.

type ListRunsResponse

type ListRunsResponse struct {
	Runs       []Run  `json:"runs"`
	NextCursor string `json:"next_cursor,omitempty"`
}

ListRunsResponse is the response for Client.ListRuns.

type Monthly

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

Monthly fires on specific days of the month. Build with NewMonthly.

func NewMonthly

func NewMonthly(days []int) (Monthly, error)

NewMonthly builds a monthly cadence. days are 1-31, at least one required. Days that don't exist in a given month (e.g. 31 in April) are silently skipped by the scheduler.

type NotConfiguredError

type NotConfiguredError struct{}

NotConfiguredError results when the Batch API client is used without a valid API key.

func (NotConfiguredError) Error

func (NotConfiguredError) Error() string

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option configures the Zenrows Batch API client.

func WithAPIKey

func WithAPIKey(apiKey string) Option

WithAPIKey configures the API key of the Zenrows Batch API client.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL configures the base URL of the Zenrows Batch API client.

func WithRetries

func WithRetries(retries int) Option

WithRetries configures how many times a transient failure (429/502/503/504, or a network error) is retried on idempotent requests. Defaults to 3; pass 0 to disable.

func WithTimeout added in v1.1.0

func WithTimeout(timeout time.Duration) Option

WithTimeout bounds how long one HTTP request to the Batch API may take, so a stalled connection fails instead of hanging. There is no limit unless you set one. A request that runs out is a network error: it is retried, within the WithRetries budget, only when retrying is safe (GET, PUT, DELETE, or a POST that carries an Idempotency-Key). An unkeyed POST, such as a submit or add-tasks without a key, returns the timeout error. It does not bound the waiters (they take their own timeout) or downloads from a presigned result_url. 0 or less leaves requests unbounded.

type PauseState

type PauseState string

PauseState is the reversible-suspend flag on a run, orthogonal to RunStatus.

const (
	PauseStateActive PauseState = "active"
	PauseStatePaused PauseState = "paused"
)

type Problem

type Problem struct {
	Type         string        `json:"type,omitempty"`
	Title        string        `json:"title,omitempty"`
	Status       int           `json:"status,omitempty"`
	Code         string        `json:"code,omitempty"`
	Detail       string        `json:"detail,omitempty"`
	Instance     string        `json:"instance,omitempty"`
	InvalidTasks []InvalidTask `json:"invalid_tasks,omitempty"`
	// Extras holds any non-standard top-level members not modeled above.
	Extras map[string]any `json:"-"`
}

Problem is an RFC 7807 problem+json body, as returned by every Batch API error response.

type ProblemDetail

type ProblemDetail = Problem

ProblemDetail is the RFC 7807 Problem JSON shape the Batch API returns on errors. Kept as an alias of Problem for backward compatibility with earlier callers of this package.

type Rate

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

Rate is an interval-based schedule fire policy — every N units, no wall-clock alignment. Build with NewRate.

func NewRate

func NewRate(every int, unit string) (Rate, error)

NewRate builds an interval-based schedule. unit is one of "minute", "hour", "day". The API rejects a rate that fires more often than the account minimum (60 minutes by default) with a 400; that limit is per account, so it is not checked here.

type RerunJobResponse

type RerunJobResponse struct {
	JobID          string    `json:"job_id"`
	Status         JobStatus `json:"status"`
	LatestRun      Run       `json:"latest_run"`
	RerunOf        string    `json:"rerun_of,omitempty"`
	RetriedTasks   int       `json:"retried_tasks"`
	InheritedTasks int       `json:"inherited_tasks"`
}

RerunJobResponse is the response for Client.Rerun.

type RerunOptions

type RerunOptions struct {
	Status         string
	IdempotencyKey string
	// WaitForIngest returns only once the new run's task rows are written, so its results
	// pages are complete. Every rerun's rows are written in the background.
	WaitForIngest bool
}

RerunOptions configures Client.Rerun. Status filters to a partial retry (e.g. "failed" or "failed,pending"); leave empty for a full replay.

type ResultType

type ResultType string

ResultType is the body format of a successful task result. The server may add values not listed here, and they decode as-is; callers must handle unknown values (e.g. a default branch, or IsKnown) rather than assume the constants are exhaustive.

const (
	ResultTypeHTML      ResultType = "html"
	ResultTypeJSON      ResultType = "json"
	ResultTypeMarkdown  ResultType = "markdown"
	ResultTypePlaintext ResultType = "plaintext"
	ResultTypePDF       ResultType = "pdf"
)

func (ResultType) IsKnown

func (r ResultType) IsKnown() bool

IsKnown reports whether r is one of the ResultType constants this SDK version defines.

type RetryFailedOptions

type RetryFailedOptions struct {
	// IncludePending also re-enqueues tasks that never started ("failed,pending") — the usual
	// move after Run().Stop() left orphan pending rows.
	IncludePending bool
	IdempotencyKey string
	// WaitForIngest returns only once the new run's task rows are written (see Client.Rerun).
	WaitForIngest bool
}

RetryFailedOptions configures JobRef.RetryFailed.

type Run

type Run struct {
	RunID             string        `json:"run_id"`
	JobID             string        `json:"job_id"`
	RunSequence       int           `json:"run_sequence"`
	Status            RunStatus     `json:"status"`
	Stats             RunStats      `json:"stats"`
	LastBatchReceived *bool         `json:"last_batch_received,omitempty"`
	PauseState        PauseState    `json:"pause_state,omitempty"`
	IngestStatus      IngestStatus  `json:"ingest_status,omitempty"`
	FailureReason     FailureReason `json:"failure_reason,omitempty"`
	// FailureDetail is a human-readable explanation of FailureReason (e.g. which cap, and when
	// it resets, UTC). Nil when absent or null.
	FailureDetail *string `json:"failure_detail,omitempty"`
	// Trigger records what started the run: RunTriggerManual or RunTriggerScheduled.
	Trigger   RunTrigger `json:"trigger,omitempty"`
	CreatedAt string     `json:"created_at"`
	UpdatedAt string     `json:"updated_at"`
}

Run is one execution of a Job.

type RunHandle

type RunHandle struct {
	RunRef
	Data Run
}

RunHandle is a RunRef plus a guaranteed, synchronous Data snapshot.

func (RunHandle) Stats

func (h RunHandle) Stats() RunStats

Stats is this run's task rollup. Shortcut for Data.Stats.

func (RunHandle) Status

func (h RunHandle) Status() RunStatus

Status is this run's status. Shortcut for Data.Status.

type RunPausedError added in v1.1.0

type RunPausedError struct {
	Run Run
}

RunPausedError is returned by the run waiters when the run is paused. A paused run makes no progress until it is resumed, so the wait stops instead of running out its timeout. Run is the paused run's state; resume it with Run().Resume, or wait with WaitForRunOptions.WaitThroughPause to keep polling.

func (RunPausedError) Error added in v1.1.0

func (e RunPausedError) Error() string

type RunRef

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

RunRef is a reference to a specific run by (jobID, runID). Read/download operations on one (usually historical) run. No Pause/Stop — the API only suspends or stops the current run (see JobRef.Run(), the CurrentRun facet). Call Load for a RunHandle with data.

func (RunRef) Delete

func (r RunRef) Delete(ctx context.Context) error

Delete scrubs this run only.

func (RunRef) DownloadAllResults

func (r RunRef) DownloadAllResults(ctx context.Context, targetPath string, opts DownloadAllResultsOptions) (string, error)

DownloadAllResults starts an export of this run's results, waits for it, and saves the zip to targetPath. See Client.DownloadAllResults for the contract.

func (RunRef) DownloadTaskToFile

func (r RunRef) DownloadTaskToFile(task TaskResult, targetPath string) error

DownloadTaskToFile downloads one task's body straight from its presigned result_url to target.

func (RunRef) DownloadTaskToMemory

func (r RunRef) DownloadTaskToMemory(task TaskResult) ([]byte, error)

DownloadTaskToMemory downloads one task's body straight from its presigned result_url and returns the raw bytes.

func (RunRef) DownloadToDir

func (r RunRef) DownloadToDir(ctx context.Context, targetDir string, opts DownloadToDirOptions) (int, error)

DownloadToDir streams every (matching) task body of this run into targetDir. See Client-level DownloadToDir (download.go) for the full contract.

func (RunRef) DownloadToMemory

func (r RunRef) DownloadToMemory(ctx context.Context, opts DownloadToMemoryOptions) ([]DownloadedResult, error)

DownloadToMemory loads every (matching) task body of this run into memory. See Client-level DownloadToMemory (download.go) for the full contract.

func (RunRef) Export

func (r RunRef) Export(exportID string) ExportRef

Export addresses a specific export of this run by id (no network call). Lazy — the first method call surfaces 404 if the id is wrong or TTL-swept.

func (RunRef) JobID

func (r RunRef) JobID() string

JobID is this run's parent job id.

func (RunRef) Load

func (r RunRef) Load(ctx context.Context) (RunHandle, error)

Load fetches the run and returns a loaded RunHandle.

func (RunRef) Results

func (r RunRef) Results(ctx context.Context, status string) iter.Seq2[TaskResult, error]

Results auto-paginates task results from this run.

func (RunRef) RunID

func (r RunRef) RunID() string

RunID is this run's id.

func (RunRef) StartExport

func (r RunRef) StartExport(ctx context.Context) (ExportRef, error)

StartExport kicks off an async zip of this run's bodies. Returns an ExportRef carrying the just-issued id; chain Wait to block for completion.

func (RunRef) TaskHistory

func (r RunRef) TaskHistory(ctx context.Context, taskID string) (*TaskHistoryResponse, error)

TaskHistory returns the per-attempt event log for one task in this run.

func (RunRef) Wait

func (r RunRef) Wait(ctx context.Context, opts WaitForRunOptions) (RunHandle, error)

Wait blocks until this run reaches a target state. Returns a fresh loaded RunHandle so chains like run.Wait(ctx, opts).DownloadToDir(...) work without re-wrapping.

type RunStats

type RunStats struct {
	Total          int            `json:"total"`
	Completed      int            `json:"completed"`
	Successful     int            `json:"successful"`
	Failed         int            `json:"failed"`
	FailureReasons map[string]int `json:"failure_reasons,omitempty"`
	Spend          *Spend         `json:"spend,omitempty"`
}

RunStats summarizes progress and spend for a run.

type RunStatus

type RunStatus string

RunStatus is the lifecycle state of a single run of a job. The server may add values not listed here, and they decode as-is; callers must handle unknown values (e.g. a default branch, or IsKnown) rather than assume the constants are exhaustive.

const (
	RunStatusRunning   RunStatus = "running"
	RunStatusPending   RunStatus = "pending"
	RunStatusCompleted RunStatus = "completed"
	RunStatusStopped   RunStatus = "stopped"
	RunStatusFailed    RunStatus = "failed"
	RunStatusDeleted   RunStatus = "deleted"
)

func (RunStatus) IsKnown

func (r RunStatus) IsKnown() bool

IsKnown reports whether r is one of the RunStatus constants this SDK version defines.

type RunTrigger added in v1.1.0

type RunTrigger string

RunTrigger records what started a run. The server may add values not listed here, and they decode as-is; callers must handle unknown values (e.g. a default branch, or IsKnown) rather than assume the constants are exhaustive.

const (
	// RunTriggerManual is a run a caller started through the API: a submit, a rerun, or a
	// manual fire of a scheduled job.
	RunTriggerManual RunTrigger = "manual"
	// RunTriggerScheduled is a run a scheduled job's schedule started.
	RunTriggerScheduled RunTrigger = "scheduled"
)

func (RunTrigger) IsKnown added in v1.1.0

func (t RunTrigger) IsKnown() bool

IsKnown reports whether t is one of the RunTrigger constants this SDK version defines.

type Schedule

type Schedule interface {
	// contains filtered or unexported methods
}

Schedule is anything that can produce the wire JobSchedule block for SubmitScheduled / ScheduleControls.Update — an At, Rate, or Calendar.

type ScheduleCadence

type ScheduleCadence struct {
	Daily   map[string]any   `json:"daily,omitempty"`
	Weekly  *ScheduleWeekly  `json:"weekly,omitempty"`
	Monthly *ScheduleMonthly `json:"monthly,omitempty"`
}

ScheduleCadence picks which days a Calendar schedule fires on. Exactly one field is set.

type ScheduleCalendar

type ScheduleCalendar struct {
	TimesOfDay []string        `json:"times_of_day"`
	Cadence    ScheduleCadence `json:"cadence"`
}

ScheduleCalendar is a calendar-style fire policy: times-of-day on a daily/weekly/monthly cadence.

type ScheduleControls

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

ScheduleControls holds operations on a scheduled job's schedule, reached via JobRef.Schedule(). Scheduled jobs only — regular jobs get a 409.

func (ScheduleControls) Pause

func (sc ScheduleControls) Pause(ctx context.Context) (JobHandle, error)

Pause skips future scheduled fires (an in-flight run keeps running). The schedule keeps ticking server-side but fires are dropped until Resume. Idempotent; returns the fresh loaded handle.

func (ScheduleControls) Resume

func (sc ScheduleControls) Resume(ctx context.Context) (JobHandle, error)

Resume re-enables scheduled fires on a paused job. Idempotent; returns the fresh loaded handle.

func (ScheduleControls) Update

func (sc ScheduleControls) Update(ctx context.Context, schedule Schedule) (JobHandle, error)

Update replaces the schedule. schedule is one of the typed builders (At, Rate, Calendar), same as SubmitScheduled. An in-flight run keeps running; the new schedule governs only future fires. Returns the fresh loaded handle.

type ScheduleMonthly

type ScheduleMonthly struct {
	Days []int `json:"days"`
}

ScheduleMonthly fires on specific days of the month (1-31).

type ScheduleRate

type ScheduleRate struct {
	Every int    `json:"every"`
	Unit  string `json:"unit"`
}

ScheduleRate is an interval-based schedule fire policy — every N units.

type ScheduleState

type ScheduleState string

ScheduleState is the run/pause flag on a scheduled job's future fires.

const (
	ScheduleStateActive ScheduleState = "active"
	ScheduleStatePaused ScheduleState = "paused"
)

type ScheduleWeekly

type ScheduleWeekly struct {
	Days []string `json:"days"`
}

ScheduleWeekly fires on specific 3-letter lower-case day names.

type Spend

type Spend struct {
	Credits float64 `json:"credits"`
	Cost    float64 `json:"cost"`
}

Spend reports credits and cost for a scoped piece of work. Indicative, not billing-grade.

type StartExportResponse

type StartExportResponse struct {
	ExportID  string       `json:"export_id"`
	Status    ExportStatus `json:"status"`
	CreatedAt string       `json:"created_at"`
	ExpiresAt string       `json:"expires_at"`
}

StartExportResponse is the response for Client.StartResultsExport.

type SubmitJobRequest

type SubmitJobRequest struct {
	Type JobType `json:"type,omitempty"`
	// Status lets you open a job for incremental task submission (JobStatusOpen) instead of a
	// normal one-shot batch where every task is already known.
	Status        JobStatus      `json:"status,omitempty"`
	ZenRowsParams map[string]any `json:"zenrows_params,omitempty"`
	Schedule      *JobSchedule   `json:"schedule,omitempty"`
	Tasks         []Task         `json:"tasks,omitempty"`
	FileInputID   string         `json:"file_input_id,omitempty"`
	ExternalID    string         `json:"external_id,omitempty"`
	Name          string         `json:"name,omitempty"`
	Metadata      map[string]any `json:"metadata,omitempty"`
	Webhook       *WebhookConfig `json:"webhook,omitempty"`
	// IdempotencyKey scopes a single submit/rerun request; resubmitting with the same key
	// returns the original response (or a conflict if the body doesn't match). Sent as a
	// header, never part of the JSON body.
	IdempotencyKey string `json:"-"`
}

SubmitJobRequest is the body for Client.SubmitJob. Most callers prefer the type-specific SubmitRegular / SubmitOpen / SubmitScheduled, which build this for you.

type SubmitJobResponse

type SubmitJobResponse struct {
	JobID         string         `json:"job_id"`
	Status        JobStatus      `json:"status"`
	LatestRun     *Run           `json:"latest_run,omitempty"`
	AcceptedTasks int            `json:"accepted_tasks"`
	Webhook       *WebhookConfig `json:"webhook,omitempty"`
}

SubmitJobResponse is the response for Client.SubmitJob.

type SubmitOpenOptions

type SubmitOpenOptions struct {
	// Tasks may be empty — tasks can be added later via JobRef.AddTasks.
	Tasks          []Task
	ZenRowsParams  map[string]any
	ExternalID     string
	Name           string
	Metadata       map[string]any
	Webhook        *WebhookConfig
	IdempotencyKey string
	WaitForIngest  bool
}

SubmitOpenOptions configures Client.SubmitOpen.

type SubmitRegularOptions

type SubmitRegularOptions struct {
	// Tasks and FileInputID are mutually exclusive — exactly one must be set.
	Tasks          []Task
	FileInputID    string
	ZenRowsParams  map[string]any
	ExternalID     string
	Name           string
	Metadata       map[string]any
	Webhook        *WebhookConfig
	IdempotencyKey string
	WaitForIngest  bool
}

SubmitRegularOptions configures Client.SubmitRegular.

type SubmitScheduledOptions

type SubmitScheduledOptions struct {
	Schedule       Schedule // an At, Rate, or Calendar
	Tasks          []Task
	FileInputID    string
	ZenRowsParams  map[string]any
	ExternalID     string
	Name           string
	Metadata       map[string]any
	Webhook        *WebhookConfig
	IdempotencyKey string
}

SubmitScheduledOptions configures Client.SubmitScheduled.

type Task

type Task struct {
	URL           string         `json:"url"`
	ExternalID    string         `json:"external_id,omitempty"`
	Metadata      map[string]any `json:"metadata,omitempty"`
	Method        string         `json:"method,omitempty"`
	Body          any            `json:"body,omitempty"`
	ZenRowsParams map[string]any `json:"zenrows_params,omitempty"`
}

Task is one URL to scrape within a job.

type TaskHistoryEvent

type TaskHistoryEvent struct {
	StartedAt string   `json:"started_at"`
	EndedAt   string   `json:"ended_at"`
	Attempt   int      `json:"attempt"`
	Error     *Problem `json:"error,omitempty"`
	Spend     *Spend   `json:"spend,omitempty"`
}

TaskHistoryEvent is one attempt in a task's history.

type TaskHistoryResponse

type TaskHistoryResponse struct {
	Events []TaskHistoryEvent `json:"events"`
}

TaskHistoryResponse is the response for Client.GetTaskHistory.

type TaskResult

type TaskResult struct {
	TaskID      string         `json:"task_id"`
	ExternalID  string         `json:"external_id,omitempty"`
	RunID       string         `json:"run_id"`
	URL         string         `json:"url"`
	Metadata    map[string]any `json:"metadata,omitempty"`
	Method      string         `json:"method,omitempty"`
	Status      TaskStatus     `json:"status"`
	Type        ResultType     `json:"type,omitempty"`
	ResultURL   string         `json:"result_url,omitempty"`
	Error       *Problem       `json:"error,omitempty"`
	SourceRunID string         `json:"source_run_id,omitempty"`
	// CreatedAt and UpdatedAt are the task row's timestamps (RFC 3339). On a finished row
	// UpdatedAt is when the scrape settled, except on rows a partial rerun copied from an
	// earlier run (SourceRunID set), where it is the copy time.
	CreatedAt string `json:"created_at"`
	UpdatedAt string `json:"updated_at"`
	// Deprecated: the Batch API does not return a per-task spend on result rows, so this is
	// always nil. Read run-level spend from Run.Stats.Spend.
	Spend *TaskSpend `json:"spend,omitempty"`
}

TaskResult is one task's outcome within a run.

type TaskSpend deprecated

type TaskSpend struct {
	Total       Spend `json:"total"`
	LastAttempt Spend `json:"last_attempt"`
}

Deprecated: TaskSpend is only referenced by the deprecated TaskResult.Spend.

TaskSpend is a task's indicative spend, both the running total across every attempt and just the most recent one.

type TaskStatus

type TaskStatus string

TaskStatus is the lifecycle state of one task within a run. The server may add values not listed here, and they decode as-is; callers must handle unknown values (e.g. a default branch, or IsKnown) rather than assume the constants are exhaustive.

const (
	TaskStatusPending    TaskStatus = "pending"
	TaskStatusProcessing TaskStatus = "processing"
	TaskStatusSuccessful TaskStatus = "successful"
	TaskStatusFailed     TaskStatus = "failed"
	// TaskStatusExpired marks a successful task whose stored body has aged out of its retention
	// window (14 days by default), counted from the row's UpdatedAt. Only successful rows
	// expire; failed rows stay failed. The row has no ResultURL, and its content endpoint
	// answers 410 result_expired. A "successful" status filter still matches it.
	TaskStatusExpired TaskStatus = "expired"
)

func (TaskStatus) IsKnown

func (t TaskStatus) IsKnown() bool

IsKnown reports whether t is one of the TaskStatus constants this SDK version defines.

type TestWebhookRequest

type TestWebhookRequest struct {
	URL       string `json:"url"`
	Signature bool   `json:"signature,omitempty"`
}

TestWebhookRequest is the body for Client.TestWebhook.

type TestWebhookResponse

type TestWebhookResponse struct {
	Delivered  bool   `json:"delivered"`
	EventID    string `json:"event_id"`
	StatusCode int    `json:"status_code,omitempty"`
	Error      string `json:"error,omitempty"`
	ElapsedMs  int    `json:"elapsed_ms"`
}

TestWebhookResponse is the outcome of a synthetic webhook test dispatch.

type Tier

type Tier string

Tier is the pricing tier a task falls into. Exactly one per task.

const (
	TierBase         Tier = "base"
	TierJS           Tier = "js_render"
	TierPremium      Tier = "premium_proxy"
	TierJSAndPremium Tier = "js_render+premium_proxy"
	TierAuto         Tier = "auto"
)

type UploadCSVOptions

type UploadCSVOptions struct {
	// URLField and ExternalIDField map canonical task fields to CSV columns — either a column
	// index (int) or a column name (string, requires Header: true). URLField is required.
	URLField        any
	ExternalIDField any
	Header          bool
	Delimiter       string
	Quote           string
}

UploadCSVOptions configures Client.UploadCSV.

type VerifyWebhookSignatureOptions added in v1.1.0

type VerifyWebhookSignatureOptions struct {
	// Tolerance is the largest accepted gap between the signature's timestamp and now.
	// Zero (or less) means DefaultWebhookTolerance.
	Tolerance time.Duration
	// SkipTimestampCheck turns off the replay window entirely.
	SkipTimestampCheck bool
	// Now overrides the clock (for tests). Nil means time.Now.
	Now func() time.Time
}

VerifyWebhookSignatureOptions tunes VerifyWebhookSignature. The zero value checks the timestamp against time.Now with DefaultWebhookTolerance (5 minutes). A zero Tolerance means "use the default", because it is also the value of an unset field; set SkipTimestampCheck to turn the check off.

type WaitForExportOptions

type WaitForExportOptions struct {
	TargetStatuses  map[ExportStatus]bool // defaults to TerminalExportStatuses
	Timeout         time.Duration         // defaults to 600s
	PollInterval    time.Duration         // defaults to 2s
	MaxPollInterval time.Duration         // defaults to 15s
}

WaitForExportOptions configures WaitForExport.

type WaitForIngestOptions

type WaitForIngestOptions struct {
	Timeout         time.Duration // defaults to 300s
	PollInterval    time.Duration // defaults to 2s
	MaxPollInterval time.Duration // defaults to 15s
}

WaitForIngestOptions configures WaitForIngest.

type WaitForRunOptions

type WaitForRunOptions struct {
	// RunID waits on a specific run. Leave empty to wait on the job's current run.
	RunID          string
	TargetStatuses map[RunStatus]bool // defaults to TerminalRunStatuses (failed included)
	// FailureStatuses return a WaiterError instead; they take precedence over TargetStatuses,
	// so {RunStatusFailed: true} makes a failed run an error. nil disables failure detection.
	FailureStatuses map[RunStatus]bool
	Timeout         time.Duration // defaults to 300s
	PollInterval    time.Duration // defaults to 2s
	MaxPollInterval time.Duration // defaults to 15s
	// WaitThroughPause keeps polling while the run is paused. By default a paused run, which
	// makes no progress until someone resumes it, ends the wait with a RunPausedError.
	WaitThroughPause bool
}

WaitForRunOptions configures WaitForRun / JobRef.Run().Wait / RunRef.Wait.

type WaiterError

type WaiterError struct {
	Value any
}

WaiterError is returned when the resource entered a failure state the caller flagged.

func (WaiterError) Error

func (e WaiterError) Error() string

type WaiterTimeoutError

type WaiterTimeoutError struct {
	Timeout time.Duration
}

WaiterTimeoutError is returned when a waiter's timeout elapsed before the target state.

func (WaiterTimeoutError) Error

func (e WaiterTimeoutError) Error() string

type WebhookConfig

type WebhookConfig struct {
	URL string `json:"url"`
	// Signature opts into HMAC signing of deliveries with the org's active HMAC key. Absent
	// on the wire the field defaults to false server-side; PUT requires it explicitly.
	Signature bool `json:"signature"`
}

WebhookConfig describes where (and how) to notify on run.completed / run.failed events.

type WebhookEvent added in v1.1.0

type WebhookEvent struct {
	Schema     string            `json:"schema"`
	EventID    string            `json:"event_id"`
	EventType  string            `json:"event_type"`
	OccurredAt string            `json:"occurred_at"`
	JobID      string            `json:"job_id"`
	ExternalID string            `json:"external_id,omitempty"`
	Metadata   map[string]string `json:"metadata,omitempty"`
	RunID      string            `json:"run_id"`
	// RunSequence counts the job's runs: 1 is the initial run, and each rerun or scheduled
	// fire adds one.
	RunSequence int `json:"run_sequence"`
	// Stats is the run's task rollup when the event was queued.
	Stats *RunStats `json:"stats,omitempty"`
	// FailureReason and FailureDetail are set on run.failed only.
	FailureReason FailureReason `json:"failure_reason,omitempty"`
	FailureDetail string        `json:"failure_detail,omitempty"`
}

WebhookEvent is the JSON body of a webhook delivery (schema "zenrows.webhook/v1"). Verify the raw body with VerifyWebhookSignature before decoding it into this type. Deliveries can repeat, so dedupe on EventID (also sent as the X-ZenRows-Event-Id header).

type Weekly

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

Weekly fires on specific days of the week. Build with NewWeekly.

func NewWeekly

func NewWeekly(days []string) (Weekly, error)

NewWeekly builds a weekly cadence. days are lower-case 3-letter names (mon/tue/wed/thu/ fri/sat/sun), at least one required.

Directories

Path Synopsis
examples
submit-and-download command
Command submit-and-download submits a small Batch job, waits for its run, retries the failed tasks once, and downloads every result body into a directory.
Command submit-and-download submits a small Batch job, waits for its run, retries the failed tasks once, and downloads every result body into a directory.
webhook-receiver command
Command webhook-receiver serves an HTTP endpoint that verifies and decodes Batch webhook deliveries.
Command webhook-receiver serves an HTTP endpoint that verifies and decodes Batch webhook deliveries.
Package version holds this module's release version.
Package version holds this module's release version.

Jump to

Keyboard shortcuts

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