From 5c588a0c8c78d1055188446dab2ed7f28b9f2fc4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:30:16 +0000 Subject: [PATCH 01/12] feat: type Store Actor stats and categories, use long timeout for Actor version writes Sync with the Store API changes of the OpenAPI specification and the reference client. --- CHANGELOG.md | 20 ++++++++++++++++++++ actor_version.go | 10 ++++++---- docs/actors.md | 2 +- docs/misc.md | 13 ++++++++----- models.go | 30 ++++++++++++++++++++++++++++++ models_test.go | 28 ++++++++++++++++++++++++++++ run.go | 2 +- store_collection.go | 18 +++++++++++++----- tests/store_test.go | 5 +++++ timeout_tier_test.go | 10 +++++++++- version.go | 2 +- 11 files changed, 122 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ad5b4a1..ec8ae2c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,26 @@ 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-11-27 + +### Added + +- `ActorStoreListItem.Categories`, `ActorStoreListItem.Stats` (the new `StoreActorStats`) and + `ActorStoreListItem.IsVerified`, which the Store endpoint now returns as typed fields. + +### Changed + +- `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 Store search behavior of the OpenAPI + specification: a search returns a single page of at most 100 Actors ranked by relevance, and + `Category` takes comma-separated category IDs. +- Added the `APIFY_AI` run origin to the `LastRunOptions.Origin` examples. + +### Deprecated + +- `StoreListOptions.SortBy`, which the API ignores. + ## [0.16.2] - 2026-11-24 ### Security 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/docs/actors.md b/docs/actors.md index 4ef4e7c..950c8e7 100644 --- a/docs/actors.md +++ b/docs/actors.md @@ -200,7 +200,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/misc.md b/docs/misc.md index 5387e0e..c8ebe57 100644 --- a/docs/misc.md +++ b/docs/misc.md @@ -13,11 +13,11 @@ Browse public Actors with `client.Store()`: | 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. | +| `Offset` | `*int64` | Number of Actors to skip. The API ignores it when `Search` is set. | +| `Limit` | `*int64` | Maximum number of Actors to return. The default and the maximum are 1000, or 100 when `Search` is set, where a larger value is reduced to 100. | +| `Search` | `*string` | Search query. Results are ranked by relevance and returned as a single page of at most 100 Actors, with no second page. Narrow them with `Category`, `Username` or `PricingModel`. | +| `SortBy` | `*string` | Deprecated: the API ignores it. Results are ordered by relevance when `Search` is set, and by Store position otherwise. Sort the results on the client for another order. | +| `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. | @@ -35,6 +35,9 @@ 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 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/store_collection.go b/store_collection.go index 8c48ee6..b38b9cb 100644 --- a/store_collection.go +++ b/store_collection.go @@ -4,15 +4,23 @@ import "context" // StoreListOptions configures listing/iterating the Apify Store. type StoreListOptions struct { - // Offset is the number of Actors to skip. + // Offset is the number of Actors to skip. The API ignores it when Search is set. 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, or + // 100 when Search is set, where a larger value is reduced to 100. Limit *int64 - // Search filters Actors by a full-text search query. + // Search ranks Actors by relevance to the query and returns them as a single page of at most + // 100 Actors, with no second page. Narrow the results with Category, Username or + // PricingModel. Search *string - // SortBy sets the sort field (e.g. "popularity", "newest"). + // SortBy is deprecated: the API ignores it. Results are ordered by relevance when Search is + // set, and by Store position otherwise. Sort the results on the client for another order. + // + // Deprecated: The API ignores this option. 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 diff --git a/tests/store_test.go b/tests/store_test.go index 32ce870..95a7a01 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) { diff --git a/timeout_tier_test.go b/timeout_tier_test.go index e61e033..725bedc 100644 --- a/timeout_tier_test.go +++ b/timeout_tier_test.go @@ -11,7 +11,7 @@ import ( // (tinyTier) is shorter than the response time, and the calls still succeed. func TestKeyValueStoreAndPublicURLCallsUseTheLongTier(t *testing.T) { ctx := context.Background() - store := `{"data":{"id":"s","urlSigningSecretKey":"secret"}}` + store := `{"data":{"id":"s","urlSigningSecretKey":"secret","versionNumber":"0.1","sourceType":"SOURCE_FILES"}}` cases := []struct { name string run func(client *ApifyClient) error @@ -20,6 +20,14 @@ 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 + }}, {"KeyValueStore RecordExists", func(c *ApifyClient) error { _, err := c.KeyValueStore("s").RecordExists(ctx, "k") return err diff --git a/version.go b/version.go index cc61236..9c54a47 100644 --- a/version.go +++ b/version.go @@ -2,7 +2,7 @@ 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. From 524f1050c3a06b05afcbc5729c96c32d7ed9c2a0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:43:41 +0000 Subject: [PATCH 02/12] feat: stream request bodies and fix Store search iteration Add io.Reader bodies for record values, Actor and task inputs and Server Actor requests, make Store iteration with a search a single request, and document the remaining Store options. --- CHANGELOG.md | 20 +++-- actor.go | 47 +++++++++-- actor_server.go | 17 +++- actor_server_test.go | 21 +++++ base.go | 26 ++++++ docs/actors.md | 4 +- docs/misc.md | 10 +-- docs/server_actors.md | 2 +- docs/storages.md | 1 + docs/tasks.md | 2 + http_client.go | 39 +++++++-- key_value_store.go | 25 ++++++ server_http.go | 18 +++- store_collection.go | 28 +++++-- store_collection_test.go | 73 ++++++++++++++--- stream_body_test.go | 150 ++++++++++++++++++++++++++++++++++ task.go | 31 +++++++ tests/key_value_store_test.go | 26 ++++++ tests/store_test.go | 27 ++++++ timeout_tier_test.go | 6 +- 20 files changed, 521 insertions(+), 52 deletions(-) create mode 100644 stream_body_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index ec8ae2c..0dba9a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,16 +9,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- `ActorStoreListItem.Categories`, `ActorStoreListItem.Stats` (the new `StoreActorStats`) and - `ActorStoreListItem.IsVerified`, which the Store endpoint now returns as typed fields. +- `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. +- An `io.Reader` as `ActorServerRequestOptions.Body`, sent the same way. Before, it was serialized + as JSON. +- `ActorStoreListItem.Categories`, `Stats` (the new `StoreActorStats`) and `IsVerified`. ### Changed +- `categories`, `stats` and `isVerified` of a Store Actor are no longer in + `ActorStoreListItem.Extra`. +- `StoreCollectionClient.Iterate` with `StoreListOptions.Search` set makes one request and yields + each Actor once. The API ignores the offset for a search, so paging through it repeated the same + Actors without end. - `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 Store search behavior of the OpenAPI - specification: a search returns a single page of at most 100 Actors ranked by relevance, and - `Category` takes comma-separated category IDs. +- Updated the documentation of `StoreListOptions` to the OpenAPI specification: the single-page + search, the comma-separated `Category` IDs, and `IncludeUnrunnableActors`, `ResponseFormat` and + `AllowsAgenticUsers`. - Added the `APIFY_AI` run origin to the `LastRunOptions.Origin` examples. ### Deprecated diff --git a/actor.go b/actor.go index 804b589..3897a83 100644 --- a/actor.go +++ b/actor.go @@ -4,6 +4,7 @@ import ( "context" "encoding/base64" "encoding/json" + "io" "net/http" "sync" "time" @@ -150,6 +151,17 @@ 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 it follows no redirect. Hence +// options.WaitForResources is ignored, as the start is never retried. +func (c *ActorClient) StartStream(ctx context.Context, input io.Reader, options ActorStartOptions) (ActorRun, error) { + return c.startWithStream(ctx, input, options, c.startTimeout(options)) +} + // 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 { @@ -171,6 +183,18 @@ func (c *ActorClient) startWithBody(ctx context.Context, body []byte, defaultCon }) } +// startWithStream starts the Actor with a streamed input of the content type from +// options.ContentType, or application/octet-stream. +func (c *ActorClient) startWithStream(ctx context.Context, input io.Reader, options ActorStartOptions, timeout time.Duration) (ActorRun, error) { + params := NewQueryParams() + options.apply(params) + contentType := "application/octet-stream" + if options.ContentType != nil && *options.ContentType != "" { + contentType = *options.ContentType + } + return postStream[ActorRun](ctx, c.ctx, "runs", params, input, contentType, 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,18 +207,31 @@ 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 } diff --git a/actor_server.go b/actor_server.go index 6c993d0..fd749b7 100644 --- a/actor_server.go +++ b/actor_server.go @@ -71,7 +71,9 @@ 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 not compressed, and nor retried on 429 or 503, since a retry would send what the + // first attempt left of the stream. 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 @@ -348,9 +350,15 @@ func (c *ActorServerClient) send(ctx context.Context, path string, options Actor if !httpMethods[method] || (options.Method != "" && options.Method != method) { 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. + bodyStream, _ := options.Body.(io.Reader) + 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 { @@ -369,6 +377,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/base.go b/base.go index d5c6317..7351404 100644 --- a/base.go +++ b/base.go @@ -309,6 +309,21 @@ func postWithBody[T any](ctx context.Context, c *resourceContext, subPath string return parseDataEnvelope[T](resp.body) } +// 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 { + 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 +402,17 @@ 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 { + 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/docs/actors.md b/docs/actors.md index 950c8e7..e5796c9 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 follows no redirect. | +| `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,7 +155,7 @@ 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)). | diff --git a/docs/misc.md b/docs/misc.md index c8ebe57..a274548 100644 --- a/docs/misc.md +++ b/docs/misc.md @@ -7,7 +7,7 @@ Browse public Actors with `client.Store()`: | 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. | +| `Iterate(StoreListOptions, chunkSize *int64) *StoreActorIterator` | Lazy iterator over matching Actors. `Limit` caps the total yielded; `chunkSize` is the page size. With `Search` set, it makes one request: `Limit` is the page size, `chunkSize` is ignored and at most 100 Actors are yielded. | `StoreListOptions` (all fields optional): @@ -20,9 +20,9 @@ Browse public Actors with `client.Store()`: | `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. | +| `AllowsAgenticUsers` | `*bool` | `true` returns only Actors that allow agentic users, and `false` only Actors that do not. | +| `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. | Each item is an `ActorStoreListItem`: @@ -42,7 +42,7 @@ Each item is an `ActorStoreListItem`: ```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 { diff --git a/docs/server_actors.md b/docs/server_actors.md index 03d5f58..97498ce 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. 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..ace17d2 100644 --- a/docs/storages.md +++ b/docs/storages.md @@ -174,6 +174,7 @@ 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 follows no redirect. To upload with retries, read the value into bytes and use `SetRecordRaw`. `SetRecordStreamWithEncoding` is the variant for a stream that is already compressed. | | `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. | diff --git a/docs/tasks.md b/docs/tasks.md index 3283073..2015b7a 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -51,6 +51,8 @@ A task is a pre-configured Actor run with stored input. Access the task collecti | `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. | +| `StartStream(ctx, input io.Reader, contentType string, TaskStartOptions) (ActorRun, error)` | Like `Start`, but reads the input from a stream, such as a file, so it is not held in memory. `contentType` defaults to `application/octet-stream`. The stream is sent once: the request is not compressed or retried (`WaitForResources` is ignored) and follows no redirect. | +| `CallStream(ctx, input io.Reader, contentType string, TaskStartOptions, waitSecs *int64) (ActorRun, error)` | `StartStream` followed by waiting for the run to finish. | | `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..7e5a500 100644 --- a/http_client.go +++ b/http_client.go @@ -152,6 +152,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. 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(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 +226,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 +243,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 { diff --git a/key_value_store.go b/key_value_store.go index 9cd00b8..ce78177 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,30 @@ 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 +// it follows no redirect. 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 { + 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. diff --git a/server_http.go b/server_http.go index d7ce518..e1753de 100644 --- a/server_http.go +++ b/server_http.go @@ -45,6 +45,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 +88,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 +101,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 +127,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 diff --git a/store_collection.go b/store_collection.go index b38b9cb..b7d2ea7 100644 --- a/store_collection.go +++ b/store_collection.go @@ -13,10 +13,10 @@ type StoreListOptions struct { // 100 Actors, with no second page. Narrow the results with Category, Username or // PricingModel. Search *string - // SortBy is deprecated: the API ignores it. Results are ordered by relevance when Search is - // set, and by Store position otherwise. Sort the results on the client for another order. + // SortBy sets the sort field. // - // Deprecated: The API ignores this option. + // Deprecated: The API ignores it. Results are ordered by relevance when Search is set, and by + // Store position otherwise. Sort the results on the client for another order. SortBy *string // 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 @@ -26,11 +26,16 @@ type StoreListOptions struct { 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, if true, returns only Actors that allow agentic users, and if false, + // only Actors that do not. 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). @@ -75,7 +80,18 @@ 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). +// +// With Search set, the API ranks the Actors by relevance and returns a single page of at most 100 +// of them, ignoring the offset, so a second page would repeat the first. The iterator then makes +// one request: Limit is the page size, chunkSize is ignored, and no more than 100 Actors are +// yielded. func (c *StoreCollectionClient) Iterate(options StoreListOptions, chunkSize *int64) *StoreActorIterator { + if options.Search != nil && *options.Search != "" { + options.Offset = nil + return newUnpaginatedIterator(func(ctx context.Context) (PaginationList[ActorStoreListItem], error) { + return c.List(ctx, options) + }) + } return newListIterator(options.Limit, chunkSize, offsetVal(options.Offset), func(ctx context.Context, offset, limit int64) (PaginationList[ActorStoreListItem], error) { opts := options opts.Offset = &offset diff --git a/store_collection_test.go b/store_collection_test.go index 0b9e469..7d2b591 100644 --- a/store_collection_test.go +++ b/store_collection_test.go @@ -2,23 +2,74 @@ package apify import ( "context" + "io" + "net/http" "strings" + "sync" "testing" ) -func TestStoreListSendsIncludeInputSchema(t *testing.T) { - backend := &mockBackend{responses: okData()} - client := testClient(backend, 0) - if _, err := client.Store().List(context.Background(), StoreListOptions{IncludeInputSchema: Ptr(true)}); err != nil { - t.Fatal(err) +// 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 +} + +// With Search set the API returns one page and ignores the offset, so the iterator makes one +// request and yields each actor once. +func TestStoreIterateWithSearchFetchesOnePage(t *testing.T) { + backend := &searchIgnoringOffsetBackend{} + it := testClient(backend, 0).Store().Iterate(StoreListOptions{Search: Ptr("scraper"), Offset: Ptr(int64(7))}, Ptr(int64(1))) + var ids []string + for { + item, err := it.Next(context.Background()) + if err != nil { + t.Fatalf("Next: %v", err) + } + if item == nil { + break + } + ids = append(ids, item.ID) } - if !strings.Contains(backend.lastURL, "includeInputSchema=1") { - t.Errorf("expected includeInputSchema=1, got %q", backend.lastURL) + if strings.Join(ids, ",") != "a1,a2" { + t.Errorf("expected each actor once, got %v", ids) } - if _, err := client.Store().List(context.Background(), StoreListOptions{}); err != nil { - t.Fatal(err) + if len(backend.urls) != 1 || !strings.Contains(backend.urls[0], "search=scraper") || strings.Contains(backend.urls[0], "offset=") { + t.Errorf("expected one request for the search without an offset, got %v", backend.urls) + } +} + +// Without Search the iterator still pages through the Store with the offset. +func TestStoreIterateWithoutSearchAdvancesTheOffset(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 strings.Contains(backend.lastURL, "includeInputSchema") { - t.Errorf("includeInputSchema must be omitted when unset, got %q", backend.lastURL) + 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) } } diff --git a/stream_body_test.go b/stream_body_test.go new file mode 100644 index 0000000..6567647 --- /dev/null +++ b/stream_body_test.go @@ -0,0 +1,150 @@ +package apify + +import ( + "context" + "net/http" + "strings" + "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 TestTaskStartStreamSendsTheStreamOnce(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) + } + assertSentOnceAsIs(t, backend, "application/octet-stream") + + backend = &mockBackend{responses: constant(201, startedRun)} + if _, err := streamClient(backend).Task("t").StartStream(context.Background(), strings.NewReader(compressibleBody), "text/csv", TaskStartOptions{}); err != nil { + t.Fatalf("StartStream with a content type: %v", err) + } + assertSentOnceAsIs(t, backend, "text/csv") +} + +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("input"), "text/plain", TaskStartOptions{}, nil) + if err != nil || run.Status != "SUCCEEDED" { + t.Fatalf("CallStream: %+v, %v", run, err) + } +} diff --git a/task.go b/task.go index 9b7929a..abd61af 100644 --- a/task.go +++ b/task.go @@ -3,6 +3,7 @@ package apify import ( "context" "encoding/json" + "io" "net/http" "time" ) @@ -111,6 +112,36 @@ 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. It has the content type +// "application/octet-stream" unless contentType is not empty. +// +// 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 it follows no redirect. Hence +// options.WaitForResources is ignored, as the start is never retried. +func (c *TaskClient) StartStream(ctx context.Context, input io.Reader, contentType string, options TaskStartOptions) (ActorRun, error) { + return c.startStreamWithTimeout(ctx, input, contentType, options, extendForServerWait(c.ctx.mediumTimeout(), options.WaitForFinish)) +} + +func (c *TaskClient) startStreamWithTimeout(ctx context.Context, input io.Reader, contentType string, options TaskStartOptions, timeout time.Duration) (ActorRun, error) { + params := NewQueryParams() + options.apply(params) + if contentType == "" { + contentType = "application/octet-stream" + } + return postStream[ActorRun](ctx, c.ctx, "runs", params, input, contentType, 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, contentType string, options TaskStartOptions, waitSecs *int64) (ActorRun, error) { + run, err := c.startStreamWithTimeout(ctx, input, contentType, options, noRequestTimeout) + if err != nil { + return ActorRun{}, err + } + return c.root.Run(run.ID).WaitForFinish(ctx, waitSecs) +} + // 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. 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 95a7a01..bcadc01 100644 --- a/tests/store_test.go +++ b/tests/store_test.go @@ -68,3 +68,30 @@ func TestListStoreIncludeInputSchema(t *testing.T) { t.Fatalf("with includeInputSchema the API returns at most 10 Actors, got %d", len(page.Items)) } } + +// TestIterateStoreSearch iterates a search, which the API answers with a single page: each Actor +// comes once, and the iteration ends. +func TestIterateStoreSearch(t *testing.T) { + client := requireClient(t) + ctx, cancel := testContext(t) + defer cancel() + + it := client.Store().Iterate(apify.StoreListOptions{Search: ptr("web scraper")}, ptr(int64(5))) + seen := map[string]bool{} + for { + item, err := it.Next(ctx) + if err != nil { + t.Fatalf("iterate: %v", err) + } + if item == nil { + break + } + if seen[item.ID] { + t.Fatalf("Actor %s was yielded twice", item.ID) + } + seen[item.ID] = true + } + if len(seen) == 0 { + t.Fatal("expected the search to find Actors") + } +} diff --git a/timeout_tier_test.go b/timeout_tier_test.go index 725bedc..23cec85 100644 --- a/timeout_tier_test.go +++ b/timeout_tier_test.go @@ -9,9 +9,9 @@ import ( // 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","versionNumber":"0.1","sourceType":"SOURCE_FILES"}}` + response := `{"data":{"id":"s","urlSigningSecretKey":"secret","versionNumber":"0.1","sourceType":"SOURCE_FILES"}}` cases := []struct { name string run func(client *ApifyClient) error @@ -47,7 +47,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) } From 788dc0d90f072b5412a67a8905b71fd585fc7796 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:55:46 +0000 Subject: [PATCH 03/12] fix: send task input streams as JSON, return redirects of streamed uploads as errors Share the task call helper, restore the Store includeInputSchema unit test and update the stream documentation. --- CHANGELOG.md | 3 ++- actor.go | 9 +++++---- actor_server.go | 5 +++-- docs/actors.md | 2 +- docs/storages.md | 2 +- docs/tasks.md | 4 ++-- http_client.go | 5 +++-- key_value_store.go | 3 ++- store_collection_test.go | 17 +++++++++++++++++ stream_body_test.go | 37 +++++++++++++++++++++++++++---------- task.go | 38 +++++++++++++++++++++----------------- tests/task_test.go | 28 ++++++++++++++++++++++++++++ 12 files changed, 112 insertions(+), 41 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0dba9a3..8e0f244 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `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. + without compression or retries, and a redirect is an error. A task input stream holds a JSON + object. - An `io.Reader` as `ActorServerRequestOptions.Body`, sent the same way. Before, it was serialized as JSON. - `ActorStoreListItem.Categories`, `Stats` (the new `StoreActorStats`) and `IsVerified`. diff --git a/actor.go b/actor.go index 3897a83..2c28a59 100644 --- a/actor.go +++ b/actor.go @@ -44,9 +44,9 @@ type ActorStartOptions struct { // 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. + // [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 } @@ -156,7 +156,8 @@ func (c *ActorClient) StartRaw(ctx context.Context, input []byte, options ActorS // 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 it follows no redirect. Hence +// would send what the first attempt left of the stream, and a redirect comes back as an error. +// The client closes the stream after the call if it is an [io.Closer]. Hence // options.WaitForResources is ignored, as the start is never retried. func (c *ActorClient) StartStream(ctx context.Context, input io.Reader, options ActorStartOptions) (ActorRun, error) { return c.startWithStream(ctx, input, options, c.startTimeout(options)) diff --git a/actor_server.go b/actor_server.go index fd749b7..8c87946 100644 --- a/actor_server.go +++ b/actor_server.go @@ -72,8 +72,9 @@ type ActorServerRequestOptions struct { 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. An [io.Reader] is a stream, sent the same way but only once: the - // request is not compressed, and nor retried on 429 or 503, since a retry would send what the - // first attempt left of the stream. A [json.RawMessage] and any other value are sent as JSON, with + // 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 after the call 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 diff --git a/docs/actors.md b/docs/actors.md index e5796c9..f624770 100644 --- a/docs/actors.md +++ b/docs/actors.md @@ -85,7 +85,7 @@ 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 follows no redirect. | +| `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 afterwards if it is an `io.Closer`. | | `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. | diff --git a/docs/storages.md b/docs/storages.md index ace17d2..afe8869 100644 --- a/docs/storages.md +++ b/docs/storages.md @@ -174,7 +174,7 @@ 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 follows no redirect. To upload with retries, read the value into bytes and use `SetRecordRaw`. `SetRecordStreamWithEncoding` is the variant for a stream that is already compressed. | +| `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 afterwards if it is an `io.Closer`. To upload with retries, read the value into bytes and use `SetRecordRaw`. `SetRecordStreamWithEncoding` is the variant for a stream that is already compressed. | | `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. | diff --git a/docs/tasks.md b/docs/tasks.md index 2015b7a..a9a5fe0 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -51,8 +51,8 @@ A task is a pre-configured Actor run with stored input. Access the task collecti | `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. | -| `StartStream(ctx, input io.Reader, contentType string, TaskStartOptions) (ActorRun, error)` | Like `Start`, but reads the input from a stream, such as a file, so it is not held in memory. `contentType` defaults to `application/octet-stream`. The stream is sent once: the request is not compressed or retried (`WaitForResources` is ignored) and follows no redirect. | -| `CallStream(ctx, input io.Reader, contentType string, TaskStartOptions, waitSecs *int64) (ActorRun, error)` | `StartStream` followed by waiting for the run to finish. | +| `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 afterwards if it is an `io.Closer`. | +| `CallStream(ctx, input io.Reader, TaskStartOptions, waitSecs *int64) (ActorRun, error)` | `StartStream` followed by waiting for the run to finish. | | `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 7e5a500..da62474 100644 --- a/http_client.go +++ b/http_client.go @@ -154,10 +154,11 @@ func (c *httpClient) callPreEncoded(ctx context.Context, method, url string, bod // 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. contentEncoding, when +// 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(ctx, method, url, body, contentType, contentEncoding, nil, c.attemptTimeout(baseTimeout, 1)) + resp, err := c.doAttemptReader(withoutRedirects(ctx), method, url, body, contentType, contentEncoding, nil, c.attemptTimeout(baseTimeout, 1)) if err != nil { return nil, err } diff --git a/key_value_store.go b/key_value_store.go index ce78177..727e95e 100644 --- a/key_value_store.go +++ b/key_value_store.go @@ -277,7 +277,8 @@ func (c *KeyValueStoreClient) SetRecordRawWithEncoding(ctx context.Context, key // 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 -// it follows no redirect. To upload with retries, read the value into bytes and use +// a redirect comes back as an error. The client closes the stream after the call 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, "") diff --git a/store_collection_test.go b/store_collection_test.go index 7d2b591..5888d4c 100644 --- a/store_collection_test.go +++ b/store_collection_test.go @@ -73,3 +73,20 @@ func TestStoreIterateWithoutSearchAdvancesTheOffset(t *testing.T) { 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) + if _, err := client.Store().List(context.Background(), StoreListOptions{IncludeInputSchema: Ptr(true)}); err != nil { + t.Fatal(err) + } + if !strings.Contains(backend.lastURL, "includeInputSchema=1") { + t.Errorf("expected includeInputSchema=1, got %q", backend.lastURL) + } + if _, err := client.Store().List(context.Background(), StoreListOptions{}); err != nil { + t.Fatal(err) + } + if strings.Contains(backend.lastURL, "includeInputSchema") { + t.Errorf("includeInputSchema must be omitted when unset, got %q", backend.lastURL) + } +} diff --git a/stream_body_test.go b/stream_body_test.go index 6567647..51b2a79 100644 --- a/stream_body_test.go +++ b/stream_body_test.go @@ -3,7 +3,9 @@ package apify import ( "context" "net/http" + "net/http/httptest" "strings" + "sync/atomic" "testing" ) @@ -123,19 +125,14 @@ func TestActorCallStreamWaitsForTheRun(t *testing.T) { } } -func TestTaskStartStreamSendsTheStreamOnce(t *testing.T) { +func TestTaskStartStreamSendsTheStreamOnceAsJSON(t *testing.T) { backend := &mockBackend{responses: constant(201, startedRun)} - run, err := streamClient(backend).Task("t").StartStream(context.Background(), strings.NewReader(compressibleBody), "", TaskStartOptions{}) + 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) } - assertSentOnceAsIs(t, backend, "application/octet-stream") - - backend = &mockBackend{responses: constant(201, startedRun)} - if _, err := streamClient(backend).Task("t").StartStream(context.Background(), strings.NewReader(compressibleBody), "text/csv", TaskStartOptions{}); err != nil { - t.Fatalf("StartStream with a content type: %v", err) - } - assertSentOnceAsIs(t, backend, "text/csv") + // The API accepts only a JSON object as the input of a task. + assertSentOnceAsIs(t, backend, "application/json") } func TestTaskCallStreamWaitsForTheRun(t *testing.T) { @@ -143,8 +140,28 @@ func TestTaskCallStreamWaitsForTheRun(t *testing.T) { {status: 201, body: startedRun}, {status: 200, body: `{"data":{"id":"run1","status":"SUCCEEDED"}}`}, }} - run, err := streamClient(backend).Task("t").CallStream(context.Background(), strings.NewReader("input"), "text/plain", TaskStartOptions{}, nil) + run, err := streamClient(backend).Task("t").CallStream(context.Background(), strings.NewReader(`{"a":1}`), TaskStartOptions{}, 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()) + } +} diff --git a/task.go b/task.go index abd61af..e9e4a76 100644 --- a/task.go +++ b/task.go @@ -113,40 +113,44 @@ 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. It has the content type -// "application/octet-stream" unless contentType is not empty. +// 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 it follows no redirect. Hence +// would send what the first attempt left of the stream, and a redirect comes back as an error. +// The client closes the stream after the call if it is an [io.Closer]. Hence // options.WaitForResources is ignored, as the start is never retried. -func (c *TaskClient) StartStream(ctx context.Context, input io.Reader, contentType string, options TaskStartOptions) (ActorRun, error) { - return c.startStreamWithTimeout(ctx, input, contentType, options, extendForServerWait(c.ctx.mediumTimeout(), options.WaitForFinish)) +func (c *TaskClient) StartStream(ctx context.Context, input io.Reader, options TaskStartOptions) (ActorRun, error) { + return c.startStreamWithTimeout(ctx, input, options, extendForServerWait(c.ctx.mediumTimeout(), options.WaitForFinish)) } -func (c *TaskClient) startStreamWithTimeout(ctx context.Context, input io.Reader, contentType string, options TaskStartOptions, timeout time.Duration) (ActorRun, error) { +func (c *TaskClient) startStreamWithTimeout(ctx context.Context, input io.Reader, options TaskStartOptions, timeout time.Duration) (ActorRun, error) { params := NewQueryParams() options.apply(params) - if contentType == "" { - contentType = "application/octet-stream" - } - return postStream[ActorRun](ctx, c.ctx, "runs", params, input, contentType, timeout) + 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, contentType string, options TaskStartOptions, waitSecs *int64) (ActorRun, error) { - run, err := c.startStreamWithTimeout(ctx, input, contentType, options, noRequestTimeout) - if err != nil { - return ActorRun{}, err - } - return c.root.Run(run.ID).WaitForFinish(ctx, waitSecs) +func (c *TaskClient) CallStream(ctx context.Context, input io.Reader, options TaskStartOptions, waitSecs *int64) (ActorRun, error) { + return c.callAndWait(ctx, 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. 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, 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. +func (c *TaskClient) callAndWait(ctx context.Context, waitSecs *int64, start func(timeout time.Duration) (ActorRun, error)) (ActorRun, error) { + run, err := start(noRequestTimeout) if err != nil { return ActorRun{}, err } 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) + } +} From 6c95a04f2829fd0f7c1cae2a59825026c842d1f9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:02:25 +0000 Subject: [PATCH 04/12] fix: close stream bodies on every path, document redirect handling for streamed requests A stream that is an io.Closer is closed when the call ends, also when it fails before sending. --- README.md | 3 ++- actor.go | 6 ++--- actor_server.go | 13 +++++++--- base.go | 10 ++++++++ docs/actors.md | 2 +- docs/server_actors.md | 2 +- docs/storages.md | 2 +- docs/tasks.md | 2 +- http_client.go | 9 ++++--- key_value_store.go | 3 ++- server_http.go | 5 ++-- stream_body_test.go | 57 +++++++++++++++++++++++++++++++++++++++++++ task.go | 4 +-- 13 files changed, 97 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index dff8dcc..4770e04 100644 --- a/README.md +++ b/README.md @@ -248,7 +248,8 @@ The transport is replaceable. Implement `HTTPBackend` (a single `Do` method) to custom client, proxy, or test double, and pass it with `WithHTTPBackend`. 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 diff --git a/actor.go b/actor.go index 2c28a59..774d07a 100644 --- a/actor.go +++ b/actor.go @@ -43,7 +43,7 @@ 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 + // 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. @@ -157,8 +157,8 @@ func (c *ActorClient) StartRaw(ctx context.Context, input []byte, options ActorS // // 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 after the call if it is an [io.Closer]. Hence -// options.WaitForResources is ignored, as the start is never retried. +// 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]. func (c *ActorClient) StartStream(ctx context.Context, input io.Reader, options ActorStartOptions) (ActorRun, error) { return c.startWithStream(ctx, input, options, c.startTimeout(options)) } diff --git a/actor_server.go b/actor_server.go index 8c87946..0b1fe4f 100644 --- a/actor_server.go +++ b/actor_server.go @@ -73,7 +73,7 @@ type ActorServerRequestOptions struct { // Body is the request body. A string or []byte is sent as it is, without a Content-Type // 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 after the call if it is an + // 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 @@ -343,7 +343,14 @@ 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) { +func (c *ActorServerClient) send(ctx context.Context, path string, options ActorServerRequestOptions, stream bool) (response *serverResponse, err error) { + // A stream body is closed whether or not the call got as far as sending it. + bodyStream, _ := options.Body.(io.Reader) + defer func() { + if err != nil { + closeStream(bodyStream) + } + }() method := strings.ToUpper(options.Method) if method == "" { method = http.MethodGet @@ -352,11 +359,9 @@ func (c *ActorServerClient) send(ctx context.Context, path string, options Actor return nil, fmt.Errorf("ActorServerRequestOptions.Method: unknown HTTP method %q", options.Method) } // A stream is sent as it is, so it is not encoded and its request is not retried. - bodyStream, _ := options.Body.(io.Reader) var body []byte var contentType string if bodyStream == nil { - var err error if body, contentType, err = encodeServerBody(options.Body); err != nil { return nil, err } diff --git a/base.go b/base.go index 7351404..69a91a0 100644 --- a/base.go +++ b/base.go @@ -309,11 +309,20 @@ 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)) @@ -406,6 +415,7 @@ func putRawWithEncoding(ctx context.Context, c *resourceContext, subPath string, // 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)) diff --git a/docs/actors.md b/docs/actors.md index f624770..0f5e3e9 100644 --- a/docs/actors.md +++ b/docs/actors.md @@ -85,7 +85,7 @@ 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 afterwards if it is an `io.Closer`. | +| `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`. | | `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. | diff --git a/docs/server_actors.md b/docs/server_actors.md index 97498ce..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. 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. 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 afe8869..ad628ad 100644 --- a/docs/storages.md +++ b/docs/storages.md @@ -174,7 +174,7 @@ 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 afterwards if it is an `io.Closer`. To upload with retries, read the value into bytes and use `SetRecordRaw`. `SetRecordStreamWithEncoding` is the variant for a stream that is already compressed. | +| `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` is the variant for a stream that is already compressed. | | `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. | diff --git a/docs/tasks.md b/docs/tasks.md index a9a5fe0..dc1e4c2 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -51,7 +51,7 @@ A task is a pre-configured Actor run with stored input. Access the task collecti | `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. | -| `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 afterwards if it is an `io.Closer`. | +| `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`. | | `CallStream(ctx, input io.Reader, TaskStartOptions, waitSecs *int64) (ActorRun, error)` | `StartStream` followed by waiting for the run to finish. | | `GetInput(ctx) (json.RawMessage, error)` | Fetch the stored input. | | `UpdateInput(ctx, input any) (json.RawMessage, error)` | Replace the stored input. | diff --git a/http_client.go b/http_client.go index da62474..c2f707e 100644 --- a/http_client.go +++ b/http_client.go @@ -44,7 +44,8 @@ const ( // as a refused connection, a DNS error or a timeout. // // 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) @@ -154,9 +155,8 @@ func (c *httpClient) callPreEncoded(ctx context.Context, method, url string, bod // 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. +// 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 { @@ -268,6 +268,7 @@ func (c *httpClient) doAttemptReader(ctx context.Context, method, url string, bo 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 727e95e..335b817 100644 --- a/key_value_store.go +++ b/key_value_store.go @@ -277,7 +277,7 @@ func (c *KeyValueStoreClient) SetRecordRawWithEncoding(ctx context.Context, key // 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 after the call if it is an +// 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 { @@ -294,6 +294,7 @@ func (c *KeyValueStoreClient) SetRecordStreamWithEncoding(ctx context.Context, k 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) diff --git a/server_http.go b/server_http.go index e1753de..3e8f038 100644 --- a/server_http.go +++ b/server_http.go @@ -27,14 +27,15 @@ 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 +// [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 diff --git a/stream_body_test.go b/stream_body_test.go index 51b2a79..4c7e205 100644 --- a/stream_body_test.go +++ b/stream_body_test.go @@ -2,6 +2,7 @@ package apify import ( "context" + "io" "net/http" "net/http/httptest" "strings" @@ -165,3 +166,59 @@ func TestStreamCallsDoNotFollowRedirects(t *testing.T) { t.Fatalf("the redirect target was called %d times", targetHits.Load()) } } + +// closeRecorder is a stream that records whether it was closed. +type closeRecorder struct { + io.Reader + closed atomic.Bool +} + +func (r *closeRecorder) Close() error { + r.closed.Store(true) + return nil +} + +// transportClosingBackend closes the request body once the request is done, as the HTTP transport +// does, which the mock backend does not. +type transportClosingBackend struct{ HTTPBackend } + +func (b transportClosingBackend) Do(req *http.Request) (*http.Response, error) { + defer func() { _ = req.Body.Close() }() + return b.HTTPBackend.Do(req) +} + +// The client closes a stream that is an io.Closer when the call ends, also when the call fails +// before it sends anything. +func TestStreamCallsCloseTheStream(t *testing.T) { + ctx := context.Background() + client := streamClient(transportClosingBackend{&mockBackend{responses: constant(200, startedRun)}}) + cases := []struct { + name string + run func(stream io.Reader) error + }{ + {"sent", func(s io.Reader) error { return client.KeyValueStore("s").SetRecordStream(ctx, "k", s, "text/plain") }}, + {"invalid key", func(s io.Reader) error { return client.KeyValueStore("s").SetRecordStream(ctx, "..", s, "text/plain") }}, + {"empty store ID", func(s io.Reader) error { return client.KeyValueStore("").SetRecordStream(ctx, "k", s, "text/plain") }}, + {"empty task ID", func(s io.Reader) error { + _, err := client.Task("").StartStream(ctx, s, TaskStartOptions{}) + return err + }}, + {"Actor start", func(s io.Reader) error { + _, err := client.Actor("a").StartStream(ctx, s, ActorStartOptions{}) + return err + }}, + {"server request with an unknown method", func(s io.Reader) error { + _, err := client.Actor("a").Server().Request(ctx, "/", ActorServerRequestOptions{Method: "NOPE", Body: s}) + return err + }}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + stream := &closeRecorder{Reader: strings.NewReader("data")} + _ = c.run(stream) + if !stream.closed.Load() { + t.Error("the stream was not closed") + } + }) + } +} diff --git a/task.go b/task.go index e9e4a76..b3c628e 100644 --- a/task.go +++ b/task.go @@ -118,8 +118,8 @@ func (c *TaskClient) startWithTimeout(ctx context.Context, input any, options Ta // // 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 after the call if it is an [io.Closer]. Hence -// options.WaitForResources is ignored, as the start is never retried. +// 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]. func (c *TaskClient) StartStream(ctx context.Context, input io.Reader, options TaskStartOptions) (ActorRun, error) { return c.startStreamWithTimeout(ctx, input, options, extendForServerWait(c.ctx.mediumTimeout(), options.WaitForFinish)) } From 9fe88d26b99da59155a8ab2041a404b1a93088ec Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:08:51 +0000 Subject: [PATCH 05/12] fix: close a streamed request body once, require backends to close request bodies --- README.md | 7 +++-- actor_server.go | 11 +++----- http_client.go | 3 +++ server_http.go | 5 ++-- stream_body_test.go | 62 +++++++++++++++++++++++++++++---------------- 5 files changed, 55 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index 4770e04..60b020d 100644 --- a/README.md +++ b/README.md @@ -245,7 +245,9 @@ 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 on error, as an `http.RoundTripper` does: the client relies +on that to close a stream body that it did not open. 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. The requests with a stream body (such as @@ -267,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) diff --git a/actor_server.go b/actor_server.go index 0b1fe4f..d4b196f 100644 --- a/actor_server.go +++ b/actor_server.go @@ -343,25 +343,21 @@ 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) (response *serverResponse, err error) { - // A stream body is closed whether or not the call got as far as sending it. +func (c *ActorServerClient) send(ctx context.Context, path string, options ActorServerRequestOptions, stream bool) (*serverResponse, error) { bodyStream, _ := options.Body.(io.Reader) - defer func() { - if err != nil { - closeStream(bodyStream) - } - }() 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) } // 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 } @@ -373,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 diff --git a/http_client.go b/http_client.go index c2f707e..b6132b4 100644 --- a/http_client.go +++ b/http_client.go @@ -43,6 +43,9 @@ 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 a stream body that it did not open. +// // 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, or a // stream body that a redirect cannot replay. diff --git a/server_http.go b/server_http.go index 3e8f038..f299f07 100644 --- a/server_http.go +++ b/server_http.go @@ -35,8 +35,8 @@ func withoutRedirects(ctx context.Context) context.Context { // 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], 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. +// 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 } @@ -143,6 +143,7 @@ func (c *httpClient) serverAttempt(ctx context.Context, call serverCall, body io 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/stream_body_test.go b/stream_body_test.go index 4c7e205..c9c7978 100644 --- a/stream_body_test.go +++ b/stream_body_test.go @@ -167,58 +167,76 @@ func TestStreamCallsDoNotFollowRedirects(t *testing.T) { } } -// closeRecorder is a stream that records whether it was closed. +// closeRecorder is a stream that counts its closes. type closeRecorder struct { io.Reader - closed atomic.Bool + closes atomic.Int32 } func (r *closeRecorder) Close() error { - r.closed.Store(true) + r.closes.Add(1) return nil } -// transportClosingBackend closes the request body once the request is done, as the HTTP transport -// does, which the mock backend does not. -type transportClosingBackend struct{ HTTPBackend } - -func (b transportClosingBackend) Do(req *http.Request) (*http.Response, error) { - defer func() { _ = req.Body.Close() }() - return b.HTTPBackend.Do(req) -} - -// The client closes a stream that is an io.Closer when the call ends, also when the call fails -// before it sends anything. -func TestStreamCallsCloseTheStream(t *testing.T) { +// 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(transportClosingBackend{&mockBackend{responses: constant(200, startedRun)}}) + client := streamClient(&mockBackend{responses: constant(200, startedRun)}) + badURLClient := NewClient(WithToken("t"), WithBaseURL("http://[::1"), WithMaxRetries(0)) cases := []struct { name string run func(stream io.Reader) error }{ - {"sent", func(s io.Reader) error { return client.KeyValueStore("s").SetRecordStream(ctx, "k", s, "text/plain") }}, {"invalid key", func(s io.Reader) error { return client.KeyValueStore("s").SetRecordStream(ctx, "..", s, "text/plain") }}, {"empty store ID", func(s io.Reader) error { return client.KeyValueStore("").SetRecordStream(ctx, "k", s, "text/plain") }}, {"empty task ID", func(s io.Reader) error { _, err := client.Task("").StartStream(ctx, s, TaskStartOptions{}) return err }}, - {"Actor start", func(s io.Reader) error { - _, err := client.Actor("a").StartStream(ctx, s, ActorStartOptions{}) + {"invalid URL", func(s io.Reader) error { + _, err := badURLClient.Actor("a").StartStream(ctx, s, ActorStartOptions{}) return err }}, {"server request with an unknown method", func(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(s io.Reader) error { + f := newServerFixture(t) + f.noActor() + _, err := f.client().Actor(serverTestActorID).Server().Request(ctx, "/", 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")} - _ = c.run(stream) - if !stream.closed.Load() { - t.Error("the stream was not closed") + if err := c.run(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) } }) } } + +// A request that was sent is closed by the HTTP transport, and the client does not close the +// stream a second time, also 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) + } +} From 28599346123c533ec0a0e0e33402bd3b23254691 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:16:44 +0000 Subject: [PATCH 06/12] test: cover every close path of stream bodies, reword the backend requirement --- README.md | 4 ++-- http_client.go | 2 +- stream_body_test.go | 57 +++++++++++++++++++++++++++++++++++++-------- 3 files changed, 50 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 60b020d..225e35a 100644 --- a/README.md +++ b/README.md @@ -246,8 +246,8 @@ the request. The transport is replaceable. Implement `HTTPBackend` (a single `Do` method) to integrate a custom client, proxy, or test double, and pass it with `WithHTTPBackend`. The backend must close -`req.Body` once it is done with it, also on error, as an `http.RoundTripper` does: the client relies -on that to close a stream body that it did not open. A backend that follows +`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. The requests with a stream body (such as diff --git a/http_client.go b/http_client.go index b6132b4..c6f6eaf 100644 --- a/http_client.go +++ b/http_client.go @@ -44,7 +44,7 @@ const ( // 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 a stream body that it did not open. +// [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, or a diff --git a/stream_body_test.go b/stream_body_test.go index c9c7978..8a57f85 100644 --- a/stream_body_test.go +++ b/stream_body_test.go @@ -186,33 +186,43 @@ func TestStreamCallsThatFailBeforeSendingCloseTheStreamOnce(t *testing.T) { badURLClient := NewClient(WithToken("t"), WithBaseURL("http://[::1"), WithMaxRetries(0)) cases := []struct { name string - run func(stream io.Reader) error + run func(t *testing.T, stream io.Reader) error }{ - {"invalid key", func(s io.Reader) error { return client.KeyValueStore("s").SetRecordStream(ctx, "..", s, "text/plain") }}, - {"empty store ID", func(s io.Reader) error { return client.KeyValueStore("").SetRecordStream(ctx, "k", s, "text/plain") }}, - {"empty task ID", func(s 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(s io.Reader) error { + {"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(s io.Reader) error { + {"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(s io.Reader) error { + {"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 to a malformed server URL", func(t *testing.T, s io.Reader) error { + f := newServerFixture(t) + f.setActor(map[string]any{"standbyUrl": "http://[::1"}) + _, err := f.client().Actor(serverTestActorID).Server().Request(ctx, "/", 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(stream); err == nil { + if err := c.run(t, stream); err == nil { t.Fatal("expected the call to fail") } if got := stream.closes.Load(); got != 1 { @@ -222,8 +232,8 @@ func TestStreamCallsThatFailBeforeSendingCloseTheStreamOnce(t *testing.T) { } } -// A request that was sent is closed by the HTTP transport, and the client does not close the -// stream a second time, also when the request fails. +// 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, whether the request succeeds or fails. func TestServerRequestStreamIsClosedOnceByTheTransport(t *testing.T) { f := newServerFixture(t) unreachable := httptest.NewServer(http.NotFoundHandler()) @@ -240,3 +250,30 @@ func TestServerRequestStreamIsClosedOnceByTheTransport(t *testing.T) { 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) + } + }) + } +} From 5e0e3edd6114d00b1d0bbdf0aac1a12eacc1c75b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:22:20 +0000 Subject: [PATCH 07/12] test: cover the request build failure of a streamed server request --- http_client.go | 3 ++- stream_body_test.go | 7 +++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/http_client.go b/http_client.go index c6f6eaf..410cf04 100644 --- a/http_client.go +++ b/http_client.go @@ -44,7 +44,8 @@ const ( // 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. +// [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, or a diff --git a/stream_body_test.go b/stream_body_test.go index 8a57f85..44c01ad 100644 --- a/stream_body_test.go +++ b/stream_body_test.go @@ -212,10 +212,9 @@ func TestStreamCallsThatFailBeforeSendingCloseTheStreamOnce(t *testing.T) { _, err := f.client().Actor(serverTestActorID).Server().Request(ctx, "/", ActorServerRequestOptions{Method: "POST", Body: s}) return err }}, - {"server request to a malformed server URL", func(t *testing.T, s io.Reader) error { + {"server request with a path that is not a valid URL", func(t *testing.T, s io.Reader) error { f := newServerFixture(t) - f.setActor(map[string]any{"standbyUrl": "http://[::1"}) - _, err := f.client().Actor(serverTestActorID).Server().Request(ctx, "/", ActorServerRequestOptions{Method: "POST", Body: s}) + _, err := f.client().Actor(serverTestActorID).Server().Request(ctx, "/%zz", ActorServerRequestOptions{Method: "POST", Body: s}) return err }}, } @@ -233,7 +232,7 @@ func TestStreamCallsThatFailBeforeSendingCloseTheStreamOnce(t *testing.T) { } // 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, whether the request succeeds or fails. +// close the stream a second time when the request fails (see TestSentStreamIsClosedOnce for success). func TestServerRequestStreamIsClosedOnceByTheTransport(t *testing.T) { f := newServerFixture(t) unreachable := httptest.NewServer(http.NotFoundHandler()) From f4fc6320cc2448c9aa14bd3b08e8dedbfad4ba4f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:26:21 +0000 Subject: [PATCH 08/12] style: shorten a test comment --- stream_body_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/stream_body_test.go b/stream_body_test.go index 44c01ad..71ac41d 100644 --- a/stream_body_test.go +++ b/stream_body_test.go @@ -232,7 +232,7 @@ func TestStreamCallsThatFailBeforeSendingCloseTheStreamOnce(t *testing.T) { } // 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 (see TestSentStreamIsClosedOnce for success). +// close the stream a second time when the request fails. func TestServerRequestStreamIsClosedOnceByTheTransport(t *testing.T) { f := newServerFixture(t) unreachable := httptest.NewServer(http.NotFoundHandler()) From e91444eb316f554df36fa7fcec50cd7f2586262c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 09:05:44 +0000 Subject: [PATCH 09/12] feat: split the Store search from the Store listing, redirect task run logs, resume streamed logs after a cut Add StoreCollectionClient.Search and drop Search and SortBy from StoreListOptions, as the API answers a search with one page. Remove the AllowsAgenticUsers filter the API dropped. Redirect the log of a task run in Call and CallStream, add StreamedLogOptions.Since and StreamedLog.LastRedirectedAt, and reopen a log stream that was cut off. Update the spec version to v2-2026-12-02T102104Z and document signed URLs and build OpenAPI access. --- CHANGELOG.md | 28 +++-- README.md | 4 +- actor.go | 6 +- build.go | 3 + call_test.go | 2 +- dataset.go | 4 + docs/actors.md | 2 +- docs/builds.md | 2 +- docs/misc.md | 31 +++-- docs/runs.md | 15 ++- docs/storages.md | 4 +- docs/tasks.md | 4 +- key_value_store.go | 2 + store_collection.go | 135 ++++++++++++++++------ store_collection_test.go | 67 ++++++++--- stream_body_test.go | 2 +- streamed_log.go | 244 +++++++++++++++++++++++++++++++-------- streamed_log_test.go | 220 ++++++++++++++++++++++++++++++++++- task.go | 24 ++-- tests/store_test.go | 46 +++++--- version.go | 2 +- 21 files changed, 685 insertions(+), 162 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e0f244..373a870 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- `StoreCollectionClient.Search`, with `StoreSearchOptions` and `StoreSearchResult`, for a text + search of the Store. The API answers it with one page of at most 100 Actors by relevance, and + `Search` sends one request, requires a non-empty `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, @@ -17,24 +20,35 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - An `io.Reader` as `ActorServerRequestOptions.Body`, sent the same way. Before, it was serialized as JSON. - `ActorStoreListItem.Categories`, `Stats` (the new `StoreActorStats`) and `IsVerified`. +- `TaskStartOptions.Log`. `TaskClient.Call` and `CallStream` now redirect the log of the run while + they wait, as `ActorClient.Call` does. Set `Log.Disabled` to turn it off. +- `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 +- `StoreListOptions` no longer has `Search` and `SortBy`, so `StoreCollectionClient.List` and + `Iterate` go through the Store in Store order. Use `StoreCollectionClient.Search` for a query: + paging through a search repeated the same Actors without end, as the API ignores the offset for it. - `categories`, `stats` and `isVerified` of a Store Actor are no longer in `ActorStoreListItem.Extra`. -- `StoreCollectionClient.Iterate` with `StoreListOptions.Search` set makes one request and yields - each Actor once. The API ignores the offset for a search, so paging through it repeated the same - Actors without end. - `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 single-page - search, the comma-separated `Category` IDs, and `IncludeUnrunnableActors`, `ResponseFormat` and - `AllowsAgenticUsers`. +- 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`. + +### Removed + +- `StoreListOptions.AllowsAgenticUsers`, as the API no longer has the filter. ### Deprecated -- `StoreListOptions.SortBy`, which the API ignores. +- `StreamedLogOptions.FromStart`. Use `Since`. ## [0.16.2] - 2026-11-24 diff --git a/README.md b/README.md index 225e35a..6450525 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 the 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). | @@ -289,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 774d07a..e1bd455 100644 --- a/actor.go +++ b/actor.go @@ -237,11 +237,7 @@ func (c *ActorClient) callAndWait(ctx context.Context, options ActorStartOptions 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/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 0f5e3e9..dd3485c 100644 --- a/docs/actors.md +++ b/docs/actors.md @@ -159,7 +159,7 @@ fmt.Println(string(result)) // raw JSON validation result | `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): 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 a274548..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. With `Search` set, it makes one request: `Limit` is the page size, `chunkSize` is ignored and at most 100 Actors are yielded. | +| `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. The API ignores it when `Search` is set. | -| `Limit` | `*int64` | Maximum number of Actors to return. The default and the maximum are 1000, or 100 when `Search` is set, where a larger value is reduced to 100. | -| `Search` | `*string` | Search query. Results are ranked by relevance and returned as a single page of at most 100 Actors, with no second page. Narrow them with `Category`, `Username` or `PricingModel`. | -| `SortBy` | `*string` | Deprecated: the API ignores it. Results are ordered by relevance when `Search` is set, and by Store position otherwise. Sort the results on the client for another order. | +| `Offset` | `*int64` | Number of Actors to skip. | +| `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` | 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. | -| `AllowsAgenticUsers` | `*bool` | `true` returns only Actors that allow agentic users, and `false` only Actors that do not. | | `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 | @@ -53,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..885b6cf 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,7 +156,8 @@ 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`. | +| `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`. | The log is split into messages at the timestamps the platform puts in front of each of them, so a @@ -170,7 +171,13 @@ returns its error and the rest of the log is not redirected, unless the `ctx` gi 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; +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/storages.md b/docs/storages.md index ad628ad..d6efedc 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`: @@ -182,7 +182,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 dc1e4c2..585e2c6 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -50,9 +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`. | -| `CallStream(ctx, input io.Reader, TaskStartOptions, waitSecs *int64) (ActorRun, error)` | `StartStream` followed by waiting for the run to finish. | +| `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/key_value_store.go b/key_value_store.go index 335b817..0d2cd6b 100644 --- a/key_value_store.go +++ b/key_value_store.go @@ -394,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/store_collection.go b/store_collection.go index b7d2ea7..386f409 100644 --- a/store_collection.go +++ b/store_collection.go @@ -1,23 +1,18 @@ 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. The API ignores it when Search is set. + // Offset is the number of Actors to skip. Offset *int64 - // Limit is the maximum number of Actors to return. The default and the maximum are 1000, or - // 100 when Search is set, where a larger value is reduced to 100. + // Limit is the maximum number of Actors to return. The default and the maximum are 1000. Limit *int64 - // Search ranks Actors by relevance to the query and returns them as a single page of at most - // 100 Actors, with no second page. Narrow the results with Category, Username or - // PricingModel. - Search *string - // SortBy sets the sort field. - // - // Deprecated: The API ignores it. Results are ordered by relevance when Search is set, and by - // Store position otherwise. Sort the results on the client for another order. - SortBy *string // 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. @@ -30,9 +25,6 @@ type StoreListOptions struct { // 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, if true, returns only Actors that allow agentic users, and if false, - // only Actors that do not. - AllowsAgenticUsers *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. @@ -46,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 the 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 } @@ -66,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) @@ -77,21 +125,11 @@ 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). -// -// With Search set, the API ranks the Actors by relevance and returns a single page of at most 100 -// of them, ignoring the offset, so a second page would repeat the first. The iterator then makes -// one request: Limit is the page size, chunkSize is ignored, and no more than 100 Actors are -// yielded. +// 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 { - if options.Search != nil && *options.Search != "" { - options.Offset = nil - return newUnpaginatedIterator(func(ctx context.Context) (PaginationList[ActorStoreListItem], error) { - return c.List(ctx, options) - }) - } return newListIterator(options.Limit, chunkSize, offsetVal(options.Offset), func(ctx context.Context, offset, limit int64) (PaginationList[ActorStoreListItem], error) { opts := options opts.Offset = &offset @@ -99,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 5888d4c..2878799 100644 --- a/store_collection_test.go +++ b/store_collection_test.go @@ -26,32 +26,65 @@ func (b *searchIgnoringOffsetBackend) Do(req *http.Request) (*http.Response, err return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(page))}, nil } -// With Search set the API returns one page and ignores the offset, so the iterator makes one -// request and yields each actor once. -func TestStoreIterateWithSearchFetchesOnePage(t *testing.T) { +// 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{} - it := testClient(backend, 0).Store().Iterate(StoreListOptions{Search: Ptr("scraper"), Offset: Ptr(int64(7))}, Ptr(int64(1))) + 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, err := it.Next(context.Background()) - if err != nil { - t.Fatalf("Next: %v", err) + 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]) } - if item == nil { - break + } + 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]) } - ids = append(ids, item.ID) } - if strings.Join(ids, ",") != "a1,a2" { - t.Errorf("expected each actor once, got %v", ids) +} + +// 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) } - if len(backend.urls) != 1 || !strings.Contains(backend.urls[0], "search=scraper") || strings.Contains(backend.urls[0], "offset=") { - t.Errorf("expected one request for the search without an offset, 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") } } -// Without Search the iterator still pages through the Store with the offset. -func TestStoreIterateWithoutSearchAdvancesTheOffset(t *testing.T) { +// 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"}]}}`}, diff --git a/stream_body_test.go b/stream_body_test.go index 71ac41d..a286992 100644 --- a/stream_body_test.go +++ b/stream_body_test.go @@ -141,7 +141,7 @@ func TestTaskCallStreamWaitsForTheRun(t *testing.T) { {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{}, nil) + 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) } diff --git a/streamed_log.go b/streamed_log.go index c7d23cb..f956b25 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,16 @@ 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 + // 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 +139,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 +179,9 @@ func (s *StreamedLog) Start(ctx context.Context) error { s.done = make(chan error, 1) s.buffer.Reset() s.scanned = 0 + s.receivedData = false + s.replayedUntil = time.Time{} + s.replaySkipCount = 0 go func() { s.done <- s.streamLog(ctx, streamCtx) }() @@ -256,25 +292,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 +306,148 @@ func (s *StreamedLog) redirect(parent, streamCtx context.Context) error { } if s.isStopping() { _ = stream.Close() - continue + break } - var readErr error - gotBytes, readErr = s.consumeStream(stream) + 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 { + // The stream ended after it had delivered data: it carried the whole log of a + // finished run. + 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.gotData() { + // Stopped before any stream delivered a byte. 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) } 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 +} + +// 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.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 +501,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 +523,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..f50b04d 100644 --- a/streamed_log_test.go +++ b/streamed_log_test.go @@ -44,6 +44,9 @@ 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. @@ -102,6 +105,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() @@ -134,6 +143,11 @@ func (b *logBackend) Do(req *http.Request) (*http.Response, error) { 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 +247,155 @@ 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) + } +} + +// 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 +822,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 +926,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 +943,11 @@ 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 +} diff --git a/task.go b/task.go index b3c628e..a31bbc5 100644 --- a/task.go +++ b/task.go @@ -74,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) { @@ -133,28 +138,33 @@ func (c *TaskClient) startStreamWithTimeout(ctx context.Context, input io.Reader // 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, waitSecs, func(timeout time.Duration) (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) { - return c.callAndWait(ctx, waitSecs, func(timeout time.Duration) (ActorRun, error) { + 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. -func (c *TaskClient) callAndWait(ctx context.Context, waitSecs *int64, start func(timeout time.Duration) (ActorRun, error)) (ActorRun, error) { +// 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/store_test.go b/tests/store_test.go index bcadc01..101b477 100644 --- a/tests/store_test.go +++ b/tests/store_test.go @@ -69,29 +69,45 @@ func TestListStoreIncludeInputSchema(t *testing.T) { } } -// TestIterateStoreSearch iterates a search, which the API answers with a single page: each Actor -// comes once, and the iteration ends. -func TestIterateStoreSearch(t *testing.T) { +// 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() - it := client.Store().Iterate(apify.StoreListOptions{Search: ptr("web scraper")}, ptr(int64(5))) + 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, err := it.Next(ctx) - if err != nil { - t.Fatalf("iterate: %v", err) - } - if item == nil { - break - } + for _, item := range result.Items { if seen[item.ID] { - t.Fatalf("Actor %s was yielded twice", item.ID) + t.Fatalf("Actor %s was returned twice", item.ID) } seen[item.ID] = true } - if len(seen) == 0 { - t.Fatal("expected the search to find Actors") +} + +// 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/version.go b/version.go index 9c54a47..b5f0dc9 100644 --- a/version.go +++ b/version.go @@ -6,4 +6,4 @@ 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" From cbea6eae4792de8e27a6b5ba5feb93aa2666db34 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 09:18:21 +0000 Subject: [PATCH 10/12] fix: read the rest of a streamed log when it is stopped after a cut, bound stream starts by the long tier Stop reads the whole log through the replay filter when a broken log stream was not replaced yet. ActorClient.StartStream and TaskClient.StartStream use the long timeout tier. Document SetRecordStreamWithEncoding, regroup the CHANGELOG entries and share the content type fallback. --- CHANGELOG.md | 26 +++++++++++++++----------- README.md | 2 +- actor.go | 28 +++++++++++++++------------- docs/actors.md | 2 +- docs/runs.md | 2 +- docs/storages.md | 3 ++- docs/tasks.md | 2 +- store_collection.go | 2 +- streamed_log.go | 28 ++++++++++++++++++++++++---- streamed_log_test.go | 39 +++++++++++++++++++++++++++++++++++++++ task.go | 5 +++-- timeout_tier_test.go | 9 +++++++++ 12 files changed, 112 insertions(+), 36 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 373a870..8c0ace7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,23 +5,21 @@ 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-11-27 +## [0.17.0] - 2026-12-03 ### Added - `StoreCollectionClient.Search`, with `StoreSearchOptions` and `StoreSearchResult`, for a text - search of the Store. The API answers it with one page of at most 100 Actors by relevance, and - `Search` sends one request, requires a non-empty `Search`, and returns the Actors and the limit. + 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. -- An `io.Reader` as `ActorServerRequestOptions.Body`, sent the same way. Before, it was serialized - as JSON. - `ActorStoreListItem.Categories`, `Stats` (the new `StoreActorStats`) and `IsVerified`. -- `TaskStartOptions.Log`. `TaskClient.Call` and `CallStream` now redirect the log of the run while - they wait, as `ActorClient.Call` does. Set `Log.Disabled` to turn it off. +- `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. @@ -30,6 +28,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `StoreListOptions` no longer has `Search` and `SortBy`, so `StoreCollectionClient.List` and `Iterate` go through the Store in Store order. Use `StoreCollectionClient.Search` for a query: paging through a search repeated the same Actors without end, as the API ignores the offset for it. +- `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, @@ -42,14 +44,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added the `APIFY_AI` run origin to the `LastRunOptions.Origin` examples. - `APISpecVersion` is `v2-2026-12-02T102104Z`. -### Removed - -- `StoreListOptions.AllowsAgenticUsers`, as the API no longer has the filter. - ### Deprecated - `StreamedLogOptions.FromStart`. Use `Since`. +### Removed + +- `StoreListOptions.Search` and `SortBy`. Use `StoreCollectionClient.Search`, as the API ignores + `sortBy`. +- `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 6450525..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, iterate and search 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). | diff --git a/actor.go b/actor.go index e1bd455..4286450 100644 --- a/actor.go +++ b/actor.go @@ -158,9 +158,18 @@ func (c *ActorClient) StartRaw(ctx context.Context, input []byte, options ActorS // 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]. +// 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, c.startTimeout(options)) + 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 @@ -175,25 +184,18 @@ 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 of the content type from -// options.ContentType, or application/octet-stream. +// 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) - contentType := "application/octet-stream" - if options.ContentType != nil && *options.ContentType != "" { - contentType = *options.ContentType - } - return postStream[ActorRun](ctx, c.ctx, "runs", params, input, contentType, timeout) + 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 diff --git a/docs/actors.md b/docs/actors.md index dd3485c..8c8a871 100644 --- a/docs/actors.md +++ b/docs/actors.md @@ -85,7 +85,7 @@ 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`. | +| `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. | diff --git a/docs/runs.md b/docs/runs.md index 885b6cf..f417a5a 100644 --- a/docs/runs.md +++ b/docs/runs.md @@ -158,7 +158,7 @@ if err := streamed.Stop(ctx); err != nil { | `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. | | `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`. | +| `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; diff --git a/docs/storages.md b/docs/storages.md index d6efedc..246dd6a 100644 --- a/docs/storages.md +++ b/docs/storages.md @@ -174,7 +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` is the variant for a stream that is already compressed. | +| `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. | diff --git a/docs/tasks.md b/docs/tasks.md index 585e2c6..c2ef711 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -51,7 +51,7 @@ A task is a pre-configured Actor run with stored input. Access the task collecti | `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. 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`. | +| `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. | diff --git a/store_collection.go b/store_collection.go index 386f409..91d5768 100644 --- a/store_collection.go +++ b/store_collection.go @@ -100,7 +100,7 @@ type StoreSearchResult struct { Limit int64 } -// StoreCollectionClient is a client for browsing and searching the Apify Store (GET /v2/store). +// 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 diff --git a/streamed_log.go b/streamed_log.go index f956b25..feb1c5a 100644 --- a/streamed_log.go +++ b/streamed_log.go @@ -93,6 +93,7 @@ type StreamedLog struct { 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 and has not been replaced by a healthy one // 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 @@ -180,6 +181,7 @@ func (s *StreamedLog) Start(ctx context.Context) error { s.buffer.Reset() s.scanned = 0 s.receivedData = false + s.streamBroken = false s.replayedUntil = time.Time{} s.replaySkipCount = 0 go func() { @@ -308,6 +310,9 @@ func (s *StreamedLog) redirect(parent, streamCtx context.Context) error { _ = stream.Close() break } + s.mu.Lock() + s.streamBroken = false + s.mu.Unlock() brokeOff, readErr := s.redirectStream(streamCtx, stream) _ = stream.Close() if readErr != nil { @@ -331,10 +336,10 @@ func (s *StreamedLog) redirect(parent, streamCtx context.Context) error { case <-streamCtx.Done(): } } - if !s.gotData() { - // Stopped before any stream delivered a byte. 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. + 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. readCtx, cancelRead := s.finalReadContext(parent) body, _, err := s.log.GetBufferWithOptions(readCtx, options) cancelRead() @@ -353,6 +358,20 @@ func (s *StreamedLog) gotData() bool { return s.receivedData } +// needsFinalRead reports whether Stop has to read the whole log: no stream delivered anything, or +// the last stream broke off and its replacement has not reached the last redirected message yet, +// so the messages after the break are still missing. The messages that were already redirected +// are skipped, as in a reopened stream. +func (s *StreamedLog) needsFinalRead() bool { + s.mu.Lock() + missing := !s.receivedData || s.streamBroken || !s.replayedUntil.IsZero() && s.replaySkipCount > 0 + s.mu.Unlock() + if missing && s.gotData() { + s.prepareReopen() + } + return missing +} + // 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 @@ -388,6 +407,7 @@ func (s *StreamedLog) prepareReopen() { defer s.mu.Unlock() s.replayedUntil = s.lastRedirected s.replaySkipCount = s.lastRedirectedCount + s.streamBroken = true s.buffer.Reset() s.scanned = 0 } diff --git a/streamed_log_test.go b/streamed_log_test.go index f50b04d..e502c52 100644 --- a/streamed_log_test.go +++ b/streamed_log_test.go @@ -346,6 +346,38 @@ func TestStreamedLogReopensABrokenStreamWithoutRepeatingMessages(t *testing.T) { } } +// 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()) + } +} + // 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) { @@ -951,3 +983,10 @@ func (s *StreamedLog) stoppedEarly() bool { defer s.mu.Unlock() return len(s.done) > 0 } + +// waitingToReopen reports whether the last log stream broke off and no stream has replaced it. +func (s *StreamedLog) waitingToReopen() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.streamBroken +} diff --git a/task.go b/task.go index a31bbc5..6b45d8b 100644 --- a/task.go +++ b/task.go @@ -124,9 +124,10 @@ func (c *TaskClient) startWithTimeout(ctx context.Context, input any, options Ta // 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]. +// 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.mediumTimeout(), options.WaitForFinish)) + 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) { diff --git a/timeout_tier_test.go b/timeout_tier_test.go index 23cec85..4acc498 100644 --- a/timeout_tier_test.go +++ b/timeout_tier_test.go @@ -3,6 +3,7 @@ package apify import ( "context" "net/http" + "strings" "testing" "time" ) @@ -28,6 +29,14 @@ func TestLongTierCallsOutliveTheShortTier(t *testing.T) { _, 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 From c421098d8fa48d93fe9384d1d5453d8063542029 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 09:32:20 +0000 Subject: [PATCH 11/12] fix: read the rest of a streamed log when Stop cuts off a replaying stream A reopened stream that Stop cuts off before it caught up with the redirected messages no longer ends the redirection. Stop reads the whole log and redirects what is missing. Tidy the CHANGELOG and docs. --- CHANGELOG.md | 10 +++++----- docs/runs.md | 7 ++++--- docs/storages.md | 2 +- streamed_log.go | 31 ++++++++++++++++--------------- streamed_log_test.go | 42 ++++++++++++++++++++++++++++++++++++++++-- 5 files changed, 66 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c0ace7..a781f62 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,9 +25,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- `StoreListOptions` no longer has `Search` and `SortBy`, so `StoreCollectionClient.List` and - `Iterate` go through the Store in Store order. Use `StoreCollectionClient.Search` for a query: - paging through a search repeated the same Actors without end, as the API ignores the offset for it. +- `StoreCollectionClient.List` and `Iterate` go through the 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 + is now `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 @@ -50,8 +50,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Removed -- `StoreListOptions.Search` and `SortBy`. Use `StoreCollectionClient.Search`, as the API ignores - `sortBy`. +- `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 diff --git a/docs/runs.md b/docs/runs.md index f417a5a..315ab09 100644 --- a/docs/runs.md +++ b/docs/runs.md @@ -164,9 +164,10 @@ The log is split into messages at the timestamps the platform puts in front of e 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` +messages in flight up to one second, then aborts the stream; if the stream delivered nothing yet, or +was cut off and its replacement has not caught up with the messages already redirected, it reads +the whole log in one request and redirects what is missing, 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 diff --git a/docs/storages.md b/docs/storages.md index 246dd6a..8f1febc 100644 --- a/docs/storages.md +++ b/docs/storages.md @@ -175,7 +175,7 @@ Single store: `client.KeyValueStore(id)`: | `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. | +| `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. | diff --git a/streamed_log.go b/streamed_log.go index feb1c5a..32cce06 100644 --- a/streamed_log.go +++ b/streamed_log.go @@ -93,7 +93,7 @@ type StreamedLog struct { 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 and has not been replaced by a healthy one + 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 @@ -191,8 +191,9 @@ 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 +// flight get up to one second. If the stream delivered nothing, or was cut off and its replacement +// has not caught up, Stop reads the whole log in one request and redirects what is missing, 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 // stopping. @@ -319,9 +320,10 @@ func (s *StreamedLog) redirect(parent, streamCtx context.Context) error { s.flush() return readErr } - if s.gotData() && !brokeOff { + if s.gotData() && !brokeOff && !s.isStopping() { // The stream ended after it had delivered data: it carried the whole log of a - // finished run. + // finished run. A stream that Stop cut off goes on below, as its replay may not + // have caught up. s.flush() return nil } @@ -339,7 +341,11 @@ func (s *StreamedLog) redirect(parent, streamCtx context.Context) error { 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. + // 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() @@ -359,17 +365,12 @@ func (s *StreamedLog) gotData() bool { } // needsFinalRead reports whether Stop has to read the whole log: no stream delivered anything, or -// the last stream broke off and its replacement has not reached the last redirected message yet, -// so the messages after the break are still missing. The messages that were already redirected -// are skipped, as in a reopened stream. +// 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() - missing := !s.receivedData || s.streamBroken || !s.replayedUntil.IsZero() && s.replaySkipCount > 0 - s.mu.Unlock() - if missing && s.gotData() { - s.prepareReopen() - } - return missing + 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 diff --git a/streamed_log_test.go b/streamed_log_test.go index e502c52..c21311e 100644 --- a/streamed_log_test.go +++ b/streamed_log_test.go @@ -51,6 +51,9 @@ type logBackend struct { 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 @@ -137,7 +140,7 @@ 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 { @@ -378,6 +381,41 @@ func TestStreamedLogStoppedWhileWaitingToReopenReadsTheRestOfTheLog(t *testing.T } } +// 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 }) + 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) { @@ -984,7 +1022,7 @@ func (s *StreamedLog) stoppedEarly() bool { return len(s.done) > 0 } -// waitingToReopen reports whether the last log stream broke off and no stream has replaced it. +// 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() From 779088bade7614f2038781ddebc43e5ef40464f4 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 09:43:42 +0000 Subject: [PATCH 12/12] fix: wait for the reopened stream in the replay test, reword the Stop docs --- CHANGELOG.md | 4 ++-- docs/runs.md | 31 ++++++++++++++++--------------- streamed_log.go | 11 ++++++----- streamed_log_test.go | 2 +- 4 files changed, 25 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a781f62..3722994 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,9 +25,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- `StoreCollectionClient.List` and `Iterate` go through the Store in Store order. Paging through a +- `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 - is now `StoreCollectionClient.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 diff --git a/docs/runs.md b/docs/runs.md index 315ab09..df6bbb8 100644 --- a/docs/runs.md +++ b/docs/runs.md @@ -164,22 +164,23 @@ The log is split into messages at the timestamps the platform puts in front of e 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, or -was cut off and its replacement has not caught up with the messages already redirected, it reads -the whole log in one request and redirects what is missing, 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. 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. +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. +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/streamed_log.go b/streamed_log.go index 32cce06..01226b7 100644 --- a/streamed_log.go +++ b/streamed_log.go @@ -191,11 +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, or was cut off and its replacement -// has not caught up, Stop reads the whole log in one request and redirects what is missing, 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() diff --git a/streamed_log_test.go b/streamed_log_test.go index c21311e..124bbb3 100644 --- a/streamed_log_test.go +++ b/streamed_log_test.go @@ -403,7 +403,7 @@ func TestStreamedLogStoppedWhileTheReopenedStreamReplaysReadsTheRestOfTheLog(t * if err := streamed.Start(ctx); err != nil { t.Fatal(err) } - waitFor(t, func() bool { return backend.streamRequests() == 2 }) + waitFor(t, func() bool { return backend.streamRequests() == 2 && !streamed.waitingToReopen() }) if err := streamed.Stop(ctx); err != nil { t.Fatalf("Stop: %v", err) }