• Stars
    star
    128
  • Rank 281,044 (Top 6 %)
  • Language Ballerina
  • License
    Apache License 2.0
  • Created about 4 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Ballerina gRPC Module

Ballerina gRPC Library

Build codecov Trivy GraalVM Check GitHub Last Commit Github issues

This library provides APIs for connecting and interacting with gRPC endpoints.

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 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.

syntax = "proto3";

service Helloworld {
    rpc hello(HelloRequest) returns (HelloResponse);
}

message HelloRequest {
    string name = 1;
}

message HelloResponse {
    string message = 1;
}

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 'Protocol Buffers to Ballerina' tool.

For information on how to generate Ballerina code for Protocol Buffers definition, see Write a gRPC service with Ballerina.

gRPC communication patterns

The common communication pattern between a 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 library supports four fundamental communication patterns used in gRPC-based applications: simple RPC(unary RPC), server streaming RPC, client streaming RPC, and bidirectional streaming RPC.

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.

service HelloWorld {
    rpc hello (google.protobuf.StringValue)
          returns (google.protobuf.StringValue);
}
Implement the gRPC server

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

// The gRPC service is attached to the listener.
service HelloWorld on new grpc:Listener(9090)  {
    // The function accepts a string message.
    remote function hello(string name) returns string|error {
        // Send the response to the client.
        return "Hi " + name + "! Greetings from gRPC service!");
    }
}
Implement the gRPC client

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

// Use ‘HelloWorldClient’ to execute the call in the synchronized mode.
HelloWorldClient helloClient = check new("http://localhost:9090");

// Call the service remote function using a client stub.
string responseFromServer = check helloClient->hello("Ballerina");

Server streaming RPC

In server-side streaming RPC, the server 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. You can invoke this in a non-blocking manner.

service HelloWorld {
    rpc lotsOfReplies (google.protobuf.StringValue)
          returns (stream google.protobuf.StringValue);
}
Implement the gRPC server

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

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

The code snippet given below calls the above service using the auto-generated Ballerina client stub and reads multiple server responses using a stream. Here, the message stream is ended with a () value.

   // Client endpoint configurations.
    HelloWorldClient helloworldClient = check new("http://localhost:9090");

    // Execute the service streaming call by registering a message listener.
    stream<string, grpc:Error?> result = 
                                check helloworldClient->lotsOfReplies("Ballerina");

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.

service HelloWorld {
    rpc lotsOfGreetings (stream google.protobuf.StringValue)
          returns (google.protobuf.StringValue);
}
Implement the gRPC server

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

// The gRPC service is attached to the listener.
service HelloWorld on new grpc:Listener(9090) {

    // This function is triggered when a new client connection is initialized.
    remote function lotsOfGreetings(stream<string, grpc:Error?> clientStream) 
                                                        returns string|error {
        // Iterate through the client stream
        check clientStream.forEach(function(string name) {
            // Handle the message sent from the stream here
        });
        // A nil value is returned once the client stream is ended
        // Return server response to the client.
        return "Ack";
    }
}
Implement the gRPC server

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

    // Client endpoint configurations.
    HelloWorldClient helloworldClient = check new("http://localhost:9090");

    // Execute the service streaming call by registering a message listener.
    LotsOfGreetingsStreamingClient streamingClient = 
                                        check helloworldClient->lotsOfGreetings();

    // Send multiple messages to the server.
    string[] greets = ["Hi", "Hey", "GM"];
    foreach string greet in greets {
        grpc:Error? connErr = streamingClient->sendstring(greet + " " + "Ballerina");
    }

    // Once all the messages are sent, the client notifies the server 
    // by closing the stream.
    grpc:Error? result = streamingClient->complete();
    // Receive the message from the server.
    string|grpc:Error response = streamingClient->receiveString();
...

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.

service Chat {
    rpc chat (stream ChatMessage)
          returns (stream google.protobuf.StringValue);
}
Implement the gRPC server

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

// The gRPC service is attached to the listener.
service Chat on new grpc:Listener(9090) {

    //This `resource` is triggered when a new caller connection is initialized.
    remote function chat(ChatStringCaller caller, 
                                    stream<ChatMessage, grpc:Error?> clientStream) {
        //Iterate through the client stream
        check clientStream.forEach(function(ChatMessage chatMsg) {
            // Handle the streamed messages sent from the client here
            grpc:Error? err = caller->sendString(
                                    string `${chatMsg.name}: ${chatMsg.message}`);
        });
        // A nil value is returned once the client stream is ended
        // Handle once the client has completed streaming
        caller->complete();
    }
}
Implement the gRPC server

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.

    // Client endpoint configurations.
    ChatClient chatClient = check new("http://localhost:9090");

    // Execute the service streaming call by registering a message listener.
    ChatStreamingClient streamingClient = check chatClient->chat();

    // Send multiple messages to the server.
    string[] greets = ["Hi", "Hey", "GM"];
    foreach string greet in greets {
        ChatMessage mes = {name: "Ballerina", message: greet};
        grpc:Error? connErr = streamingClient->sendChatMessage(mes);
    }

    // Once all the messages are sent, the server notifies the caller 
    // with a `complete` message.
    grpc:Error? result = streamingClient->complete();
    ...

    // Receive the server stream response iteratively.
    string? result = check streamingClient->receiveString();
    while !(result is ()) {
        io:println(result);
        result = streamingClient->receiveString();
    }

