Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,55 @@ All notable changes to the Apify Go client are documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.17.0] - 2026-12-03

### Added

- `StoreCollectionClient.Search`, with `StoreSearchOptions` and `StoreSearchResult`, for a text
search of Store Actors. The API answers it with one page of at most 100 Actors by relevance, and
`Search` sends one request, requires a non-empty `StoreSearchOptions.Search`, and returns the
Actors and the limit.
- `KeyValueStoreClient.SetRecordStream` and `SetRecordStreamWithEncoding`, `ActorClient.StartStream`
and `CallStream`, and `TaskClient.StartStream` and `CallStream`, which send an `io.Reader` as the
record value or the run input, so a large body is not held in memory. The stream is sent once,
without compression or retries, and a redirect is an error. A task input stream holds a JSON
object.
- `ActorStoreListItem.Categories`, `Stats` (the new `StoreActorStats`) and `IsVerified`.
- `TaskStartOptions.Log`, for the log redirection of `TaskClient.Call` and `CallStream`.
- `StreamedLogOptions.Since` and `StreamedLog.LastRedirectedAt`. A log stream that is cut off while
the run goes on is reopened, and the redirection resumes after the last redirected message.

### Changed

- `StoreCollectionClient.List` and `Iterate` go through Apify Store in Store order. Paging through a
search repeated the same Actors without end, as the API ignores the offset for it, so a search
now goes through `StoreCollectionClient.Search`.
- `TaskClient.Call` now redirects the log of the run to `os.Stderr` while it waits, as
`ActorClient.Call` does. Set `TaskStartOptions.Log.Disabled` to turn it off.
- An `io.Reader` as `ActorServerRequestOptions.Body` is sent as a stream. Before, it was serialized
as JSON.
- `categories`, `stats` and `isVerified` of a Store Actor are no longer in
`ActorStoreListItem.Extra`.
- `ActorVersionCollectionClient.Create` and `ActorVersionClient.Update` use the long timeout tier,
since a version can carry its source files.
- Updated the documentation of `StoreListOptions` to the OpenAPI specification: the comma-separated
`Category` IDs, and `IncludeUnrunnableActors` and `ResponseFormat`.
- Documented that the signature of `DatasetClient.CreateItemsPublicURL` and
`KeyValueStoreClient.CreateKeysPublicURL` grants access to everything in the storage, and when
`BuildClient.GetOpenAPIDefinition` needs a token.
- Added the `APIFY_AI` run origin to the `LastRunOptions.Origin` examples.
- `APISpecVersion` is `v2-2026-12-02T102104Z`.

### Deprecated

- `StreamedLogOptions.FromStart`. Use `Since`.

### Removed

- `StoreListOptions.Search` (use `StoreCollectionClient.Search`) and `SortBy`, which the API
ignores.
- `StoreListOptions.AllowsAgenticUsers`, as the API no longer has the filter.

## [0.16.2] - 2026-11-24

### Security
Expand Down
14 changes: 9 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ decoding the response fail.
| `client.Schedules()` / `client.Schedule(id)` | `*ScheduleCollectionClient` / `*ScheduleClient` | List/create schedules; manage a single schedule. |
| `client.Webhooks()` / `client.Webhook(id)` | `*WebhookCollectionClient` / `*WebhookClient` | List/create webhooks; manage and test a single webhook. |
| `client.WebhookDispatches()` / `client.WebhookDispatch(id)` | `*WebhookDispatchCollectionClient` / `*WebhookDispatchClient` | List/inspect webhook dispatches. |
| `client.Store()` | `*StoreCollectionClient` | Browse and iterate the Apify Store. |
| `client.Store()` | `*StoreCollectionClient` | Browse, iterate and search Apify Store. |
| `client.Me()` / `client.User(id)` | `*UserClient` | Account details, usage and limits (for your own account or your organization with `User(id)`). |
| `client.Log(buildOrRunID)` | `*LogClient` | Read or stream a build/run log. |
| `client.Actor(id).Server()` | `*ActorServerClient` | Send requests to a Server Actor (formerly Actor Standby) and get its URL and OpenAPI specification. See [docs/server_actors.md](docs/server_actors.md). |
Expand Down Expand Up @@ -245,10 +245,13 @@ the request.
## Custom HTTP transport

