diff --git a/examples/events/src/main/java/events/EventExample.java b/examples/events/src/main/java/events/EventExample.java index 628782fb8..57cbdd023 100644 --- a/examples/events/src/main/java/events/EventExample.java +++ b/examples/events/src/main/java/events/EventExample.java @@ -37,7 +37,7 @@ public static void main(String[] args) throws IOException { WorkflowInstance waitingInstance = listenDefinition.instance(Map.of()); waitingInstance .start() - .thenAccept(node -> logger.info("Waiting instance completed with result {}", node)); + .thenAccept(output -> logger.info("Waiting instance completed with result {}", output)); logger.info("Listen instance waiting for proper event, Status {}", waitingInstance.status()); logger.info("Publishing event with temperature 35"); emitDefinition.instance(Map.of("temperature", 35)).start().join(); diff --git a/examples/simpleGet/src/main/java/io/serverlessworkflow/impl/NotBlockingExample.java b/examples/simpleGet/src/main/java/io/serverlessworkflow/impl/NotBlockingExample.java index cb663c1a8..39cfe6f57 100644 --- a/examples/simpleGet/src/main/java/io/serverlessworkflow/impl/NotBlockingExample.java +++ b/examples/simpleGet/src/main/java/io/serverlessworkflow/impl/NotBlockingExample.java @@ -30,7 +30,7 @@ public static void main(String[] args) throws IOException { appl.workflowDefinition(WorkflowReader.readWorkflowFromClasspath("get.yaml")) .instance(Map.of("petId", 10)) .start() - .thenAccept(node -> logger.info("Workflow output is {}", node)); + .thenAccept(output -> logger.info("Workflow output is {}", output)); logger.info("The request has been sent, this thread might continue doing stuff"); } } diff --git a/impl/README.md b/impl/README.md index 26655a027..d0c4f0df4 100644 --- a/impl/README.md +++ b/impl/README.md @@ -1,194 +1,303 @@ -![Verify JAVA SDK](https://github.com/serverlessworkflow/sdk-java/workflows/Verify%20JAVA%20SDK/badge.svg) -![Deploy JAVA SDK](https://github.com/serverlessworkflow/sdk-java/workflows/Deploy%20JAVA%20SDK/badge.svg) [![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/serverlessworkflow/sdk-java) +[![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/serverlessworkflow/sdk-java) -# Serverless Workflow Specification - Java SDK- Reference Implementation +# Serverless Workflow Specification — Java SDK (Reference Implementation) -Welcome to Java SDK runtime reference implementation, a lightweight implementation of the Serverless Workflow specification which provides a simple, non blocking, reactive API for workflow execution. +A lightweight, non-blocking, reactive **runtime** for the [Serverless Workflow](https://serverlessworkflow.io/) specification. Use it to load, validate, and execute workflows written in YAML/JSON—or build them programmatically with our Fluent DSL. -Although initially conceived mainly for testing purposes, it was designed to be easily expanded, so it can eventually become production ready. +--- + +## Contents + +* [Status](#status) +* [Features](#features) +* [Modules](#modules) +* [Installation](#installation) +* [Quick Start](#quick-start) +* [Detailed Walkthrough](#detailed-walkthrough) +* [Fluent Java DSL](#fluent-java-dsl) +* [Mermaid Diagrams](#mermaid-diagrams) +* [Lifecycle Events](#lifecycle-events) +* [Errors & Auth](#errors--auth) +* [Development](#development) +* [License](#license) + +--- ## Status -This reference implementation is currently capable of running workflows consisting of: +| Latest Releases | Conformance to spec version | +| :------------------------------------------------------------------------------------: | :----------------------------------------------------------------------: | +| [7.x](https://github.com/serverlessworkflow/sdk-java/releases/tag/7.1.0.Final) (Java 17)| [v1.0.0](https://github.com/serverlessworkflow/specification/tree/1.0.x) | +| [5.x](https://github.com/serverlessworkflow/sdk-java/releases/tag/5.1.0.Final) (Java 11) | [v0.8](https://github.com/serverlessworkflow/specification/tree/0.8.x) | +| [4.x](https://github.com/serverlessworkflow/sdk-java/releases/tag/4.1.0.Final) (Java 1.8) | [v0.8](https://github.com/serverlessworkflow/specification/tree/0.8.x) | +| [3.0.0.Final](https://github.com/serverlessworkflow/sdk-java/releases/tag/3.0.0.Final) (Java 1.8) | [v0.7](https://github.com/serverlessworkflow/specification/tree/0.7.x) | +| [2.0.0.Final](https://github.com/serverlessworkflow/sdk-java/releases/tag/2.0.0.Final) (Java 1.8) | [v0.6](https://github.com/serverlessworkflow/specification/tree/0.6.x) | +| [1.0.3.Final](https://github.com/serverlessworkflow/sdk-java/releases/tag/1.0.3.Final) (Java 1.8) | [v0.5](https://github.com/serverlessworkflow/specification/tree/0.5.x) | + +> **Note:** `6.0.0.Final` (planned for spec **v0.9**) is intentionally **skipped** to leave room for anyone who wants to work on it. + +## Features + +This reference implementation can run workflows consisting of: + +**Tasks** + +* `Switch` +* `Set` +* `Do` +* `Raise` +* `Listen` +* `Emit` +* `Fork` +* `For` / `ForEach` +* `Try` (with `Catch`/`Retry`) +* `Wait` +* `Call` + + * **HTTP** + + * Basic auth + * Bearer auth + * OAuth2 / OIDC auth + * Digest auth (via Fluent DSL) + +**Schema Validation** + +* Input / Output validation + +**Expressions** + +* Input / Output / Export +* Special keywords: `runtime`, `workflow`, `task`, … + +**Error Definitions** + +* Standard & custom error types + +**Lifecycle Events** + +* `Pending`, `Started`, `Suspended`, `Faulted`, `Resumed`, `Cancelled`, `Completed` + +--- +## Modules -* Tasks - * Switch - * Set - * Do - * Raise - * Listen - * Emit - * Fork - * For - * Try - * Wait - * Call - * HTTP -* Schema Validation - * Input - * Output -* Expressions - * Input - * Output - * Export - * Special keywords: runtime, workflow, task... -* Error definitions +This SDK is modular by design—pull in only what you need: +* **`serverlessworkflow-impl-core`** + Workflow engine & core interfaces. Depends on generated types and CloudEvents SDK. -## Setup +* **`serverlessworkflow-impl-jackson`** + Adds Jackson integration, JQ expressions, JSON Schema validation, and CloudEvents (de)serialization. + 👉 **Most users add this one.** -Before getting started, ensure you have Java 17+ and Maven or Gradle installed. +* **`serverlessworkflow-impl-http`** + HTTP `Call` task handler. -Install [Java 17](https://openjdk.org/projects/jdk/17/) -Install [Maven](https://maven.apache.org/install.html) (if using Maven) -Install [Gradle](https://gradle.org/install) (if using Gradle) +* **`serverlessworkflow-impl-jackson-jwt`** + OAuth2/OIDC helpers for HTTP calls. -### Dependencies +There are also companion modules/docs for: -This implementation follows a modular approach, keeping dependencies minimal: -- The core library is always required. -- Additional dependencies must be explicitly included if your workflow interacts with external services (e.g., HTTP). -This ensures you only include what you need, preventing unnecessary dependencies. +* **Fluent DSL** (programmatic builder) +* **Mermaid** (diagramming workflows) -#### Maven +Links below. -You always need to add this dependency to your pom.xml `dependencies` section: +--- + +## Installation + +### Maven ```xml + - io.serverlessworkflow - serverlessworkflow-impl-core - 7.0.0.Final + io.serverlessworkflow + serverlessworkflow-impl-jackson -``` -And only if your workflow is using HTTP calls, you must add: + + + io.serverlessworkflow + serverlessworkflow-impl-http + -```xml + - io.serverlessworkflow - serverlessworkflow-impl-http - 7.0.0.Final + io.serverlessworkflow + serverlessworkflow-impl-jackson-jwt ``` -#### Gradle projects: +### Gradle (Kotlin/Groovy) -You always need to add this dependency to your build.gradle `dependencies` section: +```gradle +implementation("io.serverlessworkflow:serverlessworkflow-impl-jackson") +implementation("io.serverlessworkflow:serverlessworkflow-impl-http") // if using HTTP +implementation("io.serverlessworkflow:serverlessworkflow-impl-jackson-jwt") // if using OAuth2/OIDC +``` -```text -implementation("io.serverlessworkflow:serverlessworkflow-impl-core:7.0.0.Final") +> Requires **Java 17+**. + +--- + +## Quick Start + +We’ll run a simple workflow that performs an HTTP GET. See the full YAML in +[examples/simpleGet/src/main/resources/get.yaml](). + +### Blocking execution + +```java +try (WorkflowApplication appl = WorkflowApplication.builder().build()) { + var output = + appl.workflowDefinition(WorkflowReader.readWorkflowFromClasspath("get.yaml")) + .instance(Map.of("petId", 10)) + .start() + .join(); + logger.info("Workflow output is {}", output); +} +``` + +### Non-blocking execution + +```java +try (WorkflowApplication appl = WorkflowApplication.builder().build()) { + appl.workflowDefinition(WorkflowReader.readWorkflowFromClasspath("get.yaml")) + .instance(Map.of("petId", 10)) + .start() + .thenAccept(output -> logger.info("Workflow output is {}", output)); +} ``` -And only if your workflow is using HTTP calls, you must add: +Example output: ```text -implementation("io.serverlessworkflow:serverlessworkflow-impl-http:7.0.0.Final") +Workflow output is {"id":10,"category":{"id":10,"name":"string"},"name":"doggie",...} ``` -## How to use +Full examples: + +* Blocking: [examples/simpleGet/src/main/java/io/serverlessworkflow/impl/BlockingExample.java]() +* Non-blocking: [examples/simpleGet/src/main/java/io/serverlessworkflow/impl/NotBlockingExample.java]() -The quick version is intended for impatient users who want to try something as soon as possible. +--- -The detailed version is more suitable for those users interested in a more thoughtful discussion of the API. +## Detailed Walkthrough -### Quick version +We’ll coordinate two workflows—one **listens** for high temperatures and the other **emits** temperature events: -For a quick introduction, we will use a simple workflow [definition](../examples/simpleGet/src/main/resources/get.yaml) that performs a get call. -We are going to show two ways of invoking the workflow: - - blocking the thread till the get request goes through - - returning control to the caller, so the main thread continues while the get is executed +* `listen.yaml` waits for an event with `temperature > 38` (non-blocking) +* `emit.yaml` emits events using a workflow parameter -In order to execute the workflow, blocking the thread till the HTTP request is completed, you should write +Create an application (customize thread pools, etc.). `WorkflowApplication` is `AutoCloseable`, so use try-with-resources: -``` java +```java try (WorkflowApplication appl = WorkflowApplication.builder().build()) { - logger.info( - "Workflow output is {}", - appl.workflowDefinition(WorkflowReader.readWorkflowFromClasspath("get.yaml")) - .instance(Map.of("petId", 10)) - .start() - .join()); - } -``` -You can find the complete java code [here](../examples/simpleGet/src/main/java/io/serverlessworkflow/impl/BlockingExample.java) + var listen = appl.workflowDefinition(WorkflowReader.readWorkflowFromClasspath("listen.yaml")); + var emit = appl.workflowDefinition(WorkflowReader.readWorkflowFromClasspath("emit.yaml")); -In order to execute the workflow without blocking the calling thread till the HTTP request is completed, you should write + // Start the listener (non-blocking) + listen.instance(Map.of()) + .start() + .thenAccept(out -> logger.info("Waiting instance completed with {}", out)); -``` java - try (WorkflowApplication appl = WorkflowApplication.builder().build()) { - appl.workflowDefinition(WorkflowReader.readWorkflowFromClasspath("get.yaml")) - .instance(Map.of("petId", 10)) - .start() - .thenAccept(node -> logger.info("Workflow output is {}", node)); - } + // Emit a low temperature (ignored) + emit.instance(Map.of("temperature", 35)).start().join(); + + // Emit a high temperature (completes the waiting workflow) + emit.instance(Map.of("temperature", 39)).start().join(); +} ``` -When the HTTP request is done, both examples will print a similar output +You’ll see: -```shell -Workflow output is {"id":10,"category":{"id":10,"name":"string"},"name":"doggie","photoUrls":["string"],"tags":[{"id":10,"name":"string"}],"status":"string"} +``` +Waiting instance completed with [{"temperature":39}] ``` -You can find the complete java code [here](../examples/simpleGet/src/main/java/io/serverlessworkflow/impl/NotBlockingExample.java) +Source: `examples/events/src/main/java/events/EventExample.java` -### Detailed version +--- -To discuss runtime API we are going to use a couple of workflow: -- [listen.yaml](../examples/events/src/main/listen.yaml), which waits for an event reporting a temperature greater than 38 -- [emit.yaml](../examples/events/src/main/emit.yaml), which emits events with a certain temperature, specified as workflow parameter. +## Fluent Java DSL -Here is a summary of what we are trying to do: +Prefer building workflows programmatically with type-safe builders and recipes? +👉 **Docs:** [https://github.com/serverlessworkflow/sdk-java/blob/main/fluent/README.md](https://github.com/serverlessworkflow/sdk-java/blob/main/fluent/README.md) -- The listen.yaml workflow waits for an event (not-blocking). -- We send an event with a low temperature (ignored). -- We send an event with a high temperature (completes the workflow). +Highlights: -The first step is to create a [WorkflowApplication](core/src/main/java/io/serverlessworkflow/impl/WorkflowApplication.java) instance. An application is an abstraction that allows customization of different aspects of the workflow execution (for example, change the default `ExecutorService` for thread spawning) +* Chainable builders for `Call HTTP`, `Listen/Emit`, `Try/Catch/Retry`, `Switch`, `Fork`, etc. +* Reusable “recipes” (e.g., `http().GET().acceptJSON().endpoint("${ ... }")`) +* Static helpers for auth (`basic(...)`, `bearer(...)`, `oidc(...)`, …) and standard error types. -Since `WorkflowApplication` implements `Autocloseable`, we better use a **try-with-resources** block, ensuring any resource that the workflow might have used is freed when done. +--- -`try (WorkflowApplication appl = WorkflowApplication.builder().build())` +## Mermaid Diagrams -Once we have the application object, we use it to parse our definition examples. To load each workflow definition, we use the `readFromClasspath` helper method defined in [WorkflowReader](api/src/main/java/io/serverlessworkflow/api/WorkflowReader.java) class. +Generate Mermaid diagrams for your workflows right from the SDK. +👉 **Docs:** [https://github.com/serverlessworkflow/sdk-java/blob/main/mermaid/README.md](https://github.com/serverlessworkflow/sdk-java/blob/main/mermaid/README.md) -```java - WorkflowDefinition listenDefinition = - appl.workflowDefinition(WorkflowReader.readWorkflowFromClasspath("listen.yaml")); - WorkflowDefinition emitDefinition = - appl.workflowDefinition(WorkflowReader.readWorkflowFromClasspath("emit.yaml")); -``` +Great for docs, PRs, and visual reviews. -A [WorkflowDefinition](core/src/main/java/io/serverlessworkflow/impl/WorkflowDefinition.java) object is immutable and, therefore, thread-safe. It is used to execute as many workflow instances as desired. +--- -To execute a workflow, we first create a [WorkflowInstance](core/src/main/java/io/serverlessworkflow/impl/WorkflowInstance.java) object (its initial status is PENDING) and then invoke the `start` method on it (its status is changed to RUNNING). The `start` method returns a [CompletableFuture](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html), which we use to indicate that a log message should be printed when the workflow is completed. +## Lifecycle Events -```java - WorkflowInstance waitingInstance = listenDefinition.instance(Map.of()); - waitingInstance - .start() - .thenAccept(node -> logger.info("Waiting instance completed with result {}", node)); -``` +Every workflow publishes CloudEvents you can subscribe to (in-memory or your own broker): -As soon as the workflow execution reach the point where it waits for events to arrive, control is returned to the calling thread. Since the execution is not blocking, we can execute another workflow instance while the first one is waiting. +* `io.serverlessworkflow.workflow.*` → `pending`, `started`, `suspended`, `faulted`, `resumed`, `cancelled`, `completed` +* `io.serverlessworkflow.task.*` → `started`, `suspended`, `resumed`, `cancelled`, `completed` -We will send an event with a temperature that does not satisfy the criteria, so the listen instance will continue waiting. We use a regular Java `Map` to pass parameters to the workflow instance that sends the event. Note that since we want to wait till the event is published, we call `join` after `start`, telling the `CompletableFuture` to wait for workflow completion. +See `impl` tests/examples for consuming and asserting on these events. -```java - emitDefinition.instance(Map.of("temperature", 35)).start().join(); - ``` - - It's time to complete the waiting instance and send an event with the expected temperature. We do so by reusing `emitDefinition`. +--- -```java - emitDefinition.instance(Map.of("temperature", 39)).start().join(); - ``` - -After that, listen instance will be completed and we will see this log message +## Errors & Auth -```java -[pool-1-thread-1] INFO events.EventExample - Waiting instance completed with result [{"temperature":39}] +**Errors** + +* Raise standard errors with versioned URIs (e.g., `runtime`, `communication`, `timeout`, …) or custom ones. +* Fluent helpers (e.g., `serverError()`, `timeoutError()`) set both **type URI** and default **HTTP status**; override as needed. + +**Authentication (HTTP Call)** + +* Basic / Bearer / Digest +* OAuth2 / OpenID Connect (client credentials, etc.) +* Fluent helpers: `basic("user","pass")`, `bearer("token")`, `oidc(authority, grant, clientId, clientSecret)`, … + +--- + +## Development + +**Prereqs** + +* Java 17+ +* Maven (or Gradle) + +**Build & Verify** + +```bash +mvn -B clean verify ``` -The source code of the example is [here](../examples/events/src/main/java/events/EventExample.java) +**Formatting & Lint (CI parity)** + +```bash +mvn -B -DskipTests spotless:check checkstyle:check +``` + +**Run examples** + +* See `examples/` directory for runnable samples. + +--- + +## License + +Apache License 2.0. See `LICENSE` for details. + +--- + +*Questions or ideas? PRs and issues welcome!*