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
- Variables
- func VerifyWebhookSignature(rawBody []byte, signatureHeader string, secrets map[string]string, ...) error
- type APIError
- type AddTasksOptions
- type AddTasksResponse
- type At
- type CSVFields
- type CSVSpec
- type Cadence
- type Calendar
- type Client
- func (c *Client) AddTasks(ctx context.Context, jobID string, tasks []Task, lastBatch bool) (*AddTasksResponse, error)
- func (c *Client) AddTasksWithOptions(ctx context.Context, jobID string, tasks []Task, opts AddTasksOptions) (*AddTasksResponse, error)
- func (c *Client) CancelHMACRotation(ctx context.Context) error
- func (c *Client) CloseJob(ctx context.Context, jobID string) (*Job, error)
- func (c *Client) CreateJobInput(ctx context.Context, req CreateJobInputRequest) (*CreateJobInputResponse, error)
- func (c *Client) DeleteJob(ctx context.Context, jobID string) error
- func (c *Client) DeleteJobWebhook(ctx context.Context, jobID string) error
- func (c *Client) DeleteRun(ctx context.Context, jobID, runID string) error
- func (c *Client) DownloadAllResults(ctx context.Context, jobID, runID, targetPath string, ...) (string, error)
- func (c *Client) DownloadToDir(ctx context.Context, jobID, targetDir string, opts DownloadToDirOptions) (int, error)
- func (c *Client) DownloadToMemory(ctx context.Context, jobID string, opts DownloadToMemoryOptions) ([]DownloadedResult, error)
- func (c *Client) EstimateCost(tasks []Task, zenrowsParams map[string]any) CostEstimate
- func (c *Client) FinalizeHMACKey(ctx context.Context) (*HMACKeyFinalized, error)
- func (c *Client) GetJob(ctx context.Context, jobID string) (JobHandle, error)
- func (c *Client) GetJobWebhook(ctx context.Context, jobID string) (*WebhookConfig, error)
- func (c *Client) GetResults(ctx context.Context, jobID string, opts GetResultsOptions) (*GetResultsResponse, error)
- func (c *Client) GetResultsExport(ctx context.Context, jobID, runID, exportID string) (ExportHandle, error)
- func (c *Client) GetRun(ctx context.Context, jobID, runID string) (RunHandle, error)
- func (c *Client) GetTaskContent(ctx context.Context, jobID, taskID string, opts GetTaskContentOptions) ([]byte, error)
- func (c *Client) GetTaskHistory(ctx context.Context, jobID, taskID, runID string) (*TaskHistoryResponse, error)
- func (c *Client) IterJobs(ctx context.Context, opts ListJobsOptions) iter.Seq2[Job, error]
- func (c *Client) IterResults(ctx context.Context, jobID string, opts GetResultsOptions) iter.Seq2[TaskResult, error]
- func (c *Client) IterRuns(ctx context.Context, jobID string, opts ListRunsOptions) iter.Seq2[Run, error]
- func (c *Client) Job(jobID string) JobRef
- func (c *Client) ListHMACKeys(ctx context.Context) (*HMACKeyList, error)
- func (c *Client) ListJobs(ctx context.Context, opts ListJobsOptions) (*ListJobsResponse, error)
- func (c *Client) ListRuns(ctx context.Context, jobID string, opts ListRunsOptions) (*ListRunsResponse, error)
- func (c *Client) PutJobWebhook(ctx context.Context, jobID string, config WebhookConfig) (*WebhookConfig, error)deprecated
- func (c *Client) Rerun(ctx context.Context, jobID string, opts RerunOptions) (*RerunJobResponse, error)
- func (c *Client) RotateHMACKey(ctx context.Context) (*HMACKeyCreated, error)
- func (c *Client) Run(jobID, runID string) RunRef
- func (c *Client) SetJobWebhook(ctx context.Context, jobID, url string, signature bool) (*WebhookConfig, error)
- func (c *Client) SetJobWebhookURL(ctx context.Context, jobID, url string) (*WebhookConfig, error)
- func (c *Client) StartResultsExport(ctx context.Context, jobID, runID string) (ExportRef, error)
- func (c *Client) StopRun(ctx context.Context, jobID string) (*Run, error)
- func (c *Client) SubmitJob(ctx context.Context, jobReq SubmitJobRequest) (*SubmitJobResponse, error)
- func (c *Client) SubmitOpen(ctx context.Context, opts SubmitOpenOptions) (JobRef, error)
- func (c *Client) SubmitRegular(ctx context.Context, opts SubmitRegularOptions) (JobRef, error)
- func (c *Client) SubmitScheduled(ctx context.Context, opts SubmitScheduledOptions) (JobRef, error)
- func (c *Client) TestWebhook(ctx context.Context, req TestWebhookRequest) (*TestWebhookResponse, error)
- func (c *Client) UploadCSV(ctx context.Context, source any, opts UploadCSVOptions) (string, error)
- func (c *Client) WaitForExport(ctx context.Context, jobID, runID, exportID string, opts WaitForExportOptions) (Export, error)
- func (c *Client) WaitForIngest(ctx context.Context, jobID string, opts WaitForIngestOptions) (Job, error)
- func (c *Client) WaitForRun(ctx context.Context, jobID string, opts WaitForRunOptions) (Run, error)
- type CostEstimate
- type CostLine
- type CreateJobInputRequest
- type CreateJobInputResponse
- type CurrentRun
- func (cr CurrentRun) Cancel(ctx context.Context) (RunHandle, error)
- func (cr CurrentRun) DownloadAllResults(ctx context.Context, targetPath string, opts DownloadAllResultsOptions) (string, error)
- func (cr CurrentRun) DownloadTaskToFile(task TaskResult, targetPath string) error
- func (cr CurrentRun) DownloadTaskToMemory(task TaskResult) ([]byte, error)
- func (cr CurrentRun) DownloadToDir(ctx context.Context, targetDir string, opts DownloadToDirOptions) (int, error)
- func (cr CurrentRun) DownloadToMemory(ctx context.Context, opts DownloadToMemoryOptions) ([]DownloadedResult, error)
- func (cr CurrentRun) Load(ctx context.Context) (RunHandle, error)
- func (cr CurrentRun) Pause(ctx context.Context) (RunHandle, error)
- func (cr CurrentRun) Results(ctx context.Context, status string) iter.Seq2[TaskResult, error]
- func (cr CurrentRun) Resume(ctx context.Context) (RunHandle, error)
- func (cr CurrentRun) StartExport(ctx context.Context) (ExportRef, error)
- func (cr CurrentRun) Stop(ctx context.Context) (RunHandle, error)
- func (cr CurrentRun) TaskHistory(ctx context.Context, taskID string) (*TaskHistoryResponse, error)
- func (cr CurrentRun) Wait(ctx context.Context, opts WaitForRunOptions) (RunHandle, error)
- type Daily
- type DownloadAllResultsOptions
- type DownloadLimitExceededError
- type DownloadToDirOptions
- type DownloadToMemoryOptions
- type DownloadedResult
- type Export
- type ExportHandle
- type ExportRef
- func (r ExportRef) DownloadToPath(ctx context.Context, targetPath string) (string, error)
- func (r ExportRef) ExportID() string
- func (r ExportRef) Load(ctx context.Context) (ExportHandle, error)
- func (r ExportRef) StartResponse() *StartExportResponse
- func (r ExportRef) Wait(ctx context.Context, opts WaitForExportOptions) (ExportHandle, error)
- type ExportStatus
- type FailureReason
- type FileInputUploadTarget
- type GetResultsOptions
- type GetResultsResponse
- type GetTaskContentOptions
- type HMACKeyCreated
- type HMACKeyFinalized
- type HMACKeyList
- type HMACKeyMeta
- type IngestStatus
- type InvalidTask
- type Job
- type JobHandle
- type JobRef
- func (r JobRef) AcceptedTasks() int
- func (r JobRef) AddFileInput(ctx context.Context, source any, opts UploadCSVOptions) (string, error)
- func (r JobRef) AddTasks(ctx context.Context, tasks []Task, lastBatch bool) (*AddTasksResponse, error)
- func (r JobRef) AddTasksWithOptions(ctx context.Context, tasks []Task, opts AddTasksOptions) (*AddTasksResponse, error)
- func (r JobRef) Close(ctx context.Context) (JobHandle, error)
- func (r JobRef) Delete(ctx context.Context) error
- func (r JobRef) DeleteWebhook(ctx context.Context) error
- func (r JobRef) GetWebhook(ctx context.Context) (*WebhookConfig, error)
- func (r JobRef) JobID() string
- func (r JobRef) Load(ctx context.Context) (JobHandle, error)
- func (r JobRef) Rerun(ctx context.Context, opts RerunOptions) (RunHandle, error)
- func (r JobRef) RetryFailed(ctx context.Context, opts RetryFailedOptions) (RunHandle, error)
- func (r JobRef) Run() CurrentRun
- func (r JobRef) Runs(ctx context.Context, opts ListRunsOptions) iter.Seq2[RunHandle, error]
- func (r JobRef) Schedule() ScheduleControls
- func (r JobRef) SetWebhook(ctx context.Context, url string, signature bool) (*WebhookConfig, error)
- func (r JobRef) Status() JobStatus
- func (r JobRef) WaitForIngest(ctx context.Context, opts WaitForIngestOptions) (JobHandle, error)
- type JobSchedule
- type JobStatus
- type JobType
- type ListJobsOptions
- type ListJobsResponse
- type ListRunsOptions
- type ListRunsResponse
- type Monthly
- type NotConfiguredError
- type Option
- type PauseState
- type Problem
- type ProblemDetail
- type Rate
- type RerunJobResponse
- type RerunOptions
- type ResultType
- type RetryFailedOptions
- type Run
- type RunHandle
- type RunPausedError
- type RunRef
- func (r RunRef) Delete(ctx context.Context) error
- func (r RunRef) DownloadAllResults(ctx context.Context, targetPath string, opts DownloadAllResultsOptions) (string, error)
- func (r RunRef) DownloadTaskToFile(task TaskResult, targetPath string) error
- func (r RunRef) DownloadTaskToMemory(task TaskResult) ([]byte, error)
- func (r RunRef) DownloadToDir(ctx context.Context, targetDir string, opts DownloadToDirOptions) (int, error)
- func (r RunRef) DownloadToMemory(ctx context.Context, opts DownloadToMemoryOptions) ([]DownloadedResult, error)
- func (r RunRef) Export(exportID string) ExportRef
- func (r RunRef) JobID() string
- func (r RunRef) Load(ctx context.Context) (RunHandle, error)
- func (r RunRef) Results(ctx context.Context, status string) iter.Seq2[TaskResult, error]
- func (r RunRef) RunID() string
- func (r RunRef) StartExport(ctx context.Context) (ExportRef, error)
- func (r RunRef) TaskHistory(ctx context.Context, taskID string) (*TaskHistoryResponse, error)
- func (r RunRef) Wait(ctx context.Context, opts WaitForRunOptions) (RunHandle, error)
- type RunStats
- type RunStatus
- type RunTrigger
- type Schedule
- type ScheduleCadence
- type ScheduleCalendar
- type ScheduleControls
- type ScheduleMonthly
- type ScheduleRate
- type ScheduleState
- type ScheduleWeekly
- type Spend
- type StartExportResponse
- type SubmitJobRequest
- type SubmitJobResponse
- type SubmitOpenOptions
- type SubmitRegularOptions
- type SubmitScheduledOptions
- type Task
- type TaskHistoryEvent
- type TaskHistoryResponse
- type TaskResult
- type TaskSpenddeprecated
- type TaskStatus
- type TestWebhookRequest
- type TestWebhookResponse
- type Tier
- type UploadCSVOptions
- type VerifyWebhookSignatureOptions
- type WaitForExportOptions
- type WaitForIngestOptions
- type WaitForRunOptions
- type WaiterError
- type WaiterTimeoutError
- type WebhookConfig
- type WebhookEvent
- type Weekly
Constants ¶
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.
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.
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.
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).
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.
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.
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 ¶
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.
var TerminalExportStatuses = map[ExportStatus]bool{ ExportStatusCompleted: true, ExportStatusFailed: true, }
TerminalExportStatuses are the export statuses that don't transition again. The default target for WaitForExport.
var TerminalRunStatuses = map[RunStatus]bool{ RunStatusCompleted: true, RunStatusStopped: true, RunStatusFailed: true, RunStatusDeleted: true, }
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).
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.
type CSVFields ¶
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 ¶
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 (*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 ¶
CancelHMACRotation discards the pending rotation candidate.
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 ¶
DeleteJob deletes a job and all its artifacts. Deletion is asynchronous server-side.
func (*Client) DeleteJobWebhook ¶
DeleteJobWebhook clears the job's webhook config. Idempotent: succeeds whether or not one was set.
func (*Client) DeleteRun ¶
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 ¶
GetJob fetches a job (template + latest_run projection) by id and returns a loaded JobHandle.
func (*Client) GetJobWebhook ¶
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) 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 ¶
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 ¶
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 ¶
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
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 ¶
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) 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
CostLine is one row of a CostEstimate's breakdown: all tasks sharing a tier, aggregated.
type CreateJobInputRequest ¶
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 ¶
func (cr CurrentRun) Wait(ctx context.Context, opts WaitForRunOptions) (RunHandle, error)
Wait blocks until the current run reaches a target state. Returns a loaded RunHandle.
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 ¶
DownloadLimitExceededError is returned when a download exceeds a configured cap.
func (DownloadLimitExceededError) Error ¶
func (e DownloadLimitExceededError) Error() string
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 ¶
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 ¶
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 ¶
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) 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 ¶
func (r ExportRef) Wait(ctx context.Context, opts WaitForExportOptions) (ExportHandle, error)
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 ¶
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 ¶
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 ¶
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) DeleteWebhook ¶
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) Rerun ¶
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 ¶
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 ¶
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 ¶
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 ¶
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" )
type ListJobsOptions ¶
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 ¶
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 ¶
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 ¶
WithAPIKey configures the API key of the Zenrows Batch API client.
func WithBaseURL ¶
WithBaseURL configures the base URL of the Zenrows Batch API client.
func WithRetries ¶
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
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.
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 ¶
RunHandle is a RunRef plus a guaranteed, synchronous Data snapshot.
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) 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 ¶
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) StartExport ¶
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 ¶
TaskHistory returns the per-attempt event log for one task in this run.
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.
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.
type ScheduleMonthly ¶
type ScheduleMonthly struct {
Days []int `json:"days"`
}
ScheduleMonthly fires on specific days of the month (1-31).
type ScheduleRate ¶
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 ¶
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 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 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 ¶
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).
Source Files
¶
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. |