Debian Codegraph @

src/ruby/bin/noproto_server.rb

raw
1 #!/usr/bin/env ruby
2
3 # Copyright 2015 gRPC authors.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Sample app that helps validate RpcServer without protobuf serialization.
18 #
19 # Usage: $ path/to/noproto_server.rb
20
21 this_dir = File.expand_path(File.dirname(__FILE__))
22 lib_dir = File.join(File.dirname(this_dir), 'lib')
23 $LOAD_PATH.unshift(lib_dir) unless $LOAD_PATH.include?(lib_dir)
24
25 require 'grpc'
26 require 'optparse'
27
28 # a simple non-protobuf message class.
29 class NoProtoMsg
30 def self.marshal(_o)
31 ''
32 end
33
34 def self.unmarshal(_o)
35 NoProtoMsg.new
36 end
37 end
38
39 # service the uses the non-protobuf message class.
40 class NoProtoService
41 include GRPC::GenericService
42 rpc :AnRPC, NoProtoMsg, NoProtoMsg
43 end
44
45 # an implementation of the non-protobuf service.
46 class NoProto < NoProtoService
47 def initialize(_default_var = 'ignored')
48 end
49
50 def an_rpc(req, _call)
51 GRPC.logger.info('echo service received a request')
52 req
53 end
54 end
55
56 def load_test_certs
57 this_dir = File.expand_path(File.dirname(__FILE__))
58 data_dir = File.join(File.dirname(this_dir), 'spec/testdata')
59 files = ['ca.pem', 'server1.key', 'server1.pem']
60 files.map { |f| File.open(File.join(data_dir, f)).read }
61 end
62
63 def test_server_creds
64 certs = load_test_certs
65 GRPC::Core::ServerCredentials.new(
66 nil, [{ private_key: certs[1], cert_chain: certs[2] }], false)
67 end
68
69 def main
70 options = {
71 'host' => 'localhost:9090',
72 'secure' => false
73 }
74 OptionParser.new do |opts|
75 opts.banner = 'Usage: [--host <hostname>:<port>] [--secure|-s]'
76 opts.on('--host HOST', '<hostname>:<port>') do |v|
77 options['host'] = v
78 end
79 opts.on('-s', '--secure', 'access using test creds') do |v|
80 options['secure'] = v
81 end
82 end.parse!
83
84 s = GRPC::RpcServer.new
85 if options['secure']
86 s.add_http2_port(options['host'], test_server_creds)
87 GRPC.logger.info("... running securely on #{options['host']}")
88 else
89 s.add_http2_port(options['host'], :this_port_is_insecure)
90 GRPC.logger.info("... running insecurely on #{options['host']}")
91 end
92
93 s.handle(NoProto)
94 s.run_till_terminated
95 end
96
97 main