diff --git a/README.md b/README.md index e140529bd..69c690bbe 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,8 @@ With the SDK you can: * Read workflow JSON and YAML definitions * Write workflow definitions in JSON and YAML formats. -* Test your workflow definitions using the reference implementation. +* Test your workflow definitions using the reference implementation from `impl` +- Reuse execution components from `common/` while developing your own implementation. ## Status @@ -72,10 +73,15 @@ implementation("cloud.openworkflow.sdk:openworkflow-api:RELEASE_VERSION") ## How to Use There are, roughly speaking, two kind of users of this SDK: + + * Those ones interested on using the provided runtime reference implementation to execute workflow definitions. * Those ones interested on implementing their own runtime using Java. - * Those ones interested on using the provided runtime reference implementation. + +## Reference implementation + +The reference implementation provides a ready-to-use runtime that supports the Open Workflow Specification. It includes a workflow execution engine, validation utilities, and illustrative examples to help you quickly test and deploy your workflows. For details on usage, configuration, and supported features, see [readme](impl/README.md). -### Implementing your own runtime +## Implementing your own runtime For those ones interested on implementing their own runtime, this SDK provides an easy way to load an in memory representation of a given workflow definition. This in-memory representation consists of a hierarchy of POJOS directly generated from the Open Workflow specification [schema](api/src/main/resources/schema/workflow.yaml), which ensures the internal representation is aligned with the specification schema. The root of the hierarchy is `cloud.openworkflow.sdk.api.types.Workflow` class @@ -122,7 +128,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,17 +141,15 @@ 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 The `openworkflow-api` module depends heavily on Jackson for loading file content into an in-memory POJO. For users who use a JSON handling library other than Jackson, the `openworkflow-types` module contains Java POJOs generated from the OpenWorkflow schema without any Jackson annotations. Using this module as a dependency, they can build a reader/writer module equivalent to `openworkflow-api` with their preferred JSON library. -### Reference implementation - -The reference implementation provides a ready-to-use runtime that supports the Open Workflow Specification. It includes a workflow execution engine, validation utilities, and illustrative examples to help you quickly test and deploy your workflows. For details on usage, configuration, and supported features, see [readme](impl/README.md). - +### Reusing Common Libraries +The SDK provides standalone modules under `common/` that can be used independently by other workflow engine implementations. For more details, check the README.MD of each module. ## License [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fopen-workflow-specification%2Fsdk-java.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2Fopen-workflow-specification%2Fsdk-java?ref=badge_large) diff --git a/common/api/README.md b/common/api/README.md new file mode 100644 index 000000000..648d69e88 --- /dev/null +++ b/common/api/README.md @@ -0,0 +1,43 @@ +# Common API + +## Introduction + +This module provides core interfaces and utilities that can be reused by other workflow engine implementations. It contains foundational abstractions for service prioritization and ordering. + +## Dependency + +```xml + + cloud.openworkflow.sdk + openworkflow-common-api + 8.0.0-SNAPSHOT + +``` + +## Usage Example + +```java +import cloud.openworkflow.sdk.common.ServicePriority; + +public class MyService implements ServicePriority { + + @Override + public int priority() { + return 500; // Higher priority than default (1000) + } + + public static void main(String[] args) { + MyService service1 = new MyService(); + MyService service2 = new MyService() { + @Override + public int priority() { + return 1500; + } + }; + + // Compare services by priority + int comparison = service1.compareTo(service2); + System.out.println("Service1 has higher priority: " + (comparison < 0)); + } +} +``` diff --git a/common/api/pom.xml b/common/api/pom.xml new file mode 100644 index 000000000..5ec289b0c --- /dev/null +++ b/common/api/pom.xml @@ -0,0 +1,23 @@ + + 4.0.0 + + cloud.openworkflow.sdk + openworkflow-common + 8.0.0-SNAPSHOT + + openworkflow-common-api + Open Workflow :: Common API + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.assertj + assertj-core + test + + + + diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/ServicePriority.java b/common/api/src/main/java/cloud/openworkflow/sdk/common/ServicePriority.java similarity index 96% rename from impl/core/src/main/java/cloud/openworkflow/sdk/impl/ServicePriority.java rename to common/api/src/main/java/cloud/openworkflow/sdk/common/ServicePriority.java index a4f0c9ea3..3e7b18346 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/ServicePriority.java +++ b/common/api/src/main/java/cloud/openworkflow/sdk/common/ServicePriority.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package cloud.openworkflow.sdk.impl; +package cloud.openworkflow.sdk.common; public interface ServicePriority> extends Comparable { diff --git a/impl/core/src/test/java/cloud/openworkflow/sdk/impl/LowestPriority.java b/common/api/src/test/java/cloud/openworkflow/sdk/impl/LowestPriority.java similarity index 93% rename from impl/core/src/test/java/cloud/openworkflow/sdk/impl/LowestPriority.java rename to common/api/src/test/java/cloud/openworkflow/sdk/impl/LowestPriority.java index fc31cca00..59bfa5451 100644 --- a/impl/core/src/test/java/cloud/openworkflow/sdk/impl/LowestPriority.java +++ b/common/api/src/test/java/cloud/openworkflow/sdk/impl/LowestPriority.java @@ -15,6 +15,8 @@ */ package cloud.openworkflow.sdk.impl; +import cloud.openworkflow.sdk.common.ServicePriority; + public class LowestPriority implements ServicePriority { public int priority() { return DEFAULT_PRIORITY + 1; diff --git a/impl/core/src/test/java/cloud/openworkflow/sdk/impl/MediumPriority.java b/common/api/src/test/java/cloud/openworkflow/sdk/impl/MediumPriority.java similarity index 93% rename from impl/core/src/test/java/cloud/openworkflow/sdk/impl/MediumPriority.java rename to common/api/src/test/java/cloud/openworkflow/sdk/impl/MediumPriority.java index da356653b..7582b279c 100644 --- a/impl/core/src/test/java/cloud/openworkflow/sdk/impl/MediumPriority.java +++ b/common/api/src/test/java/cloud/openworkflow/sdk/impl/MediumPriority.java @@ -15,4 +15,6 @@ */ package cloud.openworkflow.sdk.impl; +import cloud.openworkflow.sdk.common.ServicePriority; + public class MediumPriority implements ServicePriority {} diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultHttpRequestBuilderFactory.java b/common/api/src/test/java/cloud/openworkflow/sdk/impl/PriorityTest.java similarity index 52% rename from impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultHttpRequestBuilderFactory.java rename to common/api/src/test/java/cloud/openworkflow/sdk/impl/PriorityTest.java index 1ed932fac..e37d2e607 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultHttpRequestBuilderFactory.java +++ b/common/api/src/test/java/cloud/openworkflow/sdk/impl/PriorityTest.java @@ -13,23 +13,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package cloud.openworkflow.sdk.impl.http; +package cloud.openworkflow.sdk.impl; -import cloud.openworkflow.sdk.impl.WorkflowApplication; -import java.net.http.HttpClient; -import java.net.http.HttpClient.Redirect; +import static org.assertj.core.api.Assertions.assertThat; -public class DefaultHttpRequestBuilderFactory implements WorkflowHttpRequestFactory { +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import org.junit.jupiter.api.Test; - private HttpClient client = HttpClient.newBuilder().followRedirects(Redirect.NORMAL).build(); +class PriorityTest { - @Override - public WorkflowHttpRequest request(WorkflowApplication app, WorkflowHttpRequestInfo httpInfo) { - return new DefaultHttpRequest(app, client, httpInfo); - } + @Test + void testOrder() { + + TopPriority top = new TopPriority(); + MediumPriority medium = new MediumPriority(); + LowestPriority lowest = new LowestPriority(); - @Override - public void close() { - client.close(); + List list = new ArrayList<>(Arrays.asList(medium, lowest, top)); + Collections.sort(list); + assertThat(list).containsExactly(top, medium, lowest); } } diff --git a/impl/core/src/test/java/cloud/openworkflow/sdk/impl/TopPriority.java b/common/api/src/test/java/cloud/openworkflow/sdk/impl/TopPriority.java similarity index 93% rename from impl/core/src/test/java/cloud/openworkflow/sdk/impl/TopPriority.java rename to common/api/src/test/java/cloud/openworkflow/sdk/impl/TopPriority.java index efd7e76c0..68f6940e8 100644 --- a/impl/core/src/test/java/cloud/openworkflow/sdk/impl/TopPriority.java +++ b/common/api/src/test/java/cloud/openworkflow/sdk/impl/TopPriority.java @@ -15,6 +15,8 @@ */ package cloud.openworkflow.sdk.impl; +import cloud.openworkflow.sdk.common.ServicePriority; + public class TopPriority implements ServicePriority { public int priority() { return DEFAULT_PRIORITY - 1; diff --git a/common/http-jakarta/README.md b/common/http-jakarta/README.md new file mode 100644 index 000000000..ada890e36 --- /dev/null +++ b/common/http-jakarta/README.md @@ -0,0 +1,48 @@ +# HTTP Transport with Jakarta REST + +## Introduction + +This module provides a Jakarta REST (formerly JAX-RS) implementation of the HTTP transport interface that other workflow engine implementations can reuse. It enables HTTP execution using Jakarta REST clients without requiring the full workflow engine. + +## Dependency + +```xml + + cloud.openworkflow.sdk + openworkflow-common-http-jakarta + 8.0.0-SNAPSHOT + +``` + +**Runtime Requirement**: A Jakarta REST implementation is required. Common providers include Jersey (Reference Implementation) or RESTEasy (JBoss/Red Hat). + +## Usage Example + +```java +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.ClientBuilder; +import java.util.concurrent.TimeUnit; +import cloud.openworkflow.sdk.http.*; +import cloud.openworkflow.sdk.http.jakarta.*; + +// Create and configure Jakarta REST client +Client client = ClientBuilder.newBuilder() + .connectTimeout(5, TimeUnit.SECONDS) + .readTimeout(30, TimeUnit.SECONDS) + .build(); + +// Create transport with Jakarta REST client +WorkflowHttpTransport transport = + new JakartaHttpTransport<>(client, JakartaHttpTransport.BYTES); + +// Execute requests +CompletableFuture> response = + transport.execute(request); + +// Remember to close the client at shutdown +client.close(); +``` + +**Important**: The client must be managed by the application and closed at shutdown. `WorkflowHttpResponse` implements `AutoCloseable` and must be closed using try-with-resources. + +**Limitation**: `WorkflowHttpResponse.request()` returns `Optional.empty()` as Jakarta REST does not portably expose the final request after redirects. 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/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/HttpRequestDecorator.java b/common/http-jakarta/src/main/java/cloud/openworkflow/sdk/http/jakarta/JakartaHttpRequestDecorator.java similarity index 65% rename from impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/HttpRequestDecorator.java rename to common/http-jakarta/src/main/java/cloud/openworkflow/sdk/http/jakarta/JakartaHttpRequestDecorator.java index 23217aa26..22d78a37b 100644 --- a/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/HttpRequestDecorator.java +++ b/common/http-jakarta/src/main/java/cloud/openworkflow/sdk/http/jakarta/JakartaHttpRequestDecorator.java @@ -13,13 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package cloud.openworkflow.sdk.impl.jakarta.http; +package cloud.openworkflow.sdk.http.jakarta; -import cloud.openworkflow.sdk.impl.WorkflowDecorator; +import cloud.openworkflow.sdk.common.ServicePriority; import jakarta.ws.rs.client.Invocation; +import java.util.function.Consumer; -/** - * Interface for decorating HTTP requests with additional modifications. Note that TaskContext might - * be null - */ -public interface HttpRequestDecorator extends WorkflowDecorator {} +/** Interface for decorating HTTP requests with additional modifications */ +public interface JakartaHttpRequestDecorator + extends Consumer, ServicePriority {} diff --git a/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/JakartaHttpResponse.java b/common/http-jakarta/src/main/java/cloud/openworkflow/sdk/http/jakarta/JakartaHttpResponse.java similarity index 54% rename from impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/JakartaHttpResponse.java rename to common/http-jakarta/src/main/java/cloud/openworkflow/sdk/http/jakarta/JakartaHttpResponse.java index 44e0d2aa5..0ab8d651f 100644 --- a/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/JakartaHttpResponse.java +++ b/common/http-jakarta/src/main/java/cloud/openworkflow/sdk/http/jakarta/JakartaHttpResponse.java @@ -13,59 +13,46 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package cloud.openworkflow.sdk.impl.jakarta.http; +package cloud.openworkflow.sdk.http.jakarta; -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 cloud.openworkflow.sdk.http.*; 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; +import java.util.*; -class JakartaHttpResponse implements WorkflowHttpResponse { - - private final WorkflowApplication app; - private HttpModelConverter converter; - private Response response; - private TaskContext taskContext; +/** + * Buffered native entity supports both provider conversion and original raw bytes. Caller closes. + */ +public class JakartaHttpResponse implements WorkflowHttpResponse { + private final Response response; + private final WorkflowHttpBodyConverter converter; 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); + Response response, WorkflowHttpBodyConverter converter) { + this.response = Objects.requireNonNull(response); + this.converter = Objects.requireNonNull(converter); } - @Override 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 OptionalLong lastModified() { - Date date = response.getLastModified(); - return date == null ? OptionalLong.empty() : OptionalLong.of(date.getTime()); + public String getHeader(String name) { + return response.getHeaderString(name); } @Override - public void close() { - response.close(); + public OptionalLong lastModified() { + var date = response.getLastModified(); + return date == null ? OptionalLong.empty() : OptionalLong.of(date.getTime()); } @Override @@ -77,44 +64,25 @@ public String reasonPhrase() { public String errorDetails() { try { return response.readEntity(String.class); - } catch (ProcessingException ex) { + } catch (jakarta.ws.rs.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 + "]"; + public T bodyAsObject() { + return converter.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); + public void close() { + response.close(); } private static final Collection FORBIDDEN_HTTP2_HEADERS_LOWERCASE = Arrays.asList("connection", "keep-alive", "proxy-connection", "transfer-encoding", "upgrade"); - private boolean isHttp2() { + @Override + public boolean isHttp2() { for (String str : response.getHeaders().keySet()) { if (containsUpperCase(str) || FORBIDDEN_HTTP2_HEADERS_LOWERCASE.contains(str.toLowerCase())) { 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..25d27fb12 --- /dev/null +++ b/common/http-jakarta/src/main/java/cloud/openworkflow/sdk/http/jakarta/JakartaHttpTransport.java @@ -0,0 +1,93 @@ +/* + * 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.WorkflowHttpBodyConverter; +import cloud.openworkflow.sdk.http.WorkflowHttpHeaders; +import cloud.openworkflow.sdk.http.WorkflowHttpRequestInfo; +import cloud.openworkflow.sdk.http.WorkflowHttpResponse; +import cloud.openworkflow.sdk.http.WorkflowHttpTransport; +import jakarta.ws.rs.client.Client; +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.Collection; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; + +/** + * 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 WorkflowHttpTransport { + + private final Client client; + private final WorkflowHttpBodyConverter, Response, T> converter; + private final Collection requestDecorators; + + public static final WorkflowHttpBodyConverter, Response, byte[]> BYTES = + new WorkflowHttpBodyConverter<>() { + @Override + public Entity request(WorkflowHttpRequestInfo info) { + byte[] bytes = info.body(); + return bytes == null || bytes.length == 0 + ? null + : Entity.entity( + bytes, info.contentType().orElse(WorkflowHttpHeaders.APPLICATION_JSON_TYPE)); + } + + @Override + public byte[] response(Response response) { + return response.readEntity(byte[].class); + } + }; + + public JakartaHttpTransport( + Client client, WorkflowHttpBodyConverter, Response, T> converter) { + this(client, converter, List.of()); + } + + public JakartaHttpTransport( + Client client, + WorkflowHttpBodyConverter, Response, T> converter, + Collection requestDecorators) { + this.client = Objects.requireNonNull(client, "client"); + this.converter = Objects.requireNonNull(converter); + this.requestDecorators = requestDecorators; + } + + @Override + public CompletableFuture> execute(WorkflowHttpRequestInfo request) { + 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.headers().forEach(builder::header); + requestDecorators.forEach(c -> c.accept(builder)); + Entity entity = converter.request(request); + return (entity == null + ? builder.rx().method(request.method()) + : builder.rx().method(request.method(), entity)) + .toCompletableFuture() + .thenApply(response -> new JakartaHttpResponse<>(response, converter)); + } +} diff --git a/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/template/JaxrsURITemplateResolver.java b/common/http-jakarta/src/main/java/cloud/openworkflow/sdk/http/jakarta/JaxrsURITemplateResolver.java similarity index 89% rename from impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/template/JaxrsURITemplateResolver.java rename to common/http-jakarta/src/main/java/cloud/openworkflow/sdk/http/jakarta/JaxrsURITemplateResolver.java index 48b11ca0c..ccc6f3816 100644 --- a/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/template/JaxrsURITemplateResolver.java +++ b/common/http-jakarta/src/main/java/cloud/openworkflow/sdk/http/jakarta/JaxrsURITemplateResolver.java @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package cloud.openworkflow.sdk.impl.jakarta.template; +package cloud.openworkflow.sdk.http.jakarta; -import cloud.openworkflow.sdk.impl.http.URITemplateResolver; +import cloud.openworkflow.sdk.http.URITemplateResolver; import jakarta.ws.rs.core.UriBuilder; import java.net.URI; import java.util.Map; diff --git a/common/http-jakarta/src/main/resources/META-INF/services/cloud.openworkflow.sdk.http.URITemplateResolver b/common/http-jakarta/src/main/resources/META-INF/services/cloud.openworkflow.sdk.http.URITemplateResolver new file mode 100644 index 000000000..e8e09b5b7 --- /dev/null +++ b/common/http-jakarta/src/main/resources/META-INF/services/cloud.openworkflow.sdk.http.URITemplateResolver @@ -0,0 +1 @@ +cloud.openworkflow.sdk.http.jakarta.JaxrsURITemplateResolver \ No newline at end of file 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..97911df7a --- /dev/null +++ b/common/http-jakarta/src/test/java/cloud/openworkflow/sdk/http/jakarta/JakartaHttpTransportTest.java @@ -0,0 +1,184 @@ +/* + * 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.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import cloud.openworkflow.sdk.http.WorkflowHttpRequestInfo; +import cloud.openworkflow.sdk.http.WorkflowHttpResponse; +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.SocketTimeoutException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +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.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class JakartaHttpTransportTest { + + private MockWebServer server; + + @BeforeEach + void setup() throws Exception { + server = new MockWebServer(); + server.start(); + } + + @AfterEach + void close() throws Exception { + server.close(); + } + + @Test + void doesNotCloseTheBorrowedClient() throws Exception { + Response response = mock(Response.class); + when(response.getStatus()).thenReturn(200); + when(response.getHeaders()).thenReturn(new jakarta.ws.rs.core.MultivaluedHashMap<>()); + when(response.hasEntity()).thenReturn(false); + + 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(CompletableFuture.completedFuture(response)); + + JakartaHttpTransport transport = + new JakartaHttpTransport<>(client, JakartaHttpTransport.BYTES); + try (WorkflowHttpResponse owned = + transport + .execute( + WorkflowHttpRequestInfo.builder("GET") + .build(URI.create("http://localhost/"))) + .get(5, TimeUnit.SECONDS)) { + assertThat(owned.status()).isEqualTo(200); + } + verify(client, org.mockito.Mockito.never()).close(); + verify(response).close(); + } + + @Test + void execute_shouldNotClaimToKnowTheRequestAfterProviderRedirects() throws Exception { + try (Client client = ClientBuilder.newClient()) { + JakartaHttpTransport transport = + new JakartaHttpTransport<>(client, JakartaHttpTransport.BYTES); + server.enqueue( + new MockResponse.Builder() + .code(303) + .addHeader("Location", "/final?source=redirect") + .build()); + server.enqueue(new MockResponse.Builder().body("final response").build()); + try (WorkflowHttpResponse response = + transport + .execute( + WorkflowHttpRequestInfo.builder("POST") + .headers(Map.of("X-Request", "sent")) + .body("body".getBytes(StandardCharsets.UTF_8)) + .build(server.url("/start").uri())) + .get(5, TimeUnit.SECONDS)) { + assertThat(response.status()).isEqualTo(200); + assertThat(server.takeRequest(5, TimeUnit.SECONDS).getMethod()).isEqualTo("POST"); + mockwebserver3.RecordedRequest redirected = server.takeRequest(5, TimeUnit.SECONDS); + assertThat(redirected.getMethod()).isEqualTo("GET"); + assertThat(redirected.getUrl().uri()).isEqualTo(server.url("/final?source=redirect").uri()); + } + } + } + + @Test + void execute_shouldSendResolvedDataAndReturnBufferedSuccessAndError() throws Exception { + try (Client client = ClientBuilder.newClient()) { + JakartaHttpTransport transport = + new JakartaHttpTransport<>(client, JakartaHttpTransport.BYTES); + 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 (WorkflowHttpResponse response = + transport + .execute( + WorkflowHttpRequestInfo.builder("POST") + .headers( + Map.of( + "X-Request", + "value", + "Content-Type", + "text/plain", + "Authorization", + "Basic resolved")) + .queryParams(Map.of("search", "café + tea")) + .body("café".getBytes(StandardCharsets.UTF_8)) + .build(server.url("/items?existing=yes").uri())) + .get(5, TimeUnit.SECONDS)) { + assertThat(response.status()).isEqualTo(status); + assertThat(response.headers().get("x-result")).hasSize(2); + assertThat(new String(response.body(), StandardCharsets.UTF_8)) + .isEqualTo("body " + status); + mockwebserver3.RecordedRequest 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_shouldHonorInjectedReadTimeout() throws Exception { + try (Client timeoutClient = + ClientBuilder.newBuilder().readTimeout(100, TimeUnit.MILLISECONDS).build()) { + server.enqueue( + new MockResponse.Builder().headersDelay(1, TimeUnit.SECONDS).body("late").build()); + WorkflowHttpRequestInfo request = + WorkflowHttpRequestInfo.builder("GET").build(server.url("/").uri()); + JakartaHttpTransport transport = + new JakartaHttpTransport<>(timeoutClient, JakartaHttpTransport.BYTES); + assertThatThrownBy(() -> transport.execute(request).get(5, TimeUnit.SECONDS)) + .hasRootCauseInstanceOf(SocketTimeoutException.class); + server.enqueue(new MockResponse.Builder().body("still usable").build()); + JakartaHttpTransport next = + new JakartaHttpTransport<>(timeoutClient, JakartaHttpTransport.BYTES); + try (WorkflowHttpResponse response = next.execute(request).get(5, TimeUnit.SECONDS)) { + assertThat(response.status()).isEqualTo(200); + } + } + } +} diff --git a/common/http/README.md b/common/http/README.md new file mode 100644 index 000000000..cea50eea1 --- /dev/null +++ b/common/http/README.md @@ -0,0 +1,49 @@ +# HTTP Transport + +## Introduction + +This module provides a reusable HTTP transport implementation that other workflow engine implementations can leverage. It offers a lightweight, dependency-free HTTP execution layer without requiring the full workflow engine, expression evaluation, or JSON libraries. + +## Dependency + +```xml + + cloud.openworkflow.sdk + openworkflow-common-http + 8.0.0-SNAPSHOT + +``` + +## Usage Example + +```java +import java.net.URI; +import java.net.http.HttpClient; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import cloud.openworkflow.sdk.http.*; + +class HttpActivity { + private final WorkflowHttpTransport transport; + + HttpActivity(HttpClient client) { + this.transport = new JdkHttpTransport<>(client, JdkHttpTransport.BYTES); + } + + CompletableFuture> execute(URI uri, String token) { + WorkflowHttpRequestInfo request = + WorkflowHttpRequestInfo.builder("POST") + .headers(Map.of( + "Content-Type", "application/json", + "Authorization", "Bearer " + token)) + .queryParams(Map.of("search", "café + tea")) + .body("{\"name\":\"café\"}".getBytes(StandardCharsets.UTF_8)) + .build(uri); + + return transport.execute(request); + } +} +``` + +**Important**: `WorkflowHttpTransport` does not implement `AutoCloseable` and can be reused for multiple requests. The underlying `HttpClient` should be managed by the application. `WorkflowHttpResponse` implements `AutoCloseable` and must be closed using try-with-resources. diff --git a/common/http/pom.xml b/common/http/pom.xml new file mode 100644 index 000000000..83e6e8c9d --- /dev/null +++ b/common/http/pom.xml @@ -0,0 +1,31 @@ + + 4.0.0 + + cloud.openworkflow.sdk + openworkflow-common + 8.0.0-SNAPSHOT + + openworkflow-common-http + Open Workflow :: HTTP Client + + + cloud.openworkflow.sdk + openworkflow-common-api + + + 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/JdkHttpResponse.java b/common/http/src/main/java/cloud/openworkflow/sdk/http/JdkHttpResponse.java new file mode 100644 index 000000000..e48b32022 --- /dev/null +++ b/common/http/src/main/java/cloud/openworkflow/sdk/http/JdkHttpResponse.java @@ -0,0 +1,65 @@ +/* + * 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.Version; +import java.net.http.HttpResponse; +import java.util.*; + +/** Native JDK response: already buffered, no open response resource. */ +public class JdkHttpResponse implements WorkflowHttpResponse { + private final Optional request; + private final HttpResponse response; + private final WorkflowHttpBodyConverter, T> converter; + + public JdkHttpResponse( + HttpResponse response, + WorkflowHttpBodyConverter, T> converter) { + this.response = response; + this.converter = converter; + this.request = + Optional.ofNullable(response.request()) + .map(r -> new WorkflowHttpRequestMetadata(r.method(), r.uri(), r.headers().map())); + } + + public int status() { + return response.statusCode(); + } + + public byte[] body() { + return response.body(); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public Map> headers() { + return (Map) response.headers().map(); + } + + @Override + public Optional request() { + return request; + } + + @Override + public T bodyAsObject() { + return converter.response(response); + } + + @Override + public boolean isHttp2() { + return response.version() == Version.HTTP_2; + } +} 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..2df92ff5e --- /dev/null +++ b/common/http/src/main/java/cloud/openworkflow/sdk/http/JdkHttpTransport.java @@ -0,0 +1,71 @@ +/* + * 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.HttpRequest.BodyPublisher; +import java.net.http.HttpResponse; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; + +/** JDK HTTP transport. Redirects and connect timeouts follow the configured client. */ +public final class JdkHttpTransport implements WorkflowHttpTransport { + + private final HttpClient client; + private final WorkflowHttpBodyConverter, T> converter; + + public static final WorkflowHttpBodyConverter, byte[]> BYTES = + new WorkflowHttpBodyConverter<>() { + @Override + public BodyPublisher request(WorkflowHttpRequestInfo info) { + byte[] bytes = info.body(); + return bytes == null || bytes.length == 0 + ? HttpRequest.BodyPublishers.noBody() + : HttpRequest.BodyPublishers.ofByteArray(bytes); + } + + @Override + public byte[] response(HttpResponse response) { + return response.body(); + } + }; + + public JdkHttpTransport( + HttpClient client, + WorkflowHttpBodyConverter, T> converter) { + this.client = Objects.requireNonNull(client, "client"); + this.converter = Objects.requireNonNull(converter); + } + + @Override + public CompletableFuture> execute(WorkflowHttpRequestInfo request) { + HttpRequest.Builder builder = + HttpRequest.newBuilder() + .method(request.method(), converter.request(request)) + .uri(WorkflowHttpRequestEncoding.addQueryParams(request.uri(), request.queryParams())); + if (request.contentType().isEmpty()) { + builder.header(WorkflowHttpHeaders.CONTENT_TYPE, WorkflowHttpHeaders.APPLICATION_JSON_TYPE); + } + if (request.timeout() != null) { + builder.timeout(request.timeout()); + } + request.headers().forEach((name, value) -> builder.setHeader(name, value.toString())); + return client + .sendAsync(builder.build(), HttpResponse.BodyHandlers.ofByteArray()) + .thenApply(response -> new JdkHttpResponse<>(response, converter)); + } +} diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultURITemplateResolver.java b/common/http/src/main/java/cloud/openworkflow/sdk/http/JdkURITemplateResolver.java similarity index 99% rename from impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultURITemplateResolver.java rename to common/http/src/main/java/cloud/openworkflow/sdk/http/JdkURITemplateResolver.java index 0a690439a..fc8000a47 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultURITemplateResolver.java +++ b/common/http/src/main/java/cloud/openworkflow/sdk/http/JdkURITemplateResolver.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package cloud.openworkflow.sdk.impl.http; +package cloud.openworkflow.sdk.http; import java.io.UnsupportedEncodingException; import java.net.URI; @@ -25,7 +25,7 @@ import java.util.List; import java.util.Map; -public class DefaultURITemplateResolver implements URITemplateResolver { +public class JdkURITemplateResolver implements URITemplateResolver { @Override public URI resolveTemplates(String uri, Map map) { diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/URIDecodedBuilder.java b/common/http/src/main/java/cloud/openworkflow/sdk/http/URIDecodedBuilder.java similarity index 86% rename from impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/URIDecodedBuilder.java rename to common/http/src/main/java/cloud/openworkflow/sdk/http/URIDecodedBuilder.java index c31e51a63..371a7887e 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/URIDecodedBuilder.java +++ b/common/http/src/main/java/cloud/openworkflow/sdk/http/URIDecodedBuilder.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package cloud.openworkflow.sdk.impl.http; +package cloud.openworkflow.sdk.http; import java.net.URI; @@ -24,12 +24,14 @@ public class URIDecodedBuilder { private String path; private String query; private String host; + private String fragment; public URIDecodedBuilder(URI originalUri) { this.originalUri = originalUri; this.path = originalUri.getRawPath(); this.query = originalUri.getRawQuery(); this.host = originalUri.getHost(); + this.fragment = originalUri.getRawFragment(); } public URIDecodedBuilder path(String path) { @@ -47,6 +49,11 @@ public URIDecodedBuilder host(String host) { return this; } + public URIDecodedBuilder fragment(String fragment) { + this.fragment = fragment; + return this; + } + public URI build() { StringBuilder sb = new StringBuilder(); @@ -73,8 +80,8 @@ public URI build() { sb.append("?").append(query); } - if (originalUri.getRawFragment() != null) { - sb.append("#").append(originalUri.getRawFragment()); + if (fragment != null) { + sb.append("#").append(fragment); } return URI.create(sb.toString()); diff --git a/common/http/src/main/java/cloud/openworkflow/sdk/http/URIHelper.java b/common/http/src/main/java/cloud/openworkflow/sdk/http/URIHelper.java new file mode 100644 index 000000000..e89d78158 --- /dev/null +++ b/common/http/src/main/java/cloud/openworkflow/sdk/http/URIHelper.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.net.URI; + +public class URIHelper { + + public static URI concatURI(URI base, String pathToAppend) { + return !isValid(pathToAppend) ? base : concatURI(base, URI.create(pathToAppend)); + } + + public static URI concatURI(URI base, URI child) { + if (child.isAbsolute()) { + return child; + } + + URIDecodedBuilder baseDecoded = new URIDecodedBuilder(base); + String relPath = child.getRawPath(); + if (isValid(relPath)) { + String basePath = base.getRawPath(); + if (!isValid(basePath)) { + baseDecoded.path(relPath); + } else { + + String concat; + if (basePath.endsWith("/")) { + if (relPath.startsWith("/")) { + concat = basePath + relPath.substring(1); + } else { + concat = basePath + relPath; + } + } else { + if (relPath.startsWith("/")) { + concat = basePath + relPath; + } else { + concat = basePath + '/' + relPath; + } + } + + baseDecoded.path(concat); + } + } + + String relQuery = child.getRawQuery(); + if (isValid(relPath)) { + String baseQuery = base.getRawQuery(); + if (!isValid(baseQuery)) { + baseDecoded.query(relQuery); + } else { + baseDecoded.query(baseQuery + "&" + relQuery); + } + } + + String relFragment = child.getRawFragment(); + if (isValid(relFragment)) { + baseDecoded.fragment(relFragment); + } + + return baseDecoded.build(); + } + + private static boolean isValid(String path) { + return path != null && !path.isBlank(); + } + + private URIHelper() {} +} diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/URITemplateResolver.java b/common/http/src/main/java/cloud/openworkflow/sdk/http/URITemplateResolver.java similarity index 89% rename from impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/URITemplateResolver.java rename to common/http/src/main/java/cloud/openworkflow/sdk/http/URITemplateResolver.java index 95e4ab59b..dac545093 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/URITemplateResolver.java +++ b/common/http/src/main/java/cloud/openworkflow/sdk/http/URITemplateResolver.java @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package cloud.openworkflow.sdk.impl.http; +package cloud.openworkflow.sdk.http; -import cloud.openworkflow.sdk.impl.ServicePriority; +import cloud.openworkflow.sdk.common.ServicePriority; import java.net.URI; import java.util.Map; diff --git a/impl/core/src/test/java/cloud/openworkflow/sdk/impl/ServicePriorityTest.java b/common/http/src/main/java/cloud/openworkflow/sdk/http/WorkflowHttpBodyConverter.java similarity index 66% rename from impl/core/src/test/java/cloud/openworkflow/sdk/impl/ServicePriorityTest.java rename to common/http/src/main/java/cloud/openworkflow/sdk/http/WorkflowHttpBodyConverter.java index f34c50749..b8aa31e68 100644 --- a/impl/core/src/test/java/cloud/openworkflow/sdk/impl/ServicePriorityTest.java +++ b/common/http/src/main/java/cloud/openworkflow/sdk/http/WorkflowHttpBodyConverter.java @@ -13,17 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package cloud.openworkflow.sdk.impl; +package cloud.openworkflow.sdk.http; -import static org.assertj.core.api.Assertions.assertThat; +/** Explicit per-transport conversion policy */ +public interface WorkflowHttpBodyConverter { -import org.junit.jupiter.api.Test; + T request(WorkflowHttpRequestInfo info); -class ServicePriorityTest { - - @Test - void testRightOrder() { - assertThat(WorkflowUtils.loadFirst(ServicePriority.class).orElseThrow()) - .isInstanceOf(TopPriority.class); - } + R response(V response); } diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpContentType.java b/common/http/src/main/java/cloud/openworkflow/sdk/http/WorkflowHttpHeaders.java similarity index 90% rename from impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpContentType.java rename to common/http/src/main/java/cloud/openworkflow/sdk/http/WorkflowHttpHeaders.java index 6cee52a3e..da571b6da 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpContentType.java +++ b/common/http/src/main/java/cloud/openworkflow/sdk/http/WorkflowHttpHeaders.java @@ -13,18 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package cloud.openworkflow.sdk.impl.http; +package cloud.openworkflow.sdk.http; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Locale; -public class WorkflowHttpContentType { +public class WorkflowHttpHeaders { public static final String APPLICATION_JSON_TYPE = "application/json"; public static final String APPLICATION_X_WWW_FORM_URLENCODED = "application/x-www-form-urlencoded"; - public static final String HEADER_NAME = "Content-Type"; + public static final String CONTENT_TYPE = "Content-Type"; + public static final String IF_MODIFIED_SINCE = "If-Modified-Since"; + public static final String LAST_MODIFIED = "Last-Modified"; public static boolean isURLEncodedDataType(String contentType) { return formatContentType(contentType).contains("/x-www-form-urlencoded"); diff --git a/common/http/src/main/java/cloud/openworkflow/sdk/http/WorkflowHttpRequestEncoding.java b/common/http/src/main/java/cloud/openworkflow/sdk/http/WorkflowHttpRequestEncoding.java new file mode 100644 index 000000000..1ffd110d5 --- /dev/null +++ b/common/http/src/main/java/cloud/openworkflow/sdk/http/WorkflowHttpRequestEncoding.java @@ -0,0 +1,54 @@ +/* + * 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.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 WorkflowHttpRequestEncoding { + + 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, WorkflowHttpRequestEncoding::encodeQuery); + String rawQuery = uri.getRawQuery(); + return new URIDecodedBuilder(uri) + .query(rawQuery == null || rawQuery.isEmpty() ? addedQuery : rawQuery + "&" + addedQuery) + .build(); + } + + private WorkflowHttpRequestEncoding() {} +} diff --git a/common/http/src/main/java/cloud/openworkflow/sdk/http/WorkflowHttpRequestInfo.java b/common/http/src/main/java/cloud/openworkflow/sdk/http/WorkflowHttpRequestInfo.java new file mode 100644 index 000000000..545660736 --- /dev/null +++ b/common/http/src/main/java/cloud/openworkflow/sdk/http/WorkflowHttpRequestInfo.java @@ -0,0 +1,236 @@ +/* + * 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; + +/** HTTP request information */ +public class WorkflowHttpRequestInfo { + + 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 Duration timeout; + + 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; + } + + public B body() { + return body; + } + + public Duration timeout() { + return timeout; + } + + @Override + public String toString() { + return "WorkflowHttpRequestInfo [uri=" + + uri + + ", method=" + + method + + ", redirect=" + + redirect + + ", headers=" + + headers + + ", queryParams=" + + queryParams + + ", timeout=" + + timeout + + "]"; + } + + @Override + public int hashCode() { + return Objects.hash(method, uri, queryParams); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + return obj instanceof WorkflowHttpRequestInfo other + && redirect == other.redirect + && Objects.equals(timeout, other.timeout) + && Objects.equals(method, other.method) + && Objects.equals(uri, other.uri) + && Objects.equals(headers, other.headers) + && Objects.equals(queryParams, other.queryParams) + && Objects.deepEquals(body, other.body); + } + + private WorkflowHttpRequestInfo( + URI uri, + String method, + boolean redirect, + Map headers, + Map queryParams, + B body, + Duration timeout) { + this.uri = uri; + this.method = method; + this.redirect = redirect; + this.headers = headers; + this.queryParams = queryParams; + this.body = body; + this.timeout = timeout; + } + + public Optional contentType() { + return headers.get(WorkflowHttpHeaders.CONTENT_TYPE) instanceof String contentType + ? Optional.of(contentType) + : Optional.empty(); + } + + public static Builder builder() { + return new Builder<>(); + } + + public static Builder builder(String method) { + return new Builder<>(method); + } + + 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; + private Duration timeout; + + public Builder() { + this("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 String method() { + return method; + } + + public Builder path(URI path) { + this.path = path; + return this; + } + + public Builder timeout(Duration timeout) { + this.timeout = timeout; + return this; + } + + public Builder body(B body) { + this.body = body; + 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 header(String name, String value) { + if (headers == null) { + headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + } + headers.put(name, value); + return this; + } + + public Builder ifModifiedSince(long millis) { + this.ifModifiedSince = millis; + return this; + } + + public WorkflowHttpRequestInfo build(URI uri) { + if (ifModifiedSince != null) { + String time = + 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 + if (headers == null) { + headers = Map.of(WorkflowHttpHeaders.IF_MODIFIED_SINCE, time); + } else { + headers.put(WorkflowHttpHeaders.IF_MODIFIED_SINCE, time); + } + } + return new WorkflowHttpRequestInfo<>( + path == null ? uri : URIHelper.concatURI(uri, path), + method, + redirect, + headers != null ? Collections.unmodifiableMap(headers) : Map.of(), + queryParams != null ? Collections.unmodifiableMap(queryParams) : Map.of(), + body, + timeout); + } + } +} diff --git a/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/HttpClientResolver.java b/common/http/src/main/java/cloud/openworkflow/sdk/http/WorkflowHttpRequestMetadata.java similarity index 75% rename from impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/HttpClientResolver.java rename to common/http/src/main/java/cloud/openworkflow/sdk/http/WorkflowHttpRequestMetadata.java index e2da42b64..6c2939d11 100644 --- a/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/HttpClientResolver.java +++ b/common/http/src/main/java/cloud/openworkflow/sdk/http/WorkflowHttpRequestMetadata.java @@ -13,11 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package cloud.openworkflow.sdk.impl.jakarta.http; +package cloud.openworkflow.sdk.http; -public class HttpClientResolver { +import java.net.URI; +import java.util.List; +import java.util.Map; - public static final String HTTP_CLIENT_PROVIDER = "httpClientProvider"; - - private HttpClientResolver() {} -} +public record WorkflowHttpRequestMetadata( + String method, URI uri, Map> headers) {} diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpResponse.java b/common/http/src/main/java/cloud/openworkflow/sdk/http/WorkflowHttpResponse.java similarity index 57% rename from impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpResponse.java rename to common/http/src/main/java/cloud/openworkflow/sdk/http/WorkflowHttpResponse.java index 606fec78d..416a514b2 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpResponse.java +++ b/common/http/src/main/java/cloud/openworkflow/sdk/http/WorkflowHttpResponse.java @@ -13,35 +13,52 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package cloud.openworkflow.sdk.impl.http; +package cloud.openworkflow.sdk.http; -import cloud.openworkflow.sdk.impl.WorkflowModel; -import java.util.List; -import java.util.Map; -import java.util.OptionalLong; +import java.util.*; -public interface WorkflowHttpResponse extends AutoCloseable { +/** Shared response. Callers own it and must close it, including after conversion failures. */ +public interface WorkflowHttpResponse extends AutoCloseable { + int status(); - byte[] contentAsByteArray(); + byte[] body(); - byte[] responseAsByteArray(); + Map> headers(); - WorkflowModel contentAsModel(); + boolean isHttp2(); - /** Access all headers */ - Map> headers(); + R bodyAsObject(); - /** - * Access response header given its name - * - * @param name name of the header - * @return first value of the header as string - */ - String getHeader(String name); + default Optional request() { + return Optional.empty(); + } - int status(); + default String getHeader(String name) { + return headers().entrySet().stream() + .filter(e -> e.getKey().equalsIgnoreCase(name)) + .flatMap(e -> e.getValue().stream()) + .map(String::valueOf) + .findFirst() + .orElse(null); + } - OptionalLong lastModified(); + 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() { + return body() == null ? "No error information" : new String(body()); + } default String reasonPhrase() { return switch (status()) { @@ -75,7 +92,6 @@ default String reasonPhrase() { }; } - String errorDetails(); - + @Override default void close() {} } diff --git a/common/http/src/main/java/cloud/openworkflow/sdk/http/WorkflowHttpResponses.java b/common/http/src/main/java/cloud/openworkflow/sdk/http/WorkflowHttpResponses.java new file mode 100644 index 000000000..ab07a4f2d --- /dev/null +++ b/common/http/src/main/java/cloud/openworkflow/sdk/http/WorkflowHttpResponses.java @@ -0,0 +1,65 @@ +/* + * 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 */ +public final class WorkflowHttpResponses { + private static final String HTTP_NEW_LINE = "\r\n"; + + public static byte[] responseAsByteArray(WorkflowHttpResponse response) { + boolean isHttp2 = response.isHttp2(); + byte[] content = response.body(); + 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 == 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); + } + } + + private static void addHeader(StringBuilder sb, String name, Object value) { + sb.append(name).append(": ").append(value).append(HTTP_NEW_LINE); + } + + private WorkflowHttpResponses() {} +} diff --git a/common/http/src/main/java/cloud/openworkflow/sdk/http/WorkflowHttpTransport.java b/common/http/src/main/java/cloud/openworkflow/sdk/http/WorkflowHttpTransport.java new file mode 100644 index 000000000..beb86e053 --- /dev/null +++ b/common/http/src/main/java/cloud/openworkflow/sdk/http/WorkflowHttpTransport.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; + +import java.util.concurrent.CompletableFuture; + +/** Executes resolved HTTP requests without a workflow engine. */ +public interface WorkflowHttpTransport { + + /** + * Returns a response owned by the caller for every HTTP status; transport failures complete + * exceptionally with the underlying transport error + * + *

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(WorkflowHttpRequestInfo request); +} 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..1c34db3bc --- /dev/null +++ b/common/http/src/test/java/cloud/openworkflow/sdk/http/HttpRequestInfoTest.java @@ -0,0 +1,193 @@ +/* + * 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 WorkflowHttpRequestInfo request(byte[] body) { + return WorkflowHttpRequestInfo.builder("POST") + .headers(Map.of("X-Request", "value")) + .queryParams(Map.of("page", 1)) + .body(body) + .build(URI_VALUE); + } + + @Test + void methodNormalizationDoesNotDependOnTheDefaultLocale() { + var previous = java.util.Locale.getDefault(); + try { + java.util.Locale.setDefault(java.util.Locale.forLanguageTag("tr")); + assertThat( + WorkflowHttpRequestInfo.builder("options") + .build(URI.create("https://example.test")) + .method()) + .isEqualTo("OPTIONS"); + } finally { + java.util.Locale.setDefault(previous); + } + } + + @Test + void commonBuilderPreservesEncodedPathQueryAndFragmentDelimiters() { + var request = + WorkflowHttpRequestInfo.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 = + WorkflowHttpRequestInfo.builder("GET") + .headers(Map.of("Content-Type", "text/plain")) + .build(URI.create("https://example.test")); + var second = + WorkflowHttpRequestInfo.builder("GET") + .headers(Map.of("content-type", "text/plain")) + .build(first.uri()); + 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 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 = + WorkflowHttpRequestInfo.builder(original.method()) + .headers(original.headers()) + .queryParams(original.queryParams()) + .body(original.body()) + .redirect(original.redirect()) + .timeout(original.timeout()) + .build(original.uri()); + 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( + WorkflowHttpRequestInfo.builder(original.method()) + .headers(original.headers()) + .queryParams(original.queryParams()) + .body(original.body()) + .build(URI.create("http://localhost/other"))); + assertThat(original) + .isNotEqualTo( + WorkflowHttpRequestInfo.builder("PUT") + .headers(original.headers()) + .queryParams(original.queryParams()) + .body(original.body()) + .build(original.uri())); + assertThat(original) + .isNotEqualTo( + WorkflowHttpRequestInfo.builder(original.method()) + .headers(Map.of("X-Request", "other")) + .queryParams(original.queryParams()) + .body(original.body()) + .build(original.uri())); + assertThat(original) + .isNotEqualTo( + WorkflowHttpRequestInfo.builder(original.method()) + .headers(original.headers()) + .queryParams(Map.of("page", 2)) + .body(original.body()) + .build(original.uri())); + 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(); + 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 = + WorkflowHttpRequestInfo.builder("POST") + .headers(forward) + .queryParams(reverse) + .body(new byte[] {1}) + .build(URI_VALUE); + var second = + WorkflowHttpRequestInfo.builder("POST") + .headers(reverse) + .queryParams(forward) + .body(new byte[] {1}) + .build(URI_VALUE); + 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..36f3e273b --- /dev/null +++ b/common/http/src/test/java/cloud/openworkflow/sdk/http/JdkHttpTransportTest.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.http; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.net.http.HttpClient; +import java.net.http.HttpClient.Redirect; +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.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class JdkHttpTransportTest { + + private HttpClient client; + private MockWebServer server; + + record ConsumerJson(String json) {} + + @BeforeEach + void setup() throws IOException { + server = new MockWebServer(); + server.start(); + client = HttpClient.newBuilder().followRedirects(Redirect.NORMAL).build(); + } + + @AfterEach + void close() { + server.close(); + client.close(); + } + + @Test + void sendsConditionalDateFromTheSharedBuilderExactlyOnce() throws Exception { + WorkflowHttpTransport transport = + new JdkHttpTransport<>(client, JdkHttpTransport.BYTES); + server.enqueue(new MockResponse.Builder().build()); + var request = + WorkflowHttpRequestInfo.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 { + WorkflowHttpTransport transport = + new JdkHttpTransport<>(client, JdkHttpTransport.BYTES); + server.enqueue(new MockResponse.Builder().build()); + var request = + WorkflowHttpRequestInfo.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 execute_shouldExposeTheEffectiveGetAfterASeeOtherRedirect() throws Exception { + WorkflowHttpTransport transport = + new JdkHttpTransport<>(client, JdkHttpTransport.BYTES); + server.enqueue( + new MockResponse.Builder() + .code(303) + .addHeader("Location", "/final?source=redirect") + .build()); + server.enqueue(new MockResponse.Builder().body("final response").build()); + try (WorkflowHttpResponse response = + transport + .execute( + WorkflowHttpRequestInfo.builder("POST") + .headers(Map.of("X-Request", "redirected")) + .body("initial body".getBytes(StandardCharsets.UTF_8)) + .build(server.url("/start?source=initial").uri())) + .join()) { + + 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 { + server.start(); + WorkflowHttpTransport transport = + new JdkHttpTransport<>(client, JdkHttpTransport.BYTES); + server.enqueue(new MockResponse.Builder().addHeader("X-Response", "received").build()); + try (var response = + transport + .execute( + WorkflowHttpRequestInfo.builder("GET") + .headers(Map.of("X-Request", "sent")) + .queryParams(Map.of("search", "tea + coffee")) + .build(server.url("/direct?existing=a%2Bb").uri())) + .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.getHeader("X-Response")).isEqualTo("received"); + assertThat(response.headers()).doesNotContainKey("X-Request"); + assertThat(server.takeRequest(5, TimeUnit.SECONDS).getUrl().uri()).isEqualTo(effective.uri()); + } + } + + // This example compiles and runs in a module with no engine on its classpath. + private static CompletableFuture thirdPartyCall( + WorkflowHttpTransport transport, java.net.URI uri) { + return transport.execute( + WorkflowHttpRequestInfo.builder("POST") + .headers( + Map.of( + "Content-Type", "application/json", "Authorization", "Bearer resolved-token")) + .queryParams(Map.of("search", "café + tea")) + .body("{\"name\":\"café\"}".getBytes(StandardCharsets.UTF_8)) + .build(uri)); + } + + @Test + void thirdPartyCall_shouldSendResolvedDataAndExposeErrorResponses() throws Exception { + server.start(); + WorkflowHttpTransport transport = + new JdkHttpTransport<>(client, JdkHttpTransport.BYTES); + server.enqueue( + new MockResponse.Builder() + .code(422) + .addHeader("X-Result", "invalid") + .addHeader("X-Result", "second") + .body("validation details") + .build()); + + try (cloud.openworkflow.sdk.http.WorkflowHttpResponse response = + thirdPartyCall(transport, server.url("/items?existing=a%2Bb").uri()) + .get(5, TimeUnit.SECONDS)) { + + assertThat(response.status()).isEqualTo(422); + assertThat(response.getHeader("x-result")).isEqualTo("invalid"); + @SuppressWarnings("unchecked") + var resultHeaders = (java.util.List) response.headers().get("X-RESULT"); + assertThat(resultHeaders).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 { + server.start(); + WorkflowHttpTransport transport = + new JdkHttpTransport<>(client, JdkHttpTransport.BYTES); + server.enqueue( + new MockResponse.Builder().headersDelay(1, TimeUnit.SECONDS).body("late").build()); + WorkflowHttpRequestInfo request = + WorkflowHttpRequestInfo.builder("GET") + .timeout(Duration.ofMillis(100)) + .build(server.url("/").uri()); + assertThatThrownBy(() -> transport.execute(request).get(5, TimeUnit.SECONDS)) + .hasCauseInstanceOf(HttpTimeoutException.class); + } + + @Test + void execute_shouldPreserveConfiguredRedirectBehavior() throws Exception { + server.start(); + WorkflowHttpTransport normal = new JdkHttpTransport<>(client, JdkHttpTransport.BYTES); + HttpClient noRedirectClient = + HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NEVER).build(); + WorkflowHttpRequestInfo request = + WorkflowHttpRequestInfo.builder("GET").build(server.url("/start").uri()); + server.enqueue(new MockResponse.Builder().code(302).addHeader("Location", "/end").build()); + server.enqueue(new MockResponse.Builder().body("redirected").build()); + try (var response = normal.execute(request).get(5, TimeUnit.SECONDS)) { + assertThat(new String(response.body(), StandardCharsets.UTF_8)).isEqualTo("redirected"); + } + server.enqueue(new MockResponse.Builder().code(302).addHeader("Location", "/end").build()); + WorkflowHttpTransport noRedirect = + new JdkHttpTransport<>(noRedirectClient, JdkHttpTransport.BYTES); + try (var response = noRedirect.execute(request).get(5, TimeUnit.SECONDS)) { + assertThat(response.status()).isEqualTo(302); + } + } +} diff --git a/impl/core/src/test/java/cloud/openworkflow/sdk/impl/http/DefaultURITemplateResolverTest.java b/common/http/src/test/java/cloud/openworkflow/sdk/http/JdkURITemplateResolverTest.java similarity index 85% rename from impl/core/src/test/java/cloud/openworkflow/sdk/impl/http/DefaultURITemplateResolverTest.java rename to common/http/src/test/java/cloud/openworkflow/sdk/http/JdkURITemplateResolverTest.java index 9ace2c3e9..75f569da1 100644 --- a/impl/core/src/test/java/cloud/openworkflow/sdk/impl/http/DefaultURITemplateResolverTest.java +++ b/common/http/src/test/java/cloud/openworkflow/sdk/http/JdkURITemplateResolverTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package cloud.openworkflow.sdk.impl.http; +package cloud.openworkflow.sdk.http; import static org.assertj.core.api.Assertions.assertThat; @@ -21,11 +21,11 @@ import java.util.Map; import org.junit.jupiter.api.Test; -public class DefaultURITemplateResolverTest { +public class JdkURITemplateResolverTest { @Test public void testResolve() { - URITemplateResolver resolver = new DefaultURITemplateResolver(); + URITemplateResolver resolver = new JdkURITemplateResolver(); assertThat( resolver.resolveTemplates( "https://api.example.com/users/{userId}/posts/{post-Id}", @@ -35,7 +35,7 @@ public void testResolve() { @Test public void testResolveOptional() { - URITemplateResolver resolver = new DefaultURITemplateResolver(); + URITemplateResolver resolver = new JdkURITemplateResolver(); assertThat( resolver.resolveTemplates( "https://api.example.com/pets{?limit,offset}", Map.of("limit", "10"))) diff --git a/impl/core/src/test/java/cloud/openworkflow/sdk/impl/WorkflowUtilsTest.java b/common/http/src/test/java/cloud/openworkflow/sdk/http/URIHelperTest.java similarity index 83% rename from impl/core/src/test/java/cloud/openworkflow/sdk/impl/WorkflowUtilsTest.java rename to common/http/src/test/java/cloud/openworkflow/sdk/http/URIHelperTest.java index 2704d6ba8..edaa4c204 100644 --- a/impl/core/src/test/java/cloud/openworkflow/sdk/impl/WorkflowUtilsTest.java +++ b/common/http/src/test/java/cloud/openworkflow/sdk/http/URIHelperTest.java @@ -13,20 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package cloud.openworkflow.sdk.impl; +package cloud.openworkflow.sdk.http; import static org.assertj.core.api.Assertions.assertThat; import java.net.URI; import org.junit.jupiter.api.Test; -public class WorkflowUtilsTest { +public class URIHelperTest { @Test void openApiServerWithTrailingSlashAndRootPath() { URI base = URI.create("https://petstore3.swagger.io/api/v3/"); URI path = URI.create("/pet/findByStatus"); - URI result = WorkflowUtils.concatURI(base, path.toString()); + URI result = URIHelper.concatURI(base, path.toString()); assertThat(result.toString()).isEqualTo("https://petstore3.swagger.io/api/v3/pet/findByStatus"); } @@ -36,7 +36,7 @@ void openApiServerWithoutTrailingSlashAndRootPath() { URI base = URI.create("https://petstore3.swagger.io/api/v3"); URI path = URI.create("/pet/findByStatus"); - URI result = WorkflowUtils.concatURI(base, path.toString()); + URI result = URIHelper.concatURI(base, path.toString()); assertThat(result.toString()).isEqualTo("https://petstore3.swagger.io/api/v3/pet/findByStatus"); } @@ -46,7 +46,7 @@ void baseWithSlashAndRelativePath() { URI base = URI.create("https://example.com/api/v1/"); URI path = URI.create("pets"); - URI result = WorkflowUtils.concatURI(base, path.toString()); + URI result = URIHelper.concatURI(base, path.toString()); assertThat(result.toString()).isEqualTo("https://example.com/api/v1/pets"); } @@ -56,7 +56,7 @@ void baseWithoutPathAndRootPath() { URI base = URI.create("https://example.com"); URI path = URI.create("/pets"); - URI result = WorkflowUtils.concatURI(base, path.toString()); + URI result = URIHelper.concatURI(base, path.toString()); assertThat(result.toString()).isEqualTo("https://example.com/pets"); } @@ -66,7 +66,7 @@ void absolutePathOverridesBase() { URI base = URI.create("https://example.com/api"); URI path = URI.create("https://other.example.com/foo"); - URI result = WorkflowUtils.concatURI(base, path.toString()); + URI result = URIHelper.concatURI(base, path.toString()); assertThat(result.toString()).isEqualTo("https://other.example.com/foo"); } @@ -76,7 +76,7 @@ void queryAndFragmentAreTakenFromPath() { URI base = URI.create("https://example.com/api/v1"); URI path = URI.create("/pets?status=available#top"); - URI result = WorkflowUtils.concatURI(base, path.toString()); + URI result = URIHelper.concatURI(base, path.toString()); assertThat(result.toString()).isEqualTo("https://example.com/api/v1/pets?status=available#top"); } diff --git a/common/openapi-jackson/README.md b/common/openapi-jackson/README.md new file mode 100644 index 000000000..672129b12 --- /dev/null +++ b/common/openapi-jackson/README.md @@ -0,0 +1,35 @@ +# OpenAPI Jackson Reader + +## Introduction + +This module provides a Jackson-based implementation for reading OpenAPI specifications that other workflow engine implementations can reuse. It enables parsing of OpenAPI documents in JSON or YAML format using Jackson's serialization capabilities. + +## Dependency + +```xml + + cloud.openworkflow.sdk + openworkflow-common-openapi-jackson + 8.0.0-SNAPSHOT + +``` + +## Usage Example + +```java +import cloud.openworkflow.sdk.openapi.UnifiedOpenAPI; +import cloud.openworkflow.sdk.openapi.jackson.JacksonUnifiedOpenAPIReader; + +// Read OpenAPI document from bytes +byte[] documentBytes = Files.readAllBytes(Path.of("api.yaml")); + +// Create reader and parse document +JacksonUnifiedOpenAPIReader reader = new JacksonUnifiedOpenAPIReader(); +UnifiedOpenAPI document = reader.read("api.yaml", documentBytes); + +// Use the parsed document +System.out.println("OpenAPI version: " + document.openapi()); +System.out.println("Servers: " + document.servers()); +``` + +The reader automatically detects the format (JSON or YAML) based on the file extension and uses the appropriate Jackson mapper for parsing. diff --git a/common/openapi-jackson/pom.xml b/common/openapi-jackson/pom.xml new file mode 100644 index 000000000..5846d2fb1 --- /dev/null +++ b/common/openapi-jackson/pom.xml @@ -0,0 +1,19 @@ + + 4.0.0 + + cloud.openworkflow.sdk + openworkflow-common + 8.0.0-SNAPSHOT + + openworkflow-common-openapi-jackson + + + cloud.openworkflow.sdk + openworkflow-common-openapi + + + cloud.openworkflow.sdk + openworkflow-api + + + \ No newline at end of file diff --git a/impl/openapi-jackson/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/jackson/JacksonUnifiedOpenAPIMixIn.java b/common/openapi-jackson/src/main/java/cloud/openworkflow/sdk/openapi/jackson/JacksonUnifiedOpenAPIMixIn.java similarity index 96% rename from impl/openapi-jackson/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/jackson/JacksonUnifiedOpenAPIMixIn.java rename to common/openapi-jackson/src/main/java/cloud/openworkflow/sdk/openapi/jackson/JacksonUnifiedOpenAPIMixIn.java index f60745a27..6c956fa77 100644 --- a/impl/openapi-jackson/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/jackson/JacksonUnifiedOpenAPIMixIn.java +++ b/common/openapi-jackson/src/main/java/cloud/openworkflow/sdk/openapi/jackson/JacksonUnifiedOpenAPIMixIn.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package cloud.openworkflow.sdk.impl.executors.openapi.jackson; +package cloud.openworkflow.sdk.openapi.jackson; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/impl/openapi-jackson/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/jackson/JacksonUnifiedOpenAPIMixInModule.java b/common/openapi-jackson/src/main/java/cloud/openworkflow/sdk/openapi/jackson/JacksonUnifiedOpenAPIMixInModule.java similarity index 93% rename from impl/openapi-jackson/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/jackson/JacksonUnifiedOpenAPIMixInModule.java rename to common/openapi-jackson/src/main/java/cloud/openworkflow/sdk/openapi/jackson/JacksonUnifiedOpenAPIMixInModule.java index 84feae534..f7a14cbb0 100644 --- a/impl/openapi-jackson/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/jackson/JacksonUnifiedOpenAPIMixInModule.java +++ b/common/openapi-jackson/src/main/java/cloud/openworkflow/sdk/openapi/jackson/JacksonUnifiedOpenAPIMixInModule.java @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package cloud.openworkflow.sdk.impl.executors.openapi.jackson; +package cloud.openworkflow.sdk.openapi.jackson; -import cloud.openworkflow.sdk.impl.executors.openapi.UnifiedOpenAPI; +import cloud.openworkflow.sdk.openapi.UnifiedOpenAPI; import tools.jackson.databind.module.SimpleModule; public class JacksonUnifiedOpenAPIMixInModule extends SimpleModule { diff --git a/impl/openapi-jackson/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/jackson/JacksonUnifiedOpenAPIReader.java b/common/openapi-jackson/src/main/java/cloud/openworkflow/sdk/openapi/jackson/JacksonUnifiedOpenAPIReader.java similarity index 81% rename from impl/openapi-jackson/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/jackson/JacksonUnifiedOpenAPIReader.java rename to common/openapi-jackson/src/main/java/cloud/openworkflow/sdk/openapi/jackson/JacksonUnifiedOpenAPIReader.java index 9cd0fa181..78c6b4709 100644 --- a/impl/openapi-jackson/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/jackson/JacksonUnifiedOpenAPIReader.java +++ b/common/openapi-jackson/src/main/java/cloud/openworkflow/sdk/openapi/jackson/JacksonUnifiedOpenAPIReader.java @@ -13,11 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package cloud.openworkflow.sdk.impl.executors.openapi.jackson; +package cloud.openworkflow.sdk.openapi.jackson; import cloud.openworkflow.sdk.api.WorkflowFormat; -import cloud.openworkflow.sdk.impl.executors.openapi.UnifiedOpenAPI; -import cloud.openworkflow.sdk.impl.executors.openapi.UnifiedOpenAPIReader; +import cloud.openworkflow.sdk.openapi.UnifiedOpenAPI; +import cloud.openworkflow.sdk.openapi.UnifiedOpenAPIReader; public class JacksonUnifiedOpenAPIReader implements UnifiedOpenAPIReader { @Override diff --git a/common/openapi-jackson/src/main/resources/META-INF/services/tools.jackson.databind.JacksonModule b/common/openapi-jackson/src/main/resources/META-INF/services/tools.jackson.databind.JacksonModule new file mode 100644 index 000000000..bdaa3d2ad --- /dev/null +++ b/common/openapi-jackson/src/main/resources/META-INF/services/tools.jackson.databind.JacksonModule @@ -0,0 +1 @@ +cloud.openworkflow.sdk.openapi.jackson.JacksonUnifiedOpenAPIMixInModule \ No newline at end of file diff --git a/common/openapi/README.md b/common/openapi/README.md new file mode 100644 index 000000000..e91ab3d1e --- /dev/null +++ b/common/openapi/README.md @@ -0,0 +1,62 @@ +# OpenAPI Client + +## Introduction + +This module provides a reusable OpenAPI client library that other workflow engine implementations can leverage for making HTTP calls based on OpenAPI specifications, without requiring the full workflow engine. + +## Dependency + +```xml + + cloud.openworkflow.sdk + openworkflow-common-openapi + 8.0.0-SNAPSHOT + +``` + +For JSON/YAML parsing with Jackson: + +```xml + + cloud.openworkflow.sdk + openworkflow-common-openapi-jackson + 8.0.0-SNAPSHOT + +``` + +## Usage Example + +```java +import java.net.URI; +import java.net.http.HttpClient; +import java.util.Map; +import cloud.openworkflow.sdk.api.WorkflowFormat; +import cloud.openworkflow.sdk.http.*; +import cloud.openworkflow.sdk.openapi.*; +import cloud.openworkflow.sdk.openapi.jackson.JacksonUnifiedOpenAPIReader; + +// Read OpenAPI document +UnifiedOpenAPI document = new JacksonUnifiedOpenAPIReader() + .read("api.yaml", documentBytes); + +// Create client for specific operation +OpenAPIClient client = new OpenAPIClient(document, "operationId"); + +// Create transport (reusable for multiple requests) +JdkHttpTransport transport = + new JdkHttpTransport<>(HttpClient.newHttpClient(), JdkHttpTransport.BYTES); + +// Prepare and execute request +Map parameters = Map.of("name", "John"); +WorkflowHttpRequestInfo request = + client.createRequest(parameters).build(URI.create("http://api.example.com")); + +CompletableFuture> responseFuture = + transport.execute(request); + +try (WorkflowHttpResponse response = responseFuture.get()) { + // Process response... +} +``` + +**Important**: `WorkflowHttpTransport` does not implement `AutoCloseable` and can be reused. The underlying `HttpClient` should be managed by the application. `WorkflowHttpResponse` implements `AutoCloseable` and must be closed using try-with-resources. \ No newline at end of file diff --git a/common/openapi/pom.xml b/common/openapi/pom.xml new file mode 100644 index 000000000..b3de20c32 --- /dev/null +++ b/common/openapi/pom.xml @@ -0,0 +1,31 @@ + + 4.0.0 + + cloud.openworkflow.sdk + openworkflow-common + 8.0.0-SNAPSHOT + + openworkflow-common-openapi + Open Workflow :: Common:: OpenAPI + + + cloud.openworkflow.sdk + openworkflow-common-http + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.assertj + assertj-core + test + + + com.squareup.okhttp3 + mockwebserver + test + + + diff --git a/common/openapi/src/main/java/cloud/openworkflow/sdk/openapi/OpenAPIClient.java b/common/openapi/src/main/java/cloud/openworkflow/sdk/openapi/OpenAPIClient.java new file mode 100644 index 000000000..abe15761f --- /dev/null +++ b/common/openapi/src/main/java/cloud/openworkflow/sdk/openapi/OpenAPIClient.java @@ -0,0 +1,143 @@ +/* + * 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.openapi; + +import cloud.openworkflow.sdk.http.JdkURITemplateResolver; +import cloud.openworkflow.sdk.http.URITemplateResolver; +import cloud.openworkflow.sdk.http.WorkflowHttpRequestInfo; +import java.net.URI; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.Function; + +/** OpenAPI request preparation and asynchronous execution using caller-owned HTTP resources. */ +public class OpenAPIClient { + + private final OperationDefinition operation; + + private final Function, T> converter; + + private final URITemplateResolver templateResolver; + + /** Origin is optional and used only to resolve relative server URLs; no resources are loaded. */ + public OpenAPIClient( + UnifiedOpenAPI document, String operationId, Function, T> converter) { + this(document, operationId, converter, new JdkURITemplateResolver()); + } + + public OpenAPIClient( + UnifiedOpenAPI document, + String operationId, + Function, T> converter, + URITemplateResolver templateResolver) { + this.operation = new OpenAPIProcessor(operationId).parse(Objects.requireNonNull(document)); + this.converter = converter; + + this.templateResolver = templateResolver; + } + + public OperationDefinition operation() { + return operation; + } + + public List servers(URI serverPrefix) { + List servers = operation.getServers(); + if (servers.isEmpty()) throw new IllegalArgumentException("List of servers is empty"); + return servers.stream() + .map(URI::create) + .map(server -> { + if (!server.isAbsolute()) { + if (serverPrefix == null) { + throw new IllegalArgumentException( + "Relative OpenAPI server requires a document origin: " + server); + } + return serverPrefix.resolve(server); + } + return server; + }) + .toList(); + } + + public WorkflowHttpRequestInfo.Builder createRequest(Map parameters) { + WorkflowHttpRequestInfo.Builder builder = + WorkflowHttpRequestInfo.builder(operation.getMethod()); + Map headers = new HashMap<>(); + Map queryMap = new HashMap<>(); + Map pathParameters = new HashMap<>(); + Set missingParams = new HashSet<>(); + boolean hasBody = operation.getOperation().hasRequestBody(); + Map bodyParameters = new HashMap<>(parameters); + + for (ParameterDefinition parameter : operation.getParameters()) { + switch (parameter.in()) { + case "header": + param(parameter, parameters, headers, missingParams); + bodyParameters.remove(parameter.name()); + break; + case "path": + param(parameter, parameters, pathParameters, missingParams); + bodyParameters.remove(parameter.name()); + break; + case "query": + param(parameter, parameters, queryMap, missingParams); + bodyParameters.remove(parameter.name()); + 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); + } + return builder + .body(hasBody || !bodyParameters.isEmpty() ? converter.apply(bodyParameters) : null) + .queryParams(!queryMap.isEmpty() ? queryMap : null) + .headers(!headers.isEmpty() ? headers : null) + .path(templateResolver.resolveTemplates(operation.getPath(), pathParameters)); + } + + private void param( + ParameterDefinition parameter, + Map origParameters, + Map collectorMap, + Set missingParams) { + String name = parameter.name(); + boolean isRequired = parameter.required(); + Object value = origParameters.get(name); + if (value != null) { + collectorMap.put(name, value); + } 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); + } + } + } +} 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/openapi/OpenAPIProcessor.java similarity index 84% 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/openapi/OpenAPIProcessor.java index 3a7b0b94f..650162523 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIProcessor.java +++ b/common/openapi/src/main/java/cloud/openworkflow/sdk/openapi/OpenAPIProcessor.java @@ -13,20 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package cloud.openworkflow.sdk.impl.executors.openapi; +package cloud.openworkflow.sdk.openapi; 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/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OperationDefinition.java b/common/openapi/src/main/java/cloud/openworkflow/sdk/openapi/OperationDefinition.java similarity index 90% 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/openapi/OperationDefinition.java index b466cc036..6a7603650 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OperationDefinition.java +++ b/common/openapi/src/main/java/cloud/openworkflow/sdk/openapi/OperationDefinition.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package cloud.openworkflow.sdk.impl.executors.openapi; +package cloud.openworkflow.sdk.openapi; import java.util.ArrayList; import java.util.LinkedHashMap; @@ -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/openapi/ParameterDefinition.java similarity index 89% 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/openapi/ParameterDefinition.java index 41b87ad65..a856b4121 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/ParameterDefinition.java +++ b/common/openapi/src/main/java/cloud/openworkflow/sdk/openapi/ParameterDefinition.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package cloud.openworkflow.sdk.impl.executors.openapi; +package cloud.openworkflow.sdk.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/openapi/UnifiedOpenAPI.java similarity index 99% 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/openapi/UnifiedOpenAPI.java index a858a6598..3a47c0f6e 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/UnifiedOpenAPI.java +++ b/common/openapi/src/main/java/cloud/openworkflow/sdk/openapi/UnifiedOpenAPI.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package cloud.openworkflow.sdk.impl.executors.openapi; +package cloud.openworkflow.sdk.openapi; import java.util.HashSet; import java.util.List; 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/openapi/UnifiedOpenAPIReader.java similarity index 93% 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/openapi/UnifiedOpenAPIReader.java index 6f5a59cfc..d89deb4a0 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/UnifiedOpenAPIReader.java +++ b/common/openapi/src/main/java/cloud/openworkflow/sdk/openapi/UnifiedOpenAPIReader.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package cloud.openworkflow.sdk.impl.executors.openapi; +package cloud.openworkflow.sdk.openapi; public interface UnifiedOpenAPIReader { diff --git a/common/openapi/src/main/resources/native-image/cloud.openworkflow.sdk/openworkflow-common-openapi-jackson/reflect-config.json b/common/openapi/src/main/resources/native-image/cloud.openworkflow.sdk/openworkflow-common-openapi-jackson/reflect-config.json new file mode 100644 index 000000000..c72ce1994 --- /dev/null +++ b/common/openapi/src/main/resources/native-image/cloud.openworkflow.sdk/openworkflow-common-openapi-jackson/reflect-config.json @@ -0,0 +1,14 @@ +[ +{"name":"cloud.openworkflow.sdk.openapi.UnifiedOpenAPI","queryAllPublicConstructors":true,"queryAllDeclaredConstructors":true,"queryAllPublicMethods":true,"queryAllDeclaredMethods":true,"allPublicConstructors":true,"allDeclaredConstructors":true,"allPublicMethods":true,"allDeclaredMethods":true,"allPublicFields":true,"allDeclaredFields":true,"allPublicClasses":true,"allDeclaredClasses":true}, +{"name":"cloud.openworkflow.sdk.openapi.UnifiedOpenAPI$Components","queryAllPublicConstructors":true,"queryAllDeclaredConstructors":true,"queryAllPublicMethods":true,"queryAllDeclaredMethods":true,"allPublicConstructors":true,"allDeclaredConstructors":true,"allPublicMethods":true,"allDeclaredMethods":true,"allPublicFields":true,"allDeclaredFields":true,"allPublicClasses":true,"allDeclaredClasses":true}, +{"name":"cloud.openworkflow.sdk.openapi.UnifiedOpenAPI$Content","queryAllPublicConstructors":true,"queryAllDeclaredConstructors":true,"queryAllPublicMethods":true,"queryAllDeclaredMethods":true,"allPublicConstructors":true,"allDeclaredConstructors":true,"allPublicMethods":true,"allDeclaredMethods":true,"allPublicFields":true,"allDeclaredFields":true,"allPublicClasses":true,"allDeclaredClasses":true}, +{"name":"cloud.openworkflow.sdk.openapi.UnifiedOpenAPI$HttpOperation","queryAllPublicConstructors":true,"queryAllDeclaredConstructors":true,"queryAllPublicMethods":true,"queryAllDeclaredMethods":true,"allPublicConstructors":true,"allDeclaredConstructors":true,"allPublicMethods":true,"allDeclaredMethods":true,"allPublicFields":true,"allDeclaredFields":true,"allPublicClasses":true,"allDeclaredClasses":true}, +{"name":"cloud.openworkflow.sdk.openapi.UnifiedOpenAPI$MediaType","queryAllPublicConstructors":true,"queryAllDeclaredConstructors":true,"queryAllPublicMethods":true,"queryAllDeclaredMethods":true,"allPublicConstructors":true,"allDeclaredConstructors":true,"allPublicMethods":true,"allDeclaredMethods":true,"allPublicFields":true,"allDeclaredFields":true,"allPublicClasses":true,"allDeclaredClasses":true}, +{"name":"cloud.openworkflow.sdk.openapi.UnifiedOpenAPI$Operation","queryAllPublicConstructors":true,"queryAllDeclaredConstructors":true,"queryAllPublicMethods":true,"queryAllDeclaredMethods":true,"allPublicConstructors":true,"allDeclaredConstructors":true,"allPublicMethods":true,"allDeclaredMethods":true,"allPublicFields":true,"allDeclaredFields":true,"allPublicClasses":true,"allDeclaredClasses":true}, +{"name":"cloud.openworkflow.sdk.openapi.UnifiedOpenAPI$Parameter","queryAllPublicConstructors":true,"queryAllDeclaredConstructors":true,"queryAllPublicMethods":true,"queryAllDeclaredMethods":true,"allPublicConstructors":true,"allDeclaredConstructors":true,"allPublicMethods":true,"allDeclaredMethods":true,"allPublicFields":true,"allDeclaredFields":true,"allPublicClasses":true,"allDeclaredClasses":true}, +{"name":"cloud.openworkflow.sdk.openapi.UnifiedOpenAPI$PathItem","queryAllPublicConstructors":true,"queryAllDeclaredConstructors":true,"queryAllPublicMethods":true,"queryAllDeclaredMethods":true,"allPublicConstructors":true,"allDeclaredConstructors":true,"allPublicMethods":true,"allDeclaredMethods":true,"allPublicFields":true,"allDeclaredFields":true,"allPublicClasses":true,"allDeclaredClasses":true}, +{"name":"cloud.openworkflow.sdk.openapi.UnifiedOpenAPI$RequestBody","queryAllPublicConstructors":true,"queryAllDeclaredConstructors":true,"queryAllPublicMethods":true,"queryAllDeclaredMethods":true,"allPublicConstructors":true,"allDeclaredConstructors":true,"allPublicMethods":true,"allDeclaredMethods":true,"allPublicFields":true,"allDeclaredFields":true,"allPublicClasses":true,"allDeclaredClasses":true}, +{"name":"cloud.openworkflow.sdk.openapi.UnifiedOpenAPI$Schema","queryAllPublicConstructors":true,"queryAllDeclaredConstructors":true,"queryAllPublicMethods":true,"queryAllDeclaredMethods":true,"allPublicConstructors":true,"allDeclaredConstructors":true,"allPublicMethods":true,"allDeclaredMethods":true,"allPublicFields":true,"allDeclaredFields":true,"allPublicClasses":true,"allDeclaredClasses":true}, +{"name":"cloud.openworkflow.sdk.openapi.UnifiedOpenAPI$Server","queryAllPublicConstructors":true,"queryAllDeclaredConstructors":true,"queryAllPublicMethods":true,"queryAllDeclaredMethods":true,"allPublicConstructors":true,"allDeclaredConstructors":true,"allPublicMethods":true,"allDeclaredMethods":true,"allPublicFields":true,"allDeclaredFields":true,"allPublicClasses":true,"allDeclaredClasses":true}, +{"name":"cloud.openworkflow.sdk.openapi.UnifiedOpenAPI$SwaggerVersion","queryAllPublicConstructors":true,"queryAllDeclaredConstructors":true,"queryAllPublicMethods":true,"queryAllDeclaredMethods":true,"allPublicConstructors":true,"allDeclaredConstructors":true,"allPublicMethods":true,"allDeclaredMethods":true,"allPublicFields":true,"allDeclaredFields":true,"allPublicClasses":true,"allDeclaredClasses":true} +] \ No newline at end of file diff --git a/common/openapi/src/test/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIClientTest.java b/common/openapi/src/test/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIClientTest.java new file mode 100644 index 000000000..1127fb8d5 --- /dev/null +++ b/common/openapi/src/test/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIClientTest.java @@ -0,0 +1,296 @@ +/* + * 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.assertThat; + +import cloud.openworkflow.sdk.http.JdkHttpTransport; +import cloud.openworkflow.sdk.http.WorkflowHttpRequestInfo; +import cloud.openworkflow.sdk.http.WorkflowHttpResponse; +import cloud.openworkflow.sdk.openapi.OpenAPIClient; +import cloud.openworkflow.sdk.openapi.UnifiedOpenAPI; +import java.net.URI; +import java.net.http.HttpClient; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import mockwebserver3.RecordedRequest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class OpenAPIClientTest { + + private MockWebServer mockWebServer; + private String baseUrl; + + @BeforeEach + void setUp() throws Exception { + mockWebServer = new MockWebServer(); + mockWebServer.start(); + baseUrl = mockWebServer.url("/").toString(); + } + + @AfterEach + void tearDown() throws Exception { + mockWebServer.close(); + } + + @Test + void testSimpleGetRequest() throws Exception { + // Given: A programmatically created OpenAPI document + UnifiedOpenAPI document = createSimpleOpenAPIDocument(); + + // And: A mock server response + mockWebServer.enqueue( + new MockResponse.Builder() + .code(200) + .body("{\"message\":\"Hello World\"}") + .addHeader("Content-Type", "application/json") + .build()); + + // And: An OpenAPI client + OpenAPIClient client = + new OpenAPIClient<>(document, "getGreeting", body -> serializeBody(body)); + + // When: Executing the request + try (HttpClient httpClient = HttpClient.newHttpClient()) { + JdkHttpTransport transport = + new JdkHttpTransport<>(httpClient, JdkHttpTransport.BYTES); + Map parameters = Map.of("name", "John"); + WorkflowHttpRequestInfo request = + client.createRequest(parameters).build(URI.create(baseUrl)); + CompletableFuture> responseFuture = transport.execute(request); + + try (WorkflowHttpResponse response = responseFuture.get()) { + // Then: The request should be successful + assertThat(response.status()).isEqualTo(200); + assertThat(new String(response.body(), StandardCharsets.UTF_8)) + .isEqualTo("{\"message\":\"Hello World\"}"); + + // And: The server received the correct request + RecordedRequest recordedRequest = mockWebServer.takeRequest(); + assertThat(recordedRequest.getMethod()).isEqualTo("GET"); + assertThat(recordedRequest.getRequestLine()).contains("/greetings"); + assertThat(recordedRequest.getRequestLine()).contains("name=John"); + } + } + } + + @Test + void testPostRequestWithBody() throws Exception { + // Given: A programmatically created OpenAPI document with POST operation + UnifiedOpenAPI document = createPostOpenAPIDocument(); + + // And: A mock server response + mockWebServer.enqueue( + new MockResponse.Builder() + .code(201) + .body("{\"id\":\"123\",\"status\":\"created\"}") + .addHeader("Content-Type", "application/json") + .build()); + + // And: An OpenAPI client + OpenAPIClient client = + new OpenAPIClient<>(document, "createUser", body -> serializeBody(body)); + + // When: Executing the request + try (HttpClient httpClient = HttpClient.newHttpClient()) { + JdkHttpTransport transport = + new JdkHttpTransport<>(httpClient, JdkHttpTransport.BYTES); + Map parameters = Map.of("username", "john_doe", "email", "john@example.com"); + WorkflowHttpRequestInfo request = + client.createRequest(parameters).build(URI.create(baseUrl)); + CompletableFuture> responseFuture = transport.execute(request); + + try (WorkflowHttpResponse response = responseFuture.get()) { + // Then: The request should be successful + assertThat(response.status()).isEqualTo(201); + assertThat(new String(response.body(), StandardCharsets.UTF_8)).contains("\"id\":\"123\""); + + // And: The server received the correct request + RecordedRequest recordedRequest = mockWebServer.takeRequest(); + assertThat(recordedRequest.getMethod()).isEqualTo("POST"); + assertThat(recordedRequest.getRequestLine()).contains("/users"); + String requestBody = recordedRequest.getBody().utf8(); + assertThat(requestBody).contains("john_doe"); + assertThat(requestBody).contains("john@example.com"); + } + } + } + + @Test + void testRequestWithPathParameter() throws Exception { + // Given: A programmatically created OpenAPI document with path parameter + UnifiedOpenAPI document = createPathParameterOpenAPIDocument(); + + // And: A mock server response + mockWebServer.enqueue( + new MockResponse.Builder() + .code(200) + .body("{\"id\":\"42\",\"name\":\"Test User\"}") + .addHeader("Content-Type", "application/json") + .build()); + + // And: An OpenAPI client + OpenAPIClient client = + new OpenAPIClient<>(document, "getUserById", body -> serializeBody(body)); + + // When: Executing the request + try (HttpClient httpClient = HttpClient.newHttpClient()) { + JdkHttpTransport transport = + new JdkHttpTransport<>(httpClient, JdkHttpTransport.BYTES); + Map parameters = Map.of("userId", "42"); + WorkflowHttpRequestInfo request = + client.createRequest(parameters).build(URI.create(baseUrl)); + CompletableFuture> responseFuture = transport.execute(request); + + try (WorkflowHttpResponse response = responseFuture.get()) { + // Then: The request should be successful + assertThat(response.status()).isEqualTo(200); + + // And: The server received the correct request with path parameter + RecordedRequest recordedRequest = mockWebServer.takeRequest(); + assertThat(recordedRequest.getMethod()).isEqualTo("GET"); + assertThat(recordedRequest.getRequestLine()).contains("/users/42"); + } + } + } + + // Helper method to create a simple OpenAPI document programmatically + private UnifiedOpenAPI createSimpleOpenAPIDocument() { + UnifiedOpenAPI.Parameter nameParam = + new UnifiedOpenAPI.Parameter( + "name", + "query", + true, + new UnifiedOpenAPI.Schema("string", null, null, null, null), + null); + + UnifiedOpenAPI.Operation operation = + new UnifiedOpenAPI.Operation("getGreeting", null, List.of(nameParam), null); + + UnifiedOpenAPI.PathItem pathItem = + new UnifiedOpenAPI.PathItem(null, null, operation, null, null, null, null, null, null); + + Map paths = Map.of("/greetings", pathItem); + + return new UnifiedOpenAPI( + "2.0", + List.of(new UnifiedOpenAPI.Server("http://localhost:8080")), + "localhost:8080", + "", + List.of("http"), + paths, + null, + null, + null); + } + + // Helper method to create an OpenAPI document with POST operation + private UnifiedOpenAPI createPostOpenAPIDocument() { + UnifiedOpenAPI.Schema bodySchema = + new UnifiedOpenAPI.Schema( + "object", + Map.of( + "username", + new UnifiedOpenAPI.Schema("string", null, null, null, null), + "email", + new UnifiedOpenAPI.Schema("string", null, null, null, null)), + List.of("username", "email"), + null, + null); + + UnifiedOpenAPI.RequestBody requestBody = + new UnifiedOpenAPI.RequestBody( + new UnifiedOpenAPI.Content(new UnifiedOpenAPI.MediaType(bodySchema))); + + UnifiedOpenAPI.Operation operation = + new UnifiedOpenAPI.Operation("createUser", null, null, requestBody); + + UnifiedOpenAPI.PathItem pathItem = + new UnifiedOpenAPI.PathItem(null, null, null, operation, null, null, null, null, null); + + Map paths = Map.of("/users", pathItem); + + return new UnifiedOpenAPI( + "2.0", + List.of(new UnifiedOpenAPI.Server("http://localhost:8080")), + "localhost:8080", + "", + List.of("http"), + paths, + null, + null, + null); + } + + // Helper method to create an OpenAPI document with path parameter + private UnifiedOpenAPI createPathParameterOpenAPIDocument() { + UnifiedOpenAPI.Parameter userIdParam = + new UnifiedOpenAPI.Parameter( + "userId", + "path", + true, + new UnifiedOpenAPI.Schema("string", null, null, null, null), + null); + + UnifiedOpenAPI.Operation operation = + new UnifiedOpenAPI.Operation("getUserById", null, List.of(userIdParam), null); + + UnifiedOpenAPI.PathItem pathItem = + new UnifiedOpenAPI.PathItem(null, null, operation, null, null, null, null, null, null); + + Map paths = Map.of("/users/{userId}", pathItem); + + return new UnifiedOpenAPI( + "2.0", + List.of(new UnifiedOpenAPI.Server("http://localhost:8080")), + "localhost:8080", + "", + List.of("http"), + paths, + null, + null, + null); + } + + // Simple body serialization (for testing purposes) + private byte[] serializeBody(Map body) { + if (body == null || body.isEmpty()) { + return null; + } + // Simple JSON serialization without Jackson + StringBuilder json = new StringBuilder("{"); + boolean first = true; + for (Map.Entry entry : body.entrySet()) { + if (!first) { + json.append(","); + } + json.append("\"") + .append(entry.getKey()) + .append("\":\"") + .append(entry.getValue()) + .append("\""); + first = false; + } + json.append("}"); + return json.toString().getBytes(StandardCharsets.UTF_8); + } +} diff --git a/common/pom.xml b/common/pom.xml new file mode 100644 index 000000000..906f346a4 --- /dev/null +++ b/common/pom.xml @@ -0,0 +1,18 @@ + + 4.0.0 + + cloud.openworkflow.sdk + openworkflow-parent + 8.0.0-SNAPSHOT + + openworkflow-common + pom + Open Workflow :: Common + + api + http + http-jakarta + openapi + openapi-jackson + + \ No newline at end of file diff --git a/impl/README.md b/impl/README.md index a1d944f3c..fb9ed44f4 100644 --- a/impl/README.md +++ b/impl/README.md @@ -92,7 +92,7 @@ This SDK is modular by design—pull in only what you need: * **openworkflow-impl-function** Jackson Function support. * **openworkflow-impl-json** Jackson common utilities shared by all modules in this list * **openworkflow-impl-cron** Cron parsing for workflow scheduled execution - * **openworkflow-impl-openapi** Deserialization support of OpenAPI schemas using Jackson (required for OpenAPI call task to work) + * **openworkflow-impl-openapi-jackson** Deserialization support of OpenAPI schemas using Jackson (required for OpenAPI call task to work) Additionally, The OpenWokflow specification defines a set of [call task](https://github.com/open-workflow-specification/specification/blob/main/dsl-reference.md#call), which requires additional dependencies, with the exception of HTTP (see section below). You might add those ones needed depending on the feature you are using in your definition: @@ -112,12 +112,16 @@ 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. - * **openworkflow-impl-http** HTTP `Call` task handler, based on JAX-RS client - * **openworkflow-impl-http-jackson** Optimized entity converter for Jackson model + * **openworkflow-impl-http-jakarta** HTTP `Call` task handler, based on JAX-RS client + * **openworkflow-impl-http-jakarta-jackson** Optimized entity converter for Jackson model --- @@ -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..0281df2b7 100644 --- a/impl/core/pom.xml +++ b/impl/core/pom.xml @@ -8,6 +8,14 @@ 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/FunctionReader.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/FunctionReader.java index e33e1eca5..c213b4e2d 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/FunctionReader.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/FunctionReader.java @@ -16,6 +16,7 @@ package cloud.openworkflow.sdk.impl; import cloud.openworkflow.sdk.api.types.Task; +import cloud.openworkflow.sdk.common.ServicePriority; import java.util.function.BiFunction; public interface FunctionReader diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/WorkflowApplication.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/WorkflowApplication.java index 70a9015a1..be88c49ab 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/WorkflowApplication.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/WorkflowApplication.java @@ -21,6 +21,8 @@ import cloud.openworkflow.sdk.api.types.SchemaInline; import cloud.openworkflow.sdk.api.types.Workflow; +import cloud.openworkflow.sdk.http.JdkURITemplateResolver; +import cloud.openworkflow.sdk.http.URITemplateResolver; import cloud.openworkflow.sdk.impl.additional.NamedSuppliedAdditionalObject; import cloud.openworkflow.sdk.impl.additional.NamedWorkflowAdditionalObject; import cloud.openworkflow.sdk.impl.additional.WorkflowAdditionalObject; @@ -41,10 +43,8 @@ import cloud.openworkflow.sdk.impl.executors.TaskExecutorFactory; import cloud.openworkflow.sdk.impl.expressions.ExpressionFactory; import cloud.openworkflow.sdk.impl.expressions.RuntimeDescriptor; -import cloud.openworkflow.sdk.impl.http.DefaultHttpRequestBuilderFactory; -import cloud.openworkflow.sdk.impl.http.DefaultURITemplateResolver; -import cloud.openworkflow.sdk.impl.http.URITemplateResolver; -import cloud.openworkflow.sdk.impl.http.WorkflowHttpRequestFactory; +import cloud.openworkflow.sdk.impl.http.DefaultHttpTransportFactory; +import cloud.openworkflow.sdk.impl.http.WorkflowHttpTransportFactory; import cloud.openworkflow.sdk.impl.lifecycle.LifeCycleEventType; import cloud.openworkflow.sdk.impl.lifecycle.WorkflowExecutionCompletableListener; import cloud.openworkflow.sdk.impl.lifecycle.WorkflowExecutionListener; @@ -81,7 +81,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; -import java.util.function.Supplier; +import java.util.function.Function; import java.util.stream.Collectors; public class WorkflowApplication implements AutoCloseable { @@ -105,7 +105,7 @@ public class WorkflowApplication implements AutoCloseable { private final WorkflowModelFactory contextFactory; private final WorkflowScheduler scheduler; private final Map> additionalObjects; - private final Map> additionalObjectSuppliers; + private final Map> additionalObjectSuppliers; private final AuthProviderFactory authProviderFactory; private final ConfigManager configManager; private final SecretManager secretManager; @@ -120,7 +120,7 @@ public class WorkflowApplication implements AutoCloseable { private final WorkflowLifeCycleCloudEventFactory lifeCycleCloudEventFactory; private final ScheduledExecutorService schedulerExecutorService; private final Set allowedCommands; - private final WorkflowHttpRequestFactory httpRequestBuilderFactory; + private final WorkflowHttpTransportFactory httpTransportFactory; private final Map, ServiceLoader> servicesLoaded = new ConcurrentHashMap<>(); private final Set lifeCycleEventTypes; @@ -160,7 +160,9 @@ private WorkflowApplication(Builder builder) { this.schedulerExecutorService = builder.schedulerExecutorService; this.allowedCommands = Collections.unmodifiableSet(builder.allowedCommands); this.lifeCycleEventTypes = builder.lifeCycleEventTypes; - this.httpRequestBuilderFactory = builder.httpRequestBuilderFactory; + this.httpTransportFactory = builder.httpTransportFactory; + // TODO search a better place to call this + httpTransportFactory.init(this); } public TaskExecutorFactory taskFactory() { @@ -274,7 +276,8 @@ public SchemaValidator getValidator(String resouceName, byte[] content) { private WorkflowModelFactory modelFactory; private WorkflowModelFactory contextFactory; private Map> additionalObjects = new HashMap<>(); - private Map> additionalObjectSuppliers = new HashMap<>(); + private Map> additionalObjectSuppliers = + new HashMap<>(); private AuthProviderFactory authProviderFactory; private SecretManager secretManager; private ConfigManager configManager; @@ -290,7 +293,7 @@ public SchemaValidator getValidator(String resouceName, byte[] content) { private ScheduledExecutorService schedulerExecutorService; private Set allowedCommands = new HashSet<>(); private Set lifeCycleEventTypes; - private WorkflowHttpRequestFactory httpRequestBuilderFactory; + private WorkflowHttpTransportFactory httpTransportFactory; private Builder() { ServiceLoader.load(NamedWorkflowAdditionalObject.class) @@ -400,7 +403,8 @@ public Builder withAdditionalObject( return this; } - public Builder withAdditionalObject(String name, Supplier additionalObject) { + public Builder withAdditionalObject( + String name, Function additionalObject) { additionalObjectSuppliers.put(name, additionalObject); return this; } @@ -476,9 +480,8 @@ public Builder withLifeCycleEventTypes(Set lifeCycleEventTyp return this; } - public Builder withHttpRequestBuilderFactory( - WorkflowHttpRequestFactory httpRequestBuilderFactory) { - this.httpRequestBuilderFactory = httpRequestBuilderFactory; + public Builder withHttpTransportFactory(WorkflowHttpTransportFactory httpTransportFactory) { + this.httpTransportFactory = httpTransportFactory; return this; } @@ -514,14 +517,15 @@ public WorkflowApplication build() { ServiceLoader.load(EventPublisher.class).forEach(e -> eventPublishers.add(e)); if (eventConsumer == null) { eventConsumer = - loadFirst(EventConsumer.class) - .orElseGet(() -> { - InMemoryEvents inMemory = new InMemoryEvents(executorFactory); - if (eventPublishers.isEmpty()) { - eventPublishers.add(inMemory); - } - return inMemory; - }); + (EventConsumer) + loadFirst(EventConsumer.class) + .orElseGet(() -> { + InMemoryEvents inMemory = new InMemoryEvents(executorFactory); + if (eventPublishers.isEmpty()) { + eventPublishers.add(inMemory); + } + return inMemory; + }); } if (idFactory == null) { idFactory = new MonotonicUlidWorkflowInstanceIdFactory(); @@ -564,7 +568,7 @@ public CronResolver parseCron(String cron) { } if (templateResolver == null) { templateResolver = - loadFirst(URITemplateResolver.class).orElseGet(() -> new DefaultURITemplateResolver()); + loadFirst(URITemplateResolver.class).orElseGet(() -> new JdkURITemplateResolver()); } functionReader = loadFirst(FunctionReader.class); if (cloudEventPredicateFactory == null) { @@ -597,13 +601,12 @@ public CronResolver parseCron(String cron) { if (lifeCycleEventTypes == null) { lifeCycleEventTypes = EnumSet.of(LifeCycleEventType.V8); } - if (httpRequestBuilderFactory == null) { - httpRequestBuilderFactory = - loadFirst(WorkflowHttpRequestFactory.class) - .orElseGet(() -> new DefaultHttpRequestBuilderFactory()); + if (httpTransportFactory == null) { + httpTransportFactory = + loadFirst(WorkflowHttpTransportFactory.class) + .orElseGet(() -> new DefaultHttpTransportFactory()); } WorkflowApplication app = new WorkflowApplication(this); - httpRequestBuilderFactory.init(app); return app; } @@ -643,7 +646,7 @@ public void close() { } listenersByPriority.clear(); } - safeClose(httpRequestBuilderFactory); + safeClose(httpTransportFactory); } public WorkflowPositionFactory positionFactory() { @@ -720,7 +723,7 @@ public String id() { } public Optional additionalObject(String name) { - return Optional.ofNullable(additionalObjectSuppliers.get(name)).map(v -> (T) v.get()); + return Optional.ofNullable(additionalObjectSuppliers.get(name)).map(v -> (T) v.apply(this)); } public Optional additionalObject( @@ -754,8 +757,8 @@ public Set lifeCycleEventTypes() { return lifeCycleEventTypes; } - public WorkflowHttpRequestFactory httpRequestFactory() { - return httpRequestBuilderFactory; + public WorkflowHttpTransportFactory transportFactory() { + return httpTransportFactory; } @SuppressWarnings("unchecked") diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/WorkflowDecorator.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/WorkflowDecorator.java index f506ad184..bdf5a8835 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/WorkflowDecorator.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/WorkflowDecorator.java @@ -15,6 +15,8 @@ */ package cloud.openworkflow.sdk.impl; +import cloud.openworkflow.sdk.common.ServicePriority; + /** * Parent interface for decorating object requests with additional modifications.
* It is expected that this class is inherited by specializations that indicate the type to be diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/WorkflowModelFactory.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/WorkflowModelFactory.java index a56362279..0aa5e35c2 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/WorkflowModelFactory.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/WorkflowModelFactory.java @@ -15,6 +15,7 @@ */ package cloud.openworkflow.sdk.impl; +import cloud.openworkflow.sdk.common.ServicePriority; import io.cloudevents.CloudEvent; import io.cloudevents.CloudEventData; import java.time.OffsetDateTime; diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/WorkflowUtils.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/WorkflowUtils.java index d4fa8ba1d..83f1b9e55 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/WorkflowUtils.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/WorkflowUtils.java @@ -19,6 +19,7 @@ import cloud.openworkflow.sdk.api.types.ExportAs; import cloud.openworkflow.sdk.api.types.InputFrom; import cloud.openworkflow.sdk.api.types.OutputAs; +import cloud.openworkflow.sdk.api.types.ReferenceableAuthenticationPolicy; import cloud.openworkflow.sdk.api.types.SchemaUnion; import cloud.openworkflow.sdk.api.types.SecretBasedAuthenticationPolicy; import cloud.openworkflow.sdk.api.types.TaskBase; @@ -26,7 +27,11 @@ import cloud.openworkflow.sdk.api.types.Timeout; import cloud.openworkflow.sdk.api.types.TimeoutAfter; import cloud.openworkflow.sdk.api.types.UriTemplate; +import cloud.openworkflow.sdk.api.types.Use; +import cloud.openworkflow.sdk.api.types.UseAuthentications; import cloud.openworkflow.sdk.api.types.Workflow; +import cloud.openworkflow.sdk.common.ServicePriority; +import cloud.openworkflow.sdk.impl.auth.AuthProvider; import cloud.openworkflow.sdk.impl.expressions.ExpressionDescriptor; import cloud.openworkflow.sdk.impl.expressions.ExpressionFactory; import cloud.openworkflow.sdk.impl.expressions.ExpressionUtils; @@ -34,7 +39,6 @@ import cloud.openworkflow.sdk.impl.schema.SchemaValidator; import cloud.openworkflow.sdk.impl.schema.SchemaValidatorFactory; import java.net.URI; -import java.net.URISyntaxException; import java.time.Duration; import java.util.Map; import java.util.Objects; @@ -274,43 +278,6 @@ public static final String checkSecret( .orElseThrow(() -> new IllegalStateException("Secret " + secretName + " does not exist")); } - public static URI concatURI(URI base, String pathToAppend) { - return !isValid(pathToAppend) ? base : concatURI(base, URI.create(pathToAppend)); - } - - public static URI concatURI(URI base, URI child) { - if (child.isAbsolute()) { - return child; - } - - String basePath = base.getPath(); - if (!isValid(basePath)) { - basePath = "/"; - } else if (!basePath.endsWith("/")) { - basePath = basePath + "/"; - } - - String relPath = child.getPath(); - if (relPath == null) { - relPath = ""; - } else { - while (relPath.startsWith("/")) { - relPath = relPath.substring(1); - } - } - try { - return new URI( - base.getScheme(), - base.getAuthority(), - basePath + relPath, - child.getQuery(), - child.getFragment()); - } catch (URISyntaxException e) { - throw new IllegalArgumentException( - "Failed to build combined URI from base=" + base + " and child=" + child, e); - } - } - public static WorkflowValueResolver getURISupplier( WorkflowApplication application, UriTemplate template) { if (template.getLiteralUri() != null) { @@ -324,13 +291,37 @@ public static WorkflowValueResolver getURISupplier( throw new IllegalArgumentException("Invalid uritemplate definition " + template); } - public static Optional loadFirst(Class serviceClass) { + public static > Optional loadFirst(Class serviceClass) { return ServiceLoader.load(serviceClass).stream() .map(ServiceLoader.Provider::get) .sorted() .findFirst(); } + public static AuthProvider buildAuthProvider( + WorkflowDefinition definition, ReferenceableAuthenticationPolicy policy) { + if (policy != null) { + if (policy.getAuthenticationPolicyReference() != null) { + String name = policy.getAuthenticationPolicyReference().getUse(); + Use use = definition.workflow().getUse(); + UseAuthentications authentications = use == null ? null : use.getAuthentications(); + if (authentications == null + || !authentications.getAdditionalProperties().containsKey(name)) { + throw new IllegalArgumentException( + String.format( + "Authentication '%s' is referenced but not defined in use.authentications.", + name)); + } + } + return definition + .application() + .authProviderFactory() + .getAuth(definition, policy) + .orElse(null); + } + return null; + } + public static void validationError( Optional errorBuilder, TaskContextData taskContext) { validationError(errorBuilder, taskContext.position().jsonPointer().toString()); diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/additional/ConstantAdditionalObject.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/additional/ConstantAdditionalObject.java index f88652e07..8d72325db 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/additional/ConstantAdditionalObject.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/additional/ConstantAdditionalObject.java @@ -15,6 +15,8 @@ */ package cloud.openworkflow.sdk.impl.additional; +import cloud.openworkflow.sdk.impl.WorkflowApplication; + public class ConstantAdditionalObject implements NamedSuppliedAdditionalObject { private final String name; @@ -26,7 +28,7 @@ public ConstantAdditionalObject(String name, T object) { } @Override - public T get() { + public T apply(WorkflowApplication app) { return object; } diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/additional/NamedSuppliedAdditionalObject.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/additional/NamedSuppliedAdditionalObject.java index e8fd24118..5ce4655db 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/additional/NamedSuppliedAdditionalObject.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/additional/NamedSuppliedAdditionalObject.java @@ -16,6 +16,8 @@ package cloud.openworkflow.sdk.impl.additional; import cloud.openworkflow.sdk.impl.NamedObject; -import java.util.function.Supplier; +import cloud.openworkflow.sdk.impl.WorkflowApplication; +import java.util.function.Function; -public interface NamedSuppliedAdditionalObject extends Supplier, NamedObject {} +public interface NamedSuppliedAdditionalObject + extends Function, NamedObject {} diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/auth/AccessTokenProvider.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/auth/AccessTokenProvider.java index bd064a668..955cbf979 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/auth/AccessTokenProvider.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/auth/AccessTokenProvider.java @@ -15,12 +15,13 @@ */ package cloud.openworkflow.sdk.impl.auth; +import cloud.openworkflow.sdk.http.WorkflowHttpHeaders; +import cloud.openworkflow.sdk.http.WorkflowHttpRequestInfo; import cloud.openworkflow.sdk.impl.TaskContext; import cloud.openworkflow.sdk.impl.WorkflowApplication; import cloud.openworkflow.sdk.impl.WorkflowContext; -import cloud.openworkflow.sdk.impl.http.WorkflowHttpContentType; +import cloud.openworkflow.sdk.impl.WorkflowModel; import cloud.openworkflow.sdk.impl.http.WorkflowHttpHelper; -import cloud.openworkflow.sdk.impl.http.WorkflowHttpRequestInfo; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; @@ -45,10 +46,11 @@ class AccessTokenProvider { public CompletableFuture validateAndGet(WorkflowContext workflow, TaskContext context) { AuthHttpRequestInfo authRequestInfo = requestInfoSupplier.get(); - WorkflowHttpRequestInfo httpRequestInfo = + WorkflowHttpRequestInfo httpRequestInfo = buildHttpRequestInfo(workflow, context, authRequestInfo); CompletableFuture future = - WorkflowHttpHelper.executeRequest(httpRequestInfo, app, workflow, context) + WorkflowHttpHelper.executeRequest( + httpRequestInfo, app, workflow, context, WorkflowHttpHelper.byteValidationFunction) .thenApply(bytes -> jwtConverter.fromToken(bytes)); List issuers = authRequestInfo.issuers(); if (!issuers.isEmpty()) { @@ -67,9 +69,10 @@ public CompletableFuture validateAndGet(WorkflowContext workflow, TaskConte return future; } - private WorkflowHttpRequestInfo buildHttpRequestInfo( + private WorkflowHttpRequestInfo buildHttpRequestInfo( WorkflowContext workflow, TaskContext task, AuthHttpRequestInfo requestInfo) { - WorkflowHttpRequestInfo.Builder builder = WorkflowHttpRequestInfo.builder("POST"); + WorkflowHttpRequestInfo.Builder builder = + WorkflowHttpRequestInfo.builder("POST"); Map headers = new LinkedHashMap<>(); headers.put("grant_type", requestInfo.grantType()); headers.put("User-Agent", "OAuth2-Client-Credentials/1.0"); @@ -78,7 +81,7 @@ private WorkflowHttpRequestInfo buildHttpRequestInfo( for (var entry : requestInfo.headers().entrySet()) { headers.put(entry.getKey(), entry.getValue().apply(workflow, task)); } - headers.put(WorkflowHttpContentType.HEADER_NAME, requestInfo.contentType().toString()); + headers.put(WorkflowHttpHeaders.CONTENT_TYPE, requestInfo.contentType().toString()); builder.headers(headers); Map body = new HashMap(); body.put("grant_type", requestInfo.grantType()); diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/auth/AuthHttpRequestInfoBuilder.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/auth/AuthHttpRequestInfoBuilder.java index bf1249362..1ca945152 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/auth/AuthHttpRequestInfoBuilder.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/auth/AuthHttpRequestInfoBuilder.java @@ -16,8 +16,8 @@ package cloud.openworkflow.sdk.impl.auth; import cloud.openworkflow.sdk.api.types.OAuth2TokenRequest; +import cloud.openworkflow.sdk.http.WorkflowHttpHeaders; import cloud.openworkflow.sdk.impl.WorkflowValueResolver; -import cloud.openworkflow.sdk.impl.http.WorkflowHttpContentType; import java.net.URI; import java.util.Arrays; import java.util.HashMap; @@ -137,7 +137,7 @@ AuthHttpRequestInfo build() { introspectionUri, grantType, contentType == null - ? contentType = WorkflowHttpContentType.APPLICATION_X_WWW_FORM_URLENCODED + ? contentType = WorkflowHttpHeaders.APPLICATION_X_WWW_FORM_URLENCODED : contentType, issuers == null ? List.of() : issuers); } diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/auth/DigestAuthProvider.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/auth/DigestAuthProvider.java index 00cf3d0b6..9793652c4 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/auth/DigestAuthProvider.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/auth/DigestAuthProvider.java @@ -23,13 +23,15 @@ import cloud.openworkflow.sdk.api.types.DigestAuthenticationPolicy; import cloud.openworkflow.sdk.api.types.DigestAuthenticationProperties; import cloud.openworkflow.sdk.api.types.Workflow; +import cloud.openworkflow.sdk.http.WorkflowHttpRequestInfo; +import cloud.openworkflow.sdk.http.WorkflowHttpResponse; 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 cloud.openworkflow.sdk.impl.WorkflowUtils; import cloud.openworkflow.sdk.impl.WorkflowValueResolver; -import cloud.openworkflow.sdk.impl.http.WorkflowHttpRequestInfo; -import cloud.openworkflow.sdk.impl.http.WorkflowHttpResponse; +import cloud.openworkflow.sdk.impl.http.WorkflowHttpHelper; import cloud.openworkflow.sdk.impl.utils.RandomFactory; import java.net.URI; import java.security.MessageDigest; @@ -144,9 +146,8 @@ public String scheme() { @Override public CompletableFuture content( WorkflowContext workflow, TaskContext task, URI uri, String method) { - return app.httpRequestFactory() - .request(app, WorkflowHttpRequestInfo.builder(method).build(uri)) - .invoke(workflow, task) + return WorkflowHttpHelper.executeRequest( + WorkflowHttpRequestInfo.builder(method).build(uri), app, workflow, task) .thenApply(r -> { try { return processResponse(r, uri, method, workflow, task); @@ -157,7 +158,11 @@ public CompletableFuture content( } private String processResponse( - WorkflowHttpResponse r, URI uri, String method, WorkflowContext workflow, TaskContext task) { + WorkflowHttpResponse r, + URI uri, + String method, + WorkflowContext workflow, + TaskContext task) { int responseCode = r.status(); if (responseCode == 401) { DigestServerInfo serverInfo = DigestServerInfo.from(r.getHeader("WWW-Authenticate")); diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/auth/JWTConverter.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/auth/JWTConverter.java index 16673932a..9ca5e8a26 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/auth/JWTConverter.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/auth/JWTConverter.java @@ -15,7 +15,7 @@ */ package cloud.openworkflow.sdk.impl.auth; -import cloud.openworkflow.sdk.impl.ServicePriority; +import cloud.openworkflow.sdk.common.ServicePriority; public interface JWTConverter extends ServicePriority { diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/auth/OAuthRequestBuilder.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/auth/OAuthRequestBuilder.java index 0a01e11ea..3c61f960f 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/auth/OAuthRequestBuilder.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/auth/OAuthRequestBuilder.java @@ -15,7 +15,7 @@ */ package cloud.openworkflow.sdk.impl.auth; -import static cloud.openworkflow.sdk.impl.WorkflowUtils.concatURI; +import static cloud.openworkflow.sdk.http.URIHelper.concatURI; import static cloud.openworkflow.sdk.impl.auth.AuthUtils.AUTHORITY; import cloud.openworkflow.sdk.api.types.OAuth2AuthenticationPropertiesEndpoints; diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/config/ConfigManager.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/config/ConfigManager.java index 2fdf35046..5617df34d 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/config/ConfigManager.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/config/ConfigManager.java @@ -15,7 +15,7 @@ */ package cloud.openworkflow.sdk.impl.config; -import cloud.openworkflow.sdk.impl.ServicePriority; +import cloud.openworkflow.sdk.common.ServicePriority; import java.util.Collection; import java.util.List; import java.util.Optional; diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/config/SecretManager.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/config/SecretManager.java index 24be190e3..253bcc0e7 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/config/SecretManager.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/config/SecretManager.java @@ -15,7 +15,7 @@ */ package cloud.openworkflow.sdk.impl.config; -import cloud.openworkflow.sdk.impl.ServicePriority; +import cloud.openworkflow.sdk.common.ServicePriority; import java.util.Map; @FunctionalInterface diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/events/CloudEventPredicateFactory.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/events/CloudEventPredicateFactory.java index 66d3a7044..ac05f2d07 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/events/CloudEventPredicateFactory.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/events/CloudEventPredicateFactory.java @@ -16,7 +16,7 @@ package cloud.openworkflow.sdk.impl.events; import cloud.openworkflow.sdk.api.types.EventProperties; -import cloud.openworkflow.sdk.impl.ServicePriority; +import cloud.openworkflow.sdk.common.ServicePriority; import cloud.openworkflow.sdk.impl.WorkflowApplication; public interface CloudEventPredicateFactory extends ServicePriority { diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/events/EventConsumer.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/events/EventConsumer.java index a9d93946f..e11bfaa05 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/events/EventConsumer.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/events/EventConsumer.java @@ -16,7 +16,7 @@ package cloud.openworkflow.sdk.impl.events; import cloud.openworkflow.sdk.api.types.EventFilter; -import cloud.openworkflow.sdk.impl.ServicePriority; +import cloud.openworkflow.sdk.common.ServicePriority; import cloud.openworkflow.sdk.impl.TaskContext; import cloud.openworkflow.sdk.impl.WorkflowApplication; import cloud.openworkflow.sdk.impl.WorkflowContext; diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/CallFunctionExecutorBuilder.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/CallFunctionExecutorBuilder.java index e5a72fbef..b7c26b51b 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/CallFunctionExecutorBuilder.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/CallFunctionExecutorBuilder.java @@ -21,6 +21,7 @@ import cloud.openworkflow.sdk.api.types.Task; import cloud.openworkflow.sdk.api.types.TaskBase; import cloud.openworkflow.sdk.api.types.Use; +import cloud.openworkflow.sdk.http.URIHelper; import cloud.openworkflow.sdk.impl.WorkflowDefinition; import cloud.openworkflow.sdk.impl.WorkflowMutablePosition; import cloud.openworkflow.sdk.impl.WorkflowUtils; @@ -84,8 +85,7 @@ public CallableTaskFactory init( definition .resourceLoader() .loadURI( - WorkflowUtils.concatURI( - catalogEndpoint, pathFromFunctionName(functionPosition, sep)), + URIHelper.concatURI(catalogEndpoint, pathFromFunctionName(functionPosition, sep)), (n, b) -> from(definition, n, b)); functionPosition = functionPosition.substring(0, sep); } else if (use != null diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/CallableTaskBuilder.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/CallableTaskBuilder.java index 86597b106..d29975270 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/CallableTaskBuilder.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/CallableTaskBuilder.java @@ -16,7 +16,7 @@ package cloud.openworkflow.sdk.impl.executors; import cloud.openworkflow.sdk.api.types.TaskBase; -import cloud.openworkflow.sdk.impl.ServicePriority; +import cloud.openworkflow.sdk.common.ServicePriority; import cloud.openworkflow.sdk.impl.WorkflowDefinition; import cloud.openworkflow.sdk.impl.WorkflowMutablePosition; diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/CallableTaskProxyBuilder.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/CallableTaskProxyBuilder.java index 6284a411d..6738242d3 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/CallableTaskProxyBuilder.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/CallableTaskProxyBuilder.java @@ -16,7 +16,7 @@ package cloud.openworkflow.sdk.impl.executors; import cloud.openworkflow.sdk.api.types.TaskBase; -import cloud.openworkflow.sdk.impl.ServicePriority; +import cloud.openworkflow.sdk.common.ServicePriority; public interface CallableTaskProxyBuilder extends ServicePriority { diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/RunnableTaskBuilder.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/RunnableTaskBuilder.java index aeac3df7d..610c12f3f 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/RunnableTaskBuilder.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/RunnableTaskBuilder.java @@ -16,7 +16,7 @@ package cloud.openworkflow.sdk.impl.executors; import cloud.openworkflow.sdk.api.types.RunTaskConfiguration; -import cloud.openworkflow.sdk.impl.ServicePriority; +import cloud.openworkflow.sdk.common.ServicePriority; import cloud.openworkflow.sdk.impl.WorkflowDefinition; public interface RunnableTaskBuilder diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/TaskExecutorFactory.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/TaskExecutorFactory.java index 96ec5c026..81599cb0b 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/TaskExecutorFactory.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/TaskExecutorFactory.java @@ -17,7 +17,7 @@ import cloud.openworkflow.sdk.api.types.Task; import cloud.openworkflow.sdk.api.types.TaskBase; -import cloud.openworkflow.sdk.impl.ServicePriority; +import cloud.openworkflow.sdk.common.ServicePriority; import cloud.openworkflow.sdk.impl.WorkflowDefinition; import cloud.openworkflow.sdk.impl.WorkflowMutablePosition; diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/http/CallableTaskHttpExecutorBuilder.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/http/CallableTaskHttpExecutorBuilder.java index 23ecef9ae..239e8febf 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/http/CallableTaskHttpExecutorBuilder.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/http/CallableTaskHttpExecutorBuilder.java @@ -22,6 +22,7 @@ import cloud.openworkflow.sdk.api.types.HTTPArguments; import cloud.openworkflow.sdk.api.types.TaskBase; import cloud.openworkflow.sdk.impl.WorkflowDefinition; +import cloud.openworkflow.sdk.impl.WorkflowModel; import cloud.openworkflow.sdk.impl.WorkflowMutablePosition; import cloud.openworkflow.sdk.impl.executors.CallableTaskBuilder; import cloud.openworkflow.sdk.impl.executors.CallableTaskFactory; @@ -35,8 +36,13 @@ public CallableTaskFactory init( CallHTTP task, WorkflowDefinition definition, WorkflowMutablePosition position) { final HTTPArguments httpArgs = task.getWith(); + final Endpoint endpoint = httpArgs.getEndpoint(); WorkflowHttpRequestInfoBuilderFactory builder = - WorkflowHttpRequestInfoBuilderFactory.builder(definition) + WorkflowHttpRequestInfoBuilderFactory.builder( + definition, + endpoint.getEndpointConfiguration() != null + ? endpoint.getEndpointConfiguration().getAuthentication() + : null) .withBody(httpArgs.getBody()) .withMethod(httpArgs.getMethod().toUpperCase()) .redirect(httpArgs.isRedirect()); @@ -58,10 +64,6 @@ public CallableTaskFactory init( ? httpArgs.getQuery().getHTTPQuery().getAdditionalProperties() : null)); } - final Endpoint endpoint = httpArgs.getEndpoint(); - if (endpoint.getEndpointConfiguration() != null) { - builder.withAuth(endpoint.getEndpointConfiguration().getAuthentication()); - } return () -> new HttpExecutor( builder, @@ -69,7 +71,7 @@ public CallableTaskFactory init( buildOutputFunction(httpArgs)); } - private WorkflowHttpHelper.WorkflowHttpOutputFunction buildOutputFunction( + private WorkflowHttpHelper.WorkflowHttpOutputFunction buildOutputFunction( HTTPArguments httpArgs) { return switch (httpArgs.getOutput()) { case null -> WorkflowHttpHelper.contentFunction; diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/http/HttpExecutor.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/http/HttpExecutor.java index 140a27654..9ed4bbe9e 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/http/HttpExecutor.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/http/HttpExecutor.java @@ -29,12 +29,12 @@ public class HttpExecutor implements CallableTask { private final WorkflowHttpRequestInfoBuilderFactory builder; private final WorkflowValueResolver uriSupplier; - WorkflowHttpHelper.WorkflowHttpOutputFunction outputFunction; + WorkflowHttpHelper.WorkflowHttpOutputFunction outputFunction; public HttpExecutor( WorkflowHttpRequestInfoBuilderFactory builder, WorkflowValueResolver uriSupplier, - WorkflowHttpHelper.WorkflowHttpOutputFunction outputFunction) { + WorkflowHttpHelper.WorkflowHttpOutputFunction outputFunction) { this.builder = builder; this.uriSupplier = uriSupplier; this.outputFunction = outputFunction; @@ -43,9 +43,10 @@ public HttpExecutor( public CompletableFuture apply( WorkflowContext workflow, TaskContext taskContext, WorkflowModel input) { return WorkflowHttpHelper.executeRequest( - builder - .build(workflow, taskContext, input) - .build(uriSupplier.apply(workflow, taskContext, input)), + builder.build(workflow, taskContext, input), + builder.auth(), + uriSupplier.apply(workflow, taskContext, input), + workflow.definition().application(), workflow, taskContext, outputFunction); 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..50a497abd 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 @@ -16,143 +16,74 @@ package cloud.openworkflow.sdk.impl.executors.openapi; import cloud.openworkflow.sdk.api.types.ExternalResource; +import cloud.openworkflow.sdk.http.WorkflowHttpRequestInfo.Builder; import cloud.openworkflow.sdk.impl.TaskContext; import cloud.openworkflow.sdk.impl.WorkflowApplication; import cloud.openworkflow.sdk.impl.WorkflowContext; +import cloud.openworkflow.sdk.impl.WorkflowDefinition; import cloud.openworkflow.sdk.impl.WorkflowModel; +import cloud.openworkflow.sdk.impl.WorkflowValueResolver; +import cloud.openworkflow.sdk.impl.auth.AuthProvider; import cloud.openworkflow.sdk.impl.executors.CallableTask; import cloud.openworkflow.sdk.impl.http.WorkflowHttpHelper; -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 cloud.openworkflow.sdk.openapi.OpenAPIClient; +import cloud.openworkflow.sdk.openapi.UnifiedOpenAPIReader; import java.util.Map; -import java.util.Set; import java.util.concurrent.CompletableFuture; class OpenAPIExecutor implements CallableTask { - private final OpenAPIProcessor processor; + private final String operationId; private final ExternalResource resource; - private final Map parameters; - private final WorkflowHttpRequestInfoBuilderFactory builder; + private final WorkflowValueResolver> parameters; private final UnifiedOpenAPIReader openAPIReader; + private AuthProvider authProvider; + private boolean redirect; OpenAPIExecutor( UnifiedOpenAPIReader openAPIReader, - OpenAPIProcessor processor, + String operationId, ExternalResource resource, - Map parameters, - WorkflowHttpRequestInfoBuilderFactory builder) { + WorkflowValueResolver> parameters, + AuthProvider auth, + boolean redirect) { this.openAPIReader = openAPIReader; - this.processor = processor; + this.operationId = operationId; this.resource = resource; this.parameters = parameters; - this.builder = builder; + this.authProvider = auth; + this.redirect = redirect; } @Override public CompletableFuture apply( WorkflowContext workflowContext, TaskContext taskContext, WorkflowModel input) { - return workflowContext - .definition() + WorkflowDefinition definition = workflowContext.definition(); + WorkflowApplication app = definition.application(); + return definition .resourceLoader() .load(resource, openAPIReader::read, workflowContext, taskContext, input) - .thenApply(u -> processor.parse(u)) - .thenComposeAsync( - operationDefinition -> { - fillHttpBuilder(workflowContext.definition().application(), operationDefinition); - Builder httpInfoBuilder = builder.build(workflowContext, taskContext, input); - Iterator iter = operationDefinition.getServers().iterator(); - - if (!iter.hasNext()) { - throw new IllegalArgumentException( - "List of servers is empty for schema " + resource.getName()); - } - CompletableFuture future = - WorkflowHttpHelper.executeRequest( - httpInfoBuilder.build(URI.create(iter.next())), workflowContext, taskContext); - while (iter.hasNext()) { - final String uri = iter.next(); - future = - future.exceptionallyCompose(i -> - WorkflowHttpHelper.executeRequest( - httpInfoBuilder.build(URI.create(uri)), workflowContext, taskContext)); - } - return future; - }, - 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); - } - builder - .withBody(hasBody || !bodyParameters.isEmpty() ? bodyParameters : null) - .withQueryMap(!queryMap.isEmpty() ? queryMap : null) - .withHeaders(!headers.isEmpty() ? headers : null) - .withMethod(operation.getMethod()) - .withPath( - new OperationPathResolver( - operation.getPath(), application, pathParameters, mandatoryParameters)); + .thenApply(u -> + new OpenAPIClient( + u, operationId, app.modelFactory()::from, app.templateResolver())) + .thenCompose(client -> execute(client, workflowContext, taskContext, input)); } - 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); - } - } + private CompletableFuture execute( + OpenAPIClient openApiClient, + WorkflowContext workflowContext, + TaskContext taskContext, + WorkflowModel input) { + Map resolvedParameters = + parameters != null ? parameters.apply(workflowContext, taskContext, input) : Map.of(); + Builder httpInfo = openApiClient.createRequest(resolvedParameters); + return WorkflowHttpHelper.executeRequest( + httpInfo.redirect(redirect), + authProvider, + openApiClient.servers(null).get(0), + workflowContext.definition().application(), + workflowContext, + taskContext, + WorkflowHttpHelper.contentFunction); } } 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..9fe32734c 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 @@ -22,9 +22,11 @@ import cloud.openworkflow.sdk.impl.WorkflowApplication; import cloud.openworkflow.sdk.impl.WorkflowDefinition; import cloud.openworkflow.sdk.impl.WorkflowMutablePosition; +import cloud.openworkflow.sdk.impl.WorkflowUtils; +import cloud.openworkflow.sdk.impl.WorkflowValueResolver; import cloud.openworkflow.sdk.impl.executors.CallableTaskBuilder; import cloud.openworkflow.sdk.impl.executors.CallableTaskFactory; -import cloud.openworkflow.sdk.impl.http.WorkflowHttpRequestInfoBuilderFactory; +import cloud.openworkflow.sdk.openapi.UnifiedOpenAPIReader; import java.util.Map; public class OpenAPIExecutorBuilder implements CallableTaskBuilder { @@ -38,18 +40,21 @@ public boolean accept(Class clazz) { public CallableTaskFactory init( CallOpenAPI task, WorkflowDefinition definition, WorkflowMutablePosition position) { OpenAPIArguments with = task.getWith(); - OpenAPIProcessor processor = new OpenAPIProcessor(with.getOperationId()); ExternalResource resource = with.getDocument(); - Map parameters = + WorkflowValueResolver> parameters = with.getParameters() != null && with.getParameters().getAdditionalProperties() != null - ? with.getParameters().getAdditionalProperties() - : Map.of(); - WorkflowHttpRequestInfoBuilderFactory builder = - WorkflowHttpRequestInfoBuilderFactory.builder(definition) - .withAuth(with.getAuthentication()) - .redirect(with.isRedirect()); + ? WorkflowUtils.buildMapResolver( + definition.application(), with.getParameters().getAdditionalProperties()) + : null; UnifiedOpenAPIReader reader = reader(definition.application()); - return () -> new OpenAPIExecutor(reader, processor, resource, parameters, builder); + return () -> + new OpenAPIExecutor( + reader, + with.getOperationId(), + resource, + parameters, + WorkflowUtils.buildAuthProvider(definition, with.getAuthentication()), + with.isRedirect()); } private UnifiedOpenAPIReader reader(WorkflowApplication app) { diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OperationPathResolver.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OperationPathResolver.java deleted file mode 100644 index 1cddfbdcb..000000000 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/OperationPathResolver.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * 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.impl.TaskContext; -import cloud.openworkflow.sdk.impl.WorkflowApplication; -import cloud.openworkflow.sdk.impl.WorkflowContext; -import cloud.openworkflow.sdk.impl.WorkflowModel; -import cloud.openworkflow.sdk.impl.WorkflowUtils; -import cloud.openworkflow.sdk.impl.WorkflowValueResolver; -import java.net.URI; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -class OperationPathResolver implements WorkflowValueResolver { - private final String path; - private final WorkflowValueResolver> asMap; - private final WorkflowApplication app; - private final Set mandatoryParameters; - - OperationPathResolver( - String path, - WorkflowApplication application, - Map args, - Set mandatoryParameters) { - this.path = path; - this.app = application; - this.asMap = WorkflowUtils.buildMapResolver(application, args); - this.mandatoryParameters = mandatoryParameters; - } - - @Override - public URI apply(WorkflowContext workflow, TaskContext task, WorkflowModel model) { - Map map = asMap.apply(workflow, task, model); - List nullKeys = - map.entrySet().stream() - .filter(e -> e.getValue() == null && mandatoryParameters.contains(e.getKey())) - .map(Entry::getKey) - .toList(); - if (!nullKeys.isEmpty()) { - throw new IllegalArgumentException( - "Following mandatory OpenAPI path parameters has null values after expression resolution " - + nullKeys); - } - return app.templateResolver().resolveTemplates(path, map); - } -} diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultHttpBodyConverter.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultHttpBodyConverter.java new file mode 100644 index 000000000..9edf77fea --- /dev/null +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultHttpBodyConverter.java @@ -0,0 +1,106 @@ +/* + * 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.WorkflowHttpBodyConverter; +import cloud.openworkflow.sdk.http.WorkflowHttpHeaders; +import cloud.openworkflow.sdk.http.WorkflowHttpRequestEncoding; +import cloud.openworkflow.sdk.http.WorkflowHttpRequestInfo; +import cloud.openworkflow.sdk.impl.WorkflowModel; +import cloud.openworkflow.sdk.impl.WorkflowModelFactory; +import java.net.http.HttpClient.Version; +import java.net.http.HttpRequest; +import java.net.http.HttpRequest.BodyPublisher; +import java.net.http.HttpResponse; +import java.util.*; +import java.util.stream.Collectors; + +public class DefaultHttpBodyConverter + implements WorkflowHttpBodyConverter, WorkflowModel> { + private final WorkflowModelFactory modelFactory; + + public DefaultHttpBodyConverter(WorkflowModelFactory factory) { + modelFactory = factory; + } + + @Override + public BodyPublisher request(WorkflowHttpRequestInfo httpInfo) { + WorkflowModel body = httpInfo.body(); + String contentType = httpInfo.contentType().orElse(WorkflowHttpHeaders.APPLICATION_JSON_TYPE); + if (body == null || body.isNull()) { + return HttpRequest.BodyPublishers.noBody(); + } else if (WorkflowHttpHeaders.isURLEncodedDataType(contentType)) { + return HttpRequest.BodyPublishers.ofString( + WorkflowHttpRequestEncoding.encodeMap( + WorkflowHttpHelper.requireMap(body, contentType), + WorkflowHttpRequestEncoding::encodeForm)); + } else if (WorkflowHttpHeaders.isJsonMediaType(contentType)) { + return HttpRequest.BodyPublishers.ofByteArray( + body.asJson() + .orElseThrow(() -> + new IllegalStateException( + "Underlying model needs to support conversion to Json in order to use application-json content type"))); + } else if (WorkflowHttpHeaders.isTextMediaType(contentType)) { + return HttpRequest.BodyPublishers.ofString( + WorkflowHttpHelper.requireString(body, contentType), + WorkflowHttpHeaders.charset(contentType)); + } else { + return HttpRequest.BodyPublishers.ofByteArray( + WorkflowHttpHelper.requireBinary(body, contentType)); + } + } + + @Override + public WorkflowModel response(HttpResponse response) { + byte[] body = response.body(); + return body == null || response.body().length == 0 + ? modelFactory.fromNull() + : responseContentType(response) + .map(c -> { + if (isJsonMediaType(c)) { + return modelFactory.fromJson(body); + } else if (isTextMediaType(c)) { + return modelFactory.from(new String(body, WorkflowHttpHeaders.charset(c))); + } else { + return modelFactory.fromBinary(body); + } + }) + .orElseGet(() -> inferContentType(body)); + } + + protected boolean isJsonMediaType(String contentType) { + return WorkflowHttpHeaders.isJsonMediaType(contentType); + } + + protected boolean isTextMediaType(String contentType) { + return WorkflowHttpHeaders.isTextMediaType(contentType); + } + + private Optional responseContentType(HttpResponse response) { + 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(byte[] body) { + return WorkflowResponseSniffer.asString(body) + .map(c -> modelFactory.from(c)) + .orElseGet(() -> modelFactory.fromBinary(body)); + } +} 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 deleted file mode 100644 index 7010fae0f..000000000 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultHttpRequest.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * 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.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; - - public DefaultHttpRequest( - WorkflowApplication app, HttpClient client, WorkflowHttpRequestInfo httpInfo) { - this.httpInfo = httpInfo; - this.client = 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())) - .exceptionallyCompose( - ex -> CompletableFuture.failedFuture(WorkflowHttpHelper.fromError(ex, taskContext))) - .thenApply(response -> new DefaultHttpResponse(app, response)); - } - - protected BodyPublisher buildBody() { - WorkflowModel body = httpInfo.body(); - String contentType = httpInfo.contentType(); - if (body == null || body.isNull()) { - return HttpRequest.BodyPublishers.noBody(); - } else if (WorkflowHttpContentType.isURLEncodedDataType(contentType)) { - return HttpRequest.BodyPublishers.ofString( - encodeMap( - WorkflowHttpHelper.requireMap(body, contentType), DefaultHttpRequest::encodeForm)); - } else if (isJson(contentType)) { - return HttpRequest.BodyPublishers.ofByteArray( - body.asJson() - .orElseThrow(() -> - new IllegalStateException( - "Underlying model needs to support conversion to Json in order to use application-json content type"))); - } else if (isText(contentType)) { - return HttpRequest.BodyPublishers.ofString( - WorkflowHttpHelper.requireString(body, contentType), - WorkflowHttpContentType.charset(contentType)); - } else { - return HttpRequest.BodyPublishers.ofByteArray( - WorkflowHttpHelper.requireBinary(body, contentType)); - } - } - - /* - * User might override this to change which is considered a json media type - */ - protected boolean isJson(String contentType) { - return WorkflowHttpContentType.isJsonMediaType(contentType); - } - - /* - * User might override this to change which is considered a text media type - */ - 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); - } - - private static String encodeQuery(Object part) { - return encodeForm(part).replace("+", "%20"); - } -} 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 deleted file mode 100644 index 3aae6047b..000000000 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultHttpResponse.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * 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.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; - - 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; - } -} diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultHttpTransportFactory.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultHttpTransportFactory.java new file mode 100644 index 000000000..ca31b9556 --- /dev/null +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/DefaultHttpTransportFactory.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.impl.http; + +import cloud.openworkflow.sdk.http.JdkHttpTransport; +import cloud.openworkflow.sdk.http.WorkflowHttpBodyConverter; +import cloud.openworkflow.sdk.http.WorkflowHttpTransport; +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.http.HttpClient; +import java.net.http.HttpClient.Redirect; +import java.net.http.HttpRequest.BodyPublisher; +import java.net.http.HttpResponse; + +public class DefaultHttpTransportFactory implements WorkflowHttpTransportFactory { + + private HttpClient client; + private WorkflowHttpBodyConverter, WorkflowModel> converter; + + @Override + public WorkflowHttpTransport transport( + WorkflowContext workflowContext, TaskContext taskContext) { + return new JdkHttpTransport(client, converter); + } + + @Override + public void init(WorkflowApplication app) { + client = + HttpClient.newBuilder() + .executor(app.executorService()) + .followRedirects(Redirect.NORMAL) + .build(); + converter = new DefaultHttpBodyConverter(app.modelFactory()); + } + + @Override + public void close() { + client.close(); + } +} 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..42bfefc6a 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 @@ -15,6 +15,9 @@ */ package cloud.openworkflow.sdk.impl.http; +import cloud.openworkflow.sdk.http.WorkflowHttpRequestInfo; +import cloud.openworkflow.sdk.http.WorkflowHttpResponse; +import cloud.openworkflow.sdk.http.WorkflowHttpResponses; import cloud.openworkflow.sdk.impl.TaskContext; import cloud.openworkflow.sdk.impl.WorkflowApplication; import cloud.openworkflow.sdk.impl.WorkflowContext; @@ -24,104 +27,142 @@ 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.URI; 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; import java.util.concurrent.TimeoutException; -import java.util.function.BiConsumer; 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"; private static final String STATUS = "statusCode"; - public static interface WorkflowHttpOutputFunction { - WorkflowModel apply( - WorkflowHttpResponse response, - WorkflowHttpRequestInfo requestInfo, + public static interface WorkflowHttpOutputFunction { + T apply( + WorkflowHttpResponse response, + WorkflowHttpRequestInfo requestInfo, WorkflowApplication application, TaskContext taskContext); } - public static final WorkflowHttpOutputFunction contentFunction = + public static final WorkflowHttpOutputFunction> + identityFunction = (response, requestInfo, app, taskContext) -> response; + + public static final WorkflowHttpOutputFunction contentFunction = + (response, requestInfo, app, taskContext) -> { + validateStatus(taskContext, requestInfo, response); + return response.bodyAsObject(); + }; + + public static final WorkflowHttpOutputFunction byteValidationFunction = (response, requestInfo, app, taskContext) -> { validateStatus(taskContext, requestInfo, response); - return response.contentAsModel(); + return response.body(); }; - public static final WorkflowHttpOutputFunction responseFunction = + public static final WorkflowHttpOutputFunction responseFunction = (response, requestInfo, app, taskContext) -> responseAsModel(response, app); - public static final WorkflowHttpOutputFunction rawFunction = + public static final WorkflowHttpOutputFunction rawFunction = (response, requestInfo, app, taskContext) -> - app.modelFactory().fromBinary(response.responseAsByteArray()); + app.modelFactory().fromBinary(WorkflowHttpResponses.responseAsByteArray(response)); - public static CompletableFuture executeRequest( - WorkflowHttpRequestInfo requestInfo, WorkflowContext workflow, TaskContext taskContext) { - return executeRequest(requestInfo, workflow, taskContext, contentFunction); + public static CompletableFuture> executeRequest( + WorkflowHttpRequestInfo requestInfo, + WorkflowApplication app, + WorkflowContext workflow, + TaskContext taskContext) { + return executeRequest(requestInfo, app, workflow, taskContext, identityFunction); } - public static CompletableFuture executeRequest( - WorkflowHttpRequestInfo requestInfo, + public static CompletableFuture> executeRequest( + WorkflowHttpRequestInfo.Builder requestInfo, + AuthProvider auth, + URI uri, + WorkflowApplication app, WorkflowContext workflow, - TaskContext taskContext, - WorkflowHttpOutputFunction function) { - WorkflowApplication app = workflow.definition().application(); - return asWorkflowHtppResponse(requestInfo, app, workflow, taskContext) - .thenApply(response -> { - try (response) { - return function.apply(response, requestInfo, app, taskContext); - } catch (Exception ex) { - throw fromError(ex, taskContext); - } - }); + TaskContext taskContext) { + return executeRequest(requestInfo, auth, uri, app, workflow, taskContext, identityFunction); } - public static CompletableFuture executeRequest( - WorkflowHttpRequestInfo requestInfo, + public static CompletableFuture executeRequest( + WorkflowHttpRequestInfo requestInfo, WorkflowApplication app, WorkflowContext workflow, - TaskContext taskContext) { - return asWorkflowHtppResponse(requestInfo, app, workflow, taskContext) - .thenApply(response -> { - try (response) { - validateStatus(taskContext, requestInfo, response); - return response.contentAsByteArray(); - } - }); + TaskContext taskContext, + WorkflowHttpOutputFunction function) { + return asWorkflowHtppResponse(requestInfo, app, workflow, taskContext, function); } - public static CompletableFuture asWorkflowHtppResponse( - WorkflowHttpRequestInfo requestInfo, + public static CompletableFuture executeRequest( + WorkflowHttpRequestInfo.Builder requestInfo, + AuthProvider auth, + URI uri, WorkflowApplication app, WorkflowContext workflow, - TaskContext taskContext) { - return app.httpRequestFactory().request(app, requestInfo).invoke(workflow, taskContext); + TaskContext taskContext, + WorkflowHttpOutputFunction function) { + return asWorkflowHtppResponse(requestInfo, auth, uri, app, workflow, taskContext, function) + .exceptionallyCompose(e -> CompletableFuture.failedFuture(fromError(e, taskContext))); + } + + private static CompletableFuture asWorkflowHtppResponse( + WorkflowHttpRequestInfo.Builder requestInfo, + AuthProvider auth, + URI uri, + WorkflowApplication app, + WorkflowContext workflowContext, + TaskContext taskContext, + WorkflowHttpOutputFunction function) { + + if (auth != null) { + String scheme = auth.scheme(); + return auth.content(workflowContext, taskContext, uri, requestInfo.method()) + .thenAccept(parameter -> { + if (taskContext != null) { + taskContext.authorization(scheme, parameter); + } + requestInfo.header( + AuthUtils.AUTH_HEADER_NAME, AuthUtils.authHeaderValue(scheme, parameter)); + }) + .thenCompose(__ -> + asWorkflowHtppResponse( + requestInfo.build(uri), app, workflowContext, taskContext, function)); + } else { + return asWorkflowHtppResponse( + requestInfo.build(uri), app, workflowContext, taskContext, function); + } + } + + private static CompletableFuture asWorkflowHtppResponse( + WorkflowHttpRequestInfo requestInfo, + WorkflowApplication app, + WorkflowContext workflowContext, + TaskContext taskContext, + WorkflowHttpOutputFunction function) { + return app.transportFactory() + .transport(workflowContext, taskContext) + .execute(requestInfo) + .thenApply(v -> function.apply(v, requestInfo, app, taskContext)) + .exceptionallyCompose(ex -> CompletableFuture.failedFuture(fromError(ex, taskContext))); } 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 + if (cause instanceof WorkflowException wfe) { + return wfe; + } else if (cause instanceof TimeoutException || cause instanceof SocketTimeoutException || cause instanceof HttpTimeoutException) { statusCode = Errors.TIMEOUT.status(); break; - } else if (cause instanceof WorkflowException wfe) { - return wfe; } cause = cause.getCause(); } while (cause != null); @@ -129,7 +170,9 @@ public static WorkflowException fromError(Throwable ex, TaskContext task) { } private static void validateStatus( - TaskContext task, WorkflowHttpRequestInfo requestInfo, WorkflowHttpResponse response) { + TaskContext task, + WorkflowHttpRequestInfo requestInfo, + WorkflowHttpResponse response) { int status = response.status(); if (!isSuccessful(status) && (!requestInfo.redirect() || !isRedirection(status))) { throw new WorkflowException( @@ -140,16 +183,6 @@ private static void validateStatus( } } - public static CompletableFuture processAuth( - WorkflowHttpRequestInfo requestInfo, - BiConsumer headerFiller, - WorkflowContext workflow, - TaskContext task) { - return requestInfo.auth() != null - ? addAuthHeader(requestInfo.auth(), requestInfo, headerFiller, workflow, task) - : CompletableFuture.completedFuture(null); - } - public static String requireString(WorkflowModel model, String contentType) { return model .asText() @@ -174,68 +207,14 @@ public static Map requireMap(WorkflowModel model, String content "Workflow model should support asMap for content type " + contentType)); } - 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); - } - } - - private static CompletableFuture addAuthHeader( - AuthProvider auth, - WorkflowHttpRequestInfo info, - BiConsumer headerFiller, - WorkflowContext workflow, - TaskContext task) { - String scheme = auth.scheme(); - return auth.content(workflow, task, info.uri(), info.method()) - .thenAccept(parameter -> { - if (task != null) { - task.authorization(scheme, parameter); - } - headerFiller.accept( - AuthUtils.AUTH_HEADER_NAME, AuthUtils.authHeaderValue(scheme, parameter)); - }); - } - - 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) { + WorkflowHttpResponse response, WorkflowApplication application) { return application .modelFactory() .from( Map.of( CONTENT, - response.contentAsModel(), + response.bodyAsObject(), STATUS, response.status(), HEADERS, diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpRequest.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpRequest.java deleted file mode 100644 index 92c9185c1..000000000 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpRequest.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * 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.impl.TaskContext; -import cloud.openworkflow.sdk.impl.WorkflowContext; -import java.util.concurrent.CompletableFuture; - -public interface WorkflowHttpRequest { - - CompletableFuture invoke( - WorkflowContext workflowContext, TaskContext taskContext); -} 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 deleted file mode 100644 index aa17fa634..000000000 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpRequestInfo.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * 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.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); - } - - public String contentType() { - return headers.get(WorkflowHttpContentType.HEADER_NAME) instanceof String str - ? str - : WorkflowHttpContentType.APPLICATION_JSON_TYPE; - } - - public static class Builder { - private final String method; - private boolean redirect; - private Map headers; - private Map queryParams; - private WorkflowModel body; - private AuthProvider auth; - private Long ifModifiedSince; - private URI path; - - public Builder() { - this.method = "GET"; - } - - public Builder(String method) { - this.method = Objects.requireNonNull(method).toUpperCase(); - } - - 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(WorkflowModel body) { - this.body = body; - return this; - } - - public Builder auth(AuthProvider auth) { - this.auth = auth; - return this; - } - - public Builder ifModifiedSince(long millis) { - this.ifModifiedSince = millis; - return this; - } - - public WorkflowHttpRequestInfo build(URI uri) { - 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); - } - } -} 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..b49b57804 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 @@ -16,8 +16,7 @@ package cloud.openworkflow.sdk.impl.http; import cloud.openworkflow.sdk.api.types.ReferenceableAuthenticationPolicy; -import cloud.openworkflow.sdk.api.types.Use; -import cloud.openworkflow.sdk.api.types.UseAuthentications; +import cloud.openworkflow.sdk.http.WorkflowHttpRequestInfo; import cloud.openworkflow.sdk.impl.TaskContext; import cloud.openworkflow.sdk.impl.WorkflowContext; import cloud.openworkflow.sdk.impl.WorkflowDefinition; @@ -26,47 +25,30 @@ import cloud.openworkflow.sdk.impl.WorkflowUtils; import cloud.openworkflow.sdk.impl.WorkflowValueResolver; import cloud.openworkflow.sdk.impl.auth.AuthProvider; -import cloud.openworkflow.sdk.impl.http.WorkflowHttpRequestInfo.Builder; import java.net.URI; import java.util.Map; public class WorkflowHttpRequestInfoBuilderFactory { private final WorkflowDefinition definition; + private final AuthProvider auth; private WorkflowValueResolver pathSupplier; private WorkflowFilter bodyFilter; private String method = "GET"; - private AuthProvider auth; + private boolean redirect; private WorkflowValueResolver> headers; private WorkflowValueResolver> queryMap; - public static WorkflowHttpRequestInfoBuilderFactory builder(WorkflowDefinition definition) { - return new WorkflowHttpRequestInfoBuilderFactory(definition); + public static WorkflowHttpRequestInfoBuilderFactory builder( + WorkflowDefinition definition, ReferenceableAuthenticationPolicy policy) { + return new WorkflowHttpRequestInfoBuilderFactory(definition, policy); } - private WorkflowHttpRequestInfoBuilderFactory(WorkflowDefinition definition) { + private WorkflowHttpRequestInfoBuilderFactory( + WorkflowDefinition definition, ReferenceableAuthenticationPolicy policy) { this.definition = definition; - } - - public WorkflowHttpRequestInfoBuilderFactory withAuth(ReferenceableAuthenticationPolicy policy) { - if (policy != null) { - if (policy.getAuthenticationPolicyReference() != null) { - String name = policy.getAuthenticationPolicyReference().getUse(); - Use use = definition.workflow().getUse(); - UseAuthentications authentications = use == null ? null : use.getAuthentications(); - if (authentications == null - || !authentications.getAdditionalProperties().containsKey(name)) { - throw new IllegalArgumentException( - String.format( - "Authentication '%s' is referenced but not defined in use.authentications.", - name)); - } - } - auth = - definition.application().authProviderFactory().getAuth(definition, policy).orElse(null); - } - return this; + this.auth = WorkflowUtils.buildAuthProvider(definition, policy); } public WorkflowHttpRequestInfoBuilderFactory withBody(Object body) { @@ -106,7 +88,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; } @@ -116,12 +98,14 @@ public WorkflowHttpRequestInfoBuilderFactory redirect(boolean redirect) { return this; } - public WorkflowHttpRequestInfo.Builder build( + public AuthProvider auth() { + return auth; + } + + public WorkflowHttpRequestInfo.Builder build( WorkflowContext workflow, TaskContext taskContext, WorkflowModel input) { - Builder builder = WorkflowHttpRequestInfo.builder(method).redirect(redirect); - if (auth != null) { - builder.auth(auth); - } + WorkflowHttpRequestInfo.Builder builder = + WorkflowHttpRequestInfo.builder(method).redirect(redirect); if (queryMap != null) { builder.queryParams(queryMap.apply(workflow, taskContext, input)); } diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpRequestFactory.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpTransportFactory.java similarity index 61% rename from impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpRequestFactory.java rename to impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpTransportFactory.java index dbe8fa021..d706b8104 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpRequestFactory.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/http/WorkflowHttpTransportFactory.java @@ -15,15 +15,17 @@ */ package cloud.openworkflow.sdk.impl.http; -import cloud.openworkflow.sdk.impl.ServicePriority; +import cloud.openworkflow.sdk.common.ServicePriority; +import cloud.openworkflow.sdk.http.WorkflowHttpTransport; +import cloud.openworkflow.sdk.impl.TaskContext; import cloud.openworkflow.sdk.impl.WorkflowApplication; +import cloud.openworkflow.sdk.impl.WorkflowContext; +import cloud.openworkflow.sdk.impl.WorkflowModel; -public interface WorkflowHttpRequestFactory - extends ServicePriority, AutoCloseable { +public interface WorkflowHttpTransportFactory + extends AutoCloseable, ServicePriority { - WorkflowHttpRequest request(WorkflowApplication app, WorkflowHttpRequestInfo httpInfo); + WorkflowHttpTransport transport(WorkflowContext context, TaskContext taskContext); default void init(WorkflowApplication app) {} - - default void close() {} } diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/lifecycle/WorkflowExecutionCompletableListener.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/lifecycle/WorkflowExecutionCompletableListener.java index 690e49076..ce9d31d95 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/lifecycle/WorkflowExecutionCompletableListener.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/lifecycle/WorkflowExecutionCompletableListener.java @@ -15,7 +15,7 @@ */ package cloud.openworkflow.sdk.impl.lifecycle; -import cloud.openworkflow.sdk.impl.ServicePriority; +import cloud.openworkflow.sdk.common.ServicePriority; import java.util.concurrent.CompletableFuture; public interface WorkflowExecutionCompletableListener diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/lifecycle/WorkflowExecutionListener.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/lifecycle/WorkflowExecutionListener.java index 04b25fdfd..583d8bed0 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/lifecycle/WorkflowExecutionListener.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/lifecycle/WorkflowExecutionListener.java @@ -15,7 +15,7 @@ */ package cloud.openworkflow.sdk.impl.lifecycle; -import cloud.openworkflow.sdk.impl.ServicePriority; +import cloud.openworkflow.sdk.common.ServicePriority; public interface WorkflowExecutionListener extends AutoCloseable, ServicePriority { diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/marshaller/CustomObjectMarshaller.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/marshaller/CustomObjectMarshaller.java index 485e5b1b9..e001e7d44 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/marshaller/CustomObjectMarshaller.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/marshaller/CustomObjectMarshaller.java @@ -15,7 +15,7 @@ */ package cloud.openworkflow.sdk.impl.marshaller; -import cloud.openworkflow.sdk.impl.ServicePriority; +import cloud.openworkflow.sdk.common.ServicePriority; public interface CustomObjectMarshaller extends ServicePriority> { void write(WorkflowOutputBuffer buffer, T object); diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/resources/GitHubHelper.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/resources/GitHubHelper.java index 8719f03fd..527a45349 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/resources/GitHubHelper.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/resources/GitHubHelper.java @@ -15,7 +15,7 @@ */ package cloud.openworkflow.sdk.impl.resources; -import cloud.openworkflow.sdk.impl.http.URIDecodedBuilder; +import cloud.openworkflow.sdk.http.URIDecodedBuilder; import java.net.URI; public class GitHubHelper { diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/resources/HttpResource.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/resources/HttpResource.java index d0e0560c2..039b5ddda 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/resources/HttpResource.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/resources/HttpResource.java @@ -15,12 +15,13 @@ */ package cloud.openworkflow.sdk.impl.resources; +import cloud.openworkflow.sdk.http.WorkflowHttpRequestInfo; 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 cloud.openworkflow.sdk.impl.auth.AuthProvider; import cloud.openworkflow.sdk.impl.http.WorkflowHttpHelper; -import cloud.openworkflow.sdk.impl.http.WorkflowHttpRequestInfo; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; @@ -45,10 +46,13 @@ public HttpResource(WorkflowApplication application, URI url, AuthProvider auth) @Override public CompletableFuture load(WorkflowContext workflowContext, TaskContext taskContext) { return WorkflowHttpHelper.executeRequest( - WorkflowHttpRequestInfo.builder("GET").auth(auth).build(url), + WorkflowHttpRequestInfo.builder("GET"), + auth, + url, application, workflowContext, - taskContext); + taskContext, + WorkflowHttpHelper.byteValidationFunction); } public String name() { @@ -66,8 +70,10 @@ public String name() { public CompletableFuture shouldReload( Instant lastUpdate, WorkflowContext workflowContext, TaskContext taskContext) { final long millis = lastUpdate.toEpochMilli(); - return WorkflowHttpHelper.asWorkflowHtppResponse( - WorkflowHttpRequestInfo.builder("HEAD").ifModifiedSince(millis).auth(auth).build(url), + return WorkflowHttpHelper.executeRequest( + WorkflowHttpRequestInfo.builder("HEAD").ifModifiedSince(millis), + auth, + url, application, workflowContext, taskContext) diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/scheduler/CronResolverFactory.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/scheduler/CronResolverFactory.java index fcb71b156..acced2436 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/scheduler/CronResolverFactory.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/scheduler/CronResolverFactory.java @@ -15,7 +15,7 @@ */ package cloud.openworkflow.sdk.impl.scheduler; -import cloud.openworkflow.sdk.impl.ServicePriority; +import cloud.openworkflow.sdk.common.ServicePriority; public interface CronResolverFactory extends ServicePriority { CronResolver parseCron(String cron); diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/schema/SchemaValidatorFactory.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/schema/SchemaValidatorFactory.java index 05b9bf923..a80b2760e 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/schema/SchemaValidatorFactory.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/schema/SchemaValidatorFactory.java @@ -16,7 +16,7 @@ package cloud.openworkflow.sdk.impl.schema; import cloud.openworkflow.sdk.api.types.SchemaInline; -import cloud.openworkflow.sdk.impl.ServicePriority; +import cloud.openworkflow.sdk.common.ServicePriority; public interface SchemaValidatorFactory extends ServicePriority { SchemaValidator getValidator(SchemaInline inline); diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/scripts/ScriptRunner.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/scripts/ScriptRunner.java index dac12db21..17a1a152f 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/scripts/ScriptRunner.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/scripts/ScriptRunner.java @@ -15,7 +15,7 @@ */ package cloud.openworkflow.sdk.impl.scripts; -import cloud.openworkflow.sdk.impl.ServicePriority; +import cloud.openworkflow.sdk.common.ServicePriority; import cloud.openworkflow.sdk.impl.TaskContext; import cloud.openworkflow.sdk.impl.WorkflowContext; import cloud.openworkflow.sdk.impl.WorkflowModel; diff --git a/impl/core/src/test/java/cloud/openworkflow/sdk/impl/WorkflowAdditionalObjectTest.java b/impl/core/src/test/java/cloud/openworkflow/sdk/impl/WorkflowAdditionalObjectTest.java index b5360f512..2e0d95f92 100644 --- a/impl/core/src/test/java/cloud/openworkflow/sdk/impl/WorkflowAdditionalObjectTest.java +++ b/impl/core/src/test/java/cloud/openworkflow/sdk/impl/WorkflowAdditionalObjectTest.java @@ -19,12 +19,13 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import cloud.openworkflow.sdk.common.ServicePriority; import cloud.openworkflow.sdk.impl.additional.WorkflowAdditionalObject; import cloud.openworkflow.sdk.impl.lifecycle.WorkflowExecutionCompletableListener; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import java.util.function.Supplier; +import java.util.function.Function; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -48,9 +49,10 @@ public Integer apply(WorkflowContextData workflowContext, TaskContextData taskCo } } - private class DummyAdditionalObjectSupplier implements Supplier> { + private class DummyAdditionalObjectSupplier + implements Function> { @Override - public List get() { + public List apply(WorkflowApplication app) { return List.of(mediumPrio, lowestPrio, topPrio); } } @@ -95,7 +97,7 @@ void testAdditionalObjectSupplierNull() { try (WorkflowApplication appl = WorkflowApplication.builder() .withModelFactory(modelFactory) - .withAdditionalObject(key, () -> null) + .withAdditionalObject(key, app -> null) .build()) { assertThat(appl.additionalObject(key)).isEmpty(); } diff --git a/impl/core/src/test/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIProcessorTest.java b/impl/core/src/test/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIProcessorTest.java index 24c0f4b65..b87716740 100644 --- a/impl/core/src/test/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIProcessorTest.java +++ b/impl/core/src/test/java/cloud/openworkflow/sdk/impl/executors/openapi/OpenAPIProcessorTest.java @@ -20,6 +20,11 @@ import cloud.openworkflow.sdk.impl.resources.ClasspathResource; import cloud.openworkflow.sdk.impl.resources.ExternalResourceHandler; +import cloud.openworkflow.sdk.openapi.OpenAPIProcessor; +import cloud.openworkflow.sdk.openapi.OperationDefinition; +import cloud.openworkflow.sdk.openapi.ParameterDefinition; +import cloud.openworkflow.sdk.openapi.UnifiedOpenAPI; +import cloud.openworkflow.sdk.openapi.UnifiedOpenAPIReader; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; 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/http-jackson/pom.xml b/impl/http-jackson/pom.xml index e0c7d5467..778dfc5b6 100644 --- a/impl/http-jackson/pom.xml +++ b/impl/http-jackson/pom.xml @@ -7,13 +7,13 @@ 8.0.0-SNAPSHOT - openworkflow-impl-http-jackson - Open Workflow :: Impl :: Http :: Jackson + openworkflow-impl-http-jakarta-jackson + Open Workflow :: Impl :: Http :: Jakarta:: Jackson cloud.openworkflow.sdk - openworkflow-impl-http + openworkflow-impl-http-jakarta cloud.openworkflow.sdk diff --git a/impl/http-jackson/src/main/java/cloud/openworkflow/sdk/impl/executors/http/jackson/JacksonModelConverterFactory.java b/impl/http-jackson/src/main/java/cloud/openworkflow/sdk/impl/executors/http/jackson/JacksonModelConverterFactory.java index ccc69b8c0..94dacdd54 100644 --- a/impl/http-jackson/src/main/java/cloud/openworkflow/sdk/impl/executors/http/jackson/JacksonModelConverterFactory.java +++ b/impl/http-jackson/src/main/java/cloud/openworkflow/sdk/impl/executors/http/jackson/JacksonModelConverterFactory.java @@ -15,33 +15,33 @@ */ package cloud.openworkflow.sdk.impl.executors.http.jackson; +import cloud.openworkflow.sdk.http.WorkflowHttpBodyConverter; +import cloud.openworkflow.sdk.impl.WorkflowApplication; +import cloud.openworkflow.sdk.impl.WorkflowModel; import cloud.openworkflow.sdk.impl.additional.NamedSuppliedAdditionalObject; -import cloud.openworkflow.sdk.impl.jakarta.http.DefaultHttpModelConverter; -import cloud.openworkflow.sdk.impl.jakarta.http.HttpConverterResolver; -import cloud.openworkflow.sdk.impl.jakarta.http.HttpModelConverter; +import cloud.openworkflow.sdk.impl.jakarta.http.JakartaTransportFactory; +import cloud.openworkflow.sdk.impl.jakarta.http.JakartaWorkflowBodyConverter; +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.core.Response; import tools.jackson.databind.JsonNode; public class JacksonModelConverterFactory - implements NamedSuppliedAdditionalObject { - - private static class JacksonModelConverterHolder { - - private static HttpModelConverter converter = - new DefaultHttpModelConverter() { - @Override - public Class jsonResponseType() { - return JsonNode.class; - } - }; - } + implements NamedSuppliedAdditionalObject< + WorkflowHttpBodyConverter, Response, WorkflowModel>> { @Override - public HttpModelConverter get() { - return JacksonModelConverterHolder.converter; + public WorkflowHttpBodyConverter, Response, WorkflowModel> apply( + WorkflowApplication app) { + return new JakartaWorkflowBodyConverter(app.modelFactory()) { + @Override + protected Class jsonResponseType() { + return JsonNode.class; + } + }; } @Override public String name() { - return HttpConverterResolver.HTTP_MODEL_CONVERTER; + return JakartaTransportFactory.HTTP_MODEL_CONVERTER; } } diff --git a/impl/http/pom.xml b/impl/http/pom.xml index c731cc174..1ecd8c0ae 100644 --- a/impl/http/pom.xml +++ b/impl/http/pom.xml @@ -5,9 +5,13 @@ openworkflow-impl 8.0.0-SNAPSHOT - openworkflow-impl-http - Open Workflow :: Impl :: HTTP + openworkflow-impl-http-jakarta + Open Workflow :: Impl :: HTTP:: Jakarta + + 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/HttpConverterResolver.java b/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/HttpConverterResolver.java deleted file mode 100644 index 03e57cc6f..000000000 --- a/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/HttpConverterResolver.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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.impl.TaskContext; -import cloud.openworkflow.sdk.impl.WorkflowApplication; -import cloud.openworkflow.sdk.impl.WorkflowContext; - -public class HttpConverterResolver { - - public static final String HTTP_MODEL_CONVERTER = "httpModelConverter"; - - private static class DefaultHolder { - private static final HttpModelConverter converter = new DefaultHttpModelConverter(); - } - - public static HttpModelConverter converter( - WorkflowApplication app, WorkflowContext workflowContext, TaskContext taskContext) { - return app.additionalObject( - HTTP_MODEL_CONVERTER, workflowContext, taskContext) - .orElseGet(() -> DefaultHolder.converter); - } - - private HttpConverterResolver() {} -} diff --git a/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/HttpModelConverter.java b/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/HttpModelConverter.java deleted file mode 100644 index 4aae5cf8d..000000000 --- a/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/HttpModelConverter.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * 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.impl.WorkflowModel; -import cloud.openworkflow.sdk.impl.WorkflowModelFactory; -import jakarta.ws.rs.client.Entity; -import jakarta.ws.rs.core.MediaType; -import jakarta.ws.rs.core.Response; - -public interface HttpModelConverter { - - WorkflowModel buildModel(WorkflowModelFactory modelFactory, Response entity); - - Entity buildEntity(WorkflowModel body, MediaType type); -} 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 deleted file mode 100644 index 1772699b0..000000000 --- a/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/JakartaHttpRequest.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * 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.impl.TaskContext; -import cloud.openworkflow.sdk.impl.WorkflowApplication; -import cloud.openworkflow.sdk.impl.WorkflowContext; -import cloud.openworkflow.sdk.impl.WorkflowError; -import cloud.openworkflow.sdk.impl.WorkflowException; -import cloud.openworkflow.sdk.impl.http.WorkflowHttpHelper; -import cloud.openworkflow.sdk.impl.http.WorkflowHttpRequest; -import cloud.openworkflow.sdk.impl.http.WorkflowHttpRequestInfo; -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; - -class JakartaHttpRequest implements WorkflowHttpRequest { - - protected final WorkflowHttpRequestInfo requestInfo; - protected final WorkflowApplication application; - private final Client defaultClient; - private final Collection requestDecorators; - - public JakartaHttpRequest( - WorkflowApplication application, - Client defaultClient, - WorkflowHttpRequestInfo requestInfo, - List requestDecorators) { - this.application = application; - this.defaultClient = defaultClient; - this.requestInfo = requestInfo; - this.requestDecorators = requestDecorators; - } - - @Override - public CompletableFuture invoke( - WorkflowContext workflowContext, TaskContext taskContext) { - WebTarget target = - 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)); - } -} diff --git a/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/JakartaRequestExecutorFactory.java b/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/JakartaRequestExecutorFactory.java deleted file mode 100644 index 4d8e7f102..000000000 --- a/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/JakartaRequestExecutorFactory.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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.impl.WorkflowApplication; -import cloud.openworkflow.sdk.impl.http.WorkflowHttpRequest; -import cloud.openworkflow.sdk.impl.http.WorkflowHttpRequestFactory; -import cloud.openworkflow.sdk.impl.http.WorkflowHttpRequestInfo; -import jakarta.ws.rs.client.Client; -import jakarta.ws.rs.client.ClientBuilder; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -public class JakartaRequestExecutorFactory implements WorkflowHttpRequestFactory { - - private static final String HTTP_REQUEST_DECORATOR_KEY = "HttpRequestDecorators"; - - private Client client; - private List requestDecorators; - - public Client client() { - return client; - } - - @Override - public void init(WorkflowApplication app) { - client = ClientBuilder.newBuilder().executorService(app.executorService()).build(); - requestDecorators = new ArrayList<>(app.serviceLoadedClasses(HttpRequestDecorator.class)); - requestDecorators.addAll( - app.>additionalObject(HTTP_REQUEST_DECORATOR_KEY) - .orElse(List.of())); - Collections.sort(requestDecorators); - } - - @Override - public WorkflowHttpRequest request(WorkflowApplication app, WorkflowHttpRequestInfo httpInfo) { - return new JakartaHttpRequest(app, client, httpInfo, requestDecorators); - } - - @Override - public void close() { - client.close(); - } -} diff --git a/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/JakartaTransportFactory.java b/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/JakartaTransportFactory.java new file mode 100644 index 000000000..ae2fd0128 --- /dev/null +++ b/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/JakartaTransportFactory.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.impl.jakarta.http; + +import cloud.openworkflow.sdk.http.WorkflowHttpBodyConverter; +import cloud.openworkflow.sdk.http.WorkflowHttpTransport; +import cloud.openworkflow.sdk.http.jakarta.JakartaHttpRequestDecorator; +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; +import cloud.openworkflow.sdk.impl.WorkflowModel; +import cloud.openworkflow.sdk.impl.http.WorkflowHttpTransportFactory; +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.ClientBuilder; +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +public class JakartaTransportFactory implements WorkflowHttpTransportFactory { + + public static final String HTTP_REQUEST_DECORATOR_KEY = "HttpRequestDecorators"; + public static final String HTTP_MODEL_CONVERTER = "httpModelConverter"; + public static final String HTTP_CLIENT_PROVIDER = "httpClientProvider"; + + private Client client; + private List requestDecorators; + private WorkflowHttpBodyConverter, Response, WorkflowModel> converter; + private WorkflowApplication app; + + public Client client() { + return client; + } + + @Override + public void init(WorkflowApplication app) { + this.app = app; + client = ClientBuilder.newBuilder().executorService(app.executorService()).build(); + converter = + app., Response, WorkflowModel>>additionalObject( + HTTP_MODEL_CONVERTER) + .orElse(new JakartaWorkflowBodyConverter(app.modelFactory())); + requestDecorators = + new ArrayList<>(app.serviceLoadedClasses(JakartaHttpRequestDecorator.class)); + requestDecorators.addAll( + app.>additionalObject(HTTP_REQUEST_DECORATOR_KEY) + .orElse(List.of())); + Collections.sort(requestDecorators); + } + + @Override + public void close() { + client.close(); + } + + @Override + public WorkflowHttpTransport transport( + WorkflowContext workflowContext, TaskContext taskContext) { + return new JakartaHttpTransport( + app.additionalObject(HTTP_CLIENT_PROVIDER, workflowContext, taskContext) + .orElse(client), + converter, + requestDecorators); + } +} diff --git a/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/DefaultHttpModelConverter.java b/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/JakartaWorkflowBodyConverter.java similarity index 78% rename from impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/DefaultHttpModelConverter.java rename to impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/JakartaWorkflowBodyConverter.java index 4cae13ee8..f2be3897f 100644 --- a/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/DefaultHttpModelConverter.java +++ b/impl/http/src/main/java/cloud/openworkflow/sdk/impl/jakarta/http/JakartaWorkflowBodyConverter.java @@ -15,9 +15,8 @@ */ package cloud.openworkflow.sdk.impl.jakarta.http; -import cloud.openworkflow.sdk.impl.WorkflowModel; -import cloud.openworkflow.sdk.impl.WorkflowModelFactory; -import cloud.openworkflow.sdk.impl.http.WorkflowHttpContentType; +import cloud.openworkflow.sdk.http.*; +import cloud.openworkflow.sdk.impl.*; import cloud.openworkflow.sdk.impl.http.WorkflowHttpHelper; import cloud.openworkflow.sdk.impl.http.WorkflowResponseSniffer; import jakarta.ws.rs.client.Entity; @@ -25,10 +24,48 @@ import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; -public class DefaultHttpModelConverter implements HttpModelConverter { +public class JakartaWorkflowBodyConverter + implements WorkflowHttpBodyConverter, Response, WorkflowModel> { + + private final WorkflowModelFactory modelFactory; + + public JakartaWorkflowBodyConverter(WorkflowModelFactory factory) { + modelFactory = factory; + } @Override - public WorkflowModel buildModel(WorkflowModelFactory modelFactory, Response response) { + public Entity request(WorkflowHttpRequestInfo info) { + WorkflowModel model = info.body(); + MediaType contentType = + MediaType.valueOf(info.contentType().orElse(WorkflowHttpHeaders.APPLICATION_JSON_TYPE)); + if (model == null || model.isNull()) { + return null; + } else if (MediaType.APPLICATION_JSON_TYPE.isCompatible(contentType)) { + return Entity.json(model.as(model.objectClass()).orElseThrow()); + } else if (MediaType.APPLICATION_FORM_URLENCODED_TYPE.isCompatible(contentType)) { + Form form = new Form(); + WorkflowHttpHelper.requireMap(model, contentType.toString()) + .forEach((k, v) -> form.param(k, v == null ? "" : v.toString())); + return Entity.form(form); + } else if (MediaType.TEXT_PLAIN_TYPE.isCompatible(contentType) + || MediaType.TEXT_HTML_TYPE.isCompatible(contentType) + || MediaType.APPLICATION_XHTML_XML_TYPE.isCompatible(contentType) + || MediaType.APPLICATION_XML_TYPE.isCompatible(contentType)) { + return Entity.entity( + WorkflowHttpHelper.requireString(model, contentType.toString()), contentType); + } else if (isJsonMediaType(contentType)) { + return Entity.entity(model.as(model.objectClass()).orElseThrow(), contentType); + } else if (isTextMediaType(contentType)) { + return Entity.entity( + WorkflowHttpHelper.requireString(model, contentType.toString()), contentType); + } else { + // assume binary for other content types, e.g. octet-stream, image/png, etc. + return Entity.entity(model.asByteArray().orElseThrow(), contentType); + } + } + + @Override + public WorkflowModel response(Response response) { if (!response.hasEntity()) { return modelFactory.fromNull(); } @@ -56,38 +93,12 @@ protected WorkflowModel inferModel(WorkflowModelFactory modelFactory, Response r .orElse(modelFactory.fromBinary(bytes)); } - @Override - public Entity buildEntity(WorkflowModel model, MediaType contentType) { - if (MediaType.APPLICATION_JSON_TYPE.isCompatible(contentType)) { - return Entity.json(model.as(model.objectClass()).orElseThrow()); - } else if (MediaType.APPLICATION_FORM_URLENCODED_TYPE.isCompatible(contentType)) { - Form form = new Form(); - WorkflowHttpHelper.requireMap(model, contentType.toString()) - .forEach((k, v) -> form.param(k, v == null ? "" : v.toString())); - return Entity.form(form); - } else if (MediaType.TEXT_PLAIN_TYPE.isCompatible(contentType) - || MediaType.TEXT_HTML_TYPE.isCompatible(contentType) - || MediaType.APPLICATION_XHTML_XML_TYPE.isCompatible(contentType) - || MediaType.APPLICATION_XML_TYPE.isCompatible(contentType)) { - return Entity.entity( - WorkflowHttpHelper.requireString(model, contentType.toString()), contentType); - } else if (isJsonMediaType(contentType)) { - return Entity.entity(model.as(model.objectClass()).orElseThrow(), contentType); - } else if (isTextMediaType(contentType)) { - return Entity.entity( - WorkflowHttpHelper.requireString(model, contentType.toString()), contentType); - } else { - // assume binary for other content types, e.g. octet-stream, image/png, etc. - return Entity.entity(model.asByteArray().orElseThrow(), contentType); - } - } - protected boolean isJsonMediaType(MediaType mediaType) { - return WorkflowHttpContentType.isJsonMediaType(mediaType.toString()); + return WorkflowHttpHeaders.isJsonMediaType(mediaType.toString()); } protected boolean isTextMediaType(MediaType mediaType) { - return WorkflowHttpContentType.isTextMediaType(mediaType.toString()); + return WorkflowHttpHeaders.isTextMediaType(mediaType.toString()); } protected Class jsonResponseType() { diff --git a/impl/http/src/main/resources/META-INF/services/cloud.openworkflow.sdk.impl.http.URITemplateResolver b/impl/http/src/main/resources/META-INF/services/cloud.openworkflow.sdk.impl.http.URITemplateResolver deleted file mode 100644 index cf88f096a..000000000 --- a/impl/http/src/main/resources/META-INF/services/cloud.openworkflow.sdk.impl.http.URITemplateResolver +++ /dev/null @@ -1 +0,0 @@ -cloud.openworkflow.sdk.impl.jakarta.template.JaxrsURITemplateResolver \ No newline at end of file diff --git a/impl/http/src/main/resources/META-INF/services/cloud.openworkflow.sdk.impl.http.WorkflowHttpRequestFactory b/impl/http/src/main/resources/META-INF/services/cloud.openworkflow.sdk.impl.http.WorkflowHttpRequestFactory deleted file mode 100644 index 9c18c91aa..000000000 --- a/impl/http/src/main/resources/META-INF/services/cloud.openworkflow.sdk.impl.http.WorkflowHttpRequestFactory +++ /dev/null @@ -1 +0,0 @@ -cloud.openworkflow.sdk.impl.jakarta.http.JakartaRequestExecutorFactory \ No newline at end of file diff --git a/impl/http/src/main/resources/META-INF/services/cloud.openworkflow.sdk.impl.http.WorkflowHttpTransportFactory b/impl/http/src/main/resources/META-INF/services/cloud.openworkflow.sdk.impl.http.WorkflowHttpTransportFactory new file mode 100644 index 000000000..ed7c4d5e8 --- /dev/null +++ b/impl/http/src/main/resources/META-INF/services/cloud.openworkflow.sdk.impl.http.WorkflowHttpTransportFactory @@ -0,0 +1 @@ +cloud.openworkflow.sdk.impl.jakarta.http.JakartaTransportFactory \ No newline at end of file diff --git a/impl/jackson/pom.xml b/impl/jackson/pom.xml index 2a4b286dc..7947944e6 100644 --- a/impl/jackson/pom.xml +++ b/impl/jackson/pom.xml @@ -38,7 +38,7 @@ cloud.openworkflow.sdk - openworkflow-impl-openapi + openworkflow-impl-openapi-jackson \ No newline at end of file diff --git a/impl/json-utils/src/main/java/cloud/openworkflow/sdk/impl/jackson/ObjectMapperFactory.java b/impl/json-utils/src/main/java/cloud/openworkflow/sdk/impl/jackson/ObjectMapperFactory.java index 7aa26c60c..b425167bb 100644 --- a/impl/json-utils/src/main/java/cloud/openworkflow/sdk/impl/jackson/ObjectMapperFactory.java +++ b/impl/json-utils/src/main/java/cloud/openworkflow/sdk/impl/jackson/ObjectMapperFactory.java @@ -15,7 +15,7 @@ */ package cloud.openworkflow.sdk.impl.jackson; -import cloud.openworkflow.sdk.impl.ServicePriority; +import cloud.openworkflow.sdk.common.ServicePriority; import java.util.function.Supplier; import tools.jackson.databind.ObjectMapper; diff --git a/impl/openapi-jackson/pom.xml b/impl/openapi-jackson/pom.xml index 30830539c..ebc5f2668 100644 --- a/impl/openapi-jackson/pom.xml +++ b/impl/openapi-jackson/pom.xml @@ -5,16 +5,19 @@ openworkflow-impl 8.0.0-SNAPSHOT - openworkflow-impl-openapi + openworkflow-impl-openapi-jackson Open Workflow :: Impl :: OpenAPI:: Jackson +cloud.openworkflow.sdkopenworkflow-common-openapi +com.squareup.okhttp3mockwebservertest + cloud.openworkflow.sdk - openworkflow-impl-core + openworkflow-common-openapi-jackson - + cloud.openworkflow.sdk - openworkflow-api + openworkflow-impl-core cloud.openworkflow.sdk diff --git a/impl/openapi-jackson/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/jackson/JacksonUnifiedOpenAPIReaderFactory.java b/impl/openapi-jackson/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/jackson/JacksonUnifiedOpenAPIReaderFactory.java index 91930612f..78515f371 100644 --- a/impl/openapi-jackson/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/jackson/JacksonUnifiedOpenAPIReaderFactory.java +++ b/impl/openapi-jackson/src/main/java/cloud/openworkflow/sdk/impl/executors/openapi/jackson/JacksonUnifiedOpenAPIReaderFactory.java @@ -16,7 +16,8 @@ package cloud.openworkflow.sdk.impl.executors.openapi.jackson; import cloud.openworkflow.sdk.impl.additional.ConstantAdditionalObject; -import cloud.openworkflow.sdk.impl.executors.openapi.UnifiedOpenAPIReader; +import cloud.openworkflow.sdk.openapi.UnifiedOpenAPIReader; +import cloud.openworkflow.sdk.openapi.jackson.JacksonUnifiedOpenAPIReader; public class JacksonUnifiedOpenAPIReaderFactory extends ConstantAdditionalObject { diff --git a/impl/openapi-jackson/src/main/resources/META-INF/native-image/cloud.openworkflow.sdk/openworkflow-impl-openapi/reflect-config.json b/impl/openapi-jackson/src/main/resources/META-INF/native-image/cloud.openworkflow.sdk/openworkflow-impl-openapi/reflect-config.json deleted file mode 100644 index bb5a34c07..000000000 --- a/impl/openapi-jackson/src/main/resources/META-INF/native-image/cloud.openworkflow.sdk/openworkflow-impl-openapi/reflect-config.json +++ /dev/null @@ -1,14 +0,0 @@ -[ -{"name":"cloud.openworkflow.sdk.impl.executors.openapi.UnifiedOpenAPI","queryAllPublicConstructors":true,"queryAllDeclaredConstructors":true,"queryAllPublicMethods":true,"queryAllDeclaredMethods":true,"allPublicConstructors":true,"allDeclaredConstructors":true,"allPublicMethods":true,"allDeclaredMethods":true,"allPublicFields":true,"allDeclaredFields":true,"allPublicClasses":true,"allDeclaredClasses":true}, -{"name":"cloud.openworkflow.sdk.impl.executors.openapi.UnifiedOpenAPI$Components","queryAllPublicConstructors":true,"queryAllDeclaredConstructors":true,"queryAllPublicMethods":true,"queryAllDeclaredMethods":true,"allPublicConstructors":true,"allDeclaredConstructors":true,"allPublicMethods":true,"allDeclaredMethods":true,"allPublicFields":true,"allDeclaredFields":true,"allPublicClasses":true,"allDeclaredClasses":true}, -{"name":"cloud.openworkflow.sdk.impl.executors.openapi.UnifiedOpenAPI$Content","queryAllPublicConstructors":true,"queryAllDeclaredConstructors":true,"queryAllPublicMethods":true,"queryAllDeclaredMethods":true,"allPublicConstructors":true,"allDeclaredConstructors":true,"allPublicMethods":true,"allDeclaredMethods":true,"allPublicFields":true,"allDeclaredFields":true,"allPublicClasses":true,"allDeclaredClasses":true}, -{"name":"cloud.openworkflow.sdk.impl.executors.openapi.UnifiedOpenAPI$HttpOperation","queryAllPublicConstructors":true,"queryAllDeclaredConstructors":true,"queryAllPublicMethods":true,"queryAllDeclaredMethods":true,"allPublicConstructors":true,"allDeclaredConstructors":true,"allPublicMethods":true,"allDeclaredMethods":true,"allPublicFields":true,"allDeclaredFields":true,"allPublicClasses":true,"allDeclaredClasses":true}, -{"name":"cloud.openworkflow.sdk.impl.executors.openapi.UnifiedOpenAPI$MediaType","queryAllPublicConstructors":true,"queryAllDeclaredConstructors":true,"queryAllPublicMethods":true,"queryAllDeclaredMethods":true,"allPublicConstructors":true,"allDeclaredConstructors":true,"allPublicMethods":true,"allDeclaredMethods":true,"allPublicFields":true,"allDeclaredFields":true,"allPublicClasses":true,"allDeclaredClasses":true}, -{"name":"cloud.openworkflow.sdk.impl.executors.openapi.UnifiedOpenAPI$Operation","queryAllPublicConstructors":true,"queryAllDeclaredConstructors":true,"queryAllPublicMethods":true,"queryAllDeclaredMethods":true,"allPublicConstructors":true,"allDeclaredConstructors":true,"allPublicMethods":true,"allDeclaredMethods":true,"allPublicFields":true,"allDeclaredFields":true,"allPublicClasses":true,"allDeclaredClasses":true}, -{"name":"cloud.openworkflow.sdk.impl.executors.openapi.UnifiedOpenAPI$Parameter","queryAllPublicConstructors":true,"queryAllDeclaredConstructors":true,"queryAllPublicMethods":true,"queryAllDeclaredMethods":true,"allPublicConstructors":true,"allDeclaredConstructors":true,"allPublicMethods":true,"allDeclaredMethods":true,"allPublicFields":true,"allDeclaredFields":true,"allPublicClasses":true,"allDeclaredClasses":true}, -{"name":"cloud.openworkflow.sdk.impl.executors.openapi.UnifiedOpenAPI$PathItem","queryAllPublicConstructors":true,"queryAllDeclaredConstructors":true,"queryAllPublicMethods":true,"queryAllDeclaredMethods":true,"allPublicConstructors":true,"allDeclaredConstructors":true,"allPublicMethods":true,"allDeclaredMethods":true,"allPublicFields":true,"allDeclaredFields":true,"allPublicClasses":true,"allDeclaredClasses":true}, -{"name":"cloud.openworkflow.sdk.impl.executors.openapi.UnifiedOpenAPI$RequestBody","queryAllPublicConstructors":true,"queryAllDeclaredConstructors":true,"queryAllPublicMethods":true,"queryAllDeclaredMethods":true,"allPublicConstructors":true,"allDeclaredConstructors":true,"allPublicMethods":true,"allDeclaredMethods":true,"allPublicFields":true,"allDeclaredFields":true,"allPublicClasses":true,"allDeclaredClasses":true}, -{"name":"cloud.openworkflow.sdk.impl.executors.openapi.UnifiedOpenAPI$Schema","queryAllPublicConstructors":true,"queryAllDeclaredConstructors":true,"queryAllPublicMethods":true,"queryAllDeclaredMethods":true,"allPublicConstructors":true,"allDeclaredConstructors":true,"allPublicMethods":true,"allDeclaredMethods":true,"allPublicFields":true,"allDeclaredFields":true,"allPublicClasses":true,"allDeclaredClasses":true}, -{"name":"cloud.openworkflow.sdk.impl.executors.openapi.UnifiedOpenAPI$Server","queryAllPublicConstructors":true,"queryAllDeclaredConstructors":true,"queryAllPublicMethods":true,"queryAllDeclaredMethods":true,"allPublicConstructors":true,"allDeclaredConstructors":true,"allPublicMethods":true,"allDeclaredMethods":true,"allPublicFields":true,"allDeclaredFields":true,"allPublicClasses":true,"allDeclaredClasses":true}, -{"name":"cloud.openworkflow.sdk.impl.executors.openapi.UnifiedOpenAPI$SwaggerVersion","queryAllPublicConstructors":true,"queryAllDeclaredConstructors":true,"queryAllPublicMethods":true,"queryAllDeclaredMethods":true,"allPublicConstructors":true,"allDeclaredConstructors":true,"allPublicMethods":true,"allDeclaredMethods":true,"allPublicFields":true,"allDeclaredFields":true,"allPublicClasses":true,"allDeclaredClasses":true} -] \ No newline at end of file diff --git a/impl/openapi-jackson/src/main/resources/META-INF/services/tools.jackson.databind.JacksonModule b/impl/openapi-jackson/src/main/resources/META-INF/services/tools.jackson.databind.JacksonModule deleted file mode 100644 index a986c39ba..000000000 --- a/impl/openapi-jackson/src/main/resources/META-INF/services/tools.jackson.databind.JacksonModule +++ /dev/null @@ -1 +0,0 @@ -cloud.openworkflow.sdk.impl.executors.openapi.jackson.JacksonUnifiedOpenAPIMixInModule \ No newline at end of file diff --git a/impl/openapi-jackson/src/test/java/cloud/openworkflow/sdk/impl/executors/openapi/jackson/JacksonOpenAPIProcessorTest.java b/impl/openapi-jackson/src/test/java/cloud/openworkflow/sdk/impl/executors/openapi/jackson/JacksonOpenAPIProcessorTest.java index 318521614..8f85b7e7d 100644 --- a/impl/openapi-jackson/src/test/java/cloud/openworkflow/sdk/impl/executors/openapi/jackson/JacksonOpenAPIProcessorTest.java +++ b/impl/openapi-jackson/src/test/java/cloud/openworkflow/sdk/impl/executors/openapi/jackson/JacksonOpenAPIProcessorTest.java @@ -16,7 +16,8 @@ package cloud.openworkflow.sdk.impl.executors.openapi.jackson; import cloud.openworkflow.sdk.impl.executors.openapi.OpenAPIProcessorTest; -import cloud.openworkflow.sdk.impl.executors.openapi.UnifiedOpenAPIReader; +import cloud.openworkflow.sdk.openapi.UnifiedOpenAPIReader; +import cloud.openworkflow.sdk.openapi.jackson.JacksonUnifiedOpenAPIReader; import org.junit.jupiter.api.BeforeAll; public class JacksonOpenAPIProcessorTest extends OpenAPIProcessorTest { @@ -25,7 +26,7 @@ public class JacksonOpenAPIProcessorTest extends OpenAPIProcessorTest { @BeforeAll static void init() { - reader = new JacksonUnifiedOpenAPIReaderFactory().get(); + reader = new JacksonUnifiedOpenAPIReaderFactory().apply(null); } @Override diff --git a/impl/pom.xml b/impl/pom.xml index 14c5910fd..fa612135a 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 @@ -29,7 +27,7 @@ cloud.openworkflow.sdk - openworkflow-impl-http + openworkflow-impl-http-jakarta ${project.version} @@ -85,7 +83,7 @@ cloud.openworkflow.sdk - openworkflow-impl-http-jackson + openworkflow-impl-http-jakarta-jackson ${project.version} @@ -102,7 +100,7 @@ cloud.openworkflow.sdk - openworkflow-impl-openapi + openworkflow-impl-openapi-jackson ${project.version} @@ -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..4891cc151 100644 --- a/impl/test/pom.xml +++ b/impl/test/pom.xml @@ -28,11 +28,11 @@ cloud.openworkflow.sdk - openworkflow-impl-http + openworkflow-impl-http-jakarta cloud.openworkflow.sdk - openworkflow-impl-http-jackson + openworkflow-impl-http-jakarta-jackson cloud.openworkflow.sdk @@ -52,7 +52,7 @@ cloud.openworkflow.sdk - openworkflow-impl-openapi + openworkflow-impl-openapi-jackson cloud.openworkflow.sdk @@ -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/HTTPWorkflowDefinitionTest.java b/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/HTTPWorkflowDefinitionTest.java index 7d1fc2713..1f52b0618 100644 --- a/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/HTTPWorkflowDefinitionTest.java +++ b/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/HTTPWorkflowDefinitionTest.java @@ -20,14 +20,14 @@ import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.catchThrowableOfType; +import cloud.openworkflow.sdk.http.JdkURITemplateResolver; import cloud.openworkflow.sdk.impl.WorkflowApplication; import cloud.openworkflow.sdk.impl.WorkflowError; import cloud.openworkflow.sdk.impl.WorkflowException; import cloud.openworkflow.sdk.impl.WorkflowModel; import cloud.openworkflow.sdk.impl.executors.CallableTask; import cloud.openworkflow.sdk.impl.executors.CallableTaskProxyBuilder; -import cloud.openworkflow.sdk.impl.http.DefaultHttpRequestBuilderFactory; -import cloud.openworkflow.sdk.impl.http.DefaultURITemplateResolver; +import cloud.openworkflow.sdk.impl.http.DefaultHttpTransportFactory; import cloud.openworkflow.sdk.types.Errors; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -77,8 +77,8 @@ public CallableTask build(CallableTask delegate) { static void init() { defaultApp = WorkflowApplication.builder() - .withHttpRequestBuilderFactory(new DefaultHttpRequestBuilderFactory()) - .withURITemplateResolver(new DefaultURITemplateResolver()) + .withHttpTransportFactory(new DefaultHttpTransportFactory()) + .withURITemplateResolver(new JdkURITemplateResolver()) .withCallableProxy(new TimeCallableTaskProxyBuilder()) .build(); diff --git a/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/OAuthHTTPWorkflowDefinitionTest.java b/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/OAuthHTTPWorkflowDefinitionTest.java index bd138dc1d..0bb7d3b66 100644 --- a/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/OAuthHTTPWorkflowDefinitionTest.java +++ b/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/OAuthHTTPWorkflowDefinitionTest.java @@ -20,9 +20,9 @@ import static org.assertj.core.api.Assertions.assertThat; import cloud.openworkflow.sdk.api.types.Workflow; +import cloud.openworkflow.sdk.http.JdkURITemplateResolver; import cloud.openworkflow.sdk.impl.WorkflowApplication; -import cloud.openworkflow.sdk.impl.http.DefaultHttpRequestBuilderFactory; -import cloud.openworkflow.sdk.impl.http.DefaultURITemplateResolver; +import cloud.openworkflow.sdk.impl.http.DefaultHttpTransportFactory; import java.io.IOException; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; @@ -67,8 +67,8 @@ public class OAuthHTTPWorkflowDefinitionTest { static void init() { defaultApp = WorkflowApplication.builder() - .withHttpRequestBuilderFactory(new DefaultHttpRequestBuilderFactory()) - .withURITemplateResolver(new DefaultURITemplateResolver()) + .withURITemplateResolver(new JdkURITemplateResolver()) + .withHttpTransportFactory(new DefaultHttpTransportFactory()) .build(); jakartaApp = WorkflowApplication.builder().build(); diff --git a/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/OpenAPITest.java b/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/OpenAPITest.java index 47813c32c..13a287850 100644 --- a/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/OpenAPITest.java +++ b/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/OpenAPITest.java @@ -20,11 +20,11 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import cloud.openworkflow.sdk.api.types.Workflow; +import cloud.openworkflow.sdk.http.JdkURITemplateResolver; import cloud.openworkflow.sdk.impl.WorkflowApplication; import cloud.openworkflow.sdk.impl.WorkflowDefinition; import cloud.openworkflow.sdk.impl.WorkflowException; -import cloud.openworkflow.sdk.impl.http.DefaultHttpRequestBuilderFactory; -import cloud.openworkflow.sdk.impl.http.DefaultURITemplateResolver; +import cloud.openworkflow.sdk.impl.http.DefaultHttpTransportFactory; import java.io.IOException; import java.io.InputStream; import java.time.OffsetDateTime; @@ -110,8 +110,8 @@ static void init() throws IOException { } defaultApp = WorkflowApplication.builder() - .withHttpRequestBuilderFactory(new DefaultHttpRequestBuilderFactory()) - .withURITemplateResolver(new DefaultURITemplateResolver()) + .withHttpTransportFactory(new DefaultHttpTransportFactory()) + .withURITemplateResolver(new JdkURITemplateResolver()) .build(); jakartaApp = WorkflowApplication.builder().build(); } diff --git a/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/OpenIDCHTTPWorkflowDefinitionTest.java b/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/OpenIDCHTTPWorkflowDefinitionTest.java index f32d36ab9..43c76454d 100644 --- a/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/OpenIDCHTTPWorkflowDefinitionTest.java +++ b/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/OpenIDCHTTPWorkflowDefinitionTest.java @@ -20,9 +20,9 @@ import static org.assertj.core.api.Assertions.assertThat; import cloud.openworkflow.sdk.api.types.Workflow; +import cloud.openworkflow.sdk.http.JdkURITemplateResolver; import cloud.openworkflow.sdk.impl.WorkflowApplication; -import cloud.openworkflow.sdk.impl.http.DefaultHttpRequestBuilderFactory; -import cloud.openworkflow.sdk.impl.http.DefaultURITemplateResolver; +import cloud.openworkflow.sdk.impl.http.DefaultHttpTransportFactory; import java.io.IOException; import java.util.List; import java.util.Map; @@ -65,8 +65,8 @@ public class OpenIDCHTTPWorkflowDefinitionTest { static void init() { defaultApp = WorkflowApplication.builder() - .withHttpRequestBuilderFactory(new DefaultHttpRequestBuilderFactory()) - .withURITemplateResolver(new DefaultURITemplateResolver()) + .withHttpTransportFactory(new DefaultHttpTransportFactory()) + .withURITemplateResolver(new JdkURITemplateResolver()) .build(); jakartaApp = WorkflowApplication.builder().build(); diff --git a/pom.xml b/pom.xml index 9f8e0af0b..41959aca3 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,41 @@ + + 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-api + ${project.version} + + + 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} + + + cloud.openworkflow.sdk + openworkflow-common-openapi-jackson + ${project.version} +