diff --git a/CHANGELOG.md b/CHANGELOG.md index ad5b4a1..3722994 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index dff8dcc..ac1f593 100644 --- a/README.md +++ b/README.md @@ -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). | @@ -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 @@ -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) @@ -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 diff --git a/actor.go b/actor.go index 804b589..4286450 100644 --- a/actor.go +++ b/actor.go @@ -4,6 +4,7 @@ import ( "context" "encoding/base64" "encoding/json" + "io" "net/http" "sync" "time" @@ -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 } @@ -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 { @@ -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. // @@ -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. diff --git a/actor_server.go b/actor_server.go index 6c993d0..d4b196f 100644 --- a/actor_server.go +++ b/actor_server.go @@ -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 @@ -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 { @@ -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 @@ -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, diff --git a/actor_server_test.go b/actor_server_test.go index 314136a..7d3a54e 100644 --- a/actor_server_test.go +++ b/actor_server_test.go @@ -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) + } +} diff --git a/actor_version.go b/actor_version.go index ac01cf2..28dc818 100644 --- a/actor_version.go +++ b/actor_version.go @@ -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 @@ -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. diff --git a/base.go b/base.go index d5c6317..69a91a0 100644 --- a/base.go +++ b/base.go @@ -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 @@ -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. // diff --git a/build.go b/build.go index e974399..927ac73 100644 --- a/build.go +++ b/build.go @@ -89,6 +89,9 @@ func (c *BuildClient) WaitForFinish(ctx context.Context, waitSecs *int64) (Build // GetOpenAPIDefinition returns the OpenAPI definition generated for the build, or // (nil, false, nil) if it is not available. The result is the raw OpenAPI document. +// +// The API needs no token for this if the Actor is public or if the build's owner has set general +// resource access to "Anyone with ID can read". Otherwise, the token must have access to the build. func (c *BuildClient) GetOpenAPIDefinition(ctx context.Context) (json.RawMessage, bool, error) { resp, err := getRaw(ctx, c.ctx, "openapi.json", NewQueryParams()) if err != nil { diff --git a/call_test.go b/call_test.go index 0662daa..45f083a 100644 --- a/call_test.go +++ b/call_test.go @@ -35,7 +35,7 @@ func TestCallStartsWithoutATimeout(t *testing.T) { }) t.Run("Task Call", func(t *testing.T) { backend := &slowBackend{delay: slowResponseDelay, body: run} - if _, err := slowClient(backend).Task("t").Call(context.Background(), nil, TaskStartOptions{}, Ptr(int64(0))); err != nil { + if _, err := slowClient(backend).Task("t").Call(context.Background(), nil, TaskStartOptions{Log: noLogRedirection}, Ptr(int64(0))); err != nil { t.Fatalf("Task Call: %v", err) } if n := backend.calls.Load(); n != 2 { diff --git a/dataset.go b/dataset.go index 5b819e3..0d36686 100644 --- a/dataset.go +++ b/dataset.go @@ -305,6 +305,10 @@ func (c *DatasetClient) GetStatistics(ctx context.Context) (json.RawMessage, err // // If the dataset has a URL signing secret key, the URL is signed, so it works without a token. // expiresInSecs is the validity of a signed URL, nil for no expiry, and it must be positive. +// +// The signature grants read access to all items of the dataset until it expires. The options are +// added to the URL as plain query parameters that the signature does not cover, so they only set +// the default shape of the response: anyone who holds the URL can change or remove them. func (c *DatasetClient) CreateItemsPublicURL(ctx context.Context, options DatasetListItemsOptions, expiresInSecs *int64) (string, error) { return c.CreateItemsPublicURLWithFormat(ctx, options, expiresInSecs, "") } diff --git a/docs/actors.md b/docs/actors.md index 4ef4e7c..8c8a871 100644 --- a/docs/actors.md +++ b/docs/actors.md @@ -85,6 +85,8 @@ The `Actor` value returned by `Get`/`Create`/`Update` and listed by `List`: | `StartRaw(ctx, input []byte, ActorStartOptions) (ActorRun, error)` | Like `Start`, but sends `input` as a raw request body (no JSON serialization) — for a non-JSON input such as a ZIP archive, paired with `ActorStartOptions.ContentType`. | | `Call(ctx, input any, ActorStartOptions, waitSecs *int64) (ActorRun, error)` | Start and wait for the run to finish, redirecting the run's log to `os.Stderr` while it waits (see `ActorStartOptions.Log`). `waitSecs` bounds the client-side wait; pass `nil` to wait indefinitely (until the run reaches a terminal state). Neither the start request nor the polls have a client-side timeout: `ctx` bounds the call. | | `CallRaw(ctx, input []byte, ActorStartOptions, waitSecs *int64) (ActorRun, error)` | `StartRaw` followed by waiting for the run to finish, like `Call`. | +| `StartStream(ctx, input io.Reader, ActorStartOptions) (ActorRun, error)` | Like `StartRaw`, but reads the input from a stream, such as a file, so it is not held in memory. The stream is sent once: the request is not compressed or retried (`WaitForResources` is ignored) and a redirect is an error. The client closes the stream when the call ends, if it is an `io.Closer`. The upload is bound by the long timeout tier. | +| `CallStream(ctx, input io.Reader, ActorStartOptions, waitSecs *int64) (ActorRun, error)` | `StartStream` followed by waiting for the run to finish, like `Call`. | | `Build(ctx, versionNumber string, ActorBuildOptions) (Build, error)` | Build a version. | | `DefaultBuild(ctx, waitForFinish *int64) (*BuildClient, error)` | Resolve the default build. | | `ValidateInput(ctx, input any) (json.RawMessage, error)` | Validate input against the `latest` build's schema. | @@ -153,11 +155,11 @@ fmt.Println(string(result)) // raw JSON validation result | `WaitForFinish` | `*int64` | Max seconds to wait server-side for the run to finish (max 60). | | `MaxItems` | `*int64` | Maximum dataset items to charge (pay-per-result Actors). | | `MaxTotalChargeUsd` | `*float64` | Maximum total charge in USD (pay-per-event Actors). | -| `ContentType` | `*string` | Content type of the input body. Defaults to `application/json` for `Start`/`Call`, or `application/octet-stream` for `StartRaw`/`CallRaw`, when unset. | +| `ContentType` | `*string` | Content type of the input body. Defaults to `application/json` for `Start`/`Call`, or `application/octet-stream` for `StartRaw`/`CallRaw`/`StartStream`/`CallStream`, when unset. | | `RestartOnError` | `*bool` | Restart the run if it fails. | | `ForcePermissionLevel` | `*string` | Override the Actor's permission level for this run. Accepted values: `LIMITED_PERMISSIONS`, `FULL_PERMISSIONS`. | | `Webhooks` | `[]any` | Ad-hoc webhooks to attach to this run. Each element is a map describing one webhook: `{"eventTypes": []string, "requestUrl": string, "payloadTemplate": string}` (same shape as a webhook definition; `eventTypes` are the `WebhookEventType` values listed in [webhooks.md](webhooks.md)). | -| `Log` | `*StreamedLogOptions` | Only for `Call`/`CallRaw`: how the run's log is redirected while they wait. `nil` redirects it to `os.Stderr`, with every message prefixed by `"{Actor name} runId:{run ID} -> "`. Set `Output` (an `io.Writer`), `Prefix` or `FromStart` to change that, or `Disabled` to turn the redirection off. See [`StreamedLog`](runs.md#log-redirection). `Start` and `StartRaw` ignore it. | +| `Log` | `*StreamedLogOptions` | Only for `Call`/`CallRaw`/`CallStream`: how the run's log is redirected while they wait. `nil` redirects it to `os.Stderr`, with every message prefixed by `"{Actor name} runId:{run ID} -> "`. Set `Output` (an `io.Writer`), `Prefix` or `Since` to change that, or `Disabled` to turn the redirection off. See [`StreamedLog`](runs.md#log-redirection). `Start`, `StartRaw` and `StartStream` ignore it. | | `WaitForResources` | `*int64` | Retry the start every 10 seconds while the API rejects it for lack of resources (`actor-memory-limit-exceeded` or `concurrent-runs-limit-exceeded`). `apify.WaitForResourcesIndefinitely` retries until the run starts; any other value is the number of seconds to retry for before returning the last error. `nil` (the default) does not retry. Any other error is returned immediately. | `ActorBuildOptions` (all fields optional): @@ -200,7 +202,7 @@ run, err := client.Actor("apify/hello-world").Call(ctx, | Method | Description | | --- | --- | -| `Versions().List(ctx)` / `Versions().Iterate()` / `Versions().Create(ctx, def)` | List/iterate/create versions. The endpoint returns every version in one response and takes no pagination parameters, so neither method takes options. | +| `Versions().List(ctx)` / `Versions().Iterate()` / `Versions().Create(ctx, def)` | List/iterate/create versions. `Create` and `Version(n).Update` use the long timeout tier, since a version can carry its source files. The endpoint returns every version in one response and takes no pagination parameters, so neither method takes options. | | `Version(n).Get/Update/Delete(ctx)` | Manage a single version. | | `Version(n).EnvVars().List(ctx)` / `.Iterate()` / `.Create(ctx, ActorEnvVar)` | List/iterate/create env vars. | | `Version(n).EnvVar(name).Get/Update/Delete(ctx)` | Manage a single env var. | diff --git a/docs/builds.md b/docs/builds.md index cf8b5b7..d364b13 100644 --- a/docs/builds.md +++ b/docs/builds.md @@ -18,7 +18,7 @@ single build with `client.Build(id)`, and an Actor's builds with `client.Actor(i | `Abort(ctx) (Build, error)` | Abort the build. | | `Delete(ctx) error` | Delete the build. | | `WaitForFinish(ctx, waitSecs *int64) (Build, error)` | Poll until the build is terminal. | -| `GetOpenAPIDefinition(ctx) (json.RawMessage, bool, error)` | The build's generated OpenAPI document. | +| `GetOpenAPIDefinition(ctx) (json.RawMessage, bool, error)` | The build's generated OpenAPI document. Needs no token if the Actor is public or the build's owner allows "Anyone with ID can read"; otherwise the token must have access to the build. | | `Log() *LogClient` | The build's log. | ```go diff --git a/docs/misc.md b/docs/misc.md index 5387e0e..305461b 100644 --- a/docs/misc.md +++ b/docs/misc.md @@ -2,29 +2,35 @@ ## Apify Store -Browse public Actors with `client.Store()`: +Browse and search public Actors with `client.Store()`. The API serves the Store in two ways, and the client has a method for each: `List` and `Iterate` go through the whole Store in Store order, page by page, and `Search` returns the Actors that match a query best, as a single page. | Method | Description | | --- | --- | -| `List(ctx, StoreListOptions) (PaginationList[ActorStoreListItem], error)` | One page of Store Actors. | -| `Iterate(StoreListOptions, chunkSize *int64) *StoreActorIterator` | Lazy iterator over matching Actors. `Limit` caps the total yielded; `chunkSize` is the page size. | +| `List(ctx, StoreListOptions) (PaginationList[ActorStoreListItem], error)` | One page of Store Actors in Store order. | +| `Iterate(StoreListOptions, chunkSize *int64) *StoreActorIterator` | Lazy iterator over matching Actors in Store order. `Limit` caps the total yielded; `chunkSize` is the page size. | +| `Search(ctx, StoreSearchOptions) (StoreSearchResult, error)` | The Actors that match a text query best, best match first, as a single page of at most 100. | `StoreListOptions` (all fields optional): | Field | Type | Meaning | |---|---|---| | `Offset` | `*int64` | Number of Actors to skip. | -| `Limit` | `*int64` | Maximum number of Actors to return. | -| `Search` | `*string` | Full-text search query. | -| `SortBy` | `*string` | Sort field (e.g. `"popularity"`, `"newest"`). | -| `Category` | `*string` | Filter Actors by category. | +| `Limit` | `*int64` | Maximum number of Actors to return. The default and the maximum are 1000. | +| `Category` | `*string` | Filter Actors by category. Takes one or more category IDs, separated by commas and case-insensitive; an Actor must match all of them, for example `AI_AND_ML`. An unknown category makes the API answer with a 400 error. | | `Username` | `*string` | Filter Actors by owner username. | | `PricingModel` | `*string` | Filter by pricing model. Accepted values: `FREE`, `PRICE_PER_DATASET_ITEM`, `PAY_PER_EVENT`. | -| `IncludeUnrunnableActors` | `*bool` | Include Actors the current user cannot run. | -| `AllowsAgenticUsers` | `*bool` | Filter to Actors that allow agentic users. | -| `ResponseFormat` | `*string` | Select the response format. Accepted values: `full`, `agent`. | +| `IncludeUnrunnableActors` | `*bool` | Turn off the safety filter that leaves out Actors that are not safe to run automatically, such as those of developers without a verified identity and Actors with full permissions that have few users. | +| `ResponseFormat` | `*string` | Shape of the response. `full` (default) returns every field, and `agent` a reduced field set for LLM consumers, in which `URL`, `UserPictureURL`, `IsVerified` and the optional `Stats` counts are `nil`. | | `IncludeInputSchema` | `*bool` | Add to each Actor an `inputSchema` field with a compact version of its default build's input schema. With it set, the API defaults `Limit` to 10 and does not accept a larger one. | +`StoreSearchOptions` has the same `Limit`, `Category`, `Username`, `PricingModel`, `IncludeUnrunnableActors`, `ResponseFormat` and `IncludeInputSchema` fields, with these differences: there is no `Offset`, as the API ignores it for a search, `Limit` defaults to 100 and is reduced to 100 if larger, and `Search` is added. + +| Field | Type | Meaning | +|---|---|---| +| `Search` | `string` | Text to search for. Required: `Search` returns an error, without a request, if it is empty. | + +`StoreSearchResult` has the fields `Items` (`[]ActorStoreListItem`, best match first) and `Limit` (`int64`, the number of Actors the API allowed in the result). The API sends no next page and does not report how many Actors match in total, so a result with `len(Items) == Limit` can be cut off: narrow it down with a more specific query or with `Category`, `Username` or `PricingModel`. + Each item is an `ActorStoreListItem`: | Field | Type | Meaning | @@ -35,11 +41,14 @@ Each item is an `ActorStoreListItem`: | `Title` | `string` | Human-readable title (may be empty; fall back to `Name`). | | `URL` | `*string` | URL of the Actor's page in the Apify Store, normalized. `nil` when there is none. | | `UserPictureURL` | `*string` | URL of the owner's profile picture, normalized. `nil` when there is none. | +| `Categories` | `[]string` | IDs of the categories the Actor belongs to, for example `AI_AND_ML`. `nil` when the API reports none. | +| `Stats` | `StoreActorStats` | Usage statistics and Store metrics: `TotalUsers`, `ActorReviewRating` and `ActorReviewCount`, plus `TotalRuns`, `TotalUsers7Days`, `TotalUsers30Days` and `TotalUsers90Days` (`*int64`, `nil` when absent). | +| `IsVerified` | `*bool` | Whether the Actor's developer has a verified identity. `nil` when the API does not return it. | | `Extra` | `map[string]json.RawMessage` | Any other fields returned by the API (forward compatibility). | ```go // Limit caps the total number of Actors yielded; the second argument is the per-page size. -it := client.Store().Iterate(apify.StoreListOptions{Limit: apify.Ptr(int64(20)), Search: apify.Ptr("scraper")}, apify.Ptr(int64(10))) +it := client.Store().Iterate(apify.StoreListOptions{Limit: apify.Ptr(int64(20)), Category: apify.Ptr("AI_AND_ML")}, apify.Ptr(int64(10))) for { actor, err := it.Next(ctx) if err != nil { @@ -50,6 +59,15 @@ for { } fmt.Println(actor.Title, actor.ID) } + +// Find the Actors that match a query best. +result, err := client.Store().Search(ctx, apify.StoreSearchOptions{Search: "web scraper", Limit: apify.Ptr(int64(10))}) +if err != nil { + log.Fatal(err) +} +for _, actor := range result.Items { + fmt.Println(actor.Title, actor.ID) +} ``` ## Users diff --git a/docs/runs.md b/docs/runs.md index 23d881b..df6bbb8 100644 --- a/docs/runs.md +++ b/docs/runs.md @@ -130,8 +130,8 @@ run's metadata. The commonly used fields: ## Log redirection -`ActorClient.Call` redirects the log of the run while it waits (set `ActorStartOptions.Log` to -change where it goes or turn it off). To redirect the log of any run, create a `StreamedLog`: +`ActorClient.Call` and `TaskClient.Call` redirect the log of the run while they wait (set +`ActorStartOptions.Log` or `TaskStartOptions.Log` to change where it goes or turn it off). To redirect the log of any run, create a `StreamedLog`: ```go streamed, found, err := client.Run(runID).NewStreamedLog(ctx, apify.StreamedLogOptions{Output: os.Stdout}) @@ -156,22 +156,31 @@ if err := streamed.Stop(ctx); err != nil { |---|---|---| | `Output` | `io.Writer` | Receives every message, one per line, with the prefix. Defaults to `os.Stderr`. Writes are serialized. | | `Prefix` | `*string` | Written in front of every message. The default is `"{Actor name} runId:{run ID} -> "`, which costs two requests (the run and its Actor); a non-nil `Prefix`, an empty one included, skips them. | -| `FromStart` | `*bool` | `false` drops the messages that were logged before the redirection was created. Default `true`. | -| `Disabled` | `bool` | Turns the redirection off in `ActorStartOptions.Log`. | +| `Since` | `*time.Time` | Drops the messages logged before this time. Nil redirects the whole log. To continue a redirection after a restart, pass `LastRedirectedAt` plus one millisecond. | +| `FromStart` | `*bool` | Deprecated: use `Since`. `false` drops the messages that were logged before the redirection was created. Default `true`. `Since` takes precedence. | +| `Disabled` | `bool` | Turns the redirection off in `ActorStartOptions.Log` and `TaskStartOptions.Log`. | The log is split into messages at the timestamps the platform puts in front of each of them, so a message that spans several lines is written as one, even when its lines arrive in separate reads; the last message is therefore written when the next one starts or the log ends. `Start` begins the redirection in the background, and it also ends when the `ctx` it got is done. `Stop` gives the -messages in flight up to one second, then aborts the stream; if the stream delivered nothing yet, -it reads the whole log in one request, so a short run that finished before the stream connected is -not lost. The `ctx` given to `Stop` bounds that wait and that read: when it is done first, `Stop` -returns its error and the rest of the log is not redirected, unless the `ctx` given to `Start` -ended first, which ends the redirection on purpose and is not an error. When both end at about the -same time, either result is possible. A second `Stop` while one is running returns an error. A log -that has no bytes yet (the run has not logged anything) is reopened, pausing from 500ms up to 5s, -until its first bytes arrive. `Stop` returns the error that ended the redirection early, if any; -`Call` reports it on the redirection's output and goes on. +messages in flight up to one second, then aborts the stream. If the stream delivered nothing yet, a +short run that finished before the stream connected would be lost, and if the stream was cut off and +its replacement has not caught up with the messages already redirected, the messages after the cut +would be. In both cases it reads the whole log in one request and redirects what is missing. The +`ctx` given to `Stop` bounds that wait and that read: when it is done first, `Stop` returns its +error and the rest of the log is not redirected, unless the `ctx` given to `Start` ended first, +which ends the redirection on purpose and is not an error. When both end at about the same time, +either result is possible. A second `Stop` while one is running returns an error. A log that has no +bytes yet (the run has not logged anything) is reopened, pausing from 500ms up to 5s, until its +first bytes arrive. A stream that is cut off after it delivered data, which the API does with a +stream that carried no data for several minutes while the run goes on, is reopened after one second. +The API cannot continue a stream from a given point, so the reopened stream replays the log from its +start, and the messages that were already redirected are skipped. If the reopened stream breaks off +again before it reaches the last redirected message, the redirection ends with an error. +`LastRedirectedAt() (time.Time, bool)` returns the time of the last redirected message, and false if +there is none yet. `Stop` returns the error that ended the redirection early, if any; `Call` reports +it on the redirection's output and goes on. ## Live iteration of dataset items diff --git a/docs/server_actors.md b/docs/server_actors.md index 03d5f58..af4bb72 100644 --- a/docs/server_actors.md +++ b/docs/server_actors.md @@ -74,7 +74,7 @@ _ = handler | `Method` | `string` | The HTTP method, in upper case. Defaults to `GET`. An unknown method fails before any request is sent. | | `Params` | `url.Values` | Query parameters. | | `Headers` | `http.Header` | Additional headers. They reach the Actor's server as they are and win over the headers the client sets; a header with no values removes the client's header of that name. | -| `Body` | `any` | A `string` or `[]byte` is sent as it is. A `json.RawMessage` and any other value are sent as JSON with `Content-Type: application/json`, unless `Headers` sets a content type. | +| `Body` | `any` | A `string` or `[]byte` is sent as it is. An `io.Reader` is a stream, sent as it is but once: it is not compressed and not retried on 429 or 503, since a retry would send what the first attempt left of it. 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 a content type. | | `ParentRequestID` | `string` | The `X-Actor-Request-ID` header of the request your Server Actor is handling. It is sent on as the same header, so the called Actor charges at the pricing tier of that request, and it wins over the same header in `Headers`. Use a client created with the run's `APIFY_TOKEN`. | | `Compression` | `*apify.RequestCompression` | Compresses a body of 1 KiB or more. Nil by default, which sends the body uncompressed, since the Actor's server may not decode a compressed body. Set it only if the server decodes the resulting `Content-Encoding`. A `Content-Encoding` header in `Headers` sends the body untouched. | diff --git a/docs/storages.md b/docs/storages.md index b7a273f..8f1febc 100644 --- a/docs/storages.md +++ b/docs/storages.md @@ -23,7 +23,7 @@ Single dataset: `client.Dataset(id)`: | `DownloadItems(ctx, DownloadItemsFormat, DatasetDownloadOptions) ([]byte, error)` | Export items (JSON, JSONL, CSV, XLSX, XML, RSS, HTML — see the format constants below). | | `DownloadItemsStream(ctx, DownloadItemsFormat, DatasetDownloadOptions) (io.ReadCloser, error)` | Like `DownloadItems`, but as a stream for a large export; close when done. | | `GetStatistics(ctx) (json.RawMessage, error)` | Dataset statistics. | -| `CreateItemsPublicURL(ctx, DatasetListItemsOptions, expiresInSecs *int64) (string, error)` | Signed public items URL, served as `json`. `expiresInSecs` must be positive (nil for a URL that never expires); zero or a negative value is an error returned before any request. | +| `CreateItemsPublicURL(ctx, DatasetListItemsOptions, expiresInSecs *int64) (string, error)` | Signed public items URL, served as `json`. `expiresInSecs` must be positive (nil for a URL that never expires); zero or a negative value is an error returned before any request. The signature grants read access to all items until it expires. The options are plain query parameters that it does not cover, so anyone who holds the URL can change or remove them. | | `CreateItemsPublicURLWithFormat(ctx, DatasetListItemsOptions, expiresInSecs *int64, DownloadItemsFormat) (string, error)` | Like `CreateItemsPublicURL`, but lets the URL serve another export format (CSV, XLSX, ...). An empty format defaults to `json`. | The `Dataset` value returned by `Get`/`GetOrCreate`/`Update` and listed by `List`/`Iterate`: @@ -174,6 +174,8 @@ Single store: `client.KeyValueStore(id)`: | `GetRecordStream(ctx, key) (*KeyValueStoreRecordStream, bool, error)` | Like `GetRecord`, but the value is a stream for a large record; close when done. | | `GetRecordStreamWithOptions(ctx, key, GetRecordOptions)` | Stream with options. | | `SetRecordRaw(ctx, key, value []byte, contentType string) error` | Write raw bytes, sent as they are: the client does not parse or convert the value, whatever the content type (so `application/json` bytes must already be valid JSON). | +| `SetRecordStream(ctx, key, value io.Reader, contentType string) error` | Write a value read from a stream, such as a file, so it is not held in memory. The stream is sent once: the request is not compressed or retried and a redirect is an error. The client closes the stream when the call ends, if it is an `io.Closer`. To upload with retries, read the value into bytes and use `SetRecordRaw`. | +| `SetRecordStreamWithEncoding(ctx, key, value io.Reader, contentType, contentEncoding string) error` | Like `SetRecordStream`, for a stream that is already compressed. `contentEncoding`, such as `gzip`, `br`, `zstd`, or `deflate`, is sent as the `Content-Encoding` header. | | `SetRecordRawWithOptions(ctx, key, value []byte, contentType string, SetRecordOptions) error` | Like `SetRecordRaw`, with `ContentEncoding` (the value is already compressed, as with `SetRecordRawWithEncoding`) and `DoNotRetryTimeouts` (an upload that times out fails at once instead of being retried). | | `SetRecordRawWithEncoding(ctx, key, value []byte, contentType, contentEncoding string) error` | Write raw bytes that are already compressed (`contentEncoding` e.g. `"gzip"`, `"br"`, `"zstd"`, `"deflate"`): sent as-is under `Content-Encoding`, skipping the client's own request compression so the value is never compressed twice. | | `SetRecordJSON(ctx, key, value any) error` | Write JSON. | @@ -181,7 +183,7 @@ Single store: `client.KeyValueStore(id)`: | `RecordExists(ctx, key) (bool, error)` | HEAD check. | | `DeleteRecord(ctx, key) error` | Delete a record. | | `GetRecordPublicURL(ctx, key) (string, error)` | Signed public record URL. | -| `CreateKeysPublicURL(ctx, expiresInSecs *int64) (string, error)` | Signed public key-list URL. `expiresInSecs` must be positive (nil for a URL that never expires); zero or a negative value is an error returned before any request. | +| `CreateKeysPublicURL(ctx, expiresInSecs *int64) (string, error)` | Signed public key-list URL. `expiresInSecs` must be positive (nil for a URL that never expires); zero or a negative value is an error returned before any request. The signature grants access to the list of all keys until it expires. | The `KeyValueStore` value returned by `Get`/`GetOrCreate`/`Update` and listed by `List`/`Iterate`: diff --git a/docs/tasks.md b/docs/tasks.md index 3283073..c2ef711 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -50,7 +50,9 @@ A task is a pre-configured Actor run with stored input. Access the task collecti | `Publish(ctx) (Task, error)` | Publish the task on its public landing page. An Actor can have at most 10 published tasks, and an account at most 100 (contact Apify support to raise either limit). | | `Unpublish(ctx) (Task, error)` | Unpublish the task from its public landing page. | | `Start(ctx, input any, TaskStartOptions) (ActorRun, error)` | Start a run (input overrides stored input). | -| `Call(ctx, input any, TaskStartOptions, waitSecs *int64) (ActorRun, error)` | Start and wait. Neither the start request nor the polls have a client-side timeout: `ctx` bounds the call. | +| `Call(ctx, input any, TaskStartOptions, waitSecs *int64) (ActorRun, error)` | Start and wait. Neither the start request nor the polls have a client-side timeout: `ctx` bounds the call. While it waits, it redirects the run's log to `os.Stderr`, or as `TaskStartOptions.Log` says. See [`StreamedLog`](runs.md#log-redirection). | +| `StartStream(ctx, input io.Reader, TaskStartOptions) (ActorRun, error)` | Like `Start`, but reads the input from a stream, such as a file, so it is not held in memory. The stream must hold a JSON object, which is sent as `application/json`. It is sent once: the request is not compressed or retried (`WaitForResources` is ignored) and a redirect is an error. The client closes the stream when the call ends, if it is an `io.Closer`. The upload is bound by the long timeout tier. | +| `CallStream(ctx, input io.Reader, TaskStartOptions, waitSecs *int64) (ActorRun, error)` | `StartStream` followed by waiting for the run to finish, with the same log redirection as `Call`. | | `GetInput(ctx) (json.RawMessage, error)` | Fetch the stored input. | | `UpdateInput(ctx, input any) (json.RawMessage, error)` | Replace the stored input. | | `LastRun(status string) *RunClient` | Client for the last run (optional status filter). | diff --git a/http_client.go b/http_client.go index 321da26..410cf04 100644 --- a/http_client.go +++ b/http_client.go @@ -43,8 +43,13 @@ const ( // A non-2xx status is a normal *http.Response. Return an error only for a transport failure such // as a refused connection, a DNS error or a timeout. // +// A backend must close the request 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 [FollowsRedirects] -// reports false for: such a request carries credentials meant for its original host only. +// reports false for: such a request carries credentials meant for its original host only, or a +// stream body that a redirect cannot replay. type HTTPBackend interface { // Do sends a single HTTP request and returns the response. Do(req *http.Request) (*http.Response, error) @@ -152,6 +157,21 @@ func (c *httpClient) callPreEncoded(ctx context.Context, method, url string, bod return c.doRetryLoop(ctx, method, url, body, contentType, contentEncoding, nil, baseTimeout) } +// callStream is [httpClient.call] for a body that is a stream. The body is sent as it is, in a +// single attempt without the client's own compression: a retry would send what is left of a +// stream that the failed attempt consumed, and a redirect cannot replay it, so one is returned as +// an error. contentEncoding, when not empty, says that the stream is already compressed under it. +func (c *httpClient) callStream(ctx context.Context, method, url string, body io.Reader, contentType, contentEncoding string, baseTimeout time.Duration) (*apiResponse, error) { + resp, err := c.doAttemptReader(withoutRedirects(ctx), method, url, body, contentType, contentEncoding, nil, c.attemptTimeout(baseTimeout, 1)) + if err != nil { + return nil, err + } + if resp.statusCode >= minNonSuccessStatusCode { + return nil, buildAPIError(resp.statusCode, resp.body, 1, method, extractPath(url)) + } + return resp, nil +} + // doRetryLoop sends the request and retries retryable failures with exponential backoff. func (c *httpClient) doRetryLoop(ctx context.Context, method, url string, sendBody []byte, contentType, contentEncoding string, extraHeaders map[string]string, baseTimeout time.Duration) (*apiResponse, error) { delay := c.retry.minDelayBetweenRetries @@ -211,13 +231,10 @@ func (c *httpClient) applyAuthHeadersAs(req *http.Request, tokenHeader string) { } // newRequest builds a request with the User-Agent header, the token in tokenHeader and the -// content headers. A non-empty contentEncoding says that body is compressed with it. -func (c *httpClient) newRequest(ctx context.Context, method, url string, body []byte, contentType, contentEncoding, tokenHeader string) (*http.Request, error) { - var reader io.Reader - if body != nil { - reader = bytes.NewReader(body) - } - req, err := http.NewRequestWithContext(ctx, method, url, reader) +// content headers. A non-empty contentEncoding says that body is compressed with it. A nil body +// sends no body. +func (c *httpClient) newRequest(ctx context.Context, method, url string, body io.Reader, contentType, contentEncoding, tokenHeader string) (*http.Request, error) { + req, err := http.NewRequestWithContext(ctx, method, url, body) if err != nil { return nil, err } @@ -231,8 +248,21 @@ func (c *httpClient) newRequest(ctx context.Context, method, url string, body [] return req, nil } +// bodyReader returns a reader of body, which is nil for a nil body, so that the request has no body. +func bodyReader(body []byte) io.Reader { + if body == nil { + return nil + } + return bytes.NewReader(body) +} + // doAttempt performs one round-trip with the given timeout. func (c *httpClient) doAttempt(ctx context.Context, method, url string, body []byte, contentType, contentEncoding string, extraHeaders map[string]string, timeout time.Duration) (*apiResponse, error) { + return c.doAttemptReader(ctx, method, url, bodyReader(body), contentType, contentEncoding, extraHeaders, timeout) +} + +// doAttemptReader is [httpClient.doAttempt] for a body that is a reader. +func (c *httpClient) doAttemptReader(ctx context.Context, method, url string, body io.Reader, contentType, contentEncoding string, extraHeaders map[string]string, timeout time.Duration) (*apiResponse, error) { attemptCtx := ctx cancel := func() {} if timeout != noRequestTimeout { @@ -242,6 +272,7 @@ func (c *httpClient) doAttempt(ctx context.Context, method, url string, body []b req, err := c.newRequest(attemptCtx, method, url, body, contentType, contentEncoding, "Authorization") if err != nil { + closeStream(body) // An invalid request is a caller error, so it is not retried. return nil, &APIError{StatusCode: 0, Type: "invalid-request", Message: err.Error(), Attempt: 1, HTTPMethod: method, Path: extractPath(url)} } diff --git a/key_value_store.go b/key_value_store.go index 9cd00b8..0d2cd6b 100644 --- a/key_value_store.go +++ b/key_value_store.go @@ -3,6 +3,7 @@ package apify import ( "context" "encoding/json" + "io" ) // ListKeysOptions configures [KeyValueStoreClient.ListKeys]. @@ -273,6 +274,32 @@ func (c *KeyValueStoreClient) SetRecordRawWithEncoding(ctx context.Context, key return c.setRecord(ctx, key, value, contentType, contentEncoding, true, false) } +// SetRecordStream stores a record whose value is read from a stream, for a large value that is not +// held in memory, such as a file. 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. The client closes the stream when the call ends, if it is an +// [io.Closer]. To upload with retries, read the value into bytes and use +// [KeyValueStoreClient.SetRecordRaw]. +func (c *KeyValueStoreClient) SetRecordStream(ctx context.Context, key string, value io.Reader, contentType string) error { + return c.setRecordStream(ctx, key, value, contentType, "") +} + +// SetRecordStreamWithEncoding is [KeyValueStoreClient.SetRecordStream] for a stream that is +// already compressed. contentEncoding, such as "gzip", "br", "zstd" or "deflate", is sent as the +// Content-Encoding header. +func (c *KeyValueStoreClient) SetRecordStreamWithEncoding(ctx context.Context, key string, value io.Reader, contentType, contentEncoding string) error { + return c.setRecordStream(ctx, key, value, contentType, contentEncoding) +} + +func (c *KeyValueStoreClient) setRecordStream(ctx context.Context, key string, value io.Reader, contentType, contentEncoding string) error { + safeKey, err := safePathSegment(key) + if err != nil { + closeStream(value) + return err + } + return putStream(ctx, c.ctx, "records/"+safeKey, NewQueryParams(), value, contentType, contentEncoding) +} + // setRecord is the shared implementation of the SetRecord methods. preEncoded sends value exactly // as given under contentEncoding (which may be empty), skipping the client's own request // compression; doNotRetryTimeouts makes an upload attempt that timed out fail at once. @@ -367,6 +394,8 @@ func (c *KeyValueStoreClient) GetRecordPublicURL(ctx context.Context, key string // As with GetRecordPublicURL, a signature is appended for private stores. expiresInSecs // optionally bounds the validity of a signed URL (nil for non-expiring); it must be positive, and // a zero or negative value is an error returned before any request is sent. +// +// The signature grants access to the list of all keys of the store until it expires. func (c *KeyValueStoreClient) CreateKeysPublicURL(ctx context.Context, expiresInSecs *int64) (string, error) { if err := validateExpiresInSecs(expiresInSecs); err != nil { return "", err diff --git a/models.go b/models.go index d435c96..d01b245 100644 --- a/models.go +++ b/models.go @@ -599,10 +599,40 @@ type ActorStoreListItem struct { // UserPictureURL is the URL of the owner's profile picture, normalized. Nil when there is // none. UserPictureURL *string `json:"userPictureUrl,omitempty"` + // Categories are the IDs of the categories the Actor belongs to, for example "AI_AND_ML". Nil + // when the API reports none. + Categories []string `json:"categories,omitempty"` + // Stats are the usage statistics and Apify Store metrics of the Actor. + Stats StoreActorStats `json:"stats"` + // IsVerified reports whether the Actor's developer has a verified identity. Nil when the API + // does not return it. + IsVerified *bool `json:"isVerified,omitempty"` // Extra holds any other fields returned by the API. Extra Extra `json:"-"` } +// StoreActorStats are the usage statistics and Apify Store metrics of a Store Actor, as returned +// by the Store endpoint. +type StoreActorStats struct { + // TotalUsers is the total number of Actor users, including its owner. + TotalUsers int64 `json:"totalUsers"` + // TotalRuns is the total number of runs of the Actor. Nil when the API does not return it. + TotalRuns *int64 `json:"totalRuns,omitempty"` + // TotalUsers7Days is the number of active users of the Actor in the last 7 days. Nil when the + // API does not return it. + TotalUsers7Days *int64 `json:"totalUsers7Days,omitempty"` + // TotalUsers30Days is the number of active users of the Actor in the last 30 days. Nil when + // the API does not return it. + TotalUsers30Days *int64 `json:"totalUsers30Days,omitempty"` + // TotalUsers90Days is the number of active users of the Actor in the last 90 days. Nil when + // the API does not return it. + TotalUsers90Days *int64 `json:"totalUsers90Days,omitempty"` + // ActorReviewRating is the average rating of the Actor in Apify Store. + ActorReviewRating float64 `json:"actorReviewRating"` + // ActorReviewCount is the number of reviews the Actor has received in Apify Store. + ActorReviewCount int64 `json:"actorReviewCount"` +} + func (a *ActorStoreListItem) UnmarshalJSON(data []byte) error { type alias ActorStoreListItem known := knownJSONKeys(alias{}) diff --git a/models_test.go b/models_test.go index 566cdc1..6bf85a2 100644 --- a/models_test.go +++ b/models_test.go @@ -39,3 +39,31 @@ func TestUserProxyInfoParses(t *testing.T) { t.Errorf("unexpected user %+v", user) } } + +// A Store Actor carries its categories, the Store statistics and the verified flag as typed +// fields: the statistics that older Store responses lacked stay nil. +func TestActorStoreListItemParsesStatsAndCategories(t *testing.T) { + var item ActorStoreListItem + mustUnmarshal(t, `{"id":"a1","name":"n","username":"u","title":"T","categories":["AI_AND_ML","ECOMMERCE"], + "stats":{"totalUsers":6,"totalRuns":16,"actorReviewRating":4.7,"actorReviewCount":69}, + "isVerified":true,"badge":null}`, &item) + if len(item.Categories) != 2 || item.Categories[0] != "AI_AND_ML" { + t.Errorf("unexpected categories %v", item.Categories) + } + stats := item.Stats + if stats.TotalUsers != 6 || stats.ActorReviewRating != 4.7 || stats.ActorReviewCount != 69 { + t.Errorf("unexpected required stats %+v", stats) + } + if stats.TotalRuns == nil || *stats.TotalRuns != 16 || stats.TotalUsers7Days != nil { + t.Errorf("unexpected optional stats %+v", stats) + } + if item.IsVerified == nil || !*item.IsVerified || string(item.Extra["badge"]) != "null" { + t.Errorf("unexpected item %+v", item) + } + + var minimal ActorStoreListItem + mustUnmarshal(t, `{"id":"a2","name":"n","username":"u","title":"T","categories":null,"stats":{"totalUsers":0,"actorReviewRating":0,"actorReviewCount":0}}`, &minimal) + if minimal.Categories != nil || minimal.IsVerified != nil { + t.Errorf("unexpected minimal item %+v", minimal) + } +} diff --git a/run.go b/run.go index 7bf2c6d..f2cd593 100644 --- a/run.go +++ b/run.go @@ -76,7 +76,7 @@ func newRunClient(root *ApifyClient, hc *httpClient, baseURL, resourcePath, id s type LastRunOptions struct { // Status filters by run status (e.g. "SUCCEEDED", "FAILED", "RUNNING"). Status string - // Origin filters by how the run was started (e.g. "DEVELOPMENT", "WEB", "API", "SCHEDULER"). + // Origin filters by how the run was started (e.g. "DEVELOPMENT", "WEB", "API", "SCHEDULER", "APIFY_AI"). Origin string } diff --git a/server_http.go b/server_http.go index d7ce518..f299f07 100644 --- a/server_http.go +++ b/server_http.go @@ -27,15 +27,16 @@ type noRedirectsKey struct{} // withoutRedirects returns a context that tells the HTTP backend not to follow redirects. The // request to an Actor's server carries the API token, which a redirect target picked by the -// Actor's code must never receive. +// Actor's code must never receive, and a request with a stream body cannot be replayed. func withoutRedirects(ctx context.Context) context.Context { return context.WithValue(ctx, noRedirectsKey{}, true) } // FollowsRedirects reports whether the HTTP backend may follow redirects for req. It is false // for the requests that carry credentials meant for one host only, such as those sent by -// [ActorServerClient]: such a request must get a redirect response back as it is. A custom -// [HTTPBackend] that follows redirects has to check it, and the [DefaultHTTPBackend] does. +// [ActorServerClient], and for those with a stream body, which a redirect cannot replay: such a +// request must get a redirect response back as it is. A custom [HTTPBackend] that follows +// redirects has to check it, and the [DefaultHTTPBackend] does. func FollowsRedirects(req *http.Request) bool { return req.Context().Value(noRedirectsKey{}) == nil } @@ -45,6 +46,9 @@ type serverCall struct { method string url string body []byte + // bodyStream is a request body that is a stream. It is sent as it is, in a single attempt + // (a retry would send what the first attempt left of it), and body is empty. + bodyStream io.Reader // contentType is the Content-Type of the body, set before the caller's headers. contentType string // headers are the caller's headers. They are applied last, so they win over every header @@ -85,8 +89,8 @@ func (c *httpClient) callServer(ctx context.Context, call serverCall) (*serverRe sendBody, contentEncoding := call.body, "" // A Content-Encoding header of the caller, even one without values (which removes the label), - // says that the body is theirs to encode. - if _, encodedByCaller := call.headers["Content-Encoding"]; !encodedByCaller { + // says that the body is theirs to encode. A stream is never compressed. + if _, encodedByCaller := call.headers["Content-Encoding"]; !encodedByCaller && call.bodyStream == nil { // The Content-Type that goes on the wire decides whether the body is worth compressing, // and the caller's header wins over the one the client derived from the body. contentType := call.contentType @@ -98,8 +102,15 @@ func (c *httpClient) callServer(ctx context.Context, call serverCall) (*serverRe delay := c.retry.minDelayBetweenRetries maxAttempts := c.retry.maxRetries + 1 + if call.bodyStream != nil { + maxAttempts = 1 + } for attempt := 1; ; attempt++ { - resp, err := c.serverAttempt(withoutRedirects(ctx), call, sendBody, contentEncoding, c.attemptTimeout(call.timeout, attempt)) + body := call.bodyStream + if body == nil { + body = bodyReader(sendBody) + } + resp, err := c.serverAttempt(withoutRedirects(ctx), call, body, contentEncoding, c.attemptTimeout(call.timeout, attempt)) if err != nil { return nil, err } @@ -117,7 +128,7 @@ func (c *httpClient) callServer(ctx context.Context, call serverCall) (*serverRe } // serverAttempt performs a single round-trip of call. -func (c *httpClient) serverAttempt(ctx context.Context, call serverCall, body []byte, contentEncoding string, timeout time.Duration) (*serverResponse, error) { +func (c *httpClient) serverAttempt(ctx context.Context, call serverCall, body io.Reader, contentEncoding string, timeout time.Duration) (*serverResponse, error) { attemptCtx, cancel := context.WithCancelCause(ctx) // A buffered response is bounded as a whole, a stream only until its headers arrive. var timer *time.Timer @@ -132,6 +143,7 @@ func (c *httpClient) serverAttempt(ctx context.Context, call serverCall, body [] req, err := c.newRequest(attemptCtx, call.method, call.url, body, call.contentType, contentEncoding, serverAuthorizationHeader) if err != nil { + closeStream(body) stopTimer() cancel(nil) return nil, err diff --git a/store_collection.go b/store_collection.go index 8c48ee6..91d5768 100644 --- a/store_collection.go +++ b/store_collection.go @@ -1,28 +1,33 @@ package apify -import "context" +import ( + "context" + "errors" +) -// StoreListOptions configures listing/iterating the Apify Store. +// StoreListOptions configures [StoreCollectionClient.List] and [StoreCollectionClient.Iterate], +// which go through the whole Store in Store order. To find Actors by a text query, use +// [StoreCollectionClient.Search] instead. type StoreListOptions struct { // Offset is the number of Actors to skip. Offset *int64 - // Limit is the maximum number of Actors to return. + // Limit is the maximum number of Actors to return. The default and the maximum are 1000. Limit *int64 - // Search filters Actors by a full-text search query. - Search *string - // SortBy sets the sort field (e.g. "popularity", "newest"). - SortBy *string - // Category filters Actors by category. + // Category filters Actors by category. It takes one or more category IDs, separated by commas + // and case-insensitive, and an Actor must match all of them (for example "AI_AND_ML"). An + // unknown category makes the API answer with a 400 error. Category *string // Username filters Actors by owner username. Username *string // PricingModel filters Actors by pricing model (e.g. "FREE", "PAY_PER_EVENT"). PricingModel *string - // IncludeUnrunnableActors includes Actors the current user cannot run. + // IncludeUnrunnableActors, if true, turns off the safety filter that leaves out Actors that + // are not safe to run automatically, such as those of developers without a verified identity + // and Actors with full permissions that have few users. IncludeUnrunnableActors *bool - // AllowsAgenticUsers filters to Actors that allow agentic users. - AllowsAgenticUsers *bool - // ResponseFormat selects the response format. + // ResponseFormat controls the shape of the response: "full" (the default) returns every field, + // and "agent" a reduced field set for LLM consumers, in which URL, UserPictureURL, IsVerified + // and the optional Stats counts are nil. ResponseFormat *string // IncludeInputSchema, if true, adds to each listed Actor an inputSchema field with a compact // version of its default build's input schema (property types and required properties only). @@ -33,18 +38,73 @@ type StoreListOptions struct { func (o StoreListOptions) apply(q *QueryParams) { q.AddInt("offset", o.Offset). AddInt("limit", o.Limit). - AddString("search", o.Search). - AddString("sortBy", o.SortBy). AddString("category", o.Category). AddString("username", o.Username). AddString("pricingModel", o.PricingModel). AddBool("includeUnrunnableActors", o.IncludeUnrunnableActors). - AddBool("allowsAgenticUsers", o.AllowsAgenticUsers). AddString("responseFormat", o.ResponseFormat). AddBool("includeInputSchema", o.IncludeInputSchema) } -// StoreCollectionClient is a client for browsing the Apify Store (GET /v2/store). +// StoreSearchOptions configures [StoreCollectionClient.Search]. There is no offset, as the API +// ignores it for a search. +type StoreSearchOptions struct { + // Search is the text to search for. It is required and cannot be empty, as the API answers an + // empty query with the Store listing, which is not a search. + Search string + // Limit is the maximum number of Actors to return. The API returns at most 100 Actors for a + // search, which is also the default, and reduces a larger value to 100. + Limit *int64 + // Category filters Actors by category. It takes one or more category IDs, separated by commas + // and case-insensitive, and an Actor must match all of them (for example "AI_AND_ML"). An + // unknown category makes the API answer with a 400 error. + Category *string + // Username filters Actors by owner username. + Username *string + // PricingModel filters Actors by pricing model (e.g. "FREE", "PAY_PER_EVENT"). + PricingModel *string + // IncludeUnrunnableActors, if true, turns off the safety filter that leaves out Actors that + // are not safe to run automatically, such as those of developers without a verified identity + // and Actors with full permissions that have few users. + IncludeUnrunnableActors *bool + // ResponseFormat controls the shape of the response: "full" (the default) returns every field, + // and "agent" a reduced field set for LLM consumers, in which URL, UserPictureURL, IsVerified + // and the optional Stats counts are nil. + ResponseFormat *string + // IncludeInputSchema, if true, adds to each found Actor an inputSchema field with a compact + // version of its default build's input schema (property types and required properties only). + // With it set, the API defaults Limit to 10 and does not accept a larger one. + IncludeInputSchema *bool +} + +func (o StoreSearchOptions) apply(q *QueryParams) { + StoreListOptions{ + Limit: o.Limit, + Category: o.Category, + Username: o.Username, + PricingModel: o.PricingModel, + IncludeUnrunnableActors: o.IncludeUnrunnableActors, + ResponseFormat: o.ResponseFormat, + IncludeInputSchema: o.IncludeInputSchema, + }.apply(q) + q.AddString("search", &o.Search) +} + +// StoreSearchResult is the single page of results that [StoreCollectionClient.Search] returns. +type StoreSearchResult struct { + // Items are the Actors that match the query, best match first. + Items []ActorStoreListItem + // Limit is the maximum number of Actors the API allowed in this result: the requested limit, + // or the API's maximum when no limit or a larger one was requested. With len(Items) equal to + // it, more Actors may match the query than were returned. + Limit int64 +} + +// StoreCollectionClient is a client for browsing and searching Apify Store (GET /v2/store). +// The API serves the Store in two ways, and this client has a method for each: +// [StoreCollectionClient.List] and [StoreCollectionClient.Iterate] go through the whole Store in +// Store order, page by page, and [StoreCollectionClient.Search] returns the Actors that match a +// query best, as a single page. type StoreCollectionClient struct { ctx *resourceContext } @@ -53,7 +113,8 @@ func newStoreCollectionClient(hc *httpClient, baseURL string) *StoreCollectionCl return &StoreCollectionClient{ctx: newCollectionContext(hc, baseURL, "store")} } -// List returns a single page of Store Actors matching the options. +// List returns a single page of Store Actors in Store order, matching the filters of the options. +// To find Actors by a text query, use [StoreCollectionClient.Search]. func (c *StoreCollectionClient) List(ctx context.Context, options StoreListOptions) (PaginationList[ActorStoreListItem], error) { params := NewQueryParams() options.apply(params) @@ -64,9 +125,10 @@ func (c *StoreCollectionClient) List(ctx context.Context, options StoreListOptio // It is the generic [ListIterator] specialized to Store Actors; drain it with Next. type StoreActorIterator = ListIterator[ActorStoreListItem] -// Iterate returns a lazy iterator over the Store Actors matching the options, fetching pages on -// demand. The options' Limit caps the total number of Actors yielded (unset means all); the page -// size is chunkSize (nil for the server default). +// Iterate returns a lazy iterator over the Store Actors in Store order, matching the filters of +// the options, fetching pages on demand. The options' Limit caps the total number of Actors +// yielded (unset means all); the page size is chunkSize (nil for the server default). To find +// Actors by a text query, use [StoreCollectionClient.Search]. func (c *StoreCollectionClient) Iterate(options StoreListOptions, chunkSize *int64) *StoreActorIterator { return newListIterator(options.Limit, chunkSize, offsetVal(options.Offset), func(ctx context.Context, offset, limit int64) (PaginationList[ActorStoreListItem], error) { opts := options @@ -75,3 +137,28 @@ func (c *StoreCollectionClient) Iterate(options StoreListOptions, chunkSize *int return c.List(ctx, opts) }) } + +// Search returns the Store Actors that match the query best, best match first. +// +// The API answers a search with a single page of at most 100 Actors. There is no next page and no +// way to skip results, and the API does not report how many Actors match the query in total. A +// result that holds as many Actors as [StoreSearchResult.Limit] can therefore be cut off: narrow +// it down with a more specific query or with the Category, Username and PricingModel options. To +// go through the whole Store, use [StoreCollectionClient.List] or [StoreCollectionClient.Iterate]. +// +// It returns an error, without sending a request, if options.Search is empty. +func (c *StoreCollectionClient) Search(ctx context.Context, options StoreSearchOptions) (StoreSearchResult, error) { + if options.Search == "" { + return StoreSearchResult{}, errors.New("StoreCollectionClient.Search: Search must not be empty") + } + params := NewQueryParams() + options.apply(params) + page, err := listResource[ActorStoreListItem](ctx, c.ctx, "", params) + if err != nil { + return StoreSearchResult{}, err + } + // The response has the shape of a listing page, but a search fills its total with the number of + // Actors returned and its offset with zero, whatever the query matches. They are left out, as + // they would read as the number of matches and a position to continue from. + return StoreSearchResult{Items: page.Items, Limit: page.Limit}, nil +} diff --git a/store_collection_test.go b/store_collection_test.go index 0b9e469..2878799 100644 --- a/store_collection_test.go +++ b/store_collection_test.go @@ -2,10 +2,111 @@ package apify import ( "context" + "io" + "net/http" "strings" + "sync" "testing" ) +// searchIgnoringOffsetBackend plays the Store API, which ignores the offset when a search is set: +// every request for such a search gets the same page of actors. +type searchIgnoringOffsetBackend struct { + mu sync.Mutex + urls []string +} + +func (b *searchIgnoringOffsetBackend) Do(req *http.Request) (*http.Response, error) { + b.mu.Lock() + b.urls = append(b.urls, req.URL.String()) + b.mu.Unlock() + const page = `{"data":{"total":2,"offset":0,"count":2,"limit":100,"items":[` + + `{"id":"a1","name":"one","username":"u","title":"One","stats":{"totalUsers":1}},` + + `{"id":"a2","name":"two","username":"u","title":"Two","stats":{"totalUsers":2}}]}}` + return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(page))}, nil +} + +// Search sends one request for the query with the filters and no offset, and returns the Actors +// with the limit of the page, but not the total and the offset that a search fills with the count. +func TestStoreSearchSendsOneRequestAndReturnsItemsAndLimit(t *testing.T) { + backend := &searchIgnoringOffsetBackend{} + result, err := testClient(backend, 0).Store().Search(context.Background(), StoreSearchOptions{ + Search: "scraper", + Limit: Ptr(int64(5)), + Category: Ptr("AI_AND_ML"), + Username: Ptr("apify"), + PricingModel: Ptr("FREE"), + IncludeUnrunnableActors: Ptr(true), + ResponseFormat: Ptr("agent"), + IncludeInputSchema: Ptr(true), + }) + if err != nil { + t.Fatalf("Search: %v", err) + } + var ids []string + for _, item := range result.Items { + ids = append(ids, item.ID) + } + if strings.Join(ids, ",") != "a1,a2" || result.Limit != 100 { + t.Errorf("expected Actors a1,a2 with limit 100, got %v with limit %d", ids, result.Limit) + } + if len(backend.urls) != 1 { + t.Fatalf("expected one request, got %v", backend.urls) + } + for _, want := range []string{"search=scraper", "limit=5", "category=AI_AND_ML", "username=apify", "pricingModel=FREE", "includeUnrunnableActors=1", "responseFormat=agent", "includeInputSchema=1"} { + if !strings.Contains(backend.urls[0], want) { + t.Errorf("expected %q in the request URL, got %s", want, backend.urls[0]) + } + } + for _, unwanted := range []string{"offset=", "sortBy="} { + if strings.Contains(backend.urls[0], unwanted) { + t.Errorf("did not expect %q in the request URL, got %s", unwanted, backend.urls[0]) + } + } +} + +// An empty query is not a search: the API would answer it with the Store listing. +func TestStoreSearchRejectsAnEmptyQuery(t *testing.T) { + backend := &searchIgnoringOffsetBackend{} + if _, err := testClient(backend, 0).Store().Search(context.Background(), StoreSearchOptions{}); err == nil { + t.Fatal("expected an error for an empty query") + } + if len(backend.urls) != 0 { + t.Errorf("expected no request, got %v", backend.urls) + } +} + +func TestStoreSearchReturnsAPIErrors(t *testing.T) { + backend := &mockBackend{responses: []mockResponse{{status: 400, body: `{"error":{"type":"invalid-input","message":"unknown category"}}`}}} + if _, err := testClient(backend, 0).Store().Search(context.Background(), StoreSearchOptions{Search: "x", Category: Ptr("NOPE")}); err == nil { + t.Fatal("expected the API error") + } +} + +// The iterator pages through the Store with the offset. +func TestStoreIterateAdvancesTheOffset(t *testing.T) { + backend := &mockBackend{responses: []mockResponse{ + {status: 200, body: `{"data":{"total":3,"offset":0,"count":2,"limit":2,"items":[{"id":"a1"},{"id":"a2"}]}}`}, + {status: 200, body: `{"data":{"total":3,"offset":2,"count":1,"limit":2,"items":[{"id":"a3"}]}}`}, + {status: 200, body: `{"data":{"total":3,"offset":3,"count":0,"limit":2,"items":[]}}`}, + }} + it := testClient(backend, 0).Store().Iterate(StoreListOptions{}, Ptr(int64(2))) + count := 0 + for { + item, err := it.Next(context.Background()) + if err != nil { + t.Fatalf("Next: %v", err) + } + if item == nil { + break + } + count++ + } + if count != 3 || !strings.Contains(backend.lastURL, "offset=3") { + t.Errorf("expected 3 actors paged by offset, got %d, last URL %s", count, backend.lastURL) + } +} + func TestStoreListSendsIncludeInputSchema(t *testing.T) { backend := &mockBackend{responses: okData()} client := testClient(backend, 0) diff --git a/stream_body_test.go b/stream_body_test.go new file mode 100644 index 0000000..a286992 --- /dev/null +++ b/stream_body_test.go @@ -0,0 +1,278 @@ +package apify + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" +) + +// compressibleBody is larger than the compression threshold and compresses well, so the client's +// own request compression would pick it up if a stream were not left alone. +var compressibleBody = strings.Repeat(`{"key":"value"}`, 400) + +// streamClient is a client with the request compression on, so that a test sees that a stream +// is sent untouched, and with retries on, so that a test sees that it is sent once. +func streamClient(backend HTTPBackend) *ApifyClient { + return NewClient( + WithToken("test-token"), + WithHTTPBackend(backend), + WithMaxRetries(retriesAllowed), + WithMinDelayBetweenRetries(1), + WithRequestCompression(RequestCompressionGzip), + ) +} + +func assertSentOnceAsIs(t *testing.T, backend *mockBackend, wantContentType string) { + t.Helper() + if backend.calls != 1 { + t.Fatalf("a stream is sent once, got %d requests", backend.calls) + } + if backend.lastBody != compressibleBody { + t.Errorf("the stream was altered: got %d bytes, want %d", len(backend.lastBody), len(compressibleBody)) + } + if got := backend.lastHeaders.Get("Content-Encoding"); got != "" { + t.Errorf("a stream is not compressed by the client, got Content-Encoding %q", got) + } + if got := backend.lastHeaders.Get("Content-Type"); got != wantContentType { + t.Errorf("Content-Type %q, want %q", got, wantContentType) + } +} + +func TestSetRecordStreamSendsTheStreamOnceAsIs(t *testing.T) { + backend := &mockBackend{responses: constant(200, "")} + err := streamClient(backend).KeyValueStore("s").SetRecordStream(context.Background(), "k", strings.NewReader(compressibleBody), "application/json") + if err != nil { + t.Fatalf("SetRecordStream: %v", err) + } + assertSentOnceAsIs(t, backend, "application/json") + if !strings.HasSuffix(backend.lastURL, "/key-value-stores/s/records/k") { + t.Errorf("unexpected URL %s", backend.lastURL) + } +} + +func TestSetRecordStreamWithEncodingSendsTheEncodingHeader(t *testing.T) { + backend := &mockBackend{responses: constant(200, "")} + err := streamClient(backend).KeyValueStore("s").SetRecordStreamWithEncoding(context.Background(), "k", strings.NewReader(compressibleBody), "text/plain", "gzip") + if err != nil { + t.Fatalf("SetRecordStreamWithEncoding: %v", err) + } + if backend.calls != 1 || backend.lastBody != compressibleBody || backend.lastHeaders.Get("Content-Encoding") != "gzip" { + t.Errorf("unexpected request: %d calls, headers %v", backend.calls, backend.lastHeaders) + } +} + +func TestSetRecordStreamIsNotRetried(t *testing.T) { + backend := &mockBackend{responses: constant(500, `{"error":{"type":"x","message":"boom"}}`)} + err := streamClient(backend).KeyValueStore("s").SetRecordStream(context.Background(), "k", strings.NewReader("data"), "text/plain") + if apiErr, ok := AsAPIError(err); !ok || apiErr.StatusCode != http.StatusInternalServerError { + t.Fatalf("expected the 500 as an APIError, got %v", err) + } + if backend.calls != 1 { + t.Fatalf("a stream is not retried, got %d requests", backend.calls) + } +} + +func TestSetRecordStreamRejectsADotSegmentKey(t *testing.T) { + backend := &mockBackend{responses: constant(200, "")} + if err := streamClient(backend).KeyValueStore("s").SetRecordStream(context.Background(), "..", strings.NewReader("x"), "text/plain"); err == nil { + t.Fatal("expected an error for a dot-segment key") + } + if backend.calls != 0 { + t.Fatalf("nothing is sent for a rejected key, got %d requests", backend.calls) + } +} + +const startedRun = `{"data":{"id":"run1","status":"READY"}}` + +func TestActorStartStreamSendsTheStreamOnce(t *testing.T) { + backend := &mockBackend{responses: constant(201, startedRun)} + run, err := streamClient(backend).Actor("a").StartStream(context.Background(), strings.NewReader(compressibleBody), ActorStartOptions{WaitForResources: Ptr(int64(60))}) + if err != nil || run.ID != "run1" { + t.Fatalf("StartStream: %+v, %v", run, err) + } + assertSentOnceAsIs(t, backend, "application/octet-stream") + + backend = &mockBackend{responses: constant(201, startedRun)} + options := ActorStartOptions{ContentType: Ptr("application/zip")} + if _, err := streamClient(backend).Actor("a").StartStream(context.Background(), strings.NewReader(compressibleBody), options); err != nil { + t.Fatalf("StartStream with a content type: %v", err) + } + assertSentOnceAsIs(t, backend, "application/zip") +} + +func TestActorStartStreamIsNotRetriedOnResourceShortage(t *testing.T) { + backend := &mockBackend{responses: constant(402, `{"error":{"type":"actor-memory-limit-exceeded","message":"no memory"}}`)} + _, err := streamClient(backend).Actor("a").StartStream(context.Background(), strings.NewReader("input"), ActorStartOptions{WaitForResources: Ptr(int64(60))}) + if err == nil || backend.calls != 1 { + t.Fatalf("expected the first rejection after one request, got %v after %d", err, backend.calls) + } +} + +func TestActorCallStreamWaitsForTheRun(t *testing.T) { + backend := &mockBackend{responses: []mockResponse{ + {status: 201, body: startedRun}, + {status: 200, body: `{"data":{"id":"run1","status":"SUCCEEDED"}}`}, + }} + run, err := streamClient(backend).Actor("a").CallStream(context.Background(), strings.NewReader(compressibleBody), ActorStartOptions{Log: noLogRedirection}, nil) + if err != nil || run.Status != "SUCCEEDED" { + t.Fatalf("CallStream: %+v, %v", run, err) + } + if len(backend.bodies) == 0 || backend.bodies[0] != compressibleBody { + t.Errorf("the start request did not carry the stream") + } +} + +func TestTaskStartStreamSendsTheStreamOnceAsJSON(t *testing.T) { + backend := &mockBackend{responses: constant(201, startedRun)} + run, err := streamClient(backend).Task("t").StartStream(context.Background(), strings.NewReader(compressibleBody), TaskStartOptions{}) + if err != nil || run.ID != "run1" { + t.Fatalf("StartStream: %+v, %v", run, err) + } + // The API accepts only a JSON object as the input of a task. + assertSentOnceAsIs(t, backend, "application/json") +} + +func TestTaskCallStreamWaitsForTheRun(t *testing.T) { + backend := &mockBackend{responses: []mockResponse{ + {status: 201, body: startedRun}, + {status: 200, body: `{"data":{"id":"run1","status":"SUCCEEDED"}}`}, + }} + run, err := streamClient(backend).Task("t").CallStream(context.Background(), strings.NewReader(`{"a":1}`), TaskStartOptions{Log: noLogRedirection}, nil) + if err != nil || run.Status != "SUCCEEDED" { + t.Fatalf("CallStream: %+v, %v", run, err) + } +} + +// A redirect is not followed, since a stream cannot be replayed: it comes back as an error. +func TestStreamCallsDoNotFollowRedirects(t *testing.T) { + var targetHits atomic.Int64 + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { targetHits.Add(1) })) + defer target.Close() + redirecting := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, target.URL, http.StatusTemporaryRedirect) + })) + defer redirecting.Close() + + client := NewClient(WithToken("t"), WithBaseURL(redirecting.URL), WithMaxRetries(0)) + err := client.KeyValueStore("s").SetRecordStream(context.Background(), "k", strings.NewReader("data"), "text/plain") + if err == nil { + t.Fatal("expected the redirect to be returned as an error") + } + if targetHits.Load() != 0 { + t.Fatalf("the redirect target was called %d times", targetHits.Load()) + } +} + +// closeRecorder is a stream that counts its closes. +type closeRecorder struct { + io.Reader + closes atomic.Int32 +} + +func (r *closeRecorder) Close() error { + r.closes.Add(1) + return nil +} + +// A call that fails before it sends anything closes a stream that is an io.Closer, once: the +// HTTP transport, which closes the body of a request it sent, never saw it. +func TestStreamCallsThatFailBeforeSendingCloseTheStreamOnce(t *testing.T) { + ctx := context.Background() + client := streamClient(&mockBackend{responses: constant(200, startedRun)}) + badURLClient := NewClient(WithToken("t"), WithBaseURL("http://[::1"), WithMaxRetries(0)) + cases := []struct { + name string + run func(t *testing.T, stream io.Reader) error + }{ + {"invalid key", func(_ *testing.T, s io.Reader) error { + return client.KeyValueStore("s").SetRecordStream(ctx, "..", s, "text/plain") + }}, + {"empty store ID", func(_ *testing.T, s io.Reader) error { + return client.KeyValueStore("").SetRecordStream(ctx, "k", s, "text/plain") + }}, + {"empty task ID", func(_ *testing.T, s io.Reader) error { + _, err := client.Task("").StartStream(ctx, s, TaskStartOptions{}) + return err + }}, + {"invalid URL", func(_ *testing.T, s io.Reader) error { + _, err := badURLClient.Actor("a").StartStream(ctx, s, ActorStartOptions{}) + return err + }}, + {"server request with an unknown method", func(_ *testing.T, s io.Reader) error { + _, err := client.Actor("a").Server().Request(ctx, "/", ActorServerRequestOptions{Method: "NOPE", Body: s}) + return err + }}, + {"server request of an Actor that does not exist", func(t *testing.T, s io.Reader) error { + f := newServerFixture(t) + f.noActor() + _, err := f.client().Actor(serverTestActorID).Server().Request(ctx, "/", ActorServerRequestOptions{Method: "POST", Body: s}) + return err + }}, + {"server request with a path that is not a valid URL", func(t *testing.T, s io.Reader) error { + f := newServerFixture(t) + _, err := f.client().Actor(serverTestActorID).Server().Request(ctx, "/%zz", ActorServerRequestOptions{Method: "POST", Body: s}) + return err + }}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + stream := &closeRecorder{Reader: strings.NewReader("data")} + if err := c.run(t, stream); err == nil { + t.Fatal("expected the call to fail") + } + if got := stream.closes.Load(); got != 1 { + t.Errorf("the stream was closed %d times, want once", got) + } + }) + } +} + +// The body of a request that was sent is closed by the HTTP transport, and the client does not +// close the stream a second time when the request fails. +func TestServerRequestStreamIsClosedOnceByTheTransport(t *testing.T) { + f := newServerFixture(t) + unreachable := httptest.NewServer(http.NotFoundHandler()) + unreachableURL := unreachable.URL + unreachable.Close() + f.setActor(map[string]any{"standbyUrl": unreachableURL}) + + stream := &closeRecorder{Reader: strings.NewReader("data")} + _, err := f.client().Actor(serverTestActorID).Server().Request(context.Background(), "/", ActorServerRequestOptions{Method: "POST", Body: stream}) + if err == nil { + t.Fatal("expected the connection to be refused") + } + if got := stream.closes.Load(); got != 1 { + t.Errorf("the stream was closed %d times, want once", got) + } +} + +// A stream that was sent successfully is closed once, by the HTTP transport of the default +// backend. +func TestSentStreamIsClosedOnce(t *testing.T) { + f := newServerFixture(t) + ctx := context.Background() + cases := map[string]func(stream io.Reader) error{ + "record": func(s io.Reader) error { + return f.client().KeyValueStore("s").SetRecordStream(ctx, "k", s, "text/plain") + }, + "server request": func(s io.Reader) error { + _, err := f.client().Actor(serverTestActorID).Server().Request(ctx, "/search", ActorServerRequestOptions{Method: "POST", Body: s}) + return err + }, + } + for name, run := range cases { + t.Run(name, func(t *testing.T) { + stream := &closeRecorder{Reader: strings.NewReader("data")} + if err := run(stream); err != nil { + t.Fatalf("the call failed: %v", err) + } + if got := stream.closes.Load(); got != 1 { + t.Errorf("the stream was closed %d times, want once", got) + } + }) + } +} diff --git a/streamed_log.go b/streamed_log.go index c7d23cb..01226b7 100644 --- a/streamed_log.go +++ b/streamed_log.go @@ -20,6 +20,10 @@ const ( // the request rate while a run waits long to start. emptyLogStreamRetry = 500 * time.Millisecond emptyLogStreamMaxRetry = 5 * time.Second + // brokenLogStreamReopen is how long a [StreamedLog] waits before it reopens a log stream that + // broke off before its end. The API cuts off a stream that has carried no data for several + // minutes even though the run goes on. + brokenLogStreamReopen = time.Second // stopGrace is how long [StreamedLog.Stop] waits for the messages already in flight before it // aborts the log stream. stopGrace = time.Second @@ -54,22 +58,28 @@ type StreamedLogOptions struct { // which costs two requests (the run and its Actor); a non-nil Prefix (an empty one included) // skips them. Prefix *string + // Since drops the messages logged before this time, and redirects the later ones. Nil + // redirects the whole log. To continue a redirection after a restart, pass the time of + // [StreamedLog.LastRedirectedAt] plus one millisecond. + Since *time.Time // FromStart controls whether messages logged before the redirection was created are - // redirected too (default true). With false, they are dropped. + // redirected too (default true). With false, they are dropped. Since takes precedence. + // + // Deprecated: Use Since, with the time of the creation of the redirection for the same effect. FromStart *bool } // StreamedLog redirects the live log of an Actor run to a writer, one prefixed line per message. // Get one from [RunClient.NewStreamedLog], and begin and end the redirection with -// [StreamedLog.Start] and [StreamedLog.Stop]. Messages logged before the redirection was created -// are skipped if FromStart is false. A log that is still empty is reopened until it delivers its -// first bytes. +// [StreamedLog.Start] and [StreamedLog.Stop]. Messages logged before Since are skipped. A log that +// is still empty is reopened until it delivers its first bytes. When the log stream is cut off +// while the run is still going, the stream is reopened and the redirection resumes after the last +// redirected message. type StreamedLog struct { - log *LogClient - output io.Writer - prefix string - startedAt time.Time - fromStart bool + log *LogClient + output io.Writer + prefix string + since *time.Time mu sync.Mutex // serializes writes to output and guards the fields below running bool @@ -81,6 +91,17 @@ type StreamedLog struct { done chan error buffer bytes.Buffer scanned int // how much of the buffer was searched for message timestamps + + receivedData bool // whether a log stream has delivered a byte since Start + streamBroken bool // whether the last log stream broke off, until a new stream is opened + // lastRedirected is the time of the last redirected message, and lastRedirectedCount how many + // redirected messages carry it, since several messages can share a millisecond. + lastRedirected time.Time + lastRedirectedCount int + // A reopened stream replays the messages before replayedUntil, and the first replaySkipCount + // messages at it, which were already redirected. + replayedUntil time.Time + replaySkipCount int } // NewStreamedLog creates the redirection of this run's log, which does nothing until @@ -119,15 +140,28 @@ func (c *RunClient) NewStreamedLog(ctx context.Context, options StreamedLogOptio if output == nil { output = os.Stderr } + since := options.Since + if since == nil && options.FromStart != nil && !*options.FromStart { + now := time.Now() + since = &now + } return &StreamedLog{ - log: c.Log(), - output: output, - prefix: prefix, - startedAt: time.Now(), - fromStart: options.FromStart == nil || *options.FromStart, + log: c.Log(), + output: output, + prefix: prefix, + since: since, }, true, nil } +// LastRedirectedAt returns the time of the last redirected message, and false if nothing has been +// redirected yet. To continue the redirection after a restart, pass it plus one millisecond as +// [StreamedLogOptions.Since]. +func (s *StreamedLog) LastRedirectedAt() (time.Time, bool) { + s.mu.Lock() + defer s.mu.Unlock() + return s.lastRedirected, s.lastRedirectedCount > 0 +} + // Start begins the redirection in the background. The redirection also ends when ctx is done. // It returns an error if the redirection is already running. func (s *StreamedLog) Start(ctx context.Context) error { @@ -146,6 +180,10 @@ func (s *StreamedLog) Start(ctx context.Context) error { s.done = make(chan error, 1) s.buffer.Reset() s.scanned = 0 + s.receivedData = false + s.streamBroken = false + s.replayedUntil = time.Time{} + s.replaySkipCount = 0 go func() { s.done <- s.streamLog(ctx, streamCtx) }() @@ -153,10 +191,12 @@ func (s *StreamedLog) Start(ctx context.Context) error { } // Stop ends the redirection and returns the error that stopped it early, if any. Messages in -// flight get up to one second. If the stream delivered nothing, Stop reads the whole log in one -// request, so that a short run is not lost. ctx bounds the wait, the final read included: when it -// ends first, Stop returns its error, unless the context given to Start ended first, which ends -// the redirection on purpose. It returns an error if the redirection is not running or is already +// flight get up to one second. If the stream delivered nothing, a short run that finished before +// the stream connected would be lost, and if the stream was cut off and its replacement has not +// caught up, the messages after the cut would be. In both cases Stop reads the whole log in one +// request and redirects what is missing. ctx bounds the wait, the final read included: when it ends +// first, Stop returns its error, unless the context given to Start ended first, which ends the +// redirection on purpose. It returns an error if the redirection is not running or is already // stopping. func (s *StreamedLog) Stop(ctx context.Context) error { s.mu.Lock() @@ -256,25 +296,12 @@ func (s *StreamedLog) redirect(parent, streamCtx context.Context) error { raw := true options := LogOptions{Raw: &raw} retry := emptyLogStreamRetry - gotBytes := false - for !gotBytes { - if s.isStopping() { - // The stream's context ends with the grace period, which must not cut this read - // short: it ends with the context of the caller's Stop instead. - readCtx, cancelRead := s.finalReadContext(parent) - body, _, err := s.log.GetBufferWithOptions(readCtx, options) - cancelRead() - if err != nil { - return &logReadError{err: err} - } - s.consume(body) - break - } + for !s.isStopping() { stream, err := s.log.StreamWithOptions(streamCtx, options) if err != nil { if s.isStopping() && parent.Err() == nil { - continue // the grace period ended while connecting: read the log in one request + break // the grace period ended while connecting } return err } @@ -283,45 +310,166 @@ func (s *StreamedLog) redirect(parent, streamCtx context.Context) error { } if s.isStopping() { _ = stream.Close() - continue + break } - var readErr error - gotBytes, readErr = s.consumeStream(stream) + s.mu.Lock() + s.streamBroken = false + s.mu.Unlock() + brokeOff, readErr := s.redirectStream(streamCtx, stream) _ = stream.Close() - if readErr != nil && streamCtx.Err() == nil { + if readErr != nil { s.flush() return readErr } - if !gotBytes { - select { - case <-time.After(retry): - case <-s.wake: - case <-streamCtx.Done(): - } + if s.gotData() && !brokeOff && !s.isStopping() { + // The stream ended after it had delivered data: it carried the whole log of a + // finished run. A stream that Stop cut off goes on below, as its replay may not + // have caught up. + s.flush() + return nil + } + pause := brokenLogStreamReopen + if !s.gotData() { + pause = retry retry = min(retry*2, emptyLogStreamMaxRetry) } + select { + case <-time.After(pause): + case <-s.wake: + case <-streamCtx.Done(): + } + } + if s.needsFinalRead() { + // Stopped before any stream delivered a byte, or before the log caught up after a stream + // broke off. The stream's context ends with the grace period, which must not cut this read + // short: it ends with the context of the caller's Stop instead. The read replays the whole + // log, so the messages that were already redirected are skipped, as in a reopened stream. + if s.gotData() { + s.prepareReopen() + } + readCtx, cancelRead := s.finalReadContext(parent) + body, _, err := s.log.GetBufferWithOptions(readCtx, options) + cancelRead() + if err != nil { + return &logReadError{err: err} + } + s.consume(body) } s.flush() return nil } -// consumeStream redirects the messages of stream and reports whether it delivered any byte. It -// reads until the end of the stream or an error; Stop ends it by cancelling the stream after its -// grace period, so the messages in flight are not lost. -func (s *StreamedLog) consumeStream(stream io.Reader) (bool, error) { +func (s *StreamedLog) gotData() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.receivedData +} + +// needsFinalRead reports whether Stop has to read the whole log: no stream delivered anything, or +// the last stream broke off and no stream replaced it, or its replacement has not reached the last +// redirected message yet. The messages after the break are still missing then. +func (s *StreamedLog) needsFinalRead() bool { + s.mu.Lock() + defer s.mu.Unlock() + return !s.receivedData || s.streamBroken || !s.replayedUntil.IsZero() && s.replaySkipCount > 0 +} + +// redirectStream redirects one log stream until it ends or Stop cuts it off. It reports whether +// the stream broke off and has to be opened again, which only a stream that delivered data +// before can: the error that ended it is returned in the other cases, except when the stream was +// cut off on purpose. +func (s *StreamedLog) redirectStream(streamCtx context.Context, stream io.Reader) (bool, error) { + err := s.consumeStream(stream) + if err == nil || streamCtx.Err() != nil { + return false, nil + } + if !s.gotData() || s.isStopping() || !isBrokenStreamRead(err) { + return false, err + } + if !s.replayCaughtUp() { + return false, fmt.Errorf("the reopened log stream broke off again before it reached the last redirected message: %w", err) + } + s.prepareReopen() + return true, nil +} + +// isBrokenStreamRead reports whether err, returned while reading a log stream, means that the +// transport cut the stream off. A timeout counts, since the transport ends a stream that has +// carried no data for a while with one. +func isBrokenStreamRead(err error) bool { + return isTimeoutError(err) || !isContextError(err) +} + +// prepareReopen makes the reopened stream redirect only the messages after the last redirected +// one. The API cannot continue a log stream from a given point, so the reopened stream replays the +// log from its start. The incomplete message in the buffer was not redirected, so it is replayed +// too. +func (s *StreamedLog) prepareReopen() { + s.mu.Lock() + defer s.mu.Unlock() + s.replayedUntil = s.lastRedirected + s.replaySkipCount = s.lastRedirectedCount + s.streamBroken = true + s.buffer.Reset() + s.scanned = 0 +} + +// replayCaughtUp reports whether the current stream got at least as far as the stream before it. +func (s *StreamedLog) replayCaughtUp() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.replayedUntil.IsZero() || s.replaySkipCount == 0 +} + +// isReplayed reports whether a message of a reopened stream was already redirected before the +// stream was reopened. +func (s *StreamedLog) isReplayed(logged time.Time) bool { + s.mu.Lock() + defer s.mu.Unlock() + if s.replayedUntil.IsZero() { + return false + } + if logged.Before(s.replayedUntil) { + return true + } + if logged.Equal(s.replayedUntil) && s.replaySkipCount > 0 { + s.replaySkipCount-- + return true + } + s.replayedUntil = time.Time{} + return false +} + +// rememberRedirected records the time of a redirected message. +func (s *StreamedLog) rememberRedirected(logged time.Time) { + s.mu.Lock() + defer s.mu.Unlock() + if s.lastRedirectedCount > 0 && logged.Equal(s.lastRedirected) { + s.lastRedirectedCount++ + return + } + s.lastRedirected = logged + s.lastRedirectedCount = 1 +} + +// consumeStream redirects the messages of stream until the end of the stream or an error, and +// returns that error. Stop ends it by cancelling the stream after its grace period, so the +// messages in flight are not lost. +func (s *StreamedLog) consumeStream(stream io.Reader) error { chunk := make([]byte, logReadChunkBytes) - gotBytes := false for { n, err := stream.Read(chunk) if n > 0 { - gotBytes = true + s.mu.Lock() + s.receivedData = true + s.mu.Unlock() s.consume(chunk[:n]) } if err != nil { if errors.Is(err, io.EOF) { - return gotBytes, nil + return nil } - return gotBytes, err + return err } } } @@ -375,12 +523,18 @@ func (s *StreamedLog) redirectMessages(text string) { contentEnd = markers[i+1][0] } timestamp := text[marker[2]:marker[3]] - if !s.fromStart { - if logged, err := time.Parse(time.RFC3339Nano, timestamp); err == nil && logged.Before(s.startedAt) { - continue - } + logged, err := time.Parse(time.RFC3339Nano, timestamp) + parsed := err == nil + if parsed && s.isReplayed(logged) { + continue + } + if parsed && s.since != nil && logged.Before(*s.since) { + continue } s.write(strings.TrimSpace(timestamp + text[marker[3]:contentEnd])) + if parsed { + s.rememberRedirected(logged) + } } } @@ -391,6 +545,16 @@ func (s *StreamedLog) write(message string) { _, _ = fmt.Fprintf(s.output, "%s%s\n", s.prefix, message) } +// waitForFinishWithLog waits for the run to finish and redirects its log meanwhile, the way +// [ActorClient.Call] and [TaskClient.Call] do. A failure of the redirection never fails the wait, +// since the run has already started and the caller has to get it. +func waitForFinishWithLog(ctx context.Context, run *RunClient, options *StreamedLogOptions, waitSecs *int64) (ActorRun, error) { + streamed := startLogRedirection(ctx, run, options) + finished, err := run.WaitForFinish(ctx, waitSecs) + stopLogRedirection(ctx, streamed, options) + return finished, err +} + // startLogRedirection starts redirecting the log of run, as [ActorClient.Call] does by default. // A failure never fails the call: it is reported to the redirection's output and the call goes on // without redirected logs. It returns nil when the redirection is disabled or could not start. diff --git a/streamed_log_test.go b/streamed_log_test.go index 851822f..124bbb3 100644 --- a/streamed_log_test.go +++ b/streamed_log_test.go @@ -44,10 +44,16 @@ type logBackend struct { rawOnStream bool streamChunks []string // when set, the stream serves these pieces, one per read streamTailErr error // makes the stream fail with this error after its body + // streamTailErrs makes the i-th stream (the last entry repeats) fail with its error after its + // body; a nil entry lets that stream end cleanly. + streamTailErrs []error // blockFullLog makes the read of the whole log wait until its request is canceled. blockFullLog bool // holdStream keeps the live stream open after its body, until the request is canceled. holdStream bool + // holdStreamFrom, when positive, keeps open every stream from the one with this 1-based number + // on, as holdStream does. + holdStreamFrom int // fullLogFailure, when set, makes the read of the whole log fail with this status after // fullLogDelay. fullLogFailure int @@ -102,6 +108,12 @@ func (r *chunkReader) Read(p []byte) (int, error) { return n, nil } +func (b *logBackend) streamRequests() int { + b.mu.Lock() + defer b.mu.Unlock() + return b.streamCalls +} + func (b *logBackend) fullLogReads() int { b.mu.Lock() defer b.mu.Unlock() @@ -128,12 +140,17 @@ func (b *logBackend) Do(req *http.Request) (*http.Response, error) { if b.streamChunks != nil { reader = &chunkReader{chunks: append([]string(nil), b.streamChunks...)} } - if b.holdStream { + if b.holdStream || b.holdStreamFrom > 0 && b.streamCalls >= b.holdStreamFrom { reader = &holdingReader{data: reader, ctx: req.Context()} } if b.streamTailErr != nil { reader = &failingReader{data: reader, err: b.streamTailErr} } + if len(b.streamTailErrs) > 0 { + if err := b.streamTailErrs[min(b.streamCalls-1, len(b.streamTailErrs)-1)]; err != nil { + reader = &failingReader{data: reader, err: err} + } + } return ok(reader) } b.fullLogCalls++ @@ -233,6 +250,222 @@ func TestStreamedLogDropsMessagesBeforeTheStartWhenNotFromStart(t *testing.T) { } } +func TestStreamedLogDropsMessagesBeforeSince(t *testing.T) { + log := "2026-10-30T10:00:00.000Z old\n2026-10-30T10:00:01.000Z newer\n2026-10-30T10:00:02.000Z newest\n" + backend := &logBackend{streamBodies: []string{log}} + out := &syncBuffer{} + ctx := context.Background() + since := time.Date(2026, 10, 30, 10, 0, 1, 0, time.UTC) + streamed, _, err := testClient(backend, 0).Run("run1").NewStreamedLog(ctx, StreamedLogOptions{Output: out, Prefix: Ptr(""), Since: &since}) + if err != nil { + t.Fatal(err) + } + if err := streamed.Start(ctx); err != nil { + t.Fatal(err) + } + waitFor(t, func() bool { return strings.Contains(out.String(), "newest") }) + if err := streamed.Stop(ctx); err != nil { + t.Fatal(err) + } + if got := out.String(); got != "2026-10-30T10:00:01.000Z newer\n2026-10-30T10:00:02.000Z newest\n" { + t.Fatalf("only the messages from Since on must be redirected: %q", got) + } +} + +func TestStreamedLogSinceTakesPrecedenceOverFromStart(t *testing.T) { + log := "2026-10-30T10:00:00.000Z old\n2026-10-30T10:00:01.000Z new\n" + backend := &logBackend{streamBodies: []string{log}} + out := &syncBuffer{} + ctx := context.Background() + since := time.Date(2026, 10, 30, 10, 0, 0, 0, time.UTC) + streamed, _, err := testClient(backend, 0).Run("run1").NewStreamedLog(ctx, StreamedLogOptions{Output: out, Prefix: Ptr(""), Since: &since, FromStart: Ptr(false)}) + if err != nil { + t.Fatal(err) + } + if err := streamed.Start(ctx); err != nil { + t.Fatal(err) + } + waitFor(t, func() bool { return strings.Contains(out.String(), "new") }) + if err := streamed.Stop(ctx); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "old") { + t.Fatalf("Since is before the first message, so it must be redirected: %q", out.String()) + } +} + +func TestStreamedLogReportsTheLastRedirectedMessage(t *testing.T) { + backend := &logBackend{streamBodies: []string{sampleLog}} + out := &syncBuffer{} + ctx := context.Background() + streamed, _, err := testClient(backend, 0).Run("run1").NewStreamedLog(ctx, StreamedLogOptions{Output: out, Prefix: Ptr("")}) + if err != nil { + t.Fatal(err) + } + if _, ok := streamed.LastRedirectedAt(); ok { + t.Fatal("nothing is redirected before the start") + } + if err := streamed.Start(ctx); err != nil { + t.Fatal(err) + } + waitFor(t, func() bool { return strings.Contains(out.String(), "last message") }) + if err := streamed.Stop(ctx); err != nil { + t.Fatal(err) + } + last, ok := streamed.LastRedirectedAt() + if want := time.Date(2026, 10, 30, 10, 0, 2, 0, time.UTC); !ok || !last.Equal(want) { + t.Fatalf("LastRedirectedAt = %v, %v, want %v", last, ok, want) + } +} + +// A stream that is cut off after it delivered data, while the run goes on, is reopened. The +// reopened stream replays the log from its start, and the messages that were already redirected +// are not written again, also those that share a millisecond. +func TestStreamedLogReopensABrokenStreamWithoutRepeatingMessages(t *testing.T) { + first := "2026-10-30T10:00:00.000Z a\n2026-10-30T10:00:00.000Z b\n2026-10-30T10:00:01.000Z c\n" + backend := &logBackend{ + streamBodies: []string{first, first + "2026-10-30T10:00:02.000Z d\n"}, + streamTailErrs: []error{io.ErrUnexpectedEOF, nil}, + } + out := &syncBuffer{} + ctx := context.Background() + streamed, _, err := testClient(backend, 0).Run("run1").NewStreamedLog(ctx, StreamedLogOptions{Output: out, Prefix: Ptr("")}) + if err != nil { + t.Fatal(err) + } + if err := streamed.Start(ctx); err != nil { + t.Fatal(err) + } + waitFor(t, func() bool { return strings.Contains(out.String(), " d\n") }) + if err := streamed.Stop(ctx); err != nil { + t.Fatalf("Stop: %v", err) + } + want := "2026-10-30T10:00:00.000Z a\n2026-10-30T10:00:00.000Z b\n2026-10-30T10:00:01.000Z c\n2026-10-30T10:00:02.000Z d\n" + if got := out.String(); got != want { + t.Fatalf("every message must be redirected once, in order:\n got %q\nwant %q", got, want) + } + if backend.streamCalls != 2 { + t.Fatalf("expected the broken stream to be reopened once, got %d stream requests", backend.streamCalls) + } +} + +// Stop while a broken stream is waiting to be reopened must not lose the messages that the stream +// had not delivered: Stop reads the whole log, and skips what was redirected already. +func TestStreamedLogStoppedWhileWaitingToReopenReadsTheRestOfTheLog(t *testing.T) { + ab := "2026-10-30T10:00:00.000Z a\n2026-10-30T10:00:01.000Z b\n" + full := ab + "2026-10-30T10:00:02.000Z c\n" + backend := &logBackend{ + streamBodies: []string{ab, full}, + streamTailErrs: []error{io.ErrUnexpectedEOF, nil}, + fullLog: full, + } + out := &syncBuffer{} + ctx := context.Background() + streamed, _, err := testClient(backend, 0).Run("run1").NewStreamedLog(ctx, StreamedLogOptions{Output: out, Prefix: Ptr("")}) + if err != nil { + t.Fatal(err) + } + if err := streamed.Start(ctx); err != nil { + t.Fatal(err) + } + waitFor(t, func() bool { return streamed.waitingToReopen() }) + if err := streamed.Stop(ctx); err != nil { + t.Fatalf("Stop: %v", err) + } + want := "2026-10-30T10:00:00.000Z a\n2026-10-30T10:00:01.000Z b\n2026-10-30T10:00:02.000Z c\n" + if got := out.String(); got != want { + t.Fatalf("every message must be redirected once, in order:\n got %q\nwant %q", got, want) + } + if backend.fullLogReads() != 1 { + t.Fatalf("expected one read of the whole log, got %d", backend.fullLogReads()) + } +} + +// Stop while the reopened stream is still replaying the messages that were redirected already must +// not lose the messages after them: the stream is cut off by the grace period, and Stop reads the +// whole log, skipping what was redirected. +func TestStreamedLogStoppedWhileTheReopenedStreamReplaysReadsTheRestOfTheLog(t *testing.T) { + ab := "2026-10-30T10:00:00.000Z a\n2026-10-30T10:00:01.000Z b\n" + full := ab + "2026-10-30T10:00:02.000Z c\n" + backend := &logBackend{ + // The reopened stream replays a, and then holds until it is cut off. + streamBodies: []string{ab, "2026-10-30T10:00:00.000Z a\n"}, + streamTailErrs: []error{io.ErrUnexpectedEOF, nil}, + holdStreamFrom: 2, + fullLog: full, + } + out := &syncBuffer{} + ctx := context.Background() + streamed, _, err := testClient(backend, 0).Run("run1").NewStreamedLog(ctx, StreamedLogOptions{Output: out, Prefix: Ptr("")}) + if err != nil { + t.Fatal(err) + } + if err := streamed.Start(ctx); err != nil { + t.Fatal(err) + } + waitFor(t, func() bool { return backend.streamRequests() == 2 && !streamed.waitingToReopen() }) + if err := streamed.Stop(ctx); err != nil { + t.Fatalf("Stop: %v", err) + } + want := "2026-10-30T10:00:00.000Z a\n2026-10-30T10:00:01.000Z b\n2026-10-30T10:00:02.000Z c\n" + if got := out.String(); got != want { + t.Fatalf("every message must be redirected once, in order:\n got %q\nwant %q", got, want) + } + if backend.fullLogReads() != 1 { + t.Fatalf("expected one read of the whole log, got %d", backend.fullLogReads()) + } +} + +// A reopened stream that breaks off before it reaches the last redirected message ends the +// redirection with an error, as it would loop without making progress otherwise. +func TestStreamedLogStopsWhenTheReopenedStreamBreaksOffAgainTooEarly(t *testing.T) { + first := "2026-10-30T10:00:00.000Z a\n2026-10-30T10:00:01.000Z b\n2026-10-30T10:00:02.000Z c\n" + backend := &logBackend{ + streamBodies: []string{first, "2026-10-30T10:00:00.000Z a\n"}, + streamTailErrs: []error{io.ErrUnexpectedEOF}, + } + out := &syncBuffer{} + ctx := context.Background() + streamed, _, err := testClient(backend, 0).Run("run1").NewStreamedLog(ctx, StreamedLogOptions{Output: out, Prefix: Ptr("")}) + if err != nil { + t.Fatal(err) + } + if err := streamed.Start(ctx); err != nil { + t.Fatal(err) + } + waitFor(t, func() bool { return backend.streamRequests() == 2 }) + waitFor(t, func() bool { return streamed.stoppedEarly() }) + err = streamed.Stop(ctx) + if !errors.Is(err, io.ErrUnexpectedEOF) || !strings.Contains(err.Error(), "broke off again") { + t.Fatalf("expected the error of the second break, got %v", err) + } + if got := strings.Count(out.String(), "\n"); got != 2 { + t.Fatalf("a and b must be redirected once each, got %q", out.String()) + } +} + +// A stream that breaks off before it delivered any data is not reopened: its error ends the +// redirection. +func TestStreamedLogDoesNotReopenAStreamThatBrokeBeforeAnyData(t *testing.T) { + backend := &logBackend{streamBodies: []string{""}, streamTailErrs: []error{io.ErrUnexpectedEOF}} + out := &syncBuffer{} + ctx := context.Background() + streamed, _, err := testClient(backend, 0).Run("run1").NewStreamedLog(ctx, StreamedLogOptions{Output: out, Prefix: Ptr("")}) + if err != nil { + t.Fatal(err) + } + if err := streamed.Start(ctx); err != nil { + t.Fatal(err) + } + waitFor(t, func() bool { return streamed.stoppedEarly() }) + if err := streamed.Stop(ctx); !errors.Is(err, io.ErrUnexpectedEOF) { + t.Fatalf("expected the error of the stream, got %v", err) + } + if backend.streamRequests() != 1 { + t.Fatalf("expected one stream request, got %d", backend.streamRequests()) + } +} + // The API serves the log of a run that has not logged anything as an empty stream that ends at // once: the redirection reopens it until the first bytes arrive. func TestStreamedLogReopensAnEmptyStream(t *testing.T) { @@ -659,6 +892,53 @@ func TestCallWithDisabledLogRedirectionRequestsNoLog(t *testing.T) { } } +// A task call redirects the log of its run as an Actor call does, whether the input is a value or a +// stream, and it can turn that off. +func TestTaskCallRedirectsTheLogOfTheRun(t *testing.T) { + calls := map[string]func(c *ApifyClient, options TaskStartOptions) (ActorRun, error){ + "Call": func(c *ApifyClient, options TaskStartOptions) (ActorRun, error) { + return c.Task("task1").Call(context.Background(), nil, options, Ptr(int64(0))) + }, + "CallStream": func(c *ApifyClient, options TaskStartOptions) (ActorRun, error) { + return c.Task("task1").CallStream(context.Background(), strings.NewReader("{}"), options, Ptr(int64(0))) + }, + } + for name, call := range calls { + t.Run(name+" redirects", func(t *testing.T) { + out := &syncBuffer{} + backend := &callLogBackend{logBackend: logBackend{streamBodies: []string{sampleLog}, fullLog: sampleLog}} + got, err := call(testClient(backend, 0), TaskStartOptions{Log: &StreamedLogOptions{Output: out}}) + if err != nil || got.Status != "SUCCEEDED" { + t.Fatalf("%s: %+v, %v", name, got, err) + } + if !strings.Contains(out.String(), "hello-world runId:run1 -> 2026-10-30T10:00:02.000Z last message") { + t.Fatalf("the log must be redirected with the prefix of the Actor and the run: %q", out.String()) + } + }) + t.Run(name+" with the redirection disabled", func(t *testing.T) { + backend := &callLogBackend{logBackend: logBackend{streamBodies: []string{sampleLog}, fullLog: sampleLog}} + if _, err := call(testClient(backend, 0), TaskStartOptions{Log: &StreamedLogOptions{Disabled: true}}); err != nil { + t.Fatal(err) + } + if backend.streamCalls != 0 || backend.fullLogCalls != 0 { + t.Fatalf("no log may be requested, got %d stream and %d full reads", backend.streamCalls, backend.fullLogCalls) + } + }) + } +} + +func TestATaskCallGoesOnWhenTheLogRedirectionFails(t *testing.T) { + out := &syncBuffer{} + backend := &callLogBackend{logBackend: logBackend{streamBodies: []string{sampleLog}, streamErr: errors.New("boom")}, pollDelay: 100 * time.Millisecond} + got, err := testClient(backend, 0).Task("task1").Call(context.Background(), nil, TaskStartOptions{Log: &StreamedLogOptions{Output: out, Prefix: Ptr("")}}, Ptr(int64(0))) + if err != nil || got.Status != "SUCCEEDED" { + t.Fatalf("a failing log redirection must not fail the call: %+v, %v", got, err) + } + if !strings.Contains(out.String(), "Log redirection stopped due to error") || !strings.Contains(out.String(), "boom") { + t.Fatalf("the failure must be reported: %q", out.String()) + } +} + func TestACallGoesOnWhenTheLogRedirectionFails(t *testing.T) { out := &syncBuffer{} backend := &callLogBackend{logBackend: logBackend{streamBodies: []string{sampleLog}, streamErr: errors.New("boom")}, pollDelay: 100 * time.Millisecond} @@ -716,7 +996,7 @@ func TestStreamedLogRedirectsALargeMessageQuickly(t *testing.T) { } log.WriteString("2026-10-30T10:00:01.000Z next\n") out := &syncBuffer{} - streamed := &StreamedLog{output: out, fromStart: true} + streamed := &StreamedLog{output: out} body := []byte(log.String()) started := time.Now() @@ -733,3 +1013,18 @@ func TestStreamedLogRedirectsALargeMessageQuickly(t *testing.T) { t.Fatalf("redirected %d lines, want %d", got, lines+2) } } + +// stoppedEarly reports whether the redirection ended by itself and waits for Stop to collect its +// result. +func (s *StreamedLog) stoppedEarly() bool { + s.mu.Lock() + defer s.mu.Unlock() + return len(s.done) > 0 +} + +// waitingToReopen reports whether the last log stream broke off and no stream was opened since. +func (s *StreamedLog) waitingToReopen() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.streamBroken +} diff --git a/task.go b/task.go index 9b7929a..6b45d8b 100644 --- a/task.go +++ b/task.go @@ -3,6 +3,7 @@ package apify import ( "context" "encoding/json" + "io" "net/http" "time" ) @@ -73,6 +74,11 @@ type TaskStartOptions struct { // WaitForResources retries the start while the API rejects it for lack of resources. See // [ActorStartOptions.WaitForResources]. WaitForResources *int64 + // Log configures the redirection of the run's log that [TaskClient.Call] and + // [TaskClient.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 and + // StartStream ignore it. + Log *StreamedLogOptions } func (o TaskStartOptions) apply(q *QueryParams) { @@ -111,15 +117,55 @@ func (c *TaskClient) startWithTimeout(ctx context.Context, input any, options Ta }) } +// StartStream is [TaskClient.Start] with a stream as the input that overrides the task's stored +// input, for a large input that is not held in memory, such as a file. The stream must hold a JSON +// object: the API accepts only that as a task input, and it is sent as application/json. +// +// 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 *TaskClient) StartStream(ctx context.Context, input io.Reader, options TaskStartOptions) (ActorRun, error) { + return c.startStreamWithTimeout(ctx, input, options, extendForServerWait(c.ctx.longTimeout(), options.WaitForFinish)) +} + +func (c *TaskClient) startStreamWithTimeout(ctx context.Context, input io.Reader, options TaskStartOptions, timeout time.Duration) (ActorRun, error) { + params := NewQueryParams() + options.apply(params) + return postStream[ActorRun](ctx, c.ctx, "runs", params, input, contentTypeJSON, timeout) +} + +// CallStream starts the task with a stream as its input ([TaskClient.StartStream]) and waits for +// it to finish, exactly like [TaskClient.Call] but for a streamed input. +func (c *TaskClient) CallStream(ctx context.Context, input io.Reader, options TaskStartOptions, waitSecs *int64) (ActorRun, error) { + return c.callAndWait(ctx, options, waitSecs, func(timeout time.Duration) (ActorRun, error) { + return c.startStreamWithTimeout(ctx, input, options, timeout) + }) +} + // Call starts the task and waits for it to finish. waitSecs bounds the wait, and nil waits -// indefinitely. The start request and the polls have no timeout of their own, so ctx bounds the -// whole call. +// indefinitely. +// +// While it waits, it redirects the run's log to os.Stderr or options.Log.Output, prefixed with the +// Actor name and the run ID (see [StreamedLog]). Set options.Log.Disabled to turn that off. +// +// The start request and the polls have no timeout of their own, so ctx bounds the whole call. func (c *TaskClient) Call(ctx context.Context, input any, options TaskStartOptions, waitSecs *int64) (ActorRun, error) { - run, err := c.startWithTimeout(ctx, input, options, noRequestTimeout) + return c.callAndWait(ctx, options, waitSecs, func(timeout time.Duration) (ActorRun, error) { + return c.startWithTimeout(ctx, input, options, timeout) + }) +} + +// callAndWait is the shared implementation of Call and CallStream: it starts the run with start, +// which gets the timeout of the start request, and waits for it to finish while it redirects the +// log of the run. +func (c *TaskClient) callAndWait(ctx context.Context, options TaskStartOptions, waitSecs *int64, start func(timeout time.Duration) (ActorRun, error)) (ActorRun, error) { + run, err := start(noRequestTimeout) if err != nil { return ActorRun{}, err } - return c.root.Run(run.ID).WaitForFinish(ctx, waitSecs) + return waitForFinishWithLog(ctx, c.root.Run(run.ID), options.Log, waitSecs) } // GetInput fetches the task's stored input. diff --git a/tests/key_value_store_test.go b/tests/key_value_store_test.go index 9e1ec74..729e1a6 100644 --- a/tests/key_value_store_test.go +++ b/tests/key_value_store_test.go @@ -267,3 +267,29 @@ func TestRecordPublicURLIsFetchable(t *testing.T) { t.Fatalf("expected success fetching public url, got %d", resp.StatusCode) } } + +// TestSetRecordStream uploads a value read from a stream and reads it back. +func TestSetRecordStream(t *testing.T) { + client := requireClient(t) + ctx, cancel := testContext(t) + defer cancel() + + store, err := client.KeyValueStores().GetOrCreate(ctx, uniqueName("kvs-stream")) + if err != nil { + t.Fatalf("get-or-create: %v", err) + } + defer func() { _ = client.KeyValueStore(store.ID).Delete(ctx) }() + kvs := client.KeyValueStore(store.ID) + + value := bytes.Repeat([]byte("streamed record "), 1000) + if err := kvs.SetRecordStream(ctx, "STREAMED", bytes.NewReader(value), "text/plain"); err != nil { + t.Fatalf("SetRecordStream: %v", err) + } + record, ok, err := kvs.GetRecord(ctx, "STREAMED") + if err != nil || !ok { + t.Fatalf("GetRecord: ok=%v err=%v", ok, err) + } + if !bytes.Equal(record.Value, value) { + t.Fatalf("the stored value differs: got %d bytes, want %d", len(record.Value), len(value)) + } +} diff --git a/tests/store_test.go b/tests/store_test.go index 32ce870..101b477 100644 --- a/tests/store_test.go +++ b/tests/store_test.go @@ -18,6 +18,11 @@ func TestListStore(t *testing.T) { if len(page.Items) > 5 { t.Fatalf("expected at most 5 items, got %d", len(page.Items)) } + for _, item := range page.Items { + if item.Stats.TotalUsers <= 0 { + t.Fatalf("expected the Store statistics of %s to count at least its owner, got %+v", item.ID, item.Stats) + } + } } func TestIterateStore(t *testing.T) { @@ -63,3 +68,46 @@ func TestListStoreIncludeInputSchema(t *testing.T) { t.Fatalf("with includeInputSchema the API returns at most 10 Actors, got %d", len(page.Items)) } } + +// TestSearchStore searches the Store, which the API answers with a single page ordered by +// relevance: every Actor comes once, within the limit. +func TestSearchStore(t *testing.T) { + client := requireClient(t) + ctx, cancel := testContext(t) + defer cancel() + + result, err := client.Store().Search(ctx, apify.StoreSearchOptions{Search: "web scraper", Limit: ptr(int64(5))}) + if err != nil { + t.Fatalf("Store().Search: %v", err) + } + if len(result.Items) == 0 || len(result.Items) > 5 { + t.Fatalf("expected between 1 and 5 Actors, got %d", len(result.Items)) + } + if result.Limit != 5 { + t.Fatalf("expected the limit of the result to be 5, got %d", result.Limit) + } + seen := map[string]bool{} + for _, item := range result.Items { + if seen[item.ID] { + t.Fatalf("Actor %s was returned twice", item.ID) + } + seen[item.ID] = true + } +} + +// TestSearchStoreWithFilters narrows a search with the filters shared with the listing. +func TestSearchStoreWithFilters(t *testing.T) { + client := requireClient(t) + ctx, cancel := testContext(t) + defer cancel() + + result, err := client.Store().Search(ctx, apify.StoreSearchOptions{Search: "scraper", Username: ptr("apify"), Limit: ptr(int64(3))}) + if err != nil { + t.Fatalf("Store().Search with a username: %v", err) + } + for _, item := range result.Items { + if item.Username != "apify" { + t.Fatalf("expected only Actors of apify, got %s of %s", item.ID, item.Username) + } + } +} diff --git a/tests/task_test.go b/tests/task_test.go index 1afc1d2..3d2fd8a 100644 --- a/tests/task_test.go +++ b/tests/task_test.go @@ -1,6 +1,7 @@ package apify_test import ( + "strings" "testing" apify "github.com/apify/apify-client-go" @@ -126,3 +127,30 @@ func TestTaskPublishUnpublish(t *testing.T) { t.Fatalf("unpublish: expected IsPublic to not be true, got %v", *unpublished.IsPublic) } } + +// TestTaskCallStream overrides the stored input of a task with a streamed JSON object and checks +// that the run got it. +func TestTaskCallStream(t *testing.T) { + client := requireClient(t) + ctx, cancel := testContext(t) + defer cancel() + + task, err := client.Tasks().Create(ctx, taskDef(uniqueName("task-stream"))) + if err != nil { + t.Fatalf("create: %v", err) + } + defer func() { _ = client.Task(task.ID).Delete(ctx) }() + + input := strings.NewReader(`{"message":"streamed input"}`) + run, err := client.Task(task.ID).CallStream(ctx, input, apify.TaskStartOptions{}, ptr(int64(120))) + if err != nil { + t.Fatalf("CallStream: %v", err) + } + record, ok, err := client.KeyValueStore(run.DefaultKeyValueStoreID).GetRecord(ctx, "INPUT") + if err != nil || !ok { + t.Fatalf("get INPUT: ok=%v err=%v", ok, err) + } + if !strings.Contains(string(record.Value), "streamed input") { + t.Fatalf("the run did not get the streamed input: %s", record.Value) + } +} diff --git a/timeout_tier_test.go b/timeout_tier_test.go index e61e033..4acc498 100644 --- a/timeout_tier_test.go +++ b/timeout_tier_test.go @@ -3,15 +3,16 @@ package apify import ( "context" "net/http" + "strings" "testing" "time" ) // The calls on the long tier are not cut off by a shorter short tier: here the short tier // (tinyTier) is shorter than the response time, and the calls still succeed. -func TestKeyValueStoreAndPublicURLCallsUseTheLongTier(t *testing.T) { +func TestLongTierCallsOutliveTheShortTier(t *testing.T) { ctx := context.Background() - store := `{"data":{"id":"s","urlSigningSecretKey":"secret"}}` + response := `{"data":{"id":"s","urlSigningSecretKey":"secret","versionNumber":"0.1","sourceType":"SOURCE_FILES"}}` cases := []struct { name string run func(client *ApifyClient) error @@ -20,6 +21,22 @@ func TestKeyValueStoreAndPublicURLCallsUseTheLongTier(t *testing.T) { _, err := c.KeyValueStore("s").Update(ctx, map[string]any{"name": "n"}) return err }}, + {"ActorVersions Create", func(c *ApifyClient) error { + _, err := c.Actor("a").Versions().Create(ctx, map[string]any{"versionNumber": "0.1"}) + return err + }}, + {"ActorVersion Update", func(c *ApifyClient) error { + _, err := c.Actor("a").Version("0.1").Update(ctx, map[string]any{"buildTag": "latest"}) + return err + }}, + {"Actor StartStream", func(c *ApifyClient) error { + _, err := c.Actor("a").StartStream(ctx, strings.NewReader("data"), ActorStartOptions{}) + return err + }}, + {"Task StartStream", func(c *ApifyClient) error { + _, err := c.Task("t").StartStream(ctx, strings.NewReader("{}"), TaskStartOptions{}) + return err + }}, {"KeyValueStore RecordExists", func(c *ApifyClient) error { _, err := c.KeyValueStore("s").RecordExists(ctx, "k") return err @@ -39,7 +56,7 @@ func TestKeyValueStoreAndPublicURLCallsUseTheLongTier(t *testing.T) { } for _, c := range cases { t.Run(c.name, func(t *testing.T) { - backend := &slowBackend{delay: slowResponseDelay, body: store} + backend := &slowBackend{delay: slowResponseDelay, body: response} if err := c.run(slowClient(backend)); err != nil { t.Fatalf("a long-tier call must outlive the %v short and medium tiers: %v", tinyTier, err) } diff --git a/version.go b/version.go index cc61236..b5f0dc9 100644 --- a/version.go +++ b/version.go @@ -2,8 +2,8 @@ package apify // ClientVersion is the semantic version of this client. A change to the public interface other // than an addition is a breaking change. -const ClientVersion = "0.16.2" +const ClientVersion = "0.17.0" // APISpecVersion is the `info.version` of the Apify OpenAPI specification that this client was // last updated against. -const APISpecVersion = "v2-2026-11-18T151559Z" +const APISpecVersion = "v2-2026-12-02T102104Z"