Initial commit of Google Function Adapter

implement HttpFunction
add headers processing
Some refactoring [WIP]
Add invoker integration test
Make test classes nested within test.
Add sample and refdoc

Resolves #468
This commit is contained in:
dsolomakha
2020-02-26 12:30:00 -05:00
committed by Oleg Zhurakousky
parent 366d05050f
commit fcdb6ae8c3
10 changed files with 576 additions and 0 deletions

View File

@@ -0,0 +1,132 @@
:branch: master
=== Google Cloud Functions (Alpha)
The Google Cloud Functions adapter enables Spring Cloud Function apps to run on the https://cloud.google.com/functions[Google Cloud Functions] serverless platform.
You can either run the function locally using the open source https://github.com/GoogleCloudPlatform/functions-framework-java[Google Functions Framework for Java] or on GCP.
==== Getting Started
Lets start with a simple Spring Cloud Function example:
[source, java]
----
@SpringBootApplication
public class CloudFunctionMain {
public static void main(String[] args) {
SpringApplication.run(CloudFunctionMain.class, args);
}
@Bean
public Function<String, String> uppercase() {
return value -> value.toUpperCase();
}
}
----
===== Test locally
Start by adding the Maven plugin provided as part of the Google Functions Framework for Java.
[source, xml]
----
<plugin>
<groupId>com.google.cloud.functions</groupId>
<artifactId>function-maven-plugin</artifactId>
<version>0.9.1</version>
<configuration>
<functionTarget>org.springframework.cloud.function.adapter.gcloud.GcfSpringBootHttpRequestHandler</functionTarget>
<port>8080</port>
</configuration>
</plugin>
----
Specify your configuration main class in `resources/META-INF/MANIFEST.MF`.
[source]
----
Main-Class: com.example.CloudFunctionMain
----
Then run the function:
----
mvn function:run
----
Invoke the HTTP function:
----
curl http://localhost:8080/ -d "hello"
----
===== Deploy to GCP
As of March 2020, Google Cloud Functions for Java is in Alpha.
You can get on the https://docs.google.com/forms/d/e/1FAIpQLScC98jGi7CfG0n3UYlj7Xad8XScvZC8-BBOg7Pk3uSZx_2cdQ/viewform[whitelist] to try it out.
First, add the Shade Plugin configuration to generate a fat jar when you run the `mvn package` command.
[source, xml]
----
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<outputDirectory>deploy</outputDirectory>
<shadedClassifierName>gcp</shadedClassifierName>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/spring.handlers</resource>
</transformer>
<transformer implementation="org.springframework.boot.maven.PropertiesMergingResourceTransformer">
<resource>META-INF/spring.factories</resource>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/spring.schemas</resource>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.example.CloudFunctionMain</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
----
Package the application.
----
mvn package
----
You should see the fat jar in `deploy` directory.
Make sure that you have the https://cloud.google.com/sdk/install[Cloud SDK CLI] installed.
From the project base directory run the following command to deploy.
----
gcloud alpha functions deploy function-sample-gcp \
--entry-point org.springframework.cloud.function.adapter.gcloud.GcfSpringBootHttpRequestHandler \
--runtime java11 \
--trigger-http \
--source deploy \
--memory 512MB
----
Invoke the HTTP function:
----
curl https://REGION-PROJECT_ID.cloudfunctions.net/function-sample-gcp -d "hello"
----

View File

@@ -19,6 +19,7 @@
<module>spring-cloud-function-adapter-aws</module>
<module>spring-cloud-function-adapter-openwhisk</module>
<module>spring-cloud-function-adapter-azure</module>
<module>spring-cloud-function-adapter-gcp</module>
</modules>
</project>

View File

