diff --git a/spring-cloud-function/2.0.1.RELEASE/css/highlight.css b/spring-cloud-function/2.0.1.RELEASE/css/highlight.css new file mode 100644 index 00000000..ffefef72 --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/css/highlight.css @@ -0,0 +1,35 @@ +/* + code highlight CSS resemblign the Eclipse IDE default color schema + @author Costin Leau +*/ + +.hl-keyword { + color: #7F0055; + font-weight: bold; +} + +.hl-comment { + color: #3F5F5F; + font-style: italic; +} + +.hl-multiline-comment { + color: #3F5FBF; + font-style: italic; +} + +.hl-tag { + color: #3F7F7F; +} + +.hl-attribute { + color: #7F007F; +} + +.hl-value { + color: #2A00FF; +} + +.hl-string { + color: #2A00FF; +} \ No newline at end of file diff --git a/spring-cloud-function/2.0.1.RELEASE/css/manual-multipage.css b/spring-cloud-function/2.0.1.RELEASE/css/manual-multipage.css new file mode 100644 index 00000000..0c484531 --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/css/manual-multipage.css @@ -0,0 +1,9 @@ +@IMPORT url("manual.css"); + +body.firstpage { + background: url("../images/background.png") no-repeat center top; +} + +div.part h1 { + border-top: none; +} diff --git a/spring-cloud-function/2.0.1.RELEASE/css/manual-singlepage.css b/spring-cloud-function/2.0.1.RELEASE/css/manual-singlepage.css new file mode 100644 index 00000000..4a7fd140 --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/css/manual-singlepage.css @@ -0,0 +1,6 @@ +@IMPORT url("manual.css"); + +body { + background: url("../images/background.png") no-repeat center top; +} + diff --git a/spring-cloud-function/2.0.1.RELEASE/css/manual.css b/spring-cloud-function/2.0.1.RELEASE/css/manual.css new file mode 100644 index 00000000..0ecbe2e8 --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/css/manual.css @@ -0,0 +1,344 @@ +@IMPORT url("highlight.css"); + +html { + padding: 0pt; + margin: 0pt; +} + +body { + color: #333333; + margin: 15px 30px; + font-family: Helvetica, Arial, Freesans, Clean, Sans-serif; + line-height: 1.6; + -webkit-font-smoothing: antialiased; +} + +code { + font-size: 16px; + font-family: Consolas, "Liberation Mono", Courier, monospace; +} + +:not(a)>code { + color: #6D180B; +} + +:not(pre)>code { + background-color: #F2F2F2; + border: 1px solid #CCCCCC; + border-radius: 4px; + padding: 1px 3px 0; + text-shadow: none; + white-space: nowrap; +} + +body>*:first-child { + margin-top: 0 !important; +} + +div { + margin: 0pt; +} + +hr { + border: 1px solid #CCCCCC; + background: #CCCCCC; +} + +h1,h2,h3,h4,h5,h6 { + color: #000000; + cursor: text; + font-weight: bold; + margin: 30px 0 10px; + padding: 0; +} + +h1,h2,h3 { + margin: 40px 0 10px; +} + +h1 { + margin: 70px 0 30px; + padding-top: 20px; +} + +div.part h1 { + border-top: 1px dotted #CCCCCC; +} + +h1,h1 code { + font-size: 32px; +} + +h2,h2 code { + font-size: 24px; +} + +h3,h3 code { + font-size: 20px; +} + +h4,h1 code,h5,h5 code,h6,h6 code { + font-size: 18px; +} + +div.book,div.chapter,div.appendix,div.part,div.preface { + min-width: 300px; + max-width: 1200px; + margin: 0 auto; +} + +p.releaseinfo { + font-weight: bold; + margin-bottom: 40px; + margin-top: 40px; +} + +div.authorgroup { + line-height: 1; +} + +p.copyright { + line-height: 1; + margin-bottom: -5px; +} + +.legalnotice p { + font-style: italic; + font-size: 14px; + line-height: 1; +} + +div.titlepage+p,div.titlepage+p { + margin-top: 0; +} + +pre { + line-height: 1.0; + color: black; +} + +a { + color: #4183C4; + text-decoration: none; +} + +p { + margin: 15px 0; + text-align: left; +} + +ul,ol { + padding-left: 30px; +} + +li p { + margin: 0; +} + +div.table { + margin: 1em; + padding: 0.5em; + text-align: center; +} + +div.table table,div.informaltable table { + display: table; + width: 100%; +} + +div.table td { + padding-left: 7px; + padding-right: 7px; +} + +.sidebar { + line-height: 1.4; + padding: 0 20px; + background-color: #F8F8F8; + border: 1px solid #CCCCCC; + border-radius: 3px 3px 3px 3px; +} + +.sidebar p.title { + color: #6D180B; +} + +pre.programlisting,pre.screen { + font-size: 15px; + padding: 6px 10px; + background-color: #F8F8F8; + border: 1px solid #CCCCCC; + border-radius: 3px 3px 3px 3px; + clear: both; + overflow: auto; + line-height: 1.4; + font-family: Consolas, "Liberation Mono", Courier, monospace; +} + +table { + border-collapse: collapse; + border-spacing: 0; + border: 1px solid #DDDDDD !important; + border-radius: 4px !important; + border-collapse: separate !important; + line-height: 1.6; +} + +table thead { + background: #F5F5F5; +} + +table tr { + border: none; + border-bottom: none; +} + +table th { + font-weight: bold; +} + +table th,table td { + border: none !important; + padding: 6px 13px; +} + +table tr:nth-child(2n) { + background-color: #F8F8F8; +} + +td p { + margin: 0 0 15px 0; +} + +div.table-contents td p { + margin: 0; +} + +div.important *,div.note *,div.tip *,div.warning *,div.navheader *,div.navfooter *,div.calloutlist * + { + border: none !important; + background: none !important; + margin: 0; +} + +div.important p,div.note p,div.tip p,div.warning p { + color: #6F6F6F; + line-height: 1.6; +} + +div.important code,div.note code,div.tip code,div.warning code { + background-color: #F2F2F2 !important; + border: 1px solid #CCCCCC !important; + border-radius: 4px !important; + padding: 1px 3px 0 !important; + text-shadow: none !important; + white-space: nowrap !important; +} + +.note th,.tip th,.warning th { + display: none; +} + +.note tr:first-child td,.tip tr:first-child td,.warning tr:first-child td + { + border-right: 1px solid #CCCCCC !important; + padding-top: 10px; +} + +div.calloutlist p,div.calloutlist td { + padding: 0; + margin: 0; +} + +div.calloutlist>table>tbody>tr>td:first-child { + padding-left: 10px; + width: 30px !important; +} + +div.important,div.note,div.tip,div.warning { + margin-left: 0px !important; + margin-right: 20px !important; + margin-top: 20px; + margin-bottom: 20px; + padding-top: 10px; + padding-bottom: 10px; +} + +div.toc { + line-height: 1.2; +} + +dl,dt { + margin-top: 1px; + margin-bottom: 0; +} + +div.toc>dl>dt { + font-size: 32px; + font-weight: bold; + margin: 30px 0 10px 0; + display: block; +} + +div.toc>dl>dd>dl>dt { + font-size: 24px; + font-weight: bold; + margin: 20px 0 10px 0; + display: block; +} + +div.toc>dl>dd>dl>dd>dl>dt { + font-weight: bold; + font-size: 20px; + margin: 10px 0 0 0; +} + +tbody.footnotes * { + border: none !important; +} + +div.footnote p { + margin: 0; + line-height: 1; +} + +div.footnote p sup { + margin-right: 6px; + vertical-align: middle; +} + +div.navheader { + border-bottom: 1px solid #CCCCCC; +} + +div.navfooter { + border-top: 1px solid #CCCCCC; +} + +.title { + margin-left: -1em; + padding-left: 1em; +} + +.title>a { + position: absolute; + visibility: hidden; + display: block; + font-size: 0.85em; + margin-top: 0.05em; + margin-left: -1em; + vertical-align: text-top; + color: black; +} + +.title>a:before { + content: "\00A7"; +} + +.title:hover>a,.title>a:hover,.title:hover>a:hover { + visibility: visible; +} + +.title:focus>a,.title>a:focus,.title:focus>a:focus { + outline: 0; +} diff --git a/spring-cloud-function/2.0.1.RELEASE/ghpages.sh b/spring-cloud-function/2.0.1.RELEASE/ghpages.sh new file mode 100644 index 00000000..6795216e --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/ghpages.sh @@ -0,0 +1,330 @@ +#!/bin/bash -x + +set -e + +# Set default props like MAVEN_PATH, ROOT_FOLDER etc. +function set_default_props() { + # The script should be executed from the root folder + ROOT_FOLDER=`pwd` + echo "Current folder is ${ROOT_FOLDER}" + + if [[ ! -e "${ROOT_FOLDER}/.git" ]]; then + echo "You're not in the root folder of the project!" + exit 1 + fi + + # Prop that will let commit the changes + COMMIT_CHANGES="no" + MAVEN_PATH=${MAVEN_PATH:-} + echo "Path to Maven is [${MAVEN_PATH}]" + REPO_NAME=${PWD##*/} + echo "Repo name is [${REPO_NAME}]" + SPRING_CLOUD_STATIC_REPO=${SPRING_CLOUD_STATIC_REPO:-git@github.com:spring-cloud/spring-cloud-static.git} + echo "Spring Cloud Static repo is [${SPRING_CLOUD_STATIC_REPO}" +} + +# Check if gh-pages exists and docs have been built +function check_if_anything_to_sync() { + git remote set-url --push origin `git config remote.origin.url | sed -e 's/^git:/https:/'` + + if ! (git remote set-branches --add origin gh-pages && git fetch -q); then + echo "No gh-pages, so not syncing" + exit 0 + fi + + if ! [ -d docs/target/generated-docs ] && ! [ "${BUILD}" == "yes" ]; then + echo "No gh-pages sources in docs/target/generated-docs, so not syncing" + exit 0 + fi +} + +function retrieve_current_branch() { + # Code getting the name of the current branch. For master we want to publish as we did until now + # http://stackoverflow.com/questions/1593051/how-to-programmatically-determine-the-current-checked-out-git-branch + # If there is a branch already passed will reuse it - otherwise will try to find it + CURRENT_BRANCH=${BRANCH} + if [[ -z "${CURRENT_BRANCH}" ]] ; then + CURRENT_BRANCH=$(git symbolic-ref -q HEAD) + CURRENT_BRANCH=${CURRENT_BRANCH##refs/heads/} + CURRENT_BRANCH=${CURRENT_BRANCH:-HEAD} + fi + echo "Current branch is [${CURRENT_BRANCH}]" + git checkout ${CURRENT_BRANCH} || echo "Failed to check the branch... continuing with the script" +} + +# Switches to the provided value of the release version. We always prefix it with `v` +function switch_to_tag() { + git checkout v${VERSION} +} + +# Build the docs if switch is on +function build_docs_if_applicable() { + if [[ "${BUILD}" == "yes" ]] ; then + ./mvnw clean install -P docs -pl docs -DskipTests + fi +} + +# Get the name of the `docs.main` property +# Get whitelisted branches - assumes that a `docs` module is available under `docs` profile +function retrieve_doc_properties() { + MAIN_ADOC_VALUE=$("${MAVEN_PATH}"mvn -q \ + -Dexec.executable="echo" \ + -Dexec.args='${docs.main}' \ + --non-recursive \ + org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) + echo "Extracted 'main.adoc' from Maven build [${MAIN_ADOC_VALUE}]" + + + WHITELIST_PROPERTY=${WHITELIST_PROPERTY:-"docs.whitelisted.branches"} + WHITELISTED_BRANCHES_VALUE=$("${MAVEN_PATH}"mvn -q \ + -Dexec.executable="echo" \ + -Dexec.args="\${${WHITELIST_PROPERTY}}" \ + org.codehaus.mojo:exec-maven-plugin:1.3.1:exec \ + -P docs \ + -pl docs) + echo "Extracted '${WHITELIST_PROPERTY}' from Maven build [${WHITELISTED_BRANCHES_VALUE}]" +} + +# Stash any outstanding changes +function stash_changes() { + git diff-index --quiet HEAD && dirty=$? || (echo "Failed to check if the current repo is dirty. Assuming that it is." && dirty="1") + if [ "$dirty" != "0" ]; then git stash; fi +} + +# Switch to gh-pages branch to sync it with current branch +function add_docs_from_target() { + local DESTINATION_REPO_FOLDER + if [[ -z "${DESTINATION}" && -z "${CLONE}" ]] ; then + DESTINATION_REPO_FOLDER=${ROOT_FOLDER} + elif [[ "${CLONE}" == "yes" ]]; then + mkdir -p ${ROOT_FOLDER}/target + local clonedStatic=${ROOT_FOLDER}/target/spring-cloud-static + if [[ ! -e "${clonedStatic}/.git" ]]; then + echo "Cloning Spring Cloud Static to target" + git clone ${SPRING_CLOUD_STATIC_REPO} ${clonedStatic} && git checkout gh-pages + else + echo "Spring Cloud Static already cloned - will pull changes" + cd ${clonedStatic} && git checkout gh-pages && git pull origin gh-pages + fi + DESTINATION_REPO_FOLDER=${clonedStatic}/${REPO_NAME} + mkdir -p ${DESTINATION_REPO_FOLDER} + else + if [[ ! -e "${DESTINATION}/.git" ]]; then + echo "[${DESTINATION}] is not a git repository" + exit 1 + fi + DESTINATION_REPO_FOLDER=${DESTINATION}/${REPO_NAME} + mkdir -p ${DESTINATION_REPO_FOLDER} + echo "Destination was provided [${DESTINATION}]" + fi + cd ${DESTINATION_REPO_FOLDER} + git checkout gh-pages + git pull origin gh-pages + + # Add git branches + ################################################################### + if [[ -z "${VERSION}" ]] ; then + copy_docs_for_current_version + else + copy_docs_for_provided_version + fi + commit_changes_if_applicable +} + + +# Copies the docs by using the retrieved properties from Maven build +function copy_docs_for_current_version() { + if [[ "${CURRENT_BRANCH}" == "master" ]] ; then + echo -e "Current branch is master - will copy the current docs only to the root folder" + for f in docs/target/generated-docs/*; do + file=${f#docs/target/generated-docs/*} + if ! git ls-files -i -o --exclude-standard --directory | grep -q ^$file$; then + # Not ignored... + cp -rf $f ${ROOT_FOLDER}/ + git add -A ${ROOT_FOLDER}/$file + fi + done + COMMIT_CHANGES="yes" + else + echo -e "Current branch is [${CURRENT_BRANCH}]" + # http://stackoverflow.com/questions/29300806/a-bash-script-to-check-if-a-string-is-present-in-a-comma-separated-list-of-strin + if [[ ",${WHITELISTED_BRANCHES_VALUE}," = *",${CURRENT_BRANCH},"* ]] ; then + mkdir -p ${ROOT_FOLDER}/${CURRENT_BRANCH} + echo -e "Branch [${CURRENT_BRANCH}] is whitelisted! Will copy the current docs to the [${CURRENT_BRANCH}] folder" + for f in docs/target/generated-docs/*; do + file=${f#docs/target/generated-docs/*} + if ! git ls-files -i -o --exclude-standard --directory | grep -q ^$file$; then + # Not ignored... + # We want users to access 2.0.0.BUILD-SNAPSHOT/ instead of 1.0.0.RELEASE/spring-cloud.sleuth.html + if [[ "${file}" == "${MAIN_ADOC_VALUE}.html" ]] ; then + # We don't want to copy the spring-cloud-sleuth.html + # we want it to be converted to index.html + cp -rf $f ${ROOT_FOLDER}/${CURRENT_BRANCH}/index.html + git add -A ${ROOT_FOLDER}/${CURRENT_BRANCH}/index.html + else + cp -rf $f ${ROOT_FOLDER}/${CURRENT_BRANCH} + git add -A ${ROOT_FOLDER}/${CURRENT_BRANCH}/$file + fi + fi + done + COMMIT_CHANGES="yes" + else + echo -e "Branch [${CURRENT_BRANCH}] is not on the white list! Check out the Maven [${WHITELIST_PROPERTY}] property in + [docs] module available under [docs] profile. Won't commit any changes to gh-pages for this branch." + fi + fi +} + +# Copies the docs by using the explicitly provided version +function copy_docs_for_provided_version() { + local FOLDER=${DESTINATION_REPO_FOLDER}/${VERSION} + mkdir -p ${FOLDER} + echo -e "Current tag is [v${VERSION}] Will copy the current docs to the [${FOLDER}] folder" + for f in ${ROOT_FOLDER}/docs/target/generated-docs/*; do + file=${f#${ROOT_FOLDER}/docs/target/generated-docs/*} + copy_docs_for_branch ${file} ${FOLDER} + done + COMMIT_CHANGES="yes" + CURRENT_BRANCH="v${VERSION}" +} + +# Copies the docs from target to the provided destination +# Params: +# $1 - file from target +# $2 - destination to which copy the files +function copy_docs_for_branch() { + local file=$1 + local destination=$2 + if ! git ls-files -i -o --exclude-standard --directory | grep -q ^${file}$; then + # Not ignored... + # We want users to access 2.0.0.BUILD-SNAPSHOT/ instead of 1.0.0.RELEASE/spring-cloud.sleuth.html + if [[ ("${file}" == "${MAIN_ADOC_VALUE}.html") || ("${file}" == "${REPO_NAME}.html") ]] ; then + # We don't want to copy the spring-cloud-sleuth.html + # we want it to be converted to index.html + cp -rf $f ${destination}/index.html + git add -A ${destination}/index.html + else + cp -rf $f ${destination} + git add -A ${destination}/$file + fi + fi +} + +function commit_changes_if_applicable() { + if [[ "${COMMIT_CHANGES}" == "yes" ]] ; then + COMMIT_SUCCESSFUL="no" + git commit -a -m "Sync docs from ${CURRENT_BRANCH} to gh-pages" && COMMIT_SUCCESSFUL="yes" || echo "Failed to commit changes" + + # Uncomment the following push if you want to auto push to + # the gh-pages branch whenever you commit to master locally. + # This is a little extreme. Use with care! + ################################################################### + if [[ "${COMMIT_SUCCESSFUL}" == "yes" ]] ; then + git push origin gh-pages + fi + fi +} + +# Switch back to the previous branch and exit block +function checkout_previous_branch() { + # If -version was provided we need to come back to root project + cd ${ROOT_FOLDER} + git checkout ${CURRENT_BRANCH} || echo "Failed to check the branch... continuing with the script" + if [ "$dirty" != "0" ]; then git stash pop; fi + exit 0 +} + +# Assert if properties have been properly passed +function assert_properties() { +echo "VERSION [${VERSION}], DESTINATION [${DESTINATION}], CLONE [${CLONE}]" +if [[ "${VERSION}" != "" && (-z "${DESTINATION}" && -z "${CLONE}") ]] ; then echo "Version was set but destination / clone was not!"; exit 1;fi +if [[ ("${DESTINATION}" != "" && "${CLONE}" != "") && -z "${VERSION}" ]] ; then echo "Destination / clone was set but version was not!"; exit 1;fi +if [[ "${DESTINATION}" != "" && "${CLONE}" == "yes" ]] ; then echo "Destination and clone was set. Pick one!"; exit 1;fi +} + +# Prints the usage +function print_usage() { +cat </` +- if the destination switch is passed (-d) then the script will check if the provided dir is a git repo and then will + switch to gh-pages of that repo and copy the generated docs to `docs//` + +USAGE: + +You can use the following options: + +-v|--version - the script will apply the whole procedure for a particular library version +-d|--destination - the root of destination folder where the docs should be copied. You have to use the full path. + E.g. point to spring-cloud-static folder. Can't be used with (-c) +-b|--build - will run the standard build process after checking out the branch +-c|--clone - will automatically clone the spring-cloud-static repo instead of providing the destination. + Obviously can't be used with (-d) + +EOF +} + + +# ========================================== +# ____ ____ _____ _____ _____ _______ +# / ____|/ ____| __ \|_ _| __ \__ __| +# | (___ | | | |__) | | | | |__) | | | +# \___ \| | | _ / | | | ___/ | | +# ____) | |____| | \ \ _| |_| | | | +# |_____/ \_____|_| \_\_____|_| |_| +# +# ========================================== + +while [[ $# > 0 ]] +do +key="$1" +case ${key} in + -v|--version) + VERSION="$2" + shift # past argument + ;; + -d|--destination) + DESTINATION="$2" + shift # past argument + ;; + -b|--build) + BUILD="yes" + ;; + -c|--clone) + CLONE="yes" + ;; + -h|--help) + print_usage + exit 0 + ;; + *) + echo "Invalid option: [$1]" + print_usage + exit 1 + ;; +esac +shift # past argument or value +done + +assert_properties +set_default_props +check_if_anything_to_sync +if [[ -z "${VERSION}" ]] ; then + retrieve_current_branch +else + switch_to_tag +fi +build_docs_if_applicable +retrieve_doc_properties +stash_changes +add_docs_from_target +checkout_previous_branch \ No newline at end of file diff --git a/spring-cloud-function/2.0.1.RELEASE/images/background.png b/spring-cloud-function/2.0.1.RELEASE/images/background.png new file mode 100644 index 00000000..15dca6fb Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/images/background.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/images/callouts/1.png b/spring-cloud-function/2.0.1.RELEASE/images/callouts/1.png new file mode 100644 index 00000000..7d473430 Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/images/callouts/1.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/images/callouts/2.png b/spring-cloud-function/2.0.1.RELEASE/images/callouts/2.png new file mode 100644 index 00000000..5d09341b Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/images/callouts/2.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/images/callouts/3.png b/spring-cloud-function/2.0.1.RELEASE/images/callouts/3.png new file mode 100644 index 00000000..ef7b7004 Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/images/callouts/3.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/images/caution.png b/spring-cloud-function/2.0.1.RELEASE/images/caution.png new file mode 100644 index 00000000..8a5e4fca Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/images/caution.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/images/important.png b/spring-cloud-function/2.0.1.RELEASE/images/important.png new file mode 100644 index 00000000..ec54df65 Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/images/important.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/images/logo.png b/spring-cloud-function/2.0.1.RELEASE/images/logo.png new file mode 100644 index 00000000..ade2ce6e Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/images/logo.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/images/note.png b/spring-cloud-function/2.0.1.RELEASE/images/note.png new file mode 100644 index 00000000..88d997b1 Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/images/note.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/images/remove.txt b/spring-cloud-function/2.0.1.RELEASE/images/remove.txt new file mode 100644 index 00000000..bbd40769 --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/images/remove.txt @@ -0,0 +1 @@ +please remove once this directory is not empty \ No newline at end of file diff --git a/spring-cloud-function/2.0.1.RELEASE/images/tip.png b/spring-cloud-function/2.0.1.RELEASE/images/tip.png new file mode 100644 index 00000000..6530abb4 Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/images/tip.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/images/warning.png b/spring-cloud-function/2.0.1.RELEASE/images/warning.png new file mode 100644 index 00000000..0d5b5244 Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/images/warning.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/index.html b/spring-cloud-function/2.0.1.RELEASE/index.html new file mode 100644 index 00000000..c628e5aa --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/index.html @@ -0,0 +1,117 @@ + + + + + + + +spring-cloud-function + + + + + + + + +
+
+
+
+

2.0.1.RELEASE

+
+
+
+
+

Pick The Documentation Option

+
+
+ +
+
+
+
+ + + + + \ No newline at end of file diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/css/highlight.css b/spring-cloud-function/2.0.1.RELEASE/multi/css/highlight.css new file mode 100644 index 00000000..ffefef72 --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/multi/css/highlight.css @@ -0,0 +1,35 @@ +/* + code highlight CSS resemblign the Eclipse IDE default color schema + @author Costin Leau +*/ + +.hl-keyword { + color: #7F0055; + font-weight: bold; +} + +.hl-comment { + color: #3F5F5F; + font-style: italic; +} + +.hl-multiline-comment { + color: #3F5FBF; + font-style: italic; +} + +.hl-tag { + color: #3F7F7F; +} + +.hl-attribute { + color: #7F007F; +} + +.hl-value { + color: #2A00FF; +} + +.hl-string { + color: #2A00FF; +} \ No newline at end of file diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/css/manual-multipage.css b/spring-cloud-function/2.0.1.RELEASE/multi/css/manual-multipage.css new file mode 100644 index 00000000..0c484531 --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/multi/css/manual-multipage.css @@ -0,0 +1,9 @@ +@IMPORT url("manual.css"); + +body.firstpage { + background: url("../images/background.png") no-repeat center top; +} + +div.part h1 { + border-top: none; +} diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/css/manual-singlepage.css b/spring-cloud-function/2.0.1.RELEASE/multi/css/manual-singlepage.css new file mode 100644 index 00000000..4a7fd140 --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/multi/css/manual-singlepage.css @@ -0,0 +1,6 @@ +@IMPORT url("manual.css"); + +body { + background: url("../images/background.png") no-repeat center top; +} + diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/css/manual.css b/spring-cloud-function/2.0.1.RELEASE/multi/css/manual.css new file mode 100644 index 00000000..0ecbe2e8 --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/multi/css/manual.css @@ -0,0 +1,344 @@ +@IMPORT url("highlight.css"); + +html { + padding: 0pt; + margin: 0pt; +} + +body { + color: #333333; + margin: 15px 30px; + font-family: Helvetica, Arial, Freesans, Clean, Sans-serif; + line-height: 1.6; + -webkit-font-smoothing: antialiased; +} + +code { + font-size: 16px; + font-family: Consolas, "Liberation Mono", Courier, monospace; +} + +:not(a)>code { + color: #6D180B; +} + +:not(pre)>code { + background-color: #F2F2F2; + border: 1px solid #CCCCCC; + border-radius: 4px; + padding: 1px 3px 0; + text-shadow: none; + white-space: nowrap; +} + +body>*:first-child { + margin-top: 0 !important; +} + +div { + margin: 0pt; +} + +hr { + border: 1px solid #CCCCCC; + background: #CCCCCC; +} + +h1,h2,h3,h4,h5,h6 { + color: #000000; + cursor: text; + font-weight: bold; + margin: 30px 0 10px; + padding: 0; +} + +h1,h2,h3 { + margin: 40px 0 10px; +} + +h1 { + margin: 70px 0 30px; + padding-top: 20px; +} + +div.part h1 { + border-top: 1px dotted #CCCCCC; +} + +h1,h1 code { + font-size: 32px; +} + +h2,h2 code { + font-size: 24px; +} + +h3,h3 code { + font-size: 20px; +} + +h4,h1 code,h5,h5 code,h6,h6 code { + font-size: 18px; +} + +div.book,div.chapter,div.appendix,div.part,div.preface { + min-width: 300px; + max-width: 1200px; + margin: 0 auto; +} + +p.releaseinfo { + font-weight: bold; + margin-bottom: 40px; + margin-top: 40px; +} + +div.authorgroup { + line-height: 1; +} + +p.copyright { + line-height: 1; + margin-bottom: -5px; +} + +.legalnotice p { + font-style: italic; + font-size: 14px; + line-height: 1; +} + +div.titlepage+p,div.titlepage+p { + margin-top: 0; +} + +pre { + line-height: 1.0; + color: black; +} + +a { + color: #4183C4; + text-decoration: none; +} + +p { + margin: 15px 0; + text-align: left; +} + +ul,ol { + padding-left: 30px; +} + +li p { + margin: 0; +} + +div.table { + margin: 1em; + padding: 0.5em; + text-align: center; +} + +div.table table,div.informaltable table { + display: table; + width: 100%; +} + +div.table td { + padding-left: 7px; + padding-right: 7px; +} + +.sidebar { + line-height: 1.4; + padding: 0 20px; + background-color: #F8F8F8; + border: 1px solid #CCCCCC; + border-radius: 3px 3px 3px 3px; +} + +.sidebar p.title { + color: #6D180B; +} + +pre.programlisting,pre.screen { + font-size: 15px; + padding: 6px 10px; + background-color: #F8F8F8; + border: 1px solid #CCCCCC; + border-radius: 3px 3px 3px 3px; + clear: both; + overflow: auto; + line-height: 1.4; + font-family: Consolas, "Liberation Mono", Courier, monospace; +} + +table { + border-collapse: collapse; + border-spacing: 0; + border: 1px solid #DDDDDD !important; + border-radius: 4px !important; + border-collapse: separate !important; + line-height: 1.6; +} + +table thead { + background: #F5F5F5; +} + +table tr { + border: none; + border-bottom: none; +} + +table th { + font-weight: bold; +} + +table th,table td { + border: none !important; + padding: 6px 13px; +} + +table tr:nth-child(2n) { + background-color: #F8F8F8; +} + +td p { + margin: 0 0 15px 0; +} + +div.table-contents td p { + margin: 0; +} + +div.important *,div.note *,div.tip *,div.warning *,div.navheader *,div.navfooter *,div.calloutlist * + { + border: none !important; + background: none !important; + margin: 0; +} + +div.important p,div.note p,div.tip p,div.warning p { + color: #6F6F6F; + line-height: 1.6; +} + +div.important code,div.note code,div.tip code,div.warning code { + background-color: #F2F2F2 !important; + border: 1px solid #CCCCCC !important; + border-radius: 4px !important; + padding: 1px 3px 0 !important; + text-shadow: none !important; + white-space: nowrap !important; +} + +.note th,.tip th,.warning th { + display: none; +} + +.note tr:first-child td,.tip tr:first-child td,.warning tr:first-child td + { + border-right: 1px solid #CCCCCC !important; + padding-top: 10px; +} + +div.calloutlist p,div.calloutlist td { + padding: 0; + margin: 0; +} + +div.calloutlist>table>tbody>tr>td:first-child { + padding-left: 10px; + width: 30px !important; +} + +div.important,div.note,div.tip,div.warning { + margin-left: 0px !important; + margin-right: 20px !important; + margin-top: 20px; + margin-bottom: 20px; + padding-top: 10px; + padding-bottom: 10px; +} + +div.toc { + line-height: 1.2; +} + +dl,dt { + margin-top: 1px; + margin-bottom: 0; +} + +div.toc>dl>dt { + font-size: 32px; + font-weight: bold; + margin: 30px 0 10px 0; + display: block; +} + +div.toc>dl>dd>dl>dt { + font-size: 24px; + font-weight: bold; + margin: 20px 0 10px 0; + display: block; +} + +div.toc>dl>dd>dl>dd>dl>dt { + font-weight: bold; + font-size: 20px; + margin: 10px 0 0 0; +} + +tbody.footnotes * { + border: none !important; +} + +div.footnote p { + margin: 0; + line-height: 1; +} + +div.footnote p sup { + margin-right: 6px; + vertical-align: middle; +} + +div.navheader { + border-bottom: 1px solid #CCCCCC; +} + +div.navfooter { + border-top: 1px solid #CCCCCC; +} + +.title { + margin-left: -1em; + padding-left: 1em; +} + +.title>a { + position: absolute; + visibility: hidden; + display: block; + font-size: 0.85em; + margin-top: 0.05em; + margin-left: -1em; + vertical-align: text-top; + color: black; +} + +.title>a:before { + content: "\00A7"; +} + +.title:hover>a,.title>a:hover,.title:hover>a:hover { + visibility: visible; +} + +.title:focus>a,.title>a:focus,.title:focus>a:focus { + outline: 0; +} diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/images/background.png b/spring-cloud-function/2.0.1.RELEASE/multi/images/background.png new file mode 100644 index 00000000..15dca6fb Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/multi/images/background.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/images/callouts/1.png b/spring-cloud-function/2.0.1.RELEASE/multi/images/callouts/1.png new file mode 100644 index 00000000..7d473430 Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/multi/images/callouts/1.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/images/callouts/2.png b/spring-cloud-function/2.0.1.RELEASE/multi/images/callouts/2.png new file mode 100644 index 00000000..5d09341b Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/multi/images/callouts/2.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/images/callouts/3.png b/spring-cloud-function/2.0.1.RELEASE/multi/images/callouts/3.png new file mode 100644 index 00000000..ef7b7004 Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/multi/images/callouts/3.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/images/caution.png b/spring-cloud-function/2.0.1.RELEASE/multi/images/caution.png new file mode 100644 index 00000000..8a5e4fca Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/multi/images/caution.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/images/important.png b/spring-cloud-function/2.0.1.RELEASE/multi/images/important.png new file mode 100644 index 00000000..ec54df65 Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/multi/images/important.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/images/logo.png b/spring-cloud-function/2.0.1.RELEASE/multi/images/logo.png new file mode 100644 index 00000000..ade2ce6e Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/multi/images/logo.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/images/note.png b/spring-cloud-function/2.0.1.RELEASE/multi/images/note.png new file mode 100644 index 00000000..88d997b1 Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/multi/images/note.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/images/tip.png b/spring-cloud-function/2.0.1.RELEASE/multi/images/tip.png new file mode 100644 index 00000000..6530abb4 Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/multi/images/tip.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/images/warning.png b/spring-cloud-function/2.0.1.RELEASE/multi/images/warning.png new file mode 100644 index 00000000..0d5b5244 Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/multi/images/warning.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/multi__building_and_running_a_function.html b/spring-cloud-function/2.0.1.RELEASE/multi/multi__building_and_running_a_function.html new file mode 100644 index 00000000..3e45435e --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/multi/multi__building_and_running_a_function.html @@ -0,0 +1,18 @@ + + + 3. Building and Running a Function

3. Building and Running a Function

The sample @SpringBootApplication above has a function that can be +decorated at runtime by Spring Cloud Function to be an HTTP endpoint, +or a Stream processor, for instance with RabbitMQ, Apache Kafka or +JMS.

The @Beans can be Function, Consumer or Supplier (all from +java.util), and their parametric types can be String or POJO.

Functions can also be of Flux<String> or Flux<Pojo> and Spring +Cloud Function takes care of converting the data to and from the +desired types, as long as it comes in as plain text or (in the case of +the POJO) JSON. There is also support for Message<Pojo> where the +message headers are copied from the incoming event, depending on the +adapter. The web adapter also supports conversion from form-encoded +data to a Map, and if you are using the function with Spring Cloud +Stream then all the conversion and coercion features for message +payloads will be applicable as well.

Functions can be grouped together in a single application, or deployed +one-per-jar. It’s up to the developer to choose. An app with multiple +functions can be deployed multiple times in different "personalities", +exposing different functions over different physical transports.

\ No newline at end of file diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/multi__deploying_a_packaged_function.html b/spring-cloud-function/2.0.1.RELEASE/multi/multi__deploying_a_packaged_function.html new file mode 100644 index 00000000..f9cfcd9c --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/multi/multi__deploying_a_packaged_function.html @@ -0,0 +1,3 @@ + + + 7. Deploying a Packaged Function

7. Deploying a Packaged Function

Spring Cloud Function provides a "deployer" library that allows you to launch a jar file (or exploded archive, or set of jar files) with an isolated class loader and expose the functions defined in it. This is quite a powerful tool that would allow you to, for instance, adapt a function to a range of different input-output adapters without changing the target jar file. Serverless platforms often have this kind of feature built in, so you could see it as a building block for a function invoker in such a platform (indeed the Riff Java function invoker uses this library).

The standard entry point of the API is the Spring configuration annotation @EnableFunctionDeployer. If that is used in a Spring Boot application the deployer kicks in and looks for some configuration to tell it where to find the function jar. At a minimum the user has to provide a function.location which is a URL or resource location for the archive containing the functions. It can optionally use a maven: prefix to locate the artifact via a dependency lookup (see FunctionProperties for complete details). A Spring Boot application is bootstrapped from the jar file, using the MANIFEST.MF to locate a start class, so that a standard Spring Boot fat jar works well, for example. If the target jar can be launched successfully then the result is a function registered in the main application’s FunctionCatalog. The registered function can be applied by code in the main application, even though it was created in an isolated class loader (by deault).

\ No newline at end of file diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/multi__dynamic_compilation.html b/spring-cloud-function/2.0.1.RELEASE/multi/multi__dynamic_compilation.html new file mode 100644 index 00000000..6c6ba26a --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/multi/multi__dynamic_compilation.html @@ -0,0 +1,23 @@ + + + 9. Dynamic Compilation

9. Dynamic Compilation

There is a sample app that uses the function compiler to create a +function from a configuration property. The vanilla "function-sample" +also has that feature. And there are some scripts that you can run to +see the compilation happening at run time. To run these examples, +change into the scripts directory:

cd scripts

Also, start a RabbitMQ server locally (e.g. execute rabbitmq-server).

Start the Function Registry Service:

./function-registry.sh

Register a Function:

./registerFunction.sh -n uppercase -f "f->f.map(s->s.toString().toUpperCase())"

Run a REST Microservice using that Function:

./web.sh -f uppercase -p 9000
+curl -H "Content-Type: text/plain" -H "Accept: text/plain" localhost:9000/uppercase -d foo

Register a Supplier:

./registerSupplier.sh -n words -f "()->Flux.just(\"foo\",\"bar\")"

Run a REST Microservice using that Supplier:

./web.sh -s words -p 9001
+curl -H "Accept: application/json" localhost:9001/words

Register a Consumer:

./registerConsumer.sh -n print -t String -f "System.out::println"

Run a REST Microservice using that Consumer:

./web.sh -c print -p 9002
+curl -X POST -H "Content-Type: text/plain" -d foo localhost:9002/print

Run Stream Processing Microservices:

First register a streaming words supplier:

./registerSupplier.sh -n wordstream -f "()->Flux.interval(Duration.ofMillis(1000)).map(i->\"message-\"+i)"

Then start the source (supplier), processor (function), and sink (consumer) apps +(in reverse order):

./stream.sh -p 9103 -i uppercaseWords -c print
+./stream.sh -p 9102 -i words -f uppercase -o uppercaseWords
+./stream.sh -p 9101 -s wordstream -o words

The output will appear in the console of the sink app (one message per second, converted to uppercase):

MESSAGE-0
+MESSAGE-1
+MESSAGE-2
+MESSAGE-3
+MESSAGE-4
+MESSAGE-5
+MESSAGE-6
+MESSAGE-7
+MESSAGE-8
+MESSAGE-9
+...
\ No newline at end of file diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/multi__function_catalog_and_flexible_function_signatures.html b/spring-cloud-function/2.0.1.RELEASE/multi/multi__function_catalog_and_flexible_function_signatures.html new file mode 100644 index 00000000..8bae2c55 --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/multi/multi__function_catalog_and_flexible_function_signatures.html @@ -0,0 +1,39 @@ + + + 4. Function Catalog and Flexible Function Signatures

4. Function Catalog and Flexible Function Signatures

One of the main features of Spring Cloud Function is to adapt and support a range of type signatures for user-defined functions, +while providing a consistent execution model. +That’s why all user defined functions are transformed into a canonical representation by FunctionCatalog, using primitives +defined by the Project Reactor (i.e., Flux<T> and Mono<T>). +Users can supply a bean of type Function<String,String>, for instance, and the FunctionCatalog will wrap it into a +Function<Flux<String>,Flux<String>>.

Using Reactor based primitives not only helps with the canonical representation of user defined functions, but it also +facilitates a more robust and flexible(reactive) execution model.

While users don’t normally have to care about the FunctionCatalog at all, it is useful to know what +kind of functions are supported in user code.

4.1 Java 8 function support

Generally speaking users can expect that if they write a function for +a plain old Java type (or primitive wrapper), then the function +catalog will wrap it to a Flux of the same type. If the user writes +a function using Message (from spring-messaging) it will receive and +transmit headers from any adapter that supports key-value metadata +(e.g. HTTP headers). Here are the details.

User FunctionCatalog Registration 

Function<S,T>

Function<Flux<S>, Flux<T>>

 

Function<Message<S>,Message<T>>

Function<Flux<Message<S>>, Flux<Message<T>>>

 

Function<Flux<S>, Flux<T>>

Function<Flux<S>, Flux<T>> (pass through)

 

Supplier<T>

Supplier<Flux<T>>

 

Supplier<Flux<T>>

Supplier<Flux<T>>

 

Consumer<T>

Function<Flux<T>, Mono<Void>>

 

Consumer<Message<T>>

Function<Flux<Message<T>>, Mono<Void>>

 

Consumer<Flux<T>>

Consumer<Flux<T>>

 

Consumer is a little bit special because it has a void return type, +which implies blocking, at least potentially. Most likely you will not +need to write Consumer<Flux<?>>, but if you do need to do that, +remember to subscribe to the input flux. If you declare a Consumer +of a non publisher type (which is normal), it will be converted to a +function that returns a publisher, so that it can be subscribed to in +a controlled way.

4.2 Kotlin Lambda support

We also provide support for Kotlin lambdas (since v2.0). +Consider the following:

@Bean
+open fun kotlinSupplier(): () -> String {
+    return  { "Hello from Kotlin" }
+}
+
+@Bean
+open fun kotlinFunction(): (String) -> String {
+    return  { it.toUpperCase() }
+}
+
+@Bean
+open fun kotlinConsumer(): (String) -> Unit {
+    return  { println(it) }
+}

The above represents Kotlin lambdas configured as Spring beans. The signature of each maps to a Java equivalent of +Supplier, Function and Consumer, and thus supported/recognized signatures by the framework. +While mechanics of Kotlin-to-Java mapping are outside of the scope of this documentation, it is important to understand that the +same rules for signature transformation outlined in "Java 8 function support" section are applied here as well.

To enable Kotlin support all you need is to add spring-cloud-function-kotlin module to your classpath which contains the appropriate +autoconfiguration and supporting classes.

\ No newline at end of file diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/multi__functional_bean_definitions.html b/spring-cloud-function/2.0.1.RELEASE/multi/multi__functional_bean_definitions.html new file mode 100644 index 00000000..81ec07bc --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/multi/multi__functional_bean_definitions.html @@ -0,0 +1,81 @@ + + + 8. Functional Bean Definitions

8. Functional Bean Definitions

Spring Cloud Function supports a "functional" style of bean declarations for small apps where you need fast startup. The functional style of bean declaration was a feature of Spring Framework 5.0 with significant enhancements in 5.1.

8.1 Comparing Functional with Traditional Bean Definitions

Here’s a vanilla Spring Cloud Function application from with the +familiar @Configuration and @Bean declaration style:

@SpringBootApplication
+public class DemoApplication {
+
+  @Bean
+  public Function<String, String> uppercase() {
+    return value -> value.toUpperCase();
+  }
+
+  public static void main(String[] args) {
+    SpringApplication.run(DemoApplication.class, args);
+  }
+
+}

You can run the above in a serverless platform, like AWS Lambda or Azure Functions, or you can run it in its own HTTP server just by including spring-cloud-function-starter-web on the classpath. Running the main method would expose an endpoint that you can use to ping that uppercase function:

$ curl localhost:8080 -d foo
+FOO

The web adapter in spring-cloud-function-starter-web uses Spring MVC, so you needed a Servlet container. You can also use Webflux where the default server is netty (even though you can still use Servlet containers if you want to) - just include the spring-cloud-starter-function-webflux dependency instead. The functionality is the same, and the user application code can be used in both.

Now for the functional beans: the user application code can be recast into "functional" +form, like this:

@SpringBootConfiguration
+public class DemoApplication implements ApplicationContextInitializer<GenericApplicationContext> {
+
+  public static void main(String[] args) {
+    FunctionalSpringApplication.run(DemoApplication.class, args);
+  }
+
+  public Function<String, String> uppercase() {
+    return value -> value.toUpperCase();
+  }
+
+  @Override
+  public void initialize(GenericApplicationContext context) {
+    context.registerBean("demo", FunctionRegistration.class,
+        () -> new FunctionRegistration<>(uppercase())
+            .type(FunctionType.from(String.class).to(String.class)));
+  }
+
+}

The main differences are:

  • The main class is an ApplicationContextInitializer.
  • The @Bean methods have been converted to calls to context.registerBean()
  • The @SpringBootApplication has been replaced with +@SpringBootConfiguration to signify that we are not enabling Spring +Boot autoconfiguration, and yet still marking the class as an "entry +point".
  • The SpringApplication from Spring Boot has been replaced with a +FunctionalSpringApplication from Spring Cloud Function (it’s a +subclass).

The business logic beans that you register in a Spring Cloud Function app are of type FunctionRegistration. This is a wrapper that contains both the function and information about the input and output types. In the @Bean form of the application that information can be derived reflectively, but in a functional bean registration some of it is lost unless we use a FunctionRegistration.

An alternative to using an ApplicationContextInitializer and FunctionRegistration is to make the application itself implement Function (or Consumer or Supplier). Example (equivalent to the above):

@SpringBootConfiguration
+public class DemoApplication implements Function<String, String> {
+
+  public static void main(String[] args) {
+    FunctionalSpringApplication.run(DemoApplication.class, args);
+  }
+
+  @Override
+  public String uppercase(String value) {
+    return value.toUpperCase();
+  }
+
+}

It would also work if you add a separate, standalone class of type Function and register it with the SpringApplication using an alternative form of the run() method. The main thing is that the generic type information is available at runtime through the class declaration.

The app runs in its own HTTP server if you add spring-cloud-starter-function-webflux (it won’t work with the MVC starter at the moment because the functional form of the embedded Servlet container hasn’t been implemented). The app also runs just fine in AWS Lambda or Azure Functions, and the improvements in startup time are dramatic.

[Note]Note

The "lite" web server has some limitations for the range of Function signatures - in particular it doesn’t (yet) support Message input and output, but POJOs and any kind of Publisher should be fine.

8.2 Testing Functional Applications

Spring Cloud Function also has some utilities for integration testing that will be very familiar to Spring Boot users. For example, here is an integration test for the HTTP server wrapping the app above:

@RunWith(SpringRunner.class)
+@FunctionalSpringBootTest
+@AutoConfigureWebTestClient
+public class FunctionalTests {
+
+	@Autowired
+	private WebTestClient client;
+
+	@Test
+	public void words() throws Exception {
+		client.post().uri("/").body(Mono.just("foo"), String.class).exchange()
+				.expectStatus().isOk().expectBody(String.class).isEqualTo("FOO");
+	}
+
+}

This test is almost identical to the one you would write for the @Bean version of the same app - the only difference is the @FunctionalSpringBootTest annotation, instead of the regular @SpringBootTest. All the other pieces, like the @Autowired WebTestClient, are standard Spring Boot features.

Or you could write a test for a non-HTTP app using just the FunctionCatalog. For example:

@RunWith(SpringRunner.class)
+@FunctionalSpringBootTest
+public class FunctionalTests {
+
+	@Autowired
+	private FunctionCatalog catalog;
+
+	@Test
+	public void words() throws Exception {
+		Function<Flux<String>, Flux<String>> function = catalog.lookup(Function.class,
+				"function");
+		assertThat(function.apply(Flux.just("foo")).blockFirst()).isEqualTo("FOO");
+	}
+
+}

(The FunctionCatalog always returns functions from Flux to Flux, even if the user declares them with a simpler signature.)

8.3 Limitations of Functional Bean Declaration

Most Spring Cloud Function apps have a relatively small scope compared to the whole of Spring Boot, so we are able to adapt it to these functional bean definitions easily. If you step outside that limited scope, you can extend your Spring Cloud Function app by switching back to @Bean style configuration, or by using a hybrid approach. If you want to take advantage of Spring Boot autoconfiguration for integrations with external datastores, for example, you will need to use @EnableAutoConfiguration. Your functions can still be defined using the functional declarations if you want (i.e. the "hybrid" style), but in that case you will need to explicitly switch off the "full functional mode" using spring.functional.enabled=false so that Spring Boot can take back control.

\ No newline at end of file diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/multi__getting_started.html b/spring-cloud-function/2.0.1.RELEASE/multi/multi__getting_started.html new file mode 100644 index 00000000..187512aa --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/multi/multi__getting_started.html @@ -0,0 +1,9 @@ + + + 2. Getting Started

2. Getting Started

Build from the command line (and "install" the samples):

$ ./mvnw clean install

(If you like to YOLO add -DskipTests.)

Run one of the samples, e.g.

$ java -jar spring-cloud-function-samples/function-sample/target/*.jar

This runs the app and exposes its functions over HTTP, so you can +convert a string to uppercase, like this:

$ curl -H "Content-Type: text/plain" localhost:8080/uppercase -d Hello
+HELLO

You can convert multiple strings (a Flux<String>) by separating them +with new lines

$ curl -H "Content-Type: text/plain" localhost:8080/uppercase -d 'Hello
+> World'
+HELLOWORLD

(You can use QJ in a terminal to insert a new line in a literal +string like that.)

\ No newline at end of file diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/multi__introduction.html b/spring-cloud-function/2.0.1.RELEASE/multi/multi__introduction.html new file mode 100644 index 00000000..ecf88f8a --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/multi/multi__introduction.html @@ -0,0 +1,27 @@ + + + 1. Introduction

1. Introduction

Spring Cloud Function is a project with the following high-level goals:

  • Promote the implementation of business logic via functions.
  • Decouple the development lifecycle of business logic from any specific runtime target so that the same code can run as a web endpoint, a stream processor, or a task.
  • Support a uniform programming model across serverless providers, as well as the ability to run standalone (locally or in a PaaS).
  • Enable Spring Boot features (auto-configuration, dependency injection, metrics) on serverless providers.

It abstracts away all of the transport details and +infrastructure, allowing the developer to keep all the familiar tools +and processes, and focus firmly on business logic.

Here’s a complete, executable, testable Spring Boot application +(implementing a simple string manipulation):

@SpringBootApplication
+public class Application {
+
+  @Bean
+  public Function<Flux<String>, Flux<String>> uppercase() {
+    return flux -> flux.map(value -> value.toUpperCase());
+  }
+
+  public static void main(String[] args) {
+    SpringApplication.run(Application.class, args);
+  }
+}

It’s just a Spring Boot application, so it can be built, run and +tested, locally and in a CI build, the same way as any other Spring +Boot application. The Function is from java.util and Flux is a +Reactive Streams Publisher from +Project Reactor. The function can be +accessed over HTTP or messaging.

Spring Cloud Function has 4 main features:

  1. Wrappers for @Beans of type Function, Consumer and +Supplier, exposing them to the outside world as either HTTP +endpoints and/or message stream listeners/publishers with RabbitMQ, Kafka etc.
  2. Compiling strings which are Java function bodies into bytecode, and +then turning them into @Beans that can be wrapped as above.
  3. Deploying a JAR file containing such an application context with an +isolated classloader, so that you can pack them together in a single +JVM.
  4. Adapters for AWS Lambda, Azure, Apache OpenWhisk and possibly other "serverless" service providers.
[Note]Note

Spring Cloud is released under the non-restrictive Apache 2.0 license. If you would like to contribute to this section of the documentation or if you find an error, please find the source code and issue trackers in the project at github.

\ No newline at end of file diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/multi__serverless_platform_adapters.html b/spring-cloud-function/2.0.1.RELEASE/multi/multi__serverless_platform_adapters.html new file mode 100644 index 00000000..3ede28a2 --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/multi/multi__serverless_platform_adapters.html @@ -0,0 +1,49 @@ + + + 10. Serverless Platform Adapters

10. Serverless Platform Adapters

As well as being able to run as a standalone process, a Spring Cloud +Function application can be adapted to run one of the existing +serverless platforms. In the project there are adapters for +AWS +Lambda, +Azure, +and +Apache +OpenWhisk. The Oracle Fn platform +has its own Spring Cloud Function adapter. And +Riff supports Java functions and its +Java Function +Invoker acts natively is an adapter for Spring Cloud Function jars.

10.1 AWS Lambda

The AWS adapter takes a Spring Cloud Function app and converts it to a form that can run in AWS Lambda.

10.1.1 Introduction

The adapter has a couple of generic request handlers that you can use. The most generic is SpringBootStreamHandler, which uses a Jackson ObjectMapper provided by Spring Boot to serialize and deserialize the objects in the function. There is also a SpringBootRequestHandler which you can extend, and provide the input and output types as type parameters (enabling AWS to inspect the class and do the JSON conversions itself).

If your app has more than one @Bean of type Function etc. then you can choose the one to use by configuring function.name (e.g. as FUNCTION_NAME environment variable in AWS). The functions are extracted from the Spring Cloud FunctionCatalog (searching first for Function then Consumer and finally Supplier).

10.1.2 Notes on JAR Layout

You don’t need the Spring Cloud Function Web or Stream adapter at runtime in Lambda, so you might need to exclude those before you create the JAR you send to AWS. A Lambda application has to be shaded, but a Spring Boot standalone application does not, so you can run the same app using 2 separate jars (as per the sample). The sample app creates 2 jar files, one with an aws classifier for deploying in Lambda, and one executable (thin) jar that includes spring-cloud-function-web at runtime. Spring Cloud Function will try and locate a "main class" for you from the JAR file manifest, using the Start-Class attribute (which will be added for you by the Spring Boot tooling if you use the starter parent). If there is no Start-Class in your manifest you can use an environment variable MAIN_CLASS when you deploy the function to AWS.

10.1.3 Upload

Build the sample under spring-cloud-function-samples/function-sample-aws and upload the -aws jar file to Lambda. The handler can be example.Handler or org.springframework.cloud.function.adapter.aws.SpringBootStreamHandler (FQN of the class, not a method reference, although Lambda does accept method references).

./mvnw -U clean package

Using the AWS command line tools it looks like this:

aws lambda create-function --function-name Uppercase --role arn:aws:iam::[USERID]:role/service-role/[ROLE] --zip-file fileb://function-sample-aws/target/function-sample-aws-2.0.0.BUILD-SNAPSHOT-aws.jar --handler org.springframework.cloud.function.adapter.aws.SpringBootStreamHandler --description "Spring Cloud Function Adapter Example" --runtime java8 --region us-east-1 --timeout 30 --memory-size 1024 --publish

The input type for the function in the AWS sample is a Foo with a single property called "value". So you would need this to test it:

{
+  "value": "test"
+}
[Note]Note

The AWS sample app is written in the "functional" style (as an ApplicationContextInitializer). This is much faster on startup in Lambda than the traditional @Bean style, so if you don’t need @Beans (or @EnableAutoConfiguration) it’s a good choice. Warm starts are not affected.

10.1.4 Platfom Specific Features

HTTP and API Gateway

AWS has some platform-specific data types, including batching of messages, which is much more efficient than processing each one individually. To make use of these types you can write a function that depends on those types. Or you can rely on Spring to extract the data from the AWS types and convert it to a Spring Message. To do this you tell AWS that the function is of a specific generic handler type (depending on the AWS service) and provide a bean of type Function<Message<S>,Message<T>>, where S and T are your business data types. If there is more than one bean of type Function you may also need to configure the Spring Boot property function.name to be the name of the target bean (e.g. use FUNCTION_NAME as an environment variable).

The supported AWS services and generic handler types are listed below:

ServiceAWS TypesGeneric Handler 

API Gateway

APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent

org.springframework.cloud.function.adapter.aws.SpringBootApiGatewayRequestHandler

 

Kinesis

KinesisEvent

org.springframework.cloud.function.adapter.aws.SpringBootKinesisEventHandler

 

For example, to deploy behind an API Gateway, use --handler org.springframework.cloud.function.adapter.aws.SpringBootApiGatewayRequestHandler in your AWS command line (in via the UI) and define a @Bean of type Function<Message<Foo>,Message<Bar>> where Foo and Bar are POJO types (the data will be marshalled and unmarshalled by AWS using Jackson).

10.2 Azure Functions

The Azure adapter bootstraps a Spring Cloud Function context and channels function calls from the Azure framework into the user functions, using Spring Boot configuration where necessary. Azure Functions has quite a unique, but invasive programming model, involving annotations in user code that are specific to the platform. The easiest way to use it with Spring Cloud is to extend a base class and write a method in it with the @FunctionName annotation which delegates to a base class method.

This project provides an adapter layer for a Spring Cloud Function application onto Azure. +You can write an app with a single @Bean of type Function and it will be deployable in Azure if you get the JAR file laid out right.

There is an AzureSpringBootRequestHandler which you must extend, and provide the input and output types as annotated method parameters (enabling Azure to inspect the class and create JSON bindings). The base class has two useful methods (handleRequest and handleOutput) to which you can delegate the actual function call, so mostly the function will only ever have one line.

Example:

public class FooHandler extends AzureSpringBootRequestHandler<Foo, Bar> {
+	@FunctionName("uppercase")
+	public Bar execute(
+			@HttpTrigger(name = "req", methods = { HttpMethod.GET,
+					HttpMethod.POST }, authLevel = AuthorizationLevel.ANONYMOUS)
+                    Foo foo,
+			ExecutionContext context) {
+		return handleRequest(foo, context);
+	}
+}

This Azure handler will delegate to a Function<Foo,Bar> bean (or a Function<Publisher<Foo>,Publisher<Bar>>). Some Azure triggers (e.g. @CosmosDBTrigger) result in a input type of List and in that case you can bind to List in the Azure handler, or String (the raw JSON). The List input delegates to a Function with input type Map<String,Object>, or Publisher or List of the same type. The output of the Function can be a List (one-for-one) or a single value (aggregation), and the output binding in the Azure declaration should match.

If your app has more than one @Bean of type Function etc. then you can choose the one to use by configuring function.name. Or if you make the @FunctionName in the Azure handler method match the function name it should work that way (also for function apps with multiple functions). The functions are extracted from the Spring Cloud FunctionCatalog so the default function names are the same as the bean names.

10.2.1 Notes on JAR Layout

You don’t need the Spring Cloud Function Web at runtime in Azure, so you can exclude this before you create the JAR you deploy to Azure, but it won’t be used if you include it so it doesn’t hurt to leave it in. A function application on Azure is an archive generated by the Maven plugin. The function lives in the JAR file generated by this project. The sample creates it as an executable jar, using the thin layout, so that Azure can find the handler classes. If you prefer you can just use a regular flat JAR file. The dependencies should not be included.

10.2.2 Build

./mvnw -U clean package

10.2.3 Running the sample

You can run the sample locally, just like the other Spring Cloud Function samples:

and curl -H "Content-Type: text/plain" localhost:8080/function -d '{"value": "hello foobar"}'.

You will need the az CLI app (see https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-first-java-maven for more detail). To deploy the function on Azure runtime:

$ az login
+$ mvn azure-functions:deploy

On another terminal try this: curl https://<azure-function-url-from-the-log>/api/uppercase -d '{"value": "hello foobar!"}'. Please ensure that you use the right URL for the function above. Alternatively you can test the function in the Azure Dashboard UI (click on the function name, go to the right hand side and click "Test" and to the bottom right, "Run").

The input type for the function in the Azure sample is a Foo with a single property called "value". So you need this to test it with something like below:

{
+  "value": "foobar"
+}
[Note]Note

The Azure sample app is written in the "non-functional" style (using @Bean). The functional style (with just Function or ApplicationContextInitializer) is much faster on startup in Azure than the traditional @Bean style, so if you don’t need @Beans (or @EnableAutoConfiguration) it’s a good choice. Warm starts are not affected.

10.3 Apache Openwhisk

The OpenWhisk adapter is in the form of an executable jar that can be used in a a docker image to be deployed to Openwhisk. The platform works in request-response mode, listening on port 8080 on a specific endpoint, so the adapter is a simple Spring MVC application.

10.3.1 Quick Start

Implement a POF (be sure to use the functions package):

package functions;
+
+import java.util.function.Function;
+
+public class Uppercase implements Function<String, String> {
+
+	public String apply(String input) {
+		return input.toUpperCase();
+	}
+}

Install it into your local Maven repository:

./mvnw clean install

Create a function.properties file that provides its Maven coordinates. For example:

dependencies.function: com.example:pof:0.0.1-SNAPSHOT

Copy the openwhisk runner JAR to the working directory (same directory as the properties file):

cp spring-cloud-function-adapters/spring-cloud-function-adapter-openwhisk/target/spring-cloud-function-adapter-openwhisk-2.0.0.BUILD-SNAPSHOT.jar runner.jar

Generate a m2 repo from the --thin.dryrun of the runner JAR with the above properties file:

java -jar -Dthin.root=m2 runner.jar --thin.name=function --thin.dryrun

Use the following Dockerfile:

FROM openjdk:8-jdk-alpine
+VOLUME /tmp
+COPY m2 /m2
+ADD runner.jar .
+ADD function.properties .
+ENV JAVA_OPTS=""
+ENTRYPOINT [ "java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "runner.jar", "--thin.root=/m2", "--thin.name=function", "--function.name=uppercase"]
+EXPOSE 8080
[Note]Note

you could use a Spring Cloud Function app, instead of just a jar with a POF in it, in which case you would have to change the way the app runs in the container so that it picks up the main class as a source file. For example, you could change the ENTRYPOINT above and add --spring.main.sources=com.example.SampleApplication.

Build the Docker image:

docker build -t [username/appname] .

Push the Docker image:

docker push [username/appname]

Use the OpenWhisk CLI (e.g. after vagrant ssh) to create the action:

wsk action create example --docker [username/appname]

Invoke the action:

wsk action invoke example --result --param payload foo
+{
+    "result": "FOO"
+}
\ No newline at end of file diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/multi__standalone_streaming_applications.html b/spring-cloud-function/2.0.1.RELEASE/multi/multi__standalone_streaming_applications.html new file mode 100644 index 00000000..3b922964 --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/multi/multi__standalone_streaming_applications.html @@ -0,0 +1,4 @@ + + + 6. Standalone Streaming Applications

6. Standalone Streaming Applications

To send or receive messages from a broker (such as RabbitMQ or Kafka) you can leverage spring-cloud-stream project and it’s integration with Spring Cloud Function. +Please refer to Spring Cloud Function section of the Spring Cloud Stream reference manual for more details and examples.

\ No newline at end of file diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/multi__standalone_web_applications.html b/spring-cloud-function/2.0.1.RELEASE/multi/multi__standalone_web_applications.html new file mode 100644 index 00000000..3b03c1ef --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/multi/multi__standalone_web_applications.html @@ -0,0 +1,16 @@ + + + 5. Standalone Web Applications

5. Standalone Web Applications

The spring-cloud-function-web module has autoconfiguration that +activates when it is included in a Spring Boot web application (with +MVC support). There is also a spring-cloud-starter-function-web to +collect all the optional dependencies in case you just want a simple +getting started experience.

With the web configurations activated your app will have an MVC +endpoint (on "/" by default, but configurable with +spring.cloud.function.web.path) that can be used to access the +functions in the application context. The supported content types are +plain text and JSON.

MethodPathRequestResponseStatus

GET

/{supplier}

-

Items from the named supplier

200 OK

POST

/{consumer}

JSON object or text

Mirrors input and pushes request body into consumer

202 Accepted

POST

/{consumer}

JSON array or text with new lines

Mirrors input and pushes body into consumer one by one

202 Accepted

POST

/{function}

JSON object or text

The result of applying the named function

200 OK

POST

/{function}

JSON array or text with new lines

The result of applying the named function

200 OK

GET

/{function}/{item}

-

Convert the item into an object and return the result of applying the function

200 OK

As the table above shows the behaviour of the endpoint depends on the method and also the type of incoming request data. When the incoming data is single valued, and the target function is declared as obviously single valued (i.e. not returning a collection or Flux), then the response will also contain a single value. +For multi-valued responses the client can ask for a server-sent event stream by sending `Accept: text/event-stream".

If there is only a single function (consumer etc.) in the catalog, the name in the path is optional. +Composite functions can be addressed using pipes or commas to separate function names (pipes are legal in URL paths, but a bit awkward to type on the command line).

For cases where there is more then a single function in catalog and you want to map a specific function to the root +path (e.g., "/"), or you want to compose several functions and then map to the root path you can do so by providing +spring.cloud.function.definition property which essentially used by spring-=cloud-function-web module to provide +default mapping for cases where there is some type of a conflict (e.g., more then one function available etc).

For example,

--spring.cloud.function.definition=foo|bar

The above property will compose 'foo' and 'bar' function and map the composed function to the "/" path.

Functions and consumers that are declared with input and output in Message<?> will see the request headers on the input messages, and the output message headers will be converted to HTTP headers.

When POSTing text the response format might be different with Spring Boot 2.0 and older versions, depending on the content negotiation (provide content type and accpt headers for the best results).

\ No newline at end of file diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/multi_pr01.html b/spring-cloud-function/2.0.1.RELEASE/multi/multi_pr01.html new file mode 100644 index 00000000..b198a801 --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/multi/multi_pr01.html @@ -0,0 +1,3 @@ + + +

Mark Fisher, Dave Syer, Oleg Zhurakousky

\ No newline at end of file diff --git a/spring-cloud-function/2.0.1.RELEASE/multi/multi_spring-cloud-function.html b/spring-cloud-function/2.0.1.RELEASE/multi/multi_spring-cloud-function.html new file mode 100644 index 00000000..f1066d60 --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/multi/multi_spring-cloud-function.html @@ -0,0 +1,3 @@ + + + Spring Cloud Function \ No newline at end of file diff --git a/spring-cloud-function/2.0.1.RELEASE/single/css/highlight.css b/spring-cloud-function/2.0.1.RELEASE/single/css/highlight.css new file mode 100644 index 00000000..ffefef72 --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/single/css/highlight.css @@ -0,0 +1,35 @@ +/* + code highlight CSS resemblign the Eclipse IDE default color schema + @author Costin Leau +*/ + +.hl-keyword { + color: #7F0055; + font-weight: bold; +} + +.hl-comment { + color: #3F5F5F; + font-style: italic; +} + +.hl-multiline-comment { + color: #3F5FBF; + font-style: italic; +} + +.hl-tag { + color: #3F7F7F; +} + +.hl-attribute { + color: #7F007F; +} + +.hl-value { + color: #2A00FF; +} + +.hl-string { + color: #2A00FF; +} \ No newline at end of file diff --git a/spring-cloud-function/2.0.1.RELEASE/single/css/manual-multipage.css b/spring-cloud-function/2.0.1.RELEASE/single/css/manual-multipage.css new file mode 100644 index 00000000..0c484531 --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/single/css/manual-multipage.css @@ -0,0 +1,9 @@ +@IMPORT url("manual.css"); + +body.firstpage { + background: url("../images/background.png") no-repeat center top; +} + +div.part h1 { + border-top: none; +} diff --git a/spring-cloud-function/2.0.1.RELEASE/single/css/manual-singlepage.css b/spring-cloud-function/2.0.1.RELEASE/single/css/manual-singlepage.css new file mode 100644 index 00000000..4a7fd140 --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/single/css/manual-singlepage.css @@ -0,0 +1,6 @@ +@IMPORT url("manual.css"); + +body { + background: url("../images/background.png") no-repeat center top; +} + diff --git a/spring-cloud-function/2.0.1.RELEASE/single/css/manual.css b/spring-cloud-function/2.0.1.RELEASE/single/css/manual.css new file mode 100644 index 00000000..0ecbe2e8 --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/single/css/manual.css @@ -0,0 +1,344 @@ +@IMPORT url("highlight.css"); + +html { + padding: 0pt; + margin: 0pt; +} + +body { + color: #333333; + margin: 15px 30px; + font-family: Helvetica, Arial, Freesans, Clean, Sans-serif; + line-height: 1.6; + -webkit-font-smoothing: antialiased; +} + +code { + font-size: 16px; + font-family: Consolas, "Liberation Mono", Courier, monospace; +} + +:not(a)>code { + color: #6D180B; +} + +:not(pre)>code { + background-color: #F2F2F2; + border: 1px solid #CCCCCC; + border-radius: 4px; + padding: 1px 3px 0; + text-shadow: none; + white-space: nowrap; +} + +body>*:first-child { + margin-top: 0 !important; +} + +div { + margin: 0pt; +} + +hr { + border: 1px solid #CCCCCC; + background: #CCCCCC; +} + +h1,h2,h3,h4,h5,h6 { + color: #000000; + cursor: text; + font-weight: bold; + margin: 30px 0 10px; + padding: 0; +} + +h1,h2,h3 { + margin: 40px 0 10px; +} + +h1 { + margin: 70px 0 30px; + padding-top: 20px; +} + +div.part h1 { + border-top: 1px dotted #CCCCCC; +} + +h1,h1 code { + font-size: 32px; +} + +h2,h2 code { + font-size: 24px; +} + +h3,h3 code { + font-size: 20px; +} + +h4,h1 code,h5,h5 code,h6,h6 code { + font-size: 18px; +} + +div.book,div.chapter,div.appendix,div.part,div.preface { + min-width: 300px; + max-width: 1200px; + margin: 0 auto; +} + +p.releaseinfo { + font-weight: bold; + margin-bottom: 40px; + margin-top: 40px; +} + +div.authorgroup { + line-height: 1; +} + +p.copyright { + line-height: 1; + margin-bottom: -5px; +} + +.legalnotice p { + font-style: italic; + font-size: 14px; + line-height: 1; +} + +div.titlepage+p,div.titlepage+p { + margin-top: 0; +} + +pre { + line-height: 1.0; + color: black; +} + +a { + color: #4183C4; + text-decoration: none; +} + +p { + margin: 15px 0; + text-align: left; +} + +ul,ol { + padding-left: 30px; +} + +li p { + margin: 0; +} + +div.table { + margin: 1em; + padding: 0.5em; + text-align: center; +} + +div.table table,div.informaltable table { + display: table; + width: 100%; +} + +div.table td { + padding-left: 7px; + padding-right: 7px; +} + +.sidebar { + line-height: 1.4; + padding: 0 20px; + background-color: #F8F8F8; + border: 1px solid #CCCCCC; + border-radius: 3px 3px 3px 3px; +} + +.sidebar p.title { + color: #6D180B; +} + +pre.programlisting,pre.screen { + font-size: 15px; + padding: 6px 10px; + background-color: #F8F8F8; + border: 1px solid #CCCCCC; + border-radius: 3px 3px 3px 3px; + clear: both; + overflow: auto; + line-height: 1.4; + font-family: Consolas, "Liberation Mono", Courier, monospace; +} + +table { + border-collapse: collapse; + border-spacing: 0; + border: 1px solid #DDDDDD !important; + border-radius: 4px !important; + border-collapse: separate !important; + line-height: 1.6; +} + +table thead { + background: #F5F5F5; +} + +table tr { + border: none; + border-bottom: none; +} + +table th { + font-weight: bold; +} + +table th,table td { + border: none !important; + padding: 6px 13px; +} + +table tr:nth-child(2n) { + background-color: #F8F8F8; +} + +td p { + margin: 0 0 15px 0; +} + +div.table-contents td p { + margin: 0; +} + +div.important *,div.note *,div.tip *,div.warning *,div.navheader *,div.navfooter *,div.calloutlist * + { + border: none !important; + background: none !important; + margin: 0; +} + +div.important p,div.note p,div.tip p,div.warning p { + color: #6F6F6F; + line-height: 1.6; +} + +div.important code,div.note code,div.tip code,div.warning code { + background-color: #F2F2F2 !important; + border: 1px solid #CCCCCC !important; + border-radius: 4px !important; + padding: 1px 3px 0 !important; + text-shadow: none !important; + white-space: nowrap !important; +} + +.note th,.tip th,.warning th { + display: none; +} + +.note tr:first-child td,.tip tr:first-child td,.warning tr:first-child td + { + border-right: 1px solid #CCCCCC !important; + padding-top: 10px; +} + +div.calloutlist p,div.calloutlist td { + padding: 0; + margin: 0; +} + +div.calloutlist>table>tbody>tr>td:first-child { + padding-left: 10px; + width: 30px !important; +} + +div.important,div.note,div.tip,div.warning { + margin-left: 0px !important; + margin-right: 20px !important; + margin-top: 20px; + margin-bottom: 20px; + padding-top: 10px; + padding-bottom: 10px; +} + +div.toc { + line-height: 1.2; +} + +dl,dt { + margin-top: 1px; + margin-bottom: 0; +} + +div.toc>dl>dt { + font-size: 32px; + font-weight: bold; + margin: 30px 0 10px 0; + display: block; +} + +div.toc>dl>dd>dl>dt { + font-size: 24px; + font-weight: bold; + margin: 20px 0 10px 0; + display: block; +} + +div.toc>dl>dd>dl>dd>dl>dt { + font-weight: bold; + font-size: 20px; + margin: 10px 0 0 0; +} + +tbody.footnotes * { + border: none !important; +} + +div.footnote p { + margin: 0; + line-height: 1; +} + +div.footnote p sup { + margin-right: 6px; + vertical-align: middle; +} + +div.navheader { + border-bottom: 1px solid #CCCCCC; +} + +div.navfooter { + border-top: 1px solid #CCCCCC; +} + +.title { + margin-left: -1em; + padding-left: 1em; +} + +.title>a { + position: absolute; + visibility: hidden; + display: block; + font-size: 0.85em; + margin-top: 0.05em; + margin-left: -1em; + vertical-align: text-top; + color: black; +} + +.title>a:before { + content: "\00A7"; +} + +.title:hover>a,.title>a:hover,.title:hover>a:hover { + visibility: visible; +} + +.title:focus>a,.title>a:focus,.title:focus>a:focus { + outline: 0; +} diff --git a/spring-cloud-function/2.0.1.RELEASE/single/images/background.png b/spring-cloud-function/2.0.1.RELEASE/single/images/background.png new file mode 100644 index 00000000..15dca6fb Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/single/images/background.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/single/images/callouts/1.png b/spring-cloud-function/2.0.1.RELEASE/single/images/callouts/1.png new file mode 100644 index 00000000..7d473430 Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/single/images/callouts/1.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/single/images/callouts/2.png b/spring-cloud-function/2.0.1.RELEASE/single/images/callouts/2.png new file mode 100644 index 00000000..5d09341b Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/single/images/callouts/2.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/single/images/callouts/3.png b/spring-cloud-function/2.0.1.RELEASE/single/images/callouts/3.png new file mode 100644 index 00000000..ef7b7004 Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/single/images/callouts/3.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/single/images/caution.png b/spring-cloud-function/2.0.1.RELEASE/single/images/caution.png new file mode 100644 index 00000000..8a5e4fca Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/single/images/caution.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/single/images/important.png b/spring-cloud-function/2.0.1.RELEASE/single/images/important.png new file mode 100644 index 00000000..ec54df65 Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/single/images/important.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/single/images/logo.png b/spring-cloud-function/2.0.1.RELEASE/single/images/logo.png new file mode 100644 index 00000000..ade2ce6e Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/single/images/logo.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/single/images/note.png b/spring-cloud-function/2.0.1.RELEASE/single/images/note.png new file mode 100644 index 00000000..88d997b1 Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/single/images/note.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/single/images/tip.png b/spring-cloud-function/2.0.1.RELEASE/single/images/tip.png new file mode 100644 index 00000000..6530abb4 Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/single/images/tip.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/single/images/warning.png b/spring-cloud-function/2.0.1.RELEASE/single/images/warning.png new file mode 100644 index 00000000..0d5b5244 Binary files /dev/null and b/spring-cloud-function/2.0.1.RELEASE/single/images/warning.png differ diff --git a/spring-cloud-function/2.0.1.RELEASE/single/spring-cloud-function.html b/spring-cloud-function/2.0.1.RELEASE/single/spring-cloud-function.html new file mode 100644 index 00000000..c4afffb1 --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/single/spring-cloud-function.html @@ -0,0 +1,242 @@ + + + Spring Cloud Function

Spring Cloud Function


Mark Fisher, Dave Syer, Oleg Zhurakousky

1. Introduction

Spring Cloud Function is a project with the following high-level goals:

  • Promote the implementation of business logic via functions.
  • Decouple the development lifecycle of business logic from any specific runtime target so that the same code can run as a web endpoint, a stream processor, or a task.
  • Support a uniform programming model across serverless providers, as well as the ability to run standalone (locally or in a PaaS).
  • Enable Spring Boot features (auto-configuration, dependency injection, metrics) on serverless providers.

It abstracts away all of the transport details and +infrastructure, allowing the developer to keep all the familiar tools +and processes, and focus firmly on business logic.

Here’s a complete, executable, testable Spring Boot application +(implementing a simple string manipulation):

@SpringBootApplication
+public class Application {
+
+  @Bean
+  public Function<Flux<String>, Flux<String>> uppercase() {
+    return flux -> flux.map(value -> value.toUpperCase());
+  }
+
+  public static void main(String[] args) {
+    SpringApplication.run(Application.class, args);
+  }
+}

It’s just a Spring Boot application, so it can be built, run and +tested, locally and in a CI build, the same way as any other Spring +Boot application. The Function is from java.util and Flux is a +Reactive Streams Publisher from +Project Reactor. The function can be +accessed over HTTP or messaging.

Spring Cloud Function has 4 main features:

  1. Wrappers for @Beans of type Function, Consumer and +Supplier, exposing them to the outside world as either HTTP +endpoints and/or message stream listeners/publishers with RabbitMQ, Kafka etc.
  2. Compiling strings which are Java function bodies into bytecode, and +then turning them into @Beans that can be wrapped as above.
  3. Deploying a JAR file containing such an application context with an +isolated classloader, so that you can pack them together in a single +JVM.
  4. Adapters for AWS Lambda, Azure, Apache OpenWhisk and possibly other "serverless" service providers.
[Note]Note

Spring Cloud is released under the non-restrictive Apache 2.0 license. If you would like to contribute to this section of the documentation or if you find an error, please find the source code and issue trackers in the project at github.

2. Getting Started

Build from the command line (and "install" the samples):

$ ./mvnw clean install

(If you like to YOLO add -DskipTests.)

Run one of the samples, e.g.

$ java -jar spring-cloud-function-samples/function-sample/target/*.jar

This runs the app and exposes its functions over HTTP, so you can +convert a string to uppercase, like this:

$ curl -H "Content-Type: text/plain" localhost:8080/uppercase -d Hello
+HELLO

You can convert multiple strings (a Flux<String>) by separating them +with new lines

$ curl -H "Content-Type: text/plain" localhost:8080/uppercase -d 'Hello
+> World'
+HELLOWORLD

(You can use QJ in a terminal to insert a new line in a literal +string like that.)

3. Building and Running a Function

The sample @SpringBootApplication above has a function that can be +decorated at runtime by Spring Cloud Function to be an HTTP endpoint, +or a Stream processor, for instance with RabbitMQ, Apache Kafka or +JMS.

The @Beans can be Function, Consumer or Supplier (all from +java.util), and their parametric types can be String or POJO.

Functions can also be of Flux<String> or Flux<Pojo> and Spring +Cloud Function takes care of converting the data to and from the +desired types, as long as it comes in as plain text or (in the case of +the POJO) JSON. There is also support for Message<Pojo> where the +message headers are copied from the incoming event, depending on the +adapter. The web adapter also supports conversion from form-encoded +data to a Map, and if you are using the function with Spring Cloud +Stream then all the conversion and coercion features for message +payloads will be applicable as well.

Functions can be grouped together in a single application, or deployed +one-per-jar. It’s up to the developer to choose. An app with multiple +functions can be deployed multiple times in different "personalities", +exposing different functions over different physical transports.

4. Function Catalog and Flexible Function Signatures

One of the main features of Spring Cloud Function is to adapt and support a range of type signatures for user-defined functions, +while providing a consistent execution model. +That’s why all user defined functions are transformed into a canonical representation by FunctionCatalog, using primitives +defined by the Project Reactor (i.e., Flux<T> and Mono<T>). +Users can supply a bean of type Function<String,String>, for instance, and the FunctionCatalog will wrap it into a +Function<Flux<String>,Flux<String>>.

Using Reactor based primitives not only helps with the canonical representation of user defined functions, but it also +facilitates a more robust and flexible(reactive) execution model.

While users don’t normally have to care about the FunctionCatalog at all, it is useful to know what +kind of functions are supported in user code.

4.1 Java 8 function support

Generally speaking users can expect that if they write a function for +a plain old Java type (or primitive wrapper), then the function +catalog will wrap it to a Flux of the same type. If the user writes +a function using Message (from spring-messaging) it will receive and +transmit headers from any adapter that supports key-value metadata +(e.g. HTTP headers). Here are the details.

User FunctionCatalog Registration 

Function<S,T>

Function<Flux<S>, Flux<T>>

 

Function<Message<S>,Message<T>>

Function<Flux<Message<S>>, Flux<Message<T>>>

 

Function<Flux<S>, Flux<T>>

Function<Flux<S>, Flux<T>> (pass through)

 

Supplier<T>

Supplier<Flux<T>>

 

Supplier<Flux<T>>

Supplier<Flux<T>>

 

Consumer<T>

Function<Flux<T>, Mono<Void>>

 

Consumer<Message<T>>

Function<Flux<Message<T>>, Mono<Void>>

 

Consumer<Flux<T>>

Consumer<Flux<T>>

 

Consumer is a little bit special because it has a void return type, +which implies blocking, at least potentially. Most likely you will not +need to write Consumer<Flux<?>>, but if you do need to do that, +remember to subscribe to the input flux. If you declare a Consumer +of a non publisher type (which is normal), it will be converted to a +function that returns a publisher, so that it can be subscribed to in +a controlled way.

4.2 Kotlin Lambda support

We also provide support for Kotlin lambdas (since v2.0). +Consider the following:

@Bean
+open fun kotlinSupplier(): () -> String {
+    return  { "Hello from Kotlin" }
+}
+
+@Bean
+open fun kotlinFunction(): (String) -> String {
+    return  { it.toUpperCase() }
+}
+
+@Bean
+open fun kotlinConsumer(): (String) -> Unit {
+    return  { println(it) }
+}

The above represents Kotlin lambdas configured as Spring beans. The signature of each maps to a Java equivalent of +Supplier, Function and Consumer, and thus supported/recognized signatures by the framework. +While mechanics of Kotlin-to-Java mapping are outside of the scope of this documentation, it is important to understand that the +same rules for signature transformation outlined in "Java 8 function support" section are applied here as well.

To enable Kotlin support all you need is to add spring-cloud-function-kotlin module to your classpath which contains the appropriate +autoconfiguration and supporting classes.

5. Standalone Web Applications

The spring-cloud-function-web module has autoconfiguration that +activates when it is included in a Spring Boot web application (with +MVC support). There is also a spring-cloud-starter-function-web to +collect all the optional dependencies in case you just want a simple +getting started experience.

With the web configurations activated your app will have an MVC +endpoint (on "/" by default, but configurable with +spring.cloud.function.web.path) that can be used to access the +functions in the application context. The supported content types are +plain text and JSON.

MethodPathRequestResponseStatus

GET

/{supplier}

-

Items from the named supplier

200 OK

POST

/{consumer}

JSON object or text

Mirrors input and pushes request body into consumer

202 Accepted

POST

/{consumer}

JSON array or text with new lines

Mirrors input and pushes body into consumer one by one

202 Accepted

POST

/{function}

JSON object or text

The result of applying the named function

200 OK

POST

/{function}

JSON array or text with new lines

The result of applying the named function

200 OK

GET

/{function}/{item}

-

Convert the item into an object and return the result of applying the function

200 OK

As the table above shows the behaviour of the endpoint depends on the method and also the type of incoming request data. When the incoming data is single valued, and the target function is declared as obviously single valued (i.e. not returning a collection or Flux), then the response will also contain a single value. +For multi-valued responses the client can ask for a server-sent event stream by sending `Accept: text/event-stream".

If there is only a single function (consumer etc.) in the catalog, the name in the path is optional. +Composite functions can be addressed using pipes or commas to separate function names (pipes are legal in URL paths, but a bit awkward to type on the command line).

For cases where there is more then a single function in catalog and you want to map a specific function to the root +path (e.g., "/"), or you want to compose several functions and then map to the root path you can do so by providing +spring.cloud.function.definition property which essentially used by spring-=cloud-function-web module to provide +default mapping for cases where there is some type of a conflict (e.g., more then one function available etc).

For example,

--spring.cloud.function.definition=foo|bar

The above property will compose 'foo' and 'bar' function and map the composed function to the "/" path.

Functions and consumers that are declared with input and output in Message<?> will see the request headers on the input messages, and the output message headers will be converted to HTTP headers.

When POSTing text the response format might be different with Spring Boot 2.0 and older versions, depending on the content negotiation (provide content type and accpt headers for the best results).

6. Standalone Streaming Applications

To send or receive messages from a broker (such as RabbitMQ or Kafka) you can leverage spring-cloud-stream project and it’s integration with Spring Cloud Function. +Please refer to Spring Cloud Function section of the Spring Cloud Stream reference manual for more details and examples.

7. Deploying a Packaged Function

Spring Cloud Function provides a "deployer" library that allows you to launch a jar file (or exploded archive, or set of jar files) with an isolated class loader and expose the functions defined in it. This is quite a powerful tool that would allow you to, for instance, adapt a function to a range of different input-output adapters without changing the target jar file. Serverless platforms often have this kind of feature built in, so you could see it as a building block for a function invoker in such a platform (indeed the Riff Java function invoker uses this library).

The standard entry point of the API is the Spring configuration annotation @EnableFunctionDeployer. If that is used in a Spring Boot application the deployer kicks in and looks for some configuration to tell it where to find the function jar. At a minimum the user has to provide a function.location which is a URL or resource location for the archive containing the functions. It can optionally use a maven: prefix to locate the artifact via a dependency lookup (see FunctionProperties for complete details). A Spring Boot application is bootstrapped from the jar file, using the MANIFEST.MF to locate a start class, so that a standard Spring Boot fat jar works well, for example. If the target jar can be launched successfully then the result is a function registered in the main application’s FunctionCatalog. The registered function can be applied by code in the main application, even though it was created in an isolated class loader (by deault).

8. Functional Bean Definitions

Spring Cloud Function supports a "functional" style of bean declarations for small apps where you need fast startup. The functional style of bean declaration was a feature of Spring Framework 5.0 with significant enhancements in 5.1.

8.1 Comparing Functional with Traditional Bean Definitions

Here’s a vanilla Spring Cloud Function application from with the +familiar @Configuration and @Bean declaration style:

@SpringBootApplication
+public class DemoApplication {
+
+  @Bean
+  public Function<String, String> uppercase() {
+    return value -> value.toUpperCase();
+  }
+
+  public static void main(String[] args) {
+    SpringApplication.run(DemoApplication.class, args);
+  }
+
+}

You can run the above in a serverless platform, like AWS Lambda or Azure Functions, or you can run it in its own HTTP server just by including spring-cloud-function-starter-web on the classpath. Running the main method would expose an endpoint that you can use to ping that uppercase function:

$ curl localhost:8080 -d foo
+FOO

The web adapter in spring-cloud-function-starter-web uses Spring MVC, so you needed a Servlet container. You can also use Webflux where the default server is netty (even though you can still use Servlet containers if you want to) - just include the spring-cloud-starter-function-webflux dependency instead. The functionality is the same, and the user application code can be used in both.

Now for the functional beans: the user application code can be recast into "functional" +form, like this:

@SpringBootConfiguration
+public class DemoApplication implements ApplicationContextInitializer<GenericApplicationContext> {
+
+  public static void main(String[] args) {
+    FunctionalSpringApplication.run(DemoApplication.class, args);
+  }
+
+  public Function<String, String> uppercase() {
+    return value -> value.toUpperCase();
+  }
+
+  @Override
+  public void initialize(GenericApplicationContext context) {
+    context.registerBean("demo", FunctionRegistration.class,
+        () -> new FunctionRegistration<>(uppercase())
+            .type(FunctionType.from(String.class).to(String.class)));
+  }
+
+}

The main differences are:

  • The main class is an ApplicationContextInitializer.
  • The @Bean methods have been converted to calls to context.registerBean()
  • The @SpringBootApplication has been replaced with +@SpringBootConfiguration to signify that we are not enabling Spring +Boot autoconfiguration, and yet still marking the class as an "entry +point".
  • The SpringApplication from Spring Boot has been replaced with a +FunctionalSpringApplication from Spring Cloud Function (it’s a +subclass).

The business logic beans that you register in a Spring Cloud Function app are of type FunctionRegistration. This is a wrapper that contains both the function and information about the input and output types. In the @Bean form of the application that information can be derived reflectively, but in a functional bean registration some of it is lost unless we use a FunctionRegistration.

An alternative to using an ApplicationContextInitializer and FunctionRegistration is to make the application itself implement Function (or Consumer or Supplier). Example (equivalent to the above):

@SpringBootConfiguration
+public class DemoApplication implements Function<String, String> {
+
+  public static void main(String[] args) {
+    FunctionalSpringApplication.run(DemoApplication.class, args);
+  }
+
+  @Override
+  public String uppercase(String value) {
+    return value.toUpperCase();
+  }
+
+}

It would also work if you add a separate, standalone class of type Function and register it with the SpringApplication using an alternative form of the run() method. The main thing is that the generic type information is available at runtime through the class declaration.

The app runs in its own HTTP server if you add spring-cloud-starter-function-webflux (it won’t work with the MVC starter at the moment because the functional form of the embedded Servlet container hasn’t been implemented). The app also runs just fine in AWS Lambda or Azure Functions, and the improvements in startup time are dramatic.

[Note]Note

The "lite" web server has some limitations for the range of Function signatures - in particular it doesn’t (yet) support Message input and output, but POJOs and any kind of Publisher should be fine.

8.2 Testing Functional Applications

Spring Cloud Function also has some utilities for integration testing that will be very familiar to Spring Boot users. For example, here is an integration test for the HTTP server wrapping the app above:

@RunWith(SpringRunner.class)
+@FunctionalSpringBootTest
+@AutoConfigureWebTestClient
+public class FunctionalTests {
+
+	@Autowired
+	private WebTestClient client;
+
+	@Test
+	public void words() throws Exception {
+		client.post().uri("/").body(Mono.just("foo"), String.class).exchange()
+				.expectStatus().isOk().expectBody(String.class).isEqualTo("FOO");
+	}
+
+}

This test is almost identical to the one you would write for the @Bean version of the same app - the only difference is the @FunctionalSpringBootTest annotation, instead of the regular @SpringBootTest. All the other pieces, like the @Autowired WebTestClient, are standard Spring Boot features.

Or you could write a test for a non-HTTP app using just the FunctionCatalog. For example:

@RunWith(SpringRunner.class)
+@FunctionalSpringBootTest
+public class FunctionalTests {
+
+	@Autowired
+	private FunctionCatalog catalog;
+
+	@Test
+	public void words() throws Exception {
+		Function<Flux<String>, Flux<String>> function = catalog.lookup(Function.class,
+				"function");
+		assertThat(function.apply(Flux.just("foo")).blockFirst()).isEqualTo("FOO");
+	}
+
+}

(The FunctionCatalog always returns functions from Flux to Flux, even if the user declares them with a simpler signature.)

8.3 Limitations of Functional Bean Declaration

Most Spring Cloud Function apps have a relatively small scope compared to the whole of Spring Boot, so we are able to adapt it to these functional bean definitions easily. If you step outside that limited scope, you can extend your Spring Cloud Function app by switching back to @Bean style configuration, or by using a hybrid approach. If you want to take advantage of Spring Boot autoconfiguration for integrations with external datastores, for example, you will need to use @EnableAutoConfiguration. Your functions can still be defined using the functional declarations if you want (i.e. the "hybrid" style), but in that case you will need to explicitly switch off the "full functional mode" using spring.functional.enabled=false so that Spring Boot can take back control.

9. Dynamic Compilation

There is a sample app that uses the function compiler to create a +function from a configuration property. The vanilla "function-sample" +also has that feature. And there are some scripts that you can run to +see the compilation happening at run time. To run these examples, +change into the scripts directory:

cd scripts

Also, start a RabbitMQ server locally (e.g. execute rabbitmq-server).

Start the Function Registry Service:

./function-registry.sh

Register a Function:

./registerFunction.sh -n uppercase -f "f->f.map(s->s.toString().toUpperCase())"

Run a REST Microservice using that Function:

./web.sh -f uppercase -p 9000
+curl -H "Content-Type: text/plain" -H "Accept: text/plain" localhost:9000/uppercase -d foo

Register a Supplier:

./registerSupplier.sh -n words -f "()->Flux.just(\"foo\",\"bar\")"

Run a REST Microservice using that Supplier:

./web.sh -s words -p 9001
+curl -H "Accept: application/json" localhost:9001/words

Register a Consumer:

./registerConsumer.sh -n print -t String -f "System.out::println"

Run a REST Microservice using that Consumer:

./web.sh -c print -p 9002
+curl -X POST -H "Content-Type: text/plain" -d foo localhost:9002/print

Run Stream Processing Microservices:

First register a streaming words supplier:

./registerSupplier.sh -n wordstream -f "()->Flux.interval(Duration.ofMillis(1000)).map(i->\"message-\"+i)"

Then start the source (supplier), processor (function), and sink (consumer) apps +(in reverse order):

./stream.sh -p 9103 -i uppercaseWords -c print
+./stream.sh -p 9102 -i words -f uppercase -o uppercaseWords
+./stream.sh -p 9101 -s wordstream -o words

The output will appear in the console of the sink app (one message per second, converted to uppercase):

MESSAGE-0
+MESSAGE-1
+MESSAGE-2
+MESSAGE-3
+MESSAGE-4
+MESSAGE-5
+MESSAGE-6
+MESSAGE-7
+MESSAGE-8
+MESSAGE-9
+...

10. Serverless Platform Adapters

As well as being able to run as a standalone process, a Spring Cloud +Function application can be adapted to run one of the existing +serverless platforms. In the project there are adapters for +AWS +Lambda, +Azure, +and +Apache +OpenWhisk. The Oracle Fn platform +has its own Spring Cloud Function adapter. And +Riff supports Java functions and its +Java Function +Invoker acts natively is an adapter for Spring Cloud Function jars.

10.1 AWS Lambda

The AWS adapter takes a Spring Cloud Function app and converts it to a form that can run in AWS Lambda.

10.1.1 Introduction

The adapter has a couple of generic request handlers that you can use. The most generic is SpringBootStreamHandler, which uses a Jackson ObjectMapper provided by Spring Boot to serialize and deserialize the objects in the function. There is also a SpringBootRequestHandler which you can extend, and provide the input and output types as type parameters (enabling AWS to inspect the class and do the JSON conversions itself).

If your app has more than one @Bean of type Function etc. then you can choose the one to use by configuring function.name (e.g. as FUNCTION_NAME environment variable in AWS). The functions are extracted from the Spring Cloud FunctionCatalog (searching first for Function then Consumer and finally Supplier).

10.1.2 Notes on JAR Layout

You don’t need the Spring Cloud Function Web or Stream adapter at runtime in Lambda, so you might need to exclude those before you create the JAR you send to AWS. A Lambda application has to be shaded, but a Spring Boot standalone application does not, so you can run the same app using 2 separate jars (as per the sample). The sample app creates 2 jar files, one with an aws classifier for deploying in Lambda, and one executable (thin) jar that includes spring-cloud-function-web at runtime. Spring Cloud Function will try and locate a "main class" for you from the JAR file manifest, using the Start-Class attribute (which will be added for you by the Spring Boot tooling if you use the starter parent). If there is no Start-Class in your manifest you can use an environment variable MAIN_CLASS when you deploy the function to AWS.

10.1.3 Upload

Build the sample under spring-cloud-function-samples/function-sample-aws and upload the -aws jar file to Lambda. The handler can be example.Handler or org.springframework.cloud.function.adapter.aws.SpringBootStreamHandler (FQN of the class, not a method reference, although Lambda does accept method references).

./mvnw -U clean package

Using the AWS command line tools it looks like this:

aws lambda create-function --function-name Uppercase --role arn:aws:iam::[USERID]:role/service-role/[ROLE] --zip-file fileb://function-sample-aws/target/function-sample-aws-2.0.0.BUILD-SNAPSHOT-aws.jar --handler org.springframework.cloud.function.adapter.aws.SpringBootStreamHandler --description "Spring Cloud Function Adapter Example" --runtime java8 --region us-east-1 --timeout 30 --memory-size 1024 --publish

The input type for the function in the AWS sample is a Foo with a single property called "value". So you would need this to test it:

{
+  "value": "test"
+}
[Note]Note

The AWS sample app is written in the "functional" style (as an ApplicationContextInitializer). This is much faster on startup in Lambda than the traditional @Bean style, so if you don’t need @Beans (or @EnableAutoConfiguration) it’s a good choice. Warm starts are not affected.

10.1.4 Platfom Specific Features

HTTP and API Gateway

AWS has some platform-specific data types, including batching of messages, which is much more efficient than processing each one individually. To make use of these types you can write a function that depends on those types. Or you can rely on Spring to extract the data from the AWS types and convert it to a Spring Message. To do this you tell AWS that the function is of a specific generic handler type (depending on the AWS service) and provide a bean of type Function<Message<S>,Message<T>>, where S and T are your business data types. If there is more than one bean of type Function you may also need to configure the Spring Boot property function.name to be the name of the target bean (e.g. use FUNCTION_NAME as an environment variable).

The supported AWS services and generic handler types are listed below:

ServiceAWS TypesGeneric Handler 

API Gateway

APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent

org.springframework.cloud.function.adapter.aws.SpringBootApiGatewayRequestHandler

 

Kinesis

KinesisEvent

org.springframework.cloud.function.adapter.aws.SpringBootKinesisEventHandler

 

For example, to deploy behind an API Gateway, use --handler org.springframework.cloud.function.adapter.aws.SpringBootApiGatewayRequestHandler in your AWS command line (in via the UI) and define a @Bean of type Function<Message<Foo>,Message<Bar>> where Foo and Bar are POJO types (the data will be marshalled and unmarshalled by AWS using Jackson).

10.2 Azure Functions

The Azure adapter bootstraps a Spring Cloud Function context and channels function calls from the Azure framework into the user functions, using Spring Boot configuration where necessary. Azure Functions has quite a unique, but invasive programming model, involving annotations in user code that are specific to the platform. The easiest way to use it with Spring Cloud is to extend a base class and write a method in it with the @FunctionName annotation which delegates to a base class method.

This project provides an adapter layer for a Spring Cloud Function application onto Azure. +You can write an app with a single @Bean of type Function and it will be deployable in Azure if you get the JAR file laid out right.

There is an AzureSpringBootRequestHandler which you must extend, and provide the input and output types as annotated method parameters (enabling Azure to inspect the class and create JSON bindings). The base class has two useful methods (handleRequest and handleOutput) to which you can delegate the actual function call, so mostly the function will only ever have one line.

Example:

public class FooHandler extends AzureSpringBootRequestHandler<Foo, Bar> {
+	@FunctionName("uppercase")
+	public Bar execute(
+			@HttpTrigger(name = "req", methods = { HttpMethod.GET,
+					HttpMethod.POST }, authLevel = AuthorizationLevel.ANONYMOUS)
+                    Foo foo,
+			ExecutionContext context) {
+		return handleRequest(foo, context);
+	}
+}

This Azure handler will delegate to a Function<Foo,Bar> bean (or a Function<Publisher<Foo>,Publisher<Bar>>). Some Azure triggers (e.g. @CosmosDBTrigger) result in a input type of List and in that case you can bind to List in the Azure handler, or String (the raw JSON). The List input delegates to a Function with input type Map<String,Object>, or Publisher or List of the same type. The output of the Function can be a List (one-for-one) or a single value (aggregation), and the output binding in the Azure declaration should match.

If your app has more than one @Bean of type Function etc. then you can choose the one to use by configuring function.name. Or if you make the @FunctionName in the Azure handler method match the function name it should work that way (also for function apps with multiple functions). The functions are extracted from the Spring Cloud FunctionCatalog so the default function names are the same as the bean names.

10.2.1 Notes on JAR Layout

You don’t need the Spring Cloud Function Web at runtime in Azure, so you can exclude this before you create the JAR you deploy to Azure, but it won’t be used if you include it so it doesn’t hurt to leave it in. A function application on Azure is an archive generated by the Maven plugin. The function lives in the JAR file generated by this project. The sample creates it as an executable jar, using the thin layout, so that Azure can find the handler classes. If you prefer you can just use a regular flat JAR file. The dependencies should not be included.

10.2.2 Build

./mvnw -U clean package

10.2.3 Running the sample

You can run the sample locally, just like the other Spring Cloud Function samples:

and curl -H "Content-Type: text/plain" localhost:8080/function -d '{"value": "hello foobar"}'.

You will need the az CLI app (see https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-first-java-maven for more detail). To deploy the function on Azure runtime:

$ az login
+$ mvn azure-functions:deploy

On another terminal try this: curl https://<azure-function-url-from-the-log>/api/uppercase -d '{"value": "hello foobar!"}'. Please ensure that you use the right URL for the function above. Alternatively you can test the function in the Azure Dashboard UI (click on the function name, go to the right hand side and click "Test" and to the bottom right, "Run").

The input type for the function in the Azure sample is a Foo with a single property called "value". So you need this to test it with something like below:

{
+  "value": "foobar"
+}
[Note]Note

The Azure sample app is written in the "non-functional" style (using @Bean). The functional style (with just Function or ApplicationContextInitializer) is much faster on startup in Azure than the traditional @Bean style, so if you don’t need @Beans (or @EnableAutoConfiguration) it’s a good choice. Warm starts are not affected.

10.3 Apache Openwhisk

The OpenWhisk adapter is in the form of an executable jar that can be used in a a docker image to be deployed to Openwhisk. The platform works in request-response mode, listening on port 8080 on a specific endpoint, so the adapter is a simple Spring MVC application.

10.3.1 Quick Start

Implement a POF (be sure to use the functions package):

package functions;
+
+import java.util.function.Function;
+
+public class Uppercase implements Function<String, String> {
+
+	public String apply(String input) {
+		return input.toUpperCase();
+	}
+}

Install it into your local Maven repository:

./mvnw clean install

Create a function.properties file that provides its Maven coordinates. For example:

dependencies.function: com.example:pof:0.0.1-SNAPSHOT

Copy the openwhisk runner JAR to the working directory (same directory as the properties file):

cp spring-cloud-function-adapters/spring-cloud-function-adapter-openwhisk/target/spring-cloud-function-adapter-openwhisk-2.0.0.BUILD-SNAPSHOT.jar runner.jar

Generate a m2 repo from the --thin.dryrun of the runner JAR with the above properties file:

java -jar -Dthin.root=m2 runner.jar --thin.name=function --thin.dryrun

Use the following Dockerfile:

FROM openjdk:8-jdk-alpine
+VOLUME /tmp
+COPY m2 /m2
+ADD runner.jar .
+ADD function.properties .
+ENV JAVA_OPTS=""
+ENTRYPOINT [ "java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "runner.jar", "--thin.root=/m2", "--thin.name=function", "--function.name=uppercase"]
+EXPOSE 8080
[Note]Note

you could use a Spring Cloud Function app, instead of just a jar with a POF in it, in which case you would have to change the way the app runs in the container so that it picks up the main class as a source file. For example, you could change the ENTRYPOINT above and add --spring.main.sources=com.example.SampleApplication.

Build the Docker image:

docker build -t [username/appname] .

Push the Docker image:

docker push [username/appname]

Use the OpenWhisk CLI (e.g. after vagrant ssh) to create the action:

wsk action create example --docker [username/appname]

Invoke the action:

wsk action invoke example --result --param payload foo
+{
+    "result": "FOO"
+}
\ No newline at end of file diff --git a/spring-cloud-function/2.0.1.RELEASE/spring-cloud-function.xml b/spring-cloud-function/2.0.1.RELEASE/spring-cloud-function.xml new file mode 100644 index 00000000..5afd674c --- /dev/null +++ b/spring-cloud-function/2.0.1.RELEASE/spring-cloud-function.xml @@ -0,0 +1,681 @@ + + + + + +Spring Cloud Function +2019-01-31 + + + +Mark Fisher, Dave Syer, Oleg Zhurakousky + + + +Introduction +Spring Cloud Function is a project with the following high-level goals: + + +Promote the implementation of business logic via functions. + + +Decouple the development lifecycle of business logic from any specific runtime target so that the same code can run as a web endpoint, a stream processor, or a task. + + +Support a uniform programming model across serverless providers, as well as the ability to run standalone (locally or in a PaaS). + + +Enable Spring Boot features (auto-configuration, dependency injection, metrics) on serverless providers. + + +It abstracts away all of the transport details and +infrastructure, allowing the developer to keep all the familiar tools +and processes, and focus firmly on business logic. +Here’s a complete, executable, testable Spring Boot application +(implementing a simple string manipulation): +@SpringBootApplication +public class Application { + + @Bean + public Function<Flux<String>, Flux<String>> uppercase() { + return flux -> flux.map(value -> value.toUpperCase()); + } + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} +It’s just a Spring Boot application, so it can be built, run and +tested, locally and in a CI build, the same way as any other Spring +Boot application. The Function is from java.util and Flux is a +Reactive Streams Publisher from +Project Reactor. The function can be +accessed over HTTP or messaging. +Spring Cloud Function has 4 main features: + + +Wrappers for @Beans of type Function, Consumer and +Supplier, exposing them to the outside world as either HTTP +endpoints and/or message stream listeners/publishers with RabbitMQ, Kafka etc. + + +Compiling strings which are Java function bodies into bytecode, and +then turning them into @Beans that can be wrapped as above. + + +Deploying a JAR file containing such an application context with an +isolated classloader, so that you can pack them together in a single +JVM. + + +Adapters for AWS Lambda, Azure, Apache OpenWhisk and possibly other "serverless" service providers. + + + +Spring Cloud is released under the non-restrictive Apache 2.0 license. If you would like to contribute to this section of the documentation or if you find an error, please find the source code and issue trackers in the project at github. + + + +Getting Started +Build from the command line (and "install" the samples): +$ ./mvnw clean install +(If you like to YOLO add -DskipTests.) +Run one of the samples, e.g. +$ java -jar spring-cloud-function-samples/function-sample/target/*.jar +This runs the app and exposes its functions over HTTP, so you can +convert a string to uppercase, like this: +$ curl -H "Content-Type: text/plain" localhost:8080/uppercase -d Hello +HELLO +You can convert multiple strings (a Flux<String>) by separating them +with new lines +$ curl -H "Content-Type: text/plain" localhost:8080/uppercase -d 'Hello +> World' +HELLOWORLD +(You can use QJ in a terminal to insert a new line in a literal +string like that.) + + +Building and Running a Function +The sample @SpringBootApplication above has a function that can be +decorated at runtime by Spring Cloud Function to be an HTTP endpoint, +or a Stream processor, for instance with RabbitMQ, Apache Kafka or +JMS. +The @Beans can be Function, Consumer or Supplier (all from +java.util), and their parametric types can be String or POJO. +Functions can also be of Flux<String> or Flux<Pojo> and Spring +Cloud Function takes care of converting the data to and from the +desired types, as long as it comes in as plain text or (in the case of +the POJO) JSON. There is also support for Message<Pojo> where the +message headers are copied from the incoming event, depending on the +adapter. The web adapter also supports conversion from form-encoded +data to a Map, and if you are using the function with Spring Cloud +Stream then all the conversion and coercion features for message +payloads will be applicable as well. +Functions can be grouped together in a single application, or deployed +one-per-jar. It’s up to the developer to choose. An app with multiple +functions can be deployed multiple times in different "personalities", +exposing different functions over different physical transports. + + +Function Catalog and Flexible Function Signatures +One of the main features of Spring Cloud Function is to adapt and support a range of type signatures for user-defined functions, +while providing a consistent execution model. +That’s why all user defined functions are transformed into a canonical representation by FunctionCatalog, using primitives +defined by the Project Reactor (i.e., Flux<T> and Mono<T>). +Users can supply a bean of type Function<String,String>, for instance, and the FunctionCatalog will wrap it into a +Function<Flux<String>,Flux<String>>. +Using Reactor based primitives not only helps with the canonical representation of user defined functions, but it also +facilitates a more robust and flexible(reactive) execution model. +While users don’t normally have to care about the FunctionCatalog at all, it is useful to know what +kind of functions are supported in user code. +
+Java 8 function support +Generally speaking users can expect that if they write a function for +a plain old Java type (or primitive wrapper), then the function +catalog will wrap it to a Flux of the same type. If the user writes +a function using Message (from spring-messaging) it will receive and +transmit headers from any adapter that supports key-value metadata +(e.g. HTTP headers). Here are the details. + + + + + + + +User Function +Catalog Registration + + + + + +Function<S,T> +Function<Flux<S>, Flux<T>> + + + +Function<Message<S>,Message<T>> +Function<Flux<Message<S>>, Flux<Message<T>>> + + + +Function<Flux<S>, Flux<T>> +Function<Flux<S>, Flux<T>> (pass through) + + + +Supplier<T> +Supplier<Flux<T>> + + + +Supplier<Flux<T>> +Supplier<Flux<T>> + + + +Consumer<T> +Function<Flux<T>, Mono<Void>> + + + +Consumer<Message<T>> +Function<Flux<Message<T>>, Mono<Void>> + + + +Consumer<Flux<T>> +Consumer<Flux<T>> + + + + + +Consumer is a little bit special because it has a void return type, +which implies blocking, at least potentially. Most likely you will not +need to write Consumer<Flux<?>>, but if you do need to do that, +remember to subscribe to the input flux. If you declare a Consumer +of a non publisher type (which is normal), it will be converted to a +function that returns a publisher, so that it can be subscribed to in +a controlled way. +
+
+Kotlin Lambda support +We also provide support for Kotlin lambdas (since v2.0). +Consider the following: +@Bean +open fun kotlinSupplier(): () -> String { + return { "Hello from Kotlin" } +} + +@Bean +open fun kotlinFunction(): (String) -> String { + return { it.toUpperCase() } +} + +@Bean +open fun kotlinConsumer(): (String) -> Unit { + return { println(it) } +} +The above represents Kotlin lambdas configured as Spring beans. The signature of each maps to a Java equivalent of +Supplier, Function and Consumer, and thus supported/recognized signatures by the framework. +While mechanics of Kotlin-to-Java mapping are outside of the scope of this documentation, it is important to understand that the +same rules for signature transformation outlined in "Java 8 function support" section are applied here as well. +To enable Kotlin support all you need is to add spring-cloud-function-kotlin module to your classpath which contains the appropriate +autoconfiguration and supporting classes. +
+
+ +Standalone Web Applications +The spring-cloud-function-web module has autoconfiguration that +activates when it is included in a Spring Boot web application (with +MVC support). There is also a spring-cloud-starter-function-web to +collect all the optional dependencies in case you just want a simple +getting started experience. +With the web configurations activated your app will have an MVC +endpoint (on "/" by default, but configurable with +spring.cloud.function.web.path) that can be used to access the +functions in the application context. The supported content types are +plain text and JSON. + + + + + + + + + +Method +Path +Request +Response +Status + + + + +GET +/{supplier} +- +Items from the named supplier +200 OK + + +POST +/{consumer} +JSON object or text +Mirrors input and pushes request body into consumer +202 Accepted + + +POST +/{consumer} +JSON array or text with new lines +Mirrors input and pushes body into consumer one by one +202 Accepted + + +POST +/{function} +JSON object or text +The result of applying the named function +200 OK + + +POST +/{function} +JSON array or text with new lines +The result of applying the named function +200 OK + + +GET +/{function}/{item} +- +Convert the item into an object and return the result of applying the function +200 OK + + + + +As the table above shows the behaviour of the endpoint depends on the method and also the type of incoming request data. When the incoming data is single valued, and the target function is declared as obviously single valued (i.e. not returning a collection or Flux), then the response will also contain a single value. +For multi-valued responses the client can ask for a server-sent event stream by sending `Accept: text/event-stream". +If there is only a single function (consumer etc.) in the catalog, the name in the path is optional. +Composite functions can be addressed using pipes or commas to separate function names (pipes are legal in URL paths, but a bit awkward to type on the command line). +For cases where there is more then a single function in catalog and you want to map a specific function to the root +path (e.g., "/"), or you want to compose several functions and then map to the root path you can do so by providing +spring.cloud.function.definition property which essentially used by spring-=cloud-function-web module to provide +default mapping for cases where there is some type of a conflict (e.g., more then one function available etc). +For example, +--spring.cloud.function.definition=foo|bar +The above property will compose 'foo' and 'bar' function and map the composed function to the "/" path. +Functions and consumers that are declared with input and output in Message<?> will see the request headers on the input messages, and the output message headers will be converted to HTTP headers. +When POSTing text the response format might be different with Spring Boot 2.0 and older versions, depending on the content negotiation (provide content type and accpt headers for the best results). + + +Standalone Streaming Applications +To send or receive messages from a broker (such as RabbitMQ or Kafka) you can leverage spring-cloud-stream project and it’s integration with Spring Cloud Function. +Please refer to Spring Cloud Function section of the Spring Cloud Stream reference manual for more details and examples. + + +Deploying a Packaged Function +Spring Cloud Function provides a "deployer" library that allows you to launch a jar file (or exploded archive, or set of jar files) with an isolated class loader and expose the functions defined in it. This is quite a powerful tool that would allow you to, for instance, adapt a function to a range of different input-output adapters without changing the target jar file. Serverless platforms often have this kind of feature built in, so you could see it as a building block for a function invoker in such a platform (indeed the Riff Java function invoker uses this library). +The standard entry point of the API is the Spring configuration annotation @EnableFunctionDeployer. If that is used in a Spring Boot application the deployer kicks in and looks for some configuration to tell it where to find the function jar. At a minimum the user has to provide a function.location which is a URL or resource location for the archive containing the functions. It can optionally use a maven: prefix to locate the artifact via a dependency lookup (see FunctionProperties for complete details). A Spring Boot application is bootstrapped from the jar file, using the MANIFEST.MF to locate a start class, so that a standard Spring Boot fat jar works well, for example. If the target jar can be launched successfully then the result is a function registered in the main application’s FunctionCatalog. The registered function can be applied by code in the main application, even though it was created in an isolated class loader (by deault). + + +Functional Bean Definitions +Spring Cloud Function supports a "functional" style of bean declarations for small apps where you need fast startup. The functional style of bean declaration was a feature of Spring Framework 5.0 with significant enhancements in 5.1. +
+Comparing Functional with Traditional Bean Definitions +Here’s a vanilla Spring Cloud Function application from with the +familiar @Configuration and @Bean declaration style: +@SpringBootApplication +public class DemoApplication { + + @Bean + public Function<String, String> uppercase() { + return value -> value.toUpperCase(); + } + + public static void main(String[] args) { + SpringApplication.run(DemoApplication.class, args); + } + +} +You can run the above in a serverless platform, like AWS Lambda or Azure Functions, or you can run it in its own HTTP server just by including spring-cloud-function-starter-web on the classpath. Running the main method would expose an endpoint that you can use to ping that uppercase function: +$ curl localhost:8080 -d foo +FOO +The web adapter in spring-cloud-function-starter-web uses Spring MVC, so you needed a Servlet container. You can also use Webflux where the default server is netty (even though you can still use Servlet containers if you want to) - just include the spring-cloud-starter-function-webflux dependency instead. The functionality is the same, and the user application code can be used in both. +Now for the functional beans: the user application code can be recast into "functional" +form, like this: +@SpringBootConfiguration +public class DemoApplication implements ApplicationContextInitializer<GenericApplicationContext> { + + public static void main(String[] args) { + FunctionalSpringApplication.run(DemoApplication.class, args); + } + + public Function<String, String> uppercase() { + return value -> value.toUpperCase(); + } + + @Override + public void initialize(GenericApplicationContext context) { + context.registerBean("demo", FunctionRegistration.class, + () -> new FunctionRegistration<>(uppercase()) + .type(FunctionType.from(String.class).to(String.class))); + } + +} +The main differences are: + + +The main class is an ApplicationContextInitializer. + + +The @Bean methods have been converted to calls to context.registerBean() + + +The @SpringBootApplication has been replaced with +@SpringBootConfiguration to signify that we are not enabling Spring +Boot autoconfiguration, and yet still marking the class as an "entry +point". + + +The SpringApplication from Spring Boot has been replaced with a +FunctionalSpringApplication from Spring Cloud Function (it’s a +subclass). + + +The business logic beans that you register in a Spring Cloud Function app are of type FunctionRegistration. This is a wrapper that contains both the function and information about the input and output types. In the @Bean form of the application that information can be derived reflectively, but in a functional bean registration some of it is lost unless we use a FunctionRegistration. +An alternative to using an ApplicationContextInitializer and FunctionRegistration is to make the application itself implement Function (or Consumer or Supplier). Example (equivalent to the above): +@SpringBootConfiguration +public class DemoApplication implements Function<String, String> { + + public static void main(String[] args) { + FunctionalSpringApplication.run(DemoApplication.class, args); + } + + @Override + public String uppercase(String value) { + return value.toUpperCase(); + } + +} +It would also work if you add a separate, standalone class of type Function and register it with the SpringApplication using an alternative form of the run() method. The main thing is that the generic type information is available at runtime through the class declaration. +The app runs in its own HTTP server if you add spring-cloud-starter-function-webflux (it won’t work with the MVC starter at the moment because the functional form of the embedded Servlet container hasn’t been implemented). The app also runs just fine in AWS Lambda or Azure Functions, and the improvements in startup time are dramatic. + +The "lite" web server has some limitations for the range of Function signatures - in particular it doesn’t (yet) support Message input and output, but POJOs and any kind of Publisher should be fine. + +
+
+Testing Functional Applications +Spring Cloud Function also has some utilities for integration testing that will be very familiar to Spring Boot users. For example, here is an integration test for the HTTP server wrapping the app above: +@RunWith(SpringRunner.class) +@FunctionalSpringBootTest +@AutoConfigureWebTestClient +public class FunctionalTests { + + @Autowired + private WebTestClient client; + + @Test + public void words() throws Exception { + client.post().uri("/").body(Mono.just("foo"), String.class).exchange() + .expectStatus().isOk().expectBody(String.class).isEqualTo("FOO"); + } + +} +This test is almost identical to the one you would write for the @Bean version of the same app - the only difference is the @FunctionalSpringBootTest annotation, instead of the regular @SpringBootTest. All the other pieces, like the @Autowired WebTestClient, are standard Spring Boot features. +Or you could write a test for a non-HTTP app using just the FunctionCatalog. For example: +@RunWith(SpringRunner.class) +@FunctionalSpringBootTest +public class FunctionalTests { + + @Autowired + private FunctionCatalog catalog; + + @Test + public void words() throws Exception { + Function<Flux<String>, Flux<String>> function = catalog.lookup(Function.class, + "function"); + assertThat(function.apply(Flux.just("foo")).blockFirst()).isEqualTo("FOO"); + } + +} +(The FunctionCatalog always returns functions from Flux to Flux, even if the user declares them with a simpler signature.) +
+
+Limitations of Functional Bean Declaration +Most Spring Cloud Function apps have a relatively small scope compared to the whole of Spring Boot, so we are able to adapt it to these functional bean definitions easily. If you step outside that limited scope, you can extend your Spring Cloud Function app by switching back to @Bean style configuration, or by using a hybrid approach. If you want to take advantage of Spring Boot autoconfiguration for integrations with external datastores, for example, you will need to use @EnableAutoConfiguration. Your functions can still be defined using the functional declarations if you want (i.e. the "hybrid" style), but in that case you will need to explicitly switch off the "full functional mode" using spring.functional.enabled=false so that Spring Boot can take back control. +
+
+ +Dynamic Compilation +There is a sample app that uses the function compiler to create a +function from a configuration property. The vanilla "function-sample" +also has that feature. And there are some scripts that you can run to +see the compilation happening at run time. To run these examples, +change into the scripts directory: +cd scripts +Also, start a RabbitMQ server locally (e.g. execute rabbitmq-server). +Start the Function Registry Service: +./function-registry.sh +Register a Function: +./registerFunction.sh -n uppercase -f "f->f.map(s->s.toString().toUpperCase())" +Run a REST Microservice using that Function: +./web.sh -f uppercase -p 9000 +curl -H "Content-Type: text/plain" -H "Accept: text/plain" localhost:9000/uppercase -d foo +Register a Supplier: +./registerSupplier.sh -n words -f "()->Flux.just(\"foo\",\"bar\")" +Run a REST Microservice using that Supplier: +./web.sh -s words -p 9001 +curl -H "Accept: application/json" localhost:9001/words +Register a Consumer: +./registerConsumer.sh -n print -t String -f "System.out::println" +Run a REST Microservice using that Consumer: +./web.sh -c print -p 9002 +curl -X POST -H "Content-Type: text/plain" -d foo localhost:9002/print +Run Stream Processing Microservices: +First register a streaming words supplier: +./registerSupplier.sh -n wordstream -f "()->Flux.interval(Duration.ofMillis(1000)).map(i->\"message-\"+i)" +Then start the source (supplier), processor (function), and sink (consumer) apps +(in reverse order): +./stream.sh -p 9103 -i uppercaseWords -c print +./stream.sh -p 9102 -i words -f uppercase -o uppercaseWords +./stream.sh -p 9101 -s wordstream -o words +The output will appear in the console of the sink app (one message per second, converted to uppercase): +MESSAGE-0 +MESSAGE-1 +MESSAGE-2 +MESSAGE-3 +MESSAGE-4 +MESSAGE-5 +MESSAGE-6 +MESSAGE-7 +MESSAGE-8 +MESSAGE-9 +... + + +Serverless Platform Adapters +As well as being able to run as a standalone process, a Spring Cloud +Function application can be adapted to run one of the existing +serverless platforms. In the project there are adapters for +AWS +Lambda, +Azure, +and +Apache +OpenWhisk. The Oracle Fn platform +has its own Spring Cloud Function adapter. And +Riff supports Java functions and its +Java Function +Invoker acts natively is an adapter for Spring Cloud Function jars. +
+AWS Lambda +The AWS adapter takes a Spring Cloud Function app and converts it to a form that can run in AWS Lambda. +
+Introduction +The adapter has a couple of generic request handlers that you can use. The most generic is SpringBootStreamHandler, which uses a Jackson ObjectMapper provided by Spring Boot to serialize and deserialize the objects in the function. There is also a SpringBootRequestHandler which you can extend, and provide the input and output types as type parameters (enabling AWS to inspect the class and do the JSON conversions itself). +If your app has more than one @Bean of type Function etc. then you can choose the one to use by configuring function.name (e.g. as FUNCTION_NAME environment variable in AWS). The functions are extracted from the Spring Cloud FunctionCatalog (searching first for Function then Consumer and finally Supplier). +
+
+Notes on JAR Layout +You don’t need the Spring Cloud Function Web or Stream adapter at runtime in Lambda, so you might need to exclude those before you create the JAR you send to AWS. A Lambda application has to be shaded, but a Spring Boot standalone application does not, so you can run the same app using 2 separate jars (as per the sample). The sample app creates 2 jar files, one with an aws classifier for deploying in Lambda, and one executable (thin) jar that includes spring-cloud-function-web at runtime. Spring Cloud Function will try and locate a "main class" for you from the JAR file manifest, using the Start-Class attribute (which will be added for you by the Spring Boot tooling if you use the starter parent). If there is no Start-Class in your manifest you can use an environment variable MAIN_CLASS when you deploy the function to AWS. +
+
+Upload +Build the sample under spring-cloud-function-samples/function-sample-aws and upload the -aws jar file to Lambda. The handler can be example.Handler or org.springframework.cloud.function.adapter.aws.SpringBootStreamHandler (FQN of the class, not a method reference, although Lambda does accept method references). +./mvnw -U clean package +Using the AWS command line tools it looks like this: +aws lambda create-function --function-name Uppercase --role arn:aws:iam::[USERID]:role/service-role/[ROLE] --zip-file fileb://function-sample-aws/target/function-sample-aws-2.0.0.BUILD-SNAPSHOT-aws.jar --handler org.springframework.cloud.function.adapter.aws.SpringBootStreamHandler --description "Spring Cloud Function Adapter Example" --runtime java8 --region us-east-1 --timeout 30 --memory-size 1024 --publish +The input type for the function in the AWS sample is a Foo with a single property called "value". So you would need this to test it: +{ + "value": "test" +} + +The AWS sample app is written in the "functional" style (as an ApplicationContextInitializer). This is much faster on startup in Lambda than the traditional @Bean style, so if you don’t need @Beans (or @EnableAutoConfiguration) it’s a good choice. Warm starts are not affected. + +
+
+Platfom Specific Features +
+HTTP and API Gateway +AWS has some platform-specific data types, including batching of messages, which is much more efficient than processing each one individually. To make use of these types you can write a function that depends on those types. Or you can rely on Spring to extract the data from the AWS types and convert it to a Spring Message. To do this you tell AWS that the function is of a specific generic handler type (depending on the AWS service) and provide a bean of type Function<Message<S>,Message<T>>, where S and T are your business data types. If there is more than one bean of type Function you may also need to configure the Spring Boot property function.name to be the name of the target bean (e.g. use FUNCTION_NAME as an environment variable). +The supported AWS services and generic handler types are listed below: + + + + + + + + +Service +AWS Types +Generic Handler + + + + + +API Gateway +APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent +org.springframework.cloud.function.adapter.aws.SpringBootApiGatewayRequestHandler + + + +Kinesis +KinesisEvent +org.springframework.cloud.function.adapter.aws.SpringBootKinesisEventHandler + + + + + +For example, to deploy behind an API Gateway, use --handler org.springframework.cloud.function.adapter.aws.SpringBootApiGatewayRequestHandler in your AWS command line (in via the UI) and define a @Bean of type Function<Message<Foo>,Message<Bar>> where Foo and Bar are POJO types (the data will be marshalled and unmarshalled by AWS using Jackson). +
+
+
+
+Azure Functions +The Azure adapter bootstraps a Spring Cloud Function context and channels function calls from the Azure framework into the user functions, using Spring Boot configuration where necessary. Azure Functions has quite a unique, but invasive programming model, involving annotations in user code that are specific to the platform. The easiest way to use it with Spring Cloud is to extend a base class and write a method in it with the @FunctionName annotation which delegates to a base class method. +This project provides an adapter layer for a Spring Cloud Function application onto Azure. +You can write an app with a single @Bean of type Function and it will be deployable in Azure if you get the JAR file laid out right. +There is an AzureSpringBootRequestHandler which you must extend, and provide the input and output types as annotated method parameters (enabling Azure to inspect the class and create JSON bindings). The base class has two useful methods (handleRequest and handleOutput) to which you can delegate the actual function call, so mostly the function will only ever have one line. +Example: +public class FooHandler extends AzureSpringBootRequestHandler<Foo, Bar> { + @FunctionName("uppercase") + public Bar execute( + @HttpTrigger(name = "req", methods = { HttpMethod.GET, + HttpMethod.POST }, authLevel = AuthorizationLevel.ANONYMOUS) + Foo foo, + ExecutionContext context) { + return handleRequest(foo, context); + } +} +This Azure handler will delegate to a Function<Foo,Bar> bean (or a Function<Publisher<Foo>,Publisher<Bar>>). Some Azure triggers (e.g. @CosmosDBTrigger) result in a input type of List and in that case you can bind to List in the Azure handler, or String (the raw JSON). The List input delegates to a Function with input type Map<String,Object>, or Publisher or List of the same type. The output of the Function can be a List (one-for-one) or a single value (aggregation), and the output binding in the Azure declaration should match. +If your app has more than one @Bean of type Function etc. then you can choose the one to use by configuring function.name. Or if you make the @FunctionName in the Azure handler method match the function name it should work that way (also for function apps with multiple functions). The functions are extracted from the Spring Cloud FunctionCatalog so the default function names are the same as the bean names. +
+Notes on JAR Layout +You don’t need the Spring Cloud Function Web at runtime in Azure, so you can exclude this before you create the JAR you deploy to Azure, but it won’t be used if you include it so it doesn’t hurt to leave it in. A function application on Azure is an archive generated by the Maven plugin. The function lives in the JAR file generated by this project. The sample creates it as an executable jar, using the thin layout, so that Azure can find the handler classes. If you prefer you can just use a regular flat JAR file. The dependencies should not be included. +
+
+Build +./mvnw -U clean package +
+
+Running the sample +You can run the sample locally, just like the other Spring Cloud Function samples: + + +and curl -H "Content-Type: text/plain" localhost:8080/function -d '{"value": "hello foobar"}'. +You will need the az CLI app (see https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-first-java-maven for more detail). To deploy the function on Azure runtime: +$ az login +$ mvn azure-functions:deploy +On another terminal try this: curl https://<azure-function-url-from-the-log>/api/uppercase -d '{"value": "hello foobar!"}'. Please ensure that you use the right URL for the function above. Alternatively you can test the function in the Azure Dashboard UI (click on the function name, go to the right hand side and click "Test" and to the bottom right, "Run"). +The input type for the function in the Azure sample is a Foo with a single property called "value". So you need this to test it with something like below: +{ + "value": "foobar" +} + +The Azure sample app is written in the "non-functional" style (using @Bean). The functional style (with just Function or ApplicationContextInitializer) is much faster on startup in Azure than the traditional @Bean style, so if you don’t need @Beans (or @EnableAutoConfiguration) it’s a good choice. Warm starts are not affected. + +
+
+
+Apache Openwhisk +The OpenWhisk adapter is in the form of an executable jar that can be used in a a docker image to be deployed to Openwhisk. The platform works in request-response mode, listening on port 8080 on a specific endpoint, so the adapter is a simple Spring MVC application. +
+Quick Start +Implement a POF (be sure to use the functions package): +package functions; + +import java.util.function.Function; + +public class Uppercase implements Function<String, String> { + + public String apply(String input) { + return input.toUpperCase(); + } +} +Install it into your local Maven repository: +./mvnw clean install +Create a function.properties file that provides its Maven coordinates. For example: +dependencies.function: com.example:pof:0.0.1-SNAPSHOT +Copy the openwhisk runner JAR to the working directory (same directory as the properties file): +cp spring-cloud-function-adapters/spring-cloud-function-adapter-openwhisk/target/spring-cloud-function-adapter-openwhisk-2.0.0.BUILD-SNAPSHOT.jar runner.jar +Generate a m2 repo from the --thin.dryrun of the runner JAR with the above properties file: +java -jar -Dthin.root=m2 runner.jar --thin.name=function --thin.dryrun +Use the following Dockerfile: +FROM openjdk:8-jdk-alpine +VOLUME /tmp +COPY m2 /m2 +ADD runner.jar . +ADD function.properties . +ENV JAVA_OPTS="" +ENTRYPOINT [ "java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "runner.jar", "--thin.root=/m2", "--thin.name=function", "--function.name=uppercase"] +EXPOSE 8080 +
+ +you could use a Spring Cloud Function app, instead of just a jar with a POF in it, in which case you would have to change the way the app runs in the container so that it picks up the main class as a source file. For example, you could change the ENTRYPOINT above and add --spring.main.sources=com.example.SampleApplication. + +
+Build the Docker image: +docker build -t [username/appname] . +Push the Docker image: +docker push [username/appname] +Use the OpenWhisk CLI (e.g. after vagrant ssh) to create the action: +wsk action create example --docker [username/appname] +Invoke the action: +wsk action invoke example --result --param payload foo +{ + "result": "FOO" +} +
+
+
+
\ No newline at end of file