Advanced use cases

Use the TLS protocol

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

Configure TLS in server side
// Server endpoint configuration with the SSL configurations.
listener grpc:Listener ep = new (9090, {
    host: "localhost",
    secureSocket: {
        key: {
            certFile: "../resource/path/to/public.crt",
            keyFile: "../resource/path/to/private.key"
        }
    }
});

service HelloWorld on ep {
    
}
Configure TLS in client side
    // Client endpoint configuration with SSL configurations.
    HelloWorldClient helloWorldClient = check new ("https://localhost:9090", {
        secureSocket: {
            cert: "../resource/path/to/public.crt"
        }
    });

Use headers

The Ballerina gRPC library allows to send/receive headers with the request and response using the context record type. The context record type consists of two fields called headers and content. E.g: For the string message, a type generated context record type will be as follows.

public type ContextString record {|
    string content;
    map<string|string[]> headers;
|};
Use headers at the client side
    // Set the custom headers to the request.
    ContextString requestMessage =
    {content: "WSO2", headers: {client_header_key: "0987654321"}};
    // Execute the remote call.
    ContextString result = check ep->helloContext(requestMessage);
    // Read Response content.
    string content = result.content;
    // Read Response header value.
    string headerValue = check grpc:getHeader(result.headers, 
                                                    "server_header_key");
Use headers at the server side
service "HelloWorld" on new grpc:Listener(9090) {
    remote function hello(ContextString request) returns ContextString|error {
        // Read the request content.
        string message = "Hello " + request.content;

        // Read custom headers in request message.
        string reqHeader = check grpc:getHeader(request.headers, 
                                                        "client_header_key");

        // Send response with custom headers.
        return {content: message, 
                        headers: {server_header_key: "Response Header value"}};
    }
}

Use deadlines

Deadlines allow gRPC clients to specify how long they are willing to wait for an RPC to complete before the RPC is terminated with the DEADLINE_EXCEEDED error. In Ballerina, a deadline value is set directly to the headers and it is sent via the request headers.

Set a deadline in the request headers
    time:Utc current = time:utcNow();
    time:Utc deadline = time:utcAddSeconds(current, 300);
    map<string|string[]> headers = grpc:setDeadline(deadline);
Check the deadlines
    boolean cancel = check grpc:isCancelled(request.headers);
    if (cancel) {
        return error DeadlineExceededError("Deadline exceeded");
    }

Issues and projects

Issues and Projects tabs are disabled for this repository as this is part of the Ballerina Standard Library. To report bugs, request new features, start new discussions, view project boards, etc. please visit Ballerina Standard Library parent repository.

This repository only contains the source code for the module.

Build from the source

Set Up the prerequisites

  • Download and install Java SE Development Kit (JDK) version 17 (from one of the following locations).

    • Oracle

    • OpenJDK

      Note: Set the JAVA_HOME environment variable to the path name of the directory into which you installed JDK.

Build the source

Execute the commands below to build from source.

  1. To build the library:

     ./gradlew clean build
    
  2. To run the integration tests:

     ./gradlew clean test
    
  3. To build the module without the tests:

     ./gradlew clean build -x test
    
  4. To debug the Ballerina implementation against the native implementation:

    ./gradlew clean build -Pdebug=<port>
    ./gradlew clean test -Pdebug=<port>
    
  5. To debug the Ballerina implementation against the Ballerina language:

    ./gradlew clean build -PbalJavaDebug=<port>
    ./gradlew clean test -PbalJavaDebug=<port>
    
  6. Publish the generated artifacts to the local Ballerina central repository:

    ./gradlew clean build -PpublishToLocalCentral=true
    
  7. Publish the generated artifacts to the Ballerina central repository:

    ./gradlew clean build -PpublishToCentral=true
    

Contribute to Ballerina

As an open source project, Ballerina welcomes contributions from the community.

For more information, go to the contribution guidelines.

Code of conduct

All contributors are encouraged to read the Ballerina Code of Conduct.

Useful links

More Repositories

1

ballerina-lang

The Ballerina Programming Language
Ballerina
3,286
star
2

lsp4intellij

This language client library provides language server protocol support for IntelliJ IDEA and other Jetbrains IDEs.
Java
413
star
3

