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:

  1. $ git clone -b v1.28.1 https://github.com/grpc/grpc
  2. $ cd grpc

Then change your current directory to examples/ruby/route_guide:

  1. $ 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:

  1. service RouteGuide {
  2. ...
  3. }

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.
  1. // Obtains the feature at a given position.
  2. 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 streamkeyword before the response type.
  1. // Obtains the Features available within the given Rectangle. Results are
  2. // streamed rather than returned at once (e.g. in a response message with a
  3. // repeated field), as the rectangle may cover a large area and contain a
  4. // huge number of features.
  5. 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.
  1. // Accepts a stream of Points on a route being traversed, returning a
  2. // RouteSummary when traversal is completed.
  3. 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 streamkeyword before both the request and the response.
  1. // Accepts a stream of RouteNotes sent while a route is being traversed,
  2. // while receiving other RouteNotes (e.g. from other users).
  3. 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:

  1. // Points are represented as latitude-longitude pairs in the E7 representation
  2. // (degrees multiplied by 10**7 and rounded to the nearest integer).
  3. // Latitudes should be in the range +/- 90 degrees and longitude should be in
  4. // the range +/- 180 degrees (inclusive).
  5. message Point {
  6. int32 latitude = 1;
  7. int32 longitude = 2;
  8. }

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.

  1. $ 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 module Examples::RouteGuide
    • This contain all the protocol buffer code to populate, serialize, andretrieve our request and response message types
  • lib/route_guide_services.pb, extends Examples::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

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:

  1. # ServerImpl provides an implementation of the RouteGuide service.
  2. 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.

  1. def get_feature(point, _call)
  2. name = @feature_db[{
  3. 'longitude' => point.longitude,
  4. 'latitude' => point.latitude }] || ''
  5. Feature.new(location: point, name: name)
  6. 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 multipleFeatures to our client.

  1. # in ServerImpl
  2. def list_features(rectangle, _call)
  3. RectangleEnum.new(@feature_db, rectangle).each
  4. end

As you can see, here the request object is a Rectangle in which our clientwants to find Features, 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.

  1. call.each_remote_read do |point|
  2. ...
  3. end

Finally, let’s look at our bidirectional streaming RPC route_chat.

  1. def route_chat(notes)
  2. RouteChatEnumerator.new(notes, @received_notes).each_item
  3. 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:

  1. port = '0.0.0.0:50051'
  2. s = GRPC::RpcServer.new
  3. s.add_http2_port(port, :this_port_is_insecure)
  4. GRPC.logger.info("... running insecurely on #{port}")
  5. s.handle(ServerImpl.new(feature_db))
  6. # Runs the server with SIGHUP, SIGINT and SIGQUIT signal handlers to
  7. # gracefully shutdown.
  8. # User could also choose to run server via call to run_till_terminated
  9. 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 RouteGuideservice. 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.

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

  1. GET_FEATURE_POINTS = [
  2. Point.new(latitude: 409_146_138, longitude: -746_188_906),
  3. Point.new(latitude: 0, longitude: 0)
  4. ]
  5. ..
  6. GET_FEATURE_POINTS.each do |pt|
  7. resp = stub.get_feature(pt)
  8. ...
  9. p "- found '#{resp.name}' at #{pt.inspect}"
  10. 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

  1. resps = stub.list_features(LIST_FEATURES_RECT)
  2. resps.each do |r|
  3. p "- found '#{r.name}' at #{r.location.inspect}"
  4. end

The client-side streaming method record_route is similar, except there we passthe server an Enumerable.

  1. ...
  2. reqs = RandomRoute.new(features, points_on_route)
  3. resp = stub.record_route(reqs.each)
  4. ...

Finally, let’s look at our bidirectional streaming RPC route_chat. In thiscase, we pass Enumerable to the method and get back an Enumerable.

  1. sleeping_enumerator = SleepingEnumerator.new(ROUTE_CHAT_NOTES, 1)
  2. 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:

  1. $ cd examples/ruby

Build the client and server:

  1. $ gem install bundler && bundle install

Run the server:

  1. $ 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:

  1. $ bundle exec route_guide/route_guide_client.rb ../python/route_guide/route_guide_db.json