blob: 736a38099047cd090bc019a26c0f0107a3f03999 [file] [log] [blame] [view]
Tim Emiolac66fe1e2015-02-26 03:53:16 -08001#gRPC Basics: Ruby
2
3This tutorial provides a basic Ruby programmer's introduction to working with gRPC. By walking through this example you'll learn how to:
4
5- Define a service in a .proto file.
6- Generate server and client code using the protocol buffer compiler.
7- Use the Ruby gRPC API to write a simple client and server for your service.
8
9It assumes that you have read the [Getting started](https://github.com/grpc/grpc-common) guide and are familiar with [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). Note that the example in this tutorial uses the proto3 version of the protocol buffers language, which is currently in alpha release: you can see the [release notes](https://github.com/google/protobuf/releases) for the new version in the protocol buffers Github repository.
10
11This isn't a comprehensive guide to using gRPC in Ruby: more reference documentation is coming soon.
12
13## Why use gRPC?
14
15Our example is a simple route mapping application that lets clients get information about features on their route, create a summary of their route, and exchange route information such as traffic updates with the server and other clients.
16
17With gRPC we can define our service once in a .proto file and implement clients and servers in any of gRPC's supported languages, which in turn can be run in environments ranging from servers inside Google to your own tablet - all the complexity of communication between different languages and environments is handled for you by gRPC. We also get all the advantages of working with protocol buffers, including efficient serialization, a simple IDL, and easy interface updating.
18
19## Example code and setup
20
21The example code for our tutorial is in [grpc/grpc-common/ruby/route_guide](https://github.com/grpc/grpc-common/tree/master/ruby/route_guide). To download the example, clone the `grpc-common` repository by running the following command:
22```shell
23$ git clone https://github.com/google/grpc-common.git
24```
25
26Then change your current directory to `grpc-common/ruby/route_guide`:
27```shell
28$ cd grpc-common/ruby/route_guide
29```
30
31You also should have the relevant tools installed to generate the server and client interface code - if you don't already, follow the setup instructions in [the Ruby quick start guide](https://github.com/grpc/grpc-common/tree/master/ruby).
32
33
34## Defining the service
35
36Our first step (as you'll know from [Getting started](https://github.com/grpc/grpc-common)) is to define the gRPC *service* and the method *request* and *response* types using [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). You can see the complete .proto file in [`grpc-common/protos/route_guide.proto`](https://github.com/grpc/grpc-common/blob/master/protos/route_guide.proto).
37
38To define a service, you specify a named `service` in your .proto file:
39
40```
41service RouteGuide {
42 ...
43}
44```
45
46Then you define `rpc` methods inside your service definition, specifying their request and response types. gRPC lets you define four kinds of service method, all of which are used in the `RouteGuide` service:
47
48- A *simple RPC* where the client sends a request to the server using the stub and waits for a response to come back, just like a normal function call.
49```
50 // Obtains the feature at a given position.
51 rpc GetFeature(Point) returns (Feature) {}
52```
53
54- A *server-side streaming RPC* where the client sends a request to the server and gets a stream to read a sequence of messages back. The client reads from the returned stream until there are no more messages. As you can see in our example, you specify a server-side streaming method by placing the `stream` keyword before the *response* type.
55```
56 // Obtains the Features available within the given Rectangle. Results are
57 // streamed rather than returned at once (e.g. in a response message with a
58 // repeated field), as the rectangle may cover a large area and contain a
59 // huge number of features.
60 rpc ListFeatures(Rectangle) returns (stream Feature) {}
61```
62
63- A *client-side streaming RPC* where the client writes a sequence of messages and sends them to the server, again using a provided stream. Once the client has finished writing the messages, it waits for the server to read them all and return its response. You specify a server-side streaming method by placing the `stream` keyword before the *request* type.
64```
65 // Accepts a stream of Points on a route being traversed, returning a
66 // RouteSummary when traversal is completed.
67 rpc RecordRoute(stream Point) returns (RouteSummary) {}
68```
69
70- A *bidirectional streaming RPC* where both sides send a sequence of messages using a read-write stream. The two streams operate independently, so clients and servers can read and write in whatever order they like: for example, the server could wait to receive all the client messages before writing its responses, or it could alternately read a message then write a message, or some other combination of reads and writes. The order of messages in each stream is preserved. You specify this type of method by placing the `stream` keyword before both the request and the response.
71```
72 // Accepts a stream of RouteNotes sent while a route is being traversed,
73 // while receiving other RouteNotes (e.g. from other users).
74 rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
75```
76
77Our .proto file also contains protocol buffer message type definitions for all the request and response types used in our service methods - for example, here's the `Point` message type:
78```
79// Points are represented as latitude-longitude pairs in the E7 representation
80// (degrees multiplied by 10**7 and rounded to the nearest integer).
81// Latitudes should be in the range +/- 90 degrees and longitude should be in
82// the range +/- 180 degrees (inclusive).
83message Point {
84 int32 latitude = 1;
85 int32 longitude = 2;
86}
87```
88
89
90## Generating client and server code
91
92Next we need to generate the gRPC client and server interfaces from our .proto service definition. We do this using the protocol buffer compiler `protoc` with a special gRPC Ruby plugin.
93
94If you want to run this yourself, make sure you've installed protoc and followed the gRPC Ruby plugin [installation instructions](https://github.com/grpc/grpc/blob/master/INSTALL) first):
95
96Once that's done, the following command can be used to generate the ruby code.
97
98```shell
99$ protoc -I ../../protos --ruby_out=lib --grpc_out=lib --plugin=protoc-gen-grpc=`which grpc_ruby_plugin` ../../protos/route_guide.proto
100```
101
102Running this command regenerates the following files in the lib directory:
103- `lib/route_guide.pb` defines a module `Examples::RouteGuide`
104 - This contain all the protocol buffer code to populate, serialize, and retrieve our request and response message types
105- `lib/route_guide_services.pb`, extends `Examples::RouteGuide` with stub and service classes
106 - it adds a class `Service` that is to be used as a base class for define RouteGuide service implementations
107 - a class `Stub` that can be used to access remote RouteGuide instances
108
109
110<a name="server"></a>
111## Creating the server
112
113First let's look at how we create a `RouteGuide` server. If you're only interested in creating gRPC clients, you can skip this section and go straight to [Creating the client](#client) (though you might find it interesting anyway!).
114
115There are two parts to making our `RouteGuide` service do its job:
116- Implementing the service interface generated from our service definition: doing the actual "work" of our service.
117- Running a gRPC server to listen for requests from clients and return the service responses.
118
119You can find our example `RouteGuide` server in [grpc-common/ruby/route_guide/route_guide_server.rb](https://github.com/grpc/grpc-common/blob/master/ruby/route_guide/route_guide_server.rb). Let's take a closer look at how it works.
120
121### Implementing RouteGuide
122
123As you can see, our server has a `ServerImpl` class that extends the generated `RouteGuide::Service`:
124
125```ruby
126# ServerImpl provides an implementation of the RouteGuide service.
127class ServerImpl < RouteGuide::Service
128```
129
130`ServerImpl` implements all our service methods. Let's look at the simplest type first, `GetFeature`, which just gets a `Point` from the client and returns the corresponding feature information from its database in a `Feature`.
131
132```ruby
133 def get_feature(point, _call)
134 name = @feature_db[{
135 'longitude' => point.longitude,
136 'latitude' => point.latitude }] || ''
137 Feature.new(location: point, name: name)
138 end
139```
140
141The method is passed a _call for the RPC, the client's `Point` protocol buffer request, and returns `Feature` protocol buffer. In the method we create the `Feature` with the appropriate information, and then `return` it.
142
143Now 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 multiple `Feature`s to our client.
144
145```ruby
146# in ServerImpl
147
148 def list_features(rectangle, _call)
149 RectangleEnum.new(@feature_db, rectangle).each
150 end
151
152```
153
154As you can see, here the request object is a `Rectangle` in which our client wants to find `Feature`s), but instead of returning a simple response we need to return an [Enumerator](http://ruby-doc.org//core-2.2.0/Enumerator.html) that yields the responses. In the method, we use a helper class `RectangleEnum`, to act as an Enumerator implementation.
155
156Similarly, the client-side streaming method `record_route` uses an [Enumerable](http://ruby-doc.org//core-2.2.0/Enumerable.html), but here it's obtained 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.
157
158```ruby
159 call.each_remote_read do |point|
160 ...
161 end
162```
163Finally, let's look at our bidirectional streaming RPC `route_chat`.
164
165```ruby
166 def route_chat(notes)
167 q = EnumeratorQueue.new(self)
168 t = Thread.new do
169 begin
170 notes.each do |n|
171 ...
172 end
173 end
174 q = EnumeratorQueue.new(self)
175 ...
176 return q.each_item
177 end
178```
179
180Here the method receives an [Enumerable](http://ruby-doc.org//core-2.2.0/Enumerable.html), notes, but also returns an [Enumerator](http://ruby-doc.org//core-2.2.0/Enumerator.html) that yields the responses. The implementation demonstrates how to set these up so that the requests and responses can be handled concurrently. 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 completely independently.
181
182### Starting the server
183
184Once we've implemented all our methods, we also need to start up a gRPC server so that clients can actually use our service. The following snippet shows how we do this for our `RouteGuide` service:
185
186```ruby
187 s = GRPC::RpcServer.new
188 s.add_http2_port(port)
189 logger.info("... running insecurely on #{port}")
190 s.handle(ServerImpl.new(feature_db))
191 s.run
192```
193As you can see, we build and start our server using a `GRPC::RpcServer`. To do this, we:
194
1951. Create an instance of our service implementation class `ServerImpl`.
1962. Specify the address and port we want to use to listen for client requests using the builder's `add_http2_port` method.
1973. Register our service implementation with the `GRPC::RpcServer`.
1984. Call `run` on the`GRPC::RpcServer` to create and start an RPC server for our service.
199
200<a name="client"></a>
201## Creating the client
202
203In this section, we'll look at creating a Rubyclient for our `RouteGuide` service. You can see our complete example client code in [grpc-common/ruby/route_guide/route_guide_client.rb](https://github.com/grpc/grpc-common/blob/master/ruby/route_guide/route_guide_client.rb).
204
205### Creating a stub
206
207To call service methods, we first need to create a *stub*.
208
209We use the `Stub` class of `RouteGuide` module generated from our .proto.
210
211```ruby
212 stub = RouteGuide::Stub.new('localhost:50051')
213```
214
215### Calling service methods
216
217Now let's look at how we call our service methods. Note that the gRPC Ruby only provides *blocking/synchronous* versions of each method: this means that the RPC call waits for the server to respond, and will either return a response or raise an exception.
218
219#### Simple RPC
220
221Calling the simple RPC `GetFeature` is nearly as straightforward as calling a local method.
222
223```ruby
224GET_FEATURE_POINTS = [
225 Point.new(latitude: 409_146_138, longitude: -746_188_906),
226 Point.new(latitude: 0, longitude: 0)
227]
228..
229 GET_FEATURE_POINTS.each do |pt|
230 resp = stub.get_feature(pt)
231 ...
232 p "- found '#{resp.name}' at #{pt.inspect}"
233 end
234```
235
236As you can see, we create and populate a request protocol buffer object (in our case `Point`), and create a response protocol buffer object for the server to fill 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 response information from the server from our response object.
237
238
239#### Streaming RPCs
240
241Now let's look at our streaming methods. If you've already read [Creating the server](#server) some of this may look very familiar - streaming RPCs are implemented in a similar way on both sides. Here's where we call the server-side streaming method `list_features`, which returns an `Enumerable` of `Features`
242
243```ruby
244 resps = stub.list_features(LIST_FEATURES_RECT)
245 resps.each do |r|
246 p "- found '#{r.name}' at #{r.location.inspect}"
247 end
248```
249
250`The client-side streaming method `record_rout` is similar, except there in an `Enumerable`.
251
252```ruby
253 ...
254 reqs = RandomRoute.new(features, points_on_route)
255 resp = stub.record_route(reqs.each, deadline)
256 ...
257```
258
259Finally, let's look at our bidirectional streaming RPC `route_chat`. In this case, we pass `Enumerable` to the method and get back an `Enumerable`.
260
261```ruby
262 resps = stub.route_chat(ROUTE_CHAT_NOTES)
263 resps.each { |r| p "received #{r.inspect}" }
264```
265
266Although it's not shown well by this example, each enumerable is independent of the other - both the client and server can read and write in any order the streams operate completely independently.
267
268## Try it out!
269
270Build client and server:
271
272```shell
273$ # from grpc-common/ruby
274$ gem install bundler && bundle install
275```
276Run the server, which will listen on port 50051:
277```shell
278$ # from grpc-common/ruby
279$ bundle exec route_guide/route_guide_server.rb ../node/route_guide/route_guide_db.json &
280```
281Run the client (in a different terminal):
282```shell
283$ # from grpc-common/ruby
284$ bundle exec route_guide/route_guide_client.rb ../node/route_guide/route_guide_db.json &
285```
286