alain 0.4.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/LICENSE +201 -0
- data/exe/alain +46 -0
- data/lib/alain/cargo.rb +71 -0
- data/lib/alain/driver.rb +109 -0
- data/lib/alain/proto.rb +143 -0
- data/lib/alain/svc_code.rb +61 -0
- data/lib/alain/templates/build.rs.erb +4 -0
- data/lib/alain/templates/integration_test.rs.erb +18 -0
- data/lib/alain/templates/lib.rs.erb +40 -0
- data/lib/alain/templates/main.rs.erb +22 -0
- data/lib/alain/templates/mod.rs.erb +25 -0
- data/lib/alain/templates/service.rs.erb +5 -0
- data/lib/alain/util.rb +25 -0
- data/lib/alain/version.rb +5 -0
- data/lib/alain.rb +11 -0
- metadata +75 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: 213428bef56bf0641963627713eca28d2241896e06b243f621df2f2b684264a4
|
4
|
+
data.tar.gz: 0a44b8ff46020206fcabb472e675da7ee7d9938146b6fc98c6c5bdb7e42b4530
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: f1f1fb5b832aa94b150505b20939291ca67445a816ae888bb4a0641eb8ab65744f9c853a349351bea2a9c7b963b69987f939b2678c4b606a889e5ba573d1997f
|
7
|
+
data.tar.gz: 785870f203ac9fd17311665479125524245329e3413ea7b6c1e36c44bc2b70f2c9db4b28a8c46cb8c19b2e597fd48034b7396c1f7142cb36959bcb6606edea94
|
data/LICENSE
ADDED
@@ -0,0 +1,201 @@
|
|
1
|
+
Apache License
|
2
|
+
Version 2.0, January 2004
|
3
|
+
http://www.apache.org/licenses/
|
4
|
+
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6
|
+
|
7
|
+
1. Definitions.
|
8
|
+
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
11
|
+
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13
|
+
the copyright owner that is granting the License.
|
14
|
+
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
16
|
+
other entities that control, are controlled by, or are under common
|
17
|
+
control with that entity. For the purposes of this definition,
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
19
|
+
direction or management of such entity, whether by contract or
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22
|
+
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24
|
+
exercising permissions granted by this License.
|
25
|
+
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
27
|
+
including but not limited to software source code, documentation
|
28
|
+
source, and configuration files.
|
29
|
+
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
31
|
+
transformation or translation of a Source form, including but
|
32
|
+
not limited to compiled object code, generated documentation,
|
33
|
+
and conversions to other media types.
|
34
|
+
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
36
|
+
Object form, made available under the License, as indicated by a
|
37
|
+
copyright notice that is included in or attached to the work
|
38
|
+
(an example is provided in the Appendix below).
|
39
|
+
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46
|
+
the Work and Derivative Works thereof.
|
47
|
+
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
49
|
+
the original version of the Work and any modifications or additions
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
61
|
+
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
64
|
+
subsequently incorporated within the Work.
|
65
|
+
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
72
|
+
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78
|
+
where such license applies only to those patent claims licensable
|
79
|
+
by such Contributor that are necessarily infringed by their
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
82
|
+
institute patent litigation against any entity (including a
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
85
|
+
or contributory patent infringement, then any patent licenses
|
86
|
+
granted to You under this License for that Work shall terminate
|
87
|
+
as of the date such litigation is filed.
|
88
|
+
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
91
|
+
modifications, and in Source or Object form, provided that You
|
92
|
+
meet the following conditions:
|
93
|
+
|
94
|
+
(a) You must give any other recipients of the Work or
|
95
|
+
Derivative Works a copy of this License; and
|
96
|
+
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
98
|
+
stating that You changed the files; and
|
99
|
+
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
102
|
+
attribution notices from the Source form of the Work,
|
103
|
+
excluding those notices that do not pertain to any part of
|
104
|
+
the Derivative Works; and
|
105
|
+
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
108
|
+
include a readable copy of the attribution notices contained
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
111
|
+
of the following places: within a NOTICE text file distributed
|
112
|
+
as part of the Derivative Works; within the Source form or
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
114
|
+
within a display generated by the Derivative Works, if and
|
115
|
+
wherever such third-party notices normally appear. The contents
|
116
|
+
of the NOTICE file are for informational purposes only and
|
117
|
+
do not modify the License. You may add Your own attribution
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
120
|
+
that such additional attribution notices cannot be construed
|
121
|
+
as modifying the License.
|
122
|
+
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
124
|
+
may provide additional or different license terms and conditions
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
128
|
+
the conditions stated in this License.
|
129
|
+
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
133
|
+
this License, without any additional terms or conditions.
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135
|
+
the terms of any separate license agreement you may have executed
|
136
|
+
with Licensor regarding such Contributions.
|
137
|
+
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
140
|
+
except as required for reasonable and customary use in describing the
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
142
|
+
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
152
|
+
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
158
|
+
incidental, or consequential damages of any character arising as a
|
159
|
+
result of this License or out of the use or inability to use the
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
162
|
+
other commercial damages or losses), even if such Contributor
|
163
|
+
has been advised of the possibility of such damages.
|
164
|
+
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168
|
+
or other liability obligations and/or rights consistent with this
|
169
|
+
License. However, in accepting such obligations, You may act only
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
174
|
+
of your accepting any such warranty or additional liability.
|
175
|
+
|
176
|
+
END OF TERMS AND CONDITIONS
|
177
|
+
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
179
|
+
|
180
|
+
To apply the Apache License to your work, attach the following
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182
|
+
replaced with your own identifying information. (Don't include
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
184
|
+
comment syntax for the file format. We also recommend that a
|
185
|
+
file or class name and description of purpose be included on the
|
186
|
+
same "printed page" as the copyright notice for easier
|
187
|
+
identification within third-party archives.
|
188
|
+
|
189
|
+
Copyright 2021 Chuma Takahiro
|
190
|
+
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192
|
+
you may not use this file except in compliance with the License.
|
193
|
+
You may obtain a copy of the License at
|
194
|
+
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
196
|
+
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200
|
+
See the License for the specific language governing permissions and
|
201
|
+
limitations under the License.
|
data/exe/alain
ADDED
@@ -0,0 +1,46 @@
|
|
1
|
+
#!/usr/bin/env ruby
|
2
|
+
|
3
|
+
require 'optparse'
|
4
|
+
require 'open3'
|
5
|
+
require 'alain'
|
6
|
+
|
7
|
+
class AlainCmd
|
8
|
+
def self.generate(args, params)
|
9
|
+
if check_git || params[:force_overwrite]
|
10
|
+
Alain::Driver.new(args[0]).generate(params[:update_server])
|
11
|
+
else
|
12
|
+
exit 1
|
13
|
+
end
|
14
|
+
end
|
15
|
+
|
16
|
+
def self.check_git
|
17
|
+
begin
|
18
|
+
_, _, s = Open3.capture3('git status -s')
|
19
|
+
rescue
|
20
|
+
end
|
21
|
+
unless s == 0
|
22
|
+
puts "Requires git repository. If your sure, you can use '--force' option"
|
23
|
+
puts 'Exit'
|
24
|
+
return false
|
25
|
+
end
|
26
|
+
|
27
|
+
o, _, _ = Open3.capture3('git status -s | wc -l')
|
28
|
+
unless o.to_i == 0
|
29
|
+
puts "Commit working diffs before running. If your sure, you can use '--force' option."
|
30
|
+
puts 'Exit'
|
31
|
+
return false
|
32
|
+
end
|
33
|
+
true
|
34
|
+
end
|
35
|
+
end
|
36
|
+
|
37
|
+
#cmd = ARGV.shift
|
38
|
+
params = {}
|
39
|
+
|
40
|
+
OptionParser.new do |opt|
|
41
|
+
opt.banner = 'Usage: alain [options] proto_file'
|
42
|
+
opt.on('--force', 'force generate files') { |_v| params[:force_overwrite] = true }
|
43
|
+
opt.on('--update-server', 'Overwrite main.rs/lib.rs with reference server') { |_v| params[:update_server] = true }
|
44
|
+
args = opt.parse!(ARGV)
|
45
|
+
AlainCmd.generate(args, params)
|
46
|
+
end
|
data/lib/alain/cargo.rb
ADDED
@@ -0,0 +1,71 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'tomlrb'
|
4
|
+
|
5
|
+
module Alain #:nodoc:
|
6
|
+
attr_reader :cargo
|
7
|
+
class Cargo
|
8
|
+
def initialize(dir = '.')
|
9
|
+
toml = Pathname(dir) / 'Cargo.toml'
|
10
|
+
unless File.exist? toml
|
11
|
+
puts "./Cargo.toml not found. 'cargo new' first."
|
12
|
+
exit 1
|
13
|
+
end
|
14
|
+
@cargo = Tomlrb.load_file toml
|
15
|
+
end
|
16
|
+
|
17
|
+
def add_dependencies
|
18
|
+
toml = Pathname('.') / 'Cargo.toml'
|
19
|
+
origin = File.read toml
|
20
|
+
File.open(toml, 'w') do |f|
|
21
|
+
origin.each_line do |line|
|
22
|
+
if /^\[dependencies\]/.match(line)
|
23
|
+
f.puts line
|
24
|
+
dependencies.each do |k, entry|
|
25
|
+
next if @cargo['dependencies'].keys.include? k
|
26
|
+
f.puts entry
|
27
|
+
end
|
28
|
+
elsif /^\[build-dependencies\]/.match(line)
|
29
|
+
f.puts line
|
30
|
+
build_dependencies.each do |k, entry|
|
31
|
+
next if @cargo['build-dependencies'].keys.include? k
|
32
|
+
f.puts entry
|
33
|
+
end
|
34
|
+
else
|
35
|
+
f.puts line
|
36
|
+
end
|
37
|
+
end
|
38
|
+
unless @cargo['build-dependencies']
|
39
|
+
f.puts '[build-dependencies]'
|
40
|
+
f.puts build_dependencies.values.join("\n")
|
41
|
+
end
|
42
|
+
end
|
43
|
+
end
|
44
|
+
|
45
|
+
def crate_name
|
46
|
+
@cargo.dig('package', 'name').gsub(/-/, '_')
|
47
|
+
end
|
48
|
+
|
49
|
+
private
|
50
|
+
|
51
|
+
def dependencies
|
52
|
+
{
|
53
|
+
'once_cell' => %(once_cell = "1.5"),
|
54
|
+
'prost' => %(prost = "0.7"),
|
55
|
+
'prost-types' => %(prost-types = "0.7"),
|
56
|
+
'signal-hook' => %(signal-hook = "0.3.9"),
|
57
|
+
'signal-hook-tokio' => %(signal-hook-tokio = { version = "0.3.0", features = ["futures-v0_3"] }),
|
58
|
+
'tokio' => %(tokio = { version = "1.0", features = ["full"] }),
|
59
|
+
'tokio-stream' => %(tokio-stream = "0.1.2"),
|
60
|
+
'tonic' => %(tonic = "0.4.0"),
|
61
|
+
'triggered' => %(triggered = "0.1.1")
|
62
|
+
}
|
63
|
+
end
|
64
|
+
|
65
|
+
def build_dependencies
|
66
|
+
{
|
67
|
+
'tonic-build' => %(tonic-build = { version = "0.4", features = ["prost"] }),
|
68
|
+
}
|
69
|
+
end
|
70
|
+
end
|
71
|
+
end
|
data/lib/alain/driver.rb
ADDED
@@ -0,0 +1,109 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'erb'
|
4
|
+
require 'fileutils'
|
5
|
+
|
6
|
+
module Alain #:nodoc:
|
7
|
+
class Driver
|
8
|
+
include Util
|
9
|
+
attr_reader :cargo, :proto
|
10
|
+
TMPL_DIR = Pathname(__dir__) / 'templates'
|
11
|
+
|
12
|
+
def initialize(proto_file)
|
13
|
+
@proto = Proto.parse(proto_file)
|
14
|
+
@cargo = Cargo.new
|
15
|
+
@package = @proto.package # required by namespace()
|
16
|
+
@svc_code = SvcCode.new proto.service_name(:snake)
|
17
|
+
end
|
18
|
+
|
19
|
+
def generate(update_server = false)
|
20
|
+
if @svc_code.exist?
|
21
|
+
puts 'Already exists service definition. Only update methods...'
|
22
|
+
update_svc
|
23
|
+
else
|
24
|
+
update_server = true
|
25
|
+
puts 'No service definition yet...'
|
26
|
+
puts 'Generate service definition'
|
27
|
+
parse_svc
|
28
|
+
end
|
29
|
+
if update_server
|
30
|
+
puts 'Overwrite main.rs'
|
31
|
+
parse_erb 'main.rs'
|
32
|
+
puts 'Overwrite lib.rs'
|
33
|
+
parse_erb 'lib.rs'
|
34
|
+
puts 'Generate build.rs'
|
35
|
+
parse_erb 'build.rs', '', '.'
|
36
|
+
puts 'Generate tests/common/mod.rs'
|
37
|
+
FileUtils.mkdir_p 'tests/common/'
|
38
|
+
parse_erb 'mod.rs', '', 'tests/common'
|
39
|
+
puts 'Generate tests/integration_test.rs'
|
40
|
+
parse_erb 'integration_test.rs', '', 'tests'
|
41
|
+
puts 'Update Cargo.toml'
|
42
|
+
cargo.add_dependencies
|
43
|
+
end
|
44
|
+
puts 'Done'
|
45
|
+
end
|
46
|
+
|
47
|
+
private
|
48
|
+
|
49
|
+
# patch unimplemented messages/methods
|
50
|
+
# WARNING: This skips messages in a newly imported package.
|
51
|
+
#
|
52
|
+
def update_svc
|
53
|
+
origin = File.read @svc_code.path
|
54
|
+
messages = message_diff
|
55
|
+
methods = method_diff
|
56
|
+
File.open(@svc_code.path, 'w') do |f|
|
57
|
+
origin.each_line do |line|
|
58
|
+
if m = /^\s*use crate::([A-Za-z0-9_:]+)::{/.match(line)
|
59
|
+
f.puts line
|
60
|
+
f.puts ' ' + messages[namespace(m[1])].join(", ") + ',' unless messages[namespace(m[1])].empty?
|
61
|
+
elsif m = /^impl #{proto.service_name}/.match(line)
|
62
|
+
f.puts line
|
63
|
+
f.puts methods if methods
|
64
|
+
else
|
65
|
+
f.puts line
|
66
|
+
end
|
67
|
+
end
|
68
|
+
end
|
69
|
+
end
|
70
|
+
|
71
|
+
# returns unimplemented messages
|
72
|
+
#
|
73
|
+
def message_diff
|
74
|
+
package_ns, other_ns = proto.parse_import
|
75
|
+
{}.tap do |res|
|
76
|
+
res[namespace] = package_ns.reject { |item| @svc_code.messages[namespace]&.include? item }
|
77
|
+
other_ns.each do |ns, messages|
|
78
|
+
res[namespace(ns)] = messages.reject { |item| @svc_code.messages[namespace(ns)]&.include? item }
|
79
|
+
end
|
80
|
+
end
|
81
|
+
end
|
82
|
+
|
83
|
+
# returns unimplemented methods
|
84
|
+
#
|
85
|
+
def method_diff
|
86
|
+
[].tap do |res|
|
87
|
+
proto.service.each do |svc, methods|
|
88
|
+
methods.each do |method|
|
89
|
+
next if method[:method].nil?
|
90
|
+
next if @svc_code.methods.include? snake_case(method[:method])
|
91
|
+
|
92
|
+
res << ''
|
93
|
+
res << ' ' + grpc_method(method[:method], method[:request], method[:response]).gsub(/^}/, ' }')
|
94
|
+
end
|
95
|
+
end
|
96
|
+
return nil if res.empty?
|
97
|
+
end.join("\n")
|
98
|
+
end
|
99
|
+
|
100
|
+
def parse_svc
|
101
|
+
parse_erb 'service.rs', "#{proto.service_name(:snake)}_"
|
102
|
+
end
|
103
|
+
|
104
|
+
def parse_erb(file_name, file_prefix = '', target_dir = 'src')
|
105
|
+
erb = ERB.new(File.read(TMPL_DIR / "#{file_name}.erb"), trim_mode: '-')
|
106
|
+
File.write(Pathname(target_dir) / "#{file_prefix}#{file_name}", erb.result(binding))
|
107
|
+
end
|
108
|
+
end
|
109
|
+
end
|
data/lib/alain/proto.rb
ADDED
@@ -0,0 +1,143 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'erb'
|
4
|
+
|
5
|
+
module Alain #:nodoc:
|
6
|
+
class Proto
|
7
|
+
include Util
|
8
|
+
attr_reader :package, :service
|
9
|
+
INDENT = ' ' * 4
|
10
|
+
|
11
|
+
def initialize(service, package, proto_path)
|
12
|
+
unless File.exist? proto_path
|
13
|
+
puts "#{proto_path} not found. Exit"
|
14
|
+
exit 1
|
15
|
+
end
|
16
|
+
@path = proto_path
|
17
|
+
@service = service
|
18
|
+
@package = package
|
19
|
+
end
|
20
|
+
|
21
|
+
def svc_methods
|
22
|
+
[].tap do |res|
|
23
|
+
@service.each do |svc, methods|
|
24
|
+
res << "pub struct #{svc}Service {}"
|
25
|
+
res << ''
|
26
|
+
res << '#[tonic::async_trait]'
|
27
|
+
res << "impl #{svc} for #{svc}Service {"
|
28
|
+
res << ''
|
29
|
+
methods.each do |method|
|
30
|
+
next if method[:method].nil?
|
31
|
+
|
32
|
+
res << INDENT + grpc_method(method[:method], method[:request], method[:response])
|
33
|
+
end
|
34
|
+
res << "}"
|
35
|
+
end
|
36
|
+
end.join("\n")
|
37
|
+
end
|
38
|
+
|
39
|
+
def compile_protos
|
40
|
+
<<~EOS
|
41
|
+
tonic_build::compile_protos("#{@path}")?;
|
42
|
+
EOS
|
43
|
+
end
|
44
|
+
|
45
|
+
# Tonic import macro
|
46
|
+
#
|
47
|
+
def mod_def
|
48
|
+
_, other_ns = parse_import
|
49
|
+
namespaces = [@package].concat other_ns.keys
|
50
|
+
[].tap do |res|
|
51
|
+
namespaces.each do |namespace|
|
52
|
+
ns = namespace.split('.')
|
53
|
+
res << ns.map.with_index do |n, i|
|
54
|
+
INDENT * i + "pub mod #{n} {"
|
55
|
+
end
|
56
|
+
res << INDENT * ns.length + %%tonic::include_proto!("#{@package}");%
|
57
|
+
res << ns.map.with_index do |n, i|
|
58
|
+
INDENT * (ns.length - i - 1) + '}'
|
59
|
+
end
|
60
|
+
end
|
61
|
+
end.join("\n")
|
62
|
+
end
|
63
|
+
|
64
|
+
# use definition for shorthand
|
65
|
+
#
|
66
|
+
def use_def(crate = 'crate')
|
67
|
+
package_ns, other_ns = parse_import
|
68
|
+
[].tap do |res|
|
69
|
+
res << "use #{crate}::#{namespace}::{"
|
70
|
+
package_ns.uniq.each { |message| res << "#{INDENT}#{message}," }
|
71
|
+
res << '};'
|
72
|
+
res << ''
|
73
|
+
other_ns.each do |ns, messages|
|
74
|
+
res << "use crate::#{ns.gsub('.', '::')}::{"
|
75
|
+
messages.uniq.each { |message| res << "#{INDENT}#{message}," }
|
76
|
+
res << '};'
|
77
|
+
end
|
78
|
+
end.join("\n")
|
79
|
+
end
|
80
|
+
|
81
|
+
def self.parse(proto_path)
|
82
|
+
package = nil
|
83
|
+
service = {}
|
84
|
+
current_svc = nil
|
85
|
+
File.foreach(proto_path) do |line|
|
86
|
+
case line
|
87
|
+
when /^\s*package\s+(\S+)\s*;/
|
88
|
+
package = $1
|
89
|
+
when /^\s*service\s+(\S+)\s*{/
|
90
|
+
current_svc = $1
|
91
|
+
service[current_svc] ||= []
|
92
|
+
when /^\s*rpc\s+(\S+)\s*\((\S+)\)\s+returns\s+\((\S+)\)\s*{/
|
93
|
+
service[current_svc] << {
|
94
|
+
method: $1,
|
95
|
+
request: $2,
|
96
|
+
response: $3
|
97
|
+
}
|
98
|
+
when /^\s*message\s+(\S+)\s*{/
|
99
|
+
# Filling nested messages
|
100
|
+
service[current_svc] << {
|
101
|
+
request: $1,
|
102
|
+
method: nil, response: nil
|
103
|
+
}
|
104
|
+
end
|
105
|
+
end
|
106
|
+
new(service, package, proto_path)
|
107
|
+
end
|
108
|
+
|
109
|
+
def service_name(mode = :camel)
|
110
|
+
case mode
|
111
|
+
when :snake
|
112
|
+
snake_case @service.keys.first
|
113
|
+
else
|
114
|
+
@service.keys.first
|
115
|
+
end
|
116
|
+
end
|
117
|
+
|
118
|
+
def server_mod
|
119
|
+
"#{namespace}::#{service_name :snake}_server::#{service_name}Server"
|
120
|
+
end
|
121
|
+
|
122
|
+
def parse_import
|
123
|
+
package_ns = ["#{service_name(:snake)}_server::#{service_name}"]
|
124
|
+
other_ns = {}
|
125
|
+
@service.each do |svc, methods|
|
126
|
+
methods.each do |method|
|
127
|
+
[:request, :response].each do |message_type|
|
128
|
+
next if method[message_type].nil?
|
129
|
+
|
130
|
+
case method[message_type]
|
131
|
+
when /^(.+)\.(\S+?)$/
|
132
|
+
other_ns[$1] ||= []
|
133
|
+
other_ns[$1] << $2
|
134
|
+
else
|
135
|
+
package_ns << method[message_type]
|
136
|
+
end
|
137
|
+
end
|
138
|
+
end
|
139
|
+
end
|
140
|
+
[package_ns.uniq, other_ns]
|
141
|
+
end
|
142
|
+
end
|
143
|
+
end
|
@@ -0,0 +1,61 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'erb'
|
4
|
+
|
5
|
+
module Alain #:nodoc:
|
6
|
+
# parse generated service code
|
7
|
+
#
|
8
|
+
class SvcCode
|
9
|
+
include Util
|
10
|
+
attr_reader :messages, :methods, :path
|
11
|
+
|
12
|
+
def initialize svc_name
|
13
|
+
@path = Pathname('src') / "#{svc_name}_service.rs"
|
14
|
+
@messages = message_scan
|
15
|
+
@methods = method_scan
|
16
|
+
end
|
17
|
+
|
18
|
+
def exist?
|
19
|
+
File.exist? @path
|
20
|
+
end
|
21
|
+
|
22
|
+
private
|
23
|
+
|
24
|
+
# already implemented messages by service
|
25
|
+
#
|
26
|
+
def message_scan
|
27
|
+
return [] unless exist?
|
28
|
+
|
29
|
+
res = {}
|
30
|
+
key = nil
|
31
|
+
msg_blk= false
|
32
|
+
File.foreach @path do |line|
|
33
|
+
if m = /^\s*use crate::([A-Za-z0-9_:]+)::{/.match(line)
|
34
|
+
key = m[1]
|
35
|
+
msg_blk = true
|
36
|
+
elsif msg_blk && /^\s*};/.match(line)
|
37
|
+
msg_blk = false
|
38
|
+
elsif msg_blk
|
39
|
+
messages = line.split(',').map(&:strip).reject(&:empty?)
|
40
|
+
res[key] ||= []
|
41
|
+
res[key].concat messages
|
42
|
+
end
|
43
|
+
end
|
44
|
+
res
|
45
|
+
end
|
46
|
+
|
47
|
+
# already implemented methods
|
48
|
+
#
|
49
|
+
def method_scan
|
50
|
+
return [] unless exist?
|
51
|
+
|
52
|
+
[].tap do |res|
|
53
|
+
File.foreach @path do |line|
|
54
|
+
if m = /async fn ([A-Za-z0-9_]+)\s*\(/.match(line)
|
55
|
+
res << m[1]
|
56
|
+
end
|
57
|
+
end
|
58
|
+
end
|
59
|
+
end
|
60
|
+
end
|
61
|
+
end
|
@@ -0,0 +1,18 @@
|
|
1
|
+
mod common;
|
2
|
+
use common::setup;
|
3
|
+
use triggered::trigger;
|
4
|
+
|
5
|
+
<%= proto.use_def(cargo.crate_name) %>
|
6
|
+
|
7
|
+
#[tokio::test]
|
8
|
+
async fn it_returns_ok_response() {
|
9
|
+
let (shutdown_trigger, shutdown_signal) = trigger();
|
10
|
+
let (jh, channel) = setup(shutdown_signal).await.unwrap();
|
11
|
+
|
12
|
+
let mut client = <%= proto.service_name %>Client::new(channel);
|
13
|
+
// TODO: implement gRPC client request
|
14
|
+
assert!(true);
|
15
|
+
|
16
|
+
shutdown_trigger.trigger();
|
17
|
+
jh.await.unwrap();
|
18
|
+
}
|
@@ -0,0 +1,40 @@
|
|
1
|
+
use signal_hook::consts::signal::*;
|
2
|
+
use signal_hook_tokio::Signals;
|
3
|
+
use std::net::SocketAddr;
|
4
|
+
use tokio_stream::StreamExt;
|
5
|
+
use triggered::Listener;
|
6
|
+
use tonic::transport::{Server, server::Router};
|
7
|
+
|
8
|
+
<%= proto.mod_def %>
|
9
|
+
|
10
|
+
use <%= proto.server_mod %>;
|
11
|
+
|
12
|
+
mod <%= proto.service_name :snake %>_service;
|
13
|
+
use self::<%= proto.service_name :snake %>_service::<%= proto.service_name %>Service;
|
14
|
+
|
15
|
+
pub async fn start_server(addr: SocketAddr, signal: Listener) -> Result<(), Box<dyn std::error::Error>> {
|
16
|
+
println!("ready");
|
17
|
+
create_router().await
|
18
|
+
.serve_with_shutdown(addr, signal).await.unwrap();
|
19
|
+
|
20
|
+
Ok(())
|
21
|
+
}
|
22
|
+
|
23
|
+
pub async fn create_router() -> Router<<%= proto.service_name %>Server<<%= proto.service_name %>Service>, tonic::transport::server::Unimplemented> {
|
24
|
+
let server = <%= proto.service_name %>Service{};
|
25
|
+
Server::builder()
|
26
|
+
.add_service(<%= proto.service_name %>Server::new(server))
|
27
|
+
}
|
28
|
+
|
29
|
+
pub async fn handle_signals(signals: Signals, trigger: triggered::Trigger) {
|
30
|
+
let mut signals = signals.fuse();
|
31
|
+
while let Some(signal) = signals.next().await {
|
32
|
+
match signal {
|
33
|
+
SIGTERM => {
|
34
|
+
println!("SIGTERM caught: going to shutdown");
|
35
|
+
trigger.trigger();
|
36
|
+
},
|
37
|
+
_ => unreachable!(),
|
38
|
+
}
|
39
|
+
}
|
40
|
+
}
|
@@ -0,0 +1,22 @@
|
|
1
|
+
use once_cell::sync::Lazy;
|
2
|
+
use signal_hook::consts::signal::*;
|
3
|
+
use signal_hook_tokio::Signals;
|
4
|
+
use <%= cargo.crate_name %>::{start_server, handle_signals};
|
5
|
+
|
6
|
+
pub static SERVER_BIND: Lazy<std::net::SocketAddr> = Lazy::new(|| {
|
7
|
+
format!("{}:{}", "0.0.0.0", 50051)
|
8
|
+
.parse().unwrap()
|
9
|
+
});
|
10
|
+
|
11
|
+
#[tokio::main]
|
12
|
+
pub async fn main() {
|
13
|
+
let signals = Signals::new(&[SIGTERM]).unwrap();
|
14
|
+
let handle = signals.handle();
|
15
|
+
let (shutdown_trigger, shutdown_signal) = triggered::trigger();
|
16
|
+
|
17
|
+
let signals_task = tokio::spawn(handle_signals(signals, shutdown_trigger));
|
18
|
+
|
19
|
+
start_server(*SERVER_BIND, shutdown_signal).await.unwrap();
|
20
|
+
handle.close();
|
21
|
+
signals_task.await.unwrap();
|
22
|
+
}
|
@@ -0,0 +1,25 @@
|
|
1
|
+
#![allow(dead_code)]
|
2
|
+
use std::time::Duration;
|
3
|
+
use tokio::task::JoinHandle;
|
4
|
+
use tonic::{transport::Channel, Status};
|
5
|
+
use <%= cargo.crate_name %>::create_router;
|
6
|
+
|
7
|
+
pub async fn setup(signal: triggered::Listener) -> Result<(JoinHandle<()>, Channel), Box<dyn std::error::Error>> {
|
8
|
+
let srv: JoinHandle<()> = tokio::spawn(async move {
|
9
|
+
// Launch gRPC server
|
10
|
+
create_router().await
|
11
|
+
.serve_with_shutdown("127.0.0.1:50051".parse().unwrap(), signal)
|
12
|
+
.await.unwrap()
|
13
|
+
});
|
14
|
+
|
15
|
+
tokio::time::sleep(Duration::from_millis(100)).await;
|
16
|
+
|
17
|
+
// Create channel for gRPC client
|
18
|
+
let channel = Channel::from_static("http://127.0.0.1:50051")
|
19
|
+
.timeout(Duration::from_secs(30))
|
20
|
+
.concurrency_limit(20)
|
21
|
+
.connect_lazy()
|
22
|
+
.or_else(|_e| Err(Status::cancelled("client connection error")))?;
|
23
|
+
|
24
|
+
Ok((srv, channel))
|
25
|
+
}
|
data/lib/alain/util.rb
ADDED
@@ -0,0 +1,25 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module Alain #:nodoc:
|
4
|
+
module Util
|
5
|
+
module_function
|
6
|
+
|
7
|
+
def grpc_method method, request, response
|
8
|
+
<<~EOS
|
9
|
+
async fn #{snake_case(method)}(&self, request: Request<#{namespace(request)}>) -> Result<Response<#{namespace(response)}>, Status> {
|
10
|
+
let message: #{namespace(request)} = request.into_inner();
|
11
|
+
Ok(Response::new(#{namespace(response)} { }))
|
12
|
+
}
|
13
|
+
EOS
|
14
|
+
end
|
15
|
+
|
16
|
+
def namespace(ns = @package)
|
17
|
+
ns.gsub('.', '::')
|
18
|
+
end
|
19
|
+
|
20
|
+
def snake_case(str)
|
21
|
+
str.gsub(/([a-z\d])([A-Z])/, '\1_\2')
|
22
|
+
.downcase
|
23
|
+
end
|
24
|
+
end
|
25
|
+
end
|
data/lib/alain.rb
ADDED
@@ -0,0 +1,11 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "alain/version"
|
4
|
+
|
5
|
+
module Alain
|
6
|
+
autoload :Driver, 'alain/driver'
|
7
|
+
autoload :Cargo, 'alain/cargo'
|
8
|
+
autoload :Proto, 'alain/proto'
|
9
|
+
autoload :SvcCode, 'alain/svc_code'
|
10
|
+
autoload :Util, 'alain/util'
|
11
|
+
end
|
metadata
ADDED
@@ -0,0 +1,75 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: alain
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.4.0
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- Chuma Takahiro
|
8
|
+
autorequire:
|
9
|
+
bindir: exe
|
10
|
+
cert_chain: []
|
11
|
+
date: 2021-09-10 00:00:00.000000000 Z
|
12
|
+
dependencies:
|
13
|
+
- !ruby/object:Gem::Dependency
|
14
|
+
name: tomlrb
|
15
|
+
requirement: !ruby/object:Gem::Requirement
|
16
|
+
requirements:
|
17
|
+
- - "~>"
|
18
|
+
- !ruby/object:Gem::Version
|
19
|
+
version: '2.0'
|
20
|
+
type: :runtime
|
21
|
+
prerelease: false
|
22
|
+
version_requirements: !ruby/object:Gem::Requirement
|
23
|
+
requirements:
|
24
|
+
- - "~>"
|
25
|
+
- !ruby/object:Gem::Version
|
26
|
+
version: '2.0'
|
27
|
+
description: Code generator for rust prost
|
28
|
+
email:
|
29
|
+
- co.chuma@gmail.com
|
30
|
+
executables:
|
31
|
+
- alain
|
32
|
+
extensions: []
|
33
|
+
extra_rdoc_files: []
|
34
|
+
files:
|
35
|
+
- LICENSE
|
36
|
+
- exe/alain
|
37
|
+
- lib/alain.rb
|
38
|
+
- lib/alain/cargo.rb
|
39
|
+
- lib/alain/driver.rb
|
40
|
+
- lib/alain/proto.rb
|
41
|
+
- lib/alain/svc_code.rb
|
42
|
+
- lib/alain/templates/build.rs.erb
|
43
|
+
- lib/alain/templates/integration_test.rs.erb
|
44
|
+
- lib/alain/templates/lib.rs.erb
|
45
|
+
- lib/alain/templates/main.rs.erb
|
46
|
+
- lib/alain/templates/mod.rs.erb
|
47
|
+
- lib/alain/templates/service.rs.erb
|
48
|
+
- lib/alain/util.rb
|
49
|
+
- lib/alain/version.rb
|
50
|
+
homepage: https://github.com/chumaltd/alain
|
51
|
+
licenses: []
|
52
|
+
metadata:
|
53
|
+
homepage_uri: https://github.com/chumaltd/alain
|
54
|
+
source_code_uri: https://github.com/chumaltd/alain
|
55
|
+
changelog_uri: https://github.com/chumaltd/alain/blob/main/CHANGELOG.md
|
56
|
+
post_install_message:
|
57
|
+
rdoc_options: []
|
58
|
+
require_paths:
|
59
|
+
- lib
|
60
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
61
|
+
requirements:
|
62
|
+
- - ">="
|
63
|
+
- !ruby/object:Gem::Version
|
64
|
+
version: 2.7.0
|
65
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
66
|
+
requirements:
|
67
|
+
- - ">="
|
68
|
+
- !ruby/object:Gem::Version
|
69
|
+
version: '0'
|
70
|
+
requirements: []
|
71
|
+
rubygems_version: 3.2.21
|
72
|
+
signing_key:
|
73
|
+
specification_version: 4
|
74
|
+
summary: Code generator for rust prost
|
75
|
+
test_files: []
|