ultimate_json_rpc 1.1.0 → 2.0.0

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 38b1f03e7b2d16e400022fb55e564618fda59a05120fe7ec5dbaabde0a65aa3c
4
- data.tar.gz: 9da72418f02591bb2a5d46f075748bfe7c4ed5c5eeac0773776ac218d4120309
3
+ metadata.gz: f45af26595bc5213dcf9c08cad72d1cc59f9bfc271ab41738c5b85b53cca4700
4
+ data.tar.gz: 5103120fc4d68e4dbb5d2128ae557be55a46d2b018c89fcfd699cf9dd2815772
5
5
  SHA512:
6
- metadata.gz: a5e9daa5f64023a2647750b93628771ae4ab9ab122c4d55f173e993aa065413aabc9ddd2af4cd5f4655bffc59ebf38a0411d1299569aa9cbc050a1901a7363f7
7
- data.tar.gz: '094ad4549a30f0677c7de1b5aa8a14e19bba50c8c50ee1851568cdf6197b31d0e53c0c1c20a1ffbfc63b5184f568992bc2f50b8a5c5346b84f7422300c16d687'
6
+ metadata.gz: 01576525f8649d759117e23335c67c81491aae9b9514b6d29d02e99d8bb13756bb97387a2707954169fe2eb44ca0f52757851c8cf0f3ca8270618811ccb266a4
7
+ data.tar.gz: 11b1f04708ec18d8acd99da8ab1c13cf79e00f7fdc86b9ba1b381870134af335df4d1c6dd8fe1aabce816efa1b72d5e68db7e305fc3cd298564c842136898320
data/CHANGELOG.md CHANGED
@@ -7,6 +7,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.0.0] - 2026-11-30
11
+
12
+ **2.0 removes everything the gem used to decide on your behalf.** It registers exactly the methods you tell it to: no name is refused, no name is skipped, nothing is put into the request context unless you put it there, and `rpc.discover` is not answered unless you register it. Every registered method is callable by anyone who can reach the server. Compare `server.methods_list` before and after upgrading; the README has an upgrade table.
13
+
14
+ ### Added
15
+ - `Server#expose_discovery` registers `rpc.discover`; `Server#discovery?` tells whether it is registered.
16
+ - `Server#openrpc_document` returns the OpenRPC description to the application itself, whether or not discovery is exposed to clients.
17
+
18
+ ### Changed
19
+ - **Breaking:** `rpc.discover` is no longer answered by default. In 1.x every server described all of its methods to any client that asked. It is now "Method not found" until you call `server.expose_discovery`. `Extras::Docs` reads the description from the server directly, so it works without exposing discovery and no longer runs middleware.
20
+ - **Breaking:** `Transport::Rack` and `Transport::WebSocket` no longer put the Rack env into `request.context` by default. In 1.1.0 every request got `{ rack_env: env }` without being asked. The context is now empty unless you pass `context:`, a callable that receives the env and returns exactly what should be visible. To get the 1.1.0 behaviour back, pass `context: ->(env) { { rack_env: env } }`.
21
+ - **Breaking:** `only:` raises `ArgumentError` for a name the target has no public method for. Previously the name was ignored, with a warning only when nothing at all was exposed.
22
+ - **Breaking:** the dangerous-method blocklist is removed. `expose` used to refuse any method, namespace or `expose_method` name containing one of 41 words (`open`, `load`, `send`, `system`, `public`, ...). A client can only call a registered name, so the list never protected against clients; it only overruled the developer's own `expose` call. `expose` now registers what the call says: `expose(Kernel)` and `only: [:send]` do exactly that.
23
+ - **Breaking:** `expose(target)` no longer skips a method your class defines just because every object has one of the same name. A class that defines a public `to_s`, `inspect` or `send` now gets it registered; use `except:` or `only:` to leave it out. A bare `Object.new` still contributes only the methods defined on it.
24
+ - `expose(target, only: [...])` now looks each name up on the target instead of filtering the list of methods `expose` would find by itself, so it reaches inherited and mixed-in methods and any other public method the target responds to.
25
+
26
+ ### Fixed
27
+ - A "Method not found" error carried `data: "Internal server error"` unless `expose_errors` was on. It now always carries `data: "Method not found: <name>"`, as the README already described.
28
+ - `expose` found no methods on a module that uses `extend self`.
29
+ - README: `assert_rpc_success response, 5` (the expected value is the `expected:` keyword), a `params_schema` example whose keys did not match the method's parameter names and so validated nothing, and a `rate_limit` method that does not exist.
30
+ - `examples/mcp_server.rb` reported division by zero to the client as a bare "Internal error".
31
+
32
+ ### Internal
33
+ - The README's Ruby blocks and every file in `examples/` are now executed by the test suite (`test/test_readme.rb`, `test/test_examples.rb`), so the documentation cannot drift from the code unnoticed.
34
+
10
35
  ## [1.1.0] - 2026-11-30
11
36
 
12
37
  ### Added
