Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions impl/openapi/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.serverlessworkflow</groupId>
<artifactId>serverlessworkflow-impl</artifactId>
<version>8.0.0-SNAPSHOT</version>
</parent>
<artifactId>serverlessworkflow-impl-openapi</artifactId>
<name>Serverless Workflow :: Impl :: OpenAPI</name>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
</dependency>
<dependency>
<groupId>io.serverlessworkflow</groupId>
<artifactId>serverlessworkflow-impl-core</artifactId>
</dependency>
<dependency>
<groupId>io.swagger.parser.v3</groupId>
<artifactId>swagger-parser</artifactId>
</dependency>
<dependency>
<groupId>jakarta.ws.rs</groupId>
<artifactId>jakarta.ws.rs-api</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
/*
* Copyright 2020-Present The Serverless 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 io.serverlessworkflow.impl.executors;

import io.serverlessworkflow.api.types.CallOpenAPI;
import io.serverlessworkflow.api.types.OpenAPIArguments;
import io.serverlessworkflow.api.types.TaskBase;
import io.serverlessworkflow.api.types.UriTemplate;
import io.serverlessworkflow.api.types.WithOpenAPIParameters;
import io.serverlessworkflow.api.types.Workflow;
import io.serverlessworkflow.impl.TaskContext;
import io.serverlessworkflow.impl.WorkflowApplication;
import io.serverlessworkflow.impl.WorkflowContext;
import io.serverlessworkflow.impl.WorkflowError;
import io.serverlessworkflow.impl.WorkflowException;
import io.serverlessworkflow.impl.WorkflowModel;
import io.serverlessworkflow.impl.resources.ResourceLoader;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.parser.OpenAPIV3Parser;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.Invocation;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;

public class OpenAPIExecutor implements CallableTask<CallOpenAPI> {

private static final Client client = ClientBuilder.newClient();
private WebTargetSupplier webTargetSupplier;
private RequestSupplier requestSupplier;
private OpenAPIModelConverter converter = new OpenAPIModelConverter() {};

@FunctionalInterface
private interface WebTargetSupplier {
WebTarget apply();
}

@FunctionalInterface
private interface RequestSupplier {
WorkflowModel apply(
Invocation.Builder request, WorkflowContext workflow, TaskContext task, WorkflowModel node);
}

@Override
public void init(
CallOpenAPI task, Workflow workflow, WorkflowApplication application, ResourceLoader loader) {
OpenAPIArguments args = task.getWith();

URI uri = getOpenAPIDocumentURI(args.getDocument().getEndpoint().getUriTemplate());

OpenAPIV3Parser apiv3Parser = new OpenAPIV3Parser();

OpenAPI openAPI = apiv3Parser.read(uri.toString());

OpenAPIOperationContext ctx = generateContext(openAPI, args, uri);

WithOpenAPIParameters withParams =
Optional.ofNullable(args.getParameters()).orElse(new WithOpenAPIParameters());

this.webTargetSupplier = getTargetSupplier(openAPI, ctx, withParams);

this.requestSupplier =
(request, w, taskContext, node) -> {
try {
Response response = request.method(ctx.httpMethodName(), Response.class);

if (!args.isRedirect() && !is2xx(response)) {
throw new WorkflowException(
WorkflowError.communication(
response.getStatus(),
taskContext,
"Received a non-2xx nor 3xx response but redirects are enabled")
.build());
}

if (args.isRedirect() && isNot2xxNor3xx(response)) {
throw new WorkflowException(
WorkflowError.communication(
response.getStatus(),
taskContext,
"Received a non-2xx nor 3xx response but redirects are enabled")
.build());
}

return converter.toModel(
application.modelFactory(), node, response.readEntity(node.objectClass()));
} catch (WebApplicationException exception) {
throw new WorkflowException(
WorkflowError.communication(
exception.getResponse().getStatus(), taskContext, exception)
.build());
}
};
}

private static WebTargetSupplier getTargetSupplier(
OpenAPI openAPI, OpenAPIOperationContext ctx, WithOpenAPIParameters withParams) {
return () -> {
WebTarget webTarget =
client
.target(openAPI.getServers().get(0).getUrl())
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Operation can have servers too, should Operation's servers be precedence?

.path(ctx.buildPath(withParams.getAdditionalProperties()));

MultivaluedMap<String, Object> queryParams =
ctx.buildQueryParams(withParams.getAdditionalProperties());

for (Map.Entry<String, List<Object>> queryParam : queryParams.entrySet()) {
for (Object value : queryParam.getValue()) {
webTarget = webTarget.queryParam(queryParam.getKey(), value);
}
}

return webTarget;
};
}

private static boolean is2xx(Response response) {
return response.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL);
}

private static boolean isNot2xxNor3xx(Response response) {
return !(response.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)
|| response.getStatusInfo().getFamily().equals(Response.Status.Family.REDIRECTION));
}

private static OpenAPIOperationContext generateContext(
OpenAPI openAPI, OpenAPIArguments args, URI uri) {
return openAPI.getPaths().entrySet().stream()
.flatMap(
pathEntry ->
pathEntry.getValue().readOperationsMap().entrySet().stream()
.map(
operationEntry ->
new OpenAPIOperationContext(
operationEntry.getValue().getOperationId(),
pathEntry.getKey(),
operationEntry.getKey(),
operationEntry.getValue())))
.filter(c -> c.operationId().equals(args.getOperationId()))
.findFirst()
.orElseThrow(
() ->
new IllegalArgumentException(
"Operation with id "
+ args.getOperationId()
+ " not found in OpenAPI document "
+ uri));
}

@Override
public CompletableFuture<WorkflowModel> apply(
WorkflowContext workflowContext, TaskContext taskContext, WorkflowModel input) {

return CompletableFuture.supplyAsync(
() -> {
WebTarget target = webTargetSupplier.apply();
Invocation.Builder request = target.request();
return requestSupplier.apply(request, workflowContext, taskContext, input);
},
workflowContext.definition().application().executorService());
}

@Override
public boolean accept(Class<? extends TaskBase> clazz) {
return clazz.equals(CallOpenAPI.class);
}

private static URI getOpenAPIDocumentURI(UriTemplate template) {
if (template.getLiteralUri() != null) {
return template.getLiteralUri();
} else if (template.getLiteralUriTemplate() != null) {
// https://github.com/serverlessworkflow/specification/blob/main/dsl-reference.md#uri-template
throw new UnsupportedOperationException(
"URI templates with parameters are not supported yet");
}
throw new IllegalArgumentException("Invalid UriTemplate definition " + template);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Copyright 2020-Present The Serverless 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 io.serverlessworkflow.impl.executors;

import io.serverlessworkflow.impl.WorkflowModel;
import io.serverlessworkflow.impl.WorkflowModelFactory;
import jakarta.ws.rs.client.Entity;
import java.util.Map;

public interface OpenAPIModelConverter {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@fjtirado this one has the same contract as HttpModelConverter, let's move it to a shared place?


default WorkflowModel toModel(WorkflowModelFactory factory, WorkflowModel model, Object entity) {
return factory.fromAny(model, entity);
}

default Entity toEntity(Map<String, Object> model) {
return Entity.json(model);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* Copyright 2020-Present The Serverless 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 io.serverlessworkflow.impl.executors;

import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.parameters.Parameter;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import java.util.Map;
import java.util.Objects;

public record OpenAPIOperationContext(
String operationId, String path, PathItem.HttpMethod httpMethod, Operation operation) {

public String httpMethodName() {
return httpMethod.name();
}

public String buildPath(Map<String, Object> replacements) {
String finalPath = path;
if (Objects.isNull(operation.getParameters())) {
return "";
}
for (Parameter parameter : operation.getParameters()) {
if ("path".equals(parameter.getIn())) {
String name = parameter.getName();
Object value = replacements.get(name);
if (value != null) {
finalPath = path.replaceAll("\\{\\s*" + name + "\\s*}", value.toString());
}
}
}
return finalPath;
}

public MultivaluedMap<String, Object> buildQueryParams(Map<String, Object> replacements) {
if (Objects.isNull(operation.getParameters())) {
return new MultivaluedHashMap<>();
}
MultivaluedMap<String, Object> queryParams = new MultivaluedHashMap<>();
for (Parameter parameter : operation.getParameters()) {
if ("query".equals(parameter.getIn())) {
String name = parameter.getName();
Object value = replacements.get(name);
if (value != null) {
queryParams.add(name, value.toString());
}
}
}
return queryParams;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
io.serverlessworkflow.impl.executors.OpenAPIExecutor
Loading