ballerina-spec

Ballerina Language and Platform Specifications
HTML
171
star
4

ballerina-dev-website

Dev version of the ballerina.io website
HTML
163
star
5

module-ballerina-graphql

The Ballerina GraphQL module is part of the Ballerina Standard Library. It is a spec-compliant, production-ready GraphQL implementation for writing GraphQL APIs in Ballerina.
Ballerina
144
star
6

nballerina

Ballerina compiler that generates native executables.
Ballerina
142
star
7

ballerina-library

The Ballerina Library
Ballerina
137
star
8

module-ballerina-jwt

Ballerina JWT module.
Ballerina
130
star
9

openapi-tools

Ballerina OpenApi-Tool
Java
129
star
10

ballerina-release

Ballerina release scripts
Python
126
star
11

openapi-connectors

Generate Ballerina connector with OpenAPI definition
Ballerina
126
star
12

module-ballerina-http

Ballerina HTTP Module
Java
124
star
13

module-ballerinax-nats

Ballerina NATS Module.
Ballerina
124
star
14

ballerina-platform.github.io

ballerina-platform.github.io - Github pages based ballerina.io website
HTML
124
star
15

ballerina-action

Dockerfile
124
star
16

module-ballerina-io

Ballerina io Module
Ballerina
123
star
17

module-ballerina-tcp

Ballerina socket module
Java
122
star
18

module-ballerina-oauth2

Ballerina OAuth2 Module
Ballerina
122
star
19

module-ballerina-websocket

Ballerina WebSocket Module
Java
121
star
20

module-ballerina-websub

Ballerina Websub module.
Ballerina
120
star
21

module-ballerina-mime

Ballerina MIME Module
Java
119
star
22

plugin-intellij

Ballerina extension for IntelliJ IDEA.
Java
119
star
23

module-ballerinax-mysql

Ballerina mysql Module
Ballerina
119
star
24

module-ballerina-auth

Ballerina Auth Module
Java
119
star
25

module-ballerina-sql

Ballerina SQL Module
Java
119
star
26

module-ballerina-email

Ballerina module to send and receive emails
Java
119
star
27

module-ballerinax-kafka

Ballerina Kafka Module.
Ballerina
119
star
28

module-ballerina-udp

Ballerina UDP module enables transport layer communication over UDP protocol.
Java
118
star
29

module-ballerinax-java.jdbc

Ballerina JDBC Module
Ballerina
118
star
30

module-ballerina-cache

Ballerina cache Module
Ballerina
118
star
31

module-ballerina-log

Ballerina log Module
Ballerina
118
star
32

module-ballerina-c2c

Ballerina Code2Cloud implementation
Java
118
star
33

module-ballerinax-slack

Ballerina slack module
Ballerina
118
star
34

module-ballerinax-azure-cosmosdb

Ballerina
118
star
35

plugin-vscode-compiler-toolkit

Compiler tools for Ballerina developers
TypeScript
118
star
36

ballerina-dev-tools

Ballerina Developer Tooling
Java
118
star
37

module-ballerinax-stan

Ballerina NATS Streaming Module.
Java
117
star
38

module-ballerina-crypto

Ballerina crypto Module
Ballerina
117
star
39

module-ballerina-websubhub

This modules includes a bunch of APIs to facilitate writing different WebSub Hub implementations
Ballerina
116
star
40

module-ballerinax-googleapis.calendar

Connector repository for Google Calendar API.
Ballerina
116
star
41

module-ballerina-xmldata

Ballerina xml utils Module
Ballerina
116
star
42

module-ballerinax-postgresql

Ballerina PostgreSQL DB module
Ballerina
116
star
43

module-ballerinax-java.jms

Ballerina
116
star
44

module-ballerina-file

Ballerina File Module
Ballerina
116
star
45

module-ballerinax-azure-service-bus

Ballerina
116
star
46

module-ballerinax-aws.dynamodb

This is to keep the Amazon DynamoDB connector for Ballerina.
Ballerina
116
star
47

module-ballerinax-aws.s3

Ballerina
116
star
48

module-ballerina-task

Ballerina task Module
Java
116
star
49

module-ballerina-time

Ballerina time Module
Ballerina
116
star
50

module-ballerinax-azure.functions

The implementation of Azure Functions compiler extension for Ballerina.
Java
116
star
51

module-ballerinax-datamapper

A compiler extension to extract abstract representation of Ballerina connector actions and their associated types
Java
116
star
52

module-ballerina-uuid

Ballerina UUID Module
Ballerina
116
star
53

module-ballerinax-netsuite

The Ballerina connector to perform operations on Netsuite integrate cloud system.
Ballerina
116
star
54

module-ballerinax-twitter

This repo is to keep Ballerina Twitter connector implementation for Ballerina
Ballerina
116
star
55

