From c9dd978fd0815f87b9440ac3bc49919fc991a2da Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:30:16 +0000 Subject: [PATCH 1/8] 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 e6b802926318e76ab94d7726c39ff6685db4cd9a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:43:41 +0000 Subject: [PATCH 2/8] 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 9c2e574eab1fdea55af72cfde7b7c74767004c01 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:55:46 +0000 Subject: [PATCH 3/8] 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 97d82d050719b852e06a3081fdc8930a47135efe Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:02:25 +0000 Subject: [PATCH 4/8] 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 02facbfc75263d64d7afedfe22f4538fcd79a153 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:08:51 +0000 Subject: [PATCH 5/8] 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 6d526816dd391cac86673c376724822524c607c0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:16:44 +0000 Subject: [PATCH 6/8] 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 01da42541e9fe2d55a99f5187ab75f0327380756 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:22:20 +0000 Subject: [PATCH 7/8] 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 2f59e59fa9fe8eb264fae147daf117a1e18fe6b5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:26:21 +0000 Subject: [PATCH 8/8] 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())