tonic-rails 0.2.0-aarch64-linux-gnu → 0.4.0-aarch64-linux-gnu
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +44 -1
- data/README.md +145 -2
- data/lib/generators/tonic_rails/install/install_generator.rb +45 -0
- data/lib/generators/tonic_rails/install/templates/tonic_rails.rb.tt +21 -0
- data/lib/generators/tonic_rails/service/service_generator.rb +110 -0
- data/lib/generators/tonic_rails/service/templates/handler.rb.tt +38 -0
- data/lib/generators/tonic_rails/service/templates/service.proto.tt +16 -0
- data/lib/generators/tonic_rails/service/templates/service_spec.rb.tt +17 -0
- data/lib/generators/tonic_rails/service/templates/service_test.rb.tt +14 -0
- data/lib/tonic/rails/3.3/tonic_rails_native.so +0 -0
- data/lib/tonic/rails/3.4/tonic_rails_native.so +0 -0
- data/lib/tonic/rails/4.0/tonic_rails_native.so +0 -0
- data/lib/tonic/rails/base.rb +104 -5
- data/lib/tonic/rails/configuration.rb +58 -3
- data/lib/tonic/rails/health.rb +105 -0
- data/lib/tonic/rails/peer.rb +60 -0
- data/lib/tonic/rails/router.rb +1 -0
- data/lib/tonic/rails/server.rb +50 -5
- data/lib/tonic/rails/tasks/tonic-rails.rake +13 -1
- data/lib/tonic/rails/testing/errors.rb +47 -0
- data/lib/tonic/rails/testing/minitest.rb +44 -0
- data/lib/tonic/rails/testing/rspec.rb +53 -0
- data/lib/tonic/rails/testing.rb +5 -3
- data/lib/tonic/rails/version.rb +1 -1
- data/lib/tonic-rails.rb +2 -0
- metadata +13 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 91be536ad3a1e8c1ca97da57820ed90a10a7655acc8ac4f8fc3f08cdf0458632
|
|
4
|
+
data.tar.gz: b77391b48dd895a85efcbd483ef73600afbb545424f9b497b8ea37f3a1041911
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 3ad30d527ac745b30d80ef763ef119b37c6b9951f85ae8f3f1ec56b2ee0a0dd262868d950dbfe415487f9ac7d69f0c95009a8b9f1f4e63f519958ace65c60be4
|
|
7
|
+
data.tar.gz: c3f0fadfc968526d91ec3382c08837e367fcc0a6c1ba519176492fef3c2c84f6a661a824910a7df79892c742c3686702dc51ca934370c7e6581ebb472a1a5991
|
data/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,47 @@ minor versions may contain breaking changes.
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.4.0] - 2026-10-11
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- gRPC-Web: `config.grpc_web = true` serves browser clients (unary and
|
|
15
|
+
server-streaming RPCs, binary and text encodings) without a proxy, on the
|
|
16
|
+
same port as native gRPC, with CORS via `grpc_web_origins`,
|
|
17
|
+
`grpc_web_allowed_headers` and `grpc_web_exposed_headers`. Closes #22.
|
|
18
|
+
|
|
19
|
+
## [0.3.0] - 2026-10-11
|
|
20
|
+
|
|
21
|
+
### Added
|
|
22
|
+
|
|
23
|
+
- Generators: `rails g tonic_rails:install` (initializer, proto and
|
|
24
|
+
generated-code directories, Puma plugin) and `rails g tonic_rails:service
|
|
25
|
+
Item GetItem ListItems:server` (proto, handler with a stub per RPC,
|
|
26
|
+
registration, and an RSpec or Minitest test).
|
|
27
|
+
- Controller-style callbacks for handlers: `before_rpc`, `after_rpc` and
|
|
28
|
+
`around_rpc` with `only:` / `except:`, plus `current_rpc` and `request`
|
|
29
|
+
accessors.
|
|
30
|
+
- `rescue_from` (ActiveSupport::Rescuable) with a `code:` shorthand that maps
|
|
31
|
+
an exception class to a gRPC status.
|
|
32
|
+
- `peer` in handlers: the client's address and, with mutual TLS, its
|
|
33
|
+
certificate (`peer.certificate`, an `OpenSSL::X509::Certificate`).
|
|
34
|
+
`Testing.call`/`invoke` accept `peer:`.
|
|
35
|
+
- App-controlled health: `config.health_check` (polled every
|
|
36
|
+
`health_check_interval` seconds inside the Rails executor) and
|
|
37
|
+
`Tonic::Rails.server.serving!` / `not_serving!` for the whole server or
|
|
38
|
+
individual services, so readiness probes reflect real dependency health.
|
|
39
|
+
- Test helpers: the `raise_grpc_error(code).with_message(...)` RSpec matcher
|
|
40
|
+
(`require "tonic/rails/testing/rspec"`) and `assert_grpc_error` for Minitest
|
|
41
|
+
(`Tonic::Rails::Testing::Assertions`). Both accept `Tonic::Rails::RpcError`
|
|
42
|
+
and the grpc gem's `GRPC::BadStatus`.
|
|
43
|
+
|
|
44
|
+
### Changed
|
|
45
|
+
|
|
46
|
+
- `tonic_rails:compile_protos` requires protoc 22 or newer and says so,
|
|
47
|
+
instead of generating code google-protobuf 4 can't load (older protoc,
|
|
48
|
+
such as Ubuntu's 3.21 package, emits a Ruby DSL that google-protobuf 4
|
|
49
|
+
removed).
|
|
50
|
+
|
|
10
51
|
## [0.2.0] - 2026-10-11
|
|
11
52
|
|
|
12
53
|
### Added
|
|
@@ -84,6 +125,8 @@ First public release.
|
|
|
84
125
|
- Precompiled native gems for Linux (x86_64, aarch64; glibc and musl) and
|
|
85
126
|
macOS (x86_64, arm64), Ruby 3.3 to 4.0.
|
|
86
127
|
|
|
87
|
-
[Unreleased]: https://github.com/CodingAnarchy/tonic-rails/compare/v0.
|
|
128
|
+
[Unreleased]: https://github.com/CodingAnarchy/tonic-rails/compare/v0.4.0...HEAD
|
|
129
|
+
[0.4.0]: https://github.com/CodingAnarchy/tonic-rails/compare/v0.3.0...v0.4.0
|
|
130
|
+
[0.3.0]: https://github.com/CodingAnarchy/tonic-rails/compare/v0.2.0...v0.3.0
|
|
88
131
|
[0.2.0]: https://github.com/CodingAnarchy/tonic-rails/compare/v0.1.0...v0.2.0
|
|
89
132
|
[0.1.0]: https://github.com/CodingAnarchy/tonic-rails/releases/tag/v0.1.0
|
data/README.md
CHANGED
|
@@ -60,10 +60,31 @@ On platforms without a precompiled gem, installation builds the
|
|
|
60
60
|
extension from source, which needs a [Rust toolchain](https://rustup.rs).
|
|
61
61
|
|
|
62
62
|
To generate Ruby classes from your `.proto` files you also need `protoc`
|
|
63
|
-
(the Protocol Buffers compiler) during development.
|
|
63
|
+
(the Protocol Buffers compiler) **22.0 or newer** during development.
|
|
64
|
+
Older versions, such as Ubuntu's `protobuf-compiler` package (3.21),
|
|
65
|
+
generate code that google-protobuf 4 can't load; install a current
|
|
66
|
+
release from the [protobuf releases page](https://github.com/protocolbuffers/protobuf/releases)
|
|
67
|
+
or Homebrew.
|
|
64
68
|
|
|
65
69
|
## Quick start
|
|
66
70
|
|
|
71
|
+
The generators set everything up:
|
|
72
|
+
|
|
73
|
+
```sh
|
|
74
|
+
bin/rails generate tonic_rails:install
|
|
75
|
+
bin/rails generate tonic_rails:service Item GetItem ListItems:server
|
|
76
|
+
bin/rails tonic_rails:compile_protos
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
`install` adds `config/initializers/tonic_rails.rb` (load path for
|
|
80
|
+
generated code, configuration, handler registration), `app/protos/`,
|
|
81
|
+
`lib/grpc/`, and the Puma plugin. `service` writes the `.proto`, a handler
|
|
82
|
+
in `app/grpc/` with a stub per RPC, its registration, and a spec (or
|
|
83
|
+
Minitest test). RPCs take an optional `:server`, `:client` or `:bidi`
|
|
84
|
+
streaming kind.
|
|
85
|
+
|
|
86
|
+
The rest of this section shows the same steps by hand.
|
|
87
|
+
|
|
67
88
|
### 1. Define the service
|
|
68
89
|
|
|
69
90
|
```protobuf
|
|
@@ -236,11 +257,54 @@ Any other exception becomes `INTERNAL` with the message `internal error`.
|
|
|
236
257
|
The real exception is logged and passed to `Rails.error.report`, so your
|
|
237
258
|
error tracker sees it.
|
|
238
259
|
|
|
260
|
+
### Callbacks and rescue_from
|
|
261
|
+
|
|
262
|
+
Handlers get controller-style callbacks and exception mapping:
|
|
263
|
+
|
|
264
|
+
```ruby
|
|
265
|
+
class ItemService
|
|
266
|
+
include Tonic::Rails::Base
|
|
267
|
+
rpc_service "demo.v1.ItemService"
|
|
268
|
+
|
|
269
|
+
before_rpc :authenticate, except: :ListItems
|
|
270
|
+
around_rpc :with_tenant
|
|
271
|
+
after_rpc { StatsD.increment("grpc.#{current_rpc}") }
|
|
272
|
+
|
|
273
|
+
rescue_from ActiveRecord::RecordNotFound, code: :not_found
|
|
274
|
+
rescue_from ActiveRecord::RecordInvalid, code: :invalid_argument, message: ->(e) { e.record.errors.full_messages.join(", ") }
|
|
275
|
+
rescue_from Pundit::NotAuthorizedError, with: :forbidden
|
|
276
|
+
|
|
277
|
+
private
|
|
278
|
+
|
|
279
|
+
def authenticate
|
|
280
|
+
@user = User.from_token(grpc_metadata["authorization"])
|
|
281
|
+
raise Tonic::Rails::RpcError.new("invalid token", code: :unauthenticated) unless @user
|
|
282
|
+
end
|
|
283
|
+
|
|
284
|
+
def with_tenant(&) = Tenant.switch(@user.tenant, &)
|
|
285
|
+
|
|
286
|
+
def forbidden(_e) = raise(Tonic::Rails::RpcError.new("not allowed", code: :permission_denied))
|
|
287
|
+
end
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
- `before_rpc`, `after_rpc` and `around_rpc` accept method names or a
|
|
291
|
+
block, plus `only:` / `except:` with RPC names (`:GetItem` or
|
|
292
|
+
`:get_item`). Raising in a `before_rpc` stops the call.
|
|
293
|
+
- `current_rpc` is the RPC being handled and `request` the decoded
|
|
294
|
+
request, so callbacks can inspect it.
|
|
295
|
+
- `after_rpc` runs once a streamed response has been fully sent.
|
|
296
|
+
- `rescue_from` covers the handler and its callbacks. With `code:`, the
|
|
297
|
+
exception's message is sent to the client unless you pass `message:`.
|
|
298
|
+
Handlers given with `with:` or a block must raise an `RpcError`.
|
|
299
|
+
Anything unmapped becomes `INTERNAL`, as before.
|
|
300
|
+
|
|
239
301
|
### Metadata, deadlines and shutdown
|
|
240
302
|
|
|
241
303
|
```ruby
|
|
242
304
|
def get_item(request)
|
|
243
305
|
token = grpc_metadata["authorization"] # request headers, lower-case
|
|
306
|
+
peer.ip # client address ("10.0.4.17")
|
|
307
|
+
peer.certificate&.subject # client certificate, with mutual TLS
|
|
244
308
|
deadline_ms # ms left before the client's deadline, or nil
|
|
245
309
|
deadline_exceeded? # true once it has passed
|
|
246
310
|
cancelled? # true while the server shuts down
|
|
@@ -299,6 +363,44 @@ Tonic::Rails.configure do |config|
|
|
|
299
363
|
end
|
|
300
364
|
```
|
|
301
365
|
|
|
366
|
+
## Browser clients (gRPC-Web)
|
|
367
|
+
|
|
368
|
+
Browsers can't speak native gRPC, but they can speak
|
|
369
|
+
[gRPC-Web](https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-WEB.md).
|
|
370
|
+
Turn it on and your existing handlers serve web frontends directly, with
|
|
371
|
+
no Envoy or other proxy:
|
|
372
|
+
|
|
373
|
+
```ruby
|
|
374
|
+
Tonic::Rails.configure do |config|
|
|
375
|
+
config.grpc_web = true
|
|
376
|
+
config.grpc_web_origins = ["https://app.example.com"] # CORS; omit for same-origin only
|
|
377
|
+
config.grpc_web_exposed_headers = %w[x-request-id] # response metadata browsers may read
|
|
378
|
+
end
|
|
379
|
+
```
|
|
380
|
+
|
|
381
|
+
Then call it from the browser with any gRPC-Web client, for example
|
|
382
|
+
[Connect](https://connectrpc.com/docs/web/using-clients):
|
|
383
|
+
|
|
384
|
+
```ts
|
|
385
|
+
import { createClient } from "@connectrpc/connect";
|
|
386
|
+
import { createGrpcWebTransport } from "@connectrpc/connect-web";
|
|
387
|
+
import { ItemService } from "./gen/demo/v1/items_pb";
|
|
388
|
+
|
|
389
|
+
const client = createClient(ItemService, createGrpcWebTransport({ baseUrl: "https://api.example.com" }));
|
|
390
|
+
const item = await client.getItem({ id: 1n });
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
- Unary and server-streaming RPCs work; browsers can't do client or
|
|
394
|
+
bidirectional streaming.
|
|
395
|
+
- Errors, response headers and trailers reach the browser as usual.
|
|
396
|
+
- Native gRPC clients keep working on the same port. Enabling gRPC-Web
|
|
397
|
+
also accepts HTTP/1.1, which browsers use without TLS; over HTTPS they
|
|
398
|
+
negotiate HTTP/2.
|
|
399
|
+
- `grpc_web_origins` sets CORS: listed origins may call with credentials
|
|
400
|
+
(cookies); `"*"` allows any origin without credentials (logged as a
|
|
401
|
+
warning). `grpc_web_allowed_headers` adds request headers beyond the
|
|
402
|
+
standard ones (`authorization` is already allowed).
|
|
403
|
+
|
|
302
404
|
## Testing handlers
|
|
303
405
|
|
|
304
406
|
`Tonic::Rails::Testing` calls a handler in-process, with real protobuf
|
|
@@ -322,6 +424,30 @@ result.headers["x-cache"] # => "hit"
|
|
|
322
424
|
result.trailers["x-cost-ms"] # => "3"
|
|
323
425
|
```
|
|
324
426
|
|
|
427
|
+
Matchers for gRPC statuses work with `Testing.call` and with the official
|
|
428
|
+
`grpc` client's errors:
|
|
429
|
+
|
|
430
|
+
```ruby
|
|
431
|
+
# spec/rails_helper.rb
|
|
432
|
+
require "tonic/rails/testing/rspec"
|
|
433
|
+
|
|
434
|
+
expect { Tonic::Rails::Testing.call(ItemService, :GetItem, { id: 0 }) }
|
|
435
|
+
.to raise_grpc_error(:not_found).with_message(/0/)
|
|
436
|
+
```
|
|
437
|
+
|
|
438
|
+
```ruby
|
|
439
|
+
# Minitest
|
|
440
|
+
require "tonic/rails/testing/minitest"
|
|
441
|
+
|
|
442
|
+
class ItemServiceTest < ActiveSupport::TestCase
|
|
443
|
+
include Tonic::Rails::Testing::Assertions
|
|
444
|
+
|
|
445
|
+
test "missing items" do
|
|
446
|
+
assert_grpc_error(:not_found) { Tonic::Rails::Testing.call(ItemService, :GetItem, { id: 0 }) }
|
|
447
|
+
end
|
|
448
|
+
end
|
|
449
|
+
```
|
|
450
|
+
|
|
325
451
|
## Configuration
|
|
326
452
|
|
|
327
453
|
Set options in `config/application.rb` or an environment file:
|
|
@@ -353,6 +479,11 @@ end
|
|
|
353
479
|
| `tls_client_ca_path` | `nil` | PEM CA bundle; requires client certificates (mutual TLS) |
|
|
354
480
|
| `drain_timeout` | `10` | Seconds to let in-flight calls finish on shutdown |
|
|
355
481
|
| `keepalive_interval`, `keepalive_timeout` | `15`, `5` | HTTP/2 PING interval and timeout, seconds |
|
|
482
|
+
| `grpc_web` | `false` | Serve gRPC-Web for browser clients (see [Browser clients](#browser-clients-grpc-web)) |
|
|
483
|
+
| `grpc_web_origins` | `[]` | Browser origins allowed via CORS; `"*"` for any (no credentials) |
|
|
484
|
+
| `grpc_web_allowed_headers`, `grpc_web_exposed_headers` | `[]` | Extra CORS request / response headers |
|
|
485
|
+
| `health_check` | `nil` | Callable; while false or raising, health reports `NOT_SERVING` |
|
|
486
|
+
| `health_check_interval` | `5` | Seconds between health checks |
|
|
356
487
|
| `compression` | `false` | gzip responses over 1 KiB for clients that accept it |
|
|
357
488
|
| `reflection` | `false` | Serve `grpc.reflection.v1`; exposes your schema |
|
|
358
489
|
| `interceptors` | `[]` | See [Interceptors](#interceptors) |
|
|
@@ -399,7 +530,19 @@ Don't combine it with the plugin.
|
|
|
399
530
|
- **Health checks.** `grpc.health.v1.Health` reports `SERVING` for the
|
|
400
531
|
server (`""`) and every registered service, and flips to `NOT_SERVING`
|
|
401
532
|
as soon as shutdown begins. Point your load balancer or Kubernetes
|
|
402
|
-
gRPC probes at it.
|
|
533
|
+
gRPC probes at it. To make readiness reflect your dependencies, add a
|
|
534
|
+
check that runs every `health_check_interval` seconds (default 5):
|
|
535
|
+
|
|
536
|
+
```ruby
|
|
537
|
+
config.health_check = -> { ActiveRecord::Base.connection.active? }
|
|
538
|
+
```
|
|
539
|
+
|
|
540
|
+
While it returns false or raises, the server reports `NOT_SERVING`
|
|
541
|
+
(calls are still served). You can also mark the server or a service
|
|
542
|
+
yourself, for example during maintenance:
|
|
543
|
+
`Tonic::Rails.server.not_serving!("demo.v1.ItemService")` and
|
|
544
|
+
`serving!`. A service is `SERVING` only while the check passes and it
|
|
545
|
+
isn't marked otherwise.
|
|
403
546
|
- **Graceful shutdown.** On SIGTERM or SIGINT the server stops
|
|
404
547
|
accepting connections, tells clients to go away (HTTP/2 GOAWAY), lets
|
|
405
548
|
in-flight calls finish for up to `drain_timeout` seconds, then exits.
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "rails/generators"
|
|
4
|
+
|
|
5
|
+
module TonicRails
|
|
6
|
+
module Generators
|
|
7
|
+
# rails generate tonic_rails:install
|
|
8
|
+
#
|
|
9
|
+
# Sets an app up for gRPC: an initializer (load path for generated
|
|
10
|
+
# protobuf code, configuration, handler registration), the proto and
|
|
11
|
+
# generated-code directories, and the Puma plugin.
|
|
12
|
+
class InstallGenerator < ::Rails::Generators::Base
|
|
13
|
+
source_root File.expand_path("templates", __dir__)
|
|
14
|
+
|
|
15
|
+
class_option :skip_puma, type: :boolean, default: false,
|
|
16
|
+
desc: "Don't add `plugin :tonic_rails` to config/puma.rb"
|
|
17
|
+
class_option :skip_next_steps, type: :boolean, default: false, hide: true
|
|
18
|
+
|
|
19
|
+
def create_initializer
|
|
20
|
+
template "tonic_rails.rb.tt", "config/initializers/tonic_rails.rb"
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def create_directories
|
|
24
|
+
create_file "app/protos/.keep"
|
|
25
|
+
create_file "lib/grpc/.keep"
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def add_puma_plugin
|
|
29
|
+
return if options[:skip_puma]
|
|
30
|
+
|
|
31
|
+
puma = "config/puma.rb"
|
|
32
|
+
return unless File.exist?(File.join(destination_root, puma))
|
|
33
|
+
return if File.read(File.join(destination_root, puma)).match?(/plugin\s+:tonic_rails/)
|
|
34
|
+
|
|
35
|
+
append_to_file puma, "\n# Run the tonic-rails gRPC server alongside Puma.\nplugin :tonic_rails\n"
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def show_next_steps
|
|
39
|
+
return if options[:skip_next_steps]
|
|
40
|
+
|
|
41
|
+
say "\nNext: rails generate tonic_rails:service Item GetItem ListItems:server", :green
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
end
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Ruby code generated from app/protos by `bin/rails tonic_rails:compile_protos`
|
|
4
|
+
# lives in lib/grpc. Its files require each other by plain name, so put the
|
|
5
|
+
# directory on the load path and keep Zeitwerk away from it.
|
|
6
|
+
Rails.root.join("lib/grpc").then do |generated|
|
|
7
|
+
$LOAD_PATH.unshift(generated.to_s) unless $LOAD_PATH.include?(generated.to_s)
|
|
8
|
+
Rails.autoloaders.main.ignore(generated)
|
|
9
|
+
end
|
|
10
|
+
|
|
11
|
+
Tonic::Rails.configure do |config|
|
|
12
|
+
# config.bind_address = "0.0.0.0:50051"
|
|
13
|
+
# config.dispatch_threads = ENV.fetch("RAILS_MAX_THREADS", 5).to_i
|
|
14
|
+
# config.reflection = Rails.env.development?
|
|
15
|
+
# config.health_check = -> { ActiveRecord::Base.connection.active? }
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
# Handlers in app/grpc are autoloaded; register them here so they're
|
|
19
|
+
# picked up again after code reloads.
|
|
20
|
+
Rails.application.config.to_prepare do
|
|
21
|
+
end
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "rails/generators"
|
|
4
|
+
|
|
5
|
+
module TonicRails
|
|
6
|
+
module Generators
|
|
7
|
+
# rails generate tonic_rails:service Item GetItem ListItems:server ImportItems:client Sync:bidi
|
|
8
|
+
#
|
|
9
|
+
# Creates a .proto with the service and its messages, a handler with a
|
|
10
|
+
# method per RPC, the handler's registration, and a test.
|
|
11
|
+
class ServiceGenerator < ::Rails::Generators::NamedBase
|
|
12
|
+
source_root File.expand_path("templates", __dir__)
|
|
13
|
+
|
|
14
|
+
STREAM_KINDS = %w[unary server client bidi].freeze
|
|
15
|
+
|
|
16
|
+
argument :rpcs, type: :array, default: [], banner: "Rpc[:server|:client|:bidi] ..."
|
|
17
|
+
|
|
18
|
+
class_option :package, type: :string,
|
|
19
|
+
desc: "Protobuf package (default: <app name>.v1)"
|
|
20
|
+
|
|
21
|
+
def check_rpcs
|
|
22
|
+
rpc_specs.each do |rpc|
|
|
23
|
+
next if rpc[:name].match?(/\A[A-Z][A-Za-z0-9]*\z/) && STREAM_KINDS.include?(rpc[:kind])
|
|
24
|
+
|
|
25
|
+
raise Thor::Error, "Invalid RPC #{rpc[:raw].inspect}: use CamelCase names, optionally :server, :client or :bidi"
|
|
26
|
+
end
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def create_proto
|
|
30
|
+
template "service.proto.tt", "app/protos/#{package_path}/#{service_file}_service.proto"
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
def create_handler
|
|
34
|
+
template "handler.rb.tt", "app/grpc/#{service_file}_service.rb"
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def register_handler
|
|
38
|
+
initializer = "config/initializers/tonic_rails.rb"
|
|
39
|
+
invoke "tonic_rails:install", [], skip_next_steps: true unless File.exist?(File.join(destination_root, initializer))
|
|
40
|
+
inject_into_file initializer, " Tonic::Rails.server.register(#{service_class})\n",
|
|
41
|
+
after: "Rails.application.config.to_prepare do\n"
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
def create_test
|
|
45
|
+
if File.directory?(File.join(destination_root, "spec"))
|
|
46
|
+
template "service_spec.rb.tt", "spec/grpc/#{service_file}_service_spec.rb"
|
|
47
|
+
else
|
|
48
|
+
template "service_test.rb.tt", "test/grpc/#{service_file}_service_test.rb"
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def show_next_steps
|
|
53
|
+
say "\nNext: bin/rails tonic_rails:compile_protos, then fill in app/grpc/#{service_file}_service.rb", :green
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
private
|
|
57
|
+
|
|
58
|
+
# "Item" and "ItemService" both mean the service ItemService.
|
|
59
|
+
def service_base
|
|
60
|
+
class_name.delete_suffix("Service")
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
def service_file
|
|
64
|
+
service_base.underscore
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
def service_class
|
|
68
|
+
"#{service_base}Service"
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
def package
|
|
72
|
+
options[:package] || "#{app_name}.v1"
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
def app_name
|
|
76
|
+
app = defined?(::Rails.application) && ::Rails.application
|
|
77
|
+
name = app ? app.class.module_parent_name : File.basename(destination_root)
|
|
78
|
+
name.to_s.underscore.tr("-", "_").presence || "app"
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
def package_path
|
|
82
|
+
package.tr(".", "/")
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
def ruby_module
|
|
86
|
+
package.split(".").map(&:camelize).join("::")
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
def full_service_name
|
|
90
|
+
"#{package}.#{service_class}"
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
def rpc_specs
|
|
94
|
+
list = rpcs.empty? ? ["Get#{service_base}"] : rpcs
|
|
95
|
+
list.map do |raw|
|
|
96
|
+
name, kind = raw.split(":", 2)
|
|
97
|
+
{ raw: raw, name: name.to_s, kind: kind || "unary", method: name.to_s.underscore }
|
|
98
|
+
end
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
def proto_rpc_line(rpc)
|
|
102
|
+
request = "#{rpc[:name]}Request"
|
|
103
|
+
response = "#{rpc[:name]}Response"
|
|
104
|
+
request = "stream #{request}" if %w[client bidi].include?(rpc[:kind])
|
|
105
|
+
response = "stream #{response}" if %w[server bidi].include?(rpc[:kind])
|
|
106
|
+
"rpc #{rpc[:name]}(#{request}) returns (#{response});"
|
|
107
|
+
end
|
|
108
|
+
end
|
|
109
|
+
end
|
|
110
|
+
end
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "<%= package_path %>/<%= service_file %>_service_pb"
|
|
4
|
+
|
|
5
|
+
class <%= service_class %>
|
|
6
|
+
include Tonic::Rails::Base
|
|
7
|
+
|
|
8
|
+
rpc_service "<%= full_service_name %>"
|
|
9
|
+
request_format :message
|
|
10
|
+
<% rpc_specs.each do |rpc| %>
|
|
11
|
+
<% case rpc[:kind] -%>
|
|
12
|
+
<% when "unary" -%>
|
|
13
|
+
# @param request [<%= ruby_module %>::<%= rpc[:name] %>Request]
|
|
14
|
+
# @return [<%= ruby_module %>::<%= rpc[:name] %>Response]
|
|
15
|
+
def <%= rpc[:method] %>(request)
|
|
16
|
+
raise Tonic::Rails::RpcError.new("<%= rpc[:name] %> is not implemented yet", code: :unimplemented)
|
|
17
|
+
end
|
|
18
|
+
<% when "server" -%>
|
|
19
|
+
# @param request [<%= ruby_module %>::<%= rpc[:name] %>Request]
|
|
20
|
+
# @return [Enumerable<<%= ruby_module %>::<%= rpc[:name] %>Response>] each element is streamed as it's produced
|
|
21
|
+
def <%= rpc[:method] %>(request)
|
|
22
|
+
raise Tonic::Rails::RpcError.new("<%= rpc[:name] %> is not implemented yet", code: :unimplemented)
|
|
23
|
+
end
|
|
24
|
+
<% when "client" -%>
|
|
25
|
+
# @param requests [Enumerator<<%= ruby_module %>::<%= rpc[:name] %>Request>] yields messages as they arrive
|
|
26
|
+
# @return [<%= ruby_module %>::<%= rpc[:name] %>Response]
|
|
27
|
+
def <%= rpc[:method] %>(requests)
|
|
28
|
+
raise Tonic::Rails::RpcError.new("<%= rpc[:name] %> is not implemented yet", code: :unimplemented)
|
|
29
|
+
end
|
|
30
|
+
<% else -%>
|
|
31
|
+
# @param requests [Enumerator<<%= ruby_module %>::<%= rpc[:name] %>Request>] yields messages as they arrive
|
|
32
|
+
# @return [Enumerable<<%= ruby_module %>::<%= rpc[:name] %>Response>]
|
|
33
|
+
def <%= rpc[:method] %>(requests)
|
|
34
|
+
raise Tonic::Rails::RpcError.new("<%= rpc[:name] %> is not implemented yet", code: :unimplemented)
|
|
35
|
+
end
|
|
36
|
+
<% end -%>
|
|
37
|
+
<% end -%>
|
|
38
|
+
end
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
syntax = "proto3";
|
|
2
|
+
|
|
3
|
+
package <%= package %>;
|
|
4
|
+
|
|
5
|
+
service <%= service_class %> {
|
|
6
|
+
<% rpc_specs.each do |rpc| -%>
|
|
7
|
+
<%= proto_rpc_line(rpc) %>
|
|
8
|
+
<% end -%>
|
|
9
|
+
}
|
|
10
|
+
<% rpc_specs.each do |rpc| %>
|
|
11
|
+
message <%= rpc[:name] %>Request {
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
message <%= rpc[:name] %>Response {
|
|
15
|
+
}
|
|
16
|
+
<% end -%>
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "rails_helper"
|
|
4
|
+
require "tonic/rails/testing/rspec"
|
|
5
|
+
|
|
6
|
+
RSpec.describe <%= service_class %> do
|
|
7
|
+
<% rpc_specs.each_with_index do |rpc, i| -%>
|
|
8
|
+
<% if i.positive? %>
|
|
9
|
+
<% end -%>
|
|
10
|
+
describe "<%= rpc[:name] %>" do
|
|
11
|
+
it "is not implemented yet" do
|
|
12
|
+
request = <%= %w[client bidi].include?(rpc[:kind]) ? "[#{ruby_module}::#{rpc[:name]}Request.new]" : "#{ruby_module}::#{rpc[:name]}Request.new" %>
|
|
13
|
+
expect { Tonic::Rails::Testing.call(described_class, :<%= rpc[:name] %>, request) }.to raise_grpc_error(:unimplemented)
|
|
14
|
+
end
|
|
15
|
+
end
|
|
16
|
+
<% end -%>
|
|
17
|
+
end
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "test_helper"
|
|
4
|
+
require "tonic/rails/testing/minitest"
|
|
5
|
+
|
|
6
|
+
class <%= service_class %>Test < ActiveSupport::TestCase
|
|
7
|
+
include Tonic::Rails::Testing::Assertions
|
|
8
|
+
<% rpc_specs.each do |rpc| %>
|
|
9
|
+
test "<%= rpc[:name] %> is not implemented yet" do
|
|
10
|
+
request = <%= %w[client bidi].include?(rpc[:kind]) ? "[#{ruby_module}::#{rpc[:name]}Request.new]" : "#{ruby_module}::#{rpc[:name]}Request.new" %>
|
|
11
|
+
assert_grpc_error(:unimplemented) { Tonic::Rails::Testing.call(<%= service_class %>, :<%= rpc[:name] %>, request) }
|
|
12
|
+
end
|
|
13
|
+
<% end -%>
|
|
14
|
+
end
|
|
Binary file
|
|
Binary file
|
|
Binary file
|