diff --git a/.github/workflows/pre-release.yml b/.github/workflows/pre-release.yml new file mode 100644 index 00000000..d1974575 --- /dev/null +++ b/.github/workflows/pre-release.yml @@ -0,0 +1,91 @@ +name: Pre-release updates + +on: + workflow_dispatch: + inputs: + sdkTypescriptVersion: + description: 'sdk-typescript version (without prepending v). Leave empty if you do not want to update it.' + required: false + type: string + sdkJavaVersion: + description: 'sdk-java version (without prepending v). Leave empty if you do not want to update it.' + required: false + type: string + +jobs: + updates: + # prevent from running on forks + if: github.repository_owner == 'restatedev' + runs-on: ubuntu-latest + timeout-minutes: 20 + + steps: + - name: Checkout + uses: actions/checkout@v3 + + # Setup node + - uses: actions/setup-node@v3 + if: github.event.inputs.sdkTypescriptVersion != '' + with: + node-version: "19.x" + registry-url: 'https://registry.npmjs.org' + + # Bump sdk version in node examples and run checks + - name: Run npm updates + if: github.event.inputs.sdkTypescriptVersion != '' + run: npm --prefix typescript install @restatedev/restate-sdk@^${{ inputs.sdkTypescriptVersion }} --workspaces + - name: Check npm examples compile correctly + if: github.event.inputs.sdkTypescriptVersion != '' + run: npm --prefix typescript run verify --workspaces + + # Setup Java + - uses: actions/setup-java@v3 + if: github.event.inputs.sdkJavaVersion != '' + with: + distribution: 'temurin' + java-version: '17' + + # Bump sdk version in java/kotlin examples and run checks + # 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; 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 + + # When adding a new example add the check task here + - name: Test java/hello-world-http + if: github.event.inputs.sdkJavaVersion != '' + uses: gradle/gradle-build-action@v2 + with: + arguments: check + build-root-directory: java/hello-world-http + - name: Test java/hello-world-lambda + if: github.event.inputs.sdkJavaVersion != '' + uses: gradle/gradle-build-action@v2 + with: + arguments: check + build-root-directory: java/hello-world-lambda + - name: Test kotlin/hello-world-http + if: github.event.inputs.sdkJavaVersion != '' + uses: gradle/gradle-build-action@v2 + with: + arguments: check + build-root-directory: kotlin/hello-world-http + - name: Test kotlin/hello-world-lambda + if: github.event.inputs.sdkJavaVersion != '' + uses: gradle/gradle-build-action@v2 + with: + arguments: check + build-root-directory: kotlin/hello-world-lambda + + - name: Create Pull Request + uses: peter-evans/create-pull-request@v5 + with: + title: "[GithubActions] Update Restate ${{ inputs.sdkTypescriptVersion != '' && format('SDK-Typescript {0} ', inputs.sdkTypescriptVersion) }}${{ inputs.sdkJavaVersion != '' && format('SDK-Java {0}', inputs.sdkJavaVersion) }}" + commit-message: "[GithubActions] Update Restate ${{ inputs.sdkTypescriptVersion != '' && format('SDK-Typescript {0} ', inputs.sdkTypescriptVersion) }}${{ inputs.sdkJavaVersion != '' && format('SDK-Java {0}', inputs.sdkJavaVersion) }}" + add-paths: | + **/package.json + **/package-lock.json + **/build.gradle.kts \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..9ce97dad --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,31 @@ +name: Create new release + +on: + push: + tags: + - v** + +jobs: + publish-release: + # prevent from running on forks + if: github.repository_owner == 'restatedev' + name: Publish release + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + + - name: Prepare zip files + run: ./scripts/prepare_release_zip.sh + + - name: Create release + uses: softprops/action-gh-release@v1 + with: + # create a draft release which needs manual approval + draft: true + files: | + typescript-lambda-greeter.zip + java-hello-world-http.zip + java-hello-world-lambda.zip + kotlin-hello-world-http.zip + kotlin-hello-world-lambda.zip \ No newline at end of file diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c7110d97..464f9e22 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -7,7 +7,45 @@ on: branches: [ main ] jobs: - build: + build-jvm: + # prevent from running on forks + if: github.repository_owner == 'restatedev' + runs-on: ubuntu-latest + strategy: + matrix: + jvm-version: [ 17 ] + + steps: + - uses: actions/checkout@v3 + + - name: Use JVM ${{ matrix.jvm-version }} + uses: actions/setup-java@v3 + with: + distribution: 'temurin' + java-version: ${{ matrix.jvm-version }} + + # When adding a new example make sure it's listed here + - name: Test java/hello-world-http + uses: gradle/gradle-build-action@v2 + with: + arguments: check + build-root-directory: java/hello-world-http + - name: Test java/hello-world-lambda + uses: gradle/gradle-build-action@v2 + with: + arguments: check + build-root-directory: java/hello-world-lambda + - name: Test kotlin/hello-world-http + uses: gradle/gradle-build-action@v2 + with: + arguments: check + build-root-directory: kotlin/hello-world-http + - name: Test kotlin/hello-world-lambda + uses: gradle/gradle-build-action@v2 + with: + arguments: check + build-root-directory: kotlin/hello-world-lambda + build-ts: # prevent from running on forks if: github.repository_owner == 'restatedev' runs-on: ubuntu-latest @@ -17,11 +55,13 @@ jobs: steps: - uses: actions/checkout@v3 + - uses: bufbuild/buf-setup-action@v1 - name: Use Node.js ${{ matrix.node-version }} uses: actions/setup-node@v3 with: node-version: ${{ matrix.node-version }} registry-url: 'https://registry.npmjs.org' + - run: npm ci --prefix typescript - run: npm run --prefix typescript -ws verify diff --git a/README.md b/README.md index 00c26414..396ceabb 100644 --- a/README.md +++ b/README.md @@ -6,21 +6,75 @@ Browse this repository to see how easy distributed applications development becomes with Restate. -## Typescript examples +## Starters -### Starter examples +![TypeScript](https://img.shields.io/badge/typescript-%23007ACC.svg?style=for-the-badge&logo=typescript&logoColor=white) -* [Lambda greeter](typescript/lambda-greeter): A simple example of how you can run a Restate service on AWS Lambda. -* [Payment api](typescript/payment-api/): Example API for payments, inspired by the Stripe API. -* [Food ordering](typescript/food-ordering): See how to integrate Restate with external services using Awakeables and side effects. +[Hello world on AWS Lambda](typescript/hello-world-lambda) +```shell +# Download the example +wget https://github.com/restatedev/examples/releases/latest/download/typescript-hello-world-lambda.zip && unzip typescript-hello-world-lambda.zip -d typescript-hello-world-lambda && rm typescript-hello-world-lambda.zip +``` + +![Java](https://img.shields.io/badge/java-%23ED8B00.svg?style=for-the-badge&logo=openjdk&logoColor=white) + +[Hello World HTTP](java/hello-world-http) +```shell +# Download the example +wget https://github.com/restatedev/examples/releases/latest/download/java-hello-world-http.zip && unzip java-hello-world-http.zip -d java-hello-world-http && rm java-hello-world-http.zip +``` + +[Hello world on AWS Lambda](java/hello-world-lambda) +```shell +# Download the example +wget https://github.com/restatedev/examples/releases/latest/download/java-hello-world-lambda.zip && unzip java-hello-world-lambda.zip -d java-hello-world-lambda && rm java-hello-world-lambda.zip +``` + +![Kotlin](https://img.shields.io/badge/kotlin-%237F52FF.svg?style=for-the-badge&logo=kotlin&logoColor=white) -### Intermediate examples +[Hello World HTTP](java/hello-world-kotlin-http) +```shell +# Download the example +wget https://github.com/restatedev/examples/releases/latest/download/kotlin-hello-world-http.zip && unzip kotlin-hello-world-http.zip -d kotlin-hello-world-http && rm kotlin-hello-world-http.zip +``` + +[Hello world on AWS Lambda](java/hello-world-kotlin-lambda) +```shell +# Download the example +wget https://github.com/restatedev/examples/releases/latest/download/kotlin-hello-world-lambda.zip && unzip kotlin-hello-world-lambda.zip -d kotlin-hello-world-lambda && rm kotlin-hello-world-lambda.zip +``` -* [Ticket reservation](typescript/ticket-reservation): An example to illustrate how Restate's keyed-sharding and concurrency guarantees simplify microservice architectures. +## Patterns -### Advanced examples +![TypeScript](https://img.shields.io/badge/typescript-%23007ACC.svg?style=for-the-badge&logo=typescript&logoColor=white) -- [Ecommerce store](typescript/ecommerce-store): A sophisticated example on how to build an ecommerce store based on Restate using the grpc-based Typescript SDK. +[Payment api](typescript/payment-api): Example API for payments, inspired by the Stripe API +```shell +# Download the example +wget https://github.com/restatedev/examples/releases/latest/download/typescript-payment-api.zip && unzip typescript-payment-api.zip -d typescript-payment-api && rm typescript-payment-api.zip +``` + +## Applications + +![TypeScript](https://img.shields.io/badge/typescript-%23007ACC.svg?style=for-the-badge&logo=typescript&logoColor=white) + +[Food ordering](typescript/food-ordering): Integrate Restate with external services +```shell +# Download the example +wget https://github.com/restatedev/examples/releases/latest/download/typescript-food-ordering.zip && unzip typescript-food-ordering.zip -d typescript-food-ordering && rm typescript-food-ordering.zip +``` + +[Ticket reservation](typescript/ticket-reservation): Example showing Restate's keyed-sharding and concurrency guarantees +```shell +# Download the example +wget https://github.com/restatedev/examples/releases/latest/download/typescript-ticket-reservation.zip && unzip typescript-ticket-reservation.zip -d typescript-ticket-reservation && rm typescript-ticket-reservation.zip +``` + +[Ecommerce store](typescript/ecommerce-store): An ecommerce store completely built on top of Restate +```shell +# Download the example +wget https://github.com/restatedev/examples/releases/latest/download/typescript-ecommerce-store.zip && unzip typescript-ecommerce-store.zip -d typescript-ecommerce-store && rm typescript-ecommerce-store.zip +``` ## Joining the community @@ -78,29 +132,19 @@ This should give you the following output in case of the ticket reservation exam } ``` -## Releasing (for Restate developers) - -In order to create a new release, push a tag of the form `vX.Y.Z`. -Then [create a release via GitHub](https://github.com/restatedev/example-lambda-ts-greeter/releases). +## Adding examples (for Restate developers) -### Upgrading the SDK dependency (for Restate developers) +When adding a new example: -In order to upgrade/update the SDK dependency you have to run: +* Make sure it has a `.gitignore` file and a README +* Add it to this README +* Check it's tested both in [`test.yaml`](./.github/workflows/test.yml) and [`pre-release.yaml`](./.github/workflows/pre-release.yml) +* Add it to the [zips script](./scripts/prepare_release_zip.sh) and [`release.yaml`](./.github/workflows/release.yml) -**Major version** change: +## Releasing (for Restate developers) -```shell -npm --prefix typescript install @restatedev/restate-sdk@^Z.Y.X --workspaces -``` +Before releasing, trigger the "pre-release" workflow to update sdk versions. This automatically creates a pull request, which must be manually merged. -**Minor/patch version** change: +Once the repo is ready for the release, push a tag of the form `vX.Y.Z`. -```shell -npm --prefix typescript update @restatedev/restate-sdk --workspaces -``` - -Now check whether the examples are still building: - -```shell -npm --prefix typescript run verify --workspaces -``` +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. diff --git a/java/hello-world-http/.gitignore b/java/hello-world-http/.gitignore new file mode 100644 index 00000000..53ecbad3 --- /dev/null +++ b/java/hello-world-http/.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/java/hello-world-http/README.md b/java/hello-world-http/README.md new file mode 100644 index 00000000..abf1cb33 --- /dev/null +++ b/java/hello-world-http/README.md @@ -0,0 +1,35 @@ +# Hello world - Java HTTP example + +Sample project configuration of a Restate service using the Java interface and HTTP server. It contains: + +* [`build.gradle.kts`](build.gradle.kts) +* [Service interface definition `greeter.proto`](src/main/proto/greeter.proto) +* [Service class implementation `Greeter`](src/main/java/dev/restate/sdk/examples/Greeter.java) +* [Test `GreeterTest`](src/test/java/dev/restate/sdk/examples/GreeterTest.java) +* [Logging configuration](src/main/resources/log4j2.properties) + +## Download the example + +```shell +wget https://github.com/restatedev/examples/releases/latest/download/java-hello-world-http.zip && unzip java-hello-world-http.zip -d java-hello-world-http && rm java-hello-world-http.zip +``` + +## Running the example + +You can run the Java greeter service via: + +```shell +./gradlew run +``` + +Or from your IDE. + +## Running the tests + +You can run the tests either via: + +```shell +./gradlew check +``` + +Or from your IDE. \ No newline at end of file diff --git a/java/hello-world-http/build.gradle.kts b/java/hello-world-http/build.gradle.kts new file mode 100644 index 00000000..ec121058 --- /dev/null +++ b/java/hello-world-http/build.gradle.kts @@ -0,0 +1,70 @@ +import com.google.protobuf.gradle.id + +plugins { + java + application + + id("com.google.protobuf") version "0.9.1" +} + +repositories { + mavenCentral() + // OSSRH Snapshots repo + // TODO remove it once we have the proper release + maven { url = uri("https://s01.oss.sonatype.org/content/repositories/snapshots/") } +} + +val restateVersion = "0.0.1-SNAPSHOT" + +dependencies { + // Restate SDK + implementation("dev.restate:sdk-api:$restateVersion") + implementation("dev.restate:sdk-http-vertx:$restateVersion") + // To use Jackson to read/write state entries (optional) + implementation("dev.restate:sdk-serde-jackson:$restateVersion") + + // 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") + + // Testing (optional) + testImplementation("org.junit.jupiter:junit-jupiter:5.9.1") + testImplementation("dev.restate:sdk-testing:$restateVersion") +} + +// 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:$restateVersion:all@jar" } + } + + generateProtoTasks { + all().forEach { + it.plugins { + id("grpc") + id("restate") + } + } + } +} + +// Configure test platform +tasks.withType { + useJUnitPlatform() +} + +// Set main class +application { + mainClass.set("dev.restate.sdk.examples.Greeter") +} \ No newline at end of file diff --git a/java/hello-world-http/gradle/wrapper/gradle-wrapper.jar b/java/hello-world-http/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..033e24c4 Binary files /dev/null and b/java/hello-world-http/gradle/wrapper/gradle-wrapper.jar differ diff --git a/java/hello-world-http/gradle/wrapper/gradle-wrapper.properties b/java/hello-world-http/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..62f495df --- /dev/null +++ b/java/hello-world-http/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/hello-world-http/gradlew b/java/hello-world-http/gradlew new file mode 100755 index 00000000..fcb6fca1 --- /dev/null +++ b/java/hello-world-http/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/hello-world-http/gradlew.bat b/java/hello-world-http/gradlew.bat new file mode 100644 index 00000000..6689b85b --- /dev/null +++ b/java/hello-world-http/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/hello-world-http/src/main/java/dev/restate/sdk/examples/Greeter.java b/java/hello-world-http/src/main/java/dev/restate/sdk/examples/Greeter.java new file mode 100644 index 00000000..cee8045a --- /dev/null +++ b/java/hello-world-http/src/main/java/dev/restate/sdk/examples/Greeter.java @@ -0,0 +1,39 @@ +package dev.restate.sdk.examples; + +import dev.restate.sdk.RestateContext; +import dev.restate.sdk.common.CoreSerdes; +import dev.restate.sdk.common.StateKey; +import dev.restate.sdk.examples.generated.*; +import dev.restate.sdk.http.vertx.RestateHttpEndpointBuilder; + +import static dev.restate.sdk.examples.generated.GreeterProto.*; + +/** + * This service greets the users. + */ +public class Greeter extends GreeterRestate.GreeterRestateImplBase { + + // Count state. The count is per Person name. + // See https://docs.restate.dev/services/sdk/state for more details. + private static final StateKey COUNT = StateKey.of("count", CoreSerdes.INT); + + @Override + public GreetResponse greet(RestateContext context, GreetRequest request) { + // Get the count and increment it + int count = context.get(COUNT).orElse(1); + context.set(COUNT, count + 1); + + // Send the response back + return GreetResponse.newBuilder() + .setMessage("Hello " + request.getName() + " for the " + count + " time!") + .build(); + } + + public static void main(String[] args) { + RestateHttpEndpointBuilder.builder() + // Register the service Greeter + .withService(new Greeter()) + // Start the Restate Endpoint HTTP Server + .buildAndListen(); + } +} diff --git a/java/hello-world-http/src/main/proto/greeter.proto b/java/hello-world-http/src/main/proto/greeter.proto new file mode 100644 index 00000000..2fd478b1 --- /dev/null +++ b/java/hello-world-http/src/main/proto/greeter.proto @@ -0,0 +1,27 @@ +syntax = "proto3"; + +package greeter; + +import "dev/restate/ext.proto"; + +option java_package = "dev.restate.sdk.examples.generated"; +option java_outer_classname = "GreeterProto"; + +/** + * This service greets the users. + */ +service Greeter { + // See https://docs.restate.dev/services/service_type for more details. + option (dev.restate.ext.service_type) = KEYED; + + rpc Greet (GreetRequest) returns (GreetResponse); +} + +message GreetRequest { + // `name` is the key of the service. + string name = 1 [(dev.restate.ext.field) = KEY]; +} + +message GreetResponse { + string message = 1; +} diff --git a/java/hello-world-http/src/main/resources/log4j2.properties b/java/hello-world-http/src/main/resources/log4j2.properties new file mode 100644 index 00000000..67f6693e --- /dev/null +++ b/java/hello-world-http/src/main/resources/log4j2.properties @@ -0,0 +1,12 @@ +# 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{restateServiceMethod}]}%notEmpty{[%X{restateInvocationId}]} %c - %m%n + +# Root logger +rootLogger.level = info +rootLogger.appenderRef.stdout.ref = consoleLogger \ No newline at end of file diff --git a/java/hello-world-http/src/test/java/dev/restate/sdk/examples/GreeterTest.java b/java/hello-world-http/src/test/java/dev/restate/sdk/examples/GreeterTest.java new file mode 100644 index 00000000..9f6f94c3 --- /dev/null +++ b/java/hello-world-http/src/test/java/dev/restate/sdk/examples/GreeterTest.java @@ -0,0 +1,34 @@ +package dev.restate.sdk.examples; + +import dev.restate.sdk.examples.generated.GreeterGrpc; +import dev.restate.sdk.examples.generated.GreeterGrpc.GreeterBlockingStub; +import dev.restate.sdk.examples.generated.GreeterProto.GreetRequest; +import dev.restate.sdk.examples.generated.GreeterProto.GreetResponse; +import dev.restate.sdk.testing.RestateGrpcChannel; +import dev.restate.sdk.testing.RestateRunner; +import dev.restate.sdk.testing.RestateRunnerBuilder; +import io.grpc.ManagedChannel; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class GreeterTest { + + // Runner runs Restate using testcontainers and registers services + @RegisterExtension + private static final RestateRunner restateRunner = RestateRunnerBuilder.create() + // Service to test + .withService(new Greeter()) + .buildRunner(); + + @Test + void testGreet( + // Channel to send requests to Restate services + @RestateGrpcChannel ManagedChannel channel) { + GreeterBlockingStub client = GreeterGrpc.newBlockingStub(channel); + GreetResponse response = client.greet(GreetRequest.newBuilder().setName("Francesco").build()); + + assertEquals("Hello Francesco for the 1 time!", response.getMessage()); + } +} diff --git a/java/hello-world-lambda/.gitignore b/java/hello-world-lambda/.gitignore new file mode 100644 index 00000000..53ecbad3 --- /dev/null +++ b/java/hello-world-lambda/.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/java/hello-world-lambda/README.md b/java/hello-world-lambda/README.md new file mode 100644 index 00000000..858fe35b --- /dev/null +++ b/java/hello-world-lambda/README.md @@ -0,0 +1,38 @@ +# Hello world - Java Lambda example + +Sample project configuration of a Restate service using the Java interface and AWS Lambda. It contains: + +* [`build.gradle.kts`](build.gradle.kts) +* [Service interface definition `greeter.proto`](src/main/proto/greeter.proto) +* [Service class implementation `Greeter`](src/main/java/dev/restate/sdk/examples/Greeter.java) +* [Lambda handler `LambdaHandler`](src/main/java/dev/restate/sdk/examples/LambdaHandler.java) +* [Test `GreeterTest`](src/test/java/dev/restate/sdk/examples/GreeterTest.java) +* [Logging configuration](src/main/resources/log4j2.properties) + +## Download the example + +```shell +wget https://github.com/restatedev/examples/releases/latest/download/java-hello-world-lambda.zip && unzip java-hello-world-lambda.zip -d java-hello-world-lambda && rm java-hello-world-lambda.zip +``` + +## Package + +Run: + +```shell +./gradlew shadowJar +``` + +You'll find the shadowed jar in the `build` directory. + +The class to configure in Lambda is `dev.restate.sdk.examples.LambdaHandler`. + +## Running the tests + +You can run the tests either via: + +```shell +./gradlew check +``` + +Or from your IDE. \ No newline at end of file diff --git a/java/hello-world-lambda/build.gradle.kts b/java/hello-world-lambda/build.gradle.kts new file mode 100644 index 00000000..95f9b994 --- /dev/null +++ b/java/hello-world-lambda/build.gradle.kts @@ -0,0 +1,67 @@ +import com.google.protobuf.gradle.id + +plugins { + java + + id("com.google.protobuf") version "0.9.1" + + // To package the dependency for Lambda + id("com.github.johnrengelman.shadow") version "7.1.2" +} + +repositories { + mavenCentral() + // OSSRH Snapshots repo + // TODO remove it once we have the proper release + maven { url = uri("https://s01.oss.sonatype.org/content/repositories/snapshots/") } +} + +val restateVersion = "0.0.1-SNAPSHOT" + +dependencies { + // Restate SDK + implementation("dev.restate:sdk-api:$restateVersion") + implementation("dev.restate:sdk-lambda:$restateVersion") + // To use Jackson to read/write state entries (optional) + implementation("dev.restate:sdk-serde-jackson:$restateVersion") + + // 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") + + // Testing (optional) + testImplementation("org.junit.jupiter:junit-jupiter:5.9.1") + testImplementation("dev.restate:sdk-testing:$restateVersion") +} + +// 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:$restateVersion:all@jar" } + } + + generateProtoTasks { + all().forEach { + it.plugins { + id("grpc") + id("restate") + } + } + } +} + +// Configure test platform +tasks.withType { + useJUnitPlatform() +} diff --git a/java/hello-world-lambda/gradle/wrapper/gradle-wrapper.jar b/java/hello-world-lambda/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..033e24c4 Binary files /dev/null and b/java/hello-world-lambda/gradle/wrapper/gradle-wrapper.jar differ diff --git a/java/hello-world-lambda/gradle/wrapper/gradle-wrapper.properties b/java/hello-world-lambda/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..62f495df --- /dev/null +++ b/java/hello-world-lambda/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/hello-world-lambda/gradlew b/java/hello-world-lambda/gradlew new file mode 100755 index 00000000..fcb6fca1 --- /dev/null +++ b/java/hello-world-lambda/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/hello-world-lambda/gradlew.bat b/java/hello-world-lambda/gradlew.bat new file mode 100644 index 00000000..6689b85b --- /dev/null +++ b/java/hello-world-lambda/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/hello-world-lambda/src/main/java/dev/restate/sdk/examples/Greeter.java b/java/hello-world-lambda/src/main/java/dev/restate/sdk/examples/Greeter.java new file mode 100644 index 00000000..491d105d --- /dev/null +++ b/java/hello-world-lambda/src/main/java/dev/restate/sdk/examples/Greeter.java @@ -0,0 +1,30 @@ +package dev.restate.sdk.examples; + +import dev.restate.sdk.RestateContext; +import dev.restate.sdk.common.CoreSerdes; +import dev.restate.sdk.common.StateKey; +import dev.restate.sdk.examples.generated.*; + +import static dev.restate.sdk.examples.generated.GreeterProto.*; + +/** + * This service greets the users. + */ +public class Greeter extends GreeterRestate.GreeterRestateImplBase { + + // Count state. The count is per Person name. + // See https://docs.restate.dev/services/sdk/state for more details. + private static final StateKey COUNT = StateKey.of("count", CoreSerdes.INT); + + @Override + public GreetResponse greet(RestateContext context, GreetRequest request) { + // Get the count and increment it + int count = context.get(COUNT).orElse(1); + context.set(COUNT, count + 1); + + // Send the response back + return GreetResponse.newBuilder() + .setMessage("Hello " + request.getName() + " for the " + count + " time!") + .build(); + } +} diff --git a/java/hello-world-lambda/src/main/java/dev/restate/sdk/examples/LambdaHandler.java b/java/hello-world-lambda/src/main/java/dev/restate/sdk/examples/LambdaHandler.java new file mode 100644 index 00000000..d6f7019c --- /dev/null +++ b/java/hello-world-lambda/src/main/java/dev/restate/sdk/examples/LambdaHandler.java @@ -0,0 +1,15 @@ +package dev.restate.sdk.examples; + +import dev.restate.sdk.lambda.BaseRestateLambdaHandler; +import dev.restate.sdk.lambda.RestateLambdaEndpointBuilder; + +/** + * Handler class to use in AWS Lambda. + */ +public class LambdaHandler extends BaseRestateLambdaHandler { + @Override + public void register(RestateLambdaEndpointBuilder builder) { + // Register the service Greeter to be served within this Lambda + builder.withService(new Greeter()); + } +} diff --git a/java/hello-world-lambda/src/main/proto/greeter.proto b/java/hello-world-lambda/src/main/proto/greeter.proto new file mode 100644 index 00000000..2fd478b1 --- /dev/null +++ b/java/hello-world-lambda/src/main/proto/greeter.proto @@ -0,0 +1,27 @@ +syntax = "proto3"; + +package greeter; + +import "dev/restate/ext.proto"; + +option java_package = "dev.restate.sdk.examples.generated"; +option java_outer_classname = "GreeterProto"; + +/** + * This service greets the users. + */ +service Greeter { + // See https://docs.restate.dev/services/service_type for more details. + option (dev.restate.ext.service_type) = KEYED; + + rpc Greet (GreetRequest) returns (GreetResponse); +} + +message GreetRequest { + // `name` is the key of the service. + string name = 1 [(dev.restate.ext.field) = KEY]; +} + +message GreetResponse { + string message = 1; +} diff --git a/java/hello-world-lambda/src/main/resources/log4j2.properties b/java/hello-world-lambda/src/main/resources/log4j2.properties new file mode 100644 index 00000000..67f6693e --- /dev/null +++ b/java/hello-world-lambda/src/main/resources/log4j2.properties @@ -0,0 +1,12 @@ +# 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{restateServiceMethod}]}%notEmpty{[%X{restateInvocationId}]} %c - %m%n + +# Root logger +rootLogger.level = info +rootLogger.appenderRef.stdout.ref = consoleLogger \ No newline at end of file diff --git a/java/hello-world-lambda/src/test/java/dev/restate/sdk/examples/GreeterTest.java b/java/hello-world-lambda/src/test/java/dev/restate/sdk/examples/GreeterTest.java new file mode 100644 index 00000000..9f6f94c3 --- /dev/null +++ b/java/hello-world-lambda/src/test/java/dev/restate/sdk/examples/GreeterTest.java @@ -0,0 +1,34 @@ +package dev.restate.sdk.examples; + +import dev.restate.sdk.examples.generated.GreeterGrpc; +import dev.restate.sdk.examples.generated.GreeterGrpc.GreeterBlockingStub; +import dev.restate.sdk.examples.generated.GreeterProto.GreetRequest; +import dev.restate.sdk.examples.generated.GreeterProto.GreetResponse; +import dev.restate.sdk.testing.RestateGrpcChannel; +import dev.restate.sdk.testing.RestateRunner; +import dev.restate.sdk.testing.RestateRunnerBuilder; +import io.grpc.ManagedChannel; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class GreeterTest { + + // Runner runs Restate using testcontainers and registers services + @RegisterExtension + private static final RestateRunner restateRunner = RestateRunnerBuilder.create() + // Service to test + .withService(new Greeter()) + .buildRunner(); + + @Test + void testGreet( + // Channel to send requests to Restate services + @RestateGrpcChannel ManagedChannel channel) { + GreeterBlockingStub client = GreeterGrpc.newBlockingStub(channel); + GreetResponse response = client.greet(GreetRequest.newBuilder().setName("Francesco").build()); + + assertEquals("Hello Francesco for the 1 time!", response.getMessage()); + } +} diff --git a/kotlin/hello-world-http/.gitignore b/kotlin/hello-world-http/.gitignore new file mode 100644 index 00000000..53ecbad3 --- /dev/null +++ b/kotlin/hello-world-http/.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/kotlin/hello-world-http/README.md b/kotlin/hello-world-http/README.md new file mode 100644 index 00000000..c0a57a3f --- /dev/null +++ b/kotlin/hello-world-http/README.md @@ -0,0 +1,35 @@ +# Hello world - Kotlin HTTP example + +Sample project configuration of a Restate service using the Kotlin coroutines interface and HTTP server. It contains: + +* [`build.gradle.kts`](build.gradle.kts) +* [Service interface definition `greeter.proto`](src/main/proto/greeter.proto) +* [Service class implementation `Greeter`](src/main/kotlin/dev/restate/sdk/examples/Greeter.kt) +* [Test `GreeterTest`](src/test/kotlin/dev/restate/sdk/examples/GreeterTest.kt) +* [Logging configuration](src/main/resources/log4j2.properties) + +## Download the example + +```shell +wget https://github.com/restatedev/examples/releases/latest/download/kotlin-hello-world-http.zip && unzip kotlin-hello-world-http.zip -d kotlin-hello-world-http && rm kotlin-hello-world-http.zip +``` + +## Running the example + +You can run the Kotlin greeter service via: + +```shell +./gradlew run +``` + +Or from your IDE. + +## Running the tests + +You can run the tests either via: + +```shell +./gradlew check +``` + +Or from your IDE. diff --git a/kotlin/hello-world-http/build.gradle.kts b/kotlin/hello-world-http/build.gradle.kts new file mode 100644 index 00000000..ce0354b5 --- /dev/null +++ b/kotlin/hello-world-http/build.gradle.kts @@ -0,0 +1,88 @@ +import com.google.protobuf.gradle.id +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +plugins { + kotlin("jvm") version "1.9.10" + application + + id("com.google.protobuf") version "0.9.1" +} + +repositories { + mavenCentral() + // OSSRH Snapshots repo + // TODO remove it once we have the proper release + maven { url = uri("https://s01.oss.sonatype.org/content/repositories/snapshots/") } +} + +val restateVersion = "0.0.1-SNAPSHOT" + +dependencies { + // Restate SDK + implementation("dev.restate:sdk-api-kotlin:$restateVersion") + implementation("dev.restate:sdk-http-vertx:$restateVersion") + // To use Jackson to read/write state entries (optional) + implementation("dev.restate:sdk-serde-jackson:$restateVersion") + + // Protobuf and grpc dependencies (we need the Java dependencies as well because the Kotlin dependencies rely on Java) + implementation("com.google.protobuf:protobuf-java:3.24.3") + implementation("com.google.protobuf:protobuf-kotlin:3.24.3") + implementation("io.grpc:grpc-stub:1.58.0") + implementation("io.grpc:grpc-protobuf:1.58.0") + implementation("io.grpc:grpc-kotlin-stub:1.4.0") { exclude("javax.annotation", "javax.annotation-api") } + // 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") + + // To specify the coroutines dispatcher + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3") + + // Logging (optional) + implementation("org.apache.logging.log4j:log4j-core:2.20.0") + + // Testing (optional) + testImplementation("org.junit.jupiter:junit-jupiter:5.9.1") + testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3") + testImplementation("dev.restate:sdk-testing:$restateVersion") +} + +// Setup Java/Kotlin compiler target +java { + toolchain { + languageVersion.set(JavaLanguageVersion.of(17)) + } +} + +// Configure protoc plugin +protobuf { + protoc { artifact = "com.google.protobuf:protoc:3.24.3" } + + plugins { + id("grpc") { artifact = "io.grpc:protoc-gen-grpc-java:1.58.0" } + id("grpckt") { artifact = "io.grpc:protoc-gen-grpc-kotlin:1.4.0:jdk8@jar" } + } + + generateProtoTasks { + all().forEach { + // We need both java and kotlin codegen(s) because the kotlin protobuf/grpc codegen depends on the java ones + it.plugins { + id("grpc") + id("grpckt") + } + it.builtins { + java {} + id("kotlin") + } + } + } +} + +// Configure test platform +tasks.withType { + useJUnitPlatform() +} + +// Configure main class +application { + mainClass.set("dev.restate.sdk.examples.GreeterKt") +} diff --git a/kotlin/hello-world-http/gradle/wrapper/gradle-wrapper.jar b/kotlin/hello-world-http/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..033e24c4 Binary files /dev/null and b/kotlin/hello-world-http/gradle/wrapper/gradle-wrapper.jar differ diff --git a/kotlin/hello-world-http/gradle/wrapper/gradle-wrapper.properties b/kotlin/hello-world-http/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..62f495df --- /dev/null +++ b/kotlin/hello-world-http/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/kotlin/hello-world-http/gradlew b/kotlin/hello-world-http/gradlew new file mode 100755 index 00000000..fcb6fca1 --- /dev/null +++ b/kotlin/hello-world-http/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/kotlin/hello-world-http/gradlew.bat b/kotlin/hello-world-http/gradlew.bat new file mode 100644 index 00000000..6689b85b --- /dev/null +++ b/kotlin/hello-world-http/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/kotlin/hello-world-http/src/main/kotlin/dev/restate/sdk/examples/Greeter.kt b/kotlin/hello-world-http/src/main/kotlin/dev/restate/sdk/examples/Greeter.kt new file mode 100644 index 00000000..e035db20 --- /dev/null +++ b/kotlin/hello-world-http/src/main/kotlin/dev/restate/sdk/examples/Greeter.kt @@ -0,0 +1,37 @@ +package dev.restate.sdk.examples + +import dev.restate.sdk.common.CoreSerdes +import dev.restate.sdk.common.StateKey +import dev.restate.sdk.examples.generated.* +import dev.restate.sdk.examples.generated.GreeterProto.GreetRequest +import dev.restate.sdk.examples.generated.GreeterProto.GreetResponse +import dev.restate.sdk.kotlin.RestateKtService +import dev.restate.sdk.http.vertx.RestateHttpEndpointBuilder +import kotlinx.coroutines.Dispatchers + +class Greeter : + // Use Dispatchers.Unconfined as the Executor/thread pool is managed by the SDK itself. + GreeterGrpcKt.GreeterCoroutineImplBase(Dispatchers.Unconfined), + RestateKtService { + + companion object { + private val COUNT = StateKey.of("count", CoreSerdes.INT) + } + + override suspend fun greet(request: GreetRequest): GreetResponse { + val ctx = restateContext() + + val count = ctx.get(COUNT) ?: 1 + ctx.set(COUNT, count + 1) + + return greetResponse { + message = "Hello ${request.name} for the $count time!" + } + } +} + +fun main() { + RestateHttpEndpointBuilder + .builder() + .withService(Greeter()).buildAndListen() +} diff --git a/kotlin/hello-world-http/src/main/proto/greeter.proto b/kotlin/hello-world-http/src/main/proto/greeter.proto new file mode 100644 index 00000000..2fd478b1 --- /dev/null +++ b/kotlin/hello-world-http/src/main/proto/greeter.proto @@ -0,0 +1,27 @@ +syntax = "proto3"; + +package greeter; + +import "dev/restate/ext.proto"; + +option java_package = "dev.restate.sdk.examples.generated"; +option java_outer_classname = "GreeterProto"; + +/** + * This service greets the users. + */ +service Greeter { + // See https://docs.restate.dev/services/service_type for more details. + option (dev.restate.ext.service_type) = KEYED; + + rpc Greet (GreetRequest) returns (GreetResponse); +} + +message GreetRequest { + // `name` is the key of the service. + string name = 1 [(dev.restate.ext.field) = KEY]; +} + +message GreetResponse { + string message = 1; +} diff --git a/kotlin/hello-world-http/src/main/resources/log4j2.properties b/kotlin/hello-world-http/src/main/resources/log4j2.properties new file mode 100644 index 00000000..67f6693e --- /dev/null +++ b/kotlin/hello-world-http/src/main/resources/log4j2.properties @@ -0,0 +1,12 @@ +# 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{restateServiceMethod}]}%notEmpty{[%X{restateInvocationId}]} %c - %m%n + +# Root logger +rootLogger.level = info +rootLogger.appenderRef.stdout.ref = consoleLogger \ No newline at end of file diff --git a/kotlin/hello-world-http/src/test/kotlin/dev/restate/sdk/examples/GreeterTest.kt b/kotlin/hello-world-http/src/test/kotlin/dev/restate/sdk/examples/GreeterTest.kt new file mode 100644 index 00000000..863fc76b --- /dev/null +++ b/kotlin/hello-world-http/src/test/kotlin/dev/restate/sdk/examples/GreeterTest.kt @@ -0,0 +1,33 @@ +package dev.restate.sdk.examples + +import dev.restate.sdk.examples.generated.GreeterGrpcKt.GreeterCoroutineStub +import dev.restate.sdk.examples.generated.greetRequest +import dev.restate.sdk.testing.RestateGrpcChannel +import dev.restate.sdk.testing.RestateRunner +import dev.restate.sdk.testing.RestateRunnerBuilder +import io.grpc.ManagedChannel +import kotlinx.coroutines.test.runTest +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.RegisterExtension + +class GreeterTest { + companion object { + // Runner runs Restate using testcontainers and registers services + @RegisterExtension + private val restateRunner: RestateRunner = RestateRunnerBuilder.create() + // Service to test + .withService(Greeter()) + .buildRunner() + } + + @Test + fun testGreet( + // Channel to send requests to Restate services + @RestateGrpcChannel channel: ManagedChannel) = runTest { + val client = GreeterCoroutineStub(channel) + val response = client.greet(greetRequest { name = "Francesco" }) + + assertEquals("Hello Francesco for the 1 time!", response.getMessage()) + } +} diff --git a/kotlin/hello-world-lambda/.gitignore b/kotlin/hello-world-lambda/.gitignore new file mode 100644 index 00000000..53ecbad3 --- /dev/null +++ b/kotlin/hello-world-lambda/.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/kotlin/hello-world-lambda/README.md b/kotlin/hello-world-lambda/README.md new file mode 100644 index 00000000..6ae78a64 --- /dev/null +++ b/kotlin/hello-world-lambda/README.md @@ -0,0 +1,38 @@ +# Hello world - Kotlin Lambda example + +Sample project configuration of a Restate service using the Kotlin coroutines interface and AWS Lambda. It contains: + +* [`build.gradle.kts`](build.gradle.kts) +* [Service interface definition `greeter.proto`](src/main/proto/greeter.proto) +* [Service class implementation `Greeter`](src/main/kotlin/dev/restate/sdk/examples/Greeter.kt) +* [Lambda handler `LambdaHandler`](src/main/kotlin/dev/restate/sdk/examples/LambdaHandler.kt) +* [Test `GreeterTest`](src/test/kotlin/dev/restate/sdk/examples/GreeterTest.kt) +* [Logging configuration](src/main/resources/log4j2.properties) + +## Download the example + +```shell +wget https://github.com/restatedev/examples/releases/latest/download/kotlin-hello-world-lambda.zip && unzip kotlin-hello-world-lambda.zip -d kotlin-hello-world-lambda && rm kotlin-hello-world-lambda.zip +``` + +## Package + +Run: + +```shell +./gradlew shadowJar +``` + +You'll find the shadowed jar in the `build` directory. + +The class to configure in Lambda is `dev.restate.sdk.examples.LambdaHandler`. + +## Running the tests + +You can run the tests either via: + +```shell +./gradlew check +``` + +Or from your IDE. \ No newline at end of file diff --git a/kotlin/hello-world-lambda/build.gradle.kts b/kotlin/hello-world-lambda/build.gradle.kts new file mode 100644 index 00000000..6569dfe2 --- /dev/null +++ b/kotlin/hello-world-lambda/build.gradle.kts @@ -0,0 +1,85 @@ +import com.google.protobuf.gradle.id +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +plugins { + kotlin("jvm") version "1.9.10" + + id("com.google.protobuf") version "0.9.1" + + // To package the dependency for Lambda + id("com.github.johnrengelman.shadow") version "7.1.2" +} + +repositories { + mavenCentral() + // OSSRH Snapshots repo + // TODO remove it once we have the proper release + maven { url = uri("https://s01.oss.sonatype.org/content/repositories/snapshots/") } +} + +val restateVersion = "0.0.1-SNAPSHOT" + +dependencies { + // Restate SDK + implementation("dev.restate:sdk-api-kotlin:$restateVersion") + implementation("dev.restate:sdk-lambda:$restateVersion") + // To use Jackson to read/write state entries (optional) + implementation("dev.restate:sdk-serde-jackson:$restateVersion") + + // Protobuf and grpc dependencies (we need the Java dependencies as well because the Kotlin dependencies rely on Java) + implementation("com.google.protobuf:protobuf-java:3.24.3") + implementation("com.google.protobuf:protobuf-kotlin:3.24.3") + implementation("io.grpc:grpc-stub:1.58.0") + implementation("io.grpc:grpc-protobuf:1.58.0") + implementation("io.grpc:grpc-kotlin-stub:1.4.0") { exclude("javax.annotation", "javax.annotation-api") } + // 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") + + // To specify the coroutines dispatcher + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3") + + // Logging (optional) + implementation("org.apache.logging.log4j:log4j-core:2.20.0") + + // Testing (optional) + testImplementation("org.junit.jupiter:junit-jupiter:5.9.1") + testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3") + testImplementation("dev.restate:sdk-testing:$restateVersion") +} + +// Setup Java/Kotlin compiler target +java { + toolchain { + languageVersion.set(JavaLanguageVersion.of(17)) + } +} + +// Configure protoc plugin +protobuf { + protoc { artifact = "com.google.protobuf:protoc:3.24.3" } + + plugins { + id("grpc") { artifact = "io.grpc:protoc-gen-grpc-java:1.58.0" } + id("grpckt") { artifact = "io.grpc:protoc-gen-grpc-kotlin:1.4.0:jdk8@jar" } + } + + generateProtoTasks { + all().forEach { + // We need both java and kotlin codegen(s) because the kotlin protobuf/grpc codegen depends on the java ones + it.plugins { + id("grpc") + id("grpckt") + } + it.builtins { + java {} + id("kotlin") + } + } + } +} + +// Configure test platform +tasks.withType { + useJUnitPlatform() +} \ No newline at end of file diff --git a/kotlin/hello-world-lambda/gradle/wrapper/gradle-wrapper.jar b/kotlin/hello-world-lambda/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..033e24c4 Binary files /dev/null and b/kotlin/hello-world-lambda/gradle/wrapper/gradle-wrapper.jar differ diff --git a/kotlin/hello-world-lambda/gradle/wrapper/gradle-wrapper.properties b/kotlin/hello-world-lambda/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..62f495df --- /dev/null +++ b/kotlin/hello-world-lambda/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/kotlin/hello-world-lambda/gradlew b/kotlin/hello-world-lambda/gradlew new file mode 100755 index 00000000..fcb6fca1 --- /dev/null +++ b/kotlin/hello-world-lambda/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/kotlin/hello-world-lambda/gradlew.bat b/kotlin/hello-world-lambda/gradlew.bat new file mode 100644 index 00000000..6689b85b --- /dev/null +++ b/kotlin/hello-world-lambda/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/kotlin/hello-world-lambda/src/main/kotlin/dev/restate/sdk/examples/Greeter.kt b/kotlin/hello-world-lambda/src/main/kotlin/dev/restate/sdk/examples/Greeter.kt new file mode 100644 index 00000000..0ab55ac7 --- /dev/null +++ b/kotlin/hello-world-lambda/src/main/kotlin/dev/restate/sdk/examples/Greeter.kt @@ -0,0 +1,30 @@ +package dev.restate.sdk.examples + +import dev.restate.sdk.common.CoreSerdes +import dev.restate.sdk.common.StateKey +import dev.restate.sdk.examples.generated.* +import dev.restate.sdk.examples.generated.GreeterProto.GreetRequest +import dev.restate.sdk.examples.generated.GreeterProto.GreetResponse +import dev.restate.sdk.kotlin.RestateKtService +import kotlinx.coroutines.Dispatchers + +class Greeter : + // Use Dispatchers.Unconfined as the Executor/thread pool is managed by the SDK itself. + GreeterGrpcKt.GreeterCoroutineImplBase(Dispatchers.Unconfined), + RestateKtService { + + companion object { + private val COUNT = StateKey.of("count", CoreSerdes.INT) + } + + override suspend fun greet(request: GreetRequest): GreetResponse { + val ctx = restateContext() + + val count = ctx.get(COUNT) ?: 1 + ctx.set(COUNT, count + 1) + + return greetResponse { + message = "Hello ${request.name} for the $count time!" + } + } +} diff --git a/kotlin/hello-world-lambda/src/main/kotlin/dev/restate/sdk/examples/LambdaHandler.kt b/kotlin/hello-world-lambda/src/main/kotlin/dev/restate/sdk/examples/LambdaHandler.kt new file mode 100644 index 00000000..b95f2708 --- /dev/null +++ b/kotlin/hello-world-lambda/src/main/kotlin/dev/restate/sdk/examples/LambdaHandler.kt @@ -0,0 +1,10 @@ +package dev.restate.sdk.examples + +import dev.restate.sdk.lambda.BaseRestateLambdaHandler +import dev.restate.sdk.lambda.RestateLambdaEndpointBuilder + +class LambdaHandler : BaseRestateLambdaHandler() { + override fun register(builder: RestateLambdaEndpointBuilder) { + builder.withService(Greeter()) + } +} diff --git a/kotlin/hello-world-lambda/src/main/proto/greeter.proto b/kotlin/hello-world-lambda/src/main/proto/greeter.proto new file mode 100644 index 00000000..2fd478b1 --- /dev/null +++ b/kotlin/hello-world-lambda/src/main/proto/greeter.proto @@ -0,0 +1,27 @@ +syntax = "proto3"; + +package greeter; + +import "dev/restate/ext.proto"; + +option java_package = "dev.restate.sdk.examples.generated"; +option java_outer_classname = "GreeterProto"; + +/** + * This service greets the users. + */ +service Greeter { + // See https://docs.restate.dev/services/service_type for more details. + option (dev.restate.ext.service_type) = KEYED; + + rpc Greet (GreetRequest) returns (GreetResponse); +} + +message GreetRequest { + // `name` is the key of the service. + string name = 1 [(dev.restate.ext.field) = KEY]; +} + +message GreetResponse { + string message = 1; +} diff --git a/kotlin/hello-world-lambda/src/main/resources/log4j2.properties b/kotlin/hello-world-lambda/src/main/resources/log4j2.properties new file mode 100644 index 00000000..67f6693e --- /dev/null +++ b/kotlin/hello-world-lambda/src/main/resources/log4j2.properties @@ -0,0 +1,12 @@ +# 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{restateServiceMethod}]}%notEmpty{[%X{restateInvocationId}]} %c - %m%n + +# Root logger +rootLogger.level = info +rootLogger.appenderRef.stdout.ref = consoleLogger \ No newline at end of file diff --git a/kotlin/hello-world-lambda/src/test/kotlin/dev/restate/sdk/examples/GreeterTest.kt b/kotlin/hello-world-lambda/src/test/kotlin/dev/restate/sdk/examples/GreeterTest.kt new file mode 100644 index 00000000..863fc76b --- /dev/null +++ b/kotlin/hello-world-lambda/src/test/kotlin/dev/restate/sdk/examples/GreeterTest.kt @@ -0,0 +1,33 @@ +package dev.restate.sdk.examples + +import dev.restate.sdk.examples.generated.GreeterGrpcKt.GreeterCoroutineStub +import dev.restate.sdk.examples.generated.greetRequest +import dev.restate.sdk.testing.RestateGrpcChannel +import dev.restate.sdk.testing.RestateRunner +import dev.restate.sdk.testing.RestateRunnerBuilder +import io.grpc.ManagedChannel +import kotlinx.coroutines.test.runTest +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.RegisterExtension + +class GreeterTest { + companion object { + // Runner runs Restate using testcontainers and registers services + @RegisterExtension + private val restateRunner: RestateRunner = RestateRunnerBuilder.create() + // Service to test + .withService(Greeter()) + .buildRunner() + } + + @Test + fun testGreet( + // Channel to send requests to Restate services + @RestateGrpcChannel channel: ManagedChannel) = runTest { + val client = GreeterCoroutineStub(channel) + val response = client.greet(greetRequest { name = "Francesco" }) + + assertEquals("Hello Francesco for the 1 time!", response.getMessage()) + } +} diff --git a/package-lock.json b/package-lock.json deleted file mode 100644 index 94f11647..00000000 --- a/package-lock.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "examples", - "lockfileVersion": 3, - "requires": true, - "packages": {} -} diff --git a/scripts/prepare_release_zip.sh b/scripts/prepare_release_zip.sh new file mode 100755 index 00000000..6d24e1ad --- /dev/null +++ b/scripts/prepare_release_zip.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash + +OUT_DIR="$(pwd)" + +gitzip() { + # Uses git to zip current working directory. + # This automatically excludes files excluded by .gitignore + git archive HEAD -o ${PWD##*/}.zip +} + +# create_release_zip $language $template-name +# Stores result in $OUT_DIR +create_release_zip() { + pushd $1/$2 && gitzip && popd || exit + mv "$1/$2/$2.zip" "$OUT_DIR/$1-$2.zip" + echo "Zip for $1/$2 in $OUT_DIR/$1-$2.zip" +} + +create_release_zip java hello-world-http +create_release_zip java hello-world-lambda + +create_release_zip kotlin hello-world-http +create_release_zip kotlin hello-world-lambda + +create_release_zip typescript hello-world-lambda +create_release_zip typescript ecommerce-store +create_release_zip typescript food-ordering +create_release_zip typescript payment-api +create_release_zip typescript ticket-reservation \ No newline at end of file diff --git a/typescript/README.md b/typescript/README.md index 138619fd..cbfaa828 100644 --- a/typescript/README.md +++ b/typescript/README.md @@ -4,7 +4,7 @@ This directory contains Restate examples using the Typescript SDK. ## Starter examples -- [Lambda greeter](lambda-greeter): A simple example of how you can run a Restate service on AWS Lambda. +- [Lambda greeter](hello-world-lambda): A simple example of how you can run a Restate service on AWS Lambda. - [Payment api](payment-api/): Example API for payments, inspired by the Stripe API. - [Food ordering](typescript/food-ordering): See how to integrate Restate with external services using Awakeables and side effects. diff --git a/typescript/ecommerce-store/.gitignore b/typescript/ecommerce-store/.gitignore new file mode 100644 index 00000000..11f1aa9e --- /dev/null +++ b/typescript/ecommerce-store/.gitignore @@ -0,0 +1,4 @@ +**/node_modules +**/dist +**/.vscode +**/.idea diff --git a/typescript/ecommerce-store/README.md b/typescript/ecommerce-store/README.md index 155b3669..6a86417f 100644 --- a/typescript/ecommerce-store/README.md +++ b/typescript/ecommerce-store/README.md @@ -15,6 +15,12 @@ Restate is a system for easily building resilient applications using **distribut - Optional: Docker Compose - Optional: AWS account with permissions for ECS, RDS, ECR, security groups, VPC, service discovery, IAM roles. +## Download the example + +```shell +wget https://github.com/restatedev/examples/releases/latest/download/typescript-ecommerce-store.zip && unzip typescript-ecommerce-store.zip -d typescript-ecommerce-store && rm typescript-ecommerce-store.zip +``` + ## Deployment on Docker Compose Build the Docker containers for the web app and services: diff --git a/typescript/food-ordering/README.md b/typescript/food-ordering/README.md index 8ee10540..045ca9de 100644 --- a/typescript/food-ordering/README.md +++ b/typescript/food-ordering/README.md @@ -15,6 +15,12 @@ The example illustrates the following aspects: - How to resolve Awakeables from an external service and thereby resuming Restate invocations. - How delayed calls can be used to schedule tasks for later moments in time. +## Download the example + +```shell +wget https://github.com/restatedev/examples/releases/latest/download/typescript-food-ordering.zip && unzip typescript-food-ordering.zip -d typescript-food-ordering && rm typescript-food-ordering.zip +``` + ## Detailed description This application implements the order processing middleware that sits between food delivery providers and restaurants. diff --git a/typescript/lambda-greeter/.eslintignore b/typescript/hello-world-lambda/.eslintignore similarity index 100% rename from typescript/lambda-greeter/.eslintignore rename to typescript/hello-world-lambda/.eslintignore diff --git a/typescript/lambda-greeter/.eslintrc.json b/typescript/hello-world-lambda/.eslintrc.json similarity index 100% rename from typescript/lambda-greeter/.eslintrc.json rename to typescript/hello-world-lambda/.eslintrc.json diff --git a/typescript/hello-world-lambda/.gitignore b/typescript/hello-world-lambda/.gitignore new file mode 100644 index 00000000..11f1aa9e --- /dev/null +++ b/typescript/hello-world-lambda/.gitignore @@ -0,0 +1,4 @@ +**/node_modules +**/dist +**/.vscode +**/.idea diff --git a/typescript/lambda-greeter/README.md b/typescript/hello-world-lambda/README.md similarity index 60% rename from typescript/lambda-greeter/README.md rename to typescript/hello-world-lambda/README.md index 7d535cf3..8dd9bdb3 100644 --- a/typescript/lambda-greeter/README.md +++ b/typescript/hello-world-lambda/README.md @@ -4,3 +4,9 @@ Restate is a system for easily building resilient applications using **distribut This example contains the greeter service which you can deploy on AWS Lambda. Take a look at [how to deploy Restate services on AWS Lambda](https://docs.restate.dev/services/deployment/lambda#tutorial) for more information. + +## Download the example + +```shell +wget https://github.com/restatedev/examples/releases/latest/download/typescript-hello-world-lambda.zip && unzip typescript-hello-world-lambda.zip -d typescript-hello-world-lambda && rm typescript-hello-world-lambda.zip +``` diff --git a/typescript/lambda-greeter/package.json b/typescript/hello-world-lambda/package.json similarity index 100% rename from typescript/lambda-greeter/package.json rename to typescript/hello-world-lambda/package.json diff --git a/typescript/lambda-greeter/src/app.ts b/typescript/hello-world-lambda/src/app.ts similarity index 100% rename from typescript/lambda-greeter/src/app.ts rename to typescript/hello-world-lambda/src/app.ts diff --git a/typescript/lambda-greeter/tsconfig.json b/typescript/hello-world-lambda/tsconfig.json similarity index 100% rename from typescript/lambda-greeter/tsconfig.json rename to typescript/hello-world-lambda/tsconfig.json diff --git a/typescript/payment-api/.gitignore b/typescript/payment-api/.gitignore new file mode 100644 index 00000000..11f1aa9e --- /dev/null +++ b/typescript/payment-api/.gitignore @@ -0,0 +1,4 @@ +**/node_modules +**/dist +**/.vscode +**/.idea diff --git a/typescript/payment-api/README.md b/typescript/payment-api/README.md index 9e06d713..85a270d2 100644 --- a/typescript/payment-api/README.md +++ b/typescript/payment-api/README.md @@ -20,6 +20,12 @@ Despite the relatively few lines of code (no careful synchronization, retries, o this application maintaines a high level of consistency in the presence of concurrent external requests and failures. +## Download the example + +```shell +wget https://github.com/restatedev/examples/releases/latest/download/typescript-payment-api.zip && unzip typescript-payment-api.zip -d typescript-payment-api && rm typescript-payment-api.zip +``` + ## Running this example ### Prerequisites diff --git a/typescript/ticket-reservation/.gitignore b/typescript/ticket-reservation/.gitignore new file mode 100644 index 00000000..11f1aa9e --- /dev/null +++ b/typescript/ticket-reservation/.gitignore @@ -0,0 +1,4 @@ +**/node_modules +**/dist +**/.vscode +**/.idea diff --git a/typescript/ticket-reservation/README.md b/typescript/ticket-reservation/README.md index 5ea3d23b..2b634bcf 100644 --- a/typescript/ticket-reservation/README.md +++ b/typescript/ticket-reservation/README.md @@ -6,6 +6,12 @@ Restate is a system for easily building resilient applications using **distribut ❓ Learn more about Restate from the [Restate documentation](https://docs.restate.dev). +## Download the example + +```shell +wget https://github.com/restatedev/examples/releases/latest/download/typescript-ticket-reservation.zip && unzip typescript-ticket-reservation.zip -d typescript-ticket-reservation && rm typescript-ticket-reservation.zip +``` + ## Quickstart To set up the example, use this sequence of commands: