Details
Accessing request metadata
By default the generated service interfaces don’t provide access to the request metadata, only to the request body (via the RPC method input parameter). If your methods require access to the request Metadata
, you can configure Akka gRPC to generate server “power APIs” that extend the base service interfaces to provide an additional request metadata parameter to each service method. See the detailed chapters on sbt, Gradle and Maven for how to set this build option. Note that this option doesn’t effect the generated client stubs.
Notice: you need to change GreeterServiceHandlerFactory
to GreeterServiceHandlerFactoryPowerApiHandlerFactory
.
Here’s an example implementation of these server power APIs:
- Scala
- Java
-
source
package example.myapp.helloworld; import akka.NotUsed; import akka.grpc.javadsl.Metadata; import akka.stream.Materializer; import akka.stream.javadsl.Sink; import akka.stream.javadsl.Source; import com.google.api.HttpBody; import com.google.protobuf.ByteString; import example.myapp.helloworld.grpc.GreeterServicePowerApi; import example.myapp.helloworld.grpc.HelloReply; import example.myapp.helloworld.grpc.HelloRequest; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.stream.Collectors; public class GreeterServicePowerApiImpl implements GreeterServicePowerApi { private final Materializer mat; public GreeterServicePowerApiImpl(Materializer mat) { this.mat = mat; } @Override public CompletionStage<HelloReply> sayHello(HelloRequest in, Metadata metadata) { String greetee = authTaggedName(in, metadata); System.out.println("sayHello to " + greetee); HelloReply reply = HelloReply.newBuilder().setMessage("Hello, " + greetee).build(); return CompletableFuture.completedFuture(reply); } @Override public CompletionStage<HttpBody> sayHelloHttp(HelloRequest in, Metadata metadata) { System.out.println("sayHelloHttp to " + in.getName()); HttpBody reply = HttpBody.newBuilder().setData( com.google.protobuf.ByteString.copyFrom("test".getBytes()) ).build(); return CompletableFuture.completedFuture(reply); } @Override public CompletionStage<HelloReply> itKeepsTalking(Source<HelloRequest, NotUsed> in, Metadata metadata) { System.out.println("sayHello to in stream..."); return in.runWith(Sink.seq(), mat) .thenApply(elements -> { String elementsStr = elements.stream().map(elem -> authTaggedName(elem, metadata)) .collect(Collectors.toList()).toString(); return HelloReply.newBuilder().setMessage("Hello, " + elementsStr).build(); }); } @Override public Source<HelloReply, NotUsed> itKeepsReplying(HelloRequest in, Metadata metadata) { String greetee = authTaggedName(in, metadata); System.out.println("sayHello to " + greetee + " with stream of chars"); List<Character> characters = ("Hello, " + greetee) .chars().mapToObj(c -> (char) c).collect(Collectors.toList()); return Source.from(characters) .map(character -> { return HelloReply.newBuilder().setMessage(String.valueOf(character)).build(); }); } @Override public Source<HelloReply, NotUsed> streamHellos(Source<HelloRequest, NotUsed> in, Metadata metadata) { System.out.println("sayHello to stream..."); return in.map(request -> HelloReply.newBuilder().setMessage("Hello, " + authTaggedName(request, metadata)).build()); } // Bare-bones just for GRPC metadata demonstration purposes private boolean isAuthenticated(Metadata metadata) { return metadata.getText("authorization").isPresent(); } private String authTaggedName(HelloRequest in, Metadata metadata) { boolean authenticated = isAuthenticated(metadata); return String.format("%s (%sauthenticated)", in.getName(), isAuthenticated(metadata) ? "" : "not "); } }
Status codes
To signal an error, you can fail the CompletionStage
or Source
you are returning with a GrpcServiceException
containing the status code you want to return.
For an overview of gRPC status codes and their meaning see statuscodes.md.
For unary responses:
- Scala
- Java
-
source
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import io.grpc.Status; import akka.grpc.GrpcServiceException; // ... @Override public CompletionStage<HelloReply> sayHello(HelloRequest in) { if (in.getName().isEmpty()) { CompletableFuture<HelloReply> future = new CompletableFuture<>(); future.completeExceptionally(new GrpcServiceException(Status.INVALID_ARGUMENT.withDescription("No name found"))); return future; } else { return CompletableFuture.completedFuture(HelloReply.newBuilder().setMessage("Hi, " + in.getName()).build()); } }
For streaming responses:
- Scala
- Java
-
source
import akka.NotUsed; import akka.stream.javadsl.Source; import io.grpc.Status; import akka.grpc.GrpcServiceException; // ... @Override public Source<HelloReply, NotUsed> itKeepsReplying(HelloRequest in) { if (in.getName().isEmpty()) { return Source.failed(new GrpcServiceException(Status.INVALID_ARGUMENT.withDescription("No name found"))); } else { return myResponseSource; } }
Rich error model
Beyond status codes you can also use the Rich error model.
This example uses an error model taken from common protobuf but every class that is based on com.google.protobuf.Message
can be used. Build and return the error as an AkkaGrpcException
:
- Scala
- Java
-
source
@Override public CompletionStage<HelloReply> sayHello(HelloRequest in) { ArrayList<Message> ar = new ArrayList<>(); ar.add(LocalizedMessage.newBuilder().setLocale("EN").setMessage("The password!").build()); GrpcServiceException exception = GrpcServiceException.create( Code.INVALID_ARGUMENT, "What is wrong?", ar ); CompletableFuture<HelloReply> future = new CompletableFuture<>(); future.completeExceptionally(exception); return future; }
Please look here how to handle this on the client.