diff --git a/.tools/run_jvm_tests.sh b/.tools/run_jvm_tests.sh index 7c869744..6a3f7bcf 100755 --- a/.tools/run_jvm_tests.sh +++ b/.tools/run_jvm_tests.sh @@ -11,6 +11,7 @@ pushd $PROJECT_ROOT/templates/kotlin-gradle && ./gradlew check && popd pushd $PROJECT_ROOT/templates/kotlin-gradle-lambda-cdk/lambda && ./gradlew check && popd pushd $PROJECT_ROOT/basics/basics-java && ./gradlew check && popd +pushd $PROJECT_ROOT/basics/basics-kotlin && ./gradlew check && popd pushd $PROJECT_ROOT/patterns-use-cases/sagas/sagas-java && ./gradlew check && popd pushd $PROJECT_ROOT/patterns-use-cases/payment-state-machine/payment-state-machine-java && ./gradlew check && popd diff --git a/.tools/update_jvm_examples.sh b/.tools/update_jvm_examples.sh index a3bcd509..a8361056 100755 --- a/.tools/update_jvm_examples.sh +++ b/.tools/update_jvm_examples.sh @@ -18,6 +18,7 @@ search_and_replace_version_gradle $PROJECT_ROOT/templates/kotlin-gradle search_and_replace_version_gradle $PROJECT_ROOT/templates/kotlin-gradle-lambda-cdk/lambda search_and_replace_version_gradle $PROJECT_ROOT/basics/basics-java +search_and_replace_version_gradle $PROJECT_ROOT/basics/basics-kotlin search_and_replace_version_gradle $PROJECT_ROOT/patterns-use-cases/sagas/sagas-java search_and_replace_version_gradle $PROJECT_ROOT/patterns-use-cases/async-signals-payment/async-signals-payment-java diff --git a/README.md b/README.md index d4e82b2c..ddb86515 100644 --- a/README.md +++ b/README.md @@ -63,11 +63,12 @@ challenges. ### Kotlin -| Type | Name / Link | -|------------|-------------------------------------------------------------------| -| Templates | [Template using Gradle](templates/kotlin-gradle) | -| Use Cases | [Sagas](patterns-use-cases/sagas/sagas-kotlin) | -| End-to-End | [Food Ordering App](end-to-end-applications/kotlin/food-ordering) | +| Type | Name / Link | +|------------|-------------------------------------------------------------------------| +| Templates | [Template using Gradle](templates/kotlin-gradle) | +| Basics | [Durable Execution, Event-processing, Virtual Objects](basics/basics-kotlin) | +| Use Cases | [Sagas](patterns-use-cases/sagas/sagas-kotlin) | +| End-to-End | [Food Ordering App](end-to-end-applications/kotlin/food-ordering) | ### Python diff --git a/basics/basics-java/README.md b/basics/basics-java/README.md index f5622a29..eb884163 100644 --- a/basics/basics-java/README.md +++ b/basics/basics-java/README.md @@ -1,4 +1,4 @@ -# Examples of the basic concepts for Restate in TypeScript / JavaScript +# Examples of the basic concepts for Restate in Java The examples here showcase the most basic building blocks of Restate. **Durable Execution**, **Durable Promises**, and **Virtual Objects**, and the **Workflows** abstraction built on top diff --git a/basics/basics-kotlin/.gitignore b/basics/basics-kotlin/.gitignore new file mode 100644 index 00000000..53ecbad3 --- /dev/null +++ b/basics/basics-kotlin/.gitignore @@ -0,0 +1,35 @@ +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# Ignore Gradle project-specific cache directory +.gradle + +# Ignore Gradle build output directory +build + +.idea +*.iml + +# Unignore the gradle wrapper +!gradle/wrapper/gradle-wrapper.jar \ No newline at end of file diff --git a/basics/basics-kotlin/README.md b/basics/basics-kotlin/README.md new file mode 100644 index 00000000..1f1f0a12 --- /dev/null +++ b/basics/basics-kotlin/README.md @@ -0,0 +1,66 @@ +# Examples of the basic concepts for Restate in Kotlin + +The examples here showcase the most basic building blocks of Restate. **Durable Execution**, +**Durable Promises**, and **Virtual Objects**, and the **Workflows** abstraction built on top +of them. + +The individual example files contain code snippets with comments and a brief descriptions +about how they work and how they can be run. + +### Examples + +* **[Basic Durable Execution:](durable_execution/RoleUpdateService.java):** Running code cleanly + to the end in the presence of failures. Automatic retries and recovery of previously + finished actions. The example applies a series of updates and permission setting changes + to user's profile. + ```shell + ./gradlew -PmainClass=durable_execution.RoleUpdateServiceKt run + ``` + +* **[Durable Execution with Compensations](durable_execution_compensation/RoleUpdateService.java):** + Reliably compensating / undoing previous actions upon unrecoverable errors halfway + through multi-step change. This is the same example as above, extended for cases where + a part of the change cannot be applied (conflict) and everything has to roll back. + ```shell + ./gradlew -PmainClass=durable_execution_compensation.RoleUpdateServiceKt run + ``` + +* **[Workflows](workflows/SignupWorkflow.java):** Workflows are durable execution tasks that can + be submitted and awaited. They have an identity and can be signaled and queried + through durable promises. The example is a user-signup flow that takes multiple + operations, including verifying the email address. + +* **[Virtual Objects](virtual_objects/GreeterObject.java):** Stateful serverless objects + to manage durable consistent state and state-manipulating logic. + ```shell + ./gradlew -PmainClass=virtual_objects.GreeterObjectKt run + ``` + +* **[Kafka Event-processing](events_processing/UserUpdatesService.java):** Processing events to + update various downstream systems with durable event handlers, event-delaying, + in a strict-per-key order. + ```shell + ./gradlew -PmainClass=events_processing.UserUpdatesServiceKt run + ``` + +* **[Stateful Event-processing](events_state/ProfileService.java):** Populating state from + events and making is queryable via RPC handlers. + ```shell + ./gradlew -PmainClass=events_state.ProfileServiceKt run + ``` + + +### Running the examples + +1. Start Restate Server in a separate shell: `npx restate-server` + +2. Start the relevant example. The commands are listed above for each example. + +3. Register the example at Restate server by calling + `npx restate -y deployment register --force localhost:9080`. + + _Note: the '--force' flag here is to circumvent all checks related to graceful upgrades, because it is only a playground, not a production setup._ + +4. Check the comments in the example for how to interact with the example. + +**NOTE:** When you get an error of the type `{"code":"not_found","message":"Service 'greeter' not found. ...}`, then you forgot step (3) for that example. diff --git a/basics/basics-kotlin/build.gradle.kts b/basics/basics-kotlin/build.gradle.kts new file mode 100644 index 00000000..0d0e7829 --- /dev/null +++ b/basics/basics-kotlin/build.gradle.kts @@ -0,0 +1,45 @@ +plugins { + application + kotlin("jvm") version "2.0.0" + // Kotlinx serialization (optional) + kotlin("plugin.serialization") version "2.0.0" + + id("com.google.devtools.ksp") version "2.0.0-1.0.21" +} + +repositories { + mavenCentral() +} + +val restateVersion = "1.0.1" + +dependencies { + // Annotation processor + ksp("dev.restate:sdk-api-kotlin-gen:$restateVersion") + + // Restate SDK + implementation("dev.restate:sdk-api-kotlin:$restateVersion") + implementation("dev.restate:sdk-http-vertx:$restateVersion") + + // Logging (optional) + implementation("org.apache.logging.log4j:log4j-core:2.23.0") + + // Kotlinx serialization (optional) + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.2") +} + +// Setup Java/Kotlin compiler target +java { + toolchain { + languageVersion.set(JavaLanguageVersion.of(17)) + } +} + +// Set main class +application { + if (project.hasProperty("mainClass")) { + mainClass.set(project.property("mainClass") as String) + } else { + mainClass.set("durable_execution.RoleUpdateServiceKt") + } +} diff --git a/basics/basics-kotlin/gradle/wrapper/gradle-wrapper.jar b/basics/basics-kotlin/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..033e24c4 Binary files /dev/null and b/basics/basics-kotlin/gradle/wrapper/gradle-wrapper.jar differ diff --git a/basics/basics-kotlin/gradle/wrapper/gradle-wrapper.properties b/basics/basics-kotlin/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..62f495df --- /dev/null +++ b/basics/basics-kotlin/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/basics/basics-kotlin/gradlew b/basics/basics-kotlin/gradlew new file mode 100755 index 00000000..fcb6fca1 --- /dev/null +++ b/basics/basics-kotlin/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original 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 +# +# https://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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/basics/basics-kotlin/gradlew.bat b/basics/basics-kotlin/gradlew.bat new file mode 100644 index 00000000..6689b85b --- /dev/null +++ b/basics/basics-kotlin/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/basics/basics-kotlin/src/main/kotlin/durable_execution/RoleUpdateService.kt b/basics/basics-kotlin/src/main/kotlin/durable_execution/RoleUpdateService.kt new file mode 100644 index 00000000..fe28ab94 --- /dev/null +++ b/basics/basics-kotlin/src/main/kotlin/durable_execution/RoleUpdateService.kt @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2024 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Restate Examples + * which is released under the MIT license. + * + * You can find a copy of the license in the file LICENSE + * in the root directory of this repository or package or at + * https://github.com/restatedev/examples/blob/main/LICENSE + */ +package durable_execution + +import dev.restate.sdk.annotation.Handler +import dev.restate.sdk.annotation.Service +import dev.restate.sdk.http.vertx.RestateHttpEndpointBuilder +import dev.restate.sdk.kotlin.* +import utils.* + +// This is an example of the benefits of Durable Execution. +// Durable Execution ensures code runs to the end, even in the presence of +// failures. This is particularly useful for code that updates different systems and needs to +// make sure all updates are applied: +// +// - Failures are automatically retried, unless they are explicitly labeled +// as terminal errors +// - Restate tracks execution progress in a journal. +// Work that has already been completed is not repeated during retries. +// Instead, the previously completed journal entries are replayed. +// This ensures that stable deterministic values are used during execution. +// - Durable executed functions use the regular code and control flow, +// no custom DSLs +// +@Service +class RoleUpdateService { + @Handler + suspend fun applyRoleUpdate(ctx: Context, req: UpdateRequest) { + val success = ctx.runBlock { applyUserRole(req.userId, req.role) } + if (!success) { + return + } + + for (permission in req.permissions) { + ctx.runBlock { applyPermission(req.userId, permission) } + } + } +} + +fun main() { + RestateHttpEndpointBuilder.builder() + .bind(RoleUpdateService()) + .buildAndListen() +} + +// +// See README for details on how to start and connect Restate. +// +// When invoking this function (see below for sample request), it will apply all +// role and permission changes, regardless of crashes. +// You will see all lines of the type "Applied permission remove:allow for user Sam Beckett" +// in the log, across all retries. You will also see that re-tries will not re-execute +// previously completed actions again, so each line occurs only once. +/* +curl localhost:8080/RoleUpdateService/applyRoleUpdate -H 'content-type: application/json' -d \ +'{ + "userId": "Sam Beckett", + "role": { "roleKey": "content-manager", "roleDescription": "Add/remove documents" }, + "permissions" : [ + { "permissionKey": "add", "setting": "allow" }, + { "permissionKey": "remove", "setting": "allow" }, + { "permissionKey": "share", "setting": "block" } + ] +}' +*/ + diff --git a/basics/basics-kotlin/src/main/kotlin/durable_execution_compensation/RoleUpdateService.kt b/basics/basics-kotlin/src/main/kotlin/durable_execution_compensation/RoleUpdateService.kt new file mode 100644 index 00000000..1743567d --- /dev/null +++ b/basics/basics-kotlin/src/main/kotlin/durable_execution_compensation/RoleUpdateService.kt @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2024 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Restate Examples + * which is released under the MIT license. + * + * You can find a copy of the license in the file LICENSE + * in the root directory of this repository or package or at + * https://github.com/restatedev/examples/blob/main/LICENSE + */ +package durable_execution_compensation + +import dev.restate.sdk.annotation.Handler +import dev.restate.sdk.annotation.Service +import dev.restate.sdk.common.TerminalException +import dev.restate.sdk.http.vertx.RestateHttpEndpointBuilder +import dev.restate.sdk.kotlin.* +import org.apache.logging.log4j.LogManager +import utils.* + +// This is an example of Durable Execution and compensation logic. +// Durable execution ensures code runs to the end, even in the presence of +// failures. That allows developers to implement error handling with common +// control flow in code: +// +// - This example uses the SAGA pattern: on error, the code undos previous +// operations in reverse order. +// - The code uses common exception handling and variables/arrays to remember +// the previous values to restore. +// +@Service +class RoleUpdateService { + @Handler + suspend fun applyRoleUpdate(ctx: Context, update: UpdateRequest) { + // Restate does retries for regular failures. + // TerminalErrors, on the other hand, are not retried and are propagated + // back to the caller. + // No permissions were applied so far, so if this fails, + // we propagate the error directly back to the caller. + + // We save in this list all the compensation actions + val compensationActions = mutableListOf Unit>() + + var previousRole = ctx.runBlock { getCurrentRole(update.userId) } + + try { + // Apply user role and register the compensation action + ctx.runBlock { tryApplyUserRole(update.userId, update.role) } + compensationActions += { + ctx.runBlock { + tryApplyUserRole(update.userId, previousRole) + } + } + + for (permission in update.permissions) { + // Apply permission and register compensation action + val previousPermission = ctx.runBlock { tryApplyPermission(update.userId, permission) } + compensationActions += { + ctx.runBlock { tryApplyPermission(update.userId, previousPermission) } + } + } + } catch (err: TerminalException) { + logger.info(">>> !!! ROLLING BACK CHANGES for user ID: ${update.userId}") + // Run compensations + for (compensationAction in compensationActions.reversed()) { + compensationAction() + } + // Throw TerminalException again to fail the processing + throw err + } + } + + companion object { + private val logger = + LogManager.getLogger(RoleUpdateService::class.java) + } +} + +fun main() { + RestateHttpEndpointBuilder.builder() + .bind(RoleUpdateService()) + .buildAndListen() +} + +// +// See README for details on how to start and connect Restate. +// +// When invoking this function (see below for sample request), you will see that +// all role/permission changes are attempted. Upon an unrecoverable error (like a +// semantic application error), previous operations are reversed. +// +// You will see all lines of the type "Applied permission remove:allow for user Sam Beckett", +// and, in case of a terminal error, their reversal. +// +// This will proceed reliably across the occasional process crash, that we blend in. +// Once an action has completed, it does not get re-executed on retries, so each line occurs only once. +/* +curl localhost:8080/RoleUpdateService/applyRoleUpdate -H 'content-type: application/json' -d \ +'{ + "userId": "Sam Beckett", + "role": { "roleKey": "content-manager", "roleDescription": "Add/remove documents" }, + "permissions" : [ + { "permissionKey": "add", "setting": "allow" }, + { "permissionKey": "remove", "setting": "allow" }, + { "permissionKey": "share", "setting": "block" } + ] +}' +*/ + diff --git a/basics/basics-kotlin/src/main/kotlin/events_processing/UserUpdatesService.kt b/basics/basics-kotlin/src/main/kotlin/events_processing/UserUpdatesService.kt new file mode 100644 index 00000000..b604294a --- /dev/null +++ b/basics/basics-kotlin/src/main/kotlin/events_processing/UserUpdatesService.kt @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2024 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Restate Examples + * which is released under the MIT license. + * + * You can find a copy of the license in the file LICENSE + * in the root directory of this repository or package or at + * https://github.com/restatedev/examples/blob/main/LICENSE + */ +package events_processing + +import dev.restate.sdk.annotation.Handler +import dev.restate.sdk.annotation.VirtualObject +import dev.restate.sdk.http.vertx.RestateHttpEndpointBuilder +import dev.restate.sdk.kotlin.* +import utils.* +import kotlin.time.Duration.Companion.seconds + +// +// Processing events (from Kafka) to update various downstream systems. +// - Journaling actions in Restate and driving retries from Restate, recovering +// partial progress +// - Preserving the order-per-key, but otherwise allowing high-fanout, because +// processing of events does not block other events. +// - Ability to delay events when the downstream systems are busy, without blocking +// entire partitions. +// +@VirtualObject +class UserUpdatesService { + /* + * uses the Event's key (populated for example from Kafka's key) to route the events to the correct Virtual Object. + * And ensures that events with the same key are processed one after the other. + */ + @Handler + suspend fun updateUserEvent(ctx: ObjectContext, update: UserUpdate) { + // event handler is a durably executed function that can use all the features of Restate + + var userId = ctx.runBlock { updateUserProfile(update.profile) } + while (userId == "NOT_READY") { + // Delay the processing of the event by sleeping. + // The other events for this Virtual Object / key are queued. + // Events for other keys are processed concurrently. + // The sleep suspends the function (e.g., when running on FaaS). + ctx.sleep(5.seconds) + userId = ctx.runBlock { updateUserProfile(update.profile) } + } + + + val finalUserId = userId + val roleId = ctx.runBlock { setUserPermissions(finalUserId, update.permissions) } + ctx.runBlock { provisionResources(finalUserId, roleId, update.resources) } + } + +} + +fun main() { + RestateHttpEndpointBuilder.builder() + .bind(UserUpdatesService()) + .buildAndListen() +} diff --git a/basics/basics-kotlin/src/main/kotlin/events_state/ProfileService.kt b/basics/basics-kotlin/src/main/kotlin/events_state/ProfileService.kt new file mode 100644 index 00000000..41056247 --- /dev/null +++ b/basics/basics-kotlin/src/main/kotlin/events_state/ProfileService.kt @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2024 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Restate Examples + * which is released under the MIT license. + * + * You can find a copy of the license in the file LICENSE + * in the root directory of this repository or package or at + * https://github.com/restatedev/examples/blob/main/LICENSE + */ +package events_state + +import dev.restate.sdk.annotation.Handler +import dev.restate.sdk.annotation.VirtualObject +import dev.restate.sdk.http.vertx.RestateHttpEndpointBuilder +import dev.restate.sdk.kotlin.* +import utils.* + +// +// Populate state from events (from Kafka). +// Query the state via simple RPC/HTTP calls. +// +@VirtualObject +class ProfileService { + + // store in state the user's information as coming from the registration event + @Handler + suspend fun registration(ctx: ObjectContext, name: String) = + ctx.set(NAME, name) + + // store in state the user's information as coming from the email event + @Handler + suspend fun email(ctx: ObjectContext, email: String) = + ctx.set(EMAIL, email) + + // Get user profile + @Handler + suspend fun get(ctx: ObjectContext): UserProfile = + UserProfile( + ctx.key(), + ctx.get(NAME) ?: "", + ctx.get(EMAIL) ?: "" + ) +} + +private val NAME = KtStateKey.json("name") +private val EMAIL = KtStateKey.json("email") + +fun main() { + RestateHttpEndpointBuilder.builder() + .bind(ProfileService()) + .buildAndListen() +} diff --git a/basics/basics-kotlin/src/main/kotlin/utils/data_structures.kt b/basics/basics-kotlin/src/main/kotlin/utils/data_structures.kt new file mode 100644 index 00000000..32d63838 --- /dev/null +++ b/basics/basics-kotlin/src/main/kotlin/utils/data_structures.kt @@ -0,0 +1,21 @@ +package utils + +import kotlinx.serialization.Serializable + +@Serializable +data class UserRole(val roleKey: String, val roleDescription: String) + +@Serializable +data class Permission(val permissionKey: String, val setting: String) + +@Serializable +data class UpdateRequest(val userId: String, val role: UserRole, val permissions: List) + +@Serializable +data class User(val email: String, val name: String) + +@Serializable +data class UserProfile(val id: String, val name: String, val email: String) + +@Serializable +data class UserUpdate(val profile: String, val permissions: String, val resources: String) \ No newline at end of file diff --git a/basics/basics-kotlin/src/main/kotlin/utils/stubs.kt b/basics/basics-kotlin/src/main/kotlin/utils/stubs.kt new file mode 100644 index 00000000..c586c6f9 --- /dev/null +++ b/basics/basics-kotlin/src/main/kotlin/utils/stubs.kt @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2024 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Restate Examples + * which is released under the MIT license. + * + * You can find a copy of the license in the file LICENSE + * in the root directory of this repository or package or at + * https://github.com/restatedev/examples/blob/main/LICENSE + */ +package utils + +import dev.restate.sdk.common.TerminalException +import org.apache.logging.log4j.LogManager + +private val logger = LogManager.getLogger("stubs") + +fun applyUserRole(userId: String, role: UserRole?): Boolean { + maybeCrash(0.3) + logger.info(">>> Applying role $role to user $userId") + return true +} + +fun applyPermission(userId: String, permission: Permission) { + maybeCrash(0.2) + logger.info(">>> Applying permission ${permission.permissionKey}:${permission.setting} for user $userId") +} + +fun getCurrentRole(userId: String): UserRole { + return UserRole("viewer", "User cannot do much") +} + +fun tryApplyUserRole(userId: String, role: UserRole) { + maybeCrash(0.3) + + if (role.roleKey != "viewer") { + applicationError(0.3, "Role ${role.roleKey} is not possible for user $userId") + } + logger.error(">>> Applying role $role to user $userId") +} + +fun tryApplyPermission(userId: String, permission: Permission): Permission { + maybeCrash(0.3) + + if (permission.setting != "blocked") { + applicationError( + 0.4, + "Could not apply permission ${permission.permissionKey}:${permission.setting} for user$userId due to a conflict." + ) + } + logger.info(">>> Applying permission ${permission.permissionKey}:${permission.setting} for user $userId") + + return Permission(permission.permissionKey, "blocked") +} + +fun updateUserProfile(profile: String): String { + return if (Math.random() < 0.8) "NOT_READY" else "$profile-id" +} + +fun setUserPermissions(userId: String, permissions: String): String { + return permissions +} + +fun provisionResources(userId: String, role: String, resources: String) {} + +fun createUserEntry(user: User) { +} + +fun sendEmailWithLink(email: String, secret: String) { +} + +private val killProcess: Boolean = System.getenv("CRASH_PROCESS") != null + +fun maybeCrash(probability: Double) { + if (Math.random() < probability) { + logger.error("A failure happened!") + + if (killProcess) { + logger.error("--- CRASHING THE PROCESS ---") + System.exit(1) + } else { + throw RuntimeException("A failure happened!") + } + } +} + +fun applicationError(probability: Double, message: String) { + if (Math.random() < probability) { + logger.error("Action failed: $message") + throw TerminalException(message) + } +} \ No newline at end of file diff --git a/basics/basics-kotlin/src/main/kotlin/virtual_objects/GreeterObject.kt b/basics/basics-kotlin/src/main/kotlin/virtual_objects/GreeterObject.kt new file mode 100644 index 00000000..35df9162 --- /dev/null +++ b/basics/basics-kotlin/src/main/kotlin/virtual_objects/GreeterObject.kt @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2024 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Restate Examples + * which is released under the MIT license. + * + * You can find a copy of the license in the file LICENSE + * in the root directory of this repository or package or at + * https://github.com/restatedev/examples/blob/main/LICENSE + */ +package virtual_objects + +import dev.restate.sdk.annotation.Handler +import dev.restate.sdk.annotation.VirtualObject +import dev.restate.sdk.http.vertx.RestateHttpEndpointBuilder +import dev.restate.sdk.kotlin.KtStateKey +import dev.restate.sdk.kotlin.ObjectContext + +// +// Virtual Objects hold state and have methods to interact with the object. +// An object is identified by a unique id - only one object exists per id. +// +// Virtual Objects have their state locally accessible without requiring any database +// connection or lookup. State is exclusive, and atomically committed with the +// method execution. +// +// Virtual Objects are _Stateful Serverless_ constructs. +// +@VirtualObject +class GreeterObject { + @Handler + suspend fun greet(ctx: ObjectContext, greeting: String): String { + // Access the state attached to this object (this 'name') + // State access and updates are exclusive and consistent with the invocations + + val count = ctx.get(COUNT) ?: 0 + val newCount = count + 1 + ctx.set(COUNT, newCount) + + return "$greeting ${ctx.key()}, for the $newCount-th time" + } + + @Handler + suspend fun ungreet(ctx: ObjectContext): String { + val count = ctx.get(COUNT) ?: 0 + if (count > 0) { + val newCount = count - 1 + ctx.set(COUNT, newCount) + } + + return "Dear ${ctx.key()}, taking one greeting back: $count" + } +} + +private val COUNT = KtStateKey.json("available-drivers") + +fun main() { + RestateHttpEndpointBuilder.builder() + .bind(GreeterObject()) + .buildAndListen() +} + +// See README for details on how to start and connect to Restate. +// Call this service through HTTP directly the following way: +// Example1: `curl localhost:8080/GreeterObject/mary/greet -H 'content-type: application/json' -d '"Hi"'`; +// Example2: `curl localhost:8080/GreeterObject/barack/greet -H 'content-type: application/json' -d '"Hello"'`; +// Example3: `curl localhost:8080/GreeterObject/mary/ungreet -H 'content-type: application/json' -d ''`; + diff --git a/basics/basics-kotlin/src/main/kotlin/workflows/SignupWorkflow.kt b/basics/basics-kotlin/src/main/kotlin/workflows/SignupWorkflow.kt new file mode 100644 index 00000000..972be617 --- /dev/null +++ b/basics/basics-kotlin/src/main/kotlin/workflows/SignupWorkflow.kt @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2024 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Restate Examples for the Node.js/TypeScript SDK, + * which is released under the MIT license. + * + * You can find a copy of the license in the file LICENSE + * in the root directory of this repository or package or at + * https://github.com/restatedev/examples/blob/main/LICENSE + */ +package workflows + +import dev.restate.sdk.annotation.Handler +import dev.restate.sdk.annotation.Shared +import dev.restate.sdk.annotation.VirtualObject +import dev.restate.sdk.annotation.Workflow +import dev.restate.sdk.http.vertx.RestateHttpEndpointBuilder +import dev.restate.sdk.kotlin.* +import utils.* + +// +// A simple workflow for a user signup and email verification. +// +// - the main workflow is in the run() method +// - any number of other methods can be added to implement interactions +// with the workflow. +// +// Workflow instances always have a unique ID that identifies the workflow execution. +// Each workflow instance (ID) can run only once (to success or failure). +// +@Workflow +class SignupWorkflow { + @Workflow + suspend fun run(ctx: WorkflowContext, user: User): Boolean { + // Durably executed action; write to other system + ctx.runBlock { createUserEntry(user) } + + // Store some K/V state; can be retrieved from other handlers + ctx.set(ONBOARDING_STATUS, "Created user") + + // Sent user email with verification link + val secret = ctx.random().nextUUID().toString() + ctx.runBlock { sendEmailWithLink(user.email, secret) } + ctx.set(ONBOARDING_STATUS, "Verifying user") + + // Wait until user clicked email verification link + // Resolved or rejected by the other handlers + val clickSecret: String = + ctx.promise(EMAIL_CLICKED) + .awaitable() + .await() + ctx.set(ONBOARDING_STATUS, "Link clicked") + + return clickSecret == secret + } + + + @Shared + suspend fun click(ctx: SharedWorkflowContext, secret: String) { + // Resolve the promise with the result secret + ctx.promiseHandle(EMAIL_CLICKED).resolve(secret) + } + + // Get the onboarding status of the user + @Shared + suspend fun getStatus(ctx: SharedWorkflowContext) = + ctx.get(ONBOARDING_STATUS) ?: "Unknown" + +} + +private val EMAIL_CLICKED = KtDurablePromiseKey.json("email_clicked") +private val ONBOARDING_STATUS = KtStateKey.json("status") + +fun main() { + RestateHttpEndpointBuilder.builder() + .bind(SignupWorkflow()) + .buildAndListen() +} diff --git a/basics/basics-kotlin/src/main/resources/log4j2.properties b/basics/basics-kotlin/src/main/resources/log4j2.properties new file mode 100644 index 00000000..536d1d39 --- /dev/null +++ b/basics/basics-kotlin/src/main/resources/log4j2.properties @@ -0,0 +1,26 @@ +# Set to debug or trace if log4j initialization is failing +status = warn + +# Console appender configuration +appender.console.type = Console +appender.console.name = consoleLogger +appender.console.layout.type = PatternLayout +appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %notEmpty{[%X{restateInvocationTarget}]}%notEmpty{[%X{restateInvocationId}]} %c - %m%n + +# Filter out logging during replay +appender.console.filter.replay.type = ContextMapFilter +appender.console.filter.replay.onMatch = DENY +appender.console.filter.replay.onMismatch = NEUTRAL +appender.console.filter.replay.0.type = KeyValuePair +appender.console.filter.replay.0.key = restateInvocationStatus +appender.console.filter.replay.0.value = REPLAYING + +# Restate logs to debug level +logger.app.name = dev.restate +logger.app.level = info +logger.app.additivity = false +logger.app.appenderRef.console.ref = consoleLogger + +# Root logger +rootLogger.level = info +rootLogger.appenderRef.stdout.ref = consoleLogger \ No newline at end of file