@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-function-adapter-gcp</artifactId>
<name>Spring Cloud Function Adapter GCP</name>
<description>Spring Cloud Function Adapter for Google Cloud Functions</description>
<parent>
<artifactId>spring-cloud-function-adapter-parent</artifactId>
<groupId>org.springframework.cloud</groupId>
<version>3.0.4.BUILD-SNAPSHOT</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<google.cloud.functions.version>1.0.0-alpha-2-rc3</google.cloud.functions.version>
<gson.version>2.8.5</gson.version>
</properties>
<dependencies>
<dependency>
<groupId>com.google.cloud.functions</groupId>
<artifactId>functions-framework-api</artifactId>
<version>${google.cloud.functions.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-function-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-function-web</artifactId>
</dependency>
<!-- Test-only dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.cloud.functions.invoker</groupId>
<artifactId>java-function-invoker</artifactId>
<version>${google.cloud.functions.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,73 @@
/*
* Copyright 2020-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.function.adapter.gcloud;
import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import com.google.gson.Gson;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono;
import org.springframework.cloud.function.context.AbstractSpringFunctionAdapterInitializer;
/**
* Implementation of {@link HttpFunction} for Google Cloud Function (GCF).
* This is the Spring Cloud Function adapter for GCF HTTP function.
*
* @author Dmitry Solomakha
* @author Mike Eltsufin
*/
public class GcfSpringBootHttpRequestHandler
extends AbstractSpringFunctionAdapterInitializer<HttpRequest> implements HttpFunction {
private final Gson gson = new Gson();
public GcfSpringBootHttpRequestHandler() {
super();
}
public GcfSpringBootHttpRequestHandler(Class<?> configurationClass) {
super(configurationClass);
}
/**
* The implementation of a GCF {@link HttpFunction} that will be used as the entrypoint from GCF.
*/
@Override
public void service(HttpRequest httpRequest, HttpResponse httpResponse) throws Exception {
Thread.currentThread()
.setContextClassLoader(GcfSpringBootHttpRequestHandler.class.getClassLoader());
initialize(httpRequest);
Publisher<?> input;
if (getInputType() == Void.class) {
input = Mono.empty();
}
else {
input = Mono.just(gson.fromJson(httpRequest.getReader(), getInputType()));
}
Publisher<?> output = this.apply(input);
Object result = this.result(input, output);
httpResponse.getWriter().write(gson.toJson(result));
httpResponse.getWriter().close();
}
}

View File

@@ -0,0 +1,142 @@
/*
* Copyright 2020-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.function.adapter.gcloud;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import com.google.gson.Gson;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.cloud.function.context.config.ContextFunctionCatalogAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
/**
* Unit tests for the HTTP functions adapter for Google Cloud Functions.
*
* @author Dmitry Solomakha
* @author Mike Eltsufin
*/
public class GcfSpringBootHttpRequestHandlerTests {
private static final Gson gson = new Gson();
@Test
public void testHelloWorldSupplier() throws Exception {
testFunction(HelloWorldSupplier.class, null, "Hello World!");
}
@Test
public void testJsonInputFunction() throws Exception {
testFunction(JsonInputFunction.class, new IncomingRequest("hello"),
"Thank you for sending the message: hello");
}
@Test
public void testJsonInputOutputFunction() throws Exception {
testFunction(JsonInputOutputFunction.class, new IncomingRequest("hello"),
new OutgoingResponse("Thank you for sending the message: hello"));
}
@Test
public void testJsonInputConsumer() throws Exception {
testFunction(JsonInputConsumer.class, new IncomingRequest("hello"), null);
}
private <I, O> void testFunction(Class<?> configurationClass, I input, O expectedOutput) throws Exception {
GcfSpringBootHttpRequestHandler handler = new GcfSpringBootHttpRequestHandler(configurationClass);
HttpRequest request = Mockito.mock(HttpRequest.class);
if (input != null) {
when(request.getReader()).thenReturn(new BufferedReader(new StringReader(gson.toJson(input))));
}
HttpResponse response = Mockito.mock(HttpResponse.class);
StringWriter writer = new StringWriter();
when(response.getWriter()).thenReturn(new BufferedWriter(writer));
handler.service(request, response);
assertThat(writer.toString()).isEqualTo(gson.toJson(expectedOutput));
}
@Configuration
@Import({ ContextFunctionCatalogAutoConfiguration.class })
protected static class HelloWorldSupplier {
@Bean
public Supplier<String> supplier() {
return () -> "Hello World!";
}
}
@Configuration
@Import({ ContextFunctionCatalogAutoConfiguration.class })
protected static class JsonInputFunction {
@Bean
public Function<IncomingRequest, String> function() {
return (in) -> "Thank you for sending the message: " + in.message;
}
}
@Configuration
@Import({ ContextFunctionCatalogAutoConfiguration.class })
protected static class JsonInputOutputFunction {
@Bean
public Function<IncomingRequest, OutgoingResponse> function() {
return (in) -> new OutgoingResponse("Thank you for sending the message: " + in.message);
}
}
@Configuration
@Import({ ContextFunctionCatalogAutoConfiguration.class })
protected static class JsonInputConsumer {
@Bean
public Consumer<IncomingRequest> function() {
return (in) -> System.out.println("Thank you for sending the message: " + in.message);
}
}
private static class IncomingRequest {
String message;
IncomingRequest(String message) {
this.message = message;
}
}
private static class OutgoingResponse {
String message;
OutgoingResponse(String message) {
this.message = message;
}
}
}

View File

@@ -0,0 +1 @@
deploy/

View File

@@ -0,0 +1,131 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>function-sample-gcp</artifactId>
<parent>
<artifactId>spring-cloud-function-samples</artifactId>
<groupId>org.springframework.cloud</groupId>
<version>3.0.4.BUILD-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-function-adapter-gcp</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>com.google.cloud.functions</groupId>
<artifactId>function-maven-plugin</artifactId>
<version>0.9.1</version>
<configuration>
<functionTarget>org.springframework.cloud.function.adapter.gcloud.GcfSpringBootHttpRequestHandler</functionTarget>
<port>8080</port>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<outputDirectory>deploy</outputDirectory>
<shadedClassifierName>gcp</shadedClassifierName>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/spring.handlers</resource>
</transformer>
<transformer implementation="org.springframework.boot.maven.PropertiesMergingResourceTransformer">
<resource>META-INF/spring.factories</resource>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/spring.schemas</resource>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.example.CloudFunctionMain</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/libs-snapshot-local</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone-local</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/release</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/libs-snapshot-local</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone-local</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release-local</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>

View File

@@ -0,0 +1,36 @@
/*
* Copyright 2020-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example;
import java.util.function.Function;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class CloudFunctionMain {
public static void main(String[] args) {
SpringApplication.run(CloudFunctionMain.class, args);
}
@Bean
public Function<String, String> function() {
return value -> value.toUpperCase();
}
}

View File

@@ -0,0 +1 @@
Main-Class: com.example.CloudFunctionMain

View File

@@ -24,6 +24,7 @@
<module>function-sample-aws-custom</module>
<module>function-sample-azure</module>
<module>function-sample-spring-integration</module>
<module>function-sample-gcp</module>
</modules>
<build>