Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(5)

Side by Side Diff: third_party/grpc/examples/ruby/route_guide/route_guide_server.rb

Issue 1932353002: Initial checkin of gRPC to third_party/ Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Created 4 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 #!/usr/bin/env ruby
2 # -*- coding: utf-8 -*-
3
4 # Copyright 2015, Google Inc.
5 # All rights reserved.
6 #
7 # Redistribution and use in source and binary forms, with or without
8 # modification, are permitted provided that the following conditions are
9 # met:
10 #
11 # * Redistributions of source code must retain the above copyright
12 # notice, this list of conditions and the following disclaimer.
13 # * Redistributions in binary form must reproduce the above
14 # copyright notice, this list of conditions and the following disclaimer
15 # in the documentation and/or other materials provided with the
16 # distribution.
17 # * Neither the name of Google Inc. nor the names of its
18 # contributors may be used to endorse or promote products derived from
19 # this software without specific prior written permission.
20 #
21 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32
33 # Sample app that connects to a Route Guide service.
34 #
35 # Usage: $ path/to/route_guide_server.rb path/to/route_guide_db.json &
36
37 this_dir = File.expand_path(File.dirname(__FILE__))
38 lib_dir = File.join(File.dirname(this_dir), 'lib')
39 $LOAD_PATH.unshift(lib_dir) unless $LOAD_PATH.include?(lib_dir)
40
41 require 'grpc'
42 require 'multi_json'
43 require 'route_guide_services'
44
45 include Routeguide
46 COORD_FACTOR = 1e7
47 RADIUS = 637_100
48
49 # Determines the distance between two points.
50 def calculate_distance(point_a, point_b)
51 to_radians = proc { |x| x * Math::PI / 180 }
52 lat_a = point_a.latitude / COORD_FACTOR
53 lat_b = point_b.latitude / COORD_FACTOR
54 long_a = point_a.longitude / COORD_FACTOR
55 long_b = point_b.longitude / COORD_FACTOR
56 φ1 = to_radians.call(lat_a)
57 φ2 = to_radians.call(lat_b)
58 Δφ = to_radians.call(lat_a - lat_b)
59 Δλ = to_radians.call(long_a - long_b)
60 a = Math.sin(Δφ / 2)**2 +
61 Math.cos(φ1) * Math.cos(φ2) +
62 Math.sin(Δλ / 2)**2
63 (2 * RADIUS * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))).to_i
64 end
65
66 # RectangleEnum provides an Enumerator of the points in a feature_db within a
67 # given Rectangle.
68 class RectangleEnum
69 # @param [Hash] feature_db
70 # @param [Rectangle] bounds
71 def initialize(feature_db, bounds)
72 @feature_db = feature_db
73 @bounds = bounds
74 lats = [@bounds.lo.latitude, @bounds.hi.latitude]
75 longs = [@bounds.lo.longitude, @bounds.hi.longitude]
76 @lo_lat, @hi_lat = lats.min, lats.max
77 @lo_long, @hi_long = longs.min, longs.max
78 end
79
80 # in? determines if location lies within the bounds of this instances
81 # Rectangle.
82 def in?(location)
83 location['longitude'] >= @lo_long &&
84 location['longitude'] <= @hi_long &&
85 location['latitude'] >= @lo_lat &&
86 location['latitude'] <= @hi_lat
87 end
88
89 # each yields the features in the instances feature_db that lie within the
90 # instance rectangle.
91 def each
92 return enum_for(:each) unless block_given?
93 @feature_db.each_pair do |location, name|
94 next unless in?(location)
95 next if name.nil? || name == ''
96 pt = Point.new(
97 Hash[location.each_pair.map { |k, v| [k.to_sym, v] }])
98 yield Feature.new(location: pt, name: name)
99 end
100 end
101 end
102
103 # A EnumeratorQueue wraps a Queue to yield the items added to it.
104 class EnumeratorQueue
105 extend Forwardable
106 def_delegators :@q, :push
107
108 def initialize(sentinel)
109 @q = Queue.new
110 @sentinel = sentinel
111 @received_notes = {}
112 end
113
114 def each_item
115 return enum_for(:each_item) unless block_given?
116 loop do
117 r = @q.pop
118 break if r.equal?(@sentinel)
119 fail r if r.is_a? Exception
120 yield r
121 end
122 end
123 end
124
125 # ServerImpl provides an implementation of the RouteGuide service.
126 class ServerImpl < RouteGuide::Service
127 # @param [Hash] feature_db {location => name}
128 def initialize(feature_db)
129 @feature_db = feature_db
130 @received_notes = Hash.new { |h, k| h[k] = [] }
131 end
132
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 def list_features(rectangle, _call)
141 RectangleEnum.new(@feature_db, rectangle).each
142 end
143
144 def record_route(call)
145 started, elapsed_time = 0, 0
146 distance, count, features, last = 0, 0, 0, nil
147 call.each_remote_read do |point|
148 count += 1
149 name = @feature_db[{
150 'longitude' => point.longitude,
151 'latitude' => point.latitude }] || ''
152 features += 1 unless name == ''
153 if last.nil?
154 last = point
155 started = Time.now.to_i
156 next
157 end
158 elapsed_time = Time.now.to_i - started
159 distance += calculate_distance(point, last)
160 last = point
161 end
162 RouteSummary.new(point_count: count,
163 feature_count: features,
164 distance: distance,
165 elapsed_time: elapsed_time)
166 end
167
168 def route_chat(notes)
169 q = EnumeratorQueue.new(self)
170 # run a separate thread that processes the incoming requests
171 t = Thread.new do
172 begin
173 notes.each do |n|
174 key = {
175 'latitude' => n.location.latitude,
176 'longitude' => n.location.longitude
177 }
178 earlier_msgs = @received_notes[key]
179 @received_notes[key] << n.message
180 # send back the earlier messages at this point
181 earlier_msgs.each do |r|
182 q.push(RouteNote.new(location: n.location, message: r))
183 end
184 end
185 q.push(self) # signal completion
186 rescue StandardError => e
187 q.push(e) # signal completion via an error
188 end
189 end
190 q.each_item
191 end
192 end
193
194 def main
195 if ARGV.length == 0
196 fail 'Please specify the path to the route_guide json database'
197 end
198 raw_data = []
199 File.open(ARGV[0]) do |f|
200 raw_data = MultiJson.load(f.read)
201 end
202 feature_db = Hash[raw_data.map { |x| [x['location'], x['name']] }]
203 port = '0.0.0.0:50051'
204 s = GRPC::RpcServer.new
205 s.add_http2_port(port, :this_port_is_insecure)
206 GRPC.logger.info("... running insecurely on #{port}")
207 s.handle(ServerImpl.new(feature_db))
208 s.run_till_terminated
209 end
210
211 main
OLDNEW
« no previous file with comments | « third_party/grpc/examples/ruby/route_guide/route_guide_client.rb ('k') | third_party/grpc/gRPC.podspec » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698