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