diff --git a/README.md b/README.md index e140529bd..411db9088 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,14 @@ With the SDK you can: * Test your workflow definitions using the reference implementation. +## Three ways to use the SDK + +- Use the generated Java models to read and write specification documents in your own implementation. +- Run workflows with the customizable reference engine, standalone or embedded in an application. +- Reuse execution components from `common/` in another workflow engine, without creating SDK workflow contexts. For example, use `openworkflow-common-openapi` to bind an operation and prepare its request, then send it with `openworkflow-common-http` (JDK) or `openworkflow-common-http-jakarta`. + +Common OpenAPI consumers can supply a `UnifiedOpenAPIReader` of their own. To use the SDK's JSON/YAML Jackson reader, add `cloud.openworkflow.sdk:openworkflow-impl-openapi` at the same SDK version; this optional reader retains its SDK implementation dependencies. See the [HTTP example](common/http/README.md) and [OpenAPI example](common/openapi/README.md). Production dependencies point from the reference implementation to common components. gRPC reorganization is handled separately. + ## Status | Latest Releases | Conformance to spec version | @@ -122,7 +130,7 @@ try (InputStream in = new FileInputStream("simple.yaml")) { } ``` -For additional reading helper methods, including the one to read a workflow definition from classpath, check [WorkflowReader](api/src/main/java/org/openworkflow/sdk/api/WorkflowReader.java) class. +For additional reading helper methods, including the one to read a workflow definition from classpath, check [WorkflowReader](api/src/main/java/cloud/openworkflow/sdk/api/WorkflowReader.java) class. ### Writing workflow definition to a JSON/YAML target @@ -135,7 +143,7 @@ try (OutputStream out = new FileOutputStream("simple.json")) { } ``` -For additional writing helper methods, check [WorkflowWriter](api/src/main/java/org/openworkflow/sdk/api/WorkflowWriter.java) class. +For additional writing helper methods, check [WorkflowWriter](api/src/main/java/cloud/openworkflow/sdk/api/WorkflowWriter.java) class. #### Jackson dependency diff --git a/common/http-jakarta/pom.xml b/common/http-jakarta/pom.xml new file mode 100644 index 000000000..a2236c530 --- /dev/null +++ b/common/http-jakarta/pom.xml @@ -0,0 +1,45 @@ + + 4.0.0 + + cloud.openworkflow.sdk + openworkflow-common + 8.0.0-SNAPSHOT + + openworkflow-common-http-jakarta + Open Workflow :: HTTP Client :: Jakarta + + + cloud.openworkflow.sdk + openworkflow-common-http + + + jakarta.ws.rs + jakarta.ws.rs-api + + + org.glassfish.jersey.core + jersey-client + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.assertj + assertj-core + test + + + org.mockito + mockito-core + test + + + com.squareup.okhttp3 + mockwebserver + test + + + diff --git a/common/http-jakarta/src/main/java/cloud/openworkflow/sdk/http/jakarta/JakartaHttpResponse.java b/common/http-jakarta/src/main/java/cloud/openworkflow/sdk/http/jakarta/JakartaHttpResponse.java new file mode 100644 index 000000000..ce9b35ef0 --- /dev/null +++ b/common/http-jakarta/src/main/java/cloud/openworkflow/sdk/http/jakarta/JakartaHttpResponse.java @@ -0,0 +1,146 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.http.jakarta; + +import cloud.openworkflow.sdk.http.*; +import jakarta.ws.rs.core.Response; +import java.util.*; + +/** + * Buffered native entity supports both provider conversion and original raw bytes. Caller closes. + */ +public class JakartaHttpResponse implements HttpResponse { + private final Response response; + private final HttpBodyConverter converter; + + public JakartaHttpResponse(Response response, HttpBodyConverter converter) { + this.response = Objects.requireNonNull(response); + this.converter = Objects.requireNonNull(converter); + try { + if (response.hasEntity() && !response.bufferEntity()) + throw new IllegalStateException( + "Native entity cannot be buffered for repeatable raw access"); + } catch (RuntimeException | Error e) { + closeAfterFailure(e); + throw e; + } + } + + public int status() { + return response.getStatus(); + } + + public byte[] body() { + return response.hasEntity() ? response.readEntity(byte[].class).clone() : new byte[0]; + } + + public Map> headers() { + return response.getHeaders(); + } + + @Override + public Map> stringHeaders() { + return new HttpResponseData(status(), response.getStringHeaders(), new byte[0]).headers(); + } + + @Override + public String firstHeader(String name) { + var values = response.getStringHeaders().get(name); + return values == null || values.isEmpty() ? null : values.getFirst(); + } + + @Override + public String getHeader(String name) { + return response.getHeaderString(name); + } + + @Override + public byte[] contentAsByteArray() { + return response.hasEntity() ? response.readEntity(byte[].class) : new byte[0]; + } + + @Override + public OptionalLong lastModified() { + var date = response.getLastModified(); + return date == null ? OptionalLong.empty() : OptionalLong.of(date.getTime()); + } + + @Override + public String reasonPhrase() { + return response.getStatusInfo().getReasonPhrase(); + } + + @Override + public String errorDetails() { + try { + return response.readEntity(String.class); + } catch (jakarta.ws.rs.ProcessingException ex) { + return ex.getMessage(); + } + } + + public Optional nativeResponse(Class type) { + return type.isInstance(response) ? Optional.of(type.cast(response)) : Optional.empty(); + } + + public Optional getBodyAsObject(Class type) { + try { + return converter.convert(this, type); + } catch (RuntimeException | Error e) { + closeAfterFailure(e); + throw e; + } + } + + private void closeAfterFailure(Throwable error) { + try { + response.close(); + } catch (RuntimeException | Error cleanup) { + if (cleanup != error) error.addSuppressed(cleanup); + } + } + + public void close() { + response.close(); + } + + @Override + public byte[] responseAsByteArray() { + // Preserve the SDK's existing raw formatter heuristic; this is not protocol metadata. + return HttpResponses.responseAsByteArray(this, legacyHttp2RawFormat()); + } + + private static final Collection FORBIDDEN_HTTP2_HEADERS_LOWERCASE = + Arrays.asList("connection", "keep-alive", "proxy-connection", "transfer-encoding", "upgrade"); + + private boolean legacyHttp2RawFormat() { + for (String str : response.getHeaders().keySet()) { + if (containsUpperCase(str) || FORBIDDEN_HTTP2_HEADERS_LOWERCASE.contains(str.toLowerCase())) { + return false; + } + } + return true; + } + + private boolean containsUpperCase(String str) { + for (int i = 0; i < str.length(); i++) { + if (Character.isUpperCase(str.charAt(i))) { + return true; + } + } + return false; + } +} diff --git a/common/http-jakarta/src/main/java/cloud/openworkflow/sdk/http/jakarta/JakartaHttpTransport.java b/common/http-jakarta/src/main/java/cloud/openworkflow/sdk/http/jakarta/JakartaHttpTransport.java new file mode 100644 index 000000000..f9ec39c68 --- /dev/null +++ b/common/http-jakarta/src/main/java/cloud/openworkflow/sdk/http/jakarta/JakartaHttpTransport.java @@ -0,0 +1,182 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.http.jakarta; + +import cloud.openworkflow.sdk.http.HttpTransport; +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.ClientBuilder; +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.client.WebTarget; +import jakarta.ws.rs.core.Response; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.function.Function; + +/** + * Jakarta transport. Redirect, connect timeout and read timeout settings belong to the Jakarta + * client and its provider. The default constructor uses the provider's defaults. A provider is + * required at runtime; this module does not select one for the application. Effective request + * metadata is unavailable: Jakarta REST does not portably expose the final request after + * connector-managed redirects, so buffered responses leave request() empty. + */ +public final class JakartaHttpTransport implements HttpTransport { + + private final Client client; + private final boolean ownsClient; + private final cloud.openworkflow.sdk.http.HttpBodyConverter converter; + private final Executor executor; + private final ExecutorService ownedExecutor; + + /** Creates a client and cached-thread executor owned by this transport. */ + public JakartaHttpTransport() { + this.converter = cloud.openworkflow.sdk.http.HttpBodyConverter.BYTES; + this.ownedExecutor = Executors.newCachedThreadPool(); + this.executor = ownedExecutor; + try { + this.client = ClientBuilder.newBuilder().executorService(ownedExecutor).build(); + } catch (RuntimeException | Error failure) { + ownedExecutor.shutdown(); + throw failure; + } + this.ownsClient = true; + } + + /** Borrows a client and owns a cached-thread executor for response buffering. */ + public JakartaHttpTransport(Client client) { + this(client, cloud.openworkflow.sdk.http.HttpBodyConverter.BYTES); + } + + /** Borrows a client and converter; owns a cached-thread executor for response buffering. */ + public JakartaHttpTransport( + Client client, cloud.openworkflow.sdk.http.HttpBodyConverter converter) { + this.converter = Objects.requireNonNull(converter); + this.client = Objects.requireNonNull(client, "client"); + this.ownsClient = false; + this.ownedExecutor = Executors.newCachedThreadPool(); + this.executor = ownedExecutor; + } + + /** + * Borrows all arguments. The executor must support blocking response reads. The caller configures + * the client's own executor separately and remains responsible for closing both resources. + * Submitted tasks must run or be rejected by throwing; accepted tasks must finish before executor + * shutdown. Silent discard policies and removal of queued tasks cannot guarantee response + * cleanup. + */ + public JakartaHttpTransport( + Client client, cloud.openworkflow.sdk.http.HttpBodyConverter converter, Executor executor) { + this.converter = Objects.requireNonNull(converter); + this.client = Objects.requireNonNull(client, "client"); + this.executor = Objects.requireNonNull(executor, "executor"); + this.ownsClient = false; + this.ownedExecutor = null; + } + + @Override + public CompletableFuture execute( + cloud.openworkflow.sdk.http.HttpRequestInfo request) { + CompletableFuture result = new CompletableFuture<>(); + exchange( + request, + builder -> { + String contentType = request.contentType(); + byte[] supplied = request.body(); + byte[] body = supplied == null ? null : supplied.clone(); + return CompletableFuture.completedFuture( + body == null ? null : Entity.entity(body, contentType.toString())); + }) + .whenComplete((response, error) -> { + if (error != null) { + result.completeExceptionally(error); + } else { + try { + CompletableFuture.runAsync( + () -> { + if (result.isDone()) { + response.close(); + } else { + try { + var owned = new JakartaHttpResponse(response, converter); + if (!result.complete(owned)) owned.close(); + } catch (Exception | Error ex) { + result.completeExceptionally(ex); + } + } + }, + executor) + .whenComplete((ignored, callbackError) -> { + if (callbackError != null) result.completeExceptionally(callbackError); + }); + } catch (RuntimeException | Error schedulingError) { + try { + response.close(); + } catch (RuntimeException | Error closeError) { + if (closeError != schedulingError) schedulingError.addSuppressed(closeError); + } + result.completeExceptionally(schedulingError); + } + } + }); + return result; + } + + /** + * Prepares a native request asynchronously and supplies its entity (null means no entity). The + * request's byte body is ignored by this overload, allowing existing entity converters and + * request decorators to participate. The recipient owns and must close the returned Response. + * Cancelling delivery does not cancel the network call; a response arriving after cancellation is + * closed here. + */ + public CompletableFuture exchange( + cloud.openworkflow.sdk.http.HttpRequestInfo request, + Function>> prepare) { + CompletableFuture result = new CompletableFuture<>(); + WebTarget target = client.target(request.uri()); + for (var entry : request.queryParams().entrySet()) { + target = target.queryParam(entry.getKey(), entry.getValue()); + } + Invocation.Builder builder = target.request(); + request.effectiveHeaders().forEach(builder::header); + prepare + .apply(builder) + .thenCompose(entity -> + entity == null + ? builder.rx().method(request.method()) + : builder.rx().method(request.method(), entity)) + .whenComplete((response, error) -> { + if (error != null) { + result.completeExceptionally(error); + } else if (!result.complete(response)) { + response.close(); + } + }); + return result; + } + + @Override + public void close() { + try { + if (ownsClient) client.close(); + } finally { + if (ownedExecutor != null) ownedExecutor.shutdown(); + } + } +} diff --git a/common/http-jakarta/src/test/java/cloud/openworkflow/sdk/http/jakarta/HttpConversionTest.java b/common/http-jakarta/src/test/java/cloud/openworkflow/sdk/http/jakarta/HttpConversionTest.java new file mode 100644 index 000000000..c1fdf4a5c --- /dev/null +++ b/common/http-jakarta/src/test/java/cloud/openworkflow/sdk/http/jakarta/HttpConversionTest.java @@ -0,0 +1,237 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.http.jakarta; + +import static org.assertj.core.api.Assertions.*; +import static org.mockito.Mockito.*; + +import cloud.openworkflow.sdk.http.*; +import jakarta.ws.rs.core.Response; +import java.util.*; +import org.junit.jupiter.api.Test; + +class HttpConversionTest { + record ConsumerJson(String value) {} + + private Response nativeResponse() { + Response response = mock(Response.class); + when(response.hasEntity()).thenReturn(true); + when(response.bufferEntity()).thenReturn(true); + return response; + } + + @Test + void retainsRepeatedRawRequestHeadersEvenWithConditionalDate() throws Exception { + try (var server = new mockwebserver3.MockWebServer(); + var transport = new JakartaHttpTransport()) { + server.start(); + server.enqueue(new mockwebserver3.MockResponse.Builder().build()); + Map headers = new LinkedHashMap<>(); + headers.put("X-Repeated", "one"); + headers.put("x-repeated", "two"); + headers.put("If-Modified-Since", "discarded"); + var request = + new HttpRequestInfo( + server.url("/").uri(), + "GET", + false, + headers, + Map.of(), + null, + "Sun, 06 Nov 1994 08:49:37 GMT"); + try (var response = + transport.execute(request).get(5, java.util.concurrent.TimeUnit.SECONDS)) { + var sent = server.takeRequest(5, java.util.concurrent.TimeUnit.SECONDS); + assertThat(String.join(",", sent.getHeaders().values("X-Repeated")).replace(" ", "")) + .isEqualTo("one,two"); + assertThat(sent.getHeaders().values("If-Modified-Since")) + .isEqualTo(List.of("Sun, 06 Nov 1994 08:49:37 GMT")); + } + } + } + + @Test + void sendsConditionalDateFromTheSharedBuilderExactlyOnce() throws Exception { + try (var server = new mockwebserver3.MockWebServer(); + var transport = new JakartaHttpTransport()) { + server.start(); + server.enqueue(new mockwebserver3.MockResponse.Builder().build()); + var request = + cloud.openworkflow.sdk.http.HttpRequestInfo.builder("GET") + .ifModifiedSince(784111777000L) + .build(server.url("/").uri()); + try (var response = + transport.execute(request).get(5, java.util.concurrent.TimeUnit.SECONDS)) { + var headers = + server + .takeRequest(5, java.util.concurrent.TimeUnit.SECONDS) + .getHeaders() + .values("If-Modified-Since"); + assertThat(headers).isEqualTo(java.util.List.of("Sun, 06 Nov 1994 08:49:37 GMT")); + } + } + } + + @Test + void dedicatedConditionalDateOverridesTheHeaderMap() throws Exception { + try (var server = new mockwebserver3.MockWebServer(); + var transport = new JakartaHttpTransport()) { + server.start(); + server.enqueue(new mockwebserver3.MockResponse.Builder().build()); + var request = + cloud.openworkflow.sdk.http.HttpRequestInfo.builder("GET") + .headers(java.util.Map.of("if-modified-since", "discarded")) + .ifModifiedSince(784111777000L) + .build(server.url("/").uri()); + try (var response = + transport.execute(request).get(5, java.util.concurrent.TimeUnit.SECONDS)) { + var headers = + server + .takeRequest(5, java.util.concurrent.TimeUnit.SECONDS) + .getHeaders() + .values("If-Modified-Since"); + assertThat(headers).isEqualTo(java.util.List.of("Sun, 06 Nov 1994 08:49:37 GMT")); + } + } + } + + @Test + void providerConversionAndRawAccessUseTheSameRealEntity() throws Exception { + try (var server = new mockwebserver3.MockWebServer(); + var client = jakarta.ws.rs.client.ClientBuilder.newClient()) { + server.start(); + String json = "{ \"name\" : \"native\" }\n"; + server.enqueue( + new mockwebserver3.MockResponse.Builder() + .addHeader("Content-Type", "application/json") + .body(json) + .build()); + HttpBodyConverter converter = + new HttpBodyConverter() { + public Optional convert(HttpResponse source, Class type) { + return type == ConsumerJson.class + ? Optional.of( + type.cast( + new ConsumerJson( + source + .nativeResponse(Response.class) + .orElseThrow() + .readEntity(String.class)))) + : Optional.empty(); + } + }; + try (HttpTransport transport = new JakartaHttpTransport(client, converter); + HttpResponse response = + transport + .execute( + new HttpRequestInfo( + server.url("/").uri(), "GET", Map.of(), Map.of(), null)) + .get(5, java.util.concurrent.TimeUnit.SECONDS)) { + assertThat(response.getBodyAsObject(ConsumerJson.class).orElseThrow().value()) + .isEqualTo(json); + assertThat(response.body()) + .isEqualTo(json.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + assertThat(response.getBodyAsObject(ConsumerJson.class).orElseThrow().value()) + .isEqualTo(json); + } + } + } + + @Test + void failedBufferingOrConversionKeepsThePrimaryFailure() { + for (boolean fatal : new boolean[] {false, true}) { + for (boolean buffering : new boolean[] {false, true}) { + var nativeResponse = nativeResponse(); + Throwable failure = + fatal ? new AssertionError("primary") : new IllegalStateException("primary"); + var cleanup = new jakarta.ws.rs.ProcessingException("cleanup"); + doThrow(cleanup).when(nativeResponse).close(); + if (buffering) when(nativeResponse.bufferEntity()).thenThrow(failure); + HttpBodyConverter converter = + new HttpBodyConverter() { + public Optional convert(HttpResponse response, Class type) { + if (failure instanceof Error error) throw error; + throw (RuntimeException) failure; + } + }; + var caught = + catchThrowableOfType( + Throwable.class, + () -> { + var response = new JakartaHttpResponse(nativeResponse, converter); + response.getBodyAsObject(ConsumerJson.class); + }); + assertThat(caught).isSameAs(failure); + assertThat(caught.getSuppressed()).isEqualTo(new Throwable[] {cleanup}); + } + } + } + + @Test + void rejectsAnUnbufferableEntityAndClosesIt() { + var response = nativeResponse(); + when(response.bufferEntity()).thenReturn(false); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(() -> new JakartaHttpResponse(response, HttpBodyConverter.BYTES)); + verify(response).close(); + } + + @Test + void convertsThroughTheProviderAndClosesAfterRawAccess() { + Response nativeResponse = nativeResponse(); + ConsumerJson json = new ConsumerJson("value"); + when(nativeResponse.readEntity(ConsumerJson.class)).thenReturn(json); + when(nativeResponse.readEntity(byte[].class)).thenReturn(new byte[] {1, 2}); + HttpBodyConverter converter = + new HttpBodyConverter() { + public Optional convert(HttpResponse source, Class type) { + return Optional.of( + source.nativeResponse(Response.class).orElseThrow().readEntity(type)); + } + }; + try (HttpResponse response = new JakartaHttpResponse(nativeResponse, converter)) { + assertThat(response.getBodyAsObject(ConsumerJson.class).orElseThrow()).isSameAs(json); + assertThat(response.body()).isEqualTo(new byte[] {1, 2}); + verify(nativeResponse, never()).close(); + assertThat(response.request().isEmpty()).isTrue(); + } + verify(nativeResponse).close(); + } + + @Test + void closesOnConverterFailure() { + Response nativeResponse = nativeResponse(); + HttpBodyConverter converter = + new HttpBodyConverter() { + public Optional convert(HttpResponse source, Class type) { + throw new IllegalArgumentException("conversion"); + } + }; + var response = new JakartaHttpResponse(nativeResponse, converter); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> response.getBodyAsObject(ConsumerJson.class)); + verify(nativeResponse).close(); + } + + @Test + void closesWhenBufferingFailsBeforeDelivery() { + Response response = nativeResponse(); + when(response.bufferEntity()).thenThrow(new IllegalStateException("buffer")); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(() -> new JakartaHttpResponse(response, HttpBodyConverter.BYTES)); + verify(response).close(); + } +} diff --git a/common/http-jakarta/src/test/java/cloud/openworkflow/sdk/http/jakarta/JakartaHttpTransportTest.java b/common/http-jakarta/src/test/java/cloud/openworkflow/sdk/http/jakarta/JakartaHttpTransportTest.java new file mode 100644 index 000000000..aa2ae0f13 --- /dev/null +++ b/common/http-jakarta/src/test/java/cloud/openworkflow/sdk/http/jakarta/JakartaHttpTransportTest.java @@ -0,0 +1,559 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.http.jakarta; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import cloud.openworkflow.sdk.http.HttpBodyConverter; +import cloud.openworkflow.sdk.http.HttpRequestInfo; +import com.sun.net.httpserver.HttpServer; +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.ClientBuilder; +import jakarta.ws.rs.client.CompletionStageRxInvoker; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.client.WebTarget; +import jakarta.ws.rs.core.Response; +import java.net.InetSocketAddress; +import java.net.SocketTimeoutException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.ForkJoinTask; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import org.junit.jupiter.api.Test; + +class JakartaHttpTransportTest { + private static Client clientReturning(CompletableFuture network) { + Client client = mock(Client.class); + WebTarget target = mock(WebTarget.class); + Invocation.Builder builder = mock(Invocation.Builder.class); + CompletionStageRxInvoker invoker = mock(CompletionStageRxInvoker.class); + when(client.target(any(URI.class))).thenReturn(target); + when(target.request()).thenReturn(builder); + when(builder.rx()).thenReturn(invoker); + when(invoker.method(anyString())).thenReturn(network); + return client; + } + + @Test + void stalledBodyDoesNotPreventAnotherLocalResponseFromBeingDelivered() throws Exception { + var server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + CountDownLatch stalledHeaders = new CountDownLatch(1); + CountDownLatch releaseBody = new CountDownLatch(1); + try (var serverExecutor = Executors.newCachedThreadPool(); + var transport = new JakartaHttpTransport()) { + server.setExecutor(serverExecutor); + server.createContext( + "/stalled", + exchange -> { + try (exchange) { + exchange.sendResponseHeaders(200, 1); + exchange.getResponseBody().flush(); + stalledHeaders.countDown(); + try { + if (!releaseBody.await(5, TimeUnit.SECONDS)) + throw new java.io.IOException("No release"); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new java.io.IOException(e); + } + exchange.getResponseBody().write(42); + } + }); + server.createContext( + "/ready", + exchange -> { + try (exchange) { + exchange.sendResponseHeaders(200, 1); + exchange.getResponseBody().write(43); + } + }); + server.start(); + try { + var base = URI.create("http://127.0.0.1:" + server.getAddress().getPort()); + var stalled = + transport.execute( + new HttpRequestInfo( + base.resolve("/stalled"), "GET", Map.of(), Map.of(), null)); + assertThat(stalledHeaders.await(5, TimeUnit.SECONDS)).isTrue(); + try (var ready = + transport + .execute( + new HttpRequestInfo( + base.resolve("/ready"), "GET", Map.of(), Map.of(), null)) + .get(5, TimeUnit.SECONDS)) { + assertThat(ready.body()).containsExactly((byte) 43); + assertThat(stalled.isDone()).isFalse(); + } + releaseBody.countDown(); + try (var response = stalled.get(5, TimeUnit.SECONDS)) { + assertThat(response.body()).containsExactly((byte) 42); + } + } finally { + releaseBody.countDown(); + server.stop(0); + } + } + } + + @Test + void closesOnlyItsOwnExecutorWhenTheClientIsBorrowed() throws Exception { + Response response = mock(Response.class); + AtomicReference worker = new AtomicReference<>(); + when(response.hasEntity()) + .thenAnswer(ignored -> { + worker.set(Thread.currentThread()); + return false; + }); + Client client = clientReturning(CompletableFuture.completedFuture(response)); + try (var transport = new JakartaHttpTransport(client)) { + try (var owned = + transport + .execute( + new HttpRequestInfo( + URI.create("http://localhost/"), "GET", Map.of(), Map.of(), null)) + .get(5, TimeUnit.SECONDS)) { + assertThat(worker.get()).isNotNull(); + } + } + worker.get().join(5000); + assertThat(worker.get().isAlive()).isFalse(); + verify(client, org.mockito.Mockito.never()).close(); + verify(response).close(); + } + + @Test + void usesTheInjectedExecutorWithoutClosingItOrTheClient() throws Exception { + Response response = mock(Response.class); + AtomicReference worker = new AtomicReference<>(); + when(response.hasEntity()) + .thenAnswer(ignored -> { + worker.set(Thread.currentThread()); + return false; + }); + Client client = clientReturning(CompletableFuture.completedFuture(response)); + try (var executor = + Executors.newSingleThreadExecutor(r -> new Thread(r, "consumer-http-read"))) { + try (var transport = new JakartaHttpTransport(client, HttpBodyConverter.BYTES, executor); + var owned = + transport + .execute( + new HttpRequestInfo( + URI.create("http://localhost/"), "GET", Map.of(), Map.of(), null)) + .get(5, TimeUnit.SECONDS)) { + assertThat(worker.get().getName()).isEqualTo("consumer-http-read"); + } + assertThat(executor.submit(() -> 42).get(5, TimeUnit.SECONDS)).isEqualTo(42); + verify(client, org.mockito.Mockito.never()).close(); + } + verify(response).close(); + } + + @Test + void rejectedBufferingClosesTheResponseAndPreservesTheFailure() { + Response response = mock(Response.class); + var rejected = new RejectedExecutionException("executor stopped"); + var closeFailure = new IllegalStateException("provider close failure"); + org.mockito.Mockito.doThrow(closeFailure).when(response).close(); + Client client = clientReturning(CompletableFuture.completedFuture(response)); + try (var transport = + new JakartaHttpTransport( + client, + HttpBodyConverter.BYTES, + task -> { + throw rejected; + })) { + var result = + transport.execute( + new HttpRequestInfo( + URI.create("http://localhost/"), "GET", Map.of(), Map.of(), null)); + assertThatThrownBy(() -> result.get(5, TimeUnit.SECONDS)).hasCause(rejected); + assertThat(rejected.getSuppressed()).containsExactly(closeFailure); + verify(response).close(); + verify(response, org.mockito.Mockito.never()).bufferEntity(); + } + } + + @Test + void closesLateResponsesAfterItsExecutorIsShutDown() { + var network = new CompletableFuture(); + Response response = mock(Response.class); + try (var transport = new JakartaHttpTransport(clientReturning(network))) { + var result = + transport.execute( + new HttpRequestInfo( + URI.create("http://localhost/"), "GET", Map.of(), Map.of(), null)); + transport.close(); + network.complete(response); + assertThatThrownBy(() -> result.get(5, TimeUnit.SECONDS)) + .hasCauseInstanceOf(RejectedExecutionException.class); + verify(response).close(); + verify(response, org.mockito.Mockito.never()).bufferEntity(); + } + } + + private static int statusAndClose( + CompletableFuture future) throws Exception { + try (var response = future.get(5, TimeUnit.SECONDS)) { + return response.status(); + } + } + + private static final class BorrowedRequest + extends cloud.openworkflow.sdk.http.HttpRequestInfo { + private final byte[] borrowed; + + BorrowedRequest( + URI uri, + String method, + Map headers, + Map queryParams, + byte[] body) { + super(uri, method, headers, queryParams, body); + borrowed = body; + } + + @Override + public byte[] body() { + return borrowed; + } + } + + @Test + void snapshotsCustomRequestBytesBeforeTheProviderConsumesTheEntity() throws Exception { + Client client = mock(Client.class); + WebTarget target = mock(WebTarget.class); + Invocation.Builder builder = mock(Invocation.Builder.class); + CompletionStageRxInvoker invoker = mock(CompletionStageRxInvoker.class); + Response response = mock(Response.class); + var entity = new java.util.concurrent.atomic.AtomicReference>(); + var network = new CompletableFuture(); + when(client.target(any(URI.class))).thenReturn(target); + when(target.request()).thenReturn(builder); + when(builder.rx()).thenReturn(invoker); + when(invoker.method(anyString(), any(jakarta.ws.rs.client.Entity.class))) + .thenAnswer(call -> { + entity.set(call.getArgument(1)); + return network; + }); + byte[] bytes = {1, 2}; + try (var transport = new JakartaHttpTransport(client)) { + var future = + transport.execute( + new BorrowedRequest( + URI.create("https://example.test/"), "POST", Map.of(), Map.of(), bytes)); + bytes[0] = 9; + assertThat((byte[]) entity.get().getEntity()).containsExactly((byte) 1, (byte) 2); + network.complete(response); + try (var owned = future.get(5, TimeUnit.SECONDS)) { + assertThat(owned.request()).isEmpty(); + } + verify(response).close(); + } + } + + @Test + void execute_shouldPropagateBufferingErrorsAndCloseTheResponse() { + Client client = mock(Client.class); + WebTarget target = mock(WebTarget.class); + Invocation.Builder builder = mock(Invocation.Builder.class); + CompletionStageRxInvoker invoker = mock(CompletionStageRxInvoker.class); + Response response = mock(Response.class); + AssertionError failure = new AssertionError("provider buffering failure"); + when(client.target(any(URI.class))).thenReturn(target); + when(target.request()).thenReturn(builder); + when(builder.rx()).thenReturn(invoker); + when(invoker.method(anyString())).thenReturn(CompletableFuture.completedFuture(response)); + when(response.hasEntity()).thenThrow(failure); + try (var transport = new JakartaHttpTransport(client)) { + var result = + transport.execute( + new HttpRequestInfo( + URI.create("http://localhost/"), "GET", Map.of(), Map.of(), null)); + assertThatThrownBy(() -> result.get(5, TimeUnit.SECONDS)) + .isInstanceOf(java.util.concurrent.ExecutionException.class) + .hasCause(failure); + verify(response).close(); + } + } + + @Test + void execute_shouldNotClaimToKnowTheRequestAfterProviderRedirects() throws Exception { + try (MockWebServer server = new MockWebServer(); + JakartaHttpTransport transport = new JakartaHttpTransport()) { + server.start(); + server.enqueue( + new MockResponse.Builder() + .code(303) + .addHeader("Location", "/final?source=redirect") + .build()); + server.enqueue(new MockResponse.Builder().body("final response").build()); + try (var response = + transport + .execute( + new HttpRequestInfo( + server.url("/start").uri(), + "POST", + Map.of("X-Request", "sent"), + Map.of(), + "body".getBytes(StandardCharsets.UTF_8))) + .get(5, TimeUnit.SECONDS)) { + assertThat(response.status()).isEqualTo(200); + assertThat(response.request()).isEmpty(); + assertThat(server.takeRequest(5, TimeUnit.SECONDS).getMethod()).isEqualTo("POST"); + var redirected = server.takeRequest(5, TimeUnit.SECONDS); + assertThat(redirected.getMethod()).isEqualTo("GET"); + assertThat(redirected.getUrl().uri()).isEqualTo(server.url("/final?source=redirect").uri()); + } + } + } + + @Test + void exchange_shouldPreserveSynchronousPreparationErrors() { + try (JakartaHttpTransport transport = new JakartaHttpTransport()) { + IllegalArgumentException error = new IllegalArgumentException("invalid credentials"); + assertThatThrownBy(() -> + transport.exchange( + new HttpRequestInfo( + URI.create("http://localhost/"), "GET", Map.of(), Map.of(), null), + builder -> { + throw error; + })) + .isSameAs(error); + } + } + + @Test + void close_shouldCloseAnOwnedClient() { + JakartaHttpTransport transport = new JakartaHttpTransport(); + transport.close(); + assertThatThrownBy(() -> + transport + .execute( + new HttpRequestInfo( + URI.create("http://localhost/"), "GET", Map.of(), Map.of(), null)) + .get(5, TimeUnit.SECONDS)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void execute_shouldSendResolvedDataAndReturnBufferedSuccessAndError() throws Exception { + try (MockWebServer server = new MockWebServer(); + JakartaHttpTransport transport = new JakartaHttpTransport()) { + server.start(); + for (int status : new int[] {201, 409}) { + server.enqueue( + new MockResponse.Builder() + .code(status) + .addHeader("X-Result", "one") + .addHeader("X-Result", "two") + .body("body " + status) + .build()); + try (var response = + transport + .execute( + new HttpRequestInfo( + server.url("/items?existing=yes").uri(), + "POST", + Map.of( + "X-Request", + "value", + "Content-Type", + "text/plain", + "Authorization", + "Basic resolved"), + Map.of("search", "café + tea"), + "café".getBytes(StandardCharsets.UTF_8))) + .get(5, TimeUnit.SECONDS)) { + assertThat(response.status()).isEqualTo(status); + assertThat(response.request()).isEmpty(); + assertThat(response.stringHeaders().get("x-result")).containsExactly("one", "two"); + assertThat(new String(response.body(), StandardCharsets.UTF_8)) + .isEqualTo("body " + status); + var recorded = server.takeRequest(5, TimeUnit.SECONDS); + assertThat(recorded.getMethod()).isEqualTo("POST"); + assertThat(recorded.getUrl().queryParameter("search")).isEqualTo("café + tea"); + assertThat(recorded.getUrl().queryParameter("existing")).isEqualTo("yes"); + assertThat(recorded.getHeaders().get("X-Request")).isEqualTo("value"); + assertThat(recorded.getHeaders().get("Authorization")).isEqualTo("Basic resolved"); + assertThat(recorded.getBody().utf8()).isEqualTo("café"); + } + } + } + } + + @Test + void execute_shouldHonorInjectedReadTimeoutAndKeepClientOpen() throws Exception { + try (MockWebServer server = new MockWebServer(); + Client client = + ClientBuilder.newBuilder().readTimeout(100, TimeUnit.MILLISECONDS).build()) { + server.start(); + server.enqueue( + new MockResponse.Builder().headersDelay(1, TimeUnit.SECONDS).body("late").build()); + HttpRequestInfo request = + new HttpRequestInfo(server.url("/").uri(), "GET", Map.of(), Map.of(), null); + try (var transport = new JakartaHttpTransport(client)) { + assertThatThrownBy(() -> transport.execute(request).get(5, TimeUnit.SECONDS)) + .hasRootCauseInstanceOf(SocketTimeoutException.class); + } + server.enqueue(new MockResponse.Builder().body("still usable").build()); + try (var next = new JakartaHttpTransport(client)) { + assertThat(statusAndClose(next.execute(request))).isEqualTo(200); + } + } + } + + @Test + void cancel_shouldStillSendThePreparedRequestAndKeepSharedClientOpen() throws Exception { + try (MockWebServer server = new MockWebServer(); + Client client = ClientBuilder.newClient()) { + server.start(); + server.enqueue(new MockResponse.Builder().body("late").build()); + server.enqueue(new MockResponse.Builder().body("next").build()); + HttpRequestInfo request = + new HttpRequestInfo(server.url("/").uri(), "GET", Map.of(), Map.of(), null); + try (var transport = new JakartaHttpTransport(client)) { + CompletableFuture> preparation = new CompletableFuture<>(); + var cancelled = transport.exchange(request, builder -> preparation); + assertThat(cancelled.cancel(true)).isTrue(); + preparation.complete(null); + assertThat(server.takeRequest(5, TimeUnit.SECONDS)).isNotNull(); + assertThat(cancelled.isCancelled()).isTrue(); + } + try (var next = new JakartaHttpTransport(client)) { + assertThat(statusAndClose(next.execute(request))).isEqualTo(200); + } + } + } + + @Test + void cancelledDelivery_shouldCloseLateNativeResponses() throws Exception { + assertLateResponseClosed(false); + } + + @Test + void cancelledBufferedDelivery_shouldConsumeAndCloseLateNativeResponses() throws Exception { + assertLateResponseClosed(true); + } + + private void assertLateResponseClosed(boolean buffered) throws Exception { + Client client = mock(Client.class); + WebTarget target = mock(WebTarget.class); + Invocation.Builder builder = mock(Invocation.Builder.class); + CompletionStageRxInvoker invoker = mock(CompletionStageRxInvoker.class); + Response response = mock(Response.class); + CountDownLatch closed = new CountDownLatch(1); + doAnswer( + ignored -> { + closed.countDown(); + return null; + }) + .when(response) + .close(); + CompletableFuture network = new CompletableFuture<>(); + when(client.target(any(URI.class))).thenReturn(target); + when(target.request()).thenReturn(builder); + when(builder.rx()).thenReturn(invoker); + when(invoker.method(anyString())).thenReturn(network); + HttpRequestInfo request = + new HttpRequestInfo( + URI.create("http://localhost/"), "GET", Map.of(), Map.of(), null); + try (var transport = new JakartaHttpTransport(client)) { + CompletableFuture delivery = + buffered + ? transport.execute(request) + : transport.exchange(request, ignored -> CompletableFuture.completedFuture(null)); + if (buffered) { + when(response.getStringHeaders()).thenReturn(new jakarta.ws.rs.core.MultivaluedHashMap<>()); + when(response.hasEntity()).thenReturn(true); + when(response.readEntity(byte[].class)).thenReturn(new byte[] {1, 2}); + } + delivery.cancel(true); + assertThat(network.isCancelled()).isFalse(); + network.complete(response); + assertThat(closed.await(5, TimeUnit.SECONDS)).isTrue(); + verify(response).close(); + if (buffered) { + verify(response, org.mockito.Mockito.never()).bufferEntity(); + } + } + } + + @Test + void execute_shouldNotReadTheResponseBodyOnTheCallingThread() throws Exception { + Client client = mock(Client.class); + WebTarget target = mock(WebTarget.class); + Invocation.Builder builder = mock(Invocation.Builder.class); + CompletionStageRxInvoker invoker = mock(CompletionStageRxInvoker.class); + Response response = mock(Response.class); + CountDownLatch releaseBody = new CountDownLatch(1); + AtomicReference bufferedOnCommonPool = new AtomicReference<>(); + when(client.target(any(URI.class))).thenReturn(target); + when(target.request()).thenReturn(builder); + when(builder.rx()).thenReturn(invoker); + when(invoker.method(anyString())).thenReturn(CompletableFuture.completedFuture(response)); + when(response.getStringHeaders()).thenReturn(new jakarta.ws.rs.core.MultivaluedHashMap<>()); + when(response.hasEntity()).thenReturn(true); + when(response.readEntity(byte[].class)).thenReturn(new byte[] {42}); + when(response.bufferEntity()) + .thenAnswer(ignored -> { + bufferedOnCommonPool.set(ForkJoinTask.inForkJoinPool()); + if (!releaseBody.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Body was never released"); + } + return true; + }); + try (var transport = new JakartaHttpTransport(client); + var caller = Executors.newSingleThreadExecutor()) { + try { + var result = + caller + .submit(() -> + transport.execute( + new HttpRequestInfo( + URI.create("http://localhost/"), "GET", Map.of(), Map.of(), null))) + .get(1, TimeUnit.SECONDS); + assertThat(result.isDone()).isFalse(); + var delivered = + result.thenApply(data -> { + byte[] bytes = data.body(); + data.close(); + verify(response).close(); + return bytes; + }); + releaseBody.countDown(); + assertThat(delivered.get(5, TimeUnit.SECONDS)).containsExactly((byte) 42); + assertThat(bufferedOnCommonPool.get()).isFalse(); + } finally { + releaseBody.countDown(); + } + } + } +} diff --git a/common/http/README.md b/common/http/README.md new file mode 100644 index 000000000..9fac1a970 --- /dev/null +++ b/common/http/README.md @@ -0,0 +1,263 @@ +# HTTP execution without the workflow engine + +Other workflow engines can execute already resolved HTTP requests using +`openworkflow-common-http`. This artifact has no production dependencies. The +optional `openworkflow-common-http-jakarta` artifact adds Jakarta REST support and +depends only on this artifact and the Jakarta REST API. Neither brings in +`openworkflow-impl-core`, workflow models, expression evaluation, or a JSON library. + +```xml + + cloud.openworkflow.sdk + openworkflow-common-http + 8.0.0-SNAPSHOT + +``` + +Use a long-lived transport and pass serialized bytes, resolved headers and query +parameters. For example, a third-party activity executor can return this future +directly (or await it from a coroutine): + +```java +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import cloud.openworkflow.sdk.http.*; + +class HttpActivity { + private final HttpTransport transport; + + HttpActivity(HttpTransport transport) { + this.transport = transport; + } + + CompletableFuture execute(URI uri, String resolvedToken) { + return transport.execute(new HttpRequestInfo( + uri, "POST", + Map.of("Content-Type", "application/json", "Authorization", "Bearer " + resolvedToken), + Map.of("search", "café + tea"), + "{\"name\":\"café\"}".getBytes(StandardCharsets.UTF_8))); + } +} +``` + +Create a `JdkHttpTransport()` at application startup, or inject an existing +`java.net.http.HttpClient` with `new JdkHttpTransport(client)`. The equivalent +Jakarta API is `cloud.openworkflow.sdk.http.jakarta.JakartaHttpTransport`; add the +`openworkflow-common-http-jakarta` dependency and a Jakarta REST client provider +chosen by your application. The standalone tests run this example's request in a +module without the workflow engine on its classpath. + +`HttpResponse` exposes the HTTP status, all header values (case-insensitive +lookup), and body bytes, including for non-2xx statuses. HTTP error statuses are +responses, not exceptional completions. Transport failures complete the future +exceptionally with transport exceptions, without task metadata. Bodies are fully +buffered; this API is intended for the same non-streaming usage as the existing +SDK HTTP calls. Serialized request and legacy snapshot arrays are defensively copied. Native responses copy bytes only when `body()` is requested. +Malformed requests and synchronous preparation failures can throw before a +future is returned, retaining the existing native request validation behavior. + +## Effective request metadata + +`HttpResponse.request()` is an `Optional`. +When present, it describes the request associated with the final response, +including changes caused by redirects. For example, after a POST receives a 303, +the JDK transport reports the redirected GET and its final URI, including query: + +```java +transport.execute(request).thenAccept(response -> { + try (response) { + response.request().ifPresent(effective -> { + String method = effective.method(); + URI uri = effective.uri(); + Map> headers = effective.headers(); + // Use these values for the DSL response.request fields. + }); + } +}); +``` + +- **JDK:** snapshots method, URI and headers from + [`HttpResponse.request()`](https://docs.oracle.com/en/java/javase/21/docs/api/java.net.http/java/net/http/HttpResponse.html#request()). + This includes the final query and changes made by native preparation hooks. + Headers are those exposed by `HttpRequest.headers()`; headers added internally + by the client or network stack are not guaranteed to appear. +- **Jakarta:** always returns `Optional.empty()`, including for direct calls. + Jakarta REST's portable `Response` API does not expose the final request. + A [`ClientResponseFilter`](https://jakarta.ee/specifications/restful-ws/4.0/apidocs/jakarta.ws.rs/jakarta/ws/rs/client/clientresponsefilter) + receives a request context, but the API does not guarantee that context reflects + connector-managed redirect changes. Provider-specific response types can expose + additional information; this transport does not depend on those extensions or + reconstruct a final request from the initial one. Tests use Jersey 4.0.3 and + confirm a POST/303/GET exchange with explicitly absent metadata. +- **Third-party transports:** the existing `new HttpResponseData(status, headers, + body)` constructor remains available and leaves metadata absent. Transports + that can observe the final request may use the four-argument constructor with + `Optional.of(new HttpResponseData.RequestMetadata(method, uri, requestHeaders))`. + Absence means unavailable; callers must not substitute the initial request as + if it described the final exchange. + +Metadata owns an immutable snapshot of its header map and each value list. +Header lookup is case-insensitive; the request metadata and legacy snapshot records use +case-insensitive header-name equality and hashing. Case-equivalent entries +are merged without dropping values, retaining input iteration and value order. +Legacy `HttpResponseData` snapshot equality and hashing include the optional metadata and body contents; native response implementations use object identity. +Defensive body copies and the legacy constructor's behavior remain available. +The transport adds no header logging, and metadata string representations omit +the request URI and headers because they can contain credentials. + +## Workflow boundary and compatibility + +The existing `WorkflowHttpRequestFactory`, `WorkflowHttpRequest`, and response +entry points remain available. The JDK and Jakarta implementations delegate to +these transports. Custom workflow transport factories continue to work without +implementing a new SPI. The existing ServiceLoader entries remain unchanged. +Jakarta client suppliers, ordered request decorators, and model converters still +run in the workflow adapter, including the Jackson converter. + +The workflow adapter evaluates expressions, resolves resource/secret references +and authentication policies, serializes workflow models, converts responses, +updates `TaskContext` authorization, and attaches task positions to errors. +Basic, Bearer, Digest, OAuth2 and OpenID providers keep their existing paths; +their auxiliary HTTP requests use the same delegated transports. Standalone +callers supply resolved authorization headers, or use the narrow native request +preparation hooks to obtain headers asynchronously. Workflow authentication +policy resolution is not exported as part of the standalone API. + +JDK query/form encoding and default JSON content type retain the existing rules. +Jakarta uses its client's query/entity encoding and registered providers. +The adapters retain the SDK's content-type conversion and `with.output` handling +for content, response envelopes, and raw HTTP responses. The JDK `exchange` hook +accepts a native body publisher and retains the response's protocol version, so +custom body serialization and raw HTTP/2 response formatting stay in the adapter. +Redirects follow the configured transport client: the default JDK client uses +`Redirect.NORMAL`, and Jakarta uses the provider's defaults. The existing SDK +`redirect` status validation stays in the workflow adapter; this extraction does +not change that behavior, `with.output`, or retries. + +## Lifetimes, deadlines and cancellation + +- A transport created with its no-argument constructor owns its client. Close it + at application shutdown after outstanding work finishes. Closing may wait for + active requests according to the client implementation. Jakarta also owns a + cached-thread executor, configured on its default client and used for blocking + response buffering, following the SDK application's executor pattern. +- An injected client is borrowed. Neither a call nor `transport.close()` closes + it. Jakarta's existing client/converter constructors create their own buffering + executor, so close the transport even when borrowing a client. To reuse an + application executor, use `new JakartaHttpTransport(client, converter, executor)`. + This overload borrows both resources and closes neither. Configure the injected + client's own executor separately. The supplied executor must support blocking + reads; avoid the common fork/join pool and direct execution on event-loop threads. + The SDK adapter borrows `application.executorService()` for response buffering. + Supplied executors, including a custom SDK application executor, must run tasks + or signal rejection by throwing. Finish accepted tasks before executor shutdown; + silent discard policies or removing queued tasks prevent guaranteed cleanup. + Closing a transport shuts down its owned executor without waiting for its tasks; + already submitted tasks may finish, while late responses rejected by shutdown + are closed and their delivery fails. Prefer closing after outstanding calls finish. +- `execute` transfers response ownership to the caller. Use try-with-resources, + including around conversions. Jakarta buffers the native entity and retains its + response until close; cancelled deliveries are closed by the transport. Body + buffering runs on the transport's configured executor, so the default + constructors keep blocking reads off both the caller and the shared common pool. + Executor rejection also closes an unexposed response and completes delivery + exceptionally, preserving the rejection if response cleanup fails. +- Jakarta's advanced `exchange` hook returns a native `Response` to preserve + custom entity converters. The recipient must close that response. Responses + that arrive after the returned future has been cancelled are closed by the + transport. +- JDK connect timeouts come from the injected client. The overload + `execute(request, Duration)` additionally sets the native JDK request timeout; + its scope follows `HttpRequest.Builder.timeout`, not an independent deadline + for every body read. Jakarta connect/read timeouts come from `ClientBuilder` + and its provider. No new default timeouts are imposed on existing SDK calls. +- Cancelling the returned future abandons delivery only. It does **not** cancel + preparation, interrupt the network exchange, or roll back server effects. + Tests verify that requests can still reach the local server after cancellation + and that late Jakarta responses are closed. A coroutine cancelling its await + therefore must not assume that the remote operation was stopped. +- `orTimeout` or a timeout while awaiting a future is a delivery deadline, not a + network timeout. Configure transport timeouts to bound network resource use. + +This prepares HTTP reuse by other workflow engines. Streaming, network abort guarantees, authentication-policy portability, +and normalization of transport-specific HTTP behavior remain outside this API. + +## Converter prototype — for discussion + +This second commit illustrates the injectable-converter direction proposed in review; +it is not an approved final design. Reverting it restores the first commit's +structural reorganization without losing any of that work. + +`HttpRequestInfo` is the single concrete request implementation, extracted from +`WorkflowHttpRequestInfo`: URI, method, headers, query, body, the redirect flag, +conditional-date formatting and the builder's normalization live in common. +Only the SDK adapter validates status using the redirect flag; standalone +transports return every status and follow their client's native redirect policy. +Autonomous callers construct `new HttpRequestInfo(uri, method, headers, +query, bytes)` or use its builder. `HttpRequestData` has been removed. +The SDK compatibility subclass owns only authentication; it inherits all HTTP +state and delegates builder behavior to common. It adds no second HTTP payload. The SDK request keeps its usual constructor and +accessor signatures, including its WorkflowModel-returning body accessor. It is +now an extensible class rather than a record: record patterns and record-specific +reflection are not preserved by this prototype. + +The original response contract's general behavior also lives in common: body and +header access, status, last-modified, reason phrase, error details and raw response +serialization. SDK response classes are constructor-only subclasses of the same +JDK/Jakarta implementations; they contain no response state or HTTP behavior. +The SDK-specific model parsing policy lives in explicit converter classes, not +inside a second response implementation. The old SDK response interface only +retains its workflow-typed conversion method and legacy header type view. + +`HttpTransport.execute` returns `HttpResponse`. Inject `HttpBodyConverter` through +`new JdkHttpTransport(client, converter)` or `new JakartaHttpTransport(client, converter)`. +The converter's generic method can return a consumer's own JSON type: + +```java +HttpBodyConverter converter = new HttpBodyConverter() { + public java.util.Optional convert(HttpResponse source, Class type) { + if (type == MyJson.class) { + return java.util.Optional.of(type.cast(myJsonParser.parse(source.body()))); + } + return java.util.Optional.empty(); + } +}; +transport.execute(request).thenAccept(response -> { + try (response) { + var json = response.getBodyAsObject(MyJson.class); + byte[] original = response.body(); // original payload for raw output + } +}); +``` + +The default converter supports byte arrays only. The SDK injects a converter for +WorkflowModel using its current conversion policy. For Jakarta it calls the +existing HttpModelConverter with the borrowed native Response, preserving provider +conversion and registered readers; JDK uses its original buffered native payload. +No workflow type appears in the shared contract. `nativeResponse(Class)` exposes +a borrowed handle for explicit native integration; never close or mutate it separately. + +Jakarta calls `bufferEntity()` before delivering the response on an asynchronous +executor suitable for blocking reads. This preserves original bytes even after provider conversion, but still +requires native entity buffering; a native entity that cannot be buffered is rejected and closed before delivery. A consumer using `body()` also gets a byte-array +copy. JDK already buffers its body and avoids the former response snapshot clone on delivery. Serialized request bytes are snapshotted before asynchronous execution, including custom request implementations. +`HttpResponseData` remains a compatibility snapshot/third-party implementation. +Converters must not mutate borrowed native bytes. Native responses do not promise +value equality or payload hashing. The response is caller-owned; conversion failure +closes Jakarta resources, as do cancelled deliveries and discarded OpenAPI fallback +responses. The final OpenAPI response is owned by its caller. Closing does not close +an injected client. This is deliberately a minimal prototype, not streaming support. + +The revised standalone API is a source migration from the first commit: use the +canonical `HttpRequestInfo` instead of `HttpRequestData`, and consume the +shared response interface. As in the original SDK response contract, `headers()` +can expose native provider values (for example a Date); use `stringHeaders()` for +provider-serialized text. No published compatibility with an earlier local +prototype is implied. The legacy response snapshot constructor is retained. + +Jakarta's raw status-line formatting preserves the original SDK header-casing +heuristic for compatibility; it is not exposed as negotiated protocol metadata. +It can be inaccurate for lowercase HTTP/1.1 headers. The JDK formatter uses its +native protocol version. Raw header text uses the provider's serialization. diff --git a/common/http/pom.xml b/common/http/pom.xml new file mode 100644 index 000000000..aa17ee5cb --- /dev/null +++ b/common/http/pom.xml @@ -0,0 +1,27 @@ + + 4.0.0 + + cloud.openworkflow.sdk + openworkflow-common + 8.0.0-SNAPSHOT + + openworkflow-common-http + Open Workflow :: HTTP Client + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.assertj + assertj-core + test + + + com.squareup.okhttp3 + mockwebserver + test + + + diff --git a/common/http/src/main/java/cloud/openworkflow/sdk/http/HttpBodyConverter.java b/common/http/src/main/java/cloud/openworkflow/sdk/http/HttpBodyConverter.java new file mode 100644 index 000000000..c106c5fa2 --- /dev/null +++ b/common/http/src/main/java/cloud/openworkflow/sdk/http/HttpBodyConverter.java @@ -0,0 +1,30 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.http; + +import java.util.Optional; + +/** Explicit per-transport conversion policy; no service registry or workflow types. */ +public interface HttpBodyConverter { + Optional convert(HttpResponse response, Class type); + + HttpBodyConverter BYTES = + new HttpBodyConverter() { + public Optional convert(HttpResponse response, Class type) { + return type == byte[].class ? Optional.of(type.cast(response.body())) : Optional.empty(); + } + }; +} diff --git a/common/http/src/main/java/cloud/openworkflow/sdk/http/HttpHeaderNames.java b/common/http/src/main/java/cloud/openworkflow/sdk/http/HttpHeaderNames.java new file mode 100644 index 000000000..8d1458b7f --- /dev/null +++ b/common/http/src/main/java/cloud/openworkflow/sdk/http/HttpHeaderNames.java @@ -0,0 +1,32 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.http; + +/** Hash names with the same case folding as the shared header maps. */ +final class HttpHeaderNames { + private HttpHeaderNames() {} + + static int hash(String name) { + int hash = 0; + for (int offset = 0; offset < name.length(); ) { + int codePoint = name.codePointAt(offset); + // Match String.CASE_INSENSITIVE_ORDER without locale-dependent or expanding case mappings. + hash = 31 * hash + Character.toLowerCase(Character.toUpperCase(codePoint)); + offset += Character.charCount(codePoint); + } + return hash; + } +} diff --git a/common/http/src/main/java/cloud/openworkflow/sdk/http/HttpRequestEncoding.java b/common/http/src/main/java/cloud/openworkflow/sdk/http/HttpRequestEncoding.java new file mode 100644 index 000000000..28a9b3569 --- /dev/null +++ b/common/http/src/main/java/cloud/openworkflow/sdk/http/HttpRequestEncoding.java @@ -0,0 +1,55 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.http; + +import cloud.openworkflow.sdk.impl.http.URIDecodedBuilder; +import java.net.URI; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** The SDK's existing JDK query and form encoding rules. */ +public final class HttpRequestEncoding { + + public static String encodeForm(Object part) { + return part == null ? "" : URLEncoder.encode(part.toString(), StandardCharsets.UTF_8); + } + + public static String encodeQuery(Object part) { + return encodeForm(part).replace("+", "%20"); + } + + public static String encodeMap(Map map, Function encoder) { + return map.entrySet().stream() + .map(entry -> encoder.apply(entry.getKey()) + "=" + encoder.apply(entry.getValue())) + .collect(Collectors.joining("&")); + } + + public static URI addQueryParams(URI uri, Map queryParams) { + if (queryParams.isEmpty()) { + return uri; + } + String addedQuery = encodeMap(queryParams, HttpRequestEncoding::encodeQuery); + String rawQuery = uri.getRawQuery(); + return new URIDecodedBuilder(uri) + .query(rawQuery == null || rawQuery.isEmpty() ? addedQuery : rawQuery + "&" + addedQuery) + .build(); + } + + private HttpRequestEncoding() {} +} diff --git a/common/http/src/main/java/cloud/openworkflow/sdk/http/HttpRequestInfo.java b/common/http/src/main/java/cloud/openworkflow/sdk/http/HttpRequestInfo.java new file mode 100644 index 000000000..e7585b7bd --- /dev/null +++ b/common/http/src/main/java/cloud/openworkflow/sdk/http/HttpRequestInfo.java @@ -0,0 +1,277 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.http; + +import java.net.URI; +import java.time.*; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.Map.Entry; +import java.util.stream.Collectors; + +/** + * Resolved request state and builder extracted from WorkflowHttpRequestInfo. Byte bodies are owned + * snapshots; other bodies follow their model's ownership rules. + */ +public class HttpRequestInfo { + private final URI uri; + private final String method; + private final boolean redirect; + private final Map headers; + private final Map queryParams; + private final B body; + private final String ifModifiedSince; + + public HttpRequestInfo( + URI uri, + String method, + Map headers, + Map queryParams, + B body) { + this(uri, method, false, headers, queryParams, body, null); + } + + public HttpRequestInfo( + URI uri, + String method, + boolean redirect, + Map headers, + Map queryParams, + B body, + String modified) { + this.uri = Objects.requireNonNull(uri); + this.method = Objects.requireNonNull(method); + this.redirect = redirect; + Map headerCopy = + headers instanceof SortedMap sorted + ? new TreeMap<>(sorted.comparator()) + : new LinkedHashMap<>(); + headerCopy.putAll(headers); + this.headers = + headerCopy instanceof SortedMap sortedCopy + ? Collections.unmodifiableSortedMap(sortedCopy) + : Collections.unmodifiableMap(headerCopy); + this.queryParams = Collections.unmodifiableMap(new LinkedHashMap<>(queryParams)); + this.body = copyBody(body); + this.ifModifiedSince = modified; + } + + @SuppressWarnings("unchecked") + private static B copyBody(B value) { + return value instanceof byte[] bytes ? (B) bytes.clone() : value; + } + + public URI uri() { + return uri; + } + + public String method() { + return method; + } + + public boolean redirect() { + return redirect; + } + + public Map headers() { + return headers; + } + + public Map queryParams() { + return queryParams; + } + + /** Transport headers: the dedicated conditional date overrides a conflicting map value. */ + public Map effectiveHeaders() { + if (ifModifiedSince() == null) return headers(); + Map effective = new LinkedHashMap<>(); + headers() + .forEach((name, value) -> { + if (!name.equalsIgnoreCase("If-Modified-Since")) effective.put(name, value); + }); + effective.put("If-Modified-Since", ifModifiedSince()); + return Collections.unmodifiableMap(effective); + } + + public B body() { + return copyBody(body); + } + + public String ifModifiedSince() { + return ifModifiedSince; + } + + /** Uses the last supplied value, matching JDK setHeader preparation for repeated names. */ + public String contentType() { + Object value = null; + for (var entry : headers.entrySet()) + if (entry.getKey().equalsIgnoreCase("Content-Type")) value = entry.getValue(); + return value == null ? "application/json" : value.toString(); + } + + public static Builder builder(String method) { + return new Builder<>(method); + } + + @Override + public boolean equals(Object object) { + return this == object + || object != null + && getClass() == object.getClass() + && object instanceof HttpRequestInfo other + && uri.equals(other.uri) + && method.equals(other.method) + && redirect == other.redirect + && comparableHeaders().equals(other.comparableHeaders()) + && queryParams.equals(other.queryParams) + && (body instanceof byte[] left && other.body instanceof byte[] right + ? Arrays.equals(left, right) + : Objects.equals(body, other.body)) + && Objects.equals(ifModifiedSince, other.ifModifiedSince); + } + + @Override + public int hashCode() { + return 31 + * Objects.hash( + uri, method, redirect, requestHeadersHash(), queryParams, ifModifiedSince) + + (body instanceof byte[] bytes ? Arrays.hashCode(bytes) : Objects.hashCode(body)); + } + + private Map> comparableHeaders() { + Map> values = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + headers.forEach( + (name, value) -> values.computeIfAbsent(name, key -> new ArrayList<>()).add(value)); + return values; + } + + private int requestHeadersHash() { + int result = 0; + for (var entry : comparableHeaders().entrySet()) + result += HttpHeaderNames.hash(entry.getKey()) ^ entry.getValue().hashCode(); + return result; + } + + private static URI concatURI(URI base, URI child) { + if (child.isAbsolute()) return child; + String basePath = base.getRawPath(); + if (basePath == null || basePath.isBlank()) basePath = "/"; + else if (!basePath.endsWith("/")) basePath += "/"; + String relative = child.getRawPath(); + if (relative == null) relative = ""; + while (relative.startsWith("/")) relative = relative.substring(1); + StringBuilder raw = new StringBuilder(); + if (base.getScheme() != null) raw.append(base.getScheme()).append(':'); + if (base.getRawAuthority() != null) raw.append("//").append(base.getRawAuthority()); + raw.append(basePath).append(relative); + if (child.getRawQuery() != null) raw.append('?').append(child.getRawQuery()); + if (child.getRawFragment() != null) raw.append('#').append(child.getRawFragment()); + return URI.create(raw.toString()); + } + + public static class Builder { + private final String method; + private boolean redirect; + private Map headers; + private Map queryParams; + private B body; + private Long ifModifiedSince; + private URI path; + + public Builder() { + this.method = "GET"; + } + + public Builder(String method) { + this.method = Objects.requireNonNull(method).toUpperCase(Locale.ROOT); + } + + public Builder redirect(boolean redirect) { + this.redirect = redirect; + return this; + } + + public Builder headers(Map headers) { + if (headers != null) { + this.headers = + headers.entrySet().stream() + .filter(e -> e.getValue() != null) + .collect( + Collectors.toMap( + Entry::getKey, + Entry::getValue, + (oldEntry, newEntry) -> newEntry, + () -> new TreeMap<>(String.CASE_INSENSITIVE_ORDER))); + } + return this; + } + + public Builder path(URI path) { + this.path = path; + return this; + } + + public Builder queryParams(Map queryParams) { + if (queryParams != null) { + this.queryParams = + queryParams.entrySet().stream() + .collect( + Collectors.toMap(Entry::getKey, e -> e.getValue() == null ? "" : e.getValue())); + } + return this; + } + + public Builder body(B body) { + this.body = body; + return this; + } + + public Builder ifModifiedSince(long millis) { + this.ifModifiedSince = millis; + return this; + } + + public HttpRequestInfo build(URI uri) { + return create( + path == null ? uri : concatURI(uri, path), + method, + redirect, + headers != null ? headers : Map.of(), + queryParams != null ? queryParams : Map.of(), + body, + ifModifiedSince != null + ? Instant.ofEpochMilli(ifModifiedSince) + .atZone(ZoneOffset.UTC) + .format( + DateTimeFormatter.ofPattern( + "EEE, dd MMM uuuu HH:mm:ss 'GMT'", + Locale.US)) // RFC_1123 skips the 0 in single + // digit days + : null); + } + + protected HttpRequestInfo create( + URI uri, + String method, + boolean redirect, + Map headers, + Map queryParams, + B body, + String modified) { + return new HttpRequestInfo<>(uri, method, redirect, headers, queryParams, body, modified); + } + } +} diff --git a/common/http/src/main/java/cloud/openworkflow/sdk/http/HttpResponse.java b/common/http/src/main/java/cloud/openworkflow/sdk/http/HttpResponse.java new file mode 100644 index 000000000..881019ec2 --- /dev/null +++ b/common/http/src/main/java/cloud/openworkflow/sdk/http/HttpResponse.java @@ -0,0 +1,127 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.http; + +import java.util.*; + +/** Shared response. Callers own it and must close it, including after conversion failures. */ +public interface HttpResponse extends AutoCloseable { + int status(); + + byte[] body(); + + Map> headers(); + + default Map> stringHeaders() { + Map> result = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + headers() + .forEach((name, values) -> + result + .computeIfAbsent(name, key -> new ArrayList<>()) + .addAll(values.stream().map(String::valueOf).toList())); + result.replaceAll((name, values) -> List.copyOf(values)); + return Collections.unmodifiableMap(result); + } + + default Optional request() { + return Optional.empty(); + } + + default String firstHeader(String name) { + return headers().entrySet().stream() + .filter(e -> e.getKey().equalsIgnoreCase(name)) + .flatMap(e -> e.getValue().stream()) + .map(String::valueOf) + .findFirst() + .orElse(null); + } + + /** Borrowed native response, valid only until close; consumers must not close it separately. */ + default Optional nativeResponse(Class type) { + return Optional.empty(); + } + + default Optional getBodyAsObject(Class type) { + return HttpBodyConverter.BYTES.convert(this, type); + } + + /** Legacy content access may borrow native storage; use body() for an owned copy. */ + default byte[] contentAsByteArray() { + return body(); + } + + default String getHeader(String name) { + return firstHeader(name); + } + + default OptionalLong lastModified() { + String value = getHeader("Last-Modified"); + if (value == null) return OptionalLong.empty(); + try { + return OptionalLong.of( + java.time.ZonedDateTime.parse( + value, java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME) + .toInstant() + .toEpochMilli()); + } catch (java.time.format.DateTimeParseException error) { + return OptionalLong.empty(); + } + } + + default String errorDetails() { + byte[] bytes = contentAsByteArray(); + return bytes == null ? "No error information" : new String(bytes); + } + + default byte[] responseAsByteArray() { + return HttpResponses.responseAsByteArray(this, false); + } + + default String reasonPhrase() { + return switch (status()) { + case 100 -> "Continue"; + case 101 -> "Switching Protocols"; + case 102 -> "Processing"; + case 103 -> "Early Hints"; + case 200 -> "OK"; + case 201 -> "Created"; + case 202 -> "Accepted"; + case 204 -> "No Content"; + case 206 -> "Partial Content"; + case 301 -> "Moved Permanently"; + case 302 -> "Found"; + case 304 -> "Not Modified"; + case 307 -> "Temporary Redirect"; + case 308 -> "Permanent Redirect"; + case 400 -> "Bad Request"; + case 401 -> "Unauthorized"; + case 403 -> "Forbidden"; + case 404 -> "Not Found"; + case 405 -> "Method Not Allowed"; + case 408 -> "Request Timeout"; + case 409 -> "Conflict"; + case 429 -> "Too Many Requests"; + case 500 -> "Internal Server Error"; + case 502 -> "Bad Gateway"; + case 503 -> "Service Unavailable"; + case 504 -> "Gateway Timeout"; + default -> "Unknown Status Code"; + }; + } + + @Override + default void close() {} +} diff --git a/common/http/src/main/java/cloud/openworkflow/sdk/http/HttpResponseData.java b/common/http/src/main/java/cloud/openworkflow/sdk/http/HttpResponseData.java new file mode 100644 index 000000000..a56afd1a5 --- /dev/null +++ b/common/http/src/main/java/cloud/openworkflow/sdk/http/HttpResponseData.java @@ -0,0 +1,125 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.http; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.TreeMap; + +/** + * A fully buffered response, including non-2xx responses. It owns no open network resources. + * Equality and hashing use body contents and case-insensitive header names; header value order + * remains significant. Case-equivalent header names are merged in the input map's iteration order. + */ +public record HttpResponseData( + int status, Map> headers, byte[] body, Optional request) + implements HttpResponse { + + /** For transports that cannot report the effective request associated with this response. */ + public HttpResponseData(int status, Map> headers, byte[] body) { + this(status, headers, body, Optional.empty()); + } + + public HttpResponseData { + headers = copyHeaders(headers); + body = body.clone(); + request = Objects.requireNonNull(request, "request"); + } + + private static Map> copyHeaders(Map> headers) { + Map> copy = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + headers.forEach( + (name, values) -> copy.computeIfAbsent(name, key -> new ArrayList<>()).addAll(values)); + copy.replaceAll((name, values) -> List.copyOf(values)); + return Collections.unmodifiableMap(copy); + } + + @Override + public byte[] body() { + return body.clone(); + } + + @Override + public boolean equals(Object object) { + return this == object + || object instanceof HttpResponseData other + && status == other.status + && headers.equals(other.headers) + && Arrays.equals(body, other.body) + && request.equals(other.request); + } + + @Override + public int hashCode() { + int hash = 31 * (31 * Integer.hashCode(status) + headersHash(headers)) + Arrays.hashCode(body); + return 31 * hash + request.hashCode(); + } + + private static int headersHash(Map> headers) { + // TreeMap compares names case-insensitively, but its default hash uses original key casing. + int headersHash = 0; + for (var header : headers.entrySet()) { + headersHash += HttpHeaderNames.hash(header.getKey()) ^ header.getValue().hashCode(); + } + return headersHash; + } + + /** Returns the first header value, or null when absent. */ + public String firstHeader(String name) { + List values = headers.get(name); + return values == null || values.isEmpty() ? null : values.getFirst(); + } + + /** + * Immutable transport-visible request associated with the final response, after any redirects. + * The URI includes its query. Headers preserve all visible values, with case-insensitive names; + * they need not include headers added internally by the HTTP client. The URI and headers are + * omitted from toString because they may contain credentials. + */ + public record RequestMetadata(String method, URI uri, Map> headers) { + + public RequestMetadata { + method = Objects.requireNonNull(method, "method"); + uri = Objects.requireNonNull(uri, "uri"); + headers = copyHeaders(headers); + } + + @Override + public boolean equals(Object object) { + return this == object + || object instanceof RequestMetadata other + && method.equals(other.method) + && uri.equals(other.uri) + && headers.equals(other.headers); + } + + @Override + public int hashCode() { + return 31 * Objects.hash(method, uri) + headersHash(headers); + } + + @Override + public String toString() { + return "RequestMetadata[method=" + method + ", uri=, headers=]"; + } + } +} diff --git a/common/http/src/main/java/cloud/openworkflow/sdk/http/HttpResponses.java b/common/http/src/main/java/cloud/openworkflow/sdk/http/HttpResponses.java new file mode 100644 index 000000000..188f057be --- /dev/null +++ b/common/http/src/main/java/cloud/openworkflow/sdk/http/HttpResponses.java @@ -0,0 +1,64 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.http; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.util.*; + +/** Raw HTTP serialization extracted from WorkflowHttpHelper. */ +public final class HttpResponses { + private static final String HTTP_NEW_LINE = "\r\n"; + + private static void addHeader(StringBuilder sb, String name, Object value) { + sb.append(name).append(": ").append(value).append(HTTP_NEW_LINE); + } + + private HttpResponses() {} + + public static byte[] responseAsByteArray(HttpResponse response, boolean isHttp2) { + byte[] content = response.contentAsByteArray(); + try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { + StringBuilder sb = + new StringBuilder( + isHttp2 + ? "HTTP/2 " + response.status() + : "HTTP/1.1 " + response.status() + " " + response.reasonPhrase()); + sb.append(HTTP_NEW_LINE); + for (Map.Entry> entry : response.stringHeaders().entrySet()) { + String headerName = entry.getKey(); + for (Object value : entry.getValue()) { + if (headerName.equalsIgnoreCase("Transfer-Encoding") + && value instanceof String str + && str.equalsIgnoreCase("chunked")) { + addHeader(sb, "Content-Length", content == null ? 0 : content.length); + } else { + addHeader(sb, headerName, value); + } + } + } + sb.append(HTTP_NEW_LINE); + out.write(sb.toString().getBytes(StandardCharsets.ISO_8859_1)); + + if (content != null) { + out.write(content); + } + return out.toByteArray(); + } catch (IOException io) { + throw new UncheckedIOException(io); + } + } +} diff --git a/common/http/src/main/java/cloud/openworkflow/sdk/http/HttpTransport.java b/common/http/src/main/java/cloud/openworkflow/sdk/http/HttpTransport.java new file mode 100644 index 000000000..c542d753f --- /dev/null +++ b/common/http/src/main/java/cloud/openworkflow/sdk/http/HttpTransport.java @@ -0,0 +1,40 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.http; + +import java.util.concurrent.CompletableFuture; + +/** Executes resolved HTTP requests without a workflow engine. */ +public interface HttpTransport extends AutoCloseable { + + /** + * Returns a response owned by the caller for every HTTP status; transport failures complete + * exceptionally with the underlying transport error. Cancelling the returned future abandons + * delivery, not the network exchange. The exchange may still reach the server and complete. + * Callers must close responses, including after conversion errors. Invalid requests and + * synchronous preparation failures may throw before returning a future, following native request + * validation behavior. + * + *

