ballerina/grpc : 0.8.0-alpha8

Package Overview

This package provides support for the gRPC messaging protocol. gRPC is an inter-process communication technology that allows you to connect, invoke and operate distributed heterogeneous applications as easily as making a local function call. The gRPC protocol is layered over HTTP/2 and It uses Protocol Buffers for marshaling/unmarshaling messages. This makes gRPC, highly efficient on wire and a simple service definition framework.

When you develop a gRPC application the first thing you do is define a service definition using Protocol Buffers.

Protocol buffers

This is a mechanism to serialize the structured data introduced by Google and used by the gRPC framework. Defining the service using Protocol Buffers includes defining remote methods in the service and defining message types that are sent across the network. A sample service definition is shown below.

1syntax = "proto3";
2
3service Helloworld {
4 rpc hello(HelloRequest) returns (HelloResponse);
5}
6
7message HelloRequest {
8 string name = 1;
9}
10
11message HelloResponse {
12 string message = 1;
13}

gRPC allows client applications to directly call the server-side methods using the auto-generated stubs. Protocol Buffer compiler is used to generate the stubs for the specified language. In Ballerina, the stubs are generated using the built-in proto compiler.

For the guide on how to generate Ballerina code for Protocol Buffers definition, see how to guide. For examples on the usage of the operation, see the Proto to Ballerina Example.

gRPC Communication Patterns

The common communication pattern between client and server is simple request-response style communication. However, with gRPC, you can leverage different inter-process communication patterns other than the simple request-response pattern. This package supports four fundamental communication patterns used in gRPC-based applications: simple RPC(unary RPC), server-side streaming, client-side streaming, and bidirectional streaming.

Simple RPC (Unary RPC)

In this pattern, the client invokes a remote function of a server and sends a single request to the server. The server sends a single response in return to the client along with status details. Users can invoke in both blocking and non-blocking manner.

1rpc hello (google.protobuf.StringValue)
2 returns (google.protobuf.StringValue);
Creating the server

The code snippet given below contains a service that sends a response to each request.

1// The gRPC service is attached to the listener.
2service HelloWorld on new grpc:Listener(9090) {
3 // A resource that accepts a string message.
4 remote function hello(string name) returns string|error {
5 // Send the response to the client.
6 return "Hi " + name + "! Greetings from gRPC service!");
7 }
8}
Creating the client

The code snippet given below calls the above service in a synchronized manner using an auto-generated Ballerina stub.