The transport is replaceable. Implement `HTTPBackend` (a single `Do` method) to integrate a
custom client, proxy, or test double, and pass it with `WithHTTPBackend`. A backend that follows
custom client, proxy, or test double, and pass it with `WithHTTPBackend`. The backend must close
`req.Body` once it is done with it, also when it fails, as an `http.RoundTripper` does: the client
relies on that to close the stream body of a request that was sent. A backend that follows
redirects must not follow them for a request that `apify.FollowsRedirects(req)` reports false for,
as the requests to a [Server Actor](docs/server_actors.md) carry a token meant for one host only,
and a redirect to another host would send it there:
and a redirect to another host would send it there. The requests with a stream body (such as
`SetRecordStream`) are the same, since a redirect cannot replay a stream:

```go
package main
Expand All @@ -266,7 +269,8 @@ func (b *myBackend) Do(req *http.Request) (*http.Response, error) {
if apify.FollowsRedirects(req) {
return b.inner.Do(req)
}
// This request carries a token meant for one host only, so a redirect is returned as it is.
// This request carries a token meant for one host only, or a stream body that a redirect cannot
// replay, so a redirect is returned as it is.
client := *b.inner
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
return client.Do(req)
Expand All @@ -285,7 +289,7 @@ func main() {

- `apify.ClientVersion` — the semantic version of this library.
- `apify.APISpecVersion` — the Apify OpenAPI spec version this client was built against
(`v2-2026-11-18T151559Z`).
(`v2-2026-12-02T102104Z`).

### Releasing

Expand Down
72 changes: 54 additions & 18 deletions actor.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"encoding/base64"
"encoding/json"
"io"
"net/http"
"sync"
"time"
Expand Down Expand Up @@ -42,10 +43,10 @@ type ActorStartOptions struct {
// A run that requests more memory than the account's limit is rejected with
// actor-memory-limit-exceeded and never starts, so WaitForResourcesIndefinitely retries it forever.
WaitForResources *int64
// Log configures the redirection of the run's log that [ActorClient.Call] and
// [ActorClient.CallRaw] do while they wait (see [StreamedLog]). Nil redirects it to os.Stderr
// with the default prefix; set Log.Disabled to turn the redirection off. Start and StartRaw
// ignore it.
// Log configures the redirection of the run's log that [ActorClient.Call],
// [ActorClient.CallRaw] and [ActorClient.CallStream] do while they wait (see [StreamedLog]).
// Nil redirects it to os.Stderr with the default prefix; set Log.Disabled to turn the
// redirection off. Start, StartRaw and StartStream ignore it.
Log *StreamedLogOptions
}

Expand Down Expand Up @@ -150,6 +151,27 @@ func (c *ActorClient) StartRaw(ctx context.Context, input []byte, options ActorS
return c.startWithBody(ctx, input, "application/octet-stream", options, c.startTimeout(options))
}

// StartStream starts the Actor with a stream as its input, for a large input that is not held in
// memory, such as a file. The input has the content type "application/octet-stream" unless
// options.ContentType is set.
//
// The stream is sent as it is, once: the request is neither compressed nor retried, since a retry
// would send what the first attempt left of the stream, and a redirect comes back as an error.
// Hence options.WaitForResources is ignored, as the start is never retried. The client closes the
// stream when the call ends, if it is an [io.Closer]. The upload is bound by the "long" timeout
// tier, as the stream may be large.
func (c *ActorClient) StartStream(ctx context.Context, input io.Reader, options ActorStartOptions) (ActorRun, error) {
return c.startWithStream(ctx, input, options, extendForServerWait(c.ctx.longTimeout(), options.WaitForFinish))
}

// contentTypeOr returns options.ContentType, or fallback if it is unset or empty.
func (o ActorStartOptions) contentTypeOr(fallback string) string {
if o.ContentType != nil && *o.ContentType != "" {
return *o.ContentType
}
return fallback
}

// startTimeout is the timeout of a start request: the "medium" tier, extended to cover the time
// the API may hold the response for options.WaitForFinish.
func (c *ActorClient) startTimeout(options ActorStartOptions) time.Duration {
Expand All @@ -162,15 +184,20 @@ func (c *ActorClient) startTimeout(options ActorStartOptions) time.Duration {
func (c *ActorClient) startWithBody(ctx context.Context, body []byte, defaultContentType string, options ActorStartOptions, timeout time.Duration) (ActorRun, error) {
params := NewQueryParams()
options.apply(params)
contentType := defaultContentType
if options.ContentType != nil && *options.ContentType != "" {
contentType = *options.ContentType
}
contentType := options.contentTypeOr(defaultContentType)
return startWaitingForResources(ctx, options.WaitForResources, func() (ActorRun, error) {
return postWithBody[ActorRun](ctx, c.ctx.withoutTimeoutRetry(), "runs", params, body, contentType, timeout)
})
}

// startWithStream starts the Actor with a streamed input, which has the content type
// application/octet-stream unless options.ContentType is set.
func (c *ActorClient) startWithStream(ctx context.Context, input io.Reader, options ActorStartOptions, timeout time.Duration) (ActorRun, error) {
params := NewQueryParams()
options.apply(params)
return postStream[ActorRun](ctx, c.ctx, "runs", params, input, options.contentTypeOr("application/octet-stream"), timeout)
}

// Call starts the Actor and waits for it to finish. waitSecs bounds the wait, and nil waits
// indefinitely. It returns the finished run, or the running run if the wait ran out.
//
Expand All @@ -183,27 +210,36 @@ func (c *ActorClient) Call(ctx context.Context, input any, options ActorStartOpt
if err != nil {
return ActorRun{}, err
}
return c.callWithBody(ctx, body, contentTypeJSON, options, waitSecs)
return c.callAndWait(ctx, options, waitSecs, func(timeout time.Duration) (ActorRun, error) {
return c.startWithBody(ctx, body, contentTypeJSON, options, timeout)
})
}

// CallRaw starts the Actor with a raw request body ([ActorClient.StartRaw]) and waits for it to
// finish, exactly like [ActorClient.Call] but for a non-JSON input.
func (c *ActorClient) CallRaw(ctx context.Context, input []byte, options ActorStartOptions, waitSecs *int64) (ActorRun, error) {
return c.callWithBody(ctx, input, "application/octet-stream", options, waitSecs)
return c.callAndWait(ctx, options, waitSecs, func(timeout time.Duration) (ActorRun, error) {
return c.startWithBody(ctx, input, "application/octet-stream", options, timeout)
})
}

// CallStream starts the Actor with a stream as its input ([ActorClient.StartStream]) and waits
// for it to finish, exactly like [ActorClient.Call] but for a streamed input.
func (c *ActorClient) CallStream(ctx context.Context, input io.Reader, options ActorStartOptions, waitSecs *int64) (ActorRun, error) {
return c.callAndWait(ctx, options, waitSecs, func(timeout time.Duration) (ActorRun, error) {
return c.startWithStream(ctx, input, options, timeout)
})
}

// callWithBody is the shared implementation of Call and CallRaw.
func (c *ActorClient) callWithBody(ctx context.Context, body []byte, defaultContentType string, options ActorStartOptions, waitSecs *int64) (ActorRun, error) {
run, err := c.startWithBody(ctx, body, defaultContentType, options, noRequestTimeout)
// callAndWait is the shared implementation of Call, CallRaw and CallStream: it starts the run with
// start, which gets the timeout of the start request, and waits for it to finish.
func (c *ActorClient) callAndWait(ctx context.Context, options ActorStartOptions, waitSecs *int64, start func(timeout time.Duration) (ActorRun, error)) (ActorRun, error) {
run, err := start(noRequestTimeout)
if err != nil {
return ActorRun{}, err
}
// Use the root client's run client so polling targets the canonical run route.
runClient := c.root.Run(run.ID)
streamed := startLogRedirection(ctx, runClient, options.Log)
finished, err := runClient.WaitForFinish(ctx, waitSecs)
stopLogRedirection(ctx, streamed, options.Log)
return finished, err
return waitForFinishWithLog(ctx, c.root.Run(run.ID), options.Log, waitSecs)
}

// Build builds the given version of the Actor and returns the created build.
Expand Down
20 changes: 16 additions & 4 deletions actor_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,10 @@ type ActorServerRequestOptions struct {
// removes the client's header of that name.
Headers http.Header
// Body is the request body. A string or []byte is sent as it is, without a Content-Type
// unless Headers sets one. A [json.RawMessage] and any other value are sent as JSON, with
// unless Headers sets one. An [io.Reader] is a stream, sent the same way but only once: the
// request is neither compressed nor retried on 429 or 503, since a retry would send what the
// first attempt left of the stream, and the client closes it when the call ends, if it is an
// [io.Closer]. A [json.RawMessage] and any other value are sent as JSON, with
// Content-Type application/json unless Headers sets one.
Body any
// ParentRequestID is the X-Actor-Request-ID header of the request that the calling Server
Expand Down Expand Up @@ -341,16 +344,23 @@ func (c *ActorServerClient) RequestStream(ctx context.Context, path string, opti

// send validates the options, resolves the server URL and sends the request.
func (c *ActorServerClient) send(ctx context.Context, path string, options ActorServerRequestOptions, stream bool) (*serverResponse, error) {
bodyStream, _ := options.Body.(io.Reader)
method := strings.ToUpper(options.Method)
if method == "" {
method = http.MethodGet
}
if !httpMethods[method] || (options.Method != "" && options.Method != method) {
closeStream(bodyStream)
return nil, fmt.Errorf("ActorServerRequestOptions.Method: unknown HTTP method %q", options.Method)
}
body, contentType, err := encodeServerBody(options.Body)
if err != nil {
return nil, err
// A stream is sent as it is, so it is not encoded and its request is not retried.
var body []byte
var contentType string
if bodyStream == nil {
var err error
if body, contentType, err = encodeServerBody(options.Body); err != nil {
return nil, err
}
}
var compressors []requestCompressor
if options.Compression != nil {
Expand All @@ -359,6 +369,7 @@ func (c *ActorServerClient) send(ctx context.Context, path string, options Actor

serverURL, err := c.GetURL(ctx)
if err != nil {
closeStream(bodyStream)
return nil, err
}
headers := options.Headers
Expand All @@ -369,6 +380,7 @@ func (c *ActorServerClient) send(ctx context.Context, path string, options Actor
method: method,
url: serverRequestURL(serverURL, path, options.Params),
body: body,
bodyStream: bodyStream,
contentType: contentType,
headers: headers,
compressors: compressors,
Expand Down
21 changes: 21 additions & 0 deletions actor_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -817,3 +817,24 @@ func TestActorVersionCarriesTheActorPath(t *testing.T) {
t.Fatalf("a null actorPath must decode to nil: %v, %v", v.ActorPath, err)
}
}

// A stream body is sent as it is, once: not compressed, and not retried on 429 or 503, since a
// retry would send what the first attempt left of the stream.
func TestActorServerRequestSendsAStreamBodyOnce(t *testing.T) {
f := newServerFixture(t)
f.flaky = []int{503}
server := f.client(WithMaxRetries(2), WithMinDelayBetweenRetries(time.Millisecond)).Actor(serverTestActorID).Server()
resp, err := server.Request(context.Background(), "/flaky", ActorServerRequestOptions{
Method: "POST", Body: strings.NewReader(compressibleBody), Compression: Ptr(RequestCompressionGzip),
})
if err != nil || resp.StatusCode != 503 {
t.Fatalf("expected the 503 to be returned without a retry: %+v, %v", resp, err)
}
reqs := f.requests(serverTestPrefix + "/")
if len(reqs) != 1 || string(reqs[0].body) != compressibleBody || reqs[0].header.Get("Content-Encoding") != "" {
t.Fatalf("expected one uncompressed request with the whole stream, got %d", len(reqs))
}
if got := reqs[0].header.Get("Content-Type"); got != "" {
t.Errorf("a stream has no Content-Type of its own, got %q", got)
}
}
10 changes: 6 additions & 4 deletions actor_version.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,10 @@ func (c *ActorVersionCollectionClient) Iterate() *ListIterator[ActorVersion] {
return newUnpaginatedIterator(c.List)
}

// Create creates a new Actor version. version is any JSON-serializable version definition.
// Create creates a new Actor version. version is any JSON-serializable version definition. The
// request uses the long timeout tier, since the version can carry its source files.
func (c *ActorVersionCollectionClient) Create(ctx context.Context, version any) (ActorVersion, error) {
return createResource[ActorVersion](ctx, c.ctx, NewQueryParams(), version, c.ctx.shortTimeout())
return createResource[ActorVersion](ctx, c.ctx, NewQueryParams(), version, c.ctx.longTimeout())
}

// ActorVersionClient is a client for a specific Actor version
Expand All @@ -46,9 +47,10 @@ func (c *ActorVersionClient) Get(ctx context.Context) (ActorVersion, bool, error
return getResource[ActorVersion](ctx, c.ctx, "", NewQueryParams())
}

// Update updates the version with the given fields and returns the updated object.
// Update updates the version with the given fields and returns the updated object. The request
// uses the long timeout tier, since the version can carry its source files.
func (c *ActorVersionClient) Update(ctx context.Context, newFields any) (ActorVersion, error) {
return updateResource[ActorVersion](ctx, c.ctx, "", newFields)
return updateResourceWithTimeout[ActorVersion](ctx, c.ctx, "", newFields, c.ctx.longTimeout())
}

// Delete deletes the version.
Expand Down
36 changes: 36 additions & 0 deletions base.go
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,30 @@ func postWithBody[T any](ctx context.Context, c *resourceContext, subPath string
return parseDataEnvelope[T](resp.body)
}

// closeStream closes body if it is an [io.Closer], as the HTTP transport does for a request it
// sent, so that a stream is closed whether or not the call got as far as sending it.
func closeStream(body io.Reader) {
if closer, ok := body.(io.Closer); ok {
_ = closer.Close()
}
}

// postStream performs a POST with a stream as the body and unwraps the data envelope. The body is
// sent once (see [httpClient.callStream]).
func postStream[T any](ctx context.Context, c *resourceContext, subPath string, params *QueryParams, body io.Reader, contentType string, timeout time.Duration) (T, error) {
var zero T
if c.idErr != nil {
closeStream(body)
return zero, c.idErr
}
url := c.mergedParams(params).applyToURL(c.subURL(subPath))
resp, err := c.http.callStream(ctx, http.MethodPost, url, body, contentType, "", timeout)
if err != nil {
return zero, err
}
return parseDataEnvelope[T](resp.body)
}

// deleteWithBody performs a DELETE with a JSON body and unwraps the data envelope.
func deleteWithBody[T any](ctx context.Context, c *resourceContext, subPath string, params *QueryParams, body any) (T, error) {
var zero T
Expand Down Expand Up @@ -387,6 +411,18 @@ func putRawWithEncoding(ctx context.Context, c *resourceContext, subPath string,
return err
}

// putStream performs a PUT with a stream as the body. The body is sent once and as it is, under
// contentEncoding when that is not empty (see [httpClient.callStream]).
func putStream(ctx context.Context, c *resourceContext, subPath string, params *QueryParams, body io.Reader, contentType, contentEncoding string) error {
if c.idErr != nil {
closeStream(body)
return c.idErr
}
url := c.mergedParams(params).applyToURL(c.subURL(subPath))
_, err := c.http.callStream(ctx, http.MethodPut, url, body, contentType, contentEncoding, c.longTimeout())
return err
}

// streamRaw sends a GET request and returns the response body unread, with the response headers.
// The request is not retried, and the caller closes the body.
//
Expand Down
Loading
Loading