The response's optional request metadata describes the effective request associated with the + * final response, including redirects, when observable by the transport. An empty optional means + * it is unavailable; callers must not substitute the initial request as if it were the final one. + */ + CompletableFuture execute(HttpRequestInfo request); + + /** Closes clients created by this transport; injected clients remain owned by the caller. */ + @Override + void close(); +} diff --git a/common/http/src/main/java/cloud/openworkflow/sdk/http/JdkHttpResponse.java b/common/http/src/main/java/cloud/openworkflow/sdk/http/JdkHttpResponse.java new file mode 100644 index 000000000..6343201ac --- /dev/null +++ b/common/http/src/main/java/cloud/openworkflow/sdk/http/JdkHttpResponse.java @@ -0,0 +1,81 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.http; + +import java.util.*; + +/** Native JDK response: already buffered, no open response resource. */ +public class JdkHttpResponse implements HttpResponse { + private final java.net.http.HttpResponse response; + private final HttpBodyConverter converter; + private final HttpResponseData.RequestMetadata request; + + public JdkHttpResponse(java.net.http.HttpResponse response, HttpBodyConverter converter) { + this.response = Objects.requireNonNull(response); + this.converter = Objects.requireNonNull(converter); + var r = response.request(); + request = + r == null + ? null + : new HttpResponseData.RequestMetadata(r.method(), r.uri(), r.headers().map()); + } + + public int status() { + return response.statusCode(); + } + + public byte[] body() { + return response.body() == null ? new byte[0] : response.body().clone(); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public Map> headers() { + return (Map) response.headers().map(); + } + + @Override + public Map> stringHeaders() { + return response.headers().map(); + } + + @Override + public String firstHeader(String name) { + return response.headers().firstValue(name).orElse(null); + } + + @Override + public byte[] contentAsByteArray() { + return response.body(); + } + + @Override + public byte[] responseAsByteArray() { + return HttpResponses.responseAsByteArray( + this, response.version() == java.net.http.HttpClient.Version.HTTP_2); + } + + public Optional request() { + return Optional.ofNullable(request); + } + + public Optional nativeResponse(Class type) { + return type.isInstance(response) ? Optional.of(type.cast(response)) : Optional.empty(); + } + + public Optional getBodyAsObject(Class type) { + return converter.convert(this, type); + } +} diff --git a/common/http/src/main/java/cloud/openworkflow/sdk/http/JdkHttpTransport.java b/common/http/src/main/java/cloud/openworkflow/sdk/http/JdkHttpTransport.java new file mode 100644 index 000000000..4cb12b29d --- /dev/null +++ b/common/http/src/main/java/cloud/openworkflow/sdk/http/JdkHttpTransport.java @@ -0,0 +1,136 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.http; + +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.function.Function; + +/** JDK HTTP transport. Redirects and connect timeouts follow the configured client. */ +public final class JdkHttpTransport implements HttpTransport { + + private final HttpClient client; + private final boolean ownsClient; + private final HttpBodyConverter converter; + + /** Creates an owned client with the SDK's existing NORMAL redirect policy and no timeout. */ + public JdkHttpTransport() { + this(HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NORMAL).build(), true); + } + + /** Borrows a client; closing this transport never closes that client. */ + public JdkHttpTransport(HttpClient client) { + this(client, false); + } + + private JdkHttpTransport(HttpClient client, boolean ownsClient) { + this(client, ownsClient, HttpBodyConverter.BYTES); + } + + public JdkHttpTransport(HttpClient client, HttpBodyConverter converter) { + this(client, false, converter); + } + + private JdkHttpTransport(HttpClient client, boolean ownsClient, HttpBodyConverter converter) { + this.converter = Objects.requireNonNull(converter); + this.client = Objects.requireNonNull(client, "client"); + this.ownsClient = ownsClient; + } + + @Override + public CompletableFuture execute( + HttpRequestInfo request) { + return execute(request, builder -> CompletableFuture.completedFuture(null)); + } + + /** + * Sets a JDK request timeout, covering response receipt as defined by + * HttpRequest.Builder.timeout. This is separate from a caller timing out its wait on the returned + * future. + */ + public CompletableFuture execute( + HttpRequestInfo request, Duration timeout) { + return execute( + request, + builder -> { + builder.timeout(timeout); + return CompletableFuture.completedFuture(null); + }); + } + + /** + * Prepares the native request asynchronously after headers and body are set, before sending. This + * narrow hook supports asynchronous authentication without requiring a service registry. + * Cancellation has the same delivery-only semantics as {@code execute(HttpRequestInfo)}. + */ + public CompletableFuture execute( + HttpRequestInfo request, + Function> prepare) { + byte[] supplied = request.body(); + byte[] body = supplied == null ? null : supplied.clone(); + return exchange( + request, + body == null + ? HttpRequest.BodyPublishers.noBody() + : HttpRequest.BodyPublishers.ofByteArray(body), + prepare) + .thenApply(response -> new JdkHttpResponse(response, converter)); + } + + /** + * Executes with a native body publisher instead of the request's byte body. This preserves custom + * serialization hooks and returns the native HTTP metadata, including protocol version. The body + * is fully buffered before completion, with no response resources to close. Cancellation abandons + * delivery only, as with {@code execute(HttpRequestInfo)}. + */ + public CompletableFuture> exchange( + HttpRequestInfo request, + HttpRequest.BodyPublisher body, + Function> prepare) { + HttpRequest.Builder builder = + HttpRequest.newBuilder() + .method(request.method(), body) + .uri(HttpRequestEncoding.addQueryParams(request.uri(), request.queryParams())) + .header("Content-Type", "application/json"); + request.effectiveHeaders().forEach((name, value) -> builder.setHeader(name, value.toString())); + CompletableFuture> delivery = new CompletableFuture<>(); + // Do not expose the preparation/send stage: cancelling it can skip the send callback. + prepare + .apply(builder) + .thenCompose( + ignored -> client.sendAsync(builder.build(), HttpResponse.BodyHandlers.ofByteArray())) + .whenComplete((response, error) -> { + if (error != null) { + delivery.completeExceptionally(error); + } else { + delivery.complete(response); + } + }); + return delivery; + } + + @Override + public void close() { + if (ownsClient) { + client.close(); + } + } +} diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/URIDecodedBuilder.java b/common/http/src/main/java/cloud/openworkflow/sdk/impl/http/URIDecodedBuilder.java similarity index 100% rename from impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/URIDecodedBuilder.java rename to common/http/src/main/java/cloud/openworkflow/sdk/impl/http/URIDecodedBuilder.java diff --git a/common/http/src/test/java/cloud/openworkflow/sdk/http/HttpConversionTest.java b/common/http/src/test/java/cloud/openworkflow/sdk/http/HttpConversionTest.java new file mode 100644 index 000000000..2f0dc25fb --- /dev/null +++ b/common/http/src/test/java/cloud/openworkflow/sdk/http/HttpConversionTest.java @@ -0,0 +1,176 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.http; + +import static org.assertj.core.api.Assertions.*; + +import java.net.http.HttpClient; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.TimeUnit; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import org.junit.jupiter.api.Test; + +class HttpConversionTest { + record ConsumerJson(String json) {} + + private static final class BorrowedRequest + extends cloud.openworkflow.sdk.http.HttpRequestInfo { + private final byte[] borrowed; + + BorrowedRequest( + java.net.URI uri, + String method, + Map headers, + Map queryParams, + byte[] body) { + super(uri, method, headers, queryParams, body); + borrowed = body; + } + + @Override + public byte[] body() { + return borrowed; + } + } + + @Test + void sendsConditionalDateFromTheSharedBuilderExactlyOnce() throws Exception { + try (var server = new mockwebserver3.MockWebServer(); + var transport = new JdkHttpTransport()) { + server.start(); + server.enqueue(new mockwebserver3.MockResponse.Builder().build()); + var request = + cloud.openworkflow.sdk.http.HttpRequestInfo.builder("GET") + .ifModifiedSince(784111777000L) + .build(server.url("/").uri()); + try (var response = + transport.execute(request).get(5, java.util.concurrent.TimeUnit.SECONDS)) { + var headers = + server + .takeRequest(5, java.util.concurrent.TimeUnit.SECONDS) + .getHeaders() + .values("If-Modified-Since"); + assertThat(headers).isEqualTo(java.util.List.of("Sun, 06 Nov 1994 08:49:37 GMT")); + } + } + } + + @Test + void dedicatedConditionalDateOverridesTheHeaderMap() throws Exception { + try (var server = new mockwebserver3.MockWebServer(); + var transport = new JdkHttpTransport()) { + server.start(); + server.enqueue(new mockwebserver3.MockResponse.Builder().build()); + var request = + cloud.openworkflow.sdk.http.HttpRequestInfo.builder("GET") + .headers(java.util.Map.of("if-modified-since", "discarded")) + .ifModifiedSince(784111777000L) + .build(server.url("/").uri()); + try (var response = + transport.execute(request).get(5, java.util.concurrent.TimeUnit.SECONDS)) { + var headers = + server + .takeRequest(5, java.util.concurrent.TimeUnit.SECONDS) + .getHeaders() + .values("If-Modified-Since"); + assertThat(headers).isEqualTo(java.util.List.of("Sun, 06 Nov 1994 08:49:37 GMT")); + } + } + } + + @Test + void snapshotsCustomRequestBytesBeforePendingPreparation() throws Exception { + try (var server = new MockWebServer(); + var transport = new JdkHttpTransport()) { + server.start(); + server.enqueue(new MockResponse.Builder().build()); + byte[] bytes = {1, 2}; + var preparation = new java.util.concurrent.CompletableFuture(); + var result = + transport.execute( + new BorrowedRequest(server.url("/").uri(), "POST", Map.of(), Map.of(), bytes), + builder -> preparation); + bytes[0] = 9; + preparation.complete(null); + try (var response = result.get(5, TimeUnit.SECONDS)) { + assertThat(server.takeRequest(5, TimeUnit.SECONDS).getBody().toByteArray()) + .isEqualTo(new byte[] {1, 2}); + } + } + } + + @Test + void sharedHeaderViewPreservesCaseEquivalentValues() { + HttpResponse response = + new HttpResponse() { + public int status() { + return 200; + } + + public byte[] body() { + return new byte[0]; + } + + public Map> headers() { + var headers = new LinkedHashMap>(); + headers.put("Set-Cookie", List.of("first")); + headers.put("set-cookie", List.of("second")); + return headers; + } + }; + assertThat(response.stringHeaders().get("SET-cookie")).isEqualTo(List.of("first", "second")); + assertThat(response.firstHeader("SET-cookie")).isEqualTo("first"); + } + + @Test + void convertsToAConsumerTypeUsingTheNativeResponseAndRetainsRawBytes() throws Exception { + try (var server = new MockWebServer(); + var client = HttpClient.newHttpClient()) { + server.start(); + String json = "{\"name\":\"external\"}"; + server.enqueue(new MockResponse.Builder().body(json).code(422).build()); + HttpBodyConverter converter = + new HttpBodyConverter() { + public Optional convert(HttpResponse response, Class type) { + if (type != ConsumerJson.class) return Optional.empty(); + byte[] nativeBytes = + (byte[]) + response + .nativeResponse(java.net.http.HttpResponse.class) + .orElseThrow() + .body(); + return Optional.of( + type.cast(new ConsumerJson(new String(nativeBytes, StandardCharsets.UTF_8)))); + } + }; + try (HttpTransport transport = new JdkHttpTransport(client, converter); + HttpResponse response = + transport + .execute( + new HttpRequestInfo( + server.url("/").uri(), "GET", Map.of(), Map.of(), null)) + .get(5, TimeUnit.SECONDS)) { + assertThat(response.status()).isEqualTo(422); + assertThat(response.getBodyAsObject(ConsumerJson.class).orElseThrow().json()) + .isEqualTo(json); + assertThat(response.body()).isEqualTo(json.getBytes(StandardCharsets.UTF_8)); + assertThat(response.getBodyAsObject(Integer.class).isEmpty()).isTrue(); + } + } + } +} diff --git a/common/http/src/test/java/cloud/openworkflow/sdk/http/HttpRequestInfoTest.java b/common/http/src/test/java/cloud/openworkflow/sdk/http/HttpRequestInfoTest.java new file mode 100644 index 000000000..98402c87e --- /dev/null +++ b/common/http/src/test/java/cloud/openworkflow/sdk/http/HttpRequestInfoTest.java @@ -0,0 +1,196 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.http; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.net.URI; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import org.junit.jupiter.api.Test; + +class HttpRequestInfoTest { + + private static final URI URI_VALUE = URI.create("http://localhost/items"); + + private static HttpRequestInfo request(byte[] body) { + return new HttpRequestInfo( + URI_VALUE, "POST", Map.of("X-Request", "value"), Map.of("page", 1), body); + } + + @Test + void methodNormalizationDoesNotDependOnTheDefaultLocale() { + var previous = java.util.Locale.getDefault(); + try { + java.util.Locale.setDefault(java.util.Locale.forLanguageTag("tr")); + assertThat( + HttpRequestInfo.builder("options") + .build(URI.create("https://example.test")) + .method()) + .isEqualTo("OPTIONS"); + } finally { + java.util.Locale.setDefault(previous); + } + } + + @Test + void commonBuilderPreservesEncodedPathQueryAndFragmentDelimiters() { + var request = + HttpRequestInfo.builder("GET") + .path(URI.create("items/a%2Fb?tag=a%26b#x%2Fy")) + .build(URI.create("https://example.test/v1")); + assertThat(request.uri().toString()) + .isEqualTo("https://example.test/v1/items/a%2Fb?tag=a%26b#x%2Fy"); + } + + @Test + void sharedHeadersRetainSdkCaseInsensitiveLookupAndConsistentHashing() { + var first = + HttpRequestInfo.builder("GET") + .headers(Map.of("Content-Type", "text/plain")) + .build(URI.create("https://example.test")); + var second = + new HttpRequestInfo( + first.uri(), "GET", Map.of("content-type", "text/plain"), Map.of(), null); + assertThat(first.headers().get("CONTENT-TYPE")).isEqualTo("text/plain"); + assertThat(first).isEqualTo(second); + assertThat(second).isEqualTo(first); + assertThat(first.hashCode()).isEqualTo(second.hashCode()); + } + + @Test + void genericNonByteBodiesRetainTheirOwnEqualityRules() { + int[] body = {1}; + var first = + new HttpRequestInfo( + URI.create("https://example.test"), "GET", Map.of(), Map.of(), body); + var same = new HttpRequestInfo(first.uri(), "GET", Map.of(), Map.of(), body); + var other = new HttpRequestInfo(first.uri(), "GET", Map.of(), Map.of(), new int[] {1}); + assertThat(first).isEqualTo(same).isNotEqualTo(other); + assertThat(first.hashCode()).isEqualTo(same.hashCode()); + } + + @Test + void equalsAndHashCode_shouldCompareBodyContents() { + var first = request(new byte[] {1, 2, 3}); + var second = request(new byte[] {1, 2, 3}); + var third = request(new byte[] {1, 2, 3}); + assertThat(first).isEqualTo(first).isEqualTo(second).isEqualTo(third); + assertThat(second).isEqualTo(first).isEqualTo(third); + assertThat(first.hashCode()).isEqualTo(second.hashCode()).isEqualTo(third.hashCode()); + assertThat(first).isNotEqualTo(null).isNotEqualTo("not a request"); + } + + @Test + void valueCopy_shouldRemainEqualAndUsableAsAHashKey() { + var original = request(new byte[] {1, 2, 3}); + var copy = + new HttpRequestInfo( + original.uri(), + original.method(), + original.headers(), + original.queryParams(), + original.body()); + assertThat(copy).isEqualTo(original); + assertThat(copy.hashCode()).isEqualTo(original.hashCode()); + Map, String> indexed = new HashMap<>(); + indexed.put(original, "stored"); + assertThat(indexed.get(copy)).isEqualTo("stored"); + } + + @Test + void equals_shouldIncludeEveryComponent() { + var original = request(new byte[] {1, 2, 3}); + assertThat(original) + .isNotEqualTo( + new HttpRequestInfo( + URI.create("http://localhost/other"), + original.method(), + original.headers(), + original.queryParams(), + original.body())); + assertThat(original) + .isNotEqualTo( + new HttpRequestInfo( + original.uri(), + "PUT", + original.headers(), + original.queryParams(), + original.body())); + assertThat(original) + .isNotEqualTo( + new HttpRequestInfo( + original.uri(), + original.method(), + Map.of("X-Request", "other"), + original.queryParams(), + original.body())); + assertThat(original) + .isNotEqualTo( + new HttpRequestInfo( + original.uri(), + original.method(), + original.headers(), + Map.of("page", 2), + original.body())); + assertThat(original).isNotEqualTo(request(new byte[] {1, 2, 4})); + } + + @Test + void equalsAndHashCode_shouldDistinguishAbsentAndEmptyBodies() { + var absent = request(null); + var absentCopy = request(null); + var empty = request(new byte[0]); + var emptyCopy = request(new byte[0]); + assertThat(absent).isEqualTo(absentCopy).isNotEqualTo(empty); + assertThat(absent.hashCode()).isEqualTo(absentCopy.hashCode()); + assertThat(empty).isEqualTo(emptyCopy); + assertThat(empty.hashCode()).isEqualTo(emptyCopy.hashCode()); + assertThat(new HashSet<>(Set.of(absent, empty)).contains(emptyCopy)).isTrue(); + } + + @Test + void bodyCopies_shouldKeepHashKeysStable() { + byte[] source = {1, 2, 3}; + var original = request(source); + var equivalent = request(new byte[] {1, 2, 3}); + Set> keys = new HashSet<>(Set.of(original)); + int hash = original.hashCode(); + source[0] = 9; + original.body()[1] = 9; + assertThat(original.body()).containsExactly((byte) 1, (byte) 2, (byte) 3); + assertThat(original).isEqualTo(equivalent); + assertThat(original.hashCode()).isEqualTo(hash).isEqualTo(equivalent.hashCode()); + assertThat(keys.contains(equivalent)).isTrue(); + } + + @Test + void equalsAndHashCode_shouldIgnoreMapInsertionOrder() { + Map forward = new LinkedHashMap<>(); + forward.put("first", 1); + forward.put("second", 2); + Map reverse = new LinkedHashMap<>(); + reverse.put("second", 2); + reverse.put("first", 1); + var first = new HttpRequestInfo(URI_VALUE, "POST", forward, reverse, new byte[] {1}); + var second = new HttpRequestInfo(URI_VALUE, "POST", reverse, forward, new byte[] {1}); + assertThat(first).isEqualTo(second); + assertThat(first.hashCode()).isEqualTo(second.hashCode()); + } +} diff --git a/common/http/src/test/java/cloud/openworkflow/sdk/http/HttpResponseDataTest.java b/common/http/src/test/java/cloud/openworkflow/sdk/http/HttpResponseDataTest.java new file mode 100644 index 000000000..019fa0766 --- /dev/null +++ b/common/http/src/test/java/cloud/openworkflow/sdk/http/HttpResponseDataTest.java @@ -0,0 +1,284 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.http; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.net.URI; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import org.junit.jupiter.api.Test; + +class HttpResponseDataTest { + + @Test + void thirdPartyTransport_shouldRetainTheLegacyConstructorWithExplicitlyAbsentMetadata() { + HttpTransport transport = + new HttpTransport() { + @Override + public CompletableFuture execute( + cloud.openworkflow.sdk.http.HttpRequestInfo request) { + return CompletableFuture.completedFuture( + new HttpResponseData( + 200, Map.of("X-Response", List.of("third-party")), new byte[0])); + } + + @Override + public void close() {} + }; + var response = + transport + .execute( + new HttpRequestInfo( + URI.create("https://example.test/initial"), "POST", Map.of(), Map.of(), null)) + .join(); + assertThat(response.status()).isEqualTo(200); + assertThat(response.request()).isEmpty(); + assertThat(response.firstHeader("X-Response")).isEqualTo("third-party"); + assertThat(response) + .isEqualTo( + new HttpResponseData(200, response.stringHeaders(), new byte[0], Optional.empty())); + } + + @Test + void requestMetadata_shouldSnapshotAllHeaderValuesAndKeepHashKeysStable() { + var values = new ArrayList<>(List.of("one", "two")); + Map> source = new LinkedHashMap<>(); + source.put("X-Request", values); + source.put("x-request", List.of("three", "one")); + var original = + new HttpResponseData.RequestMetadata( + "GET", URI.create("https://example.test/final?q=yes"), source); + var equivalent = + new HttpResponseData.RequestMetadata( + "GET", original.uri(), Map.of("X-REQUEST", List.of("one", "two", "three", "one"))); + Set keys = new HashSet<>(Set.of(original)); + int hash = original.hashCode(); + values.clear(); + source.clear(); + assertThat(original.headers().keySet()).containsExactly("X-Request"); + assertThat(original.headers().get("x-request")).containsExactly("one", "two", "three", "one"); + assertThatThrownBy(() -> original.headers().put("Other", List.of("value"))) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> original.headers().get("X-Request").clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThat(original).isEqualTo(equivalent); + assertThat(equivalent).isEqualTo(original); + assertThat(original.hashCode()).isEqualTo(hash).isEqualTo(equivalent.hashCode()); + assertThat(keys.contains(equivalent)).isTrue(); + } + + @Test + void requestMetadata_shouldParticipateInResponseEqualityAndRecordCopies() { + var request = + new HttpResponseData.RequestMetadata( + "GET", + URI.create("https://example.test/final?source=redirect"), + Map.of("X-Request", List.of("one", "two"))); + byte[] body = {1, 2}; + var original = new HttpResponseData(200, Map.of(), body, Optional.of(request)); + var copy = + new HttpResponseData( + original.status(), original.headers(), original.body(), original.request()); + var equivalent = + new HttpResponseData( + 200, + Map.of(), + new byte[] {1, 2}, + Optional.of( + new HttpResponseData.RequestMetadata( + "GET", request.uri(), Map.of("x-request", List.of("one", "two"))))); + int hash = original.hashCode(); + body[0] = 9; + original.body()[1] = 9; + assertThat(original).isEqualTo(copy).isEqualTo(equivalent); + assertThat(original.hashCode()) + .isEqualTo(hash) + .isEqualTo(copy.hashCode()) + .isEqualTo(equivalent.hashCode()); + assertThat(new HashSet<>(Set.of(original)).contains(equivalent)).isTrue(); + assertThat(original.body()).containsExactly((byte) 1, (byte) 2); + assertThat(original).isNotEqualTo(new HttpResponseData(200, Map.of(), new byte[] {1, 2})); + for (var other : + List.of( + new HttpResponseData.RequestMetadata("POST", request.uri(), request.headers()), + new HttpResponseData.RequestMetadata( + "GET", URI.create("https://example.test/initial"), request.headers()), + new HttpResponseData.RequestMetadata( + "GET", request.uri(), Map.of("X-Request", List.of("two", "one"))))) { + assertThat(request).isNotEqualTo(other); + assertThat(original) + .isNotEqualTo(new HttpResponseData(200, Map.of(), new byte[] {1, 2}, Optional.of(other))); + } + } + + @Test + void requestMetadata_shouldOmitRequestCredentialsFromStringRepresentations() { + var request = + new HttpResponseData.RequestMetadata( + "GET", + URI.create("https://example.test/?apiKey=query-credential"), + Map.of("Authorization", List.of("sensitive-credential"))); + assertThat(request.toString()).doesNotContain("sensitive-credential", "query-credential"); + assertThat(new HttpResponseData(200, Map.of(), new byte[0], Optional.of(request)).toString()) + .doesNotContain("sensitive-credential", "query-credential"); + } + + @Test + void headers_shouldMergeCaseEquivalentNamesWithoutLosingValues() { + var cookies = new ArrayList<>(List.of("session=abc", "theme=dark")); + Map> headers = new LinkedHashMap<>(); + headers.put("Set-Cookie", cookies); + headers.put("X-Result", List.of("ok")); + headers.put("set-cookie", List.of("csrf=xyz")); + headers.put("SET-COOKIE", List.of("session=abc")); + + var response = new HttpResponseData(200, headers, new byte[0]); + cookies.clear(); + headers.clear(); + + assertThat(response.stringHeaders()).hasSize(2); + assertThat(response.stringHeaders().keySet()).containsExactly("Set-Cookie", "X-Result"); + assertThat(response.stringHeaders().get("sEt-CoOkIe")) + .containsExactly("session=abc", "theme=dark", "csrf=xyz", "session=abc"); + assertThat(response.firstHeader("SET-cookie")).isEqualTo("session=abc"); + assertThat(response.firstHeader("x-result")).isEqualTo("ok"); + assertThatThrownBy(() -> response.stringHeaders().get("set-cookie").add("another=value")) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> response.stringHeaders().put("Other", List.of("value"))) + .isInstanceOf(UnsupportedOperationException.class); + + var equivalent = + new HttpResponseData( + 200, + Map.of( + "set-cookie", List.of("session=abc", "theme=dark", "csrf=xyz", "session=abc"), + "x-result", List.of("ok")), + new byte[0]); + assertThat(response).isEqualTo(equivalent); + assertThat(response.hashCode()).isEqualTo(equivalent.hashCode()); + } + + private static HttpResponseData response(byte[] body) { + return new HttpResponseData(200, Map.of("X-Result", List.of("one", "two")), body); + } + + @Test + void equalsAndHashCode_shouldCompareBodyContents() { + var first = response(new byte[] {1, 2, 3}); + var second = response(new byte[] {1, 2, 3}); + var third = response(new byte[] {1, 2, 3}); + assertThat(first).isEqualTo(first).isEqualTo(second).isEqualTo(third); + assertThat(second).isEqualTo(first).isEqualTo(third); + assertThat(first.hashCode()).isEqualTo(second.hashCode()).isEqualTo(third.hashCode()); + assertThat(first).isNotEqualTo(null).isNotEqualTo("not a response"); + } + + @Test + void recordCopy_shouldRemainEqualAndUsableAsAHashKey() { + var original = response(new byte[] {1, 2, 3}); + var copy = new HttpResponseData(original.status(), original.headers(), original.body()); + assertThat(copy).isEqualTo(original); + assertThat(copy.hashCode()).isEqualTo(original.hashCode()); + assertThat(new HashSet<>(Set.of(original)).contains(copy)).isTrue(); + } + + @Test + void equals_shouldIncludeEveryComponent() { + var original = response(new byte[] {1, 2, 3}); + assertThat(original) + .isNotEqualTo(new HttpResponseData(201, original.headers(), original.body())); + assertThat(original) + .isNotEqualTo( + new HttpResponseData(200, Map.of("X-Other", List.of("one", "two")), original.body())); + assertThat(original) + .isNotEqualTo( + new HttpResponseData(200, Map.of("X-Result", List.of("two", "one")), original.body())); + assertThat(original).isNotEqualTo(response(new byte[] {1, 2, 4})); + } + + @Test + void equalsAndHashCode_shouldSupportEmptyBodies() { + var first = response(new byte[0]); + var second = response(first.body()); + assertThat(first).isEqualTo(second); + assertThat(first.hashCode()).isEqualTo(second.hashCode()); + assertThat(new HashSet<>(Set.of(first)).contains(second)).isTrue(); + } + + @Test + void bodyCopies_shouldKeepHashKeysStable() { + byte[] source = {1, 2, 3}; + var original = response(source); + var equivalent = response(new byte[] {1, 2, 3}); + Set keys = new HashSet<>(Set.of(original)); + int hash = original.hashCode(); + source[0] = 9; + original.body()[1] = 9; + assertThat(original.body()).containsExactly((byte) 1, (byte) 2, (byte) 3); + assertThat(original).isEqualTo(equivalent); + assertThat(original.hashCode()).isEqualTo(hash).isEqualTo(equivalent.hashCode()); + assertThat(keys.contains(equivalent)).isTrue(); + } + + @Test + void equalsAndHashCode_shouldHonorTheHeaderComparator() { + for (var names : + List.of( + Map.entry("X-Result", "x-result"), + Map.entry("\u0130", "i"), + Map.entry("\u03c3", "\u03c2"), + Map.entry("\ud801\udc00", "\ud801\udc28"))) { + var first = + new HttpResponseData(200, Map.of(names.getKey(), List.of("value")), new byte[] {1}); + var second = + new HttpResponseData(200, Map.of(names.getValue(), List.of("value")), new byte[] {1}); + assertThat(first).isEqualTo(second); + assertThat(second).isEqualTo(first); + assertThat(first.hashCode()).isEqualTo(second.hashCode()); + assertThat(new HashSet<>(Set.of(first)).contains(second)).isTrue(); + assertThat(first.headers().keySet()).containsExactly(names.getKey()); + var firstRequest = + new HttpResponseData.RequestMetadata( + "GET", URI.create("https://example.test/"), first.headers()); + var secondRequest = + new HttpResponseData.RequestMetadata("GET", firstRequest.uri(), second.headers()); + assertThat(firstRequest).isEqualTo(secondRequest); + assertThat(secondRequest).isEqualTo(firstRequest); + assertThat(firstRequest.hashCode()).isEqualTo(secondRequest.hashCode()); + assertThat(new HashSet<>(Set.of(firstRequest)).contains(secondRequest)).isTrue(); + } + } + + @Test + void equalsAndHashCode_shouldIgnoreHeaderInsertionOrder() { + var first = + new HttpResponseData( + 200, Map.of("X-First", List.of("one"), "X-Second", List.of("two")), new byte[] {1}); + var second = + new HttpResponseData( + 200, Map.of("x-second", List.of("two"), "x-first", List.of("one")), new byte[] {1}); + assertThat(first).isEqualTo(second); + assertThat(first.hashCode()).isEqualTo(second.hashCode()); + } +} diff --git a/common/http/src/test/java/cloud/openworkflow/sdk/http/JdkHttpTransportTest.java b/common/http/src/test/java/cloud/openworkflow/sdk/http/JdkHttpTransportTest.java new file mode 100644 index 000000000..9b2ae2666 --- /dev/null +++ b/common/http/src/test/java/cloud/openworkflow/sdk/http/JdkHttpTransportTest.java @@ -0,0 +1,319 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.http; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpTimeoutException; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import org.junit.jupiter.api.Test; + +class JdkHttpTransportTest { + + @Test + void execute_shouldExposeTheEffectiveGetAfterASeeOtherRedirect() throws Exception { + try (MockWebServer server = new MockWebServer(); + HttpTransport transport = new JdkHttpTransport()) { + server.start(); + server.enqueue( + new MockResponse.Builder() + .code(303) + .addHeader("Location", "/final?source=redirect") + .build()); + server.enqueue(new MockResponse.Builder().body("final response").build()); + var response = + transport + .execute( + new HttpRequestInfo( + server.url("/start?source=initial").uri(), + "POST", + Map.of("X-Request", "redirected"), + Map.of(), + "initial body".getBytes(StandardCharsets.UTF_8))) + .get(5, TimeUnit.SECONDS); + + assertThat(response.status()).isEqualTo(200); + var effective = response.request().orElseThrow(); + assertThat(effective.method()).isEqualTo("GET"); + assertThat(effective.uri()).isEqualTo(server.url("/final?source=redirect").uri()); + assertThat(effective.headers().get("x-request")).containsExactly("redirected"); + var initial = server.takeRequest(5, TimeUnit.SECONDS); + assertThat(initial.getMethod()).isEqualTo("POST"); + assertThat(initial.getBody().utf8()).isEqualTo("initial body"); + var redirected = server.takeRequest(5, TimeUnit.SECONDS); + assertThat(redirected.getMethod()).isEqualTo("GET"); + assertThat(redirected.getUrl().uri()).isEqualTo(effective.uri()); + } + } + + @Test + void execute_shouldDistinguishDirectRequestHeadersFromResponseHeaders() throws Exception { + try (MockWebServer server = new MockWebServer(); + HttpTransport transport = new JdkHttpTransport()) { + server.start(); + server.enqueue(new MockResponse.Builder().addHeader("X-Response", "received").build()); + var response = + transport + .execute( + new HttpRequestInfo( + server.url("/direct?existing=a%2Bb").uri(), + "GET", + Map.of("X-Request", "sent"), + Map.of("search", "tea + coffee"), + null)) + .get(5, TimeUnit.SECONDS); + var effective = response.request().orElseThrow(); + assertThat(effective.method()).isEqualTo("GET"); + assertThat(effective.uri()) + .isEqualTo(server.url("/direct?existing=a%2Bb&search=tea%20%2B%20coffee").uri()); + assertThat(effective.headers().get("x-request")).containsExactly("sent"); + assertThat(effective.headers()).doesNotContainKey("X-Response"); + assertThat(response.firstHeader("X-Response")).isEqualTo("received"); + assertThat(response.stringHeaders()).doesNotContainKey("X-Request"); + assertThat(server.takeRequest(5, TimeUnit.SECONDS).getUrl().uri()).isEqualTo(effective.uri()); + } + } + + @Test + void execute_shouldCapturePreparedRequestChangesAndEveryHeaderValue() throws Exception { + try (MockWebServer server = new MockWebServer(); + JdkHttpTransport transport = new JdkHttpTransport()) { + server.start(); + server.enqueue(new MockResponse.Builder().build()); + var response = + transport + .execute( + new HttpRequestInfo( + server.url("/initial").uri(), "POST", Map.of(), Map.of(), null), + builder -> { + builder.uri(server.url("/prepared?actual=yes").uri()); + builder.method("GET", HttpRequest.BodyPublishers.noBody()); + builder.header("X-Multiple", "one").header("X-Multiple", "two"); + return CompletableFuture.completedFuture(null); + }) + .get(5, TimeUnit.SECONDS); + var effective = response.request().orElseThrow(); + assertThat(effective.method()).isEqualTo("GET"); + assertThat(effective.uri()).isEqualTo(server.url("/prepared?actual=yes").uri()); + assertThat(effective.headers().get("x-multiple")).containsExactly("one", "two"); + assertThat(server.takeRequest(5, TimeUnit.SECONDS).getHeaders().values("X-Multiple")) + .containsExactly("one", "two"); + } + } + + @Test + void exchange_shouldAbandonDeliveryWithoutCancellingPreparation() throws Exception { + try (MockWebServer server = new MockWebServer(); + JdkHttpTransport transport = new JdkHttpTransport()) { + server.start(); + server.enqueue(new MockResponse.Builder().body("sent after cancellation").build()); + HttpRequestInfo request = + new HttpRequestInfo(server.url("/").uri(), "GET", Map.of(), Map.of(), null); + CompletableFuture preparation = new CompletableFuture<>(); + var delivery = + transport.exchange(request, HttpRequest.BodyPublishers.noBody(), builder -> preparation); + assertThat(delivery.cancel(true)).isTrue(); + assertThat(preparation.isCancelled()).isFalse(); + preparation.complete(null); + assertThat(server.takeRequest(5, TimeUnit.SECONDS)).isNotNull(); + assertThat(delivery.isCancelled()).isTrue(); + } + } + + @Test + void exchange_shouldPreserveNativePublisherAndResponseMetadata() throws Exception { + try (MockWebServer server = new MockWebServer(); + JdkHttpTransport transport = new JdkHttpTransport()) { + server.start(); + server.enqueue( + new MockResponse.Builder() + .code(201) + .addHeader("X-Response", "native") + .body("response body") + .build()); + HttpRequestInfo request = + new HttpRequestInfo( + server.url("/").uri(), + "POST", + Map.of(), + Map.of(), + "unused bytes".getBytes(StandardCharsets.UTF_8)); + var response = + transport + .exchange( + request, + HttpRequest.BodyPublishers.ofString("custom publisher"), + builder -> { + builder.setHeader("Content-Type", "text/plain"); + builder.header("X-Prepared", "yes"); + return CompletableFuture.completedFuture(null); + }) + .get(5, TimeUnit.SECONDS); + assertThat(response.statusCode()).isEqualTo(201); + assertThat(response.version()).isEqualTo(HttpClient.Version.HTTP_1_1); + assertThat(response.headers().firstValue("x-response")).contains("native"); + assertThat(new String(response.body(), StandardCharsets.UTF_8)).isEqualTo("response body"); + var recorded = server.takeRequest(5, TimeUnit.SECONDS); + assertThat(recorded.getBody().utf8()).isEqualTo("custom publisher"); + assertThat(recorded.getHeaders().get("X-Prepared")).isEqualTo("yes"); + } + } + + @Test + void execute_shouldPreserveSynchronousPreparationErrors() { + try (JdkHttpTransport transport = new JdkHttpTransport()) { + IllegalArgumentException error = new IllegalArgumentException("invalid credentials"); + assertThatThrownBy(() -> + transport.execute( + new HttpRequestInfo( + java.net.URI.create("http://localhost/"), "GET", Map.of(), Map.of(), null), + builder -> { + throw error; + })) + .isSameAs(error); + } + } + + @Test + void close_shouldCloseAnOwnedClient() throws Exception { + try (MockWebServer server = new MockWebServer()) { + server.start(); + JdkHttpTransport transport = new JdkHttpTransport(); + transport.close(); + assertThatThrownBy(() -> + transport + .execute( + new HttpRequestInfo( + server.url("/").uri(), "GET", Map.of(), Map.of(), null)) + .get(5, TimeUnit.SECONDS)) + .isInstanceOf(java.util.concurrent.ExecutionException.class); + assertThat(server.getRequestCount()).isZero(); + } + } + + // This example compiles and runs in a module with no engine on its classpath. + private static CompletableFuture thirdPartyCall( + HttpTransport transport, java.net.URI uri) { + return transport.execute( + new HttpRequestInfo( + uri, + "POST", + Map.of("Content-Type", "application/json", "Authorization", "Bearer resolved-token"), + Map.of("search", "café + tea"), + "{\"name\":\"café\"}".getBytes(StandardCharsets.UTF_8))); + } + + @Test + void thirdPartyCall_shouldSendResolvedDataAndExposeErrorResponses() throws Exception { + try (MockWebServer server = new MockWebServer(); + JdkHttpTransport transport = new JdkHttpTransport()) { + server.start(); + server.enqueue( + new MockResponse.Builder() + .code(422) + .addHeader("X-Result", "invalid") + .addHeader("X-Result", "second") + .body("validation details") + .build()); + + cloud.openworkflow.sdk.http.HttpResponse response = + thirdPartyCall(transport, server.url("/items?existing=a%2Bb").uri()) + .get(5, TimeUnit.SECONDS); + + assertThat(response.status()).isEqualTo(422); + assertThat(response.firstHeader("x-result")).isEqualTo("invalid"); + assertThat(response.stringHeaders().get("X-RESULT")).containsExactly("invalid", "second"); + assertThat(new String(response.body(), StandardCharsets.UTF_8)) + .isEqualTo("validation details"); + var recorded = server.takeRequest(5, TimeUnit.SECONDS); + assertThat(recorded.getMethod()).isEqualTo("POST"); + assertThat(recorded.getUrl().encodedQuery()) + .isEqualTo("existing=a%2Bb&search=caf%C3%A9%20%2B%20tea"); + assertThat(recorded.getHeaders().get("Authorization")).isEqualTo("Bearer resolved-token"); + assertThat(recorded.getBody().utf8()).isEqualTo("{\"name\":\"café\"}"); + } + } + + @Test + void execute_shouldUseTheJdkRequestTimeout() throws Exception { + try (MockWebServer server = new MockWebServer(); + JdkHttpTransport transport = new JdkHttpTransport()) { + server.start(); + server.enqueue( + new MockResponse.Builder().headersDelay(1, TimeUnit.SECONDS).body("late").build()); + HttpRequestInfo request = + new HttpRequestInfo(server.url("/").uri(), "GET", Map.of(), Map.of(), null); + assertThatThrownBy( + () -> transport.execute(request, Duration.ofMillis(100)).get(5, TimeUnit.SECONDS)) + .hasCauseInstanceOf(HttpTimeoutException.class); + } + } + + @Test + void cancel_shouldAbandonDeliveryWithoutCancellingPreparationOrClosingSharedClient() + throws Exception { + try (MockWebServer server = new MockWebServer(); + HttpClient client = HttpClient.newHttpClient()) { + server.start(); + server.enqueue(new MockResponse.Builder().body("sent after cancellation").build()); + server.enqueue(new MockResponse.Builder().body("still usable").build()); + JdkHttpTransport transport = new JdkHttpTransport(client); + HttpRequestInfo request = + new HttpRequestInfo(server.url("/").uri(), "GET", Map.of(), Map.of(), null); + CompletableFuture auth = new CompletableFuture<>(); + CompletableFuture cancelled = + transport.execute(request, builder -> auth); + assertThat(cancelled.cancel(true)).isTrue(); + assertThat(auth.isCancelled()).isFalse(); + auth.complete(null); + assertThat(server.takeRequest(5, TimeUnit.SECONDS)).isNotNull(); + assertThat(cancelled.isCancelled()).isTrue(); + transport.close(); + assertThat(new JdkHttpTransport(client).execute(request).get(5, TimeUnit.SECONDS).status()) + .isEqualTo(200); + } + } + + @Test + void execute_shouldPreserveConfiguredRedirectBehavior() throws Exception { + try (MockWebServer server = new MockWebServer(); + JdkHttpTransport normal = new JdkHttpTransport(); + HttpClient client = + HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NEVER).build()) { + server.start(); + HttpRequestInfo request = + new HttpRequestInfo(server.url("/start").uri(), "GET", Map.of(), Map.of(), null); + server.enqueue(new MockResponse.Builder().code(302).addHeader("Location", "/end").build()); + server.enqueue(new MockResponse.Builder().body("redirected").build()); + assertThat( + new String( + normal.execute(request).get(5, TimeUnit.SECONDS).body(), StandardCharsets.UTF_8)) + .isEqualTo("redirected"); + server.enqueue(new MockResponse.Builder().code(302).addHeader("Location", "/end").build()); + assertThat(new JdkHttpTransport(client).execute(request).get(5, TimeUnit.SECONDS).status()) + .isEqualTo(302); + } + } +} diff --git a/common/openapi/README.md b/common/openapi/README.md new file mode 100644 index 000000000..430effa8f --- /dev/null +++ b/common/openapi/README.md @@ -0,0 +1,136 @@ +# OpenAPI calls without the workflow engine + +Other workflow engines can reuse OpenAPI interpretation and request +preparation without creating a workflow application, definition, task or model. + +Use `cloud.openworkflow.sdk:openworkflow-common-openapi:8.0.0-SNAPSHOT` for the +Jackson-free contract. Its only production dependency is `openworkflow-common-http` +in this repository. +Add `openworkflow-impl-openapi` for the existing JSON/YAML reader. +The optional SDK reader lives in `openworkflow-impl-openapi` and brings the SDK +implementation and API serialization dependencies. The common contract has no engine dependency. Existing package names are retained for compatibility. + +## Minimal third-party usage + +```java +import java.util.Map; +import cloud.openworkflow.sdk.api.WorkflowFormat; +import cloud.openworkflow.sdk.http.*; +import cloud.openworkflow.sdk.impl.executors.openapi.*; +import cloud.openworkflow.sdk.impl.executors.openapi.jackson.JacksonUnifiedOpenAPIReader; + +// documentBytes, resolvedParameters and the transport belong to the caller. +UnifiedOpenAPI document = new JacksonUnifiedOpenAPIReader().read("api.yaml", documentBytes); +OpenAPIClient api = new OpenAPIClient(document, "save"); +HttpRequestInfo request = api.prepare(0, resolvedParameters, + body -> WorkflowFormat.JSON.mapper().writeValueAsBytes(body)); +// Inspect the request, use your own HttpTransport, or use JdkHttpTransport / JakartaHttpTransport. +var responseFuture = transport.execute(request); +``` + +`StandaloneOpenAPITest.documentToRequestToInjectedJdkTransport` compiles and runs +this flow against a local server using the SDK Jackson reader. +Provide any `UnifiedOpenAPIReader` to replace Jackson. The contract takes an +explicit body encoder (`Function, byte[]>`), allowing callers +to choose JSON or another serialization without importing Jackson in the contract. +A null body means no entity; the encoder is called only for a present body. +Authentication headers must be declared as header parameters in the document to +be placed there by parameter binding. Alternatively, prepare the request and +supply resolved headers through a new `HttpRequestInfo`, or use the transport's +asynchronous native preparation hook. No authentication policy is inferred from +OpenAPI `security` declarations. + +`OpenAPIProcessor.parse` exposes operation lookup; `OperationDefinition` exposes +the method, path, servers and parameter metadata. `OpenAPIRequest.bind` splits +parameters into per-call path, query, header and body values. `OpenAPIClient.prepare` +selects a server by index and returns `HttpRequestInfo` without networking. +An optional document-origin URI resolves relative server URLs in the standalone +API. The reader never downloads documents or external references; the caller +supplies bytes and preserves their origin. No new cache is introduced. + +## Servers, errors and ownership + +`OpenAPIClient.execute(parameters, encoder, transport, fallback)` additionally +executes asynchronously. Choose `ServerFallback.NONE` to use the first server, +or `ON_HTTP_OR_TRANSPORT_FAILURE` to try subsequent servers after a non-2xx +response or exceptional completion. This policy can **replay POSTs and other +operations with side effects**, even when a server already applied a request. +It is a separate decision from transport execution and workflow retries. + +The final HTTP response, including a non-2xx status, headers and body, remains +`HttpResponse`. Transport failures remain exceptional completions with their +original causes. Preparation/serialization may throw synchronously; absent +operations, missing required parameters, null required path values and empty +server lists produce `IllegalArgumentException`. Malformed documents retain the +reader's parse error. There is no full OpenAPI document/schema validation. +Resolved server URIs must be absolute and contain a host; malformed values such +as `https:/api` are rejected before calling the transport. + +The workflow adapter retains its existing fallback after *any* exceptional +workflow HTTP result, including HTTP status validation and response conversion. +Its `redirect` handling and custom HTTP factories remain unchanged. Thus, a 3xx +accepted by the workflow adapter is not equivalent to a standalone non-2xx +fallback decision. Workflow exceptions and task positions stay in the adapter. + +Operations carry no invocation builder or resolved values. Each binding creates +fresh maps; each request owns its body bytes. Callers must treat documents, +metadata, and nested parameter values as read-only during use. Body serialization +is performed once per `execute`, before network fallback. Calls do not close the +injected transport or client; their owner closes them at application shutdown. +Responses retain buffered original bytes. The caller must close the final response; discarded fallback responses are closed by the client. Cancellation abandons result delivery +without guaranteeing network cancellation or preventing remote side effects. +Transport-specific query/header conversion and redirect behavior retain #1841's +limits; no streaming or stronger cancellation guarantee is added. + +## Existing SDK compatibility + +Existing `UnifiedOpenAPI`, `UnifiedOpenAPIReader`, Jackson reader/mixin class +names, the additional-object key and ServiceLoader entries remain available +transitively through the existing artifacts. `openworkflow-impl-openapi` still +registers the reader with the application; the Jackson module service and native-image reflection registrations remain +with the SDK reader. +Custom readers continue to work unchanged. + +The SDK delegates operation interpretation and parameter binding to this module. +It retains DSL interpretation, expression evaluation, resource and secret +resolution, document-fetch authentication, API-call authentication, model +conversion, response/error enrichment and retries. Document and API credentials +are resolved independently. Each invocation copies the initialized workflow HTTP +builder template, preserving authentication-provider lifetime and build-time +validation while isolating mutable builder fields. The existing default URI-template implementation is reused through a +compatibility delegate; custom URI-template resolvers continue to run in the SDK. + +## Actual supported subset + +This extraction preserves the existing subset rather than adding a complete +OpenAPI implementation: + +- Swagger 2.x and the existing OpenAPI 3-style model; JSON for `.json` names, + YAML otherwise. Version numbers are not strictly validated. +- Swagger host/basePath and the first scheme (HTTPS when absent), or OpenAPI + server URLs selected from operation, path item, then root. Empty server lists + fail. Server variables are not expanded. +- Operation lookup by `operationId` for GET, POST, PUT, DELETE, PATCH, HEAD and + OPTIONS. Path-item parameters are inherited; operation parameters override + inherited entries with the same location and name. +- Path, query and header parameters, including chained local parameter references + from Swagger `#/parameters/` and OpenAPI `#/components/parameters/`. + A supplied name can populate multiple locations. Required missing parameters + use `schema.default` when present, otherwise fail. Optional defaults are not + applied. Required null path values fail after expression resolution in the SDK. + Other null headers are omitted and null queries become empty strings. +- Existing URI-template expansion for paths; query values use the selected HTTP + transport's encoding. No OpenAPI `style`, `explode`, collection-format or + cookie serialization. Unsupported/unconsumed values remain in the body map. +- Swagger body schema properties and OpenAPI `application/json` request-body + properties are exposed as metadata. Remaining arguments form the body map; + required body fields and body defaults are not validated/applied. A request + body declaration can cause an empty body map to be sent. No general media-type + negotiation or generated clients; standalone serialization is caller-supplied. +- Direct local body-schema references to `#/definitions/` and + `#/components/schemas/` only. No nested schema, external or request-body + reference resolution, implicit reference downloads, or security-scheme handling. + +The tests characterize the supported subset and deliberately preserve its +limitations. Expanding conformance or changing replay policy requires a separate +behavior change. diff --git a/common/openapi/pom.xml b/common/openapi/pom.xml new file mode 100644 index 000000000..b7826bff3 --- /dev/null +++ b/common/openapi/pom.xml @@ -0,0 +1,26 @@ + + 4.0.0 + + cloud.openworkflow.sdk + openworkflow-common + 8.0.0-SNAPSHOT + + openworkflow-common-openapi + Open Workflow :: OpenAPI Client + + + cloud.openworkflow.sdk + openworkflow-common-http + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.assertj + assertj-core + test + + + diff --git a/common/openapi/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIClient.java b/common/openapi/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIClient.java new file mode 100644 index 000000000..8272390ca --- /dev/null +++ b/common/openapi/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIClient.java @@ -0,0 +1,148 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.impl.executors.openapi; + +import cloud.openworkflow.sdk.http.HttpRequestInfo; +import cloud.openworkflow.sdk.http.HttpTransport; +import java.net.URI; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.function.Function; + +/** OpenAPI request preparation and asynchronous execution using caller-owned HTTP resources. */ +public final class OpenAPIClient { + /** Legacy fallback may replay operations with side effects, including after HTTP errors. */ + public enum ServerFallback { + NONE, + ON_HTTP_OR_TRANSPORT_FAILURE + } + + private final OperationDefinition operation; + private final URI documentOrigin; + + public OpenAPIClient(UnifiedOpenAPI document, String operationId) { + this(document, operationId, null); + } + + /** Origin is optional and used only to resolve relative server URLs; no resources are loaded. */ + public OpenAPIClient(UnifiedOpenAPI document, String operationId, URI documentOrigin) { + this.operation = new OpenAPIProcessor(operationId).parse(Objects.requireNonNull(document)); + this.documentOrigin = documentOrigin; + } + + public OperationDefinition operation() { + return operation; + } + + public HttpRequestInfo prepare( + int serverIndex, + Map resolvedParameters, + Function, byte[]> bodyEncoder) { + return OpenAPIRequest.bind(operation, resolvedParameters) + .prepare(server(serverIndex), bodyEncoder); + } + + private URI server(int index) { + List servers = operation.getServers(); + if (servers.isEmpty()) throw new IllegalArgumentException("List of servers is empty"); + URI server = URI.create(servers.get(index)); + if (!server.isAbsolute()) { + if (documentOrigin == null) + throw new IllegalArgumentException( + "Relative OpenAPI server requires a document origin: " + server); + server = documentOrigin.resolve(server); + } + return server; + } + + /** + * Does not close the injected transport. HTTP errors remain responses; only transport or + * preparation errors complete exceptionally. Fallback is distinct from workflow retries. + * Cancellation abandons delivery and does not guarantee network cancellation. + */ + public CompletableFuture execute( + Map resolvedParameters, + Function, byte[]> bodyEncoder, + HttpTransport transport, + ServerFallback fallback) { + Objects.requireNonNull(transport); + Objects.requireNonNull(fallback); + // Serialize once per invocation, before any asynchronous fallback can observe caller mutations. + OpenAPIRequest bound = OpenAPIRequest.bind(operation, resolvedParameters); + byte[] encodedBody = bound.body() == null ? null : bodyEncoder.apply(bound.body()); + byte[] body = encodedBody == null ? null : encodedBody.clone(); + if (fallback == ServerFallback.NONE || operation.getServers().size() <= 1) + return execute(bound, body, transport, fallback, 0); + CompletableFuture delivery = + new CompletableFuture<>(); + execute(bound, body, transport, fallback, 0) + .whenComplete((response, error) -> { + if (error != null) delivery.completeExceptionally(error); + else if (!delivery.complete(response)) response.close(); + }); + return delivery; + } + + private CompletableFuture execute( + OpenAPIRequest bound, + byte[] body, + HttpTransport transport, + ServerFallback fallback, + int index) { + CompletableFuture attempt; + try { + attempt = transport.execute(bound.prepare(server(index), ignored -> body)); + } catch (RuntimeException e) { + attempt = CompletableFuture.failedFuture(e); + } + if (fallback == ServerFallback.NONE || index + 1 >= operation.getServers().size()) + return attempt; + return attempt + .handle((response, error) -> { + if (error != null) return execute(bound, body, transport, fallback, index + 1); + int status; + try { + status = response.status(); + } catch (RuntimeException | Error inspection) { + try { + response.close(); + } catch (RuntimeException | Error cleanup) { + if (cleanup != inspection) inspection.addSuppressed(cleanup); + } + return CompletableFuture.failedFuture( + inspection); + } + if (status < 200 || status >= 300) { + if (response != null) { + try { + response.close(); + } catch (RuntimeException | Error cleanup) { + // Cleanup must not veto the explicitly selected server fallback. + return execute(bound, body, transport, fallback, index + 1) + .whenComplete((next, failure) -> { + if (failure != null && failure != cleanup) failure.addSuppressed(cleanup); + }); + } + } + return execute(bound, body, transport, fallback, index + 1); + } + return CompletableFuture.completedFuture(response); + }) + .thenCompose(Function.identity()); + } +} diff --git a/common/openapi/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIPathResolver.java b/common/openapi/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIPathResolver.java new file mode 100644 index 000000000..97e54d66f --- /dev/null +++ b/common/openapi/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIPathResolver.java @@ -0,0 +1,618 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.impl.executors.openapi; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class OpenAPIPathResolver { + + public URI resolveTemplates(String uri, Map map) { + return URI.create(expandImpl(uri, map)); + } + + // Private implementation + private enum Operator { + NO_OP, + PLUS, + HASH, + DOT, + SLASH, + SEMICOLON, + QUESTION_MARK, + AMP; + } + + private static void checkVarname(String token, int col) { + if (token.startsWith(".") || token.endsWith(".")) { + throw new IllegalArgumentException( + "Variable name cannot start or end with a dot at col:" + col); + } + if (token.contains("..")) { + throw new IllegalArgumentException( + "Variable name cannot contain consecutive dots at col:" + col); + } + for (int i = 0; i < token.length(); i++) { + if (token.charAt(i) == '%') { + if (i + 2 >= token.length() + || !isHexDigit(token.charAt(i + 1)) + || !isHexDigit(token.charAt(i + 2))) { + throw new IllegalArgumentException( + "Invalid percent-encoding in variable name at col:" + col); + } + } + } + } + + private static boolean isHexDigit(char c) { + return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); + } + + private static void validateLiteral(Character c, int col) { + switch (c) { + case '+': + case '#': + case '/': + case ';': + case '?': + case '&': + case ' ': + case '!': + case '=': + case '$': + case '|': + case '*': + case ':': + case '~': + throw new IllegalArgumentException( + "Illegal character identified in the token at col:" + col); + default: + break; + } + } + + private static int getMaxChar(StringBuilder buffer, int col) { + if (buffer == null || buffer.length() == 0) { + return -1; + } else { + String value = buffer.toString(); + + if (value.isEmpty()) { + return -1; + } else { + try { + if (value.charAt(0) == '0') { + throw new IllegalArgumentException( + "Leading zero not allowed in max chars at col:" + col); + } + int result = Integer.parseInt(value); + if (result < 1 || result > 9999) { + throw new IllegalArgumentException("Max chars out of range (1-9999) at col:" + col); + } + return result; + } catch (NumberFormatException e) { + throw new IllegalArgumentException("Cannot parse max chars at col:" + col); + } + } + } + } + + private static Operator getOperator(Character c, StringBuilder token, int col) { + switch (c) { + case '+': + return Operator.PLUS; + case '#': + return Operator.HASH; + case '.': + return Operator.DOT; + case '/': + return Operator.SLASH; + case ';': + return Operator.SEMICOLON; + case '?': + return Operator.QUESTION_MARK; + case '&': + return Operator.AMP; + default: + validateLiteral(c, col); + token.append(c); + return Operator.NO_OP; + } + } + + private static String expandImpl(String str, Map substitutions) { + final StringBuilder result = new StringBuilder(str.length() * 2); + + boolean toToken = false; + final StringBuilder token = new StringBuilder(); + + Operator operator = null; + boolean composite = false; + boolean toMaxCharBuffer = false; + final StringBuilder maxCharBuffer = new StringBuilder(3); + boolean firstToken = true; + + for (int i = 0; i < str.length(); i++) { + char character = str.charAt(i); + switch (character) { + case '{': + toToken = true; + token.setLength(0); + firstToken = true; + break; + case '}': + if (toToken) { + if (toMaxCharBuffer && maxCharBuffer.length() == 0) { + throw new IllegalArgumentException("Empty prefix modifier at col:" + i); + } + boolean expanded = + expandToken( + operator, + token.toString(), + composite, + getMaxChar(maxCharBuffer, i), + firstToken, + substitutions, + result, + i); + if (expanded && firstToken) { + firstToken = false; + } + toToken = false; + token.setLength(0); + operator = null; + composite = false; + toMaxCharBuffer = false; + maxCharBuffer.setLength(0); + } else { + throw new IllegalArgumentException("Failed to expand token, invalid at col:" + i); + } + break; + case ',': + if (toToken) { + if (toMaxCharBuffer && maxCharBuffer.length() == 0) { + throw new IllegalArgumentException("Empty prefix modifier at col:" + i); + } + boolean expanded = + expandToken( + operator, + token.toString(), + composite, + getMaxChar(maxCharBuffer, i), + firstToken, + substitutions, + result, + i); + if (expanded && firstToken) { + firstToken = false; + } + token.setLength(0); + composite = false; + toMaxCharBuffer = false; + maxCharBuffer.setLength(0); + break; + } + // Intentional fall-through for commas outside the {} + default: + if (toToken) { + if (operator == null) { + operator = getOperator(character, token, i); + } else if (toMaxCharBuffer) { + if (Character.isDigit(character)) { + maxCharBuffer.append(character); + } else { + throw new IllegalArgumentException( + "Illegal character identified in the token at col:" + i); + } + } else { + if (character == ':') { + toMaxCharBuffer = true; + maxCharBuffer.setLength(0); + } else if (character == '*') { + composite = true; + } else { + validateLiteral(character, i); + token.append(character); + } + } + } else { + if (character > 0x7F || Character.isHighSurrogate(character)) { + String toEncode; + if (Character.isHighSurrogate(character) + && i + 1 < str.length() + && Character.isLowSurrogate(str.charAt(i + 1))) { + toEncode = new String(new char[] {character, str.charAt(++i)}); + } else { + toEncode = Character.toString(character); + } + for (byte b : toEncode.getBytes(StandardCharsets.UTF_8)) { + result.append(String.format("%%%02X", b & 0xFF)); + } + } else { + result.append(character); + } + } + break; + } + } + + if (!toToken) { + return result.toString(); + } else { + throw new IllegalArgumentException("Unterminated token"); + } + } + + private static void addPrefix(Operator op, StringBuilder result) { + switch (op) { + case HASH: + result.append('#'); + break; + case DOT: + result.append('.'); + break; + case SLASH: + result.append('/'); + break; + case SEMICOLON: + result.append(';'); + break; + case QUESTION_MARK: + result.append('?'); + break; + case AMP: + result.append('&'); + break; + default: + return; + } + } + + private static void addSeparator(Operator op, StringBuilder result) { + switch (op) { + case DOT: + result.append('.'); + break; + case SLASH: + result.append('/'); + break; + case SEMICOLON: + result.append(';'); + break; + case QUESTION_MARK: + case AMP: + result.append('&'); + break; + default: + result.append(','); + return; + } + } + + private static void addValue( + Operator op, String token, Object value, StringBuilder result, int maxChar) { + switch (op) { + case PLUS: + case HASH: + addExpandedValue(null, value, result, maxChar, false); + break; + case QUESTION_MARK: + case AMP: + result.append(token + '='); + addExpandedValue(null, value, result, maxChar, true); + break; + case SEMICOLON: + result.append(token); + addExpandedValue("=", value, result, maxChar, true); + break; + case DOT: + case SLASH: + case NO_OP: + addExpandedValue(null, value, result, maxChar, true); + } + } + + private static void addValueElement( + Operator op, String token, Object value, StringBuilder result, int maxChar) { + switch (op) { + case PLUS: + case HASH: + addExpandedValue(null, value, result, maxChar, false); + break; + case QUESTION_MARK: + case AMP: + case SEMICOLON: + case DOT: + case SLASH: + case NO_OP: + addExpandedValue(null, value, result, maxChar, true); + } + } + + private static boolean isSurrogate(char cp) { + return (cp >= 0xD800 && cp <= 0xDFFF); + } + + private static boolean isIprivate(char cp) { + return (0xE000 <= cp && cp <= 0xF8FF); + } + + private static boolean isUcschar(char cp) { + return (0xA0 <= cp && cp <= 0xD7FF) + || (0xF900 <= cp && cp <= 0xFDCF) + || (0xFDF0 <= cp && cp <= 0xFFEF); + } + + private static void addExpandedValue( + String prefix, Object value, StringBuilder result, int maxChar, boolean replaceReserved) { + String stringValue = convertNativeTypes(value); + int cpCount = stringValue.codePointCount(0, stringValue.length()); + int max = (maxChar != -1) ? Math.min(maxChar, cpCount) : cpCount; + result.ensureCapacity(max * 2); // hint to SB + boolean toReserved = false; + final StringBuilder reservedBuffer = new StringBuilder(3); + + if (max > 0 && prefix != null) { + result.append(prefix); + } + + int charCount = 0; + for (int i = 0; i < stringValue.length() && charCount < max; i++) { + char character = stringValue.charAt(i); + charCount++; + + if (character == '%' && !replaceReserved) { + toReserved = true; + reservedBuffer.setLength(0); + } + + String toAppend = Character.toString(character); + try { + if (isSurrogate(character)) { + StringBuilder sb = new StringBuilder(); + sb.append(Character.toChars(stringValue.codePointAt(i++))); + toAppend = URLEncoder.encode(sb.toString(), StandardCharsets.UTF_8.name()); + } else if (replaceReserved || isUcschar(character) || isIprivate(character)) { + toAppend = + URLEncoder.encode(toAppend, StandardCharsets.UTF_8.name()) + .replace("*", "%2A") + .replace("%7E", "~"); + } + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + + if (toReserved) { + reservedBuffer.append(toAppend); + + if (reservedBuffer.length() == 3) { + boolean isEncoded = false; + try { + URLDecoder.decode(reservedBuffer.toString(), StandardCharsets.UTF_8.name()); + isEncoded = true; + } catch (Exception e) { + // ignore + } + + if (isEncoded) { + result.append(reservedBuffer); + } else { + result.append("%25"); + // only if !replaceReserved + result.append(reservedBuffer.substring(1)); + } + toReserved = false; + reservedBuffer.setLength(0); + } + } else { + if (character == ' ') { + result.append("%20"); + } else if (character == '%') { + result.append("%25"); + } else { + result.append(toAppend); + } + } + } + + if (toReserved) { + result.append("%25"); + result.append(reservedBuffer.substring(1)); + } + } + + private static boolean isList(Object value) { + return value instanceof ArrayList + || // checking concrete instances first as it's faster + value instanceof List; + } + + private static boolean isMap(Object value) { + return value instanceof HashMap + || // checking concrete instances first as it's faster + value instanceof Map; + } + + enum SubstitutionType { + EMPTY, + STRING, + LIST, + MAP; + } + + private static SubstitutionType getSubstitutionType(Object value, int col) { + if (value == null) { + return SubstitutionType.EMPTY; + } else if (isNativeType(value)) { + return SubstitutionType.STRING; + } else if (isList(value)) { + return SubstitutionType.LIST; + } else if (isMap(value)) { + return SubstitutionType.MAP; + } else { + throw new IllegalArgumentException( + "Illegal class passed as substitution, found " + value.getClass() + " at col:" + col); + } + } + + private static boolean isEmpty(SubstitutionType substType, Object value) { + if (value == null) { + return true; + } else { + switch (substType) { + case STRING: + return false; + case LIST: + return ((List) value).isEmpty(); + case MAP: + return ((Map) value).isEmpty(); + default: + return true; + } + } + } + + private static boolean isNativeType(Object value) { + if (value instanceof String || value instanceof Boolean || value instanceof Number) { + return true; + } + return false; + } + + private static String convertNativeTypes(Object value) { + if (value instanceof String) { + return (String) value; + } else if (value instanceof Boolean || value instanceof Number) { + return value.toString(); + } + throw new IllegalArgumentException( + "Illegal class passed as substitution, found " + value.getClass()); + } + + // returns true if expansion happened + private static boolean expandToken( + Operator operator, + String token, + boolean composite, + int maxChar, + boolean firstToken, + Map substitutions, + StringBuilder result, + int col) { + if (token.isEmpty()) { + throw new IllegalArgumentException("Found an empty token at col:" + col); + } + + checkVarname(token, col); + + Object value = substitutions.get(token); + SubstitutionType substType = getSubstitutionType(value, col); + if (substType == SubstitutionType.EMPTY || isEmpty(substType, value)) { + return false; + } + + if (firstToken) { + addPrefix(operator, result); + } else { + addSeparator(operator, result); + } + + switch (substType) { + case STRING: + addStringValue(operator, token, (Object) value, result, maxChar); + break; + case LIST: + addListValue(operator, token, (List) value, result, maxChar, composite); + break; + case MAP: + addMapValue(operator, token, (Map) value, result, maxChar, composite); + break; + } + + return true; + } + + private static boolean addStringValue( + Operator operator, String token, Object value, StringBuilder result, int maxChar) { + addValue(operator, token, value, result, maxChar); + return true; + } + + private static boolean addListValue( + Operator operator, + String token, + List value, + StringBuilder result, + int maxChar, + boolean composite) { + boolean first = true; + for (Object v : value) { + if (first) { + addValue(operator, token, v, result, maxChar); + first = false; + } else { + if (composite) { + addSeparator(operator, result); + addValue(operator, token, v, result, maxChar); + } else { + result.append(','); + addValueElement(operator, token, v, result, maxChar); + } + } + } + return !first; + } + + private static boolean addMapValue( + Operator operator, + String token, + Map value, + StringBuilder result, + int maxChar, + boolean composite) { + boolean first = true; + if (maxChar != -1) { + throw new IllegalArgumentException("Value trimming is not allowed on Maps"); + } + for (Map.Entry v : value.entrySet()) { + if (composite) { + if (!first) { + addSeparator(operator, result); + } + addValueElement(operator, token, v.getKey(), result, maxChar); + result.append('='); + } else { + if (first) { + addValue(operator, token, v.getKey(), result, maxChar); + } else { + result.append(','); + addValueElement(operator, token, v.getKey(), result, maxChar); + } + result.append(','); + } + addValueElement(operator, token, v.getValue(), result, maxChar); + first = false; + } + return !first; + } +} diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIProcessor.java b/common/openapi/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIProcessor.java similarity index 88% rename from impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIProcessor.java rename to common/openapi/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIProcessor.java index 3a7b0b94f..1577c6e44 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIProcessor.java +++ b/common/openapi/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIProcessor.java @@ -18,15 +18,15 @@ import java.util.Objects; import java.util.Optional; -class OpenAPIProcessor { +public class OpenAPIProcessor { private final String operationId; - OpenAPIProcessor(String operationId) { + public OpenAPIProcessor(String operationId) { this.operationId = Objects.requireNonNull(operationId); } - OperationDefinition parse(UnifiedOpenAPI unifiedOpenAPI) { + public OperationDefinition parse(UnifiedOpenAPI unifiedOpenAPI) { Optional operationDefinition = unifiedOpenAPI.findOperationById(this.operationId); return operationDefinition.orElseThrow(() -> diff --git a/common/openapi/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIRequest.java b/common/openapi/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIRequest.java new file mode 100644 index 000000000..32ca5bdd0 --- /dev/null +++ b/common/openapi/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIRequest.java @@ -0,0 +1,152 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.impl.executors.openapi; + +import cloud.openworkflow.sdk.http.HttpRequestInfo; +import java.net.URI; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.function.Function; + +/** + * Per-invocation values. No expression evaluation or authentication policy resolution occurs here. + */ +public record OpenAPIRequest( + String method, + String path, + Map pathParameters, + Set mandatoryParameters, + Map headers, + Map queryParameters, + Map body) { + + public OpenAPIRequest { + pathParameters = copy(pathParameters); + mandatoryParameters = Set.copyOf(mandatoryParameters); + headers = copy(headers); + queryParameters = copy(queryParameters); + body = body == null ? null : copy(body); + } + + private static Map copy(Map values) { + return Collections.unmodifiableMap(new LinkedHashMap<>(values)); + } + + /** Preserves the SDK's parameter placement, required/default and leftover-body rules. */ + public static OpenAPIRequest bind(OperationDefinition operation, Map parameters) { + Map body = new LinkedHashMap<>(parameters); + Map headers = new LinkedHashMap<>(); + Map query = new LinkedHashMap<>(); + Map path = new LinkedHashMap<>(); + Set mandatory = new HashSet<>(); + Set missing = new HashSet<>(); + boolean hasBody = operation.getOperation().hasRequestBody(); + for (ParameterDefinition parameter : operation.getParameters()) { + Map target = + switch (parameter.in()) { + case "header" -> headers; + case "path" -> path; + case "query" -> query; + default -> null; + }; + if ("body".equals(parameter.in())) { + hasBody = true; + } + if (target == null) { + continue; + } + String name = parameter.name(); + if (parameter.required()) { + mandatory.add(name); + } + if (parameters.containsKey(name)) { + target.put(name, parameters.get(name)); + body.remove(name); + } else if (parameter.required()) { + Object value = parameter.schema() == null ? null : parameter.schema()._default(); + if (value == null) { + missing.add(name); + } else { + target.put(name, value); + } + } + } + if (!missing.isEmpty()) { + throw new IllegalArgumentException( + "Missing required OpenAPI parameters for operation '" + + operation.getOperation().operationId() + + "': " + + missing); + } + return new OpenAPIRequest( + operation.getMethod(), + operation.getPath(), + path, + mandatory, + headers, + query, + hasBody || !body.isEmpty() ? body : null); + } + + /** + * Prepares a buffered request for a resolved server URI. The encoder receives the body map only + * when an entity is present; callers choose serialization without a JSON dependency. Nested input + * values must not be mutated while preparing a call. + */ + public HttpRequestInfo prepare( + URI server, Function, byte[]> bodyEncoder) { + if (!server.isAbsolute() || server.getHost() == null) { + throw new IllegalArgumentException( + "OpenAPI server requires an absolute URI with a host: " + server); + } + var nullPaths = + pathParameters.entrySet().stream() + .filter(e -> e.getValue() == null && mandatoryParameters.contains(e.getKey())) + .map(Map.Entry::getKey) + .toList(); + if (!nullPaths.isEmpty()) { + throw new IllegalArgumentException( + "Following mandatory OpenAPI path parameters has null values after expression resolution " + + nullPaths); + } + URI child = new OpenAPIPathResolver().resolveTemplates(path, pathParameters); + URI uri; + if (child.isAbsolute()) { + // Preserve WorkflowUtils.concatURI behavior: a resolved absolute path overrides the base. + // Server selection is not an origin allowlist; document trust remains the caller's policy. + uri = child; + } else { + String basePath = server.getRawPath(); + if (basePath == null || basePath.isEmpty()) basePath = "/"; + if (!basePath.endsWith("/")) basePath += "/"; + String relative = child.toString(); + while (relative.startsWith("/")) relative = relative.substring(1); + uri = URI.create(server.getScheme() + "://" + server.getRawAuthority() + basePath + relative); + } + Map normalizedHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + headers.forEach((name, value) -> { + if (value != null) normalizedHeaders.put(name, value); + }); + Map query = new LinkedHashMap<>(); + queryParameters.forEach((name, value) -> query.put(name, value == null ? "" : value)); + return new HttpRequestInfo( + uri, method, normalizedHeaders, query, body == null ? null : bodyEncoder.apply(body)); + } +} diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OperationDefinition.java b/common/openapi/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OperationDefinition.java similarity index 91% rename from impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OperationDefinition.java rename to common/openapi/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OperationDefinition.java index b466cc036..d7f129061 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OperationDefinition.java +++ b/common/openapi/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OperationDefinition.java @@ -21,7 +21,7 @@ import java.util.Map; import java.util.Objects; -class OperationDefinition { +public class OperationDefinition { private final UnifiedOpenAPI.Operation operation; private final UnifiedOpenAPI.PathItem pathItem; @@ -29,7 +29,17 @@ class OperationDefinition { private final UnifiedOpenAPI openAPI; private final String path; - OperationDefinition( + public OperationDefinition( + UnifiedOpenAPI openAPI, UnifiedOpenAPI.Operation operation, String path, String method) { + this( + openAPI, + openAPI.paths() == null ? null : openAPI.paths().get(path), + operation, + path, + method); + } + + public OperationDefinition( UnifiedOpenAPI openAPI, UnifiedOpenAPI.PathItem pathItem, UnifiedOpenAPI.Operation operation, @@ -43,19 +53,19 @@ class OperationDefinition { this.method = Objects.requireNonNull(method, "method cannot be null"); } - String getMethod() { + public String getMethod() { return method; } - String getPath() { + public String getPath() { return path; } - UnifiedOpenAPI.Operation getOperation() { + public UnifiedOpenAPI.Operation getOperation() { return operation; } - List getServers() { + public List getServers() { if (openAPI.swaggerVersion() == UnifiedOpenAPI.SwaggerVersion.OPENAPI_V3) { if (operation.servers() != null && !operation.servers().isEmpty()) { return toUrls(operation.servers()); @@ -89,7 +99,7 @@ private void merge(Map merged, UnifiedOpenAPI. merged.put(resolved.in() + ":" + resolved.name(), resolved); } - List getParameters() { + public List getParameters() { List allParameters = mergedParameters(); List paramDefinitions = new ArrayList<>(); for (UnifiedOpenAPI.Parameter parameter : allParameters) { diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/ParameterDefinition.java b/common/openapi/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/ParameterDefinition.java similarity index 95% rename from impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/ParameterDefinition.java rename to common/openapi/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/ParameterDefinition.java index 41b87ad65..0a7e7a1d2 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/ParameterDefinition.java +++ b/common/openapi/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/ParameterDefinition.java @@ -15,5 +15,5 @@ */ package cloud.openworkflow.sdk.impl.executors.openapi; -record ParameterDefinition( +public record ParameterDefinition( String name, String in, boolean required, UnifiedOpenAPI.Schema schema) {} diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/UnifiedOpenAPI.java b/common/openapi/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/UnifiedOpenAPI.java similarity index 100% rename from impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/UnifiedOpenAPI.java rename to common/openapi/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/UnifiedOpenAPI.java diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/UnifiedOpenAPIReader.java b/common/openapi/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/UnifiedOpenAPIReader.java similarity index 100% rename from impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/UnifiedOpenAPIReader.java rename to common/openapi/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/UnifiedOpenAPIReader.java diff --git a/common/openapi/src/test/java/cloud/openworkflow/sdk/impl/executors/openapi/CustomOpenAPIReaderTest.java b/common/openapi/src/test/java/cloud/openworkflow/sdk/impl/executors/openapi/CustomOpenAPIReaderTest.java new file mode 100644 index 000000000..30167b8a7 --- /dev/null +++ b/common/openapi/src/test/java/cloud/openworkflow/sdk/impl/executors/openapi/CustomOpenAPIReaderTest.java @@ -0,0 +1,58 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.impl.executors.openapi; + +import static org.assertj.core.api.Assertions.*; + +import java.net.URI; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +class CustomOpenAPIReaderTest { + @Test + void preparesWithAConsumerReaderWithoutTheEngine() { + UnifiedOpenAPIReader reader = + (name, bytes) -> + new UnifiedOpenAPI( + null, + List.of(new UnifiedOpenAPI.Server("https://example.test")), + null, + null, + null, + Map.of( + "/items", + new UnifiedOpenAPI.PathItem( + null, + null, + new UnifiedOpenAPI.Operation("list", null, null, null), + null, + null, + null, + null, + null, + null)), + null, + null, + null); + var request = + new OpenAPIClient(reader.read("custom", new byte[0]), "list") + .prepare(0, Map.of(), ignored -> new byte[0]); + assertThat(request.uri()).isEqualTo(URI.create("https://example.test/items")); + assertThatExceptionOfType(ClassNotFoundException.class) + .isThrownBy(() -> Class.forName("cloud.openworkflow.sdk.impl.WorkflowApplication")); + } +} diff --git a/common/pom.xml b/common/pom.xml new file mode 100644 index 000000000..ec4afb4ee --- /dev/null +++ b/common/pom.xml @@ -0,0 +1,6 @@ + + 4.0.0 + cloud.openworkflow.sdkopenworkflow-parent8.0.0-SNAPSHOT + openworkflow-commonpomOpen Workflow :: Common + httphttp-jakartaopenapi + diff --git a/impl/README.md b/impl/README.md index a1d944f3c..bd89e1150 100644 --- a/impl/README.md +++ b/impl/README.md @@ -112,6 +112,10 @@ There are also companion modules/docs for: ### Http dependencies +For HTTP execution from another engine without workflow contexts, use the +[standalone HTTP client](../common/http/README.md). The existing workflow HTTP APIs +remain adapters over the same transports. + By default, the SDK reference implementation use `java.net.HttpRequest` to support Http/OpenAPI calls. Therefore, no dependency (besides the jackson modules described above) needs to be added for using Http Call task or downloading http resources. However, for further configuration of Http functionality, users might include the Jakarta based modules, which will allow customizing `jakarta.ws.rs.client.Client` in Jakarta EE environments. @@ -181,8 +185,8 @@ Workflow output is {"id":10,"category":{"id":10,"name":"string"},"name":"doggie" Full examples: -* Blocking: [examples/simpleGet/src/main/java/org/openworkflow/sdk/impl/BlockingExample.java]() -* Non-blocking: [examples/simpleGet/src/main/java/org/openworkflow/sdk/impl/NotBlockingExample.java]() +* Blocking: [examples/simpleGet/src/main/java/cloud/openworkflow/sdk/impl/BlockingExample.java]() +* Non-blocking: [examples/simpleGet/src/main/java/cloud/openworkflow/sdk/impl/NotBlockingExample.java]() --- @@ -225,7 +229,7 @@ Source: `examples/events/src/main/java/events/EventExample.java` ## Workflow execution control -As shown in previous examples, to start a new workflow instance, first a [WorkflowInstance](https://github.com/open-workflow-specification/sdk-java/blob/main/impl/core/src/main/java/org/openworkflow/sdk/impl/WorkflowInstance.java) is created from a [WorkflowDefinition](https://github.com/open-workflow-specification/sdk-java/blob/main/impl/core/src/main/java/org/openworkflow/sdk/impl/WorkflowDefinition.java#L74), specifying the desired input, and then start method is invoked over it. Start method returns a CompletableFuture, which might be used to obtain the output, either synchronously or asynchronously. +As shown in previous examples, to start a new workflow instance, first a [WorkflowInstance](https://github.com/open-workflow-specification/sdk-java/blob/main/impl/core/src/main/java/cloud/openworkflow/sdk/impl/WorkflowInstance.java) is created from a [WorkflowDefinition](https://github.com/open-workflow-specification/sdk-java/blob/main/impl/core/src/main/java/cloud/openworkflow/sdk/impl/WorkflowDefinition.java#L74), specifying the desired input, and then start method is invoked over it. Start method returns a CompletableFuture, which might be used to obtain the output, either synchronously or asynchronously. Once started, and before it completes, a workflow instance execution can be suspended or cancelled. Once cancelled, a workflow instance is done, while a suspended one might be resumed. diff --git a/impl/core/pom.xml b/impl/core/pom.xml index b151e0616..2faf22673 100644 --- a/impl/core/pom.xml +++ b/impl/core/pom.xml @@ -8,6 +8,15 @@ openworkflow-impl-core Open Workflow :: Impl :: Core + + cloud.openworkflow.sdk + openworkflow-common-openapi + + + + cloud.openworkflow.sdk + openworkflow-common-http + cloud.openworkflow.sdk openworkflow-types diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIExecutor.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIExecutor.java index b081b95f0..e268c325f 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIExecutor.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIExecutor.java @@ -25,19 +25,17 @@ import cloud.openworkflow.sdk.impl.http.WorkflowHttpRequestInfo.Builder; import cloud.openworkflow.sdk.impl.http.WorkflowHttpRequestInfoBuilderFactory; import java.net.URI; -import java.util.HashMap; -import java.util.HashSet; import java.util.Iterator; import java.util.Map; -import java.util.Set; import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; class OpenAPIExecutor implements CallableTask { private final OpenAPIProcessor processor; private final ExternalResource resource; private final Map parameters; - private final WorkflowHttpRequestInfoBuilderFactory builder; + private final Supplier builderFactory; private final UnifiedOpenAPIReader openAPIReader; OpenAPIExecutor( @@ -45,12 +43,12 @@ class OpenAPIExecutor implements CallableTask { OpenAPIProcessor processor, ExternalResource resource, Map parameters, - WorkflowHttpRequestInfoBuilderFactory builder) { + Supplier builderFactory) { this.openAPIReader = openAPIReader; this.processor = processor; this.resource = resource; this.parameters = parameters; - this.builder = builder; + this.builderFactory = builderFactory; } @Override @@ -63,7 +61,9 @@ public CompletableFuture apply( .thenApply(u -> processor.parse(u)) .thenComposeAsync( operationDefinition -> { - fillHttpBuilder(workflowContext.definition().application(), operationDefinition); + WorkflowHttpRequestInfoBuilderFactory builder = builderFactory.get(); + fillHttpBuilder( + workflowContext.definition().application(), operationDefinition, builder); Builder httpInfoBuilder = builder.build(workflowContext, taskContext, input); Iterator iter = operationDefinition.getServers().iterator(); @@ -86,73 +86,21 @@ public CompletableFuture apply( workflowContext.definition().application().executorService()); } - private void fillHttpBuilder(WorkflowApplication application, OperationDefinition operation) { - Map headers = new HashMap<>(); - Map queryMap = new HashMap<>(); - Map pathParameters = new HashMap<>(); - Set mandatoryParameters = new HashSet<>(); - Set missingParams = new HashSet<>(); - boolean hasBody = operation.getOperation().hasRequestBody(); - Map bodyParameters = new HashMap<>(parameters); - - // Parameters are unique per (in, name) - for (ParameterDefinition parameter : operation.getParameters()) { - switch (parameter.in()) { - case "header": - param(parameter, bodyParameters, headers, missingParams, mandatoryParameters); - break; - case "path": - param(parameter, bodyParameters, pathParameters, missingParams, mandatoryParameters); - break; - case "query": - param(parameter, bodyParameters, queryMap, missingParams, mandatoryParameters); - break; - case "body": - hasBody = true; - break; - } - } - - if (!missingParams.isEmpty()) { - throw new IllegalArgumentException( - "Missing required OpenAPI parameters for operation '" - + (operation.getOperation().operationId() != null - ? operation.getOperation().operationId() - : "" + "': ") - + missingParams); - } + private void fillHttpBuilder( + WorkflowApplication application, + OperationDefinition operation, + WorkflowHttpRequestInfoBuilderFactory builder) { + OpenAPIRequest request = OpenAPIRequest.bind(operation, parameters); builder - .withBody(hasBody || !bodyParameters.isEmpty() ? bodyParameters : null) - .withQueryMap(!queryMap.isEmpty() ? queryMap : null) - .withHeaders(!headers.isEmpty() ? headers : null) - .withMethod(operation.getMethod()) + .withBody(request.body()) + .withQueryMap(request.queryParameters()) + .withHeaders(request.headers()) + .withMethod(request.method()) .withPath( new OperationPathResolver( - operation.getPath(), application, pathParameters, mandatoryParameters)); - } - - private void param( - ParameterDefinition parameter, - Map bodyParameters, - Map collectorMap, - Set missingParams, - Set mandatoryParams) { - String name = parameter.name(); - boolean isRequired = parameter.required(); - if (isRequired) { - mandatoryParams.add(name); - } - if (parameters.containsKey(name)) { - collectorMap.put(name, parameters.get(name)); - bodyParameters.remove(name); - } else if (isRequired) { - UnifiedOpenAPI.Schema schema = parameter.schema(); - Object defaultValue = schema != null ? schema._default() : null; - if (defaultValue != null) { - collectorMap.put(name, defaultValue); - } else { - missingParams.add(name); - } - } + request.path(), + application, + request.pathParameters(), + request.mandatoryParameters())); } } diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIExecutorBuilder.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIExecutorBuilder.java index ba8a185f3..6cdeccd2c 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIExecutorBuilder.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIExecutorBuilder.java @@ -49,7 +49,7 @@ public CallableTaskFactory init( .withAuth(with.getAuthentication()) .redirect(with.isRedirect()); UnifiedOpenAPIReader reader = reader(definition.application()); - return () -> new OpenAPIExecutor(reader, processor, resource, parameters, builder); + return () -> new OpenAPIExecutor(reader, processor, resource, parameters, builder::copy); } private UnifiedOpenAPIReader reader(WorkflowApplication app) { diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultHttpRequest.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultHttpRequest.java index 7010fae0f..019217f28 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultHttpRequest.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultHttpRequest.java @@ -15,58 +15,42 @@ */ package cloud.openworkflow.sdk.impl.http; +import cloud.openworkflow.sdk.http.HttpRequestEncoding; +import cloud.openworkflow.sdk.http.JdkHttpTransport; import cloud.openworkflow.sdk.impl.TaskContext; import cloud.openworkflow.sdk.impl.WorkflowApplication; import cloud.openworkflow.sdk.impl.WorkflowContext; import cloud.openworkflow.sdk.impl.WorkflowModel; -import java.net.URI; -import java.net.URLEncoder; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpRequest.BodyPublisher; -import java.net.http.HttpRequest.Builder; -import java.net.http.HttpResponse; -import java.nio.charset.StandardCharsets; -import java.util.Map; import java.util.concurrent.CompletableFuture; -import java.util.function.Function; -import java.util.stream.Collectors; public class DefaultHttpRequest implements WorkflowHttpRequest { protected final WorkflowHttpRequestInfo httpInfo; protected final WorkflowApplication app; - private final HttpClient client; + private final JdkHttpTransport transport; public DefaultHttpRequest( WorkflowApplication app, HttpClient client, WorkflowHttpRequestInfo httpInfo) { this.httpInfo = httpInfo; - this.client = client; + this.transport = new JdkHttpTransport(client); this.app = app; } @Override public CompletableFuture invoke( WorkflowContext workflowContext, TaskContext taskContext) { - Builder builder = HttpRequest.newBuilder(); - builder.method(httpInfo.method(), buildBody()); - Map headers = httpInfo.headers(); - // add default content type, it might be override by specified headers. - builder.header(WorkflowHttpContentType.HEADER_NAME, "application/json"); - headers.forEach((k, v) -> builder.setHeader(k, v.toString())); - URI uri = httpInfo.uri(); - Map queryParams = httpInfo.queryParams(); - if (!queryParams.isEmpty()) { - uri = addQueryParams(uri, queryParams); - } - builder.uri(uri); - String ifModifiedSince = httpInfo.ifModifiedSince(); - if (ifModifiedSince != null) { - builder.header(WorkflowHttpHelper.IF_MODIFIED_SINCE_HEADER, ifModifiedSince); - } - return WorkflowHttpHelper.processAuth(httpInfo, builder::header, workflowContext, taskContext) - .thenCompose( - __ -> client.sendAsync(builder.build(), HttpResponse.BodyHandlers.ofByteArray())) + BodyPublisher body = buildBody(); + return transport + .exchange( + httpInfo, + body, + builder -> { + return WorkflowHttpHelper.processAuth( + httpInfo, builder::header, workflowContext, taskContext); + }) .exceptionallyCompose( ex -> CompletableFuture.failedFuture(WorkflowHttpHelper.fromError(ex, taskContext))) .thenApply(response -> new DefaultHttpResponse(app, response)); @@ -79,7 +63,7 @@ protected BodyPublisher buildBody() { return HttpRequest.BodyPublishers.noBody(); } else if (WorkflowHttpContentType.isURLEncodedDataType(contentType)) { return HttpRequest.BodyPublishers.ofString( - encodeMap( + HttpRequestEncoding.encodeMap( WorkflowHttpHelper.requireMap(body, contentType), DefaultHttpRequest::encodeForm)); } else if (isJson(contentType)) { return HttpRequest.BodyPublishers.ofByteArray( @@ -111,25 +95,11 @@ protected boolean isText(String contentType) { return WorkflowHttpContentType.isTextMediaType(contentType); } - private static URI addQueryParams(URI uri, Map queryParams) { - String addedQuery = encodeMap(queryParams, DefaultHttpRequest::encodeQuery); - String rawQuery = uri.getRawQuery(); - return new URIDecodedBuilder(uri) - .query(rawQuery == null || rawQuery.isEmpty() ? addedQuery : rawQuery + "&" + addedQuery) - .build(); - } - - private static String encodeMap(Map map, Function decoder) { - return map.entrySet().stream() - .map(entry -> decoder.apply(entry.getKey()) + "=" + decoder.apply(entry.getValue())) - .collect(Collectors.joining("&")); - } - - private static String encodeForm(Object part) { - return part == null ? "" : URLEncoder.encode(part.toString(), StandardCharsets.UTF_8); + public static String encodeForm(Object part) { + return HttpRequestEncoding.encodeForm(part); } - private static String encodeQuery(Object part) { - return encodeForm(part).replace("+", "%20"); + public static String encodeQuery(Object part) { + return HttpRequestEncoding.encodeQuery(part); } } diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultHttpResponse.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultHttpResponse.java index 3aae6047b..00e9bc582 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultHttpResponse.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultHttpResponse.java @@ -16,121 +16,12 @@ package cloud.openworkflow.sdk.impl.http; import cloud.openworkflow.sdk.impl.WorkflowApplication; -import cloud.openworkflow.sdk.impl.WorkflowModel; -import java.net.http.HttpClient.Version; import java.net.http.HttpResponse; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.OptionalLong; -import java.util.stream.Collectors; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DefaultHttpResponse implements WorkflowHttpResponse { - - private static final Logger logger = LoggerFactory.getLogger(DefaultHttpResponse.class); - private final WorkflowApplication application; - private final HttpResponse response; +/** Legacy constructor for the common JDK response with the SDK model converter. */ +public class DefaultHttpResponse extends cloud.openworkflow.sdk.http.JdkHttpResponse + implements WorkflowHttpResponse { public DefaultHttpResponse(WorkflowApplication application, HttpResponse response) { - this.application = application; - this.response = response; - } - - @Override - public byte[] contentAsByteArray() { - return response.body(); - } - - @Override - public String getHeader(String name) { - return response.headers().firstValue(name).orElse(null); - } - - @Override - public int status() { - return response.statusCode(); - } - - @Override - public OptionalLong lastModified() { - return response - .headers() - .firstValue("Last-Modified") - .map(DefaultHttpResponse::fromGMTString) - .orElseGet(OptionalLong::empty); - } - - @Override - public String errorDetails() { - byte[] body = response.body(); - return body != null ? new String(body) : "No error information"; - } - - @Override - public WorkflowModel contentAsModel() { - return response.body() == null || response.body().length == 0 - ? application.modelFactory().fromNull() - : responseContentType() - .map(c -> { - if (WorkflowHttpContentType.isJsonMediaType(c)) { - return application.modelFactory().fromJson(response.body()); - } else if (WorkflowHttpContentType.isTextMediaType(c)) { - return application - .modelFactory() - .from(new String(response.body(), WorkflowHttpContentType.charset(c))); - } else { - return application.modelFactory().fromBinary(response.body()); - } - }) - .orElseGet(this::inferContentType); - } - - private Optional responseContentType() { - return response.version() == Version.HTTP_2 - ? response.headers().firstValue("content-type") - : response.headers().map().entrySet().stream() - .filter(e -> e.getKey().equalsIgnoreCase("content-type") && !e.getValue().isEmpty()) - .findAny() - .map(e -> e.getValue().stream().map(String::valueOf).collect(Collectors.joining(","))); - } - - private WorkflowModel inferContentType() { - return WorkflowResponseSniffer.asString(response.body()) - .map(c -> application.modelFactory().from(c)) - .orElseGet(() -> application.modelFactory().fromBinary(response.body())); - } - - @Override - public String toString() { - return "DefaultHttpResponse [response=" + response + "]"; - } - - private static OptionalLong fromGMTString(String str) { - try { - return OptionalLong.of( - ZonedDateTime.parse(str, DateTimeFormatter.RFC_1123_DATE_TIME) - .toInstant() - .toEpochMilli()); - } catch (DateTimeParseException ex) { - logger.warn("Invalid date returned in Last-Modified header", ex); - return OptionalLong.empty(); - } - } - - @Override - public byte[] responseAsByteArray() { - return WorkflowHttpHelper.responseAsByteArray(this, response.version() == Version.HTTP_2); - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public Map> headers() { - Map map = response.headers().map(); - return map; + super(response, new WorkflowHttpBodyConverter(application.modelFactory())); } } diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultURITemplateResolver.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultURITemplateResolver.java index 0a690439a..9e315d363 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultURITemplateResolver.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultURITemplateResolver.java @@ -15,605 +15,13 @@ */ package cloud.openworkflow.sdk.impl.http; -import java.io.UnsupportedEncodingException; +import cloud.openworkflow.sdk.impl.executors.openapi.OpenAPIPathResolver; import java.net.URI; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; import java.util.Map; public class DefaultURITemplateResolver implements URITemplateResolver { - @Override public URI resolveTemplates(String uri, Map map) { - return URI.create(expandImpl(uri, map)); - } - - // Private implementation - private enum Operator { - NO_OP, - PLUS, - HASH, - DOT, - SLASH, - SEMICOLON, - QUESTION_MARK, - AMP; - } - - private static void checkVarname(String token, int col) { - if (token.startsWith(".") || token.endsWith(".")) { - throw new IllegalArgumentException( - "Variable name cannot start or end with a dot at col:" + col); - } - if (token.contains("..")) { - throw new IllegalArgumentException( - "Variable name cannot contain consecutive dots at col:" + col); - } - for (int i = 0; i < token.length(); i++) { - if (token.charAt(i) == '%') { - if (i + 2 >= token.length() - || !isHexDigit(token.charAt(i + 1)) - || !isHexDigit(token.charAt(i + 2))) { - throw new IllegalArgumentException( - "Invalid percent-encoding in variable name at col:" + col); - } - } - } - } - - private static boolean isHexDigit(char c) { - return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); - } - - private static void validateLiteral(Character c, int col) { - switch (c) { - case '+': - case '#': - case '/': - case ';': - case '?': - case '&': - case ' ': - case '!': - case '=': - case '$': - case '|': - case '*': - case ':': - case '~': - throw new IllegalArgumentException( - "Illegal character identified in the token at col:" + col); - default: - break; - } - } - - private static int getMaxChar(StringBuilder buffer, int col) { - if (buffer == null || buffer.length() == 0) { - return -1; - } else { - String value = buffer.toString(); - - if (value.isEmpty()) { - return -1; - } else { - try { - if (value.charAt(0) == '0') { - throw new IllegalArgumentException( - "Leading zero not allowed in max chars at col:" + col); - } - int result = Integer.parseInt(value); - if (result < 1 || result > 9999) { - throw new IllegalArgumentException("Max chars out of range (1-9999) at col:" + col); - } - return result; - } catch (NumberFormatException e) { - throw new IllegalArgumentException("Cannot parse max chars at col:" + col); - } - } - } - } - - private static Operator getOperator(Character c, StringBuilder token, int col) { - switch (c) { - case '+': - return Operator.PLUS; - case '#': - return Operator.HASH; - case '.': - return Operator.DOT; - case '/': - return Operator.SLASH; - case ';': - return Operator.SEMICOLON; - case '?': - return Operator.QUESTION_MARK; - case '&': - return Operator.AMP; - default: - validateLiteral(c, col); - token.append(c); - return Operator.NO_OP; - } - } - - private static String expandImpl(String str, Map substitutions) { - final StringBuilder result = new StringBuilder(str.length() * 2); - - boolean toToken = false; - final StringBuilder token = new StringBuilder(); - - Operator operator = null; - boolean composite = false; - boolean toMaxCharBuffer = false; - final StringBuilder maxCharBuffer = new StringBuilder(3); - boolean firstToken = true; - - for (int i = 0; i < str.length(); i++) { - char character = str.charAt(i); - switch (character) { - case '{': - toToken = true; - token.setLength(0); - firstToken = true; - break; - case '}': - if (toToken) { - if (toMaxCharBuffer && maxCharBuffer.length() == 0) { - throw new IllegalArgumentException("Empty prefix modifier at col:" + i); - } - boolean expanded = - expandToken( - operator, - token.toString(), - composite, - getMaxChar(maxCharBuffer, i), - firstToken, - substitutions, - result, - i); - if (expanded && firstToken) { - firstToken = false; - } - toToken = false; - token.setLength(0); - operator = null; - composite = false; - toMaxCharBuffer = false; - maxCharBuffer.setLength(0); - } else { - throw new IllegalArgumentException("Failed to expand token, invalid at col:" + i); - } - break; - case ',': - if (toToken) { - if (toMaxCharBuffer && maxCharBuffer.length() == 0) { - throw new IllegalArgumentException("Empty prefix modifier at col:" + i); - } - boolean expanded = - expandToken( - operator, - token.toString(), - composite, - getMaxChar(maxCharBuffer, i), - firstToken, - substitutions, - result, - i); - if (expanded && firstToken) { - firstToken = false; - } - token.setLength(0); - composite = false; - toMaxCharBuffer = false; - maxCharBuffer.setLength(0); - break; - } - // Intentional fall-through for commas outside the {} - default: - if (toToken) { - if (operator == null) { - operator = getOperator(character, token, i); - } else if (toMaxCharBuffer) { - if (Character.isDigit(character)) { - maxCharBuffer.append(character); - } else { - throw new IllegalArgumentException( - "Illegal character identified in the token at col:" + i); - } - } else { - if (character == ':') { - toMaxCharBuffer = true; - maxCharBuffer.setLength(0); - } else if (character == '*') { - composite = true; - } else { - validateLiteral(character, i); - token.append(character); - } - } - } else { - if (character > 0x7F || Character.isHighSurrogate(character)) { - String toEncode; - if (Character.isHighSurrogate(character) - && i + 1 < str.length() - && Character.isLowSurrogate(str.charAt(i + 1))) { - toEncode = new String(new char[] {character, str.charAt(++i)}); - } else { - toEncode = Character.toString(character); - } - for (byte b : toEncode.getBytes(StandardCharsets.UTF_8)) { - result.append(String.format("%%%02X", b & 0xFF)); - } - } else { - result.append(character); - } - } - break; - } - } - - if (!toToken) { - return result.toString(); - } else { - throw new IllegalArgumentException("Unterminated token"); - } - } - - private static void addPrefix(Operator op, StringBuilder result) { - switch (op) { - case HASH: - result.append('#'); - break; - case DOT: - result.append('.'); - break; - case SLASH: - result.append('/'); - break; - case SEMICOLON: - result.append(';'); - break; - case QUESTION_MARK: - result.append('?'); - break; - case AMP: - result.append('&'); - break; - default: - return; - } - } - - private static void addSeparator(Operator op, StringBuilder result) { - switch (op) { - case DOT: - result.append('.'); - break; - case SLASH: - result.append('/'); - break; - case SEMICOLON: - result.append(';'); - break; - case QUESTION_MARK: - case AMP: - result.append('&'); - break; - default: - result.append(','); - return; - } - } - - private static void addValue( - Operator op, String token, Object value, StringBuilder result, int maxChar) { - switch (op) { - case PLUS: - case HASH: - addExpandedValue(null, value, result, maxChar, false); - break; - case QUESTION_MARK: - case AMP: - result.append(token + '='); - addExpandedValue(null, value, result, maxChar, true); - break; - case SEMICOLON: - result.append(token); - addExpandedValue("=", value, result, maxChar, true); - break; - case DOT: - case SLASH: - case NO_OP: - addExpandedValue(null, value, result, maxChar, true); - } - } - - private static void addValueElement( - Operator op, String token, Object value, StringBuilder result, int maxChar) { - switch (op) { - case PLUS: - case HASH: - addExpandedValue(null, value, result, maxChar, false); - break; - case QUESTION_MARK: - case AMP: - case SEMICOLON: - case DOT: - case SLASH: - case NO_OP: - addExpandedValue(null, value, result, maxChar, true); - } - } - - private static boolean isSurrogate(char cp) { - return (cp >= 0xD800 && cp <= 0xDFFF); - } - - private static boolean isIprivate(char cp) { - return (0xE000 <= cp && cp <= 0xF8FF); - } - - private static boolean isUcschar(char cp) { - return (0xA0 <= cp && cp <= 0xD7FF) - || (0xF900 <= cp && cp <= 0xFDCF) - || (0xFDF0 <= cp && cp <= 0xFFEF); - } - - private static void addExpandedValue( - String prefix, Object value, StringBuilder result, int maxChar, boolean replaceReserved) { - String stringValue = convertNativeTypes(value); - int cpCount = stringValue.codePointCount(0, stringValue.length()); - int max = (maxChar != -1) ? Math.min(maxChar, cpCount) : cpCount; - result.ensureCapacity(max * 2); // hint to SB - boolean toReserved = false; - final StringBuilder reservedBuffer = new StringBuilder(3); - - if (max > 0 && prefix != null) { - result.append(prefix); - } - - int charCount = 0; - for (int i = 0; i < stringValue.length() && charCount < max; i++) { - char character = stringValue.charAt(i); - charCount++; - - if (character == '%' && !replaceReserved) { - toReserved = true; - reservedBuffer.setLength(0); - } - - String toAppend = Character.toString(character); - try { - if (isSurrogate(character)) { - StringBuilder sb = new StringBuilder(); - sb.append(Character.toChars(stringValue.codePointAt(i++))); - toAppend = URLEncoder.encode(sb.toString(), StandardCharsets.UTF_8.name()); - } else if (replaceReserved || isUcschar(character) || isIprivate(character)) { - toAppend = - URLEncoder.encode(toAppend, StandardCharsets.UTF_8.name()) - .replace("*", "%2A") - .replace("%7E", "~"); - } - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - - if (toReserved) { - reservedBuffer.append(toAppend); - - if (reservedBuffer.length() == 3) { - boolean isEncoded = false; - try { - URLDecoder.decode(reservedBuffer.toString(), StandardCharsets.UTF_8.name()); - isEncoded = true; - } catch (Exception e) { - // ignore - } - - if (isEncoded) { - result.append(reservedBuffer); - } else { - result.append("%25"); - // only if !replaceReserved - result.append(reservedBuffer.substring(1)); - } - toReserved = false; - reservedBuffer.setLength(0); - } - } else { - if (character == ' ') { - result.append("%20"); - } else if (character == '%') { - result.append("%25"); - } else { - result.append(toAppend); - } - } - } - - if (toReserved) { - result.append("%25"); - result.append(reservedBuffer.substring(1)); - } - } - - private static boolean isList(Object value) { - return value instanceof ArrayList - || // checking concrete instances first as it's faster - value instanceof List; - } - - private static boolean isMap(Object value) { - return value instanceof HashMap - || // checking concrete instances first as it's faster - value instanceof Map; - } - - enum SubstitutionType { - EMPTY, - STRING, - LIST, - MAP; - } - - private static SubstitutionType getSubstitutionType(Object value, int col) { - if (value == null) { - return SubstitutionType.EMPTY; - } else if (isNativeType(value)) { - return SubstitutionType.STRING; - } else if (isList(value)) { - return SubstitutionType.LIST; - } else if (isMap(value)) { - return SubstitutionType.MAP; - } else { - throw new IllegalArgumentException( - "Illegal class passed as substitution, found " + value.getClass() + " at col:" + col); - } - } - - private static boolean isEmpty(SubstitutionType substType, Object value) { - if (value == null) { - return true; - } else { - switch (substType) { - case STRING: - return false; - case LIST: - return ((List) value).isEmpty(); - case MAP: - return ((Map) value).isEmpty(); - default: - return true; - } - } - } - - private static boolean isNativeType(Object value) { - if (value instanceof String || value instanceof Boolean || value instanceof Number) { - return true; - } - return false; - } - - private static String convertNativeTypes(Object value) { - if (value instanceof String) { - return (String) value; - } else if (value instanceof Boolean || value instanceof Number) { - return value.toString(); - } - throw new IllegalArgumentException( - "Illegal class passed as substitution, found " + value.getClass()); - } - - // returns true if expansion happened - private static boolean expandToken( - Operator operator, - String token, - boolean composite, - int maxChar, - boolean firstToken, - Map substitutions, - StringBuilder result, - int col) { - if (token.isEmpty()) { - throw new IllegalArgumentException("Found an empty token at col:" + col); - } - - checkVarname(token, col); - - Object value = substitutions.get(token); - SubstitutionType substType = getSubstitutionType(value, col); - if (substType == SubstitutionType.EMPTY || isEmpty(substType, value)) { - return false; - } - - if (firstToken) { - addPrefix(operator, result); - } else { - addSeparator(operator, result); - } - - switch (substType) { - case STRING: - addStringValue(operator, token, (Object) value, result, maxChar); - break; - case LIST: - addListValue(operator, token, (List) value, result, maxChar, composite); - break; - case MAP: - addMapValue(operator, token, (Map) value, result, maxChar, composite); - break; - } - - return true; - } - - private static boolean addStringValue( - Operator operator, String token, Object value, StringBuilder result, int maxChar) { - addValue(operator, token, value, result, maxChar); - return true; - } - - private static boolean addListValue( - Operator operator, - String token, - List value, - StringBuilder result, - int maxChar, - boolean composite) { - boolean first = true; - for (Object v : value) { - if (first) { - addValue(operator, token, v, result, maxChar); - first = false; - } else { - if (composite) { - addSeparator(operator, result); - addValue(operator, token, v, result, maxChar); - } else { - result.append(','); - addValueElement(operator, token, v, result, maxChar); - } - } - } - return !first; - } - - private static boolean addMapValue( - Operator operator, - String token, - Map value, - StringBuilder result, - int maxChar, - boolean composite) { - boolean first = true; - if (maxChar != -1) { - throw new IllegalArgumentException("Value trimming is not allowed on Maps"); - } - for (Map.Entry v : value.entrySet()) { - if (composite) { - if (!first) { - addSeparator(operator, result); - } - addValueElement(operator, token, v.getKey(), result, maxChar); - result.append('='); - } else { - if (first) { - addValue(operator, token, v.getKey(), result, maxChar); - } else { - result.append(','); - addValueElement(operator, token, v.getKey(), result, maxChar); - } - result.append(','); - } - addValueElement(operator, token, v.getValue(), result, maxChar); - first = false; - } - return !first; + return new OpenAPIPathResolver().resolveTemplates(uri, map); } } diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpBodyConverter.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpBodyConverter.java new file mode 100644 index 000000000..27411772c --- /dev/null +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpBodyConverter.java @@ -0,0 +1,83 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.impl.http; + +import cloud.openworkflow.sdk.http.*; +import cloud.openworkflow.sdk.impl.WorkflowModel; +import cloud.openworkflow.sdk.impl.WorkflowModelFactory; +import java.net.http.HttpClient.Version; +import java.util.*; +import java.util.stream.Collectors; + +/** SDK model conversion policy; HTTP state and behavior stay in common. */ +public final class WorkflowHttpBodyConverter implements HttpBodyConverter { + private final WorkflowModelFactory modelFactory; + + public WorkflowHttpBodyConverter(WorkflowModelFactory factory) { + modelFactory = factory; + } + + public Optional convert(HttpResponse source, Class type) { + if (type != WorkflowModel.class) return HttpBodyConverter.BYTES.convert(source, type); + return Optional.of(type.cast(new Decoder(source).decodeModel())); + } + + private final class Decoder { + private final java.net.http.HttpResponse nativeResponse; + + @SuppressWarnings("unchecked") + Decoder(HttpResponse source) { + nativeResponse = source.nativeResponse(java.net.http.HttpResponse.class).orElseThrow(); + } + + private byte[] responseBody() { + return nativeResponse.body(); + } + + private WorkflowModel decodeModel() { + return responseBody() == null || responseBody().length == 0 + ? modelFactory.fromNull() + : responseContentType() + .map(c -> { + if (WorkflowHttpContentType.isJsonMediaType(c)) { + return modelFactory.fromJson(responseBody()); + } else if (WorkflowHttpContentType.isTextMediaType(c)) { + return modelFactory.from( + new String(responseBody(), WorkflowHttpContentType.charset(c))); + } else { + return modelFactory.fromBinary(responseBody()); + } + }) + .orElseGet(this::inferContentType); + } + + private Optional responseContentType() { + return nativeResponse.version() == Version.HTTP_2 + ? nativeResponse.headers().firstValue("content-type") + : nativeResponse.headers().map().entrySet().stream() + .filter(e -> e.getKey().equalsIgnoreCase("content-type") && !e.getValue().isEmpty()) + .findAny() + .map( + e -> e.getValue().stream().map(String::valueOf).collect(Collectors.joining(","))); + } + + private WorkflowModel inferContentType() { + return WorkflowResponseSniffer.asString(responseBody()) + .map(c -> modelFactory.from(c)) + .orElseGet(() -> modelFactory.fromBinary(responseBody())); + } + } +} diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpHelper.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpHelper.java index 6c3891f91..5d7cdd91a 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpHelper.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpHelper.java @@ -24,13 +24,8 @@ import cloud.openworkflow.sdk.impl.auth.AuthProvider; import cloud.openworkflow.sdk.impl.auth.AuthUtils; import cloud.openworkflow.sdk.types.Errors; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.UncheckedIOException; import java.net.SocketTimeoutException; import java.net.http.HttpTimeoutException; -import java.nio.charset.StandardCharsets; -import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; @@ -40,7 +35,6 @@ public class WorkflowHttpHelper { public static final String IF_MODIFIED_SINCE_HEADER = "If-Modified-Since"; - private static final String HTTP_NEW_LINE = "\r\n"; private static final String CONTENT = "content"; private static final String HEADERS = "headers"; @@ -112,7 +106,7 @@ public static CompletableFuture asWorkflowHtppResponse( public static WorkflowException fromError(Throwable ex, TaskContext task) { int statusCode = Errors.COMMUNICATION.status(); - ex = ex instanceof CompletionException ? ex.getCause() : ex; + ex = ex instanceof CompletionException && ex.getCause() != null ? ex.getCause() : ex; Throwable cause = ex; do { if (cause instanceof TimeoutException @@ -175,36 +169,7 @@ public static Map requireMap(WorkflowModel model, String content } public static byte[] responseAsByteArray(WorkflowHttpResponse response, boolean isHttp2) { - byte[] content = response.contentAsByteArray(); - try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { - StringBuilder sb = - new StringBuilder( - isHttp2 - ? "HTTP/2 " + response.status() - : "HTTP/1.1 " + response.status() + " " + response.reasonPhrase()); - sb.append(HTTP_NEW_LINE); - for (Map.Entry> entry : response.headers().entrySet()) { - String headerName = entry.getKey(); - for (Object value : entry.getValue()) { - if (headerName.equalsIgnoreCase("Transfer-Encoding") - && value instanceof String str - && str.equalsIgnoreCase("chunked")) { - addHeader(sb, "Content-Length", content.length); - } else { - addHeader(sb, headerName, value); - } - } - } - sb.append(HTTP_NEW_LINE); - out.write(sb.toString().getBytes(StandardCharsets.ISO_8859_1)); - - if (content != null) { - out.write(content); - } - return out.toByteArray(); - } catch (IOException io) { - throw new UncheckedIOException(io); - } + return cloud.openworkflow.sdk.http.HttpResponses.responseAsByteArray(response, isHttp2); } private static CompletableFuture addAuthHeader( @@ -224,10 +189,6 @@ private static CompletableFuture addAuthHeader( }); } - private static void addHeader(StringBuilder sb, String headerName, Object value) { - sb.append(headerName + ": " + value + HTTP_NEW_LINE); - } - private static WorkflowModel responseAsModel( WorkflowHttpResponse response, WorkflowApplication application) { return application diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpRequestInfo.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpRequestInfo.java index aa17fa634..eed0a465a 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpRequestInfo.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpRequestInfo.java @@ -15,126 +15,125 @@ */ package cloud.openworkflow.sdk.impl.http; +import cloud.openworkflow.sdk.http.HttpRequestInfo; import cloud.openworkflow.sdk.impl.WorkflowModel; -import cloud.openworkflow.sdk.impl.WorkflowUtils; import cloud.openworkflow.sdk.impl.auth.AuthProvider; import java.net.URI; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; -import java.util.Locale; import java.util.Map; -import java.util.Map.Entry; import java.util.Objects; -import java.util.TreeMap; -import java.util.stream.Collectors; - -public record WorkflowHttpRequestInfo( - URI uri, - String method, - boolean redirect, - Map headers, - Map queryParams, - WorkflowModel body, - AuthProvider auth, - String ifModifiedSince) { - public static Builder builder(String method) { - return new Builder(method); +/** + * Compatibility entry point adding workflow authentication to the common request implementation. + */ +public class WorkflowHttpRequestInfo extends HttpRequestInfo { + private final AuthProvider auth; + + public WorkflowHttpRequestInfo( + URI uri, + String method, + boolean redirect, + Map headers, + Map queryParams, + WorkflowModel body, + AuthProvider auth, + String modified) { + super(uri, method, redirect, headers, queryParams, body, modified); + this.auth = auth; + } + + @Override + public WorkflowModel body() { + return super.body(); + } + + public AuthProvider auth() { + return auth; + } + + @Override + public boolean equals(Object other) { + return super.equals(other) + && other instanceof WorkflowHttpRequestInfo info + && Objects.equals(auth, info.auth); } - public String contentType() { - return headers.get(WorkflowHttpContentType.HEADER_NAME) instanceof String str - ? str - : WorkflowHttpContentType.APPLICATION_JSON_TYPE; + @Override + public int hashCode() { + return 31 * super.hashCode() + Objects.hashCode(auth); } - public static class Builder { - private final String method; - private boolean redirect; - private Map headers; - private Map queryParams; - private WorkflowModel body; + public static Builder builder(String method) { + return new Builder(method); + } + + public static class Builder extends HttpRequestInfo.Builder { private AuthProvider auth; - private Long ifModifiedSince; - private URI path; public Builder() { - this.method = "GET"; + super(); } public Builder(String method) { - this.method = Objects.requireNonNull(method).toUpperCase(); + super(method); } - public Builder redirect(boolean redirect) { - this.redirect = redirect; + public Builder auth(AuthProvider auth) { + this.auth = auth; return this; } - public Builder headers(Map headers) { - if (headers != null) { - this.headers = - headers.entrySet().stream() - .filter(e -> e.getValue() != null) - .collect( - Collectors.toMap( - Entry::getKey, - Entry::getValue, - (oldEntry, newEntry) -> newEntry, - () -> new TreeMap<>(String.CASE_INSENSITIVE_ORDER))); - } + @Override + public Builder redirect(boolean value) { + super.redirect(value); return this; } - public Builder path(URI path) { - this.path = path; + @Override + public Builder headers(Map value) { + super.headers(value); return this; } - public Builder queryParams(Map queryParams) { - if (queryParams != null) { - this.queryParams = - queryParams.entrySet().stream() - .collect( - Collectors.toMap(Entry::getKey, e -> e.getValue() == null ? "" : e.getValue())); - } + @Override + public Builder queryParams(Map value) { + super.queryParams(value); return this; } - public Builder body(WorkflowModel body) { - this.body = body; + @Override + public Builder body(WorkflowModel value) { + super.body(value); return this; } - public Builder auth(AuthProvider auth) { - this.auth = auth; + @Override + public Builder path(URI value) { + super.path(value); return this; } - public Builder ifModifiedSince(long millis) { - this.ifModifiedSince = millis; + @Override + public Builder ifModifiedSince(long value) { + super.ifModifiedSince(value); return this; } + @Override public WorkflowHttpRequestInfo build(URI uri) { + return (WorkflowHttpRequestInfo) super.build(uri); + } + + @Override + protected WorkflowHttpRequestInfo create( + URI uri, + String method, + boolean redirect, + Map headers, + Map queryParams, + WorkflowModel body, + String modified) { return new WorkflowHttpRequestInfo( - path == null ? uri : WorkflowUtils.concatURI(uri, path), - method, - redirect, - headers != null ? headers : Map.of(), - queryParams != null ? queryParams : Map.of(), - body, - auth, - ifModifiedSince != null - ? Instant.ofEpochMilli(ifModifiedSince) - .atZone(ZoneOffset.UTC) - .format( - DateTimeFormatter.ofPattern( - "EEE, dd MMM uuuu HH:mm:ss 'GMT'", - Locale.US)) // RFC_1123 skips the 0 in single - // digit days - : null); + uri, method, redirect, headers, queryParams, body, auth, modified); } } } diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpRequestInfoBuilderFactory.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpRequestInfoBuilderFactory.java index 548d0b3ba..3caac8df3 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpRequestInfoBuilderFactory.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpRequestInfoBuilderFactory.java @@ -49,6 +49,24 @@ private WorkflowHttpRequestInfoBuilderFactory(WorkflowDefinition definition) { this.definition = definition; } + /** + * Copies this template's configuration without resolving authentication again. The returned + * factory owns its mutable builder fields; configured providers and resolvers retain their + * existing lifetime and are shared. + */ + public WorkflowHttpRequestInfoBuilderFactory copy() { + WorkflowHttpRequestInfoBuilderFactory copy = + new WorkflowHttpRequestInfoBuilderFactory(definition); + copy.pathSupplier = pathSupplier; + copy.bodyFilter = bodyFilter; + copy.method = method; + copy.auth = auth; + copy.redirect = redirect; + copy.headers = headers; + copy.queryMap = queryMap; + return copy; + } + public WorkflowHttpRequestInfoBuilderFactory withAuth(ReferenceableAuthenticationPolicy policy) { if (policy != null) { if (policy.getAuthenticationPolicyReference() != null) { @@ -106,7 +124,7 @@ public WorkflowHttpRequestInfoBuilderFactory withQueryMap( public WorkflowHttpRequestInfoBuilderFactory withMethod(String method) { if (method != null) { - this.method = method.toUpperCase(); + this.method = method; // The common request builder normalizes HTTP methods. } return this; } diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpResponse.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpResponse.java index 606fec78d..930d99b8d 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpResponse.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpResponse.java @@ -18,64 +18,21 @@ import cloud.openworkflow.sdk.impl.WorkflowModel; import java.util.List; import java.util.Map; -import java.util.OptionalLong; - -public interface WorkflowHttpResponse extends AutoCloseable { +/** Compatibility workflow view of the common HTTP response contract. */ +public interface WorkflowHttpResponse extends cloud.openworkflow.sdk.http.HttpResponse { + @Override byte[] contentAsByteArray(); - byte[] responseAsByteArray(); - - WorkflowModel contentAsModel(); - - /** Access all headers */ - Map> headers(); - - /** - * Access response header given its name - * - * @param name name of the header - * @return first value of the header as string - */ - String getHeader(String name); - - int status(); - - OptionalLong lastModified(); - - default String reasonPhrase() { - return switch (status()) { - case 100 -> "Continue"; - case 101 -> "Switching Protocols"; - case 102 -> "Processing"; - case 103 -> "Early Hints"; - case 200 -> "OK"; - case 201 -> "Created"; - case 202 -> "Accepted"; - case 204 -> "No Content"; - case 206 -> "Partial Content"; - case 301 -> "Moved Permanently"; - case 302 -> "Found"; - case 304 -> "Not Modified"; - case 307 -> "Temporary Redirect"; - case 308 -> "Permanent Redirect"; - case 400 -> "Bad Request"; - case 401 -> "Unauthorized"; - case 403 -> "Forbidden"; - case 404 -> "Not Found"; - case 405 -> "Method Not Allowed"; - case 408 -> "Request Timeout"; - case 409 -> "Conflict"; - case 429 -> "Too Many Requests"; - case 500 -> "Internal Server Error"; - case 502 -> "Bad Gateway"; - case 503 -> "Service Unavailable"; - case 504 -> "Gateway Timeout"; - default -> "Unknown Status Code"; - }; + @Override + default byte[] body() { + return contentAsByteArray(); } - String errorDetails(); + default WorkflowModel contentAsModel() { + return getBodyAsObject(WorkflowModel.class).orElseThrow(); + } - default void close() {} + @Override + Map> headers(); } diff --git a/impl/core/src/test/java/cloud/openworkflow/sdk/impl/http/DefaultHttpResponseTest.java b/impl/core/src/test/java/cloud/openworkflow/sdk/impl/http/DefaultHttpResponseTest.java new file mode 100644 index 000000000..9b0970f1a --- /dev/null +++ b/impl/core/src/test/java/cloud/openworkflow/sdk/impl/http/DefaultHttpResponseTest.java @@ -0,0 +1,103 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.impl.http; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import cloud.openworkflow.sdk.impl.WorkflowApplication; +import java.net.http.HttpClient; +import java.net.http.HttpHeaders; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +class DefaultHttpResponseTest { + + @Test + void rawFormatterHandlesDiscardedChunkedBodies() { + var nativeResponse = nativeResponse(); + when(nativeResponse.headers()) + .thenReturn( + HttpHeaders.of(Map.of("Transfer-Encoding", List.of("chunked")), (name, value) -> true)); + var response = new DefaultHttpResponse(mock(WorkflowApplication.class), nativeResponse); + assertThat(new String(response.responseAsByteArray(), StandardCharsets.ISO_8859_1)) + .contains("Content-Length: 0\r\n"); + } + + @Test + void sharedAccess_shouldPreserveRawBytesAndExposeNativeHandle() { + var nativeResponse = nativeResponse(); + byte[] bytes = {1, 2}; + when(nativeResponse.body()).thenReturn(bytes); + var response = new DefaultHttpResponse(mock(WorkflowApplication.class), nativeResponse); + response.body()[0] = 9; + assertThat(response.body()).containsExactly((byte) 1, (byte) 2); + assertThat(response.nativeResponse(HttpResponse.class)).contains(nativeResponse); + } + + @Test + void rawResponse_shouldRetainNativeHttpVersion() { + HttpResponse nativeResponse = nativeResponse(); + when(nativeResponse.version()).thenReturn(HttpClient.Version.HTTP_2); + when(nativeResponse.body()).thenReturn(new byte[0]); + DefaultHttpResponse response = + new DefaultHttpResponse(mock(WorkflowApplication.class), nativeResponse); + assertThat(new String(response.responseAsByteArray(), StandardCharsets.ISO_8859_1)) + .startsWith("HTTP/2 204\r\n"); + } + + @Test + void nativeConstructor_shouldAcceptNativeResponsesWithNullBodies() { + HttpResponse nativeResponse = nativeResponse(); + DefaultHttpResponse response = + new DefaultHttpResponse(mock(WorkflowApplication.class), nativeResponse); + assertThat(response.contentAsByteArray()).isNull(); + assertThat(response.status()).isEqualTo(204); + assertThat(response.getHeader("x-result")).isEqualTo("value"); + assertThat(response.errorDetails()).isEqualTo("No error information"); + assertThat(response.lastModified()).hasValue(784111777000L); + } + + @Test + void nativeConstructor_shouldRetainNativeBodyAccess() { + HttpResponse nativeResponse = nativeResponse(); + byte[] body = "message".getBytes(StandardCharsets.UTF_8); + when(nativeResponse.body()).thenReturn(body); + DefaultHttpResponse response = + new DefaultHttpResponse(mock(WorkflowApplication.class), nativeResponse); + assertThat(response.contentAsByteArray()).isSameAs(body); + response.contentAsByteArray()[0] = 'M'; + assertThat(response.errorDetails()).isEqualTo("Message"); + } + + @SuppressWarnings("unchecked") + private static HttpResponse nativeResponse() { + HttpResponse response = mock(HttpResponse.class); + when(response.statusCode()).thenReturn(204); + when(response.headers()) + .thenReturn( + HttpHeaders.of( + Map.of( + "X-Result", List.of("value"), + "Last-Modified", List.of("Sun, 06 Nov 1994 08:49:37 GMT")), + (name, value) -> true)); + return response; + } +} diff --git a/impl/core/src/test/java/cloud/openworkflow/sdk/impl/http/HttpErrorTranslationTest.java b/impl/core/src/test/java/cloud/openworkflow/sdk/impl/http/HttpErrorTranslationTest.java new file mode 100644 index 000000000..76e65d50d --- /dev/null +++ b/impl/core/src/test/java/cloud/openworkflow/sdk/impl/http/HttpErrorTranslationTest.java @@ -0,0 +1,64 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.impl.http; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import cloud.openworkflow.sdk.impl.TaskContext; +import cloud.openworkflow.sdk.impl.WorkflowPosition; +import cloud.openworkflow.sdk.types.Errors; +import java.net.SocketTimeoutException; +import java.net.http.HttpTimeoutException; +import java.util.List; +import java.util.concurrent.CompletionException; +import java.util.concurrent.TimeoutException; +import org.junit.jupiter.api.Test; + +class HttpErrorTranslationTest { + + @Test + void fromError_shouldRetainACompletionExceptionWithoutACause() { + TaskContext task = mock(TaskContext.class); + WorkflowPosition position = mock(WorkflowPosition.class); + when(task.position()).thenReturn(position); + when(position.jsonPointer()).thenReturn("do/0/callApi"); + var failure = new CompletionException("provider buffering failure", null); + var translated = WorkflowHttpHelper.fromError(failure, task); + assertThat(translated).hasCause(failure); + assertThat(translated.getWorkflowError().status()).isEqualTo(Errors.COMMUNICATION.status()); + assertThat(translated.getWorkflowError().instance()).isEqualTo("do/0/callApi"); + } + + @Test + void fromError_shouldPreserveTimeoutClassificationAndTaskPosition() { + TaskContext task = mock(TaskContext.class); + WorkflowPosition position = mock(WorkflowPosition.class); + when(task.position()).thenReturn(position); + when(position.jsonPointer()).thenReturn("do/0/callApi"); + for (Exception cause : + List.of( + new TimeoutException("deadline"), + new SocketTimeoutException("read"), + new HttpTimeoutException("request"))) { + var error = + WorkflowHttpHelper.fromError(new CompletionException(cause), task).getWorkflowError(); + assertThat(error.status()).isEqualTo(Errors.TIMEOUT.status()); + assertThat(error.instance()).isEqualTo("do/0/callApi"); + } + } +} diff --git a/impl/core/src/test/java/cloud/openworkflow/sdk/impl/http/SharedHttpContractTest.java b/impl/core/src/test/java/cloud/openworkflow/sdk/impl/http/SharedHttpContractTest.java new file mode 100644 index 000000000..429e23538 --- /dev/null +++ b/impl/core/src/test/java/cloud/openworkflow/sdk/impl/http/SharedHttpContractTest.java @@ -0,0 +1,157 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.impl.http; + +import static org.assertj.core.api.Assertions.*; +import static org.mockito.Mockito.mock; + +import cloud.openworkflow.sdk.http.HttpRequestInfo; +import cloud.openworkflow.sdk.http.JdkHttpResponse; +import cloud.openworkflow.sdk.impl.WorkflowApplication; +import cloud.openworkflow.sdk.impl.WorkflowModel; +import cloud.openworkflow.sdk.impl.auth.AuthProvider; +import java.net.URI; +import java.util.*; +import org.junit.jupiter.api.Test; + +class SharedHttpContractTest { + @Test + void selectsTheLastContentTypeForSdkBodyEncoding() throws Exception { + Map headers = new LinkedHashMap<>(); + headers.put("content-type", "text/plain"); + headers.put("Content-Type", "application/json"); + var model = mock(WorkflowModel.class); + byte[] json = "{\"value\":1}".getBytes(java.nio.charset.StandardCharsets.UTF_8); + org.mockito.Mockito.when(model.asJson()).thenReturn(Optional.of(json)); + var info = + new WorkflowHttpRequestInfo( + URI.create("https://example.test/"), + "POST", + false, + headers, + Map.of(), + model, + null, + null); + assertThat(info.contentType()).isEqualTo("application/json"); + try (var client = java.net.http.HttpClient.newHttpClient()) { + var request = new DefaultHttpRequest(mock(WorkflowApplication.class), client, info); + assertThat(request.buildBody().contentLength()).isEqualTo(json.length); + org.mockito.Mockito.verify(model).asJson(); + } + } + + @Test + void legacyResponseImplementationsNeedNoNewBodyMethod() { + byte[] bytes = {1, 2}; + WorkflowHttpResponse legacy = + new WorkflowHttpResponse() { + public byte[] contentAsByteArray() { + return bytes; + } + + public WorkflowModel contentAsModel() { + return mock(WorkflowModel.class); + } + + public Map> headers() { + return Map.of(); + } + + public String getHeader(String name) { + return null; + } + + public int status() { + return 200; + } + + public java.util.OptionalLong lastModified() { + return java.util.OptionalLong.empty(); + } + + public String errorDetails() { + return "none"; + } + }; + assertThat(legacy.getBodyAsObject(byte[].class).orElseThrow()).isEqualTo(bytes); + } + + @Test + void sdkBodyAccessorRetainsItsWorkflowModelJvmSignature() throws Exception { + assertThat(WorkflowHttpRequestInfo.class.getMethod("body").getReturnType()) + .isEqualTo(WorkflowModel.class); + } + + @Test + void sdkRequestSpecializesTheCommonImplementationOnlyForAuthentication() { + var auth = mock(AuthProvider.class); + var model = mock(WorkflowModel.class); + Map query = new HashMap<>(); + query.put("empty", null); + var common = + HttpRequestInfo.builder("post") + .headers(Map.of("content-type", "text/plain")) + .queryParams(query) + .path(URI.create("/items?source=common")) + .redirect(true) + .body(model) + .ifModifiedSince(784111777000L) + .build(URI.create("https://example.test/api")); + var sdk = + WorkflowHttpRequestInfo.builder("post") + .headers(Map.of("content-type", "text/plain")) + .queryParams(query) + .path(URI.create("/items?source=common")) + .redirect(true) + .body(model) + .ifModifiedSince(784111777000L) + .auth(auth) + .build(URI.create("https://example.test/api")); + assertThat(sdk).isInstanceOf(HttpRequestInfo.class); + assertThat(sdk.uri()).isEqualTo(common.uri()); + assertThat(sdk.method()).isEqualTo(common.method()); + assertThat(sdk.headers()).isEqualTo(common.headers()); + assertThat(sdk.queryParams()).isEqualTo(common.queryParams()); + assertThat(sdk.ifModifiedSince()).isEqualTo(common.ifModifiedSince()); + assertThat(sdk.redirect()).isTrue(); + assertThat(sdk.contentType()).isEqualTo("text/plain"); + assertThat(sdk.body()).isSameAs(model); + assertThat(sdk.auth()).isSameAs(auth); + var copy = + new WorkflowHttpRequestInfo( + sdk.uri(), + sdk.method(), + sdk.redirect(), + sdk.headers(), + sdk.queryParams(), + sdk.body(), + sdk.auth(), + sdk.ifModifiedSince()); + assertThat(copy).isEqualTo(sdk); + assertThat(copy.headers().get("CONTENT-TYPE")).isEqualTo("text/plain"); + } + + @Test + void legacyJdkConstructorIsTheCommonResponseImplementation() { + @SuppressWarnings("unchecked") + java.net.http.HttpResponse nativeResponse = mock(java.net.http.HttpResponse.class); + var response = new DefaultHttpResponse(mock(WorkflowApplication.class), nativeResponse); + assertThat(response).isInstanceOf(JdkHttpResponse.class); + assertThat(response.nativeResponse(java.net.http.HttpResponse.class).orElseThrow()) + .isSameAs(nativeResponse); + } +} diff --git a/impl/http/pom.xml b/impl/http/pom.xml index c731cc174..0384c20a1 100644 --- a/impl/http/pom.xml +++ b/impl/http/pom.xml @@ -8,6 +8,10 @@ openworkflow-impl-http Open Workflow :: Impl :: HTTP + + cloud.openworkflow.sdk + openworkflow-common-http-jakarta + cloud.openworkflow.sdk openworkflow-impl-core @@ -26,6 +30,11 @@ junit-jupiter-engine test + + org.assertj + assertj-core + test + org.mockito mockito-core @@ -47,4 +56,4 @@ test - \ No newline at end of file + diff --git a/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/JakartaHttpRequest.java b/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/JakartaHttpRequest.java index 1772699b0..0b7d5f34c 100644 --- a/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/JakartaHttpRequest.java +++ b/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/JakartaHttpRequest.java @@ -15,6 +15,8 @@ */ package cloud.openworkflow.sdk.impl.jakarta.http; +import cloud.openworkflow.sdk.http.HttpBodyConverter; +import cloud.openworkflow.sdk.http.jakarta.JakartaHttpTransport; import cloud.openworkflow.sdk.impl.TaskContext; import cloud.openworkflow.sdk.impl.WorkflowApplication; import cloud.openworkflow.sdk.impl.WorkflowContext; @@ -26,16 +28,11 @@ import cloud.openworkflow.sdk.impl.http.WorkflowHttpResponse; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.client.Client; -import jakarta.ws.rs.client.Invocation.Builder; -import jakarta.ws.rs.client.WebTarget; import jakarta.ws.rs.core.MediaType; -import jakarta.ws.rs.core.Response; import java.util.Collection; import java.util.List; -import java.util.Map; -import java.util.Map.Entry; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionStage; +import java.util.concurrent.atomic.AtomicReference; class JakartaHttpRequest implements WorkflowHttpRequest { @@ -58,56 +55,85 @@ public JakartaHttpRequest( @Override public CompletableFuture invoke( WorkflowContext workflowContext, TaskContext taskContext) { - WebTarget target = + Client client = application .additionalObject( HttpClientResolver.HTTP_CLIENT_PROVIDER, workflowContext, taskContext) - .orElse(defaultClient) - .target(requestInfo.uri()); - Map queryParams = requestInfo.queryParams(); - for (Entry entry : queryParams.entrySet()) { - target = target.queryParam(entry.getKey(), entry.getValue()); - } - Builder request = target.request(); - String ifModifiedSince = requestInfo.ifModifiedSince(); - if (ifModifiedSince != null) { - request.header(WorkflowHttpHelper.IF_MODIFIED_SINCE_HEADER, ifModifiedSince); - } - requestInfo.headers().forEach(request::header); - if (workflowContext != null) { - requestDecorators.forEach(d -> d.decorate(request, workflowContext, taskContext)); - } - return WorkflowHttpHelper.processAuth( - requestInfo, request::header, workflowContext, taskContext) - .thenCompose(__ -> - doRequest( - request, - HttpConverterResolver.converter(application, workflowContext, taskContext), - taskContext)) - .exceptionallyCompose(ex -> - ex instanceof WebApplicationException webAppEx - ? CompletableFuture.failedFuture( - new WorkflowException( - WorkflowError.communication( - webAppEx.getResponse().getStatus(), taskContext, webAppEx) - .build(), - webAppEx)) - : CompletableFuture.failedFuture(WorkflowHttpHelper.fromError(ex, taskContext))); - } - - private CompletableFuture doRequest( - Builder request, HttpModelConverter converter, TaskContext task) { - CompletionStage future = - requestInfo.body() == null || requestInfo.body().isNull() - ? request.rx().method(requestInfo.method()) - : request - .rx() - .method( - requestInfo.method(), - converter.buildEntity( - requestInfo.body(), MediaType.valueOf(requestInfo.contentType()))); - return future - .toCompletableFuture() - .thenApply(r -> new JakartaHttpResponse(application, task, converter, r)); + .orElse(defaultClient); + AtomicReference converter = new AtomicReference<>(); + CompletableFuture result = new CompletableFuture<>(); + var executor = application.executorService(); + new JakartaHttpTransport(client, HttpBodyConverter.BYTES, executor) + .exchange( + requestInfo, + builder -> { + if (workflowContext != null) { + requestDecorators.forEach(d -> d.decorate(builder, workflowContext, taskContext)); + } + return WorkflowHttpHelper.processAuth( + requestInfo, builder::header, workflowContext, taskContext) + .thenApply(ignored -> { + // Preserve resolver timing: custom converters may inspect authorization. + HttpModelConverter resolved = + HttpConverterResolver.converter(application, workflowContext, taskContext); + converter.set(resolved); + return requestInfo.body() == null || requestInfo.body().isNull() + ? null + : resolved.buildEntity( + requestInfo.body(), MediaType.valueOf(requestInfo.contentType())); + }); + }) + .whenComplete((response, error) -> { + if (error != null) { + try { + result.completeExceptionally( + error instanceof WebApplicationException webAppEx + ? new WorkflowException( + WorkflowError.communication( + webAppEx.getResponse().getStatus(), taskContext, webAppEx) + .build(), + webAppEx) + : WorkflowHttpHelper.fromError(error, taskContext)); + } catch (RuntimeException | Error translationError) { + result.completeExceptionally(translationError); + } + return; + } + try { + CompletableFuture.runAsync( + () -> { + if (result.isDone()) { + response.close(); + } else { + try { + var owned = + new JakartaHttpResponse( + application, taskContext, converter.get(), response); + if (!result.complete(owned)) owned.close(); + } catch (RuntimeException ex) { + result.completeExceptionally( + WorkflowHttpHelper.fromError(ex, taskContext)); + } catch (Error ex) { + result.completeExceptionally(ex); + } + } + }, + executor) + .whenComplete((ignored, callbackError) -> { + // Failure translation is also part of delivery; never leave its future pending. + if (callbackError != null) result.completeExceptionally(callbackError); + }); + } catch (RuntimeException | Error schedulingError) { + if (response != null) { + try { + response.close(); + } catch (RuntimeException | Error closeError) { + if (closeError != schedulingError) schedulingError.addSuppressed(closeError); + } + } + result.completeExceptionally(schedulingError); + } + }); + return result; } } diff --git a/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/JakartaHttpResponse.java b/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/JakartaHttpResponse.java index 44e0d2aa5..5ba6c2252 100644 --- a/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/JakartaHttpResponse.java +++ b/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/JakartaHttpResponse.java @@ -17,118 +17,14 @@ import cloud.openworkflow.sdk.impl.TaskContext; import cloud.openworkflow.sdk.impl.WorkflowApplication; -import cloud.openworkflow.sdk.impl.WorkflowModel; -import cloud.openworkflow.sdk.impl.http.WorkflowHttpHelper; import cloud.openworkflow.sdk.impl.http.WorkflowHttpResponse; -import jakarta.ws.rs.ProcessingException; import jakarta.ws.rs.core.Response; -import java.util.Arrays; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.OptionalLong; - -class JakartaHttpResponse implements WorkflowHttpResponse { - - private final WorkflowApplication app; - private HttpModelConverter converter; - private Response response; - private TaskContext taskContext; +/** Compatibility constructor; all HTTP behavior is implemented in common. */ +class JakartaHttpResponse extends cloud.openworkflow.sdk.http.jakarta.JakartaHttpResponse + implements WorkflowHttpResponse { public JakartaHttpResponse( - WorkflowApplication app, - TaskContext taskContext, - HttpModelConverter converter, - Response response) { - this.app = app; - this.converter = converter; - this.response = response; - this.taskContext = taskContext; - } - - @Override - public byte[] contentAsByteArray() { - return response.readEntity(byte[].class); - } - - @Override - public int status() { - return response.getStatus(); - } - - @Override - public OptionalLong lastModified() { - Date date = response.getLastModified(); - return date == null ? OptionalLong.empty() : OptionalLong.of(date.getTime()); - } - - @Override - public void close() { - response.close(); - } - - @Override - public String reasonPhrase() { - return response.getStatusInfo().getReasonPhrase(); - } - - @Override - public String errorDetails() { - try { - return response.readEntity(String.class); - } catch (ProcessingException ex) { - return ex.getMessage(); - } - } - - @Override - public WorkflowModel contentAsModel() { - try { - return converter.buildModel(app.modelFactory(), response); - } catch (ProcessingException ex) { - throw WorkflowHttpHelper.fromError(ex, taskContext); - } - } - - @Override - public String toString() { - return "JakartaHttpResponse [response=" + response + "]"; - } - - @Override - public byte[] responseAsByteArray() { - return WorkflowHttpHelper.responseAsByteArray(this, isHttp2()); - } - - @Override - public Map> headers() { - return response.getHeaders(); - } - - @Override - public String getHeader(String name) { - return response.getHeaderString(name); - } - - private static final Collection FORBIDDEN_HTTP2_HEADERS_LOWERCASE = - Arrays.asList("connection", "keep-alive", "proxy-connection", "transfer-encoding", "upgrade"); - - private boolean isHttp2() { - for (String str : response.getHeaders().keySet()) { - if (containsUpperCase(str) || FORBIDDEN_HTTP2_HEADERS_LOWERCASE.contains(str.toLowerCase())) { - return false; - } - } - return true; - } - - private boolean containsUpperCase(String str) { - for (int i = 0; i < str.length(); i++) { - if (Character.isUpperCase(str.charAt(i))) { - return true; - } - } - return false; + WorkflowApplication app, TaskContext task, HttpModelConverter converter, Response response) { + super(response, new JakartaWorkflowBodyConverter(app.modelFactory(), converter, task)); } } diff --git a/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/JakartaWorkflowBodyConverter.java b/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/JakartaWorkflowBodyConverter.java new file mode 100644 index 000000000..cb376cdd4 --- /dev/null +++ b/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/JakartaWorkflowBodyConverter.java @@ -0,0 +1,49 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.impl.jakarta.http; + +import cloud.openworkflow.sdk.http.*; +import cloud.openworkflow.sdk.impl.*; +import cloud.openworkflow.sdk.impl.http.WorkflowHttpHelper; +import jakarta.ws.rs.ProcessingException; +import jakarta.ws.rs.core.Response; +import java.util.Optional; + +/** SDK conversion and task error enrichment only; no HTTP response state. */ +final class JakartaWorkflowBodyConverter implements HttpBodyConverter { + private final WorkflowModelFactory factory; + private final HttpModelConverter converter; + private final TaskContext task; + + JakartaWorkflowBodyConverter( + WorkflowModelFactory factory, HttpModelConverter converter, TaskContext task) { + this.factory = factory; + this.converter = converter; + this.task = task; + } + + public Optional convert(HttpResponse response, Class type) { + if (type != WorkflowModel.class) return HttpBodyConverter.BYTES.convert(response, type); + try { + return Optional.of( + type.cast( + converter.buildModel( + factory, response.nativeResponse(Response.class).orElseThrow()))); + } catch (ProcessingException ex) { + throw WorkflowHttpHelper.fromError(ex, task); + } + } +} diff --git a/impl/http/src/test/java/cloud/openworkflow/sdk/impl/jakarta/http/SharedResponseHeadersTest.java b/impl/http/src/test/java/cloud/openworkflow/sdk/impl/jakarta/http/SharedResponseHeadersTest.java new file mode 100644 index 000000000..537ddc393 --- /dev/null +++ b/impl/http/src/test/java/cloud/openworkflow/sdk/impl/jakarta/http/SharedResponseHeadersTest.java @@ -0,0 +1,235 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.impl.jakarta.http; + +import static org.assertj.core.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import cloud.openworkflow.sdk.impl.TaskContext; +import cloud.openworkflow.sdk.impl.WorkflowApplication; +import cloud.openworkflow.sdk.impl.WorkflowContext; +import cloud.openworkflow.sdk.impl.WorkflowException; +import cloud.openworkflow.sdk.impl.WorkflowPosition; +import cloud.openworkflow.sdk.impl.http.WorkflowHttpRequestInfo; +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.CompletionStageRxInvoker; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.client.WebTarget; +import jakarta.ws.rs.core.Response; +import java.net.URI; +import java.util.Date; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Test; + +class SharedResponseHeadersTest { + @Test + void preservesNetworkFailuresEvenWhenTheApplicationExecutorHasStopped() { + for (boolean translationFails : new boolean[] {false, true}) { + Client client = mock(Client.class); + WebTarget target = mock(WebTarget.class); + Invocation.Builder builder = mock(Invocation.Builder.class); + CompletionStageRxInvoker invoker = mock(CompletionStageRxInvoker.class); + when(client.target(any(URI.class))).thenReturn(target); + when(target.request()).thenReturn(builder); + when(builder.rx()).thenReturn(invoker); + var networkFailure = new java.net.SocketTimeoutException("response timeout"); + when(invoker.method(anyString())).thenReturn(CompletableFuture.failedFuture(networkFailure)); + var executor = mock(ExecutorService.class); + org.mockito.Mockito.doThrow(new RejectedExecutionException("application stopped")) + .when(executor) + .execute(any(Runnable.class)); + var app = mock(WorkflowApplication.class); + when(app.executorService()).thenReturn(executor); + var task = mock(TaskContext.class); + var position = mock(WorkflowPosition.class); + when(task.position()).thenReturn(position); + when(position.jsonPointer()).thenReturn("do/0/callApi"); + var translationFailure = new IllegalStateException("failure translation"); + if (translationFails) when(task.position()).thenThrow(translationFailure); + var request = + new JakartaHttpRequest( + app, + client, + WorkflowHttpRequestInfo.builder("GET").build(URI.create("http://localhost/")), + List.of()); + var result = request.invoke(null, task); + var caught = + catchThrowableOfType(ExecutionException.class, () -> result.get(5, TimeUnit.SECONDS)); + assertThat(caught).isNotNull(); + if (translationFails) { + assertThat(caught).hasCause(translationFailure); + } else { + assertThat(caught.getCause()) + .isInstanceOf(WorkflowException.class) + .hasCause(networkFailure); + var mapped = ((WorkflowException) caught.getCause()).getWorkflowError(); + assertThat(mapped.instance()).isEqualTo("do/0/callApi"); + assertThat(mapped.status()).isEqualTo(cloud.openworkflow.sdk.types.Errors.TIMEOUT.status()); + } + verify(executor, org.mockito.Mockito.never()).execute(any(Runnable.class)); + } + } + + @Test + void rejectedApplicationTasksCloseUnexposedResponses() { + Client client = mock(Client.class); + WebTarget target = mock(WebTarget.class); + Invocation.Builder builder = mock(Invocation.Builder.class); + CompletionStageRxInvoker invoker = mock(CompletionStageRxInvoker.class); + Response response = mock(Response.class); + when(client.target(any(URI.class))).thenReturn(target); + when(target.request()).thenReturn(builder); + when(builder.rx()).thenReturn(invoker); + when(invoker.method(anyString())).thenReturn(CompletableFuture.completedFuture(response)); + var executor = mock(ExecutorService.class); + var rejected = new RejectedExecutionException("application stopped"); + var closeFailure = new IllegalStateException("provider close failure"); + org.mockito.Mockito.doThrow(rejected).when(executor).execute(any(Runnable.class)); + org.mockito.Mockito.doThrow(closeFailure).when(response).close(); + var app = mock(WorkflowApplication.class); + when(app.executorService()).thenReturn(executor); + var request = + new JakartaHttpRequest( + app, + client, + WorkflowHttpRequestInfo.builder("GET").build(URI.create("http://localhost/")), + List.of()); + var result = request.invoke(null, mock(TaskContext.class)); + assertThatThrownBy(() -> result.get(5, TimeUnit.SECONDS)).hasCause(rejected); + assertThat(rejected.getSuppressed()).containsExactly(closeFailure); + verify(response).close(); + verify(response, org.mockito.Mockito.never()).bufferEntity(); + verify(executor, org.mockito.Mockito.never()).shutdown(); + verify(client, org.mockito.Mockito.never()).close(); + } + + @Test + void buffersResponsesOnTheApplicationExecutor() throws Exception { + Client client = mock(Client.class); + WebTarget target = mock(WebTarget.class); + Invocation.Builder builder = mock(Invocation.Builder.class); + CompletionStageRxInvoker invoker = mock(CompletionStageRxInvoker.class); + Response response = mock(Response.class); + AtomicReference bufferingThread = new AtomicReference<>(); + when(client.target(any(URI.class))).thenReturn(target); + when(target.request()).thenReturn(builder); + when(builder.rx()).thenReturn(invoker); + when(invoker.method(anyString())).thenReturn(CompletableFuture.completedFuture(response)); + when(response.hasEntity()).thenReturn(true); + when(response.bufferEntity()) + .thenAnswer(ignored -> { + bufferingThread.set(Thread.currentThread()); + return true; + }); + try (var executor = Executors.newCachedThreadPool(r -> new Thread(r, "sdk-http-response"))) { + var app = mock(WorkflowApplication.class); + when(app.executorService()).thenReturn(executor); + var request = + new JakartaHttpRequest( + app, + client, + WorkflowHttpRequestInfo.builder("GET").build(URI.create("http://localhost/")), + List.of()); + try (var owned = request.invoke(null, mock(TaskContext.class)).get(5, TimeUnit.SECONDS)) { + assertThat(bufferingThread.get().getName()).isEqualTo("sdk-http-response"); + } + assertThat(executor.isShutdown()).isFalse(); + verify(client, org.mockito.Mockito.never()).close(); + } + verify(response).close(); + } + + @Test + void completesTheSdkDeliveryOnProviderErrors() { + try (var executor = Executors.newCachedThreadPool()) { + for (boolean translationFails : new boolean[] {false, true}) { + for (Throwable failure : + List.of( + new AssertionError("provider buffering failure"), + new CompletionException("provider buffering failure", null))) { + Client client = mock(Client.class); + WebTarget target = mock(WebTarget.class); + Invocation.Builder builder = mock(Invocation.Builder.class); + CompletionStageRxInvoker invoker = mock(CompletionStageRxInvoker.class); + Response nativeResponse = mock(Response.class); + when(client.target(any(URI.class))).thenReturn(target); + when(target.request()).thenReturn(builder); + when(builder.rx()).thenReturn(invoker); + when(invoker.method(anyString())) + .thenReturn(CompletableFuture.completedFuture(nativeResponse)); + when(nativeResponse.hasEntity()).thenThrow(failure); + var app = mock(WorkflowApplication.class); + when(app.executorService()).thenReturn(executor); + var request = + new JakartaHttpRequest( + app, + client, + WorkflowHttpRequestInfo.builder("GET").build(URI.create("http://localhost/")), + List.of()); + var task = mock(TaskContext.class); + var position = mock(WorkflowPosition.class); + when(task.position()).thenReturn(position); + when(position.jsonPointer()).thenReturn("do/0/callApi"); + var translationFailure = new IllegalStateException("failure translation"); + if (translationFails) when(task.position()).thenThrow(translationFailure); + var result = request.invoke(mock(WorkflowContext.class), task); + var caught = + catchThrowableOfType(ExecutionException.class, () -> result.get(5, TimeUnit.SECONDS)); + assertThat(caught).isNotNull(); + if (failure instanceof Error) assertThat(caught).hasCause(failure); + else if (translationFails) assertThat(caught).hasCause(translationFailure); + else + assertThat(caught.getCause()).isInstanceOf(WorkflowException.class).hasCause(failure); + verify(nativeResponse).close(); + } + } + } + } + + @Test + void usesProviderSerializationForTypedHeaders() { + var nativeResponse = + Response.status(200).header("Last-Modified", new Date(784111777000L)).build(); + String expected = nativeResponse.getHeaderString("Last-Modified"); + try (var response = + new JakartaHttpResponse( + mock(WorkflowApplication.class), + mock(TaskContext.class), + mock(HttpModelConverter.class), + nativeResponse)) { + assertThat(response.firstHeader("last-modified")).isEqualTo(expected); + assertThat(response.stringHeaders().get("last-modified").getFirst()).isEqualTo(expected); + assertThat(response.nativeResponse(Response.class).orElseThrow()).isSameAs(nativeResponse); + assertThat( + new String( + response.responseAsByteArray(), java.nio.charset.StandardCharsets.ISO_8859_1) + .contains("Last-Modified: " + expected)) + .isTrue(); + } + } +} diff --git a/impl/openapi-jackson/pom.xml b/impl/openapi-jackson/pom.xml index 30830539c..f09683e1f 100644 --- a/impl/openapi-jackson/pom.xml +++ b/impl/openapi-jackson/pom.xml @@ -8,6 +8,9 @@ openworkflow-impl-openapi Open Workflow :: Impl :: OpenAPI:: Jackson +cloud.openworkflow.sdkopenworkflow-common-openapi +com.squareup.okhttp3mockwebservertest + cloud.openworkflow.sdk openworkflow-impl-core diff --git a/impl/openapi-jackson/src/test/java/cloud/openworkflow/sdk/impl/executors/openapi/jackson/StandaloneOpenAPITest.java b/impl/openapi-jackson/src/test/java/cloud/openworkflow/sdk/impl/executors/openapi/jackson/StandaloneOpenAPITest.java new file mode 100644 index 000000000..4405b1c01 --- /dev/null +++ b/impl/openapi-jackson/src/test/java/cloud/openworkflow/sdk/impl/executors/openapi/jackson/StandaloneOpenAPITest.java @@ -0,0 +1,677 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.impl.executors.openapi.jackson; + +import static org.assertj.core.api.Assertions.*; + +import cloud.openworkflow.sdk.api.WorkflowFormat; +import cloud.openworkflow.sdk.http.*; +import cloud.openworkflow.sdk.impl.executors.openapi.*; +import cloud.openworkflow.sdk.impl.executors.openapi.OpenAPIClient.ServerFallback; +import java.io.IOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.TimeUnit; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import org.junit.jupiter.api.Test; + +/** Compiled third-party usage example using the optional SDK Jackson reader. */ +class StandaloneOpenAPITest { + private static final String DOCUMENT = + """ + { + "openapi":"3.0.3", + "servers":[{"url":"%s"}], + "paths":{"/pets/{id}":{"post":{ + "operationId":"save", + "parameters":[ + {"name":"id","in":"path","required":true,"schema":{"type":"string"}}, + {"name":"q","in":"query","required":false,"schema":{"type":"string"}}, + {"name":"lang","in":"query","required":true,"schema":{"default":"en"}}, + {"name":"unused","in":"query","schema":{"default":"ignored"}}, + {"name":"Authorization","in":"header","schema":{"type":"string"}}, + {"name":"cookieValue","in":"cookie","schema":{"type":"string"}} + ], + "requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Pet"}}}} + }}}, + "components":{"schemas":{"Pet":{"type":"object","required":["name"],"properties":{"name":{"type":"string"}}}}} + } + """; + + private UnifiedOpenAPI read(String server) { + return new JacksonUnifiedOpenAPIReader() + .read("api.json", DOCUMENT.formatted(server).getBytes(StandardCharsets.UTF_8)); + } + + private byte[] json(Map value) { + return WorkflowFormat.JSON.mapper().writeValueAsBytes(value); + } + + private record TrackingResponse(int status, java.util.concurrent.atomic.AtomicInteger closes) + implements HttpResponse { + public byte[] body() { + return new byte[0]; + } + + public Map> headers() { + return Map.of(); + } + + public void close() { + closes.incrementAndGet(); + } + } + + @Test + void closesAnUndeliverableResponseIfStatusInspectionFails() { + for (boolean fatal : new boolean[] {false, true}) { + Throwable failure = + fatal ? new AssertionError("status") : new IllegalStateException("status"); + Throwable cleanup = + fatal ? new AssertionError("cleanup") : new IllegalStateException("cleanup"); + var closes = new java.util.concurrent.atomic.AtomicInteger(); + HttpTransport transport = + new HttpTransport() { + public CompletableFuture execute(HttpRequestInfo request) { + return CompletableFuture.completedFuture( + new HttpResponse() { + public int status() { + if (failure instanceof Error error) throw error; + throw (RuntimeException) failure; + } + + public byte[] body() { + return new byte[0]; + } + + public Map> headers() { + return Map.of(); + } + + public void close() { + closes.incrementAndGet(); + if (cleanup instanceof Error error) throw error; + throw (RuntimeException) cleanup; + } + }); + } + + public void close() {} + }; + var result = + withServers(List.of("https://first.test", "https://second.test")) + .execute( + Map.of("id", 1), + this::json, + transport, + ServerFallback.ON_HTTP_OR_TRANSPORT_FAILURE); + assertThat(catchThrowableOfType(CompletionException.class, result::join).getCause()) + .isSameAs(failure); + assertThat(closes.get()).isEqualTo(1); + assertThat(failure.getSuppressed()).isEqualTo(new Throwable[] {cleanup}); + } + } + + @Test + void singleAttemptCancellationReachesTheTransportDeliveryFuture() { + for (boolean fallbackEnabled : new boolean[] {false, true}) { + var pending = new CompletableFuture(); + HttpTransport transport = + new HttpTransport() { + public CompletableFuture execute(HttpRequestInfo request) { + return pending; + } + + public void close() {} + }; + var api = + withServers( + fallbackEnabled + ? List.of("https://only.test") + : List.of("https://one.test", "https://two.test")); + var result = + api.execute( + Map.of("id", 1), + this::json, + transport, + fallbackEnabled ? ServerFallback.ON_HTTP_OR_TRANSPORT_FAILURE : ServerFallback.NONE); + assertThat(result.cancel(true)).isTrue(); + assertThat(pending.isCancelled()).isTrue(); + } + } + + @Test + void cleanupFailureDoesNotVetoSelectedFallback() { + for (boolean fatal : new boolean[] {false, true}) { + var calls = new java.util.concurrent.atomic.AtomicInteger(); + HttpTransport transport = + new HttpTransport() { + public CompletableFuture execute(HttpRequestInfo request) { + int status = calls.incrementAndGet() == 1 ? 503 : 200; + return CompletableFuture.completedFuture( + new HttpResponse() { + public int status() { + return status; + } + + public byte[] body() { + return new byte[0]; + } + + public Map> headers() { + return Map.of(); + } + + public void close() { + if (fatal) throw new AssertionError("cleanup"); + throw new IllegalStateException("cleanup"); + } + }); + } + + public void close() {} + }; + var response = + withServers(List.of("https://first.test", "https://second.test")) + .execute( + Map.of("id", 1), + this::json, + transport, + ServerFallback.ON_HTTP_OR_TRANSPORT_FAILURE) + .join(); + assertThat(response.status()).isEqualTo(200); + assertThat(calls.get()).isEqualTo(2); + } + } + + @Test + void fallbackOwnsDiscardedAndCancelledResponsesButNotDeliveredResponses() { + for (boolean cancelled : new boolean[] {false, true}) { + var discarded = new TrackingResponse(503, new java.util.concurrent.atomic.AtomicInteger()); + var last = new TrackingResponse(200, new java.util.concurrent.atomic.AtomicInteger()); + var pending = new CompletableFuture(); + var calls = new java.util.concurrent.atomic.AtomicInteger(); + HttpTransport transport = + new HttpTransport() { + public CompletableFuture execute(HttpRequestInfo request) { + if (calls.incrementAndGet() == 1) return CompletableFuture.completedFuture(discarded); + assertThat(discarded.closes().get()).isEqualTo(1); + return pending; + } + + public void close() { + fail("borrowed transport"); + } + }; + var result = + withServers(List.of("https://first.test", "https://second.test")) + .execute( + Map.of("id", 1), + this::json, + transport, + ServerFallback.ON_HTTP_OR_TRANSPORT_FAILURE); + if (cancelled) assertThat(result.cancel(true)).isTrue(); + pending.complete(last); + if (cancelled) assertThat(last.closes().get()).isEqualTo(1); + else { + assertThat(result.join()).isSameAs(last); + assertThat(last.closes().get()).isEqualTo(0); + result.join().close(); + assertThat(last.closes().get()).isEqualTo(1); + } + } + } + + @Test + void discoversTheSdkReaderFromTheExistingArtifact() { + var reader = + java.util.ServiceLoader.load( + cloud.openworkflow.sdk.impl.additional.NamedSuppliedAdditionalObject.class) + .stream() + .map(java.util.ServiceLoader.Provider::get) + .filter( + provider -> provider.name().equals(UnifiedOpenAPIReader.UNIFIED_OPEN_API_READER)) + .findFirst() + .orElseThrow() + .get(); + assertThat(reader instanceof JacksonUnifiedOpenAPIReader).isTrue(); + } + + @Test + void bindsInheritedReferencesAndSharedParameterNames() { + var document = + new JacksonUnifiedOpenAPIReader() + .read( + "api.yaml", + """ + openapi: 3.0.3 + servers: + - url: https://example.test + paths: + /items/{id}: + parameters: + - name: id + in: path + required: true + - $ref: '#/components/parameters/IdAlias' + - name: lang + in: query + required: true + schema: {default: en} + post: + operationId: save + parameters: + - name: id + in: query + required: true + - name: lang + in: query + required: true + schema: {default: fr} + components: + parameters: + IdAlias: + $ref: '#/components/parameters/Id' + Id: + name: id + in: header + required: true + """ + .getBytes(StandardCharsets.UTF_8)); + var api = new OpenAPIClient(document, "save"); + var operation = api.operation(); + var reconstructed = + new OperationDefinition( + document, operation.getOperation(), operation.getPath(), operation.getMethod()); + assertThat(reconstructed.getParameters()).isEqualTo(operation.getParameters()); + var request = api.prepare(0, Map.of("id", "shared", "extra", "body"), this::json); + assertThat(request.uri()).isEqualTo(URI.create("https://example.test/items/shared")); + assertThat(request.headers()).isEqualTo(Map.of("id", "shared")); + assertThat(request.queryParams()).isEqualTo(Map.of("id", "shared", "lang", "fr")); + assertThat(WorkflowFormat.JSON.mapper().readValue(request.body(), Map.class)) + .isEqualTo(Map.of("extra", "body")); + } + + @Test + void selectsOperationThenPathThenRootServers() { + var document = + new JacksonUnifiedOpenAPIReader() + .read( + "api.yaml", + """ + openapi: 3.0.3 + servers: + - url: /root + paths: + /items: + servers: + - url: /path + get: + operationId: operation + servers: + - url: /operation + post: + operationId: path + /other: + get: + operationId: root + """ + .getBytes(StandardCharsets.UTF_8)); + for (var expected : + Map.of( + "operation", "https://example.test/operation/items", + "path", "https://example.test/path/items", + "root", "https://example.test/root/other") + .entrySet()) { + var api = + new OpenAPIClient( + document, expected.getKey(), URI.create("https://example.test/api.yaml")); + var operation = api.operation(); + var reconstructed = + new OperationDefinition( + document, operation.getOperation(), operation.getPath(), operation.getMethod()); + assertThat(reconstructed.getServers()).isEqualTo(operation.getServers()); + assertThat(api.prepare(0, Map.of(), this::json).uri()) + .isEqualTo(URI.create(expected.getValue())); + } + } + + @Test + void rejectsServerUrisWithoutAnAbsoluteHost() { + for (String server : List.of("https:/api", "https:api", "https:///api")) { + var api = withServers(List.of(server)); + assertThatExceptionOfType(IllegalArgumentException.class) + .as(server) + .isThrownBy(() -> api.prepare(0, Map.of("id", 1), this::json)); + } + var bound = + OpenAPIRequest.bind( + withServers(List.of("https://example.test")).operation(), Map.of("id", 1)); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> bound.prepare(URI.create("/relative"), this::json)); + } + + @Test + void fallbackOwnsSerializedBodySnapshot() { + var api = withServers(List.of("http://first", "http://second")); + byte[] encoded = "body".getBytes(StandardCharsets.UTF_8); + List> requests = new ArrayList<>(); + CompletableFuture first = new CompletableFuture<>(); + HttpTransport transport = + new HttpTransport() { + public CompletableFuture execute( + cloud.openworkflow.sdk.http.HttpRequestInfo request) { + requests.add(request); + return requests.size() == 1 + ? first + : CompletableFuture.completedFuture( + new HttpResponseData(200, Map.of(), new byte[0])); + } + + public void close() { + fail("must remain borrowed"); + } + }; + var result = + api.execute( + Map.of("id", 1), + ignored -> encoded, + transport, + ServerFallback.ON_HTTP_OR_TRANSPORT_FAILURE); + encoded[0] = 'X'; + first.complete(new HttpResponseData(503, Map.of(), new byte[0])); + assertThat(result.join().status()).isEqualTo(200); + assertThat(requests.size()).isEqualTo(2); + assertThat(requests.get(1).body()).isEqualTo("body".getBytes(StandardCharsets.UTF_8)); + } + + @Test + void packagesReflectionMetadataWithStandaloneReader() throws Exception { + try (var stream = + getClass() + .getResourceAsStream( + "/META-INF/native-image/cloud.openworkflow.sdk/openworkflow-impl-openapi/reflect-config.json")) { + assertThat(stream).isNotNull(); + var registrations = WorkflowFormat.JSON.mapper().readValue(stream, List.class); + var names = registrations.stream().map(entry -> ((Map) entry).get("name")).toList(); + assertThat(names.contains(UnifiedOpenAPI.class.getName())).isTrue(); + for (Class nested : UnifiedOpenAPI.class.getDeclaredClasses()) { + assertThat(names.contains(nested.getName())).as(nested.getName()).isTrue(); + } + } + } + + @Test + void documentToRequestToInjectedJdkTransport() throws Exception { + try (MockWebServer server = new MockWebServer(); + JdkHttpTransport transport = new JdkHttpTransport()) { + server.start(); + server.enqueue(new MockResponse().setResponseCode(201).setBody("saved")); + OpenAPIClient api = new OpenAPIClient(read(server.url("/v1").toString()), "save"); + HttpRequestInfo request = + api.prepare( + 0, + Map.of( + "id", + "café /+", + "q", + "tea + café", + "name", + "N", + "Authorization", + "Bearer resolved"), + this::json); + assertThat(request.method()).isEqualTo("POST"); + assertThat(request.uri().getRawPath()).isEqualTo("/v1/pets/caf%C3%A9%20%2F%2B"); + assertThat(request.queryParams()).isEqualTo(Map.of("q", "tea + café", "lang", "en")); + cloud.openworkflow.sdk.http.HttpResponse response = + transport.execute(request).get(10, TimeUnit.SECONDS); + assertThat(response.status()).isEqualTo(201); + assertThat(new String(response.body(), StandardCharsets.UTF_8)).isEqualTo("saved"); + var received = server.takeRequest(10, TimeUnit.SECONDS); + assertThat(received).isNotNull(); + assertThat(received.getHeader("Authorization")).isEqualTo("Bearer resolved"); + assertThat(received.getPath().contains("q=tea%20%2B%20caf%C3%A9")).isTrue(); + assertThat( + WorkflowFormat.JSON.mapper().readValue(received.getBody().readByteArray(), Map.class)) + .isEqualTo(Map.of("name", "N")); + } + } + + @Test + void validatesDocumentOperationAndRequiredPath() { + var reader = new JacksonUnifiedOpenAPIReader(); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> reader.read("broken.json", "{".getBytes(StandardCharsets.UTF_8))); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new OpenAPIClient(read("http://localhost"), "absent")) + .withMessageContaining("absent"); + OpenAPIClient api = new OpenAPIClient(read("http://localhost"), "save"); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> api.prepare(0, Map.of(), this::json)) + .withMessageContaining("id"); + Map nullId = new HashMap<>(); + nullId.put("id", null); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> api.prepare(0, nullId, this::json)); + } + + @Test + void retainsRequiredDefaultsLeftoverBodyAndUnvalidatedBodyProperties() { + OpenAPIClient api = new OpenAPIClient(read("http://localhost"), "save"); + // Body required fields and cookies were never validated/placed by the SDK. + HttpRequestInfo request = + api.prepare(0, Map.of("id", 3, "extra", 4, "cookieValue", "c"), this::json); + assertThat(request.queryParams()).isEqualTo(Map.of("lang", "en")); + assertThat(WorkflowFormat.JSON.mapper().readValue(request.body(), Map.class)) + .isEqualTo(Map.of("extra", 4, "cookieValue", "c")); + assertThat(api.operation().getParameters().stream().filter(p -> p.in().equals("body")).count()) + .isEqualTo(1); + } + + @Test + void readsSwaggerJsonAndOpenApiYamlAndLocalReferences() { + var reader = new JacksonUnifiedOpenAPIReader(); + for (String format : List.of("json", "yaml")) { + String text = + """ + {"swagger":"2.0","host":"localhost:1234","schemes":["http"],"basePath":"/v2", + "paths":{"/pet":{"post":{"operationId":"add","parameters":[{"name":"body","in":"body","schema":{"$ref":"#/definitions/Pet"}}]}}}, + "definitions":{"Pet":{"properties":{"name":{"type":"string"}}}}} + """; + var document = reader.read("api." + format, text.getBytes(StandardCharsets.UTF_8)); + var api = new OpenAPIClient(document, "add"); + assertThat(document.swaggerVersion()).isEqualTo(UnifiedOpenAPI.SwaggerVersion.SWAGGER_V2); + assertThat(api.prepare(0, Map.of("name", "pet"), this::json).uri()) + .isEqualTo(URI.create("http://localhost:1234/v2/pet")); + assertThat(api.operation().getParameters().getFirst().in()).isEqualTo("body"); + } + var yaml = + reader.read( + "api.yaml", + """ + openapi: 3.0.3 + servers: + - url: /v1 + paths: + /pet: + get: + operationId: get + """ + .getBytes(StandardCharsets.UTF_8)); + var api = new OpenAPIClient(yaml, "get", URI.create("http://localhost/spec/api.yaml")); + assertThat(api.prepare(0, Map.of(), this::json).uri()) + .isEqualTo(URI.create("http://localhost/v1/pet")); + assertThat(api.prepare(0, Map.of(), this::json).body()).isNull(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new OpenAPIClient(yaml, "get").prepare(0, Map.of(), this::json)); + } + + private OpenAPIClient withServers(List servers) { + UnifiedOpenAPI d = read("http://localhost"); + return new OpenAPIClient( + new UnifiedOpenAPI( + d.swagger(), + servers.stream().map(UnifiedOpenAPI.Server::new).toList(), + d.host(), + d.basePath(), + d.schemes(), + d.paths(), + d.components(), + d.definitions(), + d.parameters()), + "save"); + } + + @Test + void fallbackIsExplicitAndPreservesHttpResponsesAndTransportErrors() throws Exception { + try (MockWebServer first = new MockWebServer(); + MockWebServer second = new MockWebServer(); + JdkHttpTransport transport = new JdkHttpTransport()) { + first.start(); + second.start(); + var api = withServers(List.of(first.url("/").toString(), second.url("/").toString())); + first.enqueue(new MockResponse().setResponseCode(503).setBody("first")); + assertThat( + api.execute(Map.of("id", 1), this::json, transport, ServerFallback.NONE) + .get(10, TimeUnit.SECONDS) + .status()) + .isEqualTo(503); + assertThat(second.getRequestCount()).isEqualTo(0); + first.enqueue(new MockResponse().setResponseCode(503)); + second.enqueue(new MockResponse().setResponseCode(409).setBody("conflict")); + cloud.openworkflow.sdk.http.HttpResponse finalResponse = + api.execute( + Map.of("id", 1), + this::json, + transport, + ServerFallback.ON_HTTP_OR_TRANSPORT_FAILURE) + .get(10, TimeUnit.SECONDS); + assertThat(finalResponse.status()).isEqualTo(409); + assertThat(new String(finalResponse.body(), StandardCharsets.UTF_8)).isEqualTo("conflict"); + assertThat(second.getRequestCount()).isEqualTo(1); + assertThat(second.takeRequest(10, TimeUnit.SECONDS).getMethod()).isEqualTo("POST"); + } + IOException failure = new IOException("network failure"); + HttpTransport failed = + new HttpTransport() { + public CompletableFuture execute( + cloud.openworkflow.sdk.http.HttpRequestInfo request) { + return CompletableFuture.failedFuture(failure); + } + + public void close() { + fail("OpenAPI does not own the transport"); + } + }; + var api = withServers(List.of("http://first", "http://second")); + assertThat( + catchThrowableOfType( + CompletionException.class, + () -> + api.execute( + Map.of("id", 1), + this::json, + failed, + ServerFallback.ON_HTTP_OR_TRANSPORT_FAILURE) + .join()) + .getCause()) + .isSameAs(failure); + List attempted = new ArrayList<>(); + HttpTransport recovering = + new HttpTransport() { + public CompletableFuture execute( + cloud.openworkflow.sdk.http.HttpRequestInfo request) { + attempted.add(request.uri()); + return attempted.size() == 1 + ? CompletableFuture.failedFuture(failure) + : CompletableFuture.completedFuture( + new HttpResponseData(200, Map.of(), new byte[0])); + } + + public void close() { + fail("OpenAPI does not own the transport"); + } + }; + assertThat( + api.execute( + Map.of("id", 2), + this::json, + recovering, + ServerFallback.ON_HTTP_OR_TRANSPORT_FAILURE) + .join() + .status()) + .isEqualTo(200); + assertThat(attempted) + .isEqualTo(List.of(URI.create("http://first/pets/2"), URI.create("http://second/pets/2"))); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> withServers(List.of()).prepare(0, Map.of("id", 1), this::json)); + } + + @Test + void concurrentInvocationsShareOnlyOperationDefinition() { + var api = new OpenAPIClient(read("http://localhost"), "save"); + List> requests = new ArrayList<>(); + List> pending = new ArrayList<>(); + HttpTransport transport = + new HttpTransport() { + public CompletableFuture execute( + cloud.openworkflow.sdk.http.HttpRequestInfo request) { + requests.add(request); + var result = new CompletableFuture(); + pending.add(result); + return result; + } + + public void close() { + fail("must remain borrowed"); + } + }; + var first = + api.execute( + Map.of("id", "one", "name", "first", "Authorization", "Bearer one"), + this::json, + transport, + ServerFallback.NONE); + var second = + api.execute( + Map.of("id", "two", "name", "second", "Authorization", "Bearer two"), + this::json, + transport, + ServerFallback.NONE); + assertThat(first.isDone()).isFalse(); + assertThat(second.isDone()).isFalse(); + pending.get(1).complete(new HttpResponseData(202, Map.of(), new byte[0])); + pending.get(0).complete(new HttpResponseData(201, Map.of(), new byte[0])); + assertThat(first.join().status()).isEqualTo(201); + assertThat(second.join().status()).isEqualTo(202); + assertThat(requests.get(0).uri().getPath()).isEqualTo("/pets/one"); + assertThat(requests.get(1).uri().getPath()).isEqualTo("/pets/two"); + assertThat(requests.get(0).headers().get("Authorization")).isEqualTo("Bearer one"); + assertThat(requests.get(1).headers().get("Authorization")).isEqualTo("Bearer two"); + assertThat(WorkflowFormat.JSON.mapper().readValue(requests.get(0).body(), Map.class)) + .isEqualTo(Map.of("name", "first")); + assertThat(WorkflowFormat.JSON.mapper().readValue(requests.get(1).body(), Map.class)) + .isEqualTo(Map.of("name", "second")); + } +} diff --git a/impl/pom.xml b/impl/pom.xml index 14c5910fd..a2345fbf3 100644 --- a/impl/pom.xml +++ b/impl/pom.xml @@ -11,9 +11,7 @@ 2.5.252 5.2.4 - 4.0.0 2.0.0-alpha1 - 4.0.3 9.2.1 3.7.1 25.5.5.0.3 @@ -135,17 +133,6 @@ ulid-creator ${version.com.github.f4b6a3} - - jakarta.ws.rs - jakarta.ws.rs-api - ${version.jakarta.ws.rs} - - - org.glassfish.jersey.core - jersey-client - ${version.org.glassfish.jersey} - test - org.glassfish.jersey.media jersey-media-json-jackson3 diff --git a/impl/test/pom.xml b/impl/test/pom.xml index 72133e3f4..3fdc3a3c9 100644 --- a/impl/test/pom.xml +++ b/impl/test/pom.xml @@ -65,6 +65,7 @@ org.glassfish.jersey.core jersey-client + test org.junit.jupiter diff --git a/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/HttpAdapterCompatibilityTest.java b/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/HttpAdapterCompatibilityTest.java new file mode 100644 index 000000000..cab666ce5 --- /dev/null +++ b/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/HttpAdapterCompatibilityTest.java @@ -0,0 +1,220 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.impl.test; + +import static cloud.openworkflow.sdk.api.WorkflowReader.readWorkflowFromString; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowableOfType; + +import cloud.openworkflow.sdk.api.WorkflowFormat; +import cloud.openworkflow.sdk.api.types.Workflow; +import cloud.openworkflow.sdk.impl.WorkflowApplication; +import cloud.openworkflow.sdk.impl.WorkflowException; +import cloud.openworkflow.sdk.impl.WorkflowModel; +import cloud.openworkflow.sdk.impl.WorkflowModelFactory; +import cloud.openworkflow.sdk.impl.http.DefaultHttpRequestBuilderFactory; +import cloud.openworkflow.sdk.impl.jakarta.http.DefaultHttpModelConverter; +import cloud.openworkflow.sdk.impl.jakarta.http.HttpClientResolver; +import cloud.openworkflow.sdk.impl.jakarta.http.HttpConverterResolver; +import cloud.openworkflow.sdk.impl.jakarta.http.HttpModelConverter; +import cloud.openworkflow.sdk.impl.jakarta.http.HttpRequestDecorator; +import cloud.openworkflow.sdk.impl.jakarta.http.JakartaRequestExecutorFactory; +import cloud.openworkflow.sdk.types.Errors; +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.ClientBuilder; +import jakarta.ws.rs.client.ClientRequestFilter; +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class HttpAdapterCompatibilityTest { + + private static WorkflowApplication application(boolean jdk) { + var builder = WorkflowApplication.builder(); + if (jdk) { + builder.withHttpRequestBuilderFactory(new DefaultHttpRequestBuilderFactory()); + } + return builder.build(); + } + + private static Workflow workflow(String uri) { + return readWorkflowFromString( + """ + document: + dsl: 1.0.0-alpha1 + namespace: test + name: http-adapter-compatibility + version: 1.0.0 + do: + - callApi: + call: http + with: + method: post + endpoint: + uri: %s + authentication: + basic: + username: user + password: password + body: + value: ${.value} + export: + as: + info: ${$authorization} + """ + .formatted(uri), + WorkflowFormat.YAML); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void execute_shouldKeepAuthenticationAndModelConversion(boolean jdk) throws Exception { + try (MockWebServer server = new MockWebServer(); + WorkflowApplication app = application(jdk)) { + server.start(); + if (!jdk) { + assertThat(app.httpRequestFactory()).isInstanceOf(JakartaRequestExecutorFactory.class); + } + server.enqueue( + new MockResponse.Builder() + .addHeader("Content-Type", "application/json") + .body("{\"result\":42}") + .build()); + var instance = + app.workflowDefinition(workflow(server.url("/").toString())) + .instance(Map.of("value", "resolved")); + assertThat(instance.start().get(5, TimeUnit.SECONDS).asMap().orElseThrow()) + .containsEntry("result", 42); + var recorded = server.takeRequest(5, TimeUnit.SECONDS); + assertThat(recorded.getHeaders().get("Authorization")) + .isEqualTo("Basic dXNlcjpwYXNzd29yZA=="); + assertThat(recorded.getBody().utf8()).contains("\"value\":\"resolved\""); + assertThat(((Map) instance.context().asMap().orElseThrow().get("info")).get("scheme")) + .isEqualTo("Basic"); + } + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void execute_shouldTranslateHttpErrorsWithTaskPosition(boolean jdk) throws Exception { + try (MockWebServer server = new MockWebServer(); + WorkflowApplication app = application(jdk)) { + server.start(); + server.enqueue(new MockResponse.Builder().code(409).body("conflict details").build()); + ExecutionException error = + catchThrowableOfType( + ExecutionException.class, + () -> + app.workflowDefinition(workflow(server.url("/").toString())) + .instance(Map.of("value", 1)) + .start() + .get(5, TimeUnit.SECONDS)); + assertThat(error).isNotNull(); + assertThat(error.getCause()).isInstanceOf(WorkflowException.class); + var workflowError = ((WorkflowException) error.getCause()).getWorkflowError(); + assertThat(workflowError.status()).isEqualTo(409); + assertThat(workflowError.instance()).isEqualTo("do/0/callApi"); + assertThat(workflowError.type()).isEqualTo(Errors.COMMUNICATION.toString()); + assertThat(workflowError.detail()).isEqualTo("conflict details"); + } + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void execute_shouldTranslateTransportErrorsWithTaskPosition(boolean jdk) throws Exception { + String uri; + try (MockWebServer server = new MockWebServer()) { + server.start(); + uri = server.url("/").toString(); + } + try (WorkflowApplication app = application(jdk)) { + ExecutionException error = + catchThrowableOfType( + ExecutionException.class, + () -> + app.workflowDefinition(workflow(uri)) + .instance(Map.of("value", 1)) + .start() + .get(5, TimeUnit.SECONDS)); + assertThat(error).isNotNull(); + assertThat(error.getCause()).isInstanceOf(WorkflowException.class); + var workflowError = ((WorkflowException) error.getCause()).getWorkflowError(); + assertThat(workflowError.status()).isEqualTo(Errors.COMMUNICATION.status()); + assertThat(workflowError.instance()).isEqualTo("do/0/callApi"); + } + } + + @Test + void jakarta_shouldKeepClientDecoratorAndConverterHooks() throws Exception { + try (MockWebServer server = new MockWebServer(); + Client client = ClientBuilder.newClient()) { + server.start(); + client.register( + (ClientRequestFilter) request -> request.getHeaders().add("X-Client", "injected")); + HttpRequestDecorator decorator = + (request, workflow, task) -> request.header("X-Task", task.taskName()); + HttpModelConverter converter = + new DefaultHttpModelConverter() { + @Override + public Entity buildEntity(WorkflowModel model, MediaType type) { + assertThat(model.asMap().orElseThrow()).containsEntry("value", "resolved"); + return Entity.text("converted body"); + } + + @Override + public WorkflowModel buildModel(WorkflowModelFactory factory, Response response) { + return factory.from(response.readEntity(String.class)); + } + }; + try (WorkflowApplication app = + WorkflowApplication.builder() + .withAdditionalObject(HttpClientResolver.HTTP_CLIENT_PROVIDER, () -> client) + .withAdditionalObject(HttpConverterResolver.HTTP_MODEL_CONVERTER, () -> converter) + .withAdditionalObject("HttpRequestDecorators", () -> List.of(decorator)) + .build()) { + server.enqueue( + new MockResponse.Builder() + .addHeader("Content-Type", "text/plain") + .body("converted result") + .build()); + WorkflowModel result = + app.workflowDefinition(workflow(server.url("/").toString())) + .instance(Map.of("value", "resolved")) + .start() + .get(5, TimeUnit.SECONDS); + assertThat(result.asText().orElseThrow()).isEqualTo("converted result"); + var recorded = server.takeRequest(5, TimeUnit.SECONDS); + assertThat(recorded.getHeaders().get("X-Client")).isEqualTo("injected"); + assertThat(recorded.getHeaders().get("X-Task")).isEqualTo("callApi"); + assertThat(recorded.getBody().utf8()).isEqualTo("converted body"); + } + // Application shutdown must not close the client returned by the additional-object hook. + server.enqueue(new MockResponse.Builder().body("still open").build()); + try (var response = client.target(server.url("/").uri()).request().get()) { + assertThat(response.getStatus()).isEqualTo(200); + } + } + } +} diff --git a/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/OpenAPIAdapterCompatibilityTest.java b/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/OpenAPIAdapterCompatibilityTest.java new file mode 100644 index 000000000..734d50cea --- /dev/null +++ b/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/OpenAPIAdapterCompatibilityTest.java @@ -0,0 +1,131 @@ +/* + * Copyright 2020-Present The Open Workflow Specification Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package cloud.openworkflow.sdk.impl.test; + +import static cloud.openworkflow.sdk.api.WorkflowReader.readWorkflowFromString; +import static org.assertj.core.api.Assertions.*; + +import cloud.openworkflow.sdk.api.WorkflowFormat; +import cloud.openworkflow.sdk.impl.WorkflowApplication; +import cloud.openworkflow.sdk.impl.executors.openapi.UnifiedOpenAPIReader; +import cloud.openworkflow.sdk.impl.executors.openapi.jackson.JacksonUnifiedOpenAPIReader; +import cloud.openworkflow.sdk.impl.http.DefaultHttpRequestBuilderFactory; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class OpenAPIAdapterCompatibilityTest { + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void preservesCustomReadersSeparateAuthenticationAndPostFallback(boolean jdk) throws Exception { + try (MockWebServer document = new MockWebServer(); + MockWebServer first = new MockWebServer(); + MockWebServer second = new MockWebServer()) { + document.start(); + first.start(); + second.start(); + String schema = + """ + {"openapi":"3.0.3","servers":[{"url":"%s"},{"url":"%s"}], + "paths":{"/items/{id}":{"post":{"operationId":"save","parameters":[ + {"name":"id","in":"path","required":true,"schema":{"type":"string"}}], + "requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}}}}}} + """ + .formatted(first.url("/v1"), second.url("/v1")); + document.enqueue( + new MockResponse().setHeader("Content-Type", "application/json").setBody(schema)); + first.enqueue(new MockResponse().setResponseCode(503).setBody("unavailable")); + second.enqueue( + new MockResponse() + .setHeader("Content-Type", "application/json") + .setBody("{\"saved\":true}")); + AtomicInteger reads = new AtomicInteger(); + UnifiedOpenAPIReader customReader = + (name, bytes) -> { + reads.incrementAndGet(); + return new JacksonUnifiedOpenAPIReader().read(name, bytes); + }; + var builder = + WorkflowApplication.builder() + .withAdditionalObject( + UnifiedOpenAPIReader.UNIFIED_OPEN_API_READER, () -> customReader); + if (jdk) builder.withHttpRequestBuilderFactory(new DefaultHttpRequestBuilderFactory()); + try (WorkflowApplication app = builder.build()) { + var workflow = + readWorkflowFromString( + """ + document: + dsl: 1.0.0-alpha1 + namespace: test + name: openapi-adapter-compatibility + version: 1.0.0 + do: + - save: + call: openapi + with: + document: + endpoint: + uri: %s + authentication: + basic: + username: document + password: secret + operationId: save + authentication: + basic: + username: api + password: secret + parameters: + id: ${.id} + name: ${.name} + """ + .formatted(document.url("/schema.json")), + WorkflowFormat.YAML); + var definition = app.workflowDefinition(workflow); + assertThat( + definition + .instance(Map.of("id", "one", "name", "first")) + .start() + .get(10, TimeUnit.SECONDS) + .asMap() + .orElseThrow() + .get("saved")) + .isEqualTo(true); + assertThat(reads.get()).isEqualTo(1); + var loaded = document.takeRequest(10, TimeUnit.SECONDS); + assertThat(loaded).isNotNull(); + assertThat(loaded.getHeader("Authorization")).isEqualTo("Basic ZG9jdW1lbnQ6c2VjcmV0"); + for (MockWebServer server : new MockWebServer[] {first, second}) { + var request = server.takeRequest(10, TimeUnit.SECONDS); + assertThat(request).isNotNull(); + assertThat(request.getMethod()).isEqualTo("POST"); + assertThat(request.getPath()).isEqualTo("/v1/items/one"); + assertThat(request.getHeader("Authorization")).isEqualTo("Basic YXBpOnNlY3JldA=="); + assertThat( + WorkflowFormat.JSON + .mapper() + .readValue(request.getBody().readString(StandardCharsets.UTF_8), Map.class)) + .isEqualTo(Map.of("name", "first")); + } + } + } + } +} diff --git a/pom.xml b/pom.xml index 9f8e0af0b..90d80a143 100644 --- a/pom.xml +++ b/pom.xml @@ -38,6 +38,7 @@ api + common impl types annotations @@ -49,6 +50,8 @@ + 4.0.3 + 4.0.0 21 ${java.version} ${java.version} @@ -111,6 +114,31 @@ + + org.glassfish.jersey.core + jersey-client + ${version.org.glassfish.jersey} + + + jakarta.ws.rs + jakarta.ws.rs-api + ${version.jakarta.ws.rs} + + + cloud.openworkflow.sdk + openworkflow-common-http + ${project.version} + + + cloud.openworkflow.sdk + openworkflow-common-http-jakarta + ${project.version} + + + cloud.openworkflow.sdk + openworkflow-common-openapi + ${project.version} +