## Module overview
This module contains functions to support gRPC protocol based communication. gRPC is a framework developed by Google
to support the RPC (Remote Procedure Call) protocol. The gRPC protocol is layered over HTTP/2. This protocol only supports client-initiated communication.

### Protocol buffers
This is a mechanism to serialize the structured data introduced by Google and used by the gRPC framework. Specify the
 structured data that needs to be serialized in the  `.proto` file. A sample `.proto` file is shown below.
```ballerina
syntax = "proto3";
import "google/protobuf/wrappers.proto";
service ServerStreaming {
     rpc receiveMessage(google.protobuf.StringValue) returns (stream google.protobuf.StringValue);
}
```

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

### Endpoints
Endpoints specify how the client and server communicate. This module supports service endpoints and client endpoints. The service endpoint specifies how the client communicates with the server. The client endpoint is automatically generated by passing the `.proto` file to a proto compiler. 

The Ballerina tooling distribution provides a proto compiler to generate the Ballerina client endpoint. The client endpoint generated using the Ballerina proto compiler has two client endpoints. Use the endpoint to suit the use case. 

### RPC types
This module supports the following RPC client-to-service communication methods: unary, server streaming, client streaming, and bidirectional streaming. Listeners are used to support the asynchronous and streaming communication.
#### Unary 
The server sends a response to each client request. Unary supports blocking and non-blocking communication. 
#### Server streaming
The server sends multiple responses in an asynchronous manner for each client request.
#### Client streaming
The client sends multiple requests while the server sends a single response to these requests.
#### Bidirectional Streaming
The client and server send multiple requests and responses.

## Samples

### Ballerina code generator tool

Using below command to generate stub and sample code.
```
#ballerina grpc --input [proto_file] --output [output_directory] --mode [service/client]
```
#### Options ####

`--input`  - Set proto file path.

`--output` - Set output Ballerina source files directory.

`--mode`   - Set mode (client or server) to generate code samples. If not specified, only the stub file is generated.

### Unary communication
The sample given below contains a service that sends a response to each request using an auto-generated Ballerina stub.

```ballerina
// Server listener configuration.
listener grpc:Listener ep = new(9090);

// The gRPC service is attached to the server.
service SamplegRPCService on ep {
   // A resource that accepts a string message.
   resource function receiveMessage(grpc:Caller caller, string name) {
       // Print the received message.
       io:println("Received message from : " + name);
       // Send the response to the client.
       error? err = caller->send("Hi " + name + "! Greetings from gRPC service!");

       // After sending the response, call ‘complete()’ to indicate that the response was completely sent.
       error? result = caller->complete();
   }
}
```

The sample given below calls the above service in a blocking manner using an auto-generated Ballerina stub.

```ballerina
// Use ‘BlockingClient’ to execute the call in the blocking mode.
SamplegRPCServiceBlockingClient SamplegRPCServiceBlockingEp = new("http://localhost:9090");

// Create gRPC headers.
grpc:Headers headers = new;
headers.setEntry("id", "newrequest1");

// Call the method in the service using a client stub.
var responseFromServer = SamplegRPCServiceBlockingEp->receiveMessage("Ballerina", headers = headers);
if (responseFromServer is (string, grpc:Headers)) {
    // If a response is received, print the payload.
    (string, grpc:Headers) (result, resHeaders) = responseFromServer;
    io:println("Response received : " + result);
} else {
    // If an error is returned, print the error message.
    io:println("Error while connecting grpc end-point : " + responseFromServer.reason() + " - "
                                                          + <string>responseFromServer.detail().message);
}
```
### Server Streaming
The sample given below shows a server streaming service.

```ballerina
// Server listener configuration.
listener grpc:Listener ep = new(9090);

// The gRPC service is attached to the server.
service ServerStreaming on ep {
   // Set the Streaming Annotation to ‘true’. It specifies that the resource is capable of sending multiple responses per request.
   @grpc:ResourceConfig { streaming: true }
   resource function receiveMessage(grpc:Caller caller, string name) {
       string[] greets = ["Hi", "Welcome"];
       io:println("HelloWorld");
       // Send multiple responses to the client.
       foreach var greet in greets {
           error? err = caller->send(greet + " " + name + "! Greetings from Ballerina service");
           // If an error is returned, print the error message. print response message otherwise.
           if (err is error) {
               io:println("Error from Connector: " + err.reason() + " - "
                                                   + <string>err.detail().message);
           } else {
               io:println("send reply: " + msg);
           }
       }
       // Once the messages are sent to the server, call ‘complete()’ to indicate that the request was completely sent.
       error? result = caller->complete();
   }
}
```
The sample given below calls the above service using the auto-generated Ballerina client stub and listens to the multiple responses from the server.

```ballerina
// Keep track of the message that were completely received.
boolean isCompleted = false;
public function main(string... args) {
   // Client endpoint configurations.
    ServerStreamingClient serverStreamingEp = new("http://localhost:9090");

    // Execute the service streaming call by registering a message listener.
    error? result = serverStreamingEp->receiveMessage("test", ServerStreamingMessageListener);
    if (result is error) {
        // If the service returns an error, print the error.
        io:println("Error occured while sending event " + result.reason() + " - "
                                                        + <string>result.detail().message);
    } else {
        io:println("Connected successfully to service");
    }
   // Waits for the service to send the message.
   while (!isCompleted) { }
}

// Define a listener service to receive the messages from the server.
service ServerStreamingMessageListener = service {

   // This resource method is invoked when the service receives a message.
   resource function onMessage(string message) {
       io:println("Response received from server: " + message);
   }
   
   // This resource method is invoked if an error is returned.
   resource function onError(error err) {
        io:println("Error from Connector: " + err.reason() + " - "
                                            + <string>err.detail().message);
   }

   // Invoke this resource when the server sends all the responses to the request.
    resource function onComplete() {
       isCompleted = true;
       io:println("Server Complete Sending Responses.");
   }
}
```
### Bidirectional Streaming

The sample given below includes a service that handles bidirectional streaming.

```ballerina
// Server listener configuration.
listener grpc:Listener ep = new(9090);

// Set the ‘clientStreaming’ and ‘serverStreaming’ to true. It specifies that the service supports bidirectional streaming.
@grpc:ServiceConfig {
    name: "chat",
    clientStreaming: true,
    serverStreaming: true
}
service Chat bind ep {

   // This resource method is invoked when there is a connection request from a client.
   resource function onOpen(grpc:Caller caller) {
       
   }

   // This resource method is invoked when the client sends a request.
   resource function onMessage(grpc:Caller caller, string message) {
   
   }
   
   // This resource method is invoked when the client returns an error while sending requests.
   resource function onError(grpc:Caller caller, error err) {
   
   }
   
   // This resource method is invoked when the client has finished sending requests.
   resource function onComplete(grpc:Caller caller) {
   
   }
}
```

The sample given below calls the above service.

```ballerina
// Client endpoint configuration.
ChatClient chatEp = new("http://localhost:9090");
    
grpc:StreamingClient ep;

// Call the relevant service.
var res = chatEp->chat(ChatMessageListener);
if (res is error) {
    io:println("Error from Connector: " + res.reason() + " - "
                                        + <string>res.detail().message);
    return;
} else {
    io:println("Initialized connection sucessfully.");
    ep = res;
}

// Send multiple messages to the service.
error? connErr = ep->send(“Hello”);

// After sending the message, call ‘complete()’ to indicate that the request was completely sent. 
error? result = ep->complete();

```

