diff --git a/.tools/prepare_release_zip.sh b/.tools/prepare_release_zip.sh index 8577da28..fceb9723 100755 --- a/.tools/prepare_release_zip.sh +++ b/.tools/prepare_release_zip.sh @@ -30,6 +30,7 @@ create_release_zip templates/rust rust-hello-world create_release_zip templates/rust-shuttle rust-shuttle-hello-world create_release_zip templates/typescript-lambda-cdk typescript-hello-world-lambda-cdk create_release_zip templates/kotlin-gradle-lambda-cdk kotlin-hello-world-lambda-cdk +create_release_zip templates/java-gradle-lambda-cdk java-hello-world-lambda-cdk create_release_zip templates/python python-hello-world create_release_zip tutorials/tour-of-restate-go go-tour-of-restate diff --git a/templates/java-gradle-lambda-cdk/.eslintignore b/templates/java-gradle-lambda-cdk/.eslintignore new file mode 100644 index 00000000..5035c46c --- /dev/null +++ b/templates/java-gradle-lambda-cdk/.eslintignore @@ -0,0 +1,3 @@ +node_modules +dist +cdk.out \ No newline at end of file diff --git a/templates/java-gradle-lambda-cdk/.eslintrc.json b/templates/java-gradle-lambda-cdk/.eslintrc.json new file mode 100644 index 00000000..77b1f4de --- /dev/null +++ b/templates/java-gradle-lambda-cdk/.eslintrc.json @@ -0,0 +1,15 @@ +{ + "env": { + "browser": true, + "commonjs": true, + "es2021": true + }, + "extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"], + "overrides": [], + "parser": "@typescript-eslint/parser", + "parserOptions": { + "ecmaVersion": "latest" + }, + "plugins": ["@typescript-eslint"], + "rules": {} +} diff --git a/templates/java-gradle-lambda-cdk/.gitignore b/templates/java-gradle-lambda-cdk/.gitignore new file mode 100644 index 00000000..3626cde7 --- /dev/null +++ b/templates/java-gradle-lambda-cdk/.gitignore @@ -0,0 +1,10 @@ +!jest.config.js +node_modules +.cdk.staging +cdk.out +.gradle +lambda/build +*.js +*.d.ts +*.class +cdk.context.json \ No newline at end of file diff --git a/templates/java-gradle-lambda-cdk/.prettierrc b/templates/java-gradle-lambda-cdk/.prettierrc new file mode 100644 index 00000000..da245af4 --- /dev/null +++ b/templates/java-gradle-lambda-cdk/.prettierrc @@ -0,0 +1,7 @@ +{ + "trailingComma": "all", + "tabWidth": 2, + "semi": true, + "arrowParens": "always", + "printWidth": 120 +} diff --git a/templates/java-gradle-lambda-cdk/README.md b/templates/java-gradle-lambda-cdk/README.md new file mode 100644 index 00000000..296ef668 --- /dev/null +++ b/templates/java-gradle-lambda-cdk/README.md @@ -0,0 +1,70 @@ +# Hello world - Java Lambda (CDK) example + +Sample project deploying a Java-based Restate service to AWS Lambda using the AWS Cloud Development Kit (CDK). +The stack uses the Restate CDK constructs library to register the service with against a Restate Cloud environment. + +For more information on CDK, please see [Getting started with the AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html). + +* [CDK app entry point `lambda-jvm-cdk.ts`](bin/lambda-jvm-cdk.ts) +* [CDK stack consisting of a Lambda function and providing Restate service registration](cdk/lambda-jvm-cdk-stack.ts) +* [Java Lambda handler](lambda) - based on [`hello-world-java`](../java-gradle) + +## Download the example + +- Via the CLI: + ```shell + restate example java-hello-world-lambda-cdk && cd java-hello-world-lambda-cdk + ``` + +- Via git clone: + ```shell + git clone git@github.com:restatedev/examples.git + cd examples/templates/java-gradle-lambda-cdk + ``` + +- Via `wget`: + ```shell + wget https://github.com/restatedev/examples/releases/latest/download/java-hello-world-lambda-cdk.zip && unzip java-hello-world-lambda-cdk.zip -d java-hello-world-lambda-cdk && rm java-hello-world-lambda-cdk.zip + ``` + +## Deploy + +**Pre-requisites:** + +* npm +* gradle +* JDK >= 21 +* AWS account, bootstrapped for CDK use +* valid AWS credentials with sufficient privileges to create the necessary resources +* an existing [Restate Cloud](https://restate.dev) environment (environment id + API key) + +Install npm dependencies: + +```shell +npm install +``` + +To deploy the stack, export the Restate Cloud environment id and API key, and run `cdk deploy`: + +```shell +export RESTATE_ENV_ID=env_... RESTATE_API_KEY=key_... +npx cdk deploy +``` + +The stack output will print out the Restate server ingress URL. + +### Test + +You can send a test request to the Restate ingress endpoint to call the newly deployed service: + +```shell +curl -k ${restateIngressUrl}/Greeter/greet \ + -H "Authorization: Bearer $RESTATE_API_KEY" \ + -H 'content-type: application/json' -d '"Restate"' +``` + +### Useful commands + +* `npm run build` compile the Lambda handler and synthesize CDK deployment artifacts +* `npm run deploy` perform a CDK deployment +* `npm run destroy` delete the stack and all its resources diff --git a/templates/java-gradle-lambda-cdk/bin/lambda-jvm-cdk.ts b/templates/java-gradle-lambda-cdk/bin/lambda-jvm-cdk.ts new file mode 100644 index 00000000..6293c59a --- /dev/null +++ b/templates/java-gradle-lambda-cdk/bin/lambda-jvm-cdk.ts @@ -0,0 +1,24 @@ +#!/usr/bin/env node + +/* + * Copyright (c) 2024 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Restate examples, + * which is released under the MIT license. + * + * You can find a copy of the license in the file LICENSE + * in the root directory of this repository or package or at + * https://github.com/restatedev/examples/ + */ + +import "source-map-support/register"; +import * as cdk from "aws-cdk-lib"; +import { LambdaJvmCdkStack } from "../cdk/lambda-jvm-cdk-stack"; + +const app = new cdk.App(); +new LambdaJvmCdkStack(app, "LambdaJvmCdkStack", { + env: { + account: process.env.CDK_DEFAULT_ACCOUNT, + region: process.env.CDK_DEFAULT_REGION, + }, +}); diff --git a/templates/java-gradle-lambda-cdk/cdk.json b/templates/java-gradle-lambda-cdk/cdk.json new file mode 100644 index 00000000..4d9f9e61 --- /dev/null +++ b/templates/java-gradle-lambda-cdk/cdk.json @@ -0,0 +1,59 @@ +{ + "app": "npx ts-node --prefer-ts-exts bin/lambda-jvm-cdk.ts", + "watch": { + "include": ["**"], + "exclude": [ + "README.md", + "cdk*.json", + "**/*.d.ts", + "**/*.js", + "tsconfig.json", + "package*.json", + "yarn.lock", + "node_modules", + "test" + ] + }, + "context": { + "@aws-cdk/aws-lambda:recognizeLayerVersion": true, + "@aws-cdk/core:checkSecretUsage": true, + "@aws-cdk/core:target-partitions": ["aws", "aws-cn"], + "@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true, + "@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true, + "@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true, + "@aws-cdk/aws-iam:minimizePolicies": true, + "@aws-cdk/core:validateSnapshotRemovalPolicy": true, + "@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true, + "@aws-cdk/aws-s3:createDefaultLoggingPolicy": true, + "@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true, + "@aws-cdk/aws-apigateway:disableCloudWatchRole": true, + "@aws-cdk/core:enablePartitionLiterals": true, + "@aws-cdk/aws-events:eventsTargetQueueSameAccount": true, + "@aws-cdk/aws-iam:standardizedServicePrincipals": true, + "@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true, + "@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true, + "@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true, + "@aws-cdk/aws-route53-patters:useCertificate": true, + "@aws-cdk/customresources:installLatestAwsSdkDefault": false, + "@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true, + "@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true, + "@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true, + "@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true, + "@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true, + "@aws-cdk/aws-redshift:columnId": true, + "@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true, + "@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true, + "@aws-cdk/aws-apigateway:requestValidatorUniqueId": true, + "@aws-cdk/aws-kms:aliasNameRef": true, + "@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true, + "@aws-cdk/core:includePrefixInUniqueNameGeneration": true, + "@aws-cdk/aws-efs:denyAnonymousAccess": true, + "@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": true, + "@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": true, + "@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": true, + "@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": true, + "@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": true, + "@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": true, + "@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForCodeCommitSource": true + } +} diff --git a/templates/java-gradle-lambda-cdk/cdk/lambda-jvm-cdk-stack.ts b/templates/java-gradle-lambda-cdk/cdk/lambda-jvm-cdk-stack.ts new file mode 100644 index 00000000..1a5d7177 --- /dev/null +++ b/templates/java-gradle-lambda-cdk/cdk/lambda-jvm-cdk-stack.ts @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2024 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Restate examples, + * which is released under the MIT license. + * + * You can find a copy of the license in the file LICENSE + * in the root directory of this repository or package or at + * https://github.com/restatedev/examples/ + */ + +import * as restate from "@restatedev/restate-cdk"; +import * as cdk from "aws-cdk-lib"; +import * as lambda from "aws-cdk-lib/aws-lambda"; +import * as secrets from "aws-cdk-lib/aws-secretsmanager"; +import { Construct } from "constructs"; + +export class LambdaJvmCdkStack extends cdk.Stack { + constructor(scope: Construct, id: string, props: cdk.StackProps) { + super(scope, id, props); + + const handler: lambda.Function = new lambda.Function(this, "GreeterService", { + runtime: lambda.Runtime.JAVA_21, + architecture: lambda.Architecture.ARM_64, + code: lambda.Code.fromAsset("lambda/build/distributions/lambda.zip"), + handler: "my.example.LambdaHandler", + timeout: cdk.Duration.seconds(10), + loggingFormat: lambda.LoggingFormat.JSON, + applicationLogLevelV2: lambda.ApplicationLogLevel.DEBUG, + systemLogLevelV2: lambda.SystemLogLevel.INFO, + }); + + // Set the RESTATE_ENV_ID and RESTATE_API_KEY environment variables to point to your Restate Cloud environment. + // This construct automatically creates an invoker role that Restate Cloud will be able to assume to invoke handlers + // on behalf of your environment. See https://docs.restate.dev/deploy/cloud for more information. + const restateEnvironment = new restate.RestateCloudEnvironment(this, "RestateCloud", { + environmentId: process.env.RESTATE_ENV_ID! as restate.EnvironmentId, + // Warning: this will result in the API key being baked into the CloudFormation template! + // For improved security, pre-populate the secret and pass it to the construct as a reference. + // See: https://docs.aws.amazon.com/secretsmanager/latest/userguide/cdk.html + apiKey: new secrets.Secret(this, "RestateCloudApiKey", { + secretStringValue: cdk.SecretValue.unsafePlainText(process.env.RESTATE_API_KEY!), + }), + }); + const deployer = new restate.ServiceDeployer(this, "ServiceDeployer"); + + // Alternatively, you can deploy a standalone Restate server using the SingleNodeRestateDeployment construct. + // Please see https://docs.restate.dev/deploy/lambda/self-hosted and the construct documentation for more details. + // const vpc = ec2.Vpc.fromLookup(this, "Vpc", { vpcId: "..." }); + // const restateEnvironment = new restate.SingleNodeRestateDeployment(this, "Restate", { + // vpc, + // networkConfiguration: { subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS }, + // }); + // const deployer = new restate.ServiceDeployer(this, "ServiceDeployer", { + // vpc, + // securityGroups: [restateEnvironment.adminSecurityGroup], + // }); + + deployer.deployService("Greeter", handler.currentVersion, restateEnvironment); + new cdk.CfnOutput(this, "restateIngressUrl", { value: restateEnvironment.ingressUrl }); + } +} diff --git a/templates/java-gradle-lambda-cdk/lambda/.settings/org.eclipse.buildship.core.prefs b/templates/java-gradle-lambda-cdk/lambda/.settings/org.eclipse.buildship.core.prefs new file mode 100644 index 00000000..5b3f7365 --- /dev/null +++ b/templates/java-gradle-lambda-cdk/lambda/.settings/org.eclipse.buildship.core.prefs @@ -0,0 +1,13 @@ +arguments=--init-script /var/folders/4x/r9ldvl2j0pldhp2nb9qvxy0w0000gn/T/db3b08fc4a9ef609cb16b96b200fa13e563f396e9bb1ed0905fdab7bc3bc513b.gradle +auto.sync=false +build.scans.enabled=false +connection.gradle.distribution=GRADLE_DISTRIBUTION(WRAPPER) +connection.project.dir= +eclipse.preferences.version=1 +gradle.user.home= +java.home=/Library/Java/JavaVirtualMachines/zulu-19.jdk/Contents/Home +jvm.arguments= +offline.mode=false +override.workspace.settings=true +show.console.view=true +show.executions.view=true diff --git a/templates/java-gradle-lambda-cdk/lambda/build.gradle.kts b/templates/java-gradle-lambda-cdk/lambda/build.gradle.kts new file mode 100644 index 00000000..5d082eef --- /dev/null +++ b/templates/java-gradle-lambda-cdk/lambda/build.gradle.kts @@ -0,0 +1,53 @@ +import java.net.URI + +plugins { + java +} + +repositories { + mavenCentral() +} + +val restateVersion = "1.2.0" + +dependencies { + // Annotation processor + annotationProcessor("dev.restate:sdk-api-gen:$restateVersion") + + // Restate SDK + implementation("dev.restate:sdk-api:$restateVersion") + implementation("dev.restate:sdk-http-vertx:$restateVersion") + implementation("dev.restate:sdk-lambda:$restateVersion") + // To use Jackson to read/write state entries (optional) + implementation("dev.restate:sdk-serde-jackson:$restateVersion") + + testImplementation(platform("org.junit:junit-bom:5.11.3")) + testImplementation("org.junit.jupiter:junit-jupiter") + testImplementation("dev.restate:sdk-testing:$restateVersion") + + // AWS Lambda-specific logging, see https://docs.aws.amazon.com/lambda/latest/dg/java-logging.html#java-logging-log4j2 + val log4j2version = "2.24.2" + implementation("org.apache.logging.log4j:log4j-core:$log4j2version") + implementation("org.apache.logging.log4j:log4j-layout-template-json:$log4j2version") + implementation("com.amazonaws:aws-lambda-java-log4j2:1.6.0") +} + +// Setup Java compiler target +java { + toolchain { + languageVersion.set(JavaLanguageVersion.of(17)) + } +} + +tasks.register("lambdaZip") { + from(tasks.compileJava.get()) + from(tasks.processResources.get()) + + into("lib") { + from(configurations.runtimeClasspath) + } +} + +tasks.build { + dependsOn("lambdaZip") +} diff --git a/templates/java-gradle-lambda-cdk/lambda/gradle/wrapper/gradle-wrapper.jar b/templates/java-gradle-lambda-cdk/lambda/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..033e24c4 Binary files /dev/null and b/templates/java-gradle-lambda-cdk/lambda/gradle/wrapper/gradle-wrapper.jar differ diff --git a/templates/java-gradle-lambda-cdk/lambda/gradle/wrapper/gradle-wrapper.properties b/templates/java-gradle-lambda-cdk/lambda/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..a80b22ce --- /dev/null +++ b/templates/java-gradle-lambda-cdk/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.6-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/templates/java-gradle-lambda-cdk/lambda/gradlew b/templates/java-gradle-lambda-cdk/lambda/gradlew new file mode 100755 index 00000000..fcb6fca1 --- /dev/null +++ b/templates/java-gradle-lambda-cdk/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/templates/java-gradle-lambda-cdk/lambda/gradlew.bat b/templates/java-gradle-lambda-cdk/lambda/gradlew.bat new file mode 100644 index 00000000..93e3f59f --- /dev/null +++ b/templates/java-gradle-lambda-cdk/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/templates/java-gradle-lambda-cdk/lambda/src/main/java/my/example/Greeter.java b/templates/java-gradle-lambda-cdk/lambda/src/main/java/my/example/Greeter.java new file mode 100644 index 00000000..6fc7dc4c --- /dev/null +++ b/templates/java-gradle-lambda-cdk/lambda/src/main/java/my/example/Greeter.java @@ -0,0 +1,26 @@ +package my.example; + +import static my.example.Utils.sendNotification; +import static my.example.Utils.sendReminder; + +import dev.restate.sdk.Context; +import dev.restate.sdk.annotation.Handler; +import dev.restate.sdk.annotation.Service; +import dev.restate.sdk.http.vertx.RestateHttpEndpointBuilder; +import java.time.Duration; + +@Service +public class Greeter { + + @Handler + public String greet(Context ctx, String name) { + // Durably execute a set of steps; resilient against failures + String greetingId = ctx.random().nextUUID().toString(); + ctx.run(() -> sendNotification(greetingId, name)); + ctx.sleep(Duration.ofMillis(1000)); + ctx.run(() -> sendReminder(greetingId)); + + // Respond to caller + return "You said hi to " + name + "!"; + } +} diff --git a/templates/java-gradle-lambda-cdk/lambda/src/main/java/my/example/LambdaHandler.java b/templates/java-gradle-lambda-cdk/lambda/src/main/java/my/example/LambdaHandler.java new file mode 100644 index 00000000..461bd232 --- /dev/null +++ b/templates/java-gradle-lambda-cdk/lambda/src/main/java/my/example/LambdaHandler.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2024 - Restate Software, Inc., Restate GmbH + * + * This file is part of the Restate examples, + * which is released under the MIT license. + * + * You can find a copy of the license in the file LICENSE + * in the root directory of this repository or package or at + * https://github.com/restatedev/examples/ + */ + + package my.example; + + import dev.restate.sdk.lambda.BaseRestateLambdaHandler; + import dev.restate.sdk.lambda.RestateLambdaEndpointBuilder; + + import my.example.Greeter; + + public class LambdaHandler extends BaseRestateLambdaHandler { + @Override + public void register(RestateLambdaEndpointBuilder builder) { + builder.bind(new Greeter()); + } + } diff --git a/templates/java-gradle-lambda-cdk/lambda/src/main/java/my/example/Utils.java b/templates/java-gradle-lambda-cdk/lambda/src/main/java/my/example/Utils.java new file mode 100644 index 00000000..ab2141f7 --- /dev/null +++ b/templates/java-gradle-lambda-cdk/lambda/src/main/java/my/example/Utils.java @@ -0,0 +1,22 @@ +package my.example; + +// You can remove this file. +// It's only purpose is providing stubs for the template. + +class Utils { + public static void sendNotification(String greetingId, String name){ + if (Math.random() < 0.5) { // 50% chance of failure + System.out.println("👻 Failed to send notification: " + greetingId + " - " + name); + throw new RuntimeException("Failed to send notification: " + greetingId + " - " + name); + } + System.out.println("Notification sent: " + greetingId + " - " + name); + } + + public static void sendReminder(String greetingId){ + if (Math.random() < 0.5) { // 50% chance of failure + System.out.println("👻 Failed to send reminder: " + greetingId); + throw new RuntimeException("Failed to send reminder: " + greetingId); + } + System.out.println("Reminder sent: " + greetingId); + } +} \ No newline at end of file diff --git a/templates/java-gradle-lambda-cdk/lambda/src/main/resources/log4j2.properties b/templates/java-gradle-lambda-cdk/lambda/src/main/resources/log4j2.properties new file mode 100644 index 00000000..536d1d39 --- /dev/null +++ b/templates/java-gradle-lambda-cdk/lambda/src/main/resources/log4j2.properties @@ -0,0 +1,26 @@ +# Set to debug or trace if log4j initialization is failing +status = warn + +# Console appender configuration +appender.console.type = Console +appender.console.name = consoleLogger +appender.console.layout.type = PatternLayout +appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %notEmpty{[%X{restateInvocationTarget}]}%notEmpty{[%X{restateInvocationId}]} %c - %m%n + +# Filter out logging during replay +appender.console.filter.replay.type = ContextMapFilter +appender.console.filter.replay.onMatch = DENY +appender.console.filter.replay.onMismatch = NEUTRAL +appender.console.filter.replay.0.type = KeyValuePair +appender.console.filter.replay.0.key = restateInvocationStatus +appender.console.filter.replay.0.value = REPLAYING + +# Restate logs to debug level +logger.app.name = dev.restate +logger.app.level = info +logger.app.additivity = false +logger.app.appenderRef.console.ref = consoleLogger + +# Root logger +rootLogger.level = info +rootLogger.appenderRef.stdout.ref = consoleLogger \ No newline at end of file diff --git a/templates/java-gradle-lambda-cdk/package.json b/templates/java-gradle-lambda-cdk/package.json new file mode 100644 index 00000000..13565387 --- /dev/null +++ b/templates/java-gradle-lambda-cdk/package.json @@ -0,0 +1,33 @@ +{ + "name": "lambda-jvm-cdk", + "version": "0.1.0", + "bin": { + "lambda-jvm-cdk": "bin/lambda-jvm-cdk.js" + }, + "scripts": { + "lint": "eslint --ignore-path .eslintignore --ext .ts .", + "build": "npm run build-lambda && npm run build-cdk", + "build-lambda": "cd lambda && ./gradlew build", + "build-cdk": "cdk synth", + "watch": "tsc -w", + "format": "prettier --ignore-path .eslintignore --write \"**/*.+(js|ts|json)\"", + "verify": "npm run format -- --check && npm run lint && npm run build", + "deploy": "npm run build && cdk deploy", + "destroy": "npx cdk destroy" + }, + "devDependencies": { + "@restatedev/restate-cdk": "^1.1.0-rc.1", + "@types/node": "22.5.2", + "@typescript-eslint/eslint-plugin": "^8.3.0", + "aws-cdk": "^2.155.0", + "esbuild": "^0.23.1", + "prettier": "^3.3.3", + "ts-node": "^10.9.2", + "typescript": "^5.5.4" + }, + "dependencies": { + "aws-cdk-lib": "^2.155.0", + "constructs": "^10.3.0", + "source-map-support": "^0.5.21" + } +} diff --git a/templates/java-gradle-lambda-cdk/tsconfig.json b/templates/java-gradle-lambda-cdk/tsconfig.json new file mode 100644 index 00000000..f2915dc2 --- /dev/null +++ b/templates/java-gradle-lambda-cdk/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "nodenext", + "lib": ["es2020", "dom"], + "declaration": true, + "strict": true, + "noImplicitAny": true, + "strictNullChecks": true, + "noImplicitThis": true, + "alwaysStrict": true, + "noUnusedLocals": false, + "noUnusedParameters": false, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": false, + "inlineSourceMap": true, + "inlineSources": true, + "experimentalDecorators": true, + "strictPropertyInitialization": false, + "typeRoots": ["./node_modules/@types"] + }, + "exclude": ["node_modules", "cdk.out"] +}