ballerina-update-tool

Ballerina Update Tool implementation to manage Ballerina versions
Java
116
star
56

module-ballerinax-ai.agent

Ballerina ReAct type Agent module using Large language models (LLMs)
Ballerina
115
star
57

module-ballerina-os

Ballerina system Module
Java
115
star
58

module-ballerinax-jaeger

Ballerina Jaeger Observability Extension Module
Java
115
star
59

module-ballerinax-aws.sqs

Ballerina
115
star
60

module-ballerinax-mssql

Ballerina MSSQL DB module
Ballerina
115
star
61

module-ballerinax-aws.lambda

Java
115
star
62

module-ballerina-serdes

This is the Ballerina SerDes package, which is a part of the Ballerina Language Standard Library
Java
115
star
63

module-ballerinax-oracledb

Oracle Database Connector for Ballerina
Ballerina
115
star
64

module-ballerina-xslt

Ballerina xslt module
Java
115
star
65

module-ballerina-url

Ballerina encoding module.
Ballerina
115
star
66

module-ballerinax-rabbitmq

Ballerina RabbitMQ Module.
Ballerina
115
star
67

module-ballerinax-prometheus

Ballerina Prometheus Observability Extension Module
Java
115
star
68

module-ballerinai-transaction

Ballerina internal module of transaction implementation
Ballerina
115
star
69

module-ballerinax-mysql.driver

Ballerina Azure MySQL Module
Ballerina
115
star
70

module-ballerinax-azure-storage-service

Ballerina
115
star
71

graphql-tools

Maintain the source code for GraphQL related tools.
Java
115
star
72

module-ballerina-jballerina.java.arrays

Ballerina Java Array Module
Ballerina
114
star
73

module-ballerina-constraint

Ballerina Constraint Module
Ballerina
114
star
74

module-ballerinax-choreo

Ballerina Choreo Observability Extension Module
Java
114
star
75

ballerina-performance-cloud

Ballerina Performance Tests in Cloud
Shell
114
star
76

module-ballerinax-azure.eventhub

Azure Eventhub connector
Ballerina
114
star
77

module-ballerina-regex

Ballerina Regex Module
Ballerina
114
star
78

plugin-gradle

Ballerina Gradle plugin
Groovy
114
star
79

module-ballerinax-mssql.driver

Ballerina MSSQL DB Driver
Ballerina
114
star
80

module-ballerina-random

Ballerina Random Library
Ballerina
114
star
81

module-ballerinax-health.fhir.templates

FHIR Ballerina templates
Ballerina
114
star
82

module-ballerinax-persist.sql

SQL database support of Ballerina Persist
Ballerina
114
star
83

module-ballerinax-microsoft.onedrive

The Ballerina connector to perform operations on the files, which is stored on OneDrive
Ballerina
114
star
84

ballerina-custom-jre

Generates platform-specific custom Java runtime images to be bundled with Ballerina platform distributions, which contains only the required modules for Ballerina runtime.
114
star
85

asyncapi-tools

This repository is the code base for the ballerina async-api tool
Java
114
star
86

persist-tools

Ballerina persist tools
Ballerina
113
star
87

module-ballerinax-cdata.connect

Manage Ballerina CData connector modules centrally.
Java
113
star
88

module-ballerina-persist

Ballerina Persist module
Java
113
star
89

module-ballerinax-peoplehr

Ballerina connector for People HR
Ballerina
113
star
90

module-ballerinax-aws.ses

The Ballerina connector to perform operations on Amazon Simple Email Service(Amazon SES).
Ballerina
113
star
91

module-ballerinax-googleapis.people

Repository for Google People API Connector
Ballerina
113
star
92

module-ballerinax-microsoft.teams

The Ballerina Microsoft Teams Connector for teamwork and intelligent communications.
Ballerina
113
star
93

module-ballerinax-googleapis.drive

Repository for Google Drive module.
Ballerina
113
star
94

module-ballerinax-microsoft.excel

The Ballerina connector to perform operations on Excel workbooks stored in Microsoft OneDrive.
Ballerina
113
star
95

asyncapi-triggers

This repo will contain the trigger source code generated through ballerina async api tool
Ballerina
113
star
96

module-ballerinax-aws.simpledb

This is to keep the Amazon SimpleDB connector for Ballerina.
Ballerina
112
star
97

module-ballerinax-aws.sns

This repo is to keep the newly written Amazon SNS connector for Ballerina.
Ballerina
112
star
98

module-ballerina-toml

Ballerina TOML Parser
Ballerina
112
star
99

edi-tools

This library provides the functionality required to process EDI files and implement EDI integrations.
Ballerina
112
star
100

module-ballerinax-health.fhir.r4

FHIR R4 Ballerina modules
Ballerina
112
star