Minor cleanup and improvements in new GCF adapter

Resolves #468
This commit is contained in:
Oleg Zhurakousky
2020-04-02 09:51:25 +02:00
parent fcdb6ae8c3
commit d3345576bd
6 changed files with 115 additions and 100 deletions

View File

@@ -0,0 +1,89 @@
/*
* 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.nio.charset.StandardCharsets;
import java.util.Map.Entry;
import java.util.function.Function;
import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import org.springframework.cloud.function.context.AbstractSpringFunctionAdapterInitializer;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.util.Assert;
import org.springframework.util.MimeTypeUtils;
/**
* 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
* @author Oleg Zhurakousky
*
* @since 3.0.4
*/
public class FunctionInvoker
extends AbstractSpringFunctionAdapterInitializer<HttpRequest> implements HttpFunction {
public FunctionInvoker() {
super();
}
public FunctionInvoker(Class<?> configurationClass) {
super(configurationClass);
System.setProperty("spring.http.converters.preferred-json-mapper", "gson");
Thread.currentThread() //TODO investigate if it is necessary
.setContextClassLoader(FunctionInvoker.class.getClassLoader());
initialize(null);
}
/**
* The implementation of a GCF {@link HttpFunction} that will be used as the entry point from GCF.
*/
@Override
public void service(HttpRequest httpRequest, HttpResponse httpResponse) throws Exception {
try {
String functionName = System.getenv().containsKey("spring.cloud.function.definition")
? System.getenv("spring.cloud.function.definition") : "";
Function<Message<BufferedReader>, Message<byte[]>> function =
this.catalog.lookup(functionName, MimeTypeUtils.APPLICATION_JSON.toString());
Assert.notNull(function, "'function' with name '" + functionName + "' must not be null");
Message<BufferedReader> message = getInputType() == Void.class
? null : MessageBuilder.withPayload(httpRequest.getReader())
.copyHeaders(httpRequest.getHeaders())
.build();
Message<byte[]> result = function.apply(message);
if (result != null) {
httpResponse.getWriter().write(new String(result.getPayload(), StandardCharsets.UTF_8));
for (Entry<String, Object> header : result.getHeaders().entrySet()) {
httpResponse.appendHeader(header.getKey(), header.getValue().toString());
}
}
}
finally {
httpResponse.getWriter().close();
}
}
}

View File

@@ -1,73 +0,0 @@
/*
* 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

@@ -34,6 +34,8 @@ import org.springframework.cloud.function.context.config.ContextFunctionCatalogA
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@@ -44,7 +46,7 @@ import static org.mockito.Mockito.when;
* @author Dmitry Solomakha
* @author Mike Eltsufin
*/
public class GcfSpringBootHttpRequestHandlerTests {
public class FunctionInvokerTests {
private static final Gson gson = new Gson();
@@ -71,21 +73,23 @@ public class GcfSpringBootHttpRequestHandlerTests {
}
private <I, O> void testFunction(Class<?> configurationClass, I input, O expectedOutput) throws Exception {
GcfSpringBootHttpRequestHandler handler = new GcfSpringBootHttpRequestHandler(configurationClass);
try (FunctionInvoker handler = new FunctionInvoker(configurationClass);) {
HttpRequest request = Mockito.mock(HttpRequest.class);
HttpRequest request = Mockito.mock(HttpRequest.class);
if (input != null) {
when(request.getReader()).thenReturn(new BufferedReader(new StringReader(gson.toJson(input))));
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);
if (expectedOutput != null) {
assertThat(writer.toString()).isEqualTo(gson.toJson(expectedOutput));
}
}
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
@@ -110,8 +114,11 @@ public class GcfSpringBootHttpRequestHandlerTests {
@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);
public Function<IncomingRequest, Message<OutgoingResponse>> function() {
return (in) -> {
return MessageBuilder.withPayload(new OutgoingResponse("Thank you for sending the message: " + in.message))
.setHeader("foo", "bar").build();
};
}
}