diff --git a/.changesets/1793357308-562eaa46.yaml b/.changesets/1793357308-562eaa46.yaml new file mode 100644 index 000000000..99a88bc4d --- /dev/null +++ b/.changesets/1793357308-562eaa46.yaml @@ -0,0 +1,10 @@ +id: 1793357308-562eaa46 +features: + - operationTimeout +targets: + - javav2 +type: feat +bump: minor +description: add an SDK-wide and per-call timeout that bounds the whole call including the response body and streams, on both HTTP clients, and honour x-speakeasy-timeout behind the enforceOperationTimeout option, which is on for new SDKs and off for existing ones +author: AshGodfrey +date: "2026-10-30" diff --git a/pkg/generate/snapshots/java8_raw_pagination_unwrap_java_test.go b/pkg/generate/snapshots/java8_raw_pagination_unwrap_java_test.go index c1e062567..564899c44 100644 --- a/pkg/generate/snapshots/java8_raw_pagination_unwrap_java_test.go +++ b/pkg/generate/snapshots/java8_raw_pagination_unwrap_java_test.go @@ -103,6 +103,7 @@ import java.io.InputStream; import java.lang.Iterable; import java.lang.Long; import java.lang.String; +import java.time.Duration; import java.util.Collection; import java.util.Iterator; import java.util.stream.Stream; @@ -110,6 +111,7 @@ import org.openapis.openapi.SDKConfiguration; import org.openapis.openapi.operations.ListItems; import org.openapis.openapi.utils.Headers; import org.openapis.openapi.utils.Java8Compat; +import org.openapis.openapi.utils.Options; import org.openapis.openapi.utils.Utils; import org.openapis.openapi.utils.pagination.CursorTracker; import org.openapis.openapi.utils.pagination.Paginator; @@ -120,11 +122,13 @@ public class ListItemsRequestBuilder { private final Headers _headers = new Headers(); private final ListItemsRequest.Builder pojoBuilder; private ListItemsRequest request; + private final Options.Builder optionsBuilder; private boolean _setterCalled; public ListItemsRequestBuilder(SDKConfiguration sdkConfiguration) { this.sdkConfiguration = sdkConfiguration; this.pojoBuilder = ListItemsRequest.builder(); + this.optionsBuilder = Options.builder(); } public ListItemsRequestBuilder cursor(@Nullable String cursor) { @@ -139,6 +143,11 @@ public class ListItemsRequestBuilder { return this; } + public ListItemsRequestBuilder timeout(Duration timeout) { + this.optionsBuilder.timeout(timeout); + return this; + } + private ListItemsRequest _buildRequest() { if (this._setterCalled) { this.request = this.pojoBuilder.build(); @@ -159,8 +168,9 @@ public class ListItemsRequestBuilder { * @return The response from the server. */ public ListItemsResponse call() { + Options options = optionsBuilder.build(); RequestOperation operation - = new ListItems.Sync(sdkConfiguration, _headers); + = new ListItems.Sync(sdkConfiguration, options, _headers); return operation.handleResponse(operation.doRequest(this._buildRequest())); } @@ -179,8 +189,9 @@ public class ListItemsRequestBuilder { */ public Iterable callAsIterable() { ListItemsRequest request = pojoBuilder.build(); + Options options = optionsBuilder.build(); RequestOperation operation - = new ListItems.Sync(sdkConfiguration, _headers); + = new ListItems.Sync(sdkConfiguration, options, _headers); Iterator> iterator = new Paginator<>( request, diff --git a/pkg/generate/snapshots/namespaces/mode_method_subsdk_collision_java_test.go b/pkg/generate/snapshots/namespaces/mode_method_subsdk_collision_java_test.go index 12e7b2258..34c064006 100644 --- a/pkg/generate/snapshots/namespaces/mode_method_subsdk_collision_java_test.go +++ b/pkg/generate/snapshots/namespaces/mode_method_subsdk_collision_java_test.go @@ -93,11 +93,13 @@ package org.openapis.openapi; import static org.openapis.openapi.operations.Operations.AsyncRequestlessOperation; +import jakarta.annotation.Nullable; import java.util.concurrent.CompletableFuture; import org.openapis.openapi.models.operations.async.GetFederationStatusRequestBuilder; import org.openapis.openapi.models.operations.async.GetFederationStatusResponse; import org.openapis.openapi.operations.GetFederationStatus; import org.openapis.openapi.utils.Headers; +import org.openapis.openapi.utils.Options; public class AsyncFederation { @@ -142,13 +144,23 @@ public class AsyncFederation { } /** - * Makes an async request + * Makes an async request(required parameters only). * * @return {@code CompletableFuture} - The async response */ public CompletableFuture getFederationStatusDirect() { + return getFederationStatus(null); + } + + /** + * Makes an async request + * + * @param options additional options + * @return {@code CompletableFuture} - The async response + */ + public CompletableFuture getFederationStatus(@Nullable Options options) { AsyncRequestlessOperation operation - = new GetFederationStatus.Async(sdkConfiguration, _headers); + = new GetFederationStatus.Async(sdkConfiguration, options, _headers); return operation.doRequest() .thenCompose(operation::handleResponse); } @@ -166,10 +178,12 @@ package org.openapis.openapi; import static org.openapis.openapi.operations.Operations.RequestlessOperation; +import jakarta.annotation.Nullable; import org.openapis.openapi.models.operations.GetFederationStatusRequestBuilder; import org.openapis.openapi.models.operations.GetFederationStatusResponse; import org.openapis.openapi.operations.GetFederationStatus; import org.openapis.openapi.utils.Headers; +import org.openapis.openapi.utils.Options; public class Federation { @@ -213,14 +227,25 @@ public class Federation { } /** - * Makes a request. + * Makes a request (required parameters only). * * @return The response from the API call * @throws RuntimeException subclass if the API call fails */ public GetFederationStatusResponse getFederationStatusDirect() { + return getFederationStatus(null); + } + + /** + * Makes a request. + * + * @param options additional options + * @return The response from the API call + * @throws RuntimeException subclass if the API call fails + */ + public GetFederationStatusResponse getFederationStatus(@Nullable Options options) { RequestlessOperation operation - = new GetFederationStatus.Sync(sdkConfiguration, _headers); + = new GetFederationStatus.Sync(sdkConfiguration, options, _headers); return operation.handleResponse(operation.doRequest()); } @@ -264,11 +289,13 @@ package org.openapis.openapi; import static org.openapis.openapi.operations.Operations.AsyncRequestlessOperation; +import jakarta.annotation.Nullable; import java.util.concurrent.CompletableFuture; import org.openapis.openapi.models.operations.async.GetFederationStatusRequestBuilder; import org.openapis.openapi.models.operations.async.GetFederationStatusResponse; import org.openapis.openapi.operations.GetFederationStatus; import org.openapis.openapi.utils.Headers; +import org.openapis.openapi.utils.Options; public class AsyncFederation { @@ -313,13 +340,23 @@ public class AsyncFederation { } /** - * Makes an async request + * Makes an async request(required parameters only). * * @return {@code CompletableFuture} - The async response */ public CompletableFuture getFederationStatusDirect() { + return getFederationStatus(null); + } + + /** + * Makes an async request + * + * @param options additional options + * @return {@code CompletableFuture} - The async response + */ + public CompletableFuture getFederationStatus(@Nullable Options options) { AsyncRequestlessOperation operation - = new GetFederationStatus.Async(sdkConfiguration, _headers); + = new GetFederationStatus.Async(sdkConfiguration, options, _headers); return operation.doRequest() .thenCompose(operation::handleResponse); } @@ -337,10 +374,12 @@ package org.openapis.openapi; import static org.openapis.openapi.operations.Operations.RequestlessOperation; +import jakarta.annotation.Nullable; import org.openapis.openapi.models.operations.GetFederationStatusRequestBuilder; import org.openapis.openapi.models.operations.GetFederationStatusResponse; import org.openapis.openapi.operations.GetFederationStatus; import org.openapis.openapi.utils.Headers; +import org.openapis.openapi.utils.Options; public class Federation { @@ -384,14 +423,25 @@ public class Federation { } /** - * Makes a request. + * Makes a request (required parameters only). * * @return The response from the API call * @throws RuntimeException subclass if the API call fails */ public GetFederationStatusResponse getFederationStatusDirect() { + return getFederationStatus(null); + } + + /** + * Makes a request. + * + * @param options additional options + * @return The response from the API call + * @throws RuntimeException subclass if the API call fails + */ + public GetFederationStatusResponse getFederationStatus(@Nullable Options options) { RequestlessOperation operation - = new GetFederationStatus.Sync(sdkConfiguration, _headers); + = new GetFederationStatus.Sync(sdkConfiguration, options, _headers); return operation.handleResponse(operation.doRequest()); } @@ -478,11 +528,13 @@ package org.openapis.openapi; import static org.openapis.openapi.operations.Operations.AsyncRequestlessOperation; +import jakarta.annotation.Nullable; import java.util.concurrent.CompletableFuture; import org.openapis.openapi.models.operations.async.GetFederationStatusRequestBuilder; import org.openapis.openapi.models.operations.async.GetFederationStatusResponse; import org.openapis.openapi.operations.GetFederationStatus; import org.openapis.openapi.utils.Headers; +import org.openapis.openapi.utils.Options; public class AsyncFederation { @@ -521,13 +573,23 @@ public class AsyncFederation { } /** - * Makes an async request + * Makes an async request(required parameters only). * * @return {@code CompletableFuture} - The async response */ public CompletableFuture getFederationStatusDirect() { + return getFederationStatus(null); + } + + /** + * Makes an async request + * + * @param options additional options + * @return {@code CompletableFuture} - The async response + */ + public CompletableFuture getFederationStatus(@Nullable Options options) { AsyncRequestlessOperation operation - = new GetFederationStatus.Async(sdkConfiguration, _headers); + = new GetFederationStatus.Async(sdkConfiguration, options, _headers); return operation.doRequest() .thenCompose(operation::handleResponse); } @@ -545,10 +607,12 @@ package org.openapis.openapi; import static org.openapis.openapi.operations.Operations.RequestlessOperation; +import jakarta.annotation.Nullable; import org.openapis.openapi.models.operations.GetFederationStatusRequestBuilder; import org.openapis.openapi.models.operations.GetFederationStatusResponse; import org.openapis.openapi.operations.GetFederationStatus; import org.openapis.openapi.utils.Headers; +import org.openapis.openapi.utils.Options; public class Federation { @@ -586,14 +650,25 @@ public class Federation { } /** - * Makes a request. + * Makes a request (required parameters only). * * @return The response from the API call * @throws RuntimeException subclass if the API call fails */ public GetFederationStatusResponse getFederationStatusDirect() { + return getFederationStatus(null); + } + + /** + * Makes a request. + * + * @param options additional options + * @return The response from the API call + * @throws RuntimeException subclass if the API call fails + */ + public GetFederationStatusResponse getFederationStatus(@Nullable Options options) { RequestlessOperation operation - = new GetFederationStatus.Sync(sdkConfiguration, _headers); + = new GetFederationStatus.Sync(sdkConfiguration, options, _headers); return operation.handleResponse(operation.doRequest()); } diff --git a/pkg/generate/snapshots/namespaces/model_namespace_subsdk_collision_java_test.go b/pkg/generate/snapshots/namespaces/model_namespace_subsdk_collision_java_test.go index 74c7fbb7d..2603776d0 100644 --- a/pkg/generate/snapshots/namespaces/model_namespace_subsdk_collision_java_test.go +++ b/pkg/generate/snapshots/namespaces/model_namespace_subsdk_collision_java_test.go @@ -29,10 +29,12 @@ package org.openapis.openapi; import static org.openapis.openapi.operations.Operations.RequestlessOperation; +import jakarta.annotation.Nullable; import org.openapis.openapi.models.operations.CreatePetRequestBuilder; import org.openapis.openapi.models.operations.CreatePetResponse; import org.openapis.openapi.operations.CreatePet; import org.openapis.openapi.utils.Headers; +import org.openapis.openapi.utils.Options; public class Pet { @@ -64,14 +66,25 @@ public class Pet { } /** - * Makes a request. + * Makes a request (required parameters only). * * @return The response from the API call * @throws RuntimeException subclass if the API call fails */ public CreatePetResponse createPetDirect() { + return createPet(null); + } + + /** + * Makes a request. + * + * @param options additional options + * @return The response from the API call + * @throws RuntimeException subclass if the API call fails + */ + public CreatePetResponse createPet(@Nullable Options options) { RequestlessOperation operation - = new CreatePet.Sync(sdkConfiguration, _headers); + = new CreatePet.Sync(sdkConfiguration, options, _headers); return operation.handleResponse(operation.doRequest()); } diff --git a/pkg/generate/snapshots/operation_timeout_flag_off_java_test.go b/pkg/generate/snapshots/operation_timeout_flag_off_java_test.go new file mode 100644 index 000000000..0866ccaff --- /dev/null +++ b/pkg/generate/snapshots/operation_timeout_flag_off_java_test.go @@ -0,0 +1,246 @@ +package snapshots + +import ( + "testing" + + "github.com/speakeasy-api/openapi-generation/v2/pkg/generate/snapshots/snaptest" +) + +// With enforceOperationTimeout disabled, an operation declaring +// x-speakeasy-timeout resolves its timeout from the SDK configuration alone +// and renders no Duration literal, so existing SDKs regenerated without +// opting in keep ignoring the extension. The primary and secondary variants +// cover the enabled path at runtime. +func TestSnapOperationTimeoutFlagOff(t *testing.T) { + t.Parallel() + spec := `openapi: 3.1.0 +info: + title: Timeout API + version: 1.0.0 +paths: + /things: + get: + operationId: listThings + x-speakeasy-timeout: 2000 + responses: + '200': + description: OK + content: + application/json: + schema: + type: object + properties: + id: + type: string` + + genYaml := `java: + groupId: com.example + artifactId: timeouts + asyncMode: disabled + generateSpringBootStarter: false + enforceOperationTimeout: false +` + + expectedSnapshotFiles := []string{ + "src/main/java/org/openapis/openapi/operations/ListThings.java", + } + + expectedSnapshot := `--- src/main/java/org/openapis/openapi/operations/ListThings.java --- +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + * Generated under the AGPL-3.0-only license. + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.openapis.openapi.operations; + +import static org.openapis.openapi.operations.Operations.RequestlessOperation; +import static org.openapis.openapi.utils.Exceptions.unchecked; + +import com.fasterxml.jackson.core.type.TypeReference; +import jakarta.annotation.Nonnull; +import jakarta.annotation.Nullable; +import java.io.InputStream; +import java.lang.Exception; +import java.lang.String; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.List; +import java.util.Optional; +import org.openapis.openapi.SDKConfiguration; +import org.openapis.openapi.SecuritySource; +import org.openapis.openapi.models.errors.APIException; +import org.openapis.openapi.models.operations.ListThingsResponse; +import org.openapis.openapi.models.operations.ListThingsResponseBody; +import org.openapis.openapi.utils.HTTPClient; +import org.openapis.openapi.utils.HTTPRequest; +import org.openapis.openapi.utils.Headers; +import org.openapis.openapi.utils.Hook.AfterErrorContextImpl; +import org.openapis.openapi.utils.Hook.AfterSuccessContextImpl; +import org.openapis.openapi.utils.Hook.BeforeRequestContextImpl; +import org.openapis.openapi.utils.Options; +import org.openapis.openapi.utils.Utils; + + +public class ListThings { + + static abstract class Base { + final SDKConfiguration sdkConfiguration; + final String baseUrl; + final SecuritySource securitySource; + final Optional timeout; + final HTTPClient client; + final Headers _headers; + + public Base( + @Nonnull SDKConfiguration sdkConfiguration, @Nullable Options options, + Headers _headers) { + this.sdkConfiguration = sdkConfiguration; + this._headers =_headers; + this.baseUrl = this.sdkConfiguration.serverUrl(); + this.securitySource = null; + Optional.ofNullable(options) + .ifPresent(o -> o.validate(List.of(Options.Option.TIMEOUT))); + this.timeout = Optional.ofNullable(options).flatMap(Options::timeout).or(sdkConfiguration::timeout); + this.client = this.sdkConfiguration.client(); + } + + Optional securitySource() { + return Optional.ofNullable(this.securitySource); + } + + BeforeRequestContextImpl createBeforeRequestContext() { + return new BeforeRequestContextImpl( + this.sdkConfiguration, + this.baseUrl, + "listThings", + java.util.Optional.empty(), + securitySource()); + } + + AfterSuccessContextImpl createAfterSuccessContext() { + return new AfterSuccessContextImpl( + this.sdkConfiguration, + this.baseUrl, + "listThings", + java.util.Optional.empty(), + securitySource()); + } + + AfterErrorContextImpl createAfterErrorContext() { + return new AfterErrorContextImpl( + this.sdkConfiguration, + this.baseUrl, + "listThings", + java.util.Optional.empty(), + securitySource()); + } + HttpRequest buildRequest() throws Exception { + String url = Utils.generateURL( + this.baseUrl, + "/things"); + HTTPRequest req = new HTTPRequest(url, "GET") + .timeout(this.timeout); + req.addHeader("Accept", "application/json") + .addHeader("user-agent", SDKConfiguration.USER_AGENT); + _headers.forEach((k, list) -> list.forEach(v -> req.addHeader(k, v))); + + return req.build(); + } + } + + public static class Sync extends Base + implements RequestlessOperation { + public Sync(@Nonnull SDKConfiguration sdkConfiguration, Headers _headers) { + this(sdkConfiguration, null, + _headers); + } + + public Sync( + @Nonnull SDKConfiguration sdkConfiguration, @Nullable Options options, + Headers _headers) { + super( + sdkConfiguration, options, + _headers); + } + + private HttpRequest onBuildRequest() throws Exception { + HttpRequest req = buildRequest(); + return sdkConfiguration.hooks().beforeRequest(createBeforeRequestContext(), req); + } + + private HttpResponse onError(HttpResponse response, Exception error) throws Exception { + return sdkConfiguration.hooks().afterError( + createAfterErrorContext(), + Optional.ofNullable(response), + Optional.ofNullable(error)); + } + + private HttpResponse onSuccess(HttpResponse response) throws Exception { + return sdkConfiguration.hooks().afterSuccess(createAfterSuccessContext(), response); + } + + @Override + public HttpResponse doRequest() { + HttpRequest r = unchecked(() -> onBuildRequest()).get(); + HttpResponse httpRes; + try { + httpRes = client.send(r); + if (Utils.statusCodeMatches(httpRes.statusCode(), "4XX", "5XX")) { + httpRes = onError(httpRes, null); + } else { + httpRes = onSuccess(httpRes); + } + } catch (Exception e) { + httpRes = unchecked(() -> onError(null, e)).get(); + } + + return httpRes; + } + + + @Override + public ListThingsResponse handleResponse(HttpResponse response) { + String contentType = response + .headers() + .firstValue("Content-Type") + .orElse("application/octet-stream"); + ListThingsResponse.Builder resBuilder = + ListThingsResponse + .builder() + .contentType(contentType) + .statusCode(response.statusCode()) + .rawResponse(response); + + ListThingsResponse res = resBuilder.build(); + + if (Utils.statusCodeMatches(response.statusCode(), "200")) { + if (Utils.contentTypeMatches(contentType, "application/json")) { + return res.withObject(Utils.unmarshal(response, new TypeReference() {})); + } else { + throw APIException.from("Unexpected content-type received: " + contentType, response); + } + } + if (Utils.statusCodeMatches(response.statusCode(), "4XX")) { + // no content + throw APIException.from("API error occurred", response); + } + if (Utils.statusCodeMatches(response.statusCode(), "5XX")) { + // no content + throw APIException.from("API error occurred", response); + } + throw APIException.from("Unexpected status code received: " + response.statusCode(), response); + } + } +} + + +` // end of snapshot + + snaptest.DoTestSnapshot(t, snaptest.Options{ + Spec: spec, + GenYaml: genYaml, + IncludeGlobs: expectedSnapshotFiles, + Expected: expectedSnapshot, + }) +} diff --git a/services/speakeasy-api-test-service/internal/eventstreams/service.go b/services/speakeasy-api-test-service/internal/eventstreams/service.go index 835b05932..430d6d48f 100644 --- a/services/speakeasy-api-test-service/internal/eventstreams/service.go +++ b/services/speakeasy-api-test-service/internal/eventstreams/service.go @@ -30,6 +30,10 @@ func pushChunks(rw http.ResponseWriter, chunks []string) { } func pushEvents(rw http.ResponseWriter, events [][]string) { + pushEventsEvery(rw, events, 100*time.Millisecond) +} + +func pushEventsEvery(rw http.ResponseWriter, events [][]string, interval time.Duration) { for _, event := range events { for _, line := range event { fmt.Fprintln(rw, line) @@ -40,14 +44,22 @@ func pushEvents(rw http.ResponseWriter, events [][]string) { f.Flush() } - time.Sleep(100 * time.Millisecond) + time.Sleep(interval) } } -func HandleEventStreamJSON(rw http.ResponseWriter, _ *http.Request) { +// HandleEventStreamJSON streams four JSON events 100ms apart. An +// event-interval-ms request header widens the spacing so a stream can outlast +// a client timeout by a wide margin. +func HandleEventStreamJSON(rw http.ResponseWriter, r *http.Request) { rw.Header().Add("Content-Type", "text/event-stream") - pushEvents(rw, [][]string{ + interval := 100 * time.Millisecond + if ms, err := strconv.Atoi(r.Header.Get("event-interval-ms")); err == nil && ms > 0 && ms <= 5000 { + interval = time.Duration(ms) * time.Millisecond + } + + pushEventsEvery(rw, [][]string{ { `data: {"content": "Hello"}`, }, @@ -63,7 +75,7 @@ func HandleEventStreamJSON(rw http.ResponseWriter, _ *http.Request) { { `data: {"content": "!"}`, }, - }) + }, interval) } // HandleEventStreamMalformed emits a well-formed frame followed by a frame diff --git a/templates/perms.go b/templates/perms.go index 6bff49c30..8e9253e60 100644 --- a/templates/perms.go +++ b/templates/perms.go @@ -1021,6 +1021,7 @@ var fileMode = map[string]fs.FileMode{ "templates/javav2/tests/primary/ServerAdditionalTest.java": 0o644, "templates/javav2/tests/primary/StreamingParserAdditionalTest.java": 0o644, "templates/javav2/tests/primary/TelemetryAdditionalTest.java": 0o644, + "templates/javav2/tests/primary/TimeoutAdditionalTest.java": 0o644, "templates/javav2/tests/primary/TransportClientAdditionalTest.java": 0o644, "templates/javav2/tests/primary/UnionsAdditionalTest.java": 0o644, "templates/javav2/tests/primary/Utf8UrlEncoderTest.java": 0o644, @@ -1045,6 +1046,7 @@ var fileMode = map[string]fs.FileMode{ "templates/javav2/tests/secondary/PaginationAdditionalTest.java": 0o644, "templates/javav2/tests/secondary/ResponseBodiesAdditionalTest.java": 0o644, "templates/javav2/tests/secondary/RetriesAdditionalTest.java": 0o644, + "templates/javav2/tests/secondary/TimeoutAdditionalTest.java": 0o644, "templates/javav2/tests/secondary/TransportClientAdditionalTest.java": 0o644, "templates/javav2/tests/secondary/TransportTypesTest.java": 0o644, "templates/javav2/tests/security-options": 0o20000000755, diff --git a/templates/templates/common/common/typeDefs.d.ts b/templates/templates/common/common/typeDefs.d.ts index bed91826d..2b77cb229 100644 --- a/templates/templates/common/common/typeDefs.d.ts +++ b/templates/templates/common/common/typeDefs.d.ts @@ -1987,6 +1987,12 @@ declare global { */ All: Record; + /** + * x-speakeasy-timeout: default request timeout for the operation, in + * milliseconds. + */ + Timeout?: number; + /** * x-speakeasy-exports entries declared on the operation; these alias the * operation's generated request type. diff --git a/templates/templates/javav2/async-method.java.stmpl b/templates/templates/javav2/async-method.java.stmpl index 8fde12716..b216a8599 100644 --- a/templates/templates/javav2/async-method.java.stmpl +++ b/templates/templates/javav2/async-method.java.stmpl @@ -34,6 +34,18 @@ {{- templateMethodCallArgs (collectRequiredArgs $signatureParameters $op) false 16 3}}); } {{- end}} + {{- $withoutOptions := withoutOptionsParam $signatureParameters}} + {{- if and (ne (len $withoutOptions) (len $signatureParameters)) (ne (len $withoutOptions) (len $requiredParameters)) (gt (len $withoutOptions) 0)}} + {{- "\n"}} +{{templateCommentsForOperation $op "Makes an async request" $withoutOptions (print $asyncResponseType " - The async response")}} + {{- if and ($op.Comments) ($op.Comments.Deprecated)}} + {{templateDeprecatedAnnotation $op}} + {{- end}} + public {{$asyncResponseType}} {{$methodName}}({{templateMethodParams $withoutOptions false 12 2}}) { + return {{$methodName}}( + {{- templateMethodCallArgs (legacyOverloadArgs $signatureParameters) false 16 3}}); + } + {{- end}} {{- "\n"}} {{- if (isStreamingOperation $op)}} diff --git a/templates/templates/javav2/auxiliary/src/main/java/{{templateAuxPath .}}/utils/AsyncRetries.java.stmpl b/templates/templates/javav2/auxiliary/src/main/java/{{templateAuxPath .}}/utils/AsyncRetries.java.stmpl index 7dd0671d2..a7e50f4cf 100644 --- a/templates/templates/javav2/auxiliary/src/main/java/{{templateAuxPath .}}/utils/AsyncRetries.java.stmpl +++ b/templates/templates/javav2/auxiliary/src/main/java/{{templateAuxPath .}}/utils/AsyncRetries.java.stmpl @@ -12,6 +12,9 @@ import java.io.InterruptedIOException; import java.net.ConnectException; {{- if $okHttp}} import java.net.SocketTimeoutException; +{{- else}} +import java.net.http.HttpConnectTimeoutException; +import java.net.http.HttpTimeoutException; {{- end}} import {{javaHttpResponseFqn}}; import java.time.Duration; @@ -140,6 +143,8 @@ public class AsyncRetries { return (isConnectTimeout(e) && backoff.retryConnectError()) || (isReadTimeout(e) && backoff.retryReadTimeoutError()); {{- else}} + if (e instanceof HttpConnectTimeoutException && backoff.retryConnectError()) return true; + if (e instanceof HttpTimeoutException && !(e instanceof HttpConnectTimeoutException) && backoff.retryReadTimeoutError()) return true; String message = e.getMessage(); if (message == null) return false; return (message.contains("Connect timed out") && backoff.retryConnectError()) @@ -393,6 +398,9 @@ import java.io.InterruptedIOException; import java.net.ConnectException; {{- if $okHttp}} import java.net.SocketTimeoutException; +{{- else}} +import java.net.http.HttpConnectTimeoutException; +import java.net.http.HttpTimeoutException; {{- end}} import {{javaHttpResponseFqn}}; import java.time.Duration; @@ -488,6 +496,8 @@ public class AsyncRetries { return (isConnectTimeout(e) && backoff.retryConnectError()) || (isReadTimeout(e) && backoff.retryReadTimeoutError()); {{- else}} + if (e instanceof HttpConnectTimeoutException && backoff.retryConnectError()) return true; + if (e instanceof HttpTimeoutException && !(e instanceof HttpConnectTimeoutException) && backoff.retryReadTimeoutError()) return true; String message = e.getMessage(); if (message == null) return false; return (message.contains("Connect timed out") && backoff.retryConnectError()) diff --git a/templates/templates/javav2/auxiliary/src/main/java/{{templateAuxPath .}}/utils/HTTPRequest.java.stmpl b/templates/templates/javav2/auxiliary/src/main/java/{{templateAuxPath .}}/utils/HTTPRequest.java.stmpl index 3120a5ff6..8738ba3ab 100644 --- a/templates/templates/javav2/auxiliary/src/main/java/{{templateAuxPath .}}/utils/HTTPRequest.java.stmpl +++ b/templates/templates/javav2/auxiliary/src/main/java/{{templateAuxPath .}}/utils/HTTPRequest.java.stmpl @@ -16,6 +16,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.time.Duration; public class HTTPRequest { @@ -28,6 +29,7 @@ public class HTTPRequest { private final List queryParams = new ArrayList<>(); private final Map> headers = new HashMap<>(); private Optional body = Optional.empty(); // mutable + private Optional timeout = Optional.empty(); public HTTPRequest(String baseURL, String method) { Utils.checkNotNull(baseURL, "baseURL"); @@ -40,6 +42,12 @@ public class HTTPRequest { Utils.checkNotNull(body, "body"); this.body = body; } + + public HTTPRequest timeout(Optional timeout) { + Utils.checkNotNull(timeout, "timeout"); + this.timeout = timeout; + return this; + } public HTTPRequest addHeader(String key, String value) { List headerValues = headers.get(key); @@ -104,6 +112,7 @@ public class HTTPRequest { } {{- end}} headers.forEach((k, list) -> list.forEach(v -> requestBuilder.header(k, v))); + timeout.ifPresent(requestBuilder::timeout); return requestBuilder.build(); } diff --git a/templates/templates/javav2/auxiliary/src/main/java/{{templateAuxPath .}}/utils/Options.java.stmpl b/templates/templates/javav2/auxiliary/src/main/java/{{templateAuxPath .}}/utils/Options.java.stmpl index 9712b9103..0faa6d966 100644 --- a/templates/templates/javav2/auxiliary/src/main/java/{{templateAuxPath .}}/utils/Options.java.stmpl +++ b/templates/templates/javav2/auxiliary/src/main/java/{{templateAuxPath .}}/utils/Options.java.stmpl @@ -1,29 +1,41 @@ package {{templatePackageName}}.utils; +import java.time.Duration; import java.util.Optional; import java.util.List; public class Options { public enum Option { - RETRY_CONFIG; + RETRY_CONFIG, + TIMEOUT; } - private Optional retryConfig = Optional.empty(); + private final Optional retryConfig; + private final Optional timeout; - private Options(Optional retryConfig) { + private Options(Optional retryConfig, Optional timeout) { Utils.checkNotNull(retryConfig, "retryConfig"); + Utils.checkNotNull(timeout, "timeout"); this.retryConfig = retryConfig; + this.timeout = timeout; } public Optional retryConfig() { return retryConfig; } + public Optional timeout() { + return timeout; + } + public final void validate(List