ballerina/grpc module
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.
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.
// 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.
// 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.
// 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.
// 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.
// 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.
// 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();
Type Definitions
Type | Values | Description | |
---|---|---|---|
Chunking | CHUNKING_NEVER | CHUNKING_AUTO | CHUNKING_ALWAYS | Defines the possible values for the chunking configuration in HTTP services and clients.
|
|
Compression | COMPRESSION_NEVER | COMPRESSION_AUTO | COMPRESSION_ALWAYS | Options to compress using gzip or deflate.
|
|
KeepAlive | KEEPALIVE_NEVER | KEEPALIVE_AUTO | KEEPALIVE_ALWAYS | Defines the possible values for the keep-alive configuration in service and client endpoints. |
Annotations
Name | Attachement Points | Data Type | Description |
---|---|---|---|
ResourceConfig | resource | GrpcResourceConfig | Service resource configuration. Sets only for server streaming service. |
ServiceConfig | service | GrpcServiceConfig | Service configuration. Sets only for client and bidirectional streaming service. |
ServiceDescriptor | service | ServiceDescriptorData | Service descriptor data generated at compile time. This is for internal use. |
Records Summary
Record | Description | ||
---|---|---|---|
ClientEndpointConfig | Represents client endpoint configuration. | ||
GrpcResourceConfig | Service resource configuration. Sets only for server streaming service. | ||
GrpcServiceConfig | Service configuration. Sets only for client and bidirectional streaming service. | ||
Local | Presents a read-only view of the local address. | ||
PoolConfiguration | Configurations for managing gRPC client connection pool. | ||
Protocols | Protocols record represents SSL/TLS protocol related options to be used for HTTP client/service invocation. | ||
ProxyConfig | Proxy server configurations to be used with the HTTP client endpoint. | ||
Remote | Presents a read-only view of the remote address. | ||
RequestLimits | Configures limits for requests. If these limits are violated, the request is rejected. | ||
SecureSocket | Provides configurations for facilitating secure communication with a remote HTTP endpoint. | ||
ServiceDescriptorData | Service descriptor data. This is for internal use. | ||
ServiceEndpointConfiguration | Represents the gRPC server endpoint configuration. | ||
ServiceOcspStapling | OcspStapling record represents options related to check whether a certificate is revoked or not. | ||
ServiceSecureSocket | Configures the SSL/TLS options to be used for HTTP service. | ||
ValidateCert | ValidateCert record represents options related to check whether a certificate is revoked or not. |
Objects Summary
Object | Description | ||
---|---|---|---|
Headers | Provides actions to read/write header values in gRPC request/response message. |
||
Listener | Represents server listener where one or more services can be registered. so that ballerina program can offer service through this listener. |
Endpoints Summary
Endpoint | Description | ||
---|---|---|---|
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. The API it provides includes functions to send request/error messages. |
||
StreamingClient | Provides the gRPC actions for interacting with gRPC server. |
Constants
Name | Data Type | Value | Description | |
---|---|---|---|---|
OK | int | 0 | Indicates operation is successful. |
|
CANCELED | int | 1 | Indicates the operation was canceled (typically by the caller). |
|
UNKNOWN | int | 2 | Indicates unknown error.(e.g. Status value received is unknown) |
|
INVALID_ARGUMENT | int | 3 | Indicates client specified an invalid argument. |
|
DEADLINE_EXCEEDED | int | 4 | Indicates operation expired before completion. |
|
NOT_FOUND | int | 5 | Indicates some requested entity (e.g., file or directory) was not found. |
|
ALREADY_EXISTS | int | 6 | Indicates the attempt to create an entity failed because one already exists. |
|
PERMISSION_DENIED | int | 7 | Indicates the caller does not have permission to execute the specified operation. |
|
RESOURCE_EXHAUSTED | int | 8 | Indicates some resource has been exhausted. |
|
FAILED_PRECONDITION | int | 9 | Indicates operation was rejected because the system is not in a state required for the operation's execution. |
|
ABORTED | int | 10 | Indicates the operation was aborted. |
|
OUT_OF_RANGE | int | 11 | Indicates specified value is out of range. |
|
UNIMPLEMENTED | int | 12 | Indicates operation is not implemented or not supported/enabled in this service. |
|
INTERNAL | int | 13 | Indicates internal errors. |
|
UNAVAILABLE | int | 14 | Indicates the service is currently unavailable. |
|
DATA_LOSS | int | 15 | Indicates unrecoverable data loss or corruption. |
|
UNAUTHENTICATED | int | 16 | Indicates the request does not have valid authentication credentials for the operation. |
|
KEEPALIVE_AUTO | AUTO | Decides to keep the connection alive or not based on the |
||
KEEPALIVE_ALWAYS | ALWAYS | Keeps the connection alive irrespective of the |
||
KEEPALIVE_NEVER | NEVER | Closes the connection irrespective of the |
||
COMPRESSION_AUTO | 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_ALWAYS | ALWAYS | Always set accept-encoding/content-encoding in outbound request/response. |
||
COMPRESSION_NEVER | NEVER | Never set accept-encoding/content-encoding header in outbound request/response. |
||
CHUNKING_AUTO | AUTO | If the payload is less than 8KB, content-length header is set in the outbound request/response, otherwise chunking header is set in the outbound request/response. |
||
CHUNKING_ALWAYS | ALWAYS | Always set chunking header in the response. |
||
CHUNKING_NEVER | NEVER | Never set the chunking header even if the payload is larger than 8KB in the outbound request/response. |
public type ClientEndpointConfig record
Represents client endpoint configuration.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
timeoutMillis | int | 60000 | The maximum time to wait (in milliseconds) for a response before closing the connection |
keepAlive | AUTO|ALWAYS|NEVER | KEEPALIVE_AUTO | Specifies whether to reuse a connection for multiple requests |
httpVersion | string | 2.0 | The HTTP version understood by the client |
chunking | AUTO|ALWAYS|NEVER | CHUNKING_NEVER | The chunking behaviour of the request |
forwarded | string | disable | The choice of setting |
proxy | grpc:ProxyConfig? | () | Proxy server related options |
poolConfig | grpc:PoolConfiguration? | () | Connection pool configuration |
secureSocket | grpc:SecureSocket? | () | SSL/TLS related options |
compression | AUTO|ALWAYS|NEVER | COMPRESSION_AUTO | Specifies the way of handling compression ( |
public type GrpcResourceConfig record
Service resource configuration. Sets only for server streaming service.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
streaming | boolean | false | Server streaming flag. This flag sets to true to specify that the resource is capable of sending multiple responses per request. |
requestType | typedesc | Request message type of the resource. This is an optional field. If it is not specified, request type is derived from input argument of the resource. |
|
responseType | typedesc | Response message type of the resource. This is an optional field. If it is not specified, response type is derived from the he value passed to the send() expression. |
public type GrpcServiceConfig record
Service configuration. Sets only for client and bidirectional streaming service.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
name | string | Resource name. This applies only for client streaming and bidirectional streaming where we can define only one resource. In order to generate proto file, service resource name need to pass as annotation parameter. |
|
requestType | typedesc | Request message type of the resource. This is an optional field. If it is not specified, request type is derived from input argument of the resource. |
|
responseType | typedesc | Response message type of the resource. This is an optional field. If it is not specified, response type is derived from the he value passed to the send() expression. |
|
clientStreaming | boolean | false | Client streaming flag. This applies only for client streaming and bidirectional streaming. Flag sets to true, if the service defines as client/bidirectional streaming. |
serverStreaming | boolean | false | Server streaming flag. This applies only for bidirectional streaming. Flag sets to true, if the service defines as bidirectional streaming. |
public type Local record
Presents a read-only view of the local address.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
host | string | The local host name/IP |
|
port | int | 0 | The local port |
public type PoolConfiguration record
Configurations for managing gRPC client connection pool.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
maxActiveConnections | int | config:getAsInt(b7a.http.pool.maxActiveConnections, defaultValue=-1) | Max active connections per route(host:port). Default value is -1 which indicates unlimited. |
maxIdleConnections | int | config:getAsInt(b7a.http.pool.maxIdleConnections, defaultValue=1000) | Maximum number of idle connections allowed per pool. |
waitTimeinMillis | int | config:getAsInt(b7a.http.pool.waitTimeinMillis, defaultValue=60000) | Maximum amount of time, the client should wait for an idle connection before it sends an error when the pool is exhausted |
maxActiveStreamsPerConnection | int | config:getAsInt(b7a.http.pool.maxActiveStreamsPerConnection, defaultValue=50) | Maximum active streams per connection. This only applies to HTTP/2. |
public type Protocols record
Protocols record represents SSL/TLS protocol related options to be used for HTTP client/service invocation.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
name | string | SSL Protocol to be used. eg TLS1.2 |
|
versions | string[] | [] | SSL/TLS protocols to be enabled. eg TLSv1,TLSv1.1,TLSv1.2 |
public type ProxyConfig record
Proxy server configurations to be used with the HTTP client endpoint.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
host | string | Host name of the proxy server |
|
port | int | 0 | Proxy server port |
userName | string | Proxy server username |
|
password | string | proxy server password |
public type Remote record
Presents a read-only view of the remote address.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
host | string | The remote host name/IP |
|
port | int | 0 | The remote port |
public type RequestLimits record
Configures limits for requests. If these limits are violated, the request is rejected.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
maxUriLength | int | -1 | Maximum allowed length for a URI. Exceeding this limit will result in a
|
maxHeaderSize | int | -1 | Maximum allowed size for headers. Exceeding this limit will result in a
|
maxEntityBodySize | int | -1 | Maximum allowed size for the entity body. Exceeding this limit will result in a
|
public type SecureSocket record
Provides configurations for facilitating secure communication with a remote HTTP endpoint.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
trustStore | crypto:TrustStore? | () | Configurations associated with TrustStore |
keyStore | crypto:KeyStore? | () | Configurations associated with KeyStore |
certFile | string | A file containing the certificate of the client |
|
keyFile | string | A file containing the private key of the client |
|
keyPassword | string | Password of the private key if it is encrypted |
|
trustedCertFile | string | A file containing a list of certificates or a single certificate that the client trusts |
|
protocol | grpc:Protocols? | () | SSL/TLS protocol related options |
certValidation | grpc:ValidateCert? | () | Certificate validation against CRL or OCSP related options |
ciphers | string[] | [] | List of ciphers to be used eg: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA |
verifyHostname | boolean | true | Enable/disable host name verification |
shareSession | boolean | true | Enable/disable new SSL session creation |
ocspStapling | boolean | false | Enable/disable OCSP stapling |
public type ServiceDescriptorData record
Service descriptor data. This is for internal use.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
descriptor | string | Service descriptor sets at compile time. |
|
descMap | map | {} | Service dependent descriptor map sets at compile time. |
public type ServiceEndpointConfiguration record
Represents the gRPC server endpoint configuration.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
host | string | 0.0.0.0 | The server hostname. |
keepAlive | AUTO|ALWAYS|NEVER | KEEPALIVE_AUTO | Can be set to either |
secureSocket | grpc:ServiceSecureSocket? | () | The SSL configurations for the client endpoint. |
httpVersion | string | 2.0 | HTTP version supported by the endpoint. This should be 2.0 as gRPC works only with HTTP/2. |
requestLimits | grpc:RequestLimits? | () | Configures the parameters for request validation. |
timeoutMillis | int | DEFAULT_LISTENER_TIMEOUT | Period of time in milliseconds that a connection waits for a read/write operation. Use value 0 to disable timeout. |
maxPipelinedRequests | int | MAX_PIPELINED_REQUESTS | Defines the maximum number of requests that can be processed at a given time on a single connection. By default 10 requests can be pipelined on a single cinnection and user can change this limit appropriately. This will be applicable only for HTTP 1.1 |
public type ServiceOcspStapling record
OcspStapling record represents options related to check whether a certificate is revoked or not.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
enable | boolean | false | The status of OcspStapling |
cacheSize | int | 0 | Maximum size of the cache |
cacheValidityPeriod | int | 0 | Time duration of cache validity period |
public type ServiceSecureSocket record
Configures the SSL/TLS options to be used for HTTP service.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
trustStore | crypto:TrustStore? | () | Configures the trust store to be used |
keyStore | crypto:KeyStore? | () | Configures the key store to be used |
certFile | string | A file containing the certificate of the server |
|
keyFile | string | A file containing the private key of the server |
|
keyPassword | string | Password of the private key if it is encrypted |
|
trustedCertFile | string | A file containing a list of certificates or a single certificate that the server trusts |
|
protocol | grpc:Protocols? | () | SSL/TLS protocol related options |
certValidation | grpc:ValidateCert? | () | Certificate validation against CRL or OCSP related options |
ciphers | string[] | [] | List of ciphers to be used (e.g.: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA) |
sslVerifyClient | string | The type of client certificate verification |
|
shareSession | boolean | true | Enable/disable new SSL session creation |
ocspStapling | grpc:ServiceOcspStapling? | () | Enable/disable OCSP stapling |
handshakeTimeout | int | SSL handshake time out |
|
sessionTimeout | int | SSL session time out |
public type ValidateCert record
ValidateCert record represents options related to check whether a certificate is revoked or not.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
enable | boolean | false | The status of validateCertEnabled |
cacheSize | int | 0 | Maximum size of the cache |
cacheValidityPeriod | int | 0 | Time duration of cache validity period |
public type Headers object
Provides actions to read/write header values in gRPC request/response message.
-
<Headers> exists(string headerName) returns (boolean)
Check whether the requested header exists.
Parameter Name Data Type Default Value Description headerName string The header name.
Return Type Description boolean Returns true if header exists, false otherwise.
-
<Headers> get(string headerName) returns (string)
Returns the header value with the specified header name. If there are more than one header value for the specified header name, the first value is returned.
Parameter Name Data Type Default Value Description headerName string The header name.
Return Type Description string Returns first header value if exists, nil otherwise.
-
<Headers> getAll(string headerName) returns (string[])
Gets all transport headers with the specified header name.
Parameter Name Data Type Default Value Description headerName string The header name.
Return Type Description string[] Returns header value array.
-
<Headers> setEntry(string headerName, string headerValue)
Sets the value of a transport header.
Parameter Name Data Type Default Value Description headerName string The header name.
headerValue string The header value.
-
<Headers> addEntry(string headerName, string headerValue)
Adds the specified key/value pair as an HTTP header to the request.
Parameter Name Data Type Default Value Description headerName string The header name.
headerValue string The header value.
-
<Headers> remove(string headerName)
Removes a transport header from the request.
Parameter Name Data Type Default Value Description headerName string The header name.
-
<Headers> removeAll()
Removes all transport headers from the message.
public type Listener object
Represents server listener where one or more services can be registered. so that ballerina program can offer service through this listener.
-
<Listener> __init(int port, grpc:ServiceEndpointConfiguration? config)
Gets called when the endpoint is being initialize during module init time.
Parameter Name Data Type Default Value Description port int Listener port.
config grpc:ServiceEndpointConfiguration? () The ServiceEndpointConfiguration of the endpoint.
-
<Listener> __start() returns (error?<>)
Starts the registered service.
Return Type Description error?<> Returns an error if encounters an error while starting the server, returns nil otherwise.
-
<Listener> __stop() returns (error?<>)
Stops the registered service.
Return Type Description error?<> Returns an error if encounters an error while stopping the server, returns nil otherwise.
-
<Listener> __attach(service s, string? name) returns (error?<>)
Gets called every time a service attaches itself to this endpoint - also happens at module init time.
Parameter Name Data Type Default Value Description s service The type of the service to be registered.
name string? () Name of the service.
Return Type Description error?<> Returns an error if encounters an error while attaching the service, returns nil otherwise.
Endpoint Caller
Provides the gRPC remote functions for interacting with caller.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
remoteDetails | grpc:Remote | {} | The remote details |
local | grpc:Local | {} | The local details |
-
<Caller> send(any res, grpc:Headers? headers) returns (error?<>)
Sends outbound response to the caller.
Parameter Name Data Type Default Value Description res any - The outbound response message.
headers grpc:Headers? () - Optional headers parameter. Passes header value if needed. Default sets to nil.
Return Type Description error?<> - Returns an error if encounters an error while sending the response, returns nil otherwise.
-
<Caller> complete() returns (error?<>)
Informs the caller, server finished sending messages.
Return Type Description error?<> Returns an error if encounters an error while sending the response, returns nil otherwise.
-
<Caller> isCancelled() returns (boolean)
Checks whether the connection is closed by the caller.
Return Type Description boolean Returns true, if caller already closed the connection. false otherwise.
-
<Caller> sendError(int statusCode, string message, grpc:Headers? headers) returns (error?<>)
Sends server error to the caller.
Parameter Name Data Type Default Value Description statusCode int Error status code.
message string Error message.
headers grpc:Headers? () Optional headers parameter. Passes header value if needed. Default sets to nil.
Return Type Description error?<> Returns an error if encounters an error while sending the response, returns nil otherwise.
Endpoint Client
The gRPC client endpoint provides the capability for initiating contact with a remote gRPC service. The API it provides includes functions to send request/error messages.
-
<Client> blockingExecute(string methodID, any payload, grpc:Headers? headers) returns ((any,Headers)|error<>)
Calls when executing blocking call with gRPC service.
Parameter Name Data Type Default Value Description methodID string Remote service method id.
payload any Request message. Message type varies with remote service method parameter.
headers grpc:Headers? () Optional headers parameter. Passes header value if needed. Default sets to nil.
Return Type Description (any,Headers)|error<> Returns response message and headers if executes successfully, error otherwise.
-
<Client> nonBlockingExecute(string methodID, any payload, service listenerService, grpc:Headers? headers) returns (error?<>)
Calls when executing non-blocking call with gRPC service.
Parameter Name Data Type Default Value Description methodID string Remote service method id.
payload any Request message. Message type varies with remote service method parameter..
listenerService service Call back listener service. This service listens the response message from service.
headers grpc:Headers? () Optional headers parameter. Passes header value if needed. Default sets to nil.
Return Type Description error?<> Returns an error if encounters an error while sending the request, returns nil otherwise.
-
<Client> streamingExecute(string methodID, service listenerService, grpc:Headers? headers) returns (StreamingClient|error<>)
Calls when executing streaming call with gRPC service.
Parameter Name Data Type Default Value Description methodID string Remote service method id.
listenerService service Call back listener service. This service listens the response message from service.
headers grpc:Headers? () Optional headers parameter. Passes header value if needed. Default sets to nil.
Return Type Description StreamingClient|error<> Returns client connection if executes successfully, error otherwise.
Endpoint StreamingClient
Provides the gRPC actions for interacting with gRPC server.
-
<StreamingClient> send(any res) returns (error?<>)
Sends request message to the server.
Parameter Name Data Type Default Value Description res any The inbound request message.
Return Type Description error?<> Returns an error if encounters an error while sending the response, returns nil otherwise.
-
<StreamingClient> complete() returns (error?<>)
Informs the server, caller finished sending messages.
Return Type Description error?<> Returns an error if encounters an error while sending the response, returns nil otherwise.
-
<StreamingClient> sendError(int statusCode, string message) returns (error?<>)
Sends error message to the server.
Parameter Name Data Type Default Value Description statusCode int Error status code.
message string Error message.
Return Type Description error?<> Returns an error if encounters an error while sending the response, returns nil otherwise.