gRPC Basics - Ruby
This tutorial provides a basic Ruby programmer’s introduction to working with gRPC.
By walking through this example you’ll learn how to:
- Define a service in a .proto file.
- Generate server and client code using the protocol buffer compiler.
- Use the Ruby gRPC API to write a simple client and server for your service.
It assumes that you have read theOverview and are familiarwithprotocolbuffers. Notethat the example in this tutorial uses the proto3 version of the protocolbuffers language: you can find out more intheproto3 languageguide.
Why use gRPC?
Our example is a simple route mapping application that lets clients getinformation about features on their route, create a summary of their route, andexchange route information such as traffic updates with the server and otherclients.
With gRPC we can define our service once in a .proto file and implement clientsand servers in any of gRPC’s supported languages, which in turn can be run inenvironments ranging from servers inside Google to your own tablet - all thecomplexity of communication between different languages and environments ishandled for you by gRPC. We also get all the advantages of working with protocolbuffers, including efficient serialization, a simple IDL, and easy interfaceupdating.
Example code and setup
The example code for our tutorial is ingrpc/grpc/examples/ruby/route_guide.To download the example, clone the grpc
repository by running the followingcommand:
$ git clone -b v1.28.1 https://github.com/grpc/grpc
$ cd grpc
Then change your current directory to examples/ruby/route_guide
:
$ cd examples/ruby/route_guide
You also should have the relevant tools installed to generate the server andclient interface code - if you don’t already, follow the setup instructions inthe Ruby quick start guide.
Defining the service
Our first step (as you’ll know from theOverview) is todefine the gRPC service and the method request and response types usingprotocolbuffers. You cansee the complete .proto file inexamples/protos/route_guide.proto
.
To define a service, you specify a named service
in your .proto file:
service RouteGuide {
...
}
Then you define rpc
methods inside your service definition, specifying theirrequest and response types. gRPC lets you define four kinds of service method,all of which are used in the RouteGuide
service:
- A simple RPC where the client sends a request to the server using the stuband waits for a response to come back, just like a normal function call.
// Obtains the feature at a given position.
rpc GetFeature(Point) returns (Feature) {}
- A server-side streaming RPC where the client sends a request to the serverand gets a stream to read a sequence of messages back. The client reads fromthe returned stream until there are no more messages. As you can see in ourexample, you specify a server-side streaming method by placing the
stream
keyword before the response type.
// Obtains the Features available within the given Rectangle. Results are
// streamed rather than returned at once (e.g. in a response message with a
// repeated field), as the rectangle may cover a large area and contain a
// huge number of features.
rpc ListFeatures(Rectangle) returns (stream Feature) {}
- A client-side streaming RPC where the client writes a sequence of messagesand sends them to the server, again using a provided stream. Once the clienthas finished writing the messages, it waits for the server to read them alland return its response. You specify a client-side streaming method by placingthe
stream
keyword before the request type.
// Accepts a stream of Points on a route being traversed, returning a
// RouteSummary when traversal is completed.
rpc RecordRoute(stream Point) returns (RouteSummary) {}
- A bidirectional streaming RPC where both sides send a sequence of messagesusing a read-write stream. The two streams operate independently, so clientsand servers can read and write in whatever order they like: for example, theserver could wait to receive all the client messages before writing itsresponses, or it could alternately read a message then write a message, orsome other combination of reads and writes. The order of messages in eachstream is preserved. You specify this type of method by placing the
stream
keyword before both the request and the response.
// Accepts a stream of RouteNotes sent while a route is being traversed,
// while receiving other RouteNotes (e.g. from other users).
rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
Our .proto
file also contains protocol buffer message type definitions for allthe request and response types used in our service methods - for example, here’sthe Point
message type:
// Points are represented as latitude-longitude pairs in the E7 representation
// (degrees multiplied by 10**7 and rounded to the nearest integer).
// Latitudes should be in the range +/- 90 degrees and longitude should be in
// the range +/- 180 degrees (inclusive).
message Point {
int32 latitude = 1;
int32 longitude = 2;
}
Generating client and server code
Next we need to generate the gRPC client and server interfaces from our .protoservice definition. We do this using the protocol buffer compiler protoc
witha special gRPC Ruby plugin.
If you want to run this yourself, make sure you’ve installed protoc and followedthe gRPC Ruby plugininstallationinstructions first):
Once that’s done, the following command can be used to generate the ruby code.
$ grpc_tools_ruby_protoc -I ../../protos --ruby_out=../lib --grpc_out=../lib ../../protos/route_guide.proto
Running this command regenerates the following files in the lib directory:
lib/route_guide.pb
defines a moduleExamples::RouteGuide
- This contain all the protocol buffer code to populate, serialize, andretrieve our request and response message types
lib/route_guide_services.pb
, extendsExamples::RouteGuide
with stub andservice classes- a class
Service
for use as a base class when defining RouteGuide serviceimplementations - a class
Stub
that can be used to access remote RouteGuide instances
- a class
Creating the server
First let’s look at how we create a RouteGuide
server. If you’re onlyinterested in creating gRPC clients, you can skip this section and go straighttoCreating the client (though you might find it interestinganyway!).
There are two parts to making our RouteGuide
service do its job:
- Implementing the service interface generated from our service definition:doing the actual “work” of our service.
- Running a gRPC server to listen for requests from clients and return theservice responses.
You can find our example RouteGuide
server inexamples/ruby/route_guide/route_guide_server.rb.Let’s take a closer look at how it works.
Implementing RouteGuide
As you can see, our server has a ServerImpl
class that extends the generatedRouteGuide::Service
:
# ServerImpl provides an implementation of the RouteGuide service.
class ServerImpl < RouteGuide::Service
ServerImpl
implements all our service methods. Let’s look at the simplest typefirst, GetFeature
, which just gets a Point
from the client and returns thecorresponding feature information from its database in a Feature
.
def get_feature(point, _call)
name = @feature_db[{
'longitude' => point.longitude,
'latitude' => point.latitude }] || ''
Feature.new(location: point, name: name)
end
The method is passed a _call for the RPC, the client’s Point
protocol bufferrequest, and returns a Feature
protocol buffer. In the method we create theFeature
with the appropriate information, and then return
it.
Now let’s look at something a bit more complicated - a streaming RPC.ListFeatures
is a server-side streaming RPC, so we need to send back multipleFeature
s to our client.
# in ServerImpl
def list_features(rectangle, _call)
RectangleEnum.new(@feature_db, rectangle).each
end
As you can see, here the request object is a Rectangle
in which our clientwants to find Feature
s, but instead of returning a simple response we need toreturn anEnumerator thatyields the responses. In the method, we use a helper class RectangleEnum
, toact as an Enumerator implementation.
Similarly, the client-side streaming method record_route
uses anEnumerable, but here it’sobtained from the call object, which we’ve ignored in the earlier examples.call.each_remote_read
yields each message sent by the client in turn.
call.each_remote_read do |point|
...
end
Finally, let’s look at our bidirectional streaming RPC route_chat
.
def route_chat(notes)
RouteChatEnumerator.new(notes, @received_notes).each_item
end
Here the method receives anEnumerable, but also returnsanEnumerator that yields theresponses. Although each side will always get the other’s messages in the order they were written,both the client and server can read and write in any order — the streams operate completelyindependently.
Starting the server
Once we’ve implemented all our methods, we also need to start up a gRPC serverso that clients can actually use our service. The following snippet shows how wedo this for our RouteGuide
service:
port = '0.0.0.0:50051'
s = GRPC::RpcServer.new
s.add_http2_port(port, :this_port_is_insecure)
GRPC.logger.info("... running insecurely on #{port}")
s.handle(ServerImpl.new(feature_db))
# Runs the server with SIGHUP, SIGINT and SIGQUIT signal handlers to
# gracefully shutdown.
# User could also choose to run server via call to run_till_terminated
s.run_till_terminated_or_interrupted([1, 'int', 'SIGQUIT'])
As you can see, we build and start our server using a GRPC::RpcServer
. To dothis, we:
- Create an instance of our service implementation class
ServerImpl
. - Specify the address and port we want to use to listen for client requestsusing the builder’s
add_http2_port
method. - Register our service implementation with the
GRPC::RpcServer
. - Call
run
on theGRPC::RpcServer
to create and start an RPC server for ourservice.
Creating the client
In this section, we’ll look at creating a Ruby client for our RouteGuide
service. You can see our complete example client code inexamples/ruby/route_guide/route_guide_client.rb.
Creating a stub
To call service methods, we first need to create a stub.
We use the Stub
class of the RouteGuide
module generated from our .proto.
stub = RouteGuide::Stub.new('localhost:50051')
Calling service methods
Now let’s look at how we call our service methods. Note that the gRPC Ruby onlyprovides blocking/synchronous versions of each method: this means that theRPC call waits for the server to respond, and will either return a response orraise an exception.
Simple RPC
Calling the simple RPC GetFeature
is nearly as straightforward as calling alocal method.
GET_FEATURE_POINTS = [
Point.new(latitude: 409_146_138, longitude: -746_188_906),
Point.new(latitude: 0, longitude: 0)
]
..
GET_FEATURE_POINTS.each do |pt|
resp = stub.get_feature(pt)
...
p "- found '#{resp.name}' at #{pt.inspect}"
end
As you can see, we create and populate a request protocol buffer object (in ourcase Point
), and create a response protocol buffer object for the server tofill in. Finally, we call the method on the stub, passing it the context,request, and response. If the method returns OK
, then we can read the responseinformation from the server from our response object.
Streaming RPCs
Now let’s look at our streaming methods. If you’ve already readCreating theserver some of this may look very familiar - streaming RPCs areimplemented in a similar way on both sides. Here’s where we call the server-sidestreaming method list_features
, which returns an Enumerable
of Features
resps = stub.list_features(LIST_FEATURES_RECT)
resps.each do |r|
p "- found '#{r.name}' at #{r.location.inspect}"
end
The client-side streaming method record_route
is similar, except there we passthe server an Enumerable
.
...
reqs = RandomRoute.new(features, points_on_route)
resp = stub.record_route(reqs.each)
...
Finally, let’s look at our bidirectional streaming RPC route_chat
. In thiscase, we pass Enumerable
to the method and get back an Enumerable
.
sleeping_enumerator = SleepingEnumerator.new(ROUTE_CHAT_NOTES, 1)
stub.route_chat(sleeping_enumerator.each_item) { |r| p "received #{r.inspect}" }
Although it’s not shown well by this example, each enumerable is independent ofthe other - both the client and server can read and write in any order — thestreams operate completely independently.
Try it out!
Work from the example directory:
$ cd examples/ruby
Build the client and server:
$ gem install bundler && bundle install
Run the server:
$ bundle exec route_guide/route_guide_server.rb ../python/route_guide/route_guide_db.json
Note
The route_guide_db.json
file is actually language-agnostic, it happens to be located in the python
folder.
From a different terminal, run the client:
$ bundle exec route_guide/route_guide_client.rb ../python/route_guide/route_guide_db.json