data/README.md CHANGED
@@ -9,10 +9,15 @@
9
9
 
10
10
  Network-agnostic JSON-RPC 2.0 server that exposes Ruby modules, classes, and instances as callable RPC endpoints. UltimateJsonRpc handles JSON-RPC message parsing, method dispatch, and response serialization — transport (HTTP, WebSocket, stdio, TCP, etc.) is the caller's responsibility.
11
11
 
12
+ > [!WARNING]
13
+ > **Every method you register can be called by anyone who can reach the server, with any arguments.**
14
+ > UltimateJsonRpc registers exactly what you tell it to and nothing else. It has no list of forbidden methods, skips nothing because of its name, adds no authentication, puts nothing into the request context on its own, and does not describe its methods to clients unless you register that too. `server.expose(obj)` publishes every public method defined on `obj`. Read [Which methods get exposed](#which-methods-get-exposed) before you expose anything.
15
+
12
16
  ## Installation
13
17
 
14
18
  Add to your Gemfile:
15
19
 
20
+ <!-- readme-test: skip (a Gemfile line, not code to run) -->
16
21
  ```ruby
17
22
  gem "ultimate_json_rpc"
18
23
  ```
@@ -46,6 +51,44 @@ server.expose_method("double", description: "Double a number") { |n| n * 2 }
46
51
  server.expose_method("greet") { |name:, greeting: "Hello"| "#{greeting}, #{name}!" }
47
52
  ```
48
53
 
54
+ ### Which methods get exposed
55
+
56
+ **Exactly the ones you register. UltimateJsonRpc never adds to that list, never removes from it, and never refuses a name.**
57
+
58
+ These are all the rules there are:
59
+
60
+ | You write | What gets registered |
61
+ |---|---|
62
+ | `server.expose(target)` | Every public method defined directly on `target`. For a module or class: its own singleton methods (`def self.add`), plus its instance methods if it does `extend self`. For an instance: the public methods written in its class, and those defined on the object itself. |
63
+ | `server.expose(target, only: [...])` | Exactly the named public methods, wherever they are defined, inherited ones included. A name `target` has no public method for raises `ArgumentError`. |
64
+ | `server.expose(target, except: [...])` | What `server.expose(target)` would register, minus the named ones. |
65
+ | `server.expose_method(name) { ... }` | That one block or callable, under that name. |
66
+
67
+ `expose(target)` leaves out inherited and mixed-in methods, and a bare `Object.new` contributes only the methods defined on that object. Nothing else is left out.
68
+
69
+ What follows from these rules is your responsibility, not the gem's:
70
+
71
+ - **Anyone who can reach the server can call every registered method, with any JSON arguments, as often as they like.** There is no authentication, authorization or rate limiting unless you add it ([Authorization](#authorization), [Rate limiting](#rate-limiting)).
72
+ - **There is no list of forbidden methods.** `server.expose(Kernel)` registers `system`, `eval` and `exec`. `only: [:instance_eval]` registers `instance_eval`. Versions before 2.0 refused these; 2.0 does what the call says.
73
+ - **No method is skipped because of what it is called.** If your class defines a public `to_s`, `inspect` or `send`, `server.expose(obj)` registers it.
74
+ - **`expose(target)` takes the method list as it is when it runs.** A public method someone adds to an exposed class later is published at the next boot, and nobody is asked. Use `only:` to make the list part of your code.
75
+ - **The server does not describe itself to clients.** `rpc.discover` is "Method not found" until you call `server.expose_discovery`; after that it lists every registered method to anyone who asks ([Service discovery](#service-discovery)).
76
+
77
+ State the list, look at it, and lock it:
78
+
79
+ ```ruby
80
+ module Admin
81
+ def self.status = "ok"
82
+ def self.wipe_everything = "gone" # public, so server.expose(Admin) would publish it
83
+ end
84
+
85
+ server.expose(Admin, only: [:status]) # the list is now part of your code
86
+ server.methods_list # => ["status"]
87
+ server.freeze # nothing more can be registered
88
+ ```
89
+
90
+ A test such as `assert_equal %w[status], server.methods_list` keeps it that way.
91
+
49
92
  ### Chainable API
50
93
 
51
94
  All setup methods return `self`, and the server is callable via `to_proc`:
@@ -65,20 +108,31 @@ responses = json_requests.map(&server)
65
108
  Declare return types for discovery metadata (purely informational, no runtime enforcement):
66
109
 
67
110
  ```ruby
68
- server.expose_method("add", returns: { "type" => "number" }) { |a, b| a + b }
111
+ server.expose_method("sum", returns: { "type" => "number" }) { |a, b| a + b }
69
112
  server.expose(Calculator, returns: { add: { "type" => "number" } })
70
113
  ```
71
114
 
72
115
  ### Service discovery
73
116
 
74
- Built-in `rpc.discover` returns an [OpenRPC](https://open-rpc.org/) 1.3.2-compatible document:
117
+ The server can describe its methods as an [OpenRPC](https://open-rpc.org/) 1.3.2-compatible document. Your own code can always read it:
75
118
 
76
119
  ```ruby
120
+ server.openrpc_document
121
+ # => {"openrpc"=>"1.3.2", "info"=>{"title"=>"My API", "version"=>"1.0"}, "methods"=>[...]}
122
+ ```
123
+
124
+ **Clients cannot, unless you say so.** `rpc.discover` is not answered until you register it:
125
+
126
+ ```ruby
127
+ server.expose_discovery
128
+
77
129
  request = '{"jsonrpc":"2.0","method":"rpc.discover","id":1}'
78
130
  server.handle(request)
79
131
  # => '{"jsonrpc":"2.0","result":{"openrpc":"1.3.2","info":{"title":"My API","version":"1.0"},"methods":[...]},"id":1}'
80
132
  ```
81
133
 
134
+ Once registered, it tells any client the name, parameters and description of every method. To limit who may ask, use `server.authorize("rpc.discover") { |request| ... }`.
135
+
82
136
  ### Middleware
83
137
 
84
138
  Add cross-cutting concerns like logging, auth, or rate limiting:
@@ -123,17 +177,19 @@ end
123
177
 
124
178
  `request.context` is a per-request Hash for everything that is not part of the JSON-RPC message: who is calling, over which connection, with which credentials.
125
179
 
126
- The transport seeds it. Pass `context:` to `handle` (or `handle_parsed`); every request, including each item of a batch, starts with its own copy:
180
+ **It is empty unless you fill it.** No adapter adds anything by itself: not the Rack env, not a header, not the caller's address. To fill it, pass `context:` to `handle` (or `handle_parsed`); every request, including each item of a batch, gets its own copy:
127
181
 
128
182
  ```ruby
129
183
  server.handle(json, context: { user: current_user, ip: request.ip })
130
184
  ```
131
185
 
132
- The Rack and WebSocket adapters do this for you (see [Transport examples](#transport-examples)). Middleware reads the context and can add to it:
186
+ With the Rack and WebSocket adapters, the context is whatever your `context:` callable returns, and empty if you gave none (see [Transport examples](#transport-examples)).
187
+
188
+ Middleware reads the context and can add to it:
133
189
 
134
190
  ```ruby
135
191
  server.use do |request, next_call|
136
- request.context[:user] = authenticate(request.context[:rack_env]["HTTP_AUTHORIZATION"])
192
+ request.context[:user] = authenticate(request.context[:token])
137
193
  next_call.call
138
194
  end
139
195
  ```
@@ -164,6 +220,7 @@ Hook errors are rescued and logged via `Kernel.warn`, never breaking dispatch.
164
220
 
165
221
  Swap the JSON encoder/decoder (defaults to stdlib `JSON`):
166
222
 
223
+ <!-- readme-test: skip (needs the oj gem) -->
167
224
  ```ruby
168
225
  require "oj"
169
226
  Oj.mimic_JSON
@@ -196,17 +253,17 @@ server = UltimateJsonRpc::Server.new(timeout: 5)
196
253
  Declare parameter schemas to validate incoming params before dispatch:
197
254
 
198
255
  ```ruby
199
- server.expose_method("add", params_schema: {
256
+ server.expose_method("sum", params_schema: {
200
257
  a: { "type" => "number" },
201
258
  b: { "type" => "number" }
202
259
  }) { |a, b| a + b }
203
260
 
204
261
  server.expose(Calculator, params_schema: {
205
- add: { left: { "type" => "number" }, right: { "type" => "number" } }
262
+ add: { a: { "type" => "number" }, b: { "type" => "number" } }
206
263
  })
207
264
  ```
208
265
 
209
- Supported JSON Schema keywords: `type` (`string`, `number`, `integer`, `boolean`, `array`, `object`, `null`) and `enum`. On mismatch, returns `-32602 Invalid params` with a descriptive message. Schemas also appear in `rpc.discover` output.
266
+ Supported JSON Schema keywords: `type` (`string`, `number`, `integer`, `boolean`, `array`, `object`, `null`) and `enum`. On mismatch, returns `-32602 Invalid params` with a descriptive message. Schemas also appear in the OpenRPC document.
210
267
 
211
268
  ### Method deprecation
212
269
 
@@ -218,7 +275,7 @@ server.expose_method("old_multiply", deprecated: "Use multiply_v2 instead") { |a
218
275
  server.expose(Calculator, deprecated: { add: "Use add_v2" })
219
276
  ```
220
277
 
221
- Deprecated methods still work normally but appear flagged in `rpc.discover` output.
278
+ Deprecated methods still work normally but appear flagged in the OpenRPC document.
222
279
 
223
280
  ### Per-method profiling
224
281
 
@@ -281,15 +338,22 @@ server.register_error(code: 42, message: "InsufficientFunds", description: "Acco
281
338
  server.register_error(code: 43, message: "AccountLocked")
282
339
  ```
283
340
 
284
- Registered errors appear in `rpc.discover` under `components.errors`, so consumers know which error codes to expect.
341
+ Registered errors appear in the OpenRPC document under `components.errors`, so consumers know which error codes to expect.
285
342
 
286
343
  ### Error handling
287
344
 
288
345
  Raise `ApplicationError` for custom error codes, or `ServerError` for implementation-defined errors:
289
346
 
290
347
  ```ruby
291
- raise UltimateJsonRpc::ApplicationError.new(code: 42, message: "Custom error", data: { "detail" => "info" })
292
- raise UltimateJsonRpc::ServerError.new(code: -32_001, message: "Server shutting down")
348
+ server.expose_method("withdraw") do |amount|
349
+ raise UltimateJsonRpc::ApplicationError.new(code: 42, message: "Insufficient funds", data: { "balance" => 10 }) if amount > 10
350
+
351
+ "ok"
352
+ end
353
+
354
+ server.expose_method("status") do
355
+ raise UltimateJsonRpc::ServerError.new(code: -32_050, message: "Server shutting down")
356
+ end
293
357
  ```
294
358
 
295
359
  Params are checked against the method's signature before it is called: a wrong number of positional arguments, a missing required keyword, or an unknown keyword returns Invalid params (`-32602`) without running the method. Every exception raised inside the method, including `ArgumentError`, becomes Internal error (`-32603`).
@@ -324,16 +388,16 @@ server.handle(request) # still works
324
388
  ### Features
325
389
 
326
390
  - **JSON-RPC 2.0** compliant (requests, notifications, batch requests)
327
- - **Expose modules** — singleton methods become RPC methods
391
+ - **Expose modules** — singleton methods become RPC methods, including modules that `extend self`
328
392
  - **Expose instances** — public methods become RPC methods
329
393
  - **Expose blocks** — `server.expose_method("name") { ... }` for standalone methods
330
394
  - **Namespacing** — `server.expose(obj, namespace: "ns")` makes methods callable as `ns.method_name`
331
- - **Method filtering** — `server.expose(obj, only: [:add])` or `except: [:internal]`
395
+ - **Method filtering** — `server.expose(obj, only: [:add])` or `except: [:internal]`; `only:` also reaches inherited methods
332
396
  - **Method descriptions** — `descriptions:` hash or `description:` keyword for discovery
333
397
  - **Return type annotations** — `returns:` hash or keyword for discovery metadata
334
- - **Service metadata** — `name:` and `version:` appear in `rpc.discover` responses
398
+ - **Service metadata** — `name:` and `version:` appear in the OpenRPC document
335
399
  - **Positional and keyword params** — arrays map to positional args, objects map to keyword args
336
- - **Service discovery** — built-in `rpc.discover` returns OpenRPC 1.3.2-compatible schema
400
+ - **Service discovery** — `server.openrpc_document` for you; `rpc.discover` for clients once you call `expose_discovery`
337
401
  - **Middleware** — `server.use { |request, next_call| ... }` for cross-cutting concerns
338
402
  - **Request context** — transports seed `request.context`; methods read it via `UltimateJsonRpc.current_request`
339
403
  - **Scoped middleware** — `only:` / `except:` with glob patterns to target specific methods or namespaces
@@ -341,12 +405,12 @@ server.handle(request) # still works
341
405
  - **Parameter validation** — `params_schema:` with JSON Schema types and enum constraints
342
406
  - **Request timeout** — `Server.new(timeout: 5)` prevents slow handlers from blocking
343
407
  - **Method deprecation** — mark methods as deprecated in discovery metadata
344
- - **Error catalog** — `register_error` documents app error codes in `rpc.discover`
408
+ - **Error catalog** — `register_error` documents app error codes in the OpenRPC document
345
409
  - **Authorization** — `authorize("admin.*") { |req| ... }` for declarative access control
346
410
  - **Error handling** — standard JSON-RPC error codes, `ApplicationError`, and `ServerError`
347
411
  - **Error visibility** — `expose_errors: true` to include exception messages in error responses
348
- - **Rate limiting** — sliding-window `rate_limit(max:, period:)` with per-caller keying
349
- - **Security** — dangerous methods (eval, system, exec, etc.) are automatically blocked
412
+ - **Rate limiting** — sliding-window `Extras::RateLimiter.new(server, max:, period:)` with per-caller keying
413
+ - **Explicit surface** — a client can only call what you registered; `methods_list` shows it
350
414
  - **Chainable API** — all setup methods return `self`
351
415
  - **Callable** — `to_proc` enables `requests.map(&server)`
352
416
  - **Rack adapter** — `UltimateJsonRpc::Transport::Rack.new(server)` for instant HTTP deployment
@@ -379,10 +443,10 @@ run UltimateJsonRpc::Transport::Rack.new(server)
379
443
 
380
444
  `UltimateJsonRpc::Transport::Rack` handles Content-Type, returns 200 for responses, 204 for notifications, and 405 for non-POST requests.
381
445
 
382
- Each request's context is `{ rack_env: env }` by default, so middleware and `authorize` blocks can read headers. Pass `context:` to build your own:
446
+ Nothing from the HTTP request reaches `request.context` unless you say so. Pass `context:`, a callable that receives the Rack env and returns exactly what middleware, `authorize` blocks and your methods should see:
383
447
 
384
448
  ```ruby
385
- run UltimateJsonRpc::Transport::Rack.new(server, context: ->(env) { { user: env["warden"].user } })
449
+ run UltimateJsonRpc::Transport::Rack.new(server, context: ->(env) { { token: env["HTTP_AUTHORIZATION"] } })
386
450
  ```
387
451
 
388
452
  #### MCP (Model Context Protocol)
@@ -404,6 +468,7 @@ UltimateJsonRpc::Extras::MCP.new(server).run
404
468
 
405
469
  Use the WebSocket adapter with any Rack-compatible library (e.g., `faye-websocket`):
406
470
 
471
+ <!-- readme-test: skip (needs faye-websocket and a live connection) -->
407
472
  ```ruby
408
473
  require "ultimate_json_rpc/transport/websocket"
409
474
 
@@ -414,7 +479,7 @@ ws = Faye::WebSocket.new(env)
414
479
  ws_handler.call(env, ws)
415
480
  ```
416
481
 
417
- The handshake's Rack env seeds the context of every message on that socket (`{ rack_env: env }`, or whatever a `context:` callable passed to `WebSocket.new` returns).
482
+ As with Rack, nothing from the handshake reaches `request.context` unless you pass `WebSocket.new(server, context: ->(env) { ... })`; what it returns is used for every message on that socket.
418
483
 
419
484
  See `examples/websocket_server.ru` for a complete runnable example.
420
485
 
@@ -422,6 +487,7 @@ See `examples/websocket_server.ru` for a complete runnable example.
422
487
 
423
488
  Use the built-in TCP adapter for internal microservices:
424
489
 
490
+ <!-- readme-test: skip (starts a server that runs until interrupted) -->
425
491
  ```ruby
426
492
  require "ultimate_json_rpc/transport/tcp"
427
493
 
@@ -483,22 +549,45 @@ require "ultimate_json_rpc/extras/test_helpers"
483
549
  class MyTest < Minitest::Test
484
550
  include UltimateJsonRpc::Extras::TestHelpers
485
551
 
552
+ def setup
553
+ @server = UltimateJsonRpc::Server.new.expose(Calculator)
554
+ end
555
+
486
556
  def test_addition
487
- response = rpc_call(server, "add", params: [2, 3])
488
- assert_rpc_success response, 5
557
+ response = rpc_call(@server, "add", params: [2, 3])
558
+ assert_rpc_success response, expected: 5
489
559
  end
490
560
 
491
561
  def test_method_not_found
492
- response = rpc_call(server, "nonexistent")
562
+ response = rpc_call(@server, "nonexistent")
493
563
  assert_rpc_error response, code: -32_601
494
564
  end
495
565
 
496
566
  def test_notification
497
- assert_rpc_notification server, "add", params: [1, 2]
567
+ assert_rpc_notification @server, "add", params: [1, 2]
568
+ end
569
+
570
+ def test_caller_identity
571
+ @server.expose_method("whoami") { UltimateJsonRpc.current_request.context[:user] }
572
+ response = rpc_call(@server, "whoami", context: { user: "alice" })
573
+ assert_rpc_success response, expected: "alice"
498
574
  end
499
575
  end
500
576
  ```
501
577
 
578
+ ## Upgrading from 1.x to 2.0
579
+
580
+ 2.0 removes everything the gem used to decide on your behalf. Before deploying it, print `server.methods_list` under 1.x and under 2.0 and compare the two.
581
+
582
+ | 1.x | 2.0 | What to do |
583
+ |---|---|---|
584
+ | `expose` raised "method name '...' is dangerous" for 41 names (`open`, `load`, `send`, `system`, ...), also as namespaces and in `expose_method`. | No name is refused. | If you counted on that error to stop something being published, list the methods with `only:`. |
585
+ | `expose(obj)` skipped a method your class defined when every object has one of that name (`to_s`, `inspect`, `send`, `hash`, `==`). | It is registered like any other public method. | Remove it with `except:`, or use `only:`. |
586
+ | `only:` ignored a name the target did not have. | `only:` raises `ArgumentError` for it, and finds inherited methods. | Fix the name. |
587
+ | (1.1 only) The Rack and WebSocket adapters put `{ rack_env: env }` into `request.context`. | The context is empty unless you pass `context:`. | `Transport::Rack.new(server, context: ->(env) { { token: env["HTTP_AUTHORIZATION"] } })` |
588
+ | `rpc.discover` was always answered. | It is "Method not found" until you register it. | `server.expose_discovery`, if clients need it. `server.openrpc_document` and `Extras::Docs` work without it. |
589
+ | "Method not found" carried `data: "Internal server error"`. | It carries `data: "Method not found: <name>"`. | Nothing, unless a client matched on the old text. |
590
+
502
591
  ## Development
503
592
 
504
593
  ```bash
@@ -23,8 +23,10 @@ module MathTools
23
23
  def self.add(a, b) = a + b
24
24
  def self.subtract(a, b) = a - b
25
25
  def self.multiply(a, b) = a * b
26
+ # An ApplicationError's message is passed on to the client as the tool's
27
+ # error text. Any other exception reaches it as a bare "Internal error".
26
28
  def self.divide(a, b)
27
- raise ArgumentError, "Division by zero" if b.zero?
29
+ raise UltimateJsonRpc::ApplicationError.new(code: 1, message: "Division by zero") if b.zero?
28
30
 
29
31
  a.to_f / b
30
32
  end
@@ -6,25 +6,6 @@ module UltimateJsonRpc
6
6
  VARIADIC_DEFAULTS = { rest: "args", keyrest: "kwargs" }.freeze
7
7
  private_constant :VARIADIC_DEFAULTS
8
8
 
9
- DANGEROUS_METHODS = %w[
10
- eval instance_eval class_eval module_eval
11
- send public_send __send__
12
- system exec spawn fork
13
- define_method remove_method undef_method
14
- binding method_missing respond_to_missing?
15
- exit exit! abort
16
- require require_relative load
17
- open
18
- instance_variable_get instance_variable_set
19
- class_variable_get class_variable_set
20
- const_get const_set remove_const
21
- method
22
- include extend prepend
23
- attr_accessor attr_reader attr_writer
24
- public private protected
25
- ].freeze
26
- private_constant :DANGEROUS_METHODS
27
-
28
9
  TYPE_CHECKS = {
29
10
  "string" => String, "number" => Numeric, "integer" => Integer,
30
11
  "boolean" => [TrueClass, FalseClass], "array" => Array,
@@ -188,10 +169,10 @@ module UltimateJsonRpc
188
169
  params_schema: nil)
189
170
  validate_expose_args!(target, only, except)
190
171
  prefix = namespace.to_s.then { |ns| ns.empty? ? "" : "#{ns}." }
191
- methods = filter_methods(callable_methods(target), only: only, except: except)
192
- Kernel.warn "UltimateJsonRpc: expose registered 0 methods from #{target.inspect}" if methods.empty?
193
- methods.each do |m|
194
- register_exposed(prefix:, method_name: m, target:, descriptions:, returns:, deprecated:, params_schema:)
172
+ callables = only ? named_callables(target, only) : discovered_callables(target, except)
173
+ Kernel.warn "UltimateJsonRpc: expose registered 0 methods from #{target.inspect}" if callables.empty?
174
+ callables.each do |method_name, callable|
175
+ register_exposed(prefix:, method_name:, callable:, descriptions:, returns:, deprecated:, params_schema:)
195
176
  end
196
177
  end
197
178
 
@@ -270,10 +251,9 @@ module UltimateJsonRpc
270
251
  desc
271
252
  end
272
253
 
273
- def register_exposed(prefix:, method_name:, target:, descriptions:, returns:, deprecated:, params_schema:)
254
+ def register_exposed(prefix:, method_name:, callable:, descriptions:, returns:, deprecated:, params_schema:)
274
255
  full_name = "#{prefix}#{method_name}"
275
256
  validate_method_name!(full_name)
276
- callable = target.method(method_name.to_sym)
277
257
  @entries[full_name] = Entry.new(
278
258
  callable: callable,
279
259
  signature: build_signature(callable),
@@ -299,27 +279,42 @@ module UltimateJsonRpc
299
279
  source[method_name.to_s]
300
280
  end
301
281
 
302
- def callable_methods(target)
303
- if target.is_a?(Module)
304
- target.singleton_methods(false).map(&:to_s)
305
- else
306
- ((target.class.public_instance_methods(false) - Object.public_instance_methods) |
307
- target.singleton_methods(false)).map(&:to_s)
308
- end
282
+ # What expose registers is decided by the call alone, never by what a
283
+ # method happens to be called.
284
+ #
285
+ # With only:, exactly the named public methods, wherever they are defined.
286
+ def named_callables(target, only)
287
+ Array(only).map(&:to_s).uniq.to_h { |name| [name, named_callable(target, name)] }
288
+ end
289
+
290
+ def named_callable(target, name)
291
+ target.public_method(name)
292
+ rescue NameError
293
+ raise ArgumentError, "#{target.inspect} has no public method '#{name}'"
294
+ end
295
+
296
+ # Without only:, the public methods defined directly on the target.
297
+ def discovered_callables(target, except)
298
+ names = defined_methods(target) - Array(except).map(&:to_s)
299
+ names.to_h { |name| [name, target.method(name)] }
309
300
  end
310
301
 
311
- def filter_methods(methods, only:, except:)
312
- if only
313
- allowed = Array(only).map(&:to_s)
314
- methods.select { |m| allowed.include?(m) }
315
- elsif except
316
- blocked = Array(except).map(&:to_s)
317
- methods.reject { |m| blocked.include?(m) }
318
- else
319
- methods
302
+ # A module or class: its own singleton methods, plus its instance methods
303
+ # when it extends itself. An instance: the methods of its class and those
304
+ # defined on the object itself. Object is not anyone's own class, so a
305
+ # bare Object.new contributes only what was defined on it.
306
+ def defined_methods(target)
307
+ names = target.singleton_methods(false)
308
+ if target.is_a?(Module)
309
+ names |= target.public_instance_methods(false) if extends_itself?(target)
310
+ elsif !target.instance_of?(Object)
311
+ names |= target.class.public_instance_methods(false)
320
312
  end
313
+ names.map(&:to_s)
321
314
  end
322
315
 
316
+ def extends_itself?(mod) = !mod.is_a?(Class) && mod.singleton_class.include?(mod)
317
+
323
318
  def validate_expose_args!(target, only, except)
324
319
  raise ArgumentError, "target must not be nil" if target.nil?
325
320
  raise ArgumentError, "cannot use both :only and :except" if only && except
@@ -329,18 +324,10 @@ module UltimateJsonRpc
329
324
  raise ArgumentError, "method name must not be empty" if name.empty?
330
325
  raise ArgumentError, "method names starting with 'rpc.' are reserved" if name.start_with?("rpc.")
331
326
 
332
- validate_segments!(name)
327
+ raise ArgumentError, "method name contains empty segment" if name.split(".", -1).any?(&:empty?)
333
328
  raise ArgumentError, "method '#{name}' is already registered" if @entries.key?(name)
334
329
  end
335
330
 
336
- def validate_segments!(name)
337
- segments = name.include?(".") ? name.split(".", -1) : [name]
338
- segments.each do |segment|
339
- raise ArgumentError, "method name contains empty segment" if segment.empty?
340
- raise ArgumentError, "method name '#{segment}' is dangerous" if DANGEROUS_METHODS.include?(segment)
341
- end
342
- end
343
-
344
331
  def resolve_callable(callable, block)
345
332
  raise ArgumentError, "provide either a callable or a block, not both" if callable && block
346
333
  raise ArgumentError, "a callable or block is required" unless callable || block
@@ -18,14 +18,11 @@ module UltimateJsonRpc
18
18
 
19
19
  private
20
20
 
21
+ # Read straight from the server, so it works whether or not discovery is
22
+ # exposed to clients. The round trip gives the document as a client
23
+ # would see it (string keys throughout).
21
24
  def discover
22
- @discover ||= begin
23
- request = { "jsonrpc" => "2.0", "method" => "rpc.discover", "id" => 1 }
24
- result = @json.parse(@server.handle(@json.generate(request)))
25
- raise "rpc.discover returned an error: #{result["error"]&.inspect}" unless result.key?("result")
26
-
27
- result["result"]
28
- end
25
+ @discover ||= @json.parse(@json.generate(@server.openrpc_document))
29
26
  end
30
27
 
31
28
  def title_section
@@ -86,15 +86,26 @@ module UltimateJsonRpc
86
86
  private_constant :BatchProcessor
87
87
 
88
88
  module OpenRPCBuilder
89
- private
90
-
91
- def build_openrpc_document
89
+ # The OpenRPC description of every registered method. Always available to
90
+ # the application itself; clients get it only after #expose_discovery.
91
+ def openrpc_document
92
92
  doc = { "openrpc" => "1.3.2", "info" => build_info, "methods" => @handler.methods_info }
93
93
  doc.delete("info") if doc["info"].empty?
94
94
  doc["components"] = { "errors" => @error_catalog } if @error_catalog&.any?
95
95
  doc
96
96
  end
97
97
 
98
+ # Registers rpc.discover, which returns #openrpc_document to any client
99
+ # that asks. Until this is called, rpc.discover is Method not found.
100
+ def expose_discovery
101
+ @discovery = true
102
+ self
103
+ end
104
+
105
+ def discovery? = @discovery
106
+
107
+ private
108
+
98
109
  def build_info
99
110
  { "title" => @name, "version" => @version, "description" => @description }.compact
100
111
  end
@@ -168,10 +179,14 @@ module UltimateJsonRpc
168
179
  @max_concurrency = max_concurrency
169
180
  @json = @json_adapter = json
170
181
  @handler = Core::Handler.new
182
+ @discovery = false
171
183
  @middleware = []
172
184
  @hooks = HOOK_EVENTS.to_h { |e| [e, []] }
173
185
  end
174
186
 
187
+ # Registers the public methods defined directly on +target+, or exactly
188
+ # the names given in +only:+. Nothing is filtered or refused: every
189
+ # registered method can be called by any client that reaches the server.
175
190
  def expose(target, namespace: nil, only: nil, except: nil, descriptions: nil, returns: nil, deprecated: nil,
176
191
  params_schema: nil)
177
192
  @handler.expose(target, namespace:, only:, except:, descriptions:, returns:, deprecated:, params_schema:)
@@ -318,7 +333,8 @@ module UltimateJsonRpc
318
333
  def elapsed(start) = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start
319
334
 
320
335
  def precompile_middleware
321
- methods = @handler.methods_list + ["rpc.discover"]
336
+ methods = @handler.methods_list
337
+ methods += ["rpc.discover"] if @discovery
322
338
  @middleware_index = methods.to_h do |name|
323
339
  [name, @middleware.select { |_, matcher| matcher.call(name) }.freeze]
324
340
  end.freeze
@@ -359,15 +375,16 @@ module UltimateJsonRpc
359
375
  end
360
376
 
361
377
  def invoke_handler(request)
362
- return @handler.call(request.method_name, request.params) unless request.method_name == "rpc.discover"
378
+ return openrpc_document if @discovery && request.method_name == "rpc.discover"
363
379
 
364
- build_openrpc_document
380
+ @handler.call(request.method_name, request.params)
365
381
  end
366
382
 
367
383
  def error_details(err)
368
384
  case err
369
385
  when Core::MethodNotFound
370
- [Core::METHOD_NOT_FOUND, Core::ERROR_MESSAGES[Core::METHOD_NOT_FOUND], generic_data(err)]
386
+ # The message only echoes the name the client sent, so it is never hidden.
387
+ [Core::METHOD_NOT_FOUND, Core::ERROR_MESSAGES[Core::METHOD_NOT_FOUND], err.message]
371
388
  when Core::ApplicationError, Core::ServerError then [err.code, err.message, err.rpc_data]
372
389
  when Core::InvalidParams then [Core::INVALID_PARAMS, nil, generic_data(err, GENERIC_PARAMS_DATA)]
373
390
  when Core::InvalidRequest then [Core::INVALID_REQUEST, nil, generic_data(err)]
@@ -10,7 +10,7 @@ module UltimateJsonRpc
10
10
 
11
11
  # +context+ is an optional callable that turns the Rack env into the
12
12
  # request context, e.g. <tt>->(env) { { user: env["warden"].user } }</tt>.
13
- # Without it the context is <tt>{ rack_env: env }</tt>.
13
+ # Without it nothing from the HTTP request reaches the context.
14
14
  def initialize(server, context: nil)
15
15
  raise ArgumentError, "context must respond to #call" unless context.nil? || context.respond_to?(:call)
16
16
 
@@ -40,7 +40,7 @@ module UltimateJsonRpc
40
40
 
41
41
  private
42
42
 
43
- def build_context(env) = @context ? @context.call(env) : { rack_env: env }
43
+ def build_context(env) = @context&.call(env)
44
44
 
45
45
  def method_not_allowed
46
46
  [405, NOT_ALLOWED_HEADERS.dup, [NOT_ALLOWED_BODY]]
@@ -6,8 +6,8 @@ module UltimateJsonRpc
6
6
  attr_reader :server
7
7
 
8
8
  # +context+ is an optional callable that turns the Rack env of the
9
- # WebSocket handshake into the request context. Without it the context
10
- # is <tt>{ rack_env: env }</tt>.
9
+ # WebSocket handshake into the request context. Without it nothing from
10
+ # the handshake reaches the context.
11
11
  def initialize(server, context: nil)
12
12
  raise ArgumentError, "context must respond to #call" unless context.nil? || context.respond_to?(:call)
13
13
 
@@ -20,7 +20,7 @@ module UltimateJsonRpc
20
20
  end
21
21
 
22
22
  def call(env, socket)
23
- context = @context ? @context.call(env) : { rack_env: env }
23
+ context = @context&.call(env)
24
24
  socket.on(:message) do |event|
25
25
  response = on_message(event.respond_to?(:data) ? event.data : event, context:)
26
26
  socket.send(response) if response
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module UltimateJsonRpc
4
- VERSION = "1.1.0"
4
+ VERSION = "2.0.0"
5
5
  end
@@ -106,6 +106,9 @@ module UltimateJsonRpc
106
106
  def use: (?only: Array[String | Symbol] | String | Symbol | nil, ?except: Array[String | Symbol] | String | Symbol | nil) { (Core::Request, Proc) -> untyped } -> self
107
107
  def on: (Symbol) { (*untyped) -> void } -> self
108
108
  def register_error: (code: Integer, message: String, ?description: String?) -> self
109
+ def expose_discovery: () -> self
110
+ def discovery?: () -> bool
111
+ def openrpc_document: () -> Hash[String, untyped]
109
112
  def authorize: (*String, ?code: Integer, ?message: String) { (Core::Request) -> boolish } -> self
110
113
  def to_proc: () -> Proc
111
114
  def inspect: () -> String
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ultimate_json_rpc
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.1.0
4
+ version: 2.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Andriy Tyurnikov