diff --git a/.github/workflows/pre-release.yml b/.github/workflows/pre-release.yml index 284143d1..d18642fa 100644 --- a/.github/workflows/pre-release.yml +++ b/.github/workflows/pre-release.yml @@ -57,7 +57,7 @@ jobs: # When adding a new example make sure it's listed here - name: Find and replace restateVersion in build.gradle.kts for java templates if: github.event.inputs.sdkJavaVersion != '' - run: for jvmDir in hello-world-http hello-world-lambda food-ordering/app patterns; do sed -i 's/val restateVersion = "[0-9A-Z.-]*"/val restateVersion = "${{ inputs.sdkJavaVersion }}"/' java/$jvmDir/build.gradle.kts; done + run: for jvmDir in hello-world-http hello-world-lambda food-ordering/app tour-of-restate patterns; do sed -i 's/val restateVersion = "[0-9A-Z.-]*"/val restateVersion = "${{ inputs.sdkJavaVersion }}"/' java/$jvmDir/build.gradle.kts; done - name: Find and replace restateVersion in build.gradle.kts for kotlin templates if: github.event.inputs.sdkJavaVersion != '' run: for jvmDir in hello-world-http hello-world-lambda; do sed -i 's/val restateVersion = "[0-9A-Z.-]*"/val restateVersion = "${{ inputs.sdkJavaVersion }}"/' kotlin/$jvmDir/build.gradle.kts; done @@ -90,6 +90,12 @@ jobs: with: arguments: check build-root-directory: java/patterns + - name: Test java/tour-of-restate + if: github.event.inputs.sdkJavaVersion != '' + uses: gradle/gradle-build-action@v2 + with: + arguments: check + build-root-directory: java/tour-of-restate - name: Test kotlin/hello-world-http if: github.event.inputs.sdkJavaVersion != '' uses: gradle/gradle-build-action@v2 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 29814030..c89cfcf4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -35,6 +35,7 @@ jobs: java-hello-world-http.zip java-hello-world-lambda.zip java-food-ordering.zip + java-tour-of-restate.zip kotlin-hello-world-http.zip kotlin-hello-world-lambda.zip kotlin-hello-world-lambda-cdk.zip \ No newline at end of file diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index d107cfc5..cfa1b204 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -45,6 +45,11 @@ jobs: with: arguments: check build-root-directory: java/patterns + - name: Test java/tour-of-restate + uses: gradle/gradle-build-action@v2 + with: + arguments: check + build-root-directory: java/tour-of-restate - name: Test kotlin/hello-world-http uses: gradle/gradle-build-action@v2 with: diff --git a/README.md b/README.md index 40ee6bee..e8249888 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,11 @@ Browse this repository to see how easy distributed applications development beco | Kotlin | [Hello world on AWS Lambda](kotlin/hello-world-lambda) | | Kotlin | [Hello world on AWS Lambda + CDK](kotlin/hello-world-lambda-cdk) | +## Tutorials +| Language | Name / Link | +|----------|-----------------------------------------| +| Java | [Tour of Restate](java/tour-of-restate) | + ## Patterns | Language | Name / Link | @@ -119,3 +124,5 @@ Before releasing, trigger the "pre-release" workflow to update sdk versions. Thi Once the repo is ready for the release, push a tag of the form `vX.Y.Z`. This triggers a workflow that [creates a draft release](https://github.com/restatedev/examples/releases) on Github, which you need to approve to finalize it. + +Please update the version tag referenced on the [Tour of Restate](https://github.com/restatedev/documentation/blob/main/docs/tour.mdx) documentation page. diff --git a/java/README.md b/java/README.md index b16a6e60..39b49f8a 100644 --- a/java/README.md +++ b/java/README.md @@ -8,6 +8,11 @@ This directory contains Restate examples using the Java SDK. | Java | [Hello World HTTP](hello-world-http) | | Java | [Hello world on AWS Lambda](hello-world-lambda) | +## Tutorials +| Language | Name / Link | +|----------|-----------------------------------------| +| Java | [Tour of Restate](java/tour-of-restate) | + ## Patterns | Language | Name / Link | diff --git a/java/tour-of-restate/.gitignore b/java/tour-of-restate/.gitignore new file mode 100644 index 00000000..835e8dca --- /dev/null +++ b/java/tour-of-restate/.gitignore @@ -0,0 +1,3 @@ +.gradle +.idea +build \ No newline at end of file diff --git a/java/tour-of-restate/README.md b/java/tour-of-restate/README.md new file mode 100644 index 00000000..4ca0a728 --- /dev/null +++ b/java/tour-of-restate/README.md @@ -0,0 +1,41 @@ +# A Tour of Restate with Java + +Restate is a system for easily building resilient applications using **distributed durable RPC & async/await**. + +This example contains the code for the `Tour of Restate` tutorial, for the Java SDK. +This tutorial takes your through key Restate features by developing an end-to-end ticketing app. + +❓ Learn more about Restate from the [Restate documentation](https://docs.restate.dev). + + +## Download the example + +- Via the CLI: + ```shell + restate example java-tour-of-restate && cd java-tour-of-restate + ``` + +- Via git clone: + ```shell + git clone git@github.com:restatedev/examples.git + cd examples/java/tour-of-restate + ``` + +- Via `wget`: + ```shell + wget https://github.com/restatedev/examples/releases/latest/download/java-tour-of-restate.zip && unzip java-tour-of-restate.zip -d java-tour-of-restate && rm java-tour-of-restate.zip + ``` + +## Running the example + +Have a look at the [Tour of Restate tutorial](https://docs.restate.dev/tour) in the documentation to build and run the application in this repository. + +In short, you can run the different parts of the code via: + +```typescript +./gradlew run +./gradlew -PmainClass=dev.restate.tour.part1.AppMain run +./gradlew -PmainClass=dev.restate.tour.part2.AppMain run +./gradlew -PmainClass=dev.restate.tour.part3.AppMain run +./gradlew -PmainClass=dev.restate.tour.part4.AppMain run +``` diff --git a/java/tour-of-restate/build.gradle.kts b/java/tour-of-restate/build.gradle.kts new file mode 100644 index 00000000..6ac2fea4 --- /dev/null +++ b/java/tour-of-restate/build.gradle.kts @@ -0,0 +1,62 @@ +import com.google.protobuf.gradle.id + +plugins { + java + application + + id("com.google.protobuf") version "0.9.1" +} + +repositories { + mavenCentral() +} + +val restateSdkVersion = "0.7.0" + +dependencies { + // Restate SDK + implementation("dev.restate:sdk-api:$restateSdkVersion") + implementation("dev.restate:sdk-http-vertx:$restateSdkVersion") + // To use Jackson to read/write state entries (optional) + implementation("dev.restate:sdk-serde-jackson:$restateSdkVersion") + + // Protobuf and grpc dependencies + implementation("com.google.protobuf:protobuf-java:3.24.3") + implementation("io.grpc:grpc-stub:1.58.0") + implementation("io.grpc:grpc-protobuf:1.58.0") + // This is needed to compile the @Generated annotation forced by the grpc compiler + // See https://github.com/grpc/grpc-java/issues/9153 + compileOnly("org.apache.tomcat:annotations-api:6.0.53") + + // Logging (optional) + implementation("org.apache.logging.log4j:log4j-core:2.20.0") +} + +// Configure protoc plugin +protobuf { + protoc { artifact = "com.google.protobuf:protoc:3.24.3" } + + // We need both grpc and restate codegen(s) because the restate codegen depends on the grpc one + plugins { + id("grpc") { artifact = "io.grpc:protoc-gen-grpc-java:1.58.0" } + id("restate") { artifact = "dev.restate:protoc-gen-restate:$restateSdkVersion:all@jar" } + } + + generateProtoTasks { + all().forEach { + it.plugins { + id("grpc") + id("restate") + } + } + } +} + +// Set main class +application { + if (project.hasProperty("mainClass")) { + mainClass.set(project.property("mainClass") as String); + } else { + mainClass.set("dev.restate.tour.app.AppMain") + } +} diff --git a/java/tour-of-restate/gradle/wrapper/gradle-wrapper.jar b/java/tour-of-restate/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..033e24c4 Binary files /dev/null and b/java/tour-of-restate/gradle/wrapper/gradle-wrapper.jar differ diff --git a/java/tour-of-restate/gradle/wrapper/gradle-wrapper.properties b/java/tour-of-restate/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..62f495df --- /dev/null +++ b/java/tour-of-restate/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/java/tour-of-restate/gradlew b/java/tour-of-restate/gradlew new file mode 100755 index 00000000..fcb6fca1 --- /dev/null +++ b/java/tour-of-restate/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/java/tour-of-restate/gradlew.bat b/java/tour-of-restate/gradlew.bat new file mode 100644 index 00000000..6689b85b --- /dev/null +++ b/java/tour-of-restate/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/java/tour-of-restate/src/main/java/dev/restate/tour/app/AppMain.java b/java/tour-of-restate/src/main/java/dev/restate/tour/app/AppMain.java new file mode 100644 index 00000000..8d4e0d14 --- /dev/null +++ b/java/tour-of-restate/src/main/java/dev/restate/tour/app/AppMain.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2023 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Tour of Restate Java, + * 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/tour-of-restate + */ + +package dev.restate.tour.app; + +import dev.restate.sdk.http.vertx.RestateHttpEndpointBuilder; + +public class AppMain { + public static void main(String[] args) { + RestateHttpEndpointBuilder.builder() + .withService(new Checkout()) + .withService(new TicketService()) + .withService(new UserSession()) + .buildAndListen(); + } +} diff --git a/java/tour-of-restate/src/main/java/dev/restate/tour/app/Checkout.java b/java/tour-of-restate/src/main/java/dev/restate/tour/app/Checkout.java new file mode 100644 index 00000000..2a09aa32 --- /dev/null +++ b/java/tour-of-restate/src/main/java/dev/restate/tour/app/Checkout.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2023 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Tour of Restate Java, + * 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/tour-of-restate + */ + +package dev.restate.tour.app; + +import com.google.protobuf.BoolValue; +import dev.restate.sdk.RestateContext; +import dev.restate.sdk.common.TerminalException; +import dev.restate.tour.generated.CheckoutRestate; +import dev.restate.tour.generated.Tour.CheckoutFlowRequest; + +public class Checkout extends CheckoutRestate.CheckoutRestateImplBase { + @Override + public BoolValue checkout(RestateContext ctx, CheckoutFlowRequest request) throws TerminalException { + return BoolValue.of(true); + } +} diff --git a/java/tour-of-restate/src/main/java/dev/restate/tour/app/TicketService.java b/java/tour-of-restate/src/main/java/dev/restate/tour/app/TicketService.java new file mode 100644 index 00000000..6426d628 --- /dev/null +++ b/java/tour-of-restate/src/main/java/dev/restate/tour/app/TicketService.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2023 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Tour of Restate Java, + * 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/tour-of-restate + */ + +package dev.restate.tour.app; + +import com.google.protobuf.BoolValue; +import dev.restate.sdk.RestateContext; +import dev.restate.sdk.common.TerminalException; +import dev.restate.tour.generated.TicketServiceRestate; +import dev.restate.tour.generated.Tour.Ticket; + +public class TicketService extends TicketServiceRestate.TicketServiceRestateImplBase { + @Override + public BoolValue reserve(RestateContext ctx, Ticket request) throws TerminalException { + return BoolValue.of(true); + } + + @Override + public void unreserve(RestateContext ctx, Ticket request) throws TerminalException { + } + + @Override + public void markAsSold(RestateContext ctx, Ticket request) throws TerminalException { + } +} diff --git a/java/tour-of-restate/src/main/java/dev/restate/tour/app/UserSession.java b/java/tour-of-restate/src/main/java/dev/restate/tour/app/UserSession.java new file mode 100644 index 00000000..574cd3ff --- /dev/null +++ b/java/tour-of-restate/src/main/java/dev/restate/tour/app/UserSession.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2023 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Tour of Restate Java, + * 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/tour-of-restate + */ + +package dev.restate.tour.app; + +import com.google.protobuf.BoolValue; +import dev.restate.sdk.RestateContext; +import dev.restate.sdk.common.TerminalException; +import dev.restate.tour.generated.Tour.CheckoutRequest; +import dev.restate.tour.generated.Tour.ExpireTicketRequest; +import dev.restate.tour.generated.Tour.ReserveTicket; +import dev.restate.tour.generated.UserSessionRestate; + +public class UserSession extends UserSessionRestate.UserSessionRestateImplBase { + @Override + public BoolValue addTicket(RestateContext ctx, ReserveTicket request) throws TerminalException { + return BoolValue.of(true); + } + + @Override + public void expireTicket(RestateContext ctx, ExpireTicketRequest request) throws TerminalException { + } + + @Override + public BoolValue checkout(RestateContext ctx, CheckoutRequest request) throws TerminalException { + return BoolValue.of(true); + } +} \ No newline at end of file diff --git a/java/tour-of-restate/src/main/java/dev/restate/tour/auxiliary/EmailClient.java b/java/tour-of-restate/src/main/java/dev/restate/tour/auxiliary/EmailClient.java new file mode 100644 index 00000000..65d120c9 --- /dev/null +++ b/java/tour-of-restate/src/main/java/dev/restate/tour/auxiliary/EmailClient.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2023 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Tour of Restate Java, + * 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/tour-of-restate + */ + +package dev.restate.tour.auxiliary; + +public class EmailClient { + public static EmailClient get() { + return new EmailClient(); + } + + public boolean notifyUserOfPaymentSuccess(String userId) { + System.out.println("Notifying user " + userId + " of payment success"); + // send the email + return true; + } + + public boolean notifyUserOfPaymentFailure(String userId) { + System.out.println("Notifying user " + userId + " of payment failure"); + // send the email + return true; + } +} \ No newline at end of file diff --git a/java/tour-of-restate/src/main/java/dev/restate/tour/auxiliary/PaymentClient.java b/java/tour-of-restate/src/main/java/dev/restate/tour/auxiliary/PaymentClient.java new file mode 100644 index 00000000..7e937978 --- /dev/null +++ b/java/tour-of-restate/src/main/java/dev/restate/tour/auxiliary/PaymentClient.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2023 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Tour of Restate Java, + * 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/tour-of-restate + */ + +package dev.restate.tour.auxiliary; + +public class PaymentClient { + private static int i = 0; + + public static PaymentClient get() { + return new PaymentClient(); + } + + public boolean call(String idempotencyKey, double amount) { + System.out.println("Payment call succeeded for idempotency key " + idempotencyKey + " and amount " + amount); + // do the call + return true; + } + + public boolean failingCall(String idempotencyKey, double amount) { + if (i >= 2) { + System.out.println("Payment call succeeded for idempotency key " + idempotencyKey + " and amount " + amount); + i = 0; + return true; + } else { + System.out.println("Payment call failed for idempotency key " + idempotencyKey + " and amount " + amount + ". Retrying..."); + i = i + 1; + throw new IllegalStateException("Payment call failed"); + } + } +} diff --git a/java/tour-of-restate/src/main/java/dev/restate/tour/auxiliary/TicketStatus.java b/java/tour-of-restate/src/main/java/dev/restate/tour/auxiliary/TicketStatus.java new file mode 100644 index 00000000..1cb4f68f --- /dev/null +++ b/java/tour-of-restate/src/main/java/dev/restate/tour/auxiliary/TicketStatus.java @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2023 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Tour of Restate Java, + * 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/tour-of-restate + */ + +package dev.restate.tour.auxiliary; + +public enum TicketStatus { + Available, + Reserved, + Sold +} \ No newline at end of file diff --git a/java/tour-of-restate/src/main/java/dev/restate/tour/part1/AppMain.java b/java/tour-of-restate/src/main/java/dev/restate/tour/part1/AppMain.java new file mode 100644 index 00000000..f0d051da --- /dev/null +++ b/java/tour-of-restate/src/main/java/dev/restate/tour/part1/AppMain.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2023 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Tour of Restate Java, + * 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/tour-of-restate + */ + +package dev.restate.tour.part1; + +import dev.restate.sdk.http.vertx.RestateHttpEndpointBuilder; + +public class AppMain { + public static void main(String[] args) { + RestateHttpEndpointBuilder.builder() + .withService(new Checkout()) + .withService(new TicketService()) + .withService(new UserSession()) + .buildAndListen(); + } +} diff --git a/java/tour-of-restate/src/main/java/dev/restate/tour/part1/Checkout.java b/java/tour-of-restate/src/main/java/dev/restate/tour/part1/Checkout.java new file mode 100644 index 00000000..8eb1936c --- /dev/null +++ b/java/tour-of-restate/src/main/java/dev/restate/tour/part1/Checkout.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2023 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Tour of Restate Java, + * 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/tour-of-restate + */ + +package dev.restate.tour.part1; + +import com.google.protobuf.BoolValue; +import dev.restate.sdk.RestateContext; +import dev.restate.sdk.common.TerminalException; +import dev.restate.tour.generated.CheckoutRestate; +import dev.restate.tour.generated.Tour.CheckoutFlowRequest; + +public class Checkout extends CheckoutRestate.CheckoutRestateImplBase { + @Override + public BoolValue checkout(RestateContext ctx, CheckoutFlowRequest request) throws TerminalException { + return BoolValue.of(true); + } +} diff --git a/java/tour-of-restate/src/main/java/dev/restate/tour/part1/TicketService.java b/java/tour-of-restate/src/main/java/dev/restate/tour/part1/TicketService.java new file mode 100644 index 00000000..c062aca6 --- /dev/null +++ b/java/tour-of-restate/src/main/java/dev/restate/tour/part1/TicketService.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2023 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Tour of Restate Java, + * 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/tour-of-restate + */ + +package dev.restate.tour.part1; + +import com.google.protobuf.BoolValue; +import dev.restate.sdk.RestateContext; +import dev.restate.sdk.common.TerminalException; +import dev.restate.tour.generated.TicketServiceRestate; +import dev.restate.tour.generated.Tour.Ticket; + +import java.time.Duration; + +public class TicketService extends TicketServiceRestate.TicketServiceRestateImplBase { + + @Override + public BoolValue reserve(RestateContext ctx, Ticket request) throws TerminalException { + ctx.sleep(Duration.ofSeconds(35)); + return BoolValue.of(true); + } + + @Override + public void unreserve(RestateContext ctx, Ticket request) throws TerminalException { + } + + @Override + public void markAsSold(RestateContext ctx, Ticket request) throws TerminalException { + } +} diff --git a/java/tour-of-restate/src/main/java/dev/restate/tour/part1/UserSession.java b/java/tour-of-restate/src/main/java/dev/restate/tour/part1/UserSession.java new file mode 100644 index 00000000..3136ed40 --- /dev/null +++ b/java/tour-of-restate/src/main/java/dev/restate/tour/part1/UserSession.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2023 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Tour of Restate Java, + * 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/tour-of-restate + */ + +package dev.restate.tour.part1; + +import com.google.protobuf.BoolValue; +import dev.restate.sdk.RestateContext; +import dev.restate.sdk.common.TerminalException; +import dev.restate.tour.generated.CheckoutRestate; +import dev.restate.tour.generated.TicketServiceRestate; +import dev.restate.tour.generated.Tour.*; +import dev.restate.tour.generated.UserSessionRestate; + +public class UserSession extends UserSessionRestate.UserSessionRestateImplBase { + @Override + public BoolValue addTicket(RestateContext ctx, ReserveTicket request) throws TerminalException { + var ticketClnt = TicketServiceRestate.newClient(ctx); + ticketClnt.oneWay().reserve(Ticket.newBuilder().setTicketId(request.getTicketId()).build()); + + return BoolValue.of(true); + } + + @Override + public void expireTicket(RestateContext ctx, ExpireTicketRequest request) throws TerminalException { + var ticketClnt = TicketServiceRestate.newClient(ctx); + ticketClnt.oneWay().unreserve(Ticket.newBuilder().setTicketId(request.getTicketId()).build()); + } + + @Override + public BoolValue checkout(RestateContext ctx, CheckoutRequest request) throws TerminalException { + var checkoutClnt = CheckoutRestate.newClient(ctx); + var checkoutSuccess = checkoutClnt.checkout( + CheckoutFlowRequest.newBuilder().setUserId(request.getUserId()).addTickets("456").build() + ).await(); + + return checkoutSuccess; + } + +} diff --git a/java/tour-of-restate/src/main/java/dev/restate/tour/part2/AppMain.java b/java/tour-of-restate/src/main/java/dev/restate/tour/part2/AppMain.java new file mode 100644 index 00000000..14186dcc --- /dev/null +++ b/java/tour-of-restate/src/main/java/dev/restate/tour/part2/AppMain.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2023 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Tour of Restate Java, + * 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/tour-of-restate + */ + +package dev.restate.tour.part2; + +import dev.restate.sdk.http.vertx.RestateHttpEndpointBuilder; + +public class AppMain { + public static void main(String[] args) { + RestateHttpEndpointBuilder.builder() + .withService(new Checkout()) + .withService(new TicketService()) + .withService(new UserSession()) + .buildAndListen(); + } +} diff --git a/java/tour-of-restate/src/main/java/dev/restate/tour/part2/Checkout.java b/java/tour-of-restate/src/main/java/dev/restate/tour/part2/Checkout.java new file mode 100644 index 00000000..928dd25d --- /dev/null +++ b/java/tour-of-restate/src/main/java/dev/restate/tour/part2/Checkout.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2023 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Tour of Restate Java, + * 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/tour-of-restate + */ + +package dev.restate.tour.part2; + +import com.google.protobuf.BoolValue; +import dev.restate.sdk.RestateContext; +import dev.restate.sdk.common.CoreSerdes; +import dev.restate.sdk.common.TerminalException; +import dev.restate.tour.generated.CheckoutRestate; +import dev.restate.tour.generated.Tour.CheckoutFlowRequest; + +import java.time.Duration; +import java.util.UUID; + +public class Checkout extends CheckoutRestate.CheckoutRestateImplBase { + @Override + public BoolValue checkout(RestateContext ctx, CheckoutFlowRequest request) throws TerminalException { + return BoolValue.of(true); + } +} diff --git a/java/tour-of-restate/src/main/java/dev/restate/tour/part2/TicketService.java b/java/tour-of-restate/src/main/java/dev/restate/tour/part2/TicketService.java new file mode 100644 index 00000000..58a2e07c --- /dev/null +++ b/java/tour-of-restate/src/main/java/dev/restate/tour/part2/TicketService.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2023 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Tour of Restate Java, + * 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/tour-of-restate + */ + +package dev.restate.tour.part2; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.google.protobuf.BoolValue; +import dev.restate.sdk.RestateContext; +import dev.restate.sdk.common.CoreSerdes; +import dev.restate.sdk.common.StateKey; +import dev.restate.sdk.common.TerminalException; +import dev.restate.sdk.serde.jackson.JacksonSerdes; +import dev.restate.tour.auxiliary.PaymentClient; +import dev.restate.tour.auxiliary.TicketStatus; +import dev.restate.tour.generated.TicketServiceRestate; +import dev.restate.tour.generated.Tour.Ticket; +import io.grpc.Status; + +public class TicketService extends TicketServiceRestate.TicketServiceRestateImplBase { + public static final StateKey STATE_KEY = StateKey.of("status", JacksonSerdes.of(TicketStatus.class)); + + @Override + public BoolValue reserve(RestateContext ctx, Ticket request) throws TerminalException { + var status = ctx.get(STATE_KEY).orElse(TicketStatus.Available); + + if (status.equals(TicketStatus.Available)) { + ctx.set(STATE_KEY, TicketStatus.Reserved); + return BoolValue.of(true); + } else { + return BoolValue.of(false); + } + } + + @Override + public void unreserve(RestateContext ctx, Ticket request) throws TerminalException { + var status = ctx.get(STATE_KEY).orElse(TicketStatus.Available); + + if (!status.equals(TicketStatus.Sold)) { + ctx.clear(STATE_KEY); + } + } + + @Override + public void markAsSold(RestateContext ctx, Ticket request) throws TerminalException { + var status = ctx.get(STATE_KEY).orElse(TicketStatus.Available); + + if (status.equals(TicketStatus.Reserved)) { + ctx.set(STATE_KEY, TicketStatus.Sold); + } + } +} diff --git a/java/tour-of-restate/src/main/java/dev/restate/tour/part2/UserSession.java b/java/tour-of-restate/src/main/java/dev/restate/tour/part2/UserSession.java new file mode 100644 index 00000000..ab0aa731 --- /dev/null +++ b/java/tour-of-restate/src/main/java/dev/restate/tour/part2/UserSession.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2023 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Tour of Restate Java, + * 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/tour-of-restate + */ + +package dev.restate.tour.part2; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.google.protobuf.BoolValue; +import dev.restate.sdk.RestateContext; +import dev.restate.sdk.common.StateKey; +import dev.restate.sdk.common.TerminalException; +import dev.restate.sdk.serde.jackson.JacksonSerdes; +import dev.restate.tour.generated.*; +import dev.restate.tour.generated.Tour.*; + +import java.time.Duration; +import java.util.HashSet; +import java.util.Set; + +public class UserSession extends UserSessionRestate.UserSessionRestateImplBase { + + + public static final StateKey> STATE_KEY = StateKey.of("tickets", JacksonSerdes.of(new TypeReference<>() {})); + + @Override + public BoolValue addTicket(RestateContext ctx, ReserveTicket request) throws TerminalException { + var ticketClnt = TicketServiceRestate.newClient(ctx); + var reservationSuccess = ticketClnt + .reserve(Ticket.newBuilder().setTicketId(request.getTicketId()).build()) + .await(); + + if (reservationSuccess.getValue()) { + var tickets = ctx.get(STATE_KEY).orElseGet(HashSet::new); + tickets.add(request.getTicketId()); + ctx.set(STATE_KEY, tickets); + + var userSessionClnt = UserSessionRestate.newClient(ctx); + userSessionClnt.delayed(Duration.ofMinutes(15)).expireTicket( + ExpireTicketRequest.newBuilder().setTicketId(request.getTicketId()).setUserId(request.getUserId()).build() + ); + } + + return reservationSuccess; + } + + @Override + public void expireTicket(RestateContext ctx, ExpireTicketRequest request) throws TerminalException { + var tickets = ctx.get(STATE_KEY).orElseGet(HashSet::new); + + var removed = tickets.removeIf(s -> s.equals(request.getTicketId())); + + if (removed) { + ctx.set(STATE_KEY, tickets); + var ticketClnt = TicketServiceRestate.newClient(ctx); + ticketClnt.oneWay().unreserve(Ticket.newBuilder().setTicketId(request.getTicketId()).build()); + } + } + + @Override + public BoolValue checkout(RestateContext ctx, CheckoutRequest request) throws TerminalException { + var tickets = ctx.get(STATE_KEY).orElseGet(HashSet::new); + + if (tickets.isEmpty()) { + return BoolValue.of(false); + } + + var checkoutClnt = CheckoutRestate.newClient(ctx); + var checkoutSuccess = checkoutClnt.checkout( + CheckoutFlowRequest.newBuilder().setUserId(request.getUserId()).addAllTickets(tickets).build() + ).await(); + + if (checkoutSuccess.getValue()) { + ctx.clear(STATE_KEY); + } + + return checkoutSuccess; + } +} diff --git a/java/tour-of-restate/src/main/java/dev/restate/tour/part3/AppMain.java b/java/tour-of-restate/src/main/java/dev/restate/tour/part3/AppMain.java new file mode 100644 index 00000000..09f041cd --- /dev/null +++ b/java/tour-of-restate/src/main/java/dev/restate/tour/part3/AppMain.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2023 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Tour of Restate Java, + * 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/tour-of-restate + */ + +package dev.restate.tour.part3; + +import dev.restate.sdk.http.vertx.RestateHttpEndpointBuilder; + +public class AppMain { + public static void main(String[] args) { + RestateHttpEndpointBuilder.builder() + .withService(new Checkout()) + .withService(new TicketService()) + .withService(new UserSession()) + .buildAndListen(); + } +} diff --git a/java/tour-of-restate/src/main/java/dev/restate/tour/part3/Checkout.java b/java/tour-of-restate/src/main/java/dev/restate/tour/part3/Checkout.java new file mode 100644 index 00000000..d3af335f --- /dev/null +++ b/java/tour-of-restate/src/main/java/dev/restate/tour/part3/Checkout.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2023 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Tour of Restate Java, + * 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/tour-of-restate + */ + +package dev.restate.tour.part3; + +import com.google.protobuf.BoolValue; +import dev.restate.sdk.RestateContext; +import dev.restate.sdk.common.CoreSerdes; +import dev.restate.sdk.common.TerminalException; +import dev.restate.tour.auxiliary.EmailClient; +import dev.restate.tour.auxiliary.PaymentClient; +import dev.restate.tour.generated.CheckoutRestate; +import dev.restate.tour.generated.Tour.CheckoutFlowRequest; + +import java.time.Duration; +import java.util.UUID; + +public class Checkout extends CheckoutRestate.CheckoutRestateImplBase { + + PaymentClient paymentClient = PaymentClient.get(); + EmailClient emailClient = EmailClient.get(); + + @Override + public BoolValue checkout(RestateContext ctx, CheckoutFlowRequest request) throws TerminalException { + // Generate idempotency key for the stripe client + var idempotencyKey = ctx.sideEffect(CoreSerdes.STRING_UTF8, () -> UUID.randomUUID().toString()); + + // We are a uniform shop where everything costs 40 USD + var totalPrice = request.getTicketsList().size() * 40.0; + + boolean success = ctx.sideEffect(CoreSerdes.BOOLEAN, () -> paymentClient.call(idempotencyKey, totalPrice)); + + if (success) { + ctx.sideEffect(()-> emailClient.notifyUserOfPaymentSuccess(request.getUserId())); + } else { + ctx.sideEffect(() -> emailClient.notifyUserOfPaymentFailure(request.getUserId())); + } + + return BoolValue.of(success); + } +} diff --git a/java/tour-of-restate/src/main/java/dev/restate/tour/part3/TicketService.java b/java/tour-of-restate/src/main/java/dev/restate/tour/part3/TicketService.java new file mode 100644 index 00000000..42fae4db --- /dev/null +++ b/java/tour-of-restate/src/main/java/dev/restate/tour/part3/TicketService.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2023 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Tour of Restate Java, + * 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/tour-of-restate + */ + +package dev.restate.tour.part3; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.google.protobuf.BoolValue; +import dev.restate.sdk.RestateContext; +import dev.restate.sdk.common.StateKey; +import dev.restate.sdk.common.TerminalException; +import dev.restate.sdk.serde.jackson.JacksonSerdes; +import dev.restate.tour.auxiliary.TicketStatus; +import dev.restate.tour.generated.TicketServiceRestate; +import dev.restate.tour.generated.Tour.Ticket; + +public class TicketService extends TicketServiceRestate.TicketServiceRestateImplBase { + + public static final StateKey STATE_KEY = StateKey.of("status", JacksonSerdes.of(TicketStatus.class)); + + @Override + public BoolValue reserve(RestateContext ctx, Ticket request) throws TerminalException { + var status = ctx.get(STATE_KEY).orElse(TicketStatus.Available); + + if (status.equals(TicketStatus.Available)) { + ctx.set(STATE_KEY, TicketStatus.Reserved); + return BoolValue.of(true); + } else { + return BoolValue.of(false); + } + } + + @Override + public void unreserve(RestateContext ctx, Ticket request) throws TerminalException { + var status = ctx.get(STATE_KEY).orElse(TicketStatus.Available); + + if (!status.equals(TicketStatus.Sold)) { + ctx.clear(STATE_KEY); + } + } + + @Override + public void markAsSold(RestateContext ctx, Ticket request) throws TerminalException { + var status = ctx.get(STATE_KEY).orElse(TicketStatus.Available); + + if (status.equals(TicketStatus.Reserved)) { + ctx.set(STATE_KEY, TicketStatus.Sold); + } + } +} diff --git a/java/tour-of-restate/src/main/java/dev/restate/tour/part3/UserSession.java b/java/tour-of-restate/src/main/java/dev/restate/tour/part3/UserSession.java new file mode 100644 index 00000000..e522e792 --- /dev/null +++ b/java/tour-of-restate/src/main/java/dev/restate/tour/part3/UserSession.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2023 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Tour of Restate Java, + * 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/tour-of-restate + */ + +package dev.restate.tour.part3; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.google.protobuf.BoolValue; +import dev.restate.sdk.RestateContext; +import dev.restate.sdk.common.StateKey; +import dev.restate.sdk.common.TerminalException; +import dev.restate.sdk.serde.jackson.JacksonSerdes; +import dev.restate.tour.generated.*; +import dev.restate.tour.generated.Tour.*; + +import java.time.Duration; +import java.util.HashSet; +import java.util.Set; + +public class UserSession extends UserSessionRestate.UserSessionRestateImplBase { + + + public static final StateKey> STATE_KEY = StateKey.of("tickets", JacksonSerdes.of(new TypeReference<>() {})); + + @Override + public BoolValue addTicket(RestateContext ctx, ReserveTicket request) throws TerminalException { + var ticketClnt = TicketServiceRestate.newClient(ctx); + var reservationSuccess = ticketClnt + .reserve(Ticket.newBuilder().setTicketId(request.getTicketId()).build()) + .await().getValue(); + + if (reservationSuccess) { + var tickets = ctx.get(STATE_KEY).orElseGet(HashSet::new); + tickets.add(request.getTicketId()); + ctx.set(STATE_KEY, tickets); + + var userSessionClnt = UserSessionRestate.newClient(ctx); + userSessionClnt.delayed(Duration.ofMinutes(15)).expireTicket( + ExpireTicketRequest.newBuilder().setTicketId(request.getTicketId()).setUserId(request.getUserId()).build() + ); + } + + return BoolValue.of(reservationSuccess); + } + + @Override + public void expireTicket(RestateContext ctx, ExpireTicketRequest request) throws TerminalException { + var tickets = ctx.get(STATE_KEY).orElseGet(HashSet::new); + + var removed = tickets.removeIf(s -> s.equals(request.getTicketId())); + + if (removed) { + ctx.set(STATE_KEY, tickets); + var ticketClnt = TicketServiceRestate.newClient(ctx); + ticketClnt.oneWay().unreserve(Ticket.newBuilder().setTicketId(request.getTicketId()).build()); + } + } + + @Override + public BoolValue checkout(RestateContext ctx, CheckoutRequest request) throws TerminalException { + // 1. Retrieve the tickets from state + var tickets = ctx.get(STATE_KEY).orElseGet(HashSet::new); + + // 2. If there are no tickets, return `false` + if (tickets.isEmpty()) { + return BoolValue.of(false); + } + + // 3. Call the `checkout` function of the checkout service with the tickets + var checkoutClnt = CheckoutRestate.newClient(ctx); + var checkoutSuccess = checkoutClnt.checkout( + CheckoutFlowRequest.newBuilder().setUserId(request.getUserId()).addAllTickets(tickets).build() + ).await(); + + // 4. If this was successful, empty the tickets. + // Otherwise, let the user try again. + if (checkoutSuccess.getValue()) { + var ticketClnt = TicketServiceRestate.newClient(ctx); + tickets.forEach(t -> ticketClnt.oneWay().markAsSold(Ticket.newBuilder().setTicketId(t).build())); + ctx.clear(STATE_KEY); + } + + return checkoutSuccess; + } +} diff --git a/java/tour-of-restate/src/main/java/dev/restate/tour/part4/AppMain.java b/java/tour-of-restate/src/main/java/dev/restate/tour/part4/AppMain.java new file mode 100644 index 00000000..8bdf1028 --- /dev/null +++ b/java/tour-of-restate/src/main/java/dev/restate/tour/part4/AppMain.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2023 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Tour of Restate Java, + * 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/tour-of-restate + */ + +package dev.restate.tour.part4; + +import dev.restate.sdk.http.vertx.RestateHttpEndpointBuilder; + +public class AppMain { + public static void main(String[] args) { + RestateHttpEndpointBuilder.builder() + .withService(new Checkout()) + .withService(new TicketService()) + .withService(new UserSession()) + .buildAndListen(); + } +} diff --git a/java/tour-of-restate/src/main/java/dev/restate/tour/part4/Checkout.java b/java/tour-of-restate/src/main/java/dev/restate/tour/part4/Checkout.java new file mode 100644 index 00000000..dbeb04da --- /dev/null +++ b/java/tour-of-restate/src/main/java/dev/restate/tour/part4/Checkout.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2023 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Tour of Restate Java, + * 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/tour-of-restate + */ + +package dev.restate.tour.part4; + +import com.google.protobuf.BoolValue; +import dev.restate.sdk.RestateContext; +import dev.restate.sdk.common.CoreSerdes; +import dev.restate.sdk.common.TerminalException; +import dev.restate.tour.auxiliary.EmailClient; +import dev.restate.tour.auxiliary.PaymentClient; +import dev.restate.tour.generated.CheckoutRestate; +import dev.restate.tour.generated.Tour.CheckoutFlowRequest; + +import java.util.UUID; + +public class Checkout extends CheckoutRestate.CheckoutRestateImplBase { + + PaymentClient paymentClient = PaymentClient.get(); + EmailClient emailClient = EmailClient.get(); + + @Override + public BoolValue checkout(RestateContext ctx, CheckoutFlowRequest request) throws TerminalException { + // Generate idempotency key for the stripe client + var idempotencyKey = ctx.sideEffect(CoreSerdes.STRING_UTF8, () -> UUID.randomUUID().toString()); + + // We are a uniform shop where everything costs 40 USD + var totalPrice = request.getTicketsList().size() * 40.0; + + boolean success = ctx.sideEffect(CoreSerdes.BOOLEAN, () -> paymentClient.failingCall(idempotencyKey, totalPrice)); + + if (success) { + ctx.sideEffect(CoreSerdes.BOOLEAN, ()-> emailClient.notifyUserOfPaymentSuccess(request.getUserId())); + } else { + ctx.sideEffect(CoreSerdes.BOOLEAN, () -> emailClient.notifyUserOfPaymentFailure(request.getUserId())); + } + + return BoolValue.of(success); + } +} diff --git a/java/tour-of-restate/src/main/java/dev/restate/tour/part4/TicketService.java b/java/tour-of-restate/src/main/java/dev/restate/tour/part4/TicketService.java new file mode 100644 index 00000000..58aca565 --- /dev/null +++ b/java/tour-of-restate/src/main/java/dev/restate/tour/part4/TicketService.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2023 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Tour of Restate Java, + * 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/tour-of-restate + */ + +package dev.restate.tour.part4; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.google.protobuf.BoolValue; +import dev.restate.sdk.RestateContext; +import dev.restate.sdk.common.StateKey; +import dev.restate.sdk.common.TerminalException; +import dev.restate.sdk.serde.jackson.JacksonSerdes; +import dev.restate.tour.auxiliary.TicketStatus; +import dev.restate.tour.generated.TicketServiceRestate; +import dev.restate.tour.generated.Tour.Ticket; + +public class TicketService extends TicketServiceRestate.TicketServiceRestateImplBase { + + public static final StateKey STATE_KEY = StateKey.of("status", JacksonSerdes.of(TicketStatus.class)); + + @Override + public BoolValue reserve(RestateContext ctx, Ticket request) throws TerminalException { + var status = ctx.get(STATE_KEY).orElse(TicketStatus.Available); + + if (status.equals(TicketStatus.Available)) { + ctx.set(STATE_KEY, TicketStatus.Reserved); + return BoolValue.of(true); + } else { + return BoolValue.of(false); + } + } + + @Override + public void unreserve(RestateContext ctx, Ticket request) throws TerminalException { + var status = ctx.get(STATE_KEY).orElse(TicketStatus.Available); + + if (!status.equals(TicketStatus.Sold)) { + ctx.clear(STATE_KEY); + } + } + + @Override + public void markAsSold(RestateContext ctx, Ticket request) throws TerminalException { + var status = ctx.get(STATE_KEY).orElse(TicketStatus.Available); + + if (status.equals(TicketStatus.Reserved)) { + ctx.set(STATE_KEY, TicketStatus.Sold); + } + } +} diff --git a/java/tour-of-restate/src/main/java/dev/restate/tour/part4/UserSession.java b/java/tour-of-restate/src/main/java/dev/restate/tour/part4/UserSession.java new file mode 100644 index 00000000..1dda1916 --- /dev/null +++ b/java/tour-of-restate/src/main/java/dev/restate/tour/part4/UserSession.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2023 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Tour of Restate Java, + * 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/tour-of-restate + */ + +package dev.restate.tour.part4; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.google.protobuf.BoolValue; +import dev.restate.sdk.RestateContext; +import dev.restate.sdk.common.StateKey; +import dev.restate.sdk.common.TerminalException; +import dev.restate.sdk.serde.jackson.JacksonSerdes; +import dev.restate.tour.generated.CheckoutRestate; +import dev.restate.tour.generated.TicketServiceRestate; +import dev.restate.tour.generated.Tour.*; +import dev.restate.tour.generated.UserSessionRestate; + +import java.time.Duration; +import java.util.HashSet; +import java.util.Set; + +public class UserSession extends UserSessionRestate.UserSessionRestateImplBase { + + public static final StateKey> STATE_KEY = StateKey.of("tickets", JacksonSerdes.of(new TypeReference<>() {})); + + @Override + public BoolValue addTicket(RestateContext ctx, ReserveTicket request) throws TerminalException { + var ticketClnt = TicketServiceRestate.newClient(ctx); + var reservationSuccess = ticketClnt + .reserve(Ticket.newBuilder().setTicketId(request.getTicketId()).build()) + .await(); + + if (reservationSuccess.getValue()) { + var tickets = ctx.get(STATE_KEY).orElseGet(HashSet::new); + tickets.add(request.getTicketId()); + ctx.set(STATE_KEY, tickets); + + var userSessionClnt = UserSessionRestate.newClient(ctx); + userSessionClnt.delayed(Duration.ofMinutes(15)).expireTicket( + ExpireTicketRequest.newBuilder().setTicketId(request.getTicketId()).setUserId(request.getUserId()).build() + ); + } + + return reservationSuccess; + } + + @Override + public void expireTicket(RestateContext ctx, ExpireTicketRequest request) throws TerminalException { + var tickets = ctx.get(STATE_KEY).orElseGet(HashSet::new); + + var removed = tickets.removeIf(s -> s.equals(request.getTicketId())); + + if (removed) { + ctx.set(STATE_KEY, tickets); + var ticketClnt = TicketServiceRestate.newClient(ctx); + ticketClnt.oneWay().unreserve(Ticket.newBuilder().setTicketId(request.getTicketId()).build()); + } + } + + @Override + public BoolValue checkout(RestateContext ctx, CheckoutRequest request) throws TerminalException { + var tickets = ctx.get(STATE_KEY).orElseGet(HashSet::new); + + if (tickets.isEmpty()) { + return BoolValue.of(false); + } + + var checkoutClnt = CheckoutRestate.newClient(ctx); + var checkoutSuccess = checkoutClnt.checkout( + CheckoutFlowRequest.newBuilder().setUserId(request.getUserId()).addAllTickets(tickets).build() + ).await(); + + if (checkoutSuccess.getValue()) { + var ticketClnt = TicketServiceRestate.newClient(ctx); + tickets.forEach(t -> ticketClnt.oneWay().markAsSold(Ticket.newBuilder().setTicketId(t).build())); + ctx.clear(STATE_KEY); + } + + return checkoutSuccess; + } +} diff --git a/java/tour-of-restate/src/main/proto/tour.proto b/java/tour-of-restate/src/main/proto/tour.proto new file mode 100644 index 00000000..845157c7 --- /dev/null +++ b/java/tour-of-restate/src/main/proto/tour.proto @@ -0,0 +1,63 @@ +syntax = "proto3"; + +package example; + +option java_package = "dev.restate.tour.generated"; + +import "google/protobuf/empty.proto"; +import "google/protobuf/wrappers.proto"; + +import "dev/restate/ext.proto"; + +service UserSession { + option (dev.restate.ext.service_type) = KEYED; + + rpc AddTicket (ReserveTicket) returns (google.protobuf.BoolValue); + + rpc Checkout (CheckoutRequest) returns (google.protobuf.BoolValue); + + rpc ExpireTicket (ExpireTicketRequest) returns (google.protobuf.Empty); +} + +message ReserveTicket { + string user_id = 1 [(dev.restate.ext.field) = KEY]; + string ticket_id = 2; +} + +message CheckoutRequest { + string user_id = 1 [(dev.restate.ext.field) = KEY]; +} + +message ExpireTicketRequest { + string user_id = 1 [(dev.restate.ext.field) = KEY]; + string ticket_id = 2; +} + +service TicketService { + option (dev.restate.ext.service_type) = KEYED; + + rpc Reserve (Ticket) returns (google.protobuf.BoolValue); + + rpc Unreserve (Ticket) returns (google.protobuf.Empty); + + rpc MarkAsSold (Ticket) returns (google.protobuf.Empty); +} + +message Ticket { + string ticket_id = 1 [(dev.restate.ext.field) = KEY]; +} + +message ResultValue { + bool value = 1; +} + +service Checkout { + option (dev.restate.ext.service_type) = UNKEYED; + + rpc Checkout (CheckoutFlowRequest) returns (google.protobuf.BoolValue); +} + +message CheckoutFlowRequest { + string user_id = 1; + repeated string tickets = 2; +} \ No newline at end of file diff --git a/java/tour-of-restate/src/main/resources/log4j2.properties b/java/tour-of-restate/src/main/resources/log4j2.properties new file mode 100644 index 00000000..834ae0f4 --- /dev/null +++ b/java/tour-of-restate/src/main/resources/log4j2.properties @@ -0,0 +1,18 @@ +# 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} [%tn] %-5p %c{1}:%L - %m%n + +# Restate logs to debug level +logger.app.name = dev.restate +logger.app.level = debug +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 diff --git a/scripts/prepare_release_zip.sh b/scripts/prepare_release_zip.sh index 112c6053..0e609424 100755 --- a/scripts/prepare_release_zip.sh +++ b/scripts/prepare_release_zip.sh @@ -19,6 +19,7 @@ create_release_zip() { create_release_zip java hello-world-http create_release_zip java hello-world-lambda create_release_zip java food-ordering +create_release_zip java tour-of-restate create_release_zip kotlin hello-world-http create_release_zip kotlin hello-world-lambda