1// Use ‘BlockingClient’ to execute the call in the blocking mode.
2HelloWorldClient blockingClient = new("http://localhost:9090");
3
4// Create gRPC headers.
5map<string|string[]> headers = {id: "newrequest1"};
6
7// Call the method in the service using a client stub.
8ContextString|grpc:Error responseFromServer = blockingClient->hello({content: "Ballerina", headers: headers);

For examples on the usage of the operation, see Unary Ballerina Example and Unary Non-Ballerina Example

Server streaming RPC

In server-side streaming RPC, the sends back a sequence of responses after getting the client's request message. After sending all the server responses, the server marks the end of the stream by sending the server status details. Users can invoke in a non-blocking manner.

1rpc lotsOfReplies (google.protobuf.StringValue)
2 returns (stream google.protobuf.StringValue);
Creating the server

The code snippet given below contains a service that sends a sequence of responses to each request.

1// The gRPC service is attached to the listener.
2service HelloWorld on new grpc:Listener(9090) {
3 remote function lotsOfReplies(string name) returns stream<string, grpc:Error?> {
4 string[] greets = ["Hi " + name, "Welcome " + name];
5 // Send multiple responses to the client.
6 return greets.toStream();
7 }
8}
Creating the client

The code snippet given below calls the above service using the auto-generated Ballerina client stub and listens to the multiple responses from the server.

1 // Client endpoint configurations.
2 HelloWorldClient helloworldClient = new("http://localhost:9090");
3
4 // Execute the service streaming call by registering a message listener.
5 stream<string, grpc:Error?>|grpc:Error result = helloworldClient->lotsOfReplies("Ballerina");

For examples on the usage of the operation, see the Server Streaming Example.

Client streaming RPC

In client streaming RPC, the client sends multiple messages to the server instead of a single request. The server sends back a single response to the client.

1rpc lotsOfGreetings (stream google.protobuf.StringValue)
2 returns (google.protobuf.StringValue);
Creating the server

The code snippet given below contains a service that receives a sequence of requests from the client and a single response in return.

1// The gRPC service is attached to the listener.
2service HelloWorld on new grpc:Listener(9090) {
3
4 //This `resource` is triggered when a new client connection is initialized.
5 remote function lotsOfGreetings(stream<string, grpc:Error?> clientStream) returns string|error {
6 //Iterate through the client stream
7 error? e = clientStream.forEach(function(string name) {
8 // Handle the message sent from the stream here
9 });
10 //A nil value is returned once the client stream is completed
11 if (e is ()) {
12 return "Ack";
13 } else if (e is error) {
14 // Handle the error sent by the client here
15 }
16 }
17}
Creating the client

The code snippet given below calls the above service using the auto-generated Ballerina client stub and sends multiple request messages from the server.

1 // Client endpoint configurations.
2 HelloWorldClient helloworldClient = new("http://localhost:9090");
3
4 // Execute the service streaming call by registering a message listener.
5 LotsOfGreetingsStreamingClient|grpc:Error streamingClient = helloworldClient->lotsOfGreetings();
6
7 // Send multiple messages to the server.
8 string[] greets = ["Hi", "Hey", "GM"];
9 foreach string greet in greets {
10 grpc:Error? connErr = streamingClient->sendstring(greet + " " + "Ballerina");
11 }
12
13 // Once all the messages are sent, the server notifies the caller with a `complete` message.
14 grpc:Error? result = streamingClient->complete();
15
16 string|grpc:Error response = streamingClient->receiveString();
17...

For examples on the usage of the operation, see the Client Streaming Example.

Bidirectional Streaming RPC

In bidirectional streaming RPC, the client is sending a request to the server as a stream of messages. The server also responds with a stream of messages.

1rpc chat (stream ChatMessage)
2 returns (stream google.protobuf.StringValue);
Creating the server

The code snippet given below includes a service that handles bidirectional streaming.

1// The gRPC service is attached to the listener.
2service Chat on new grpc:Listener(9090) {
3
4 //This `resource` is triggered when a new caller connection is initialized.
5 remote function chat(ChatStringCaller caller, stream<ChatMessage, grpc:Error?> clientStream) {
6 //Iterate through the client stream
7 error? e = clientStream.forEach(function(ChatMessage chatMsg) {
8 // Handle the streamed messages sent from the client here
9 grpc:Error? err = caller->send(string `${chatMsg.name}: ${chatMsg.message}`);
10 });
11 //A nil value is returned once the client has competed streaming
12 if (e is ()) {
13 // Handle once the client has completed streaming
14 } else if (e is error) {
15 // Handle the error sent by the client here
16 }
17 }
18}
Creating the client

The code snippet given below calls the above service using the auto-generated Ballerina client stub and sends multiple request messages to the server and receives multiple responses from the server.

1 // Client endpoint configurations.
2 ChatClient chatClient = new("http://localhost:9090");
3
4 // Execute the service streaming call by registering a message listener.
5 ChatStreamingClient|grpc:Error streamingClient = = chatClient->chat();
6
7 // Send multiple messages to the server.
8 string[] greets = ["Hi", "Hey", "GM"];
9 foreach string greet in greets {
10 ChatMessage mes = {name: "Ballerina", message: greet};
11 grpc:Error? connErr = streamingClient->sendChatMessage(mes);
12 }
13
14 // Once all the messages are sent, the server notifies the caller with a `complete` message.
15 grpc:Error? result = streamingClient->complete();
16 ...
17
18 // Receives the server stream response iteratively.
19 string|grpc:Error result = streamingClient->receiveString();
20 while !(result is ()) {
21 if !(result is grpc:Error) {
22 io:println(result);
23 }
24 result = streamingClient->receiveString();
25 }

For examples on the usage of the operation, see the Bidirectional Streaming Example.

Advanced Use cases

Using the TLS protocol

The Ballerina gRPC package allows the use TLS in communication. This setting expects a secure socket to be set in the connection configuration as shown below.

Configuring TLS in server side
1// Server endpoint configuration with the SSL configurations.
2listener grpc:Listener ep = new (9090, {
3 host: "localhost",
4 secureSocket: {
5 keyStore: {
6 path: "bre/security/ballerinaKeystore.p12",
7 password: "ballerina"
8 }
9 }
10});
11
12service HelloWorld on ep {
13
14}
Configuring TLS in client side
1 // Client endpoint configuration with SSL configurations.
2 HelloWorldClient helloWorldClient = new ("https://localhost:9090", {
3 secureSocket: {
4 trustStore: {
5 path: "/bre/security/ballerinaTruststore.p12",
6 password: "ballerina"
7 }
8 }
9 });

For examples on the usage of the operation, see the Secured Unary Example.

Listeners

[1]

Listener

Represents server listener where one or more services can be registered.

Clients

[6]

Caller

Provides the gRPC remote functions for interacting with caller.

Client

The gRPC client endpoint provides the capability for initiating contact with a remote gRPC service.

ClientOAuth2Handler

Defines the OAuth2 handler for client authentication.

ListenerLdapUserStoreBasicAuthProvider

Defines the LDAP store Basic Auth handler for listener authentication.

ListenerOAuth2Handler

Defines the OAuth2 handler for listener authentication.

StreamingClient

Provides the gRPC streaming client actions for interacting with the gRPC server.

Functions

[5]

getDeadline

Return the deadline value as time:Time.

getHeader

Returns the header value with the specified header name.

getHeaders

Gets all the transport headers with the specified header name.

isCancelled

Check whether the deadline already exceeded or not.

setDeadline

Enable the deadline by adding the deadline header to the given headers.

Classes

[5]

ClientBasicAuthHandler

Defines the Basic Auth handler for client authentication.

ClientBearerTokenAuthHandler

Defines the Bearer token auth handler for client authentication.

ClientSelfSignedJwtAuthHandler

Defines the self signed JWT handler for client authentication.

ConnectionManager
ListenerJwtAuthHandler

Defines the JWT auth handler for listener authentication.

Object Types

[2]

AbstractClientEndpoint

Represents the abstract gRPC client endpoint.

Service

The gRPC service type

Records

[19]

BearerTokenConfig

Represents token for Bearer token authentication.

CertKey

Represents combination of certificate, private key and private key password if encrypted.

ClientConfiguration

Represents client endpoint configuration.

ClientSecureSocket

Provides the configurations for facilitating secure communication with a remote gRPC endpoint.

CredentialsConfig

Represents credentials for Basic Auth authentication.

JwtIssuerConfig

Represents JWT issuer configurations for JWT authentication.

JwtValidatorConfig

Represents JWT validator configurations for JWT authentication.

LdapUserStoreConfig

Represents LDAP user store configurations for Basic Auth authentication.

ListenerConfiguration

Represents the gRPC server endpoint configuration.

ListenerSecureSocket

Configures the SSL/TLS options to be used for HTTP service.

Local

Presents a read-only view of the local address.

OAuth2ClientCredentialsGrantConfig

Represents OAuth2 client credentials grant configurations for OAuth2 authentication.

OAuth2IntrospectionConfig

Represents OAuth2 introspection server configurations for OAuth2 authentication.

OAuth2PasswordGrantConfig

Represents OAuth2 password grant configurations for OAuth2 authentication.

OAuth2RefreshTokenGrantConfig

Represents OAuth2 refresh token grant configurations for OAuth2 authentication.

PoolConfiguration

Configurations for managing the gRPC client connection pool.

Remote

Presents a read-only view of the remote address.

RetryConfiguration

Represents grpc client retry functionality configurations.

ServiceDescriptorData

Service descriptor data generated at the compile time.

Constants

[26]

ABORTED

The gRPC error status code: 10 Aborted.

ALREADY_EXISTS

The gRPC error status code: 6 Already Exists.

AUTH_HEADER

Represents the Authorization header name.

AUTH_SCHEME_BASIC

The prefix used to denote the Basic authentication scheme.

AUTH_SCHEME_BEARER

The prefix used to denote the Bearer authentication scheme.

CANCELED

The gRPC error status code: 1 Canceled.

COMPRESSION_ALWAYS

Always set accept-encoding/content-encoding in outbound request/response.

COMPRESSION_AUTO

When service behaves as a HTTP gateway inbound request/response accept-encoding option is set as the outbound request/response accept-encoding/content-encoding option.

COMPRESSION_NEVER

Never set accept-encoding/content-encoding header in outbound request/response.

DATA_LOSS

The gRPC error status code: 15 Data Loss.

DEADLINE_EXCEEDED

The gRPC error status code: 4 Deadline Exceeded.

DEALINE_HEADER

Represents the deadline header name.

FAILED_PRECONDITION

The gRPC error status code: 9 Failed Precondition.

INTERNAL

The gRPC error status code: 13 Internal.

INVALID_ARGUMENT

The gRPC error status code: 3 Invalid Argument.

NOT_FOUND

The gRPC error status code: 5 Not Found.

OK

The gRPC error status code: 0 OK.

OUT_OF_RANGE

The gRPC error status code: 11 Out of Range.

PERMISSION_DENIED

The gRPC error status code: 7 Permission Denied.

PERMISSION_DENIED_ERROR_MSG

The permission denied error message.

RESOURCE_EXHAUSTED

The gRPC error status code: 8 Resource Exhausted.

UNAUTHENTICATED

The gRPC error status code: 16 Unauthenticated.

UNAUTHENTICATED_ERROR_MSG

The permission denied error message.

UNAVAILABLE

The gRPC error status code: 14 Unavailable.

UNIMPLEMENTED

The gRPC error status code: 12 Unimplemented.

UNKNOWN

The gRPC error status code: 2 Unknown.

Enums

[3]

CertValidationType

Represents certification validation type options.

Protocol

Represents protocol options.

VerifyClient

Represents client verify options.

Annotations

[1]

ServiceDescriptor

Service descriptor annotation.

Types

[4]

ClientAuthConfig

Defines the authentication configurations for the HTTP client.

Compression

Options to compress using gzip or deflate.

ErrorType

Represents gRPC related error types.

OAuth2GrantConfig

Represents OAuth2 grant configurations for OAuth2 authentication.

Errors

[1]

Error

Represents gRPC related errors.