ultimate_json_rpc 1.0.0 → 1.1.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 +4 -4
- data/CHANGELOG.md +17 -0
- data/README.md +40 -4
- data/lib/ultimate_json_rpc/core/handler.rb +92 -28
- data/lib/ultimate_json_rpc/core/request.rb +5 -2
- data/lib/ultimate_json_rpc/extras/mcp.rb +7 -4
- data/lib/ultimate_json_rpc/extras/test_helpers.rb +4 -4
- data/lib/ultimate_json_rpc/server.rb +43 -22
- data/lib/ultimate_json_rpc/transport/rack.rb +10 -2
- data/lib/ultimate_json_rpc/transport/websocket.rb +12 -5
- data/lib/ultimate_json_rpc/version.rb +1 -1
- data/lib/ultimate_json_rpc.rb +12 -0
- data/sig/ultimate_json_rpc.rbs +10 -8
- metadata +2 -2
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 38b1f03e7b2d16e400022fb55e564618fda59a05120fe7ec5dbaabde0a65aa3c
|
|
4
|
+
data.tar.gz: 9da72418f02591bb2a5d46f075748bfe7c4ed5c5eeac0773776ac218d4120309
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: a5e9daa5f64023a2647750b93628771ae4ab9ab122c4d55f173e993aa065413aabc9ddd2af4cd5f4655bffc59ebf38a0411d1299569aa9cbc050a1901a7363f7
|
|
7
|
+
data.tar.gz: '094ad4549a30f0677c7de1b5aa8a14e19bba50c8c50ee1851568cdf6197b31d0e53c0c1c20a1ffbfc63b5184f568992bc2f50b8a5c5346b84f7422300c16d687'
|
data/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [1.1.0] - 2026-11-30
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
- `Server#handle` and `Server#handle_parsed` accept `context:`, a Hash that seeds `request.context` for every request in the call (each batch item gets its own copy). This is how a transport tells middleware, `authorize` blocks and rate limiters who the caller is.
|
|
14
|
+
- `UltimateJsonRpc.current_request` returns the request being dispatched on the current fiber, so exposed methods can read `request.context`. Previously the context was only visible to middleware, despite the README saying handlers could use it.
|
|
15
|
+
- `Transport::Rack` seeds the context with `{ rack_env: env }` and accepts `context:` (a callable taking the env) to build a custom one. `Transport::WebSocket` does the same with the handshake env, and `on_message` accepts `context:`.
|
|
16
|
+
- Test helpers `rpc_call` and `rpc_notify` accept `context:`.
|
|
17
|
+
|
|
18
|
+
### Changed
|
|
19
|
+
- Params are now checked against the method's signature before the call, instead of rescuing `ArgumentError` and matching its message. A wrong argument count, missing keyword or unknown keyword still returns `-32602 Invalid params`, and the method no longer runs at all in those cases.
|
|
20
|
+
- A method declared with a catch-all signature (`*args`, `**opts`, e.g. a `Forwardable` delegator) accepts any params, so an arity error raised further down is now `-32603 Internal error` rather than `-32602`.
|
|
21
|
+
|
|
22
|
+
### Fixed
|
|
23
|
+
- An `ArgumentError` raised inside a method body whose message starts with "wrong number of arguments" or "missing keyword" (typically a bug in a nested call) was reported to the client as `-32602 Invalid params`. It is now `-32603 Internal error`.
|
|
24
|
+
- A callable object that only implements `#call` can now be invoked with named params; previously this failed with an internal error.
|
|
25
|
+
- MCP adapter: `initialize`, `notifications/initialized`, `tools/list` and `tools/call` now accept the params real clients send (`protocolVersion`, `capabilities`, `clientInfo`, `cursor`, `_meta`). Previously any `initialize` request carrying params was rejected with `-32602 Invalid params`, so the handshake failed with every real MCP client.
|
|
26
|
+
|
|
10
27
|
## [1.0.0] - 2026-03-20
|
|
11
28
|
|
|
12
29
|
### Added
|
data/README.md
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
# UltimateJsonRpc
|
|
2
2
|
|
|
3
3
|
[](https://github.com/rubakas/ultimate_json_rpc/actions/workflows/main.yml)
|
|
4
|
+
[](https://rubygems.org/gems/ultimate_json_rpc)
|
|
5
|
+
[](https://rubygems.org/gems/ultimate_json_rpc)
|
|
6
|
+
[](https://www.ruby-lang.org)
|
|
7
|
+
[](https://opensource.org/licenses/MIT)
|
|
8
|
+
[](https://www.jsonrpc.org/specification)
|
|
4
9
|
|
|
5
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.
|
|
6
11
|
|
|
@@ -114,15 +119,35 @@ server.use(except: ["ping", "health"]) do |request, next_call|
|
|
|
114
119
|
end
|
|
115
120
|
```
|
|
116
121
|
|
|
117
|
-
|
|
122
|
+
### Request context
|
|
123
|
+
|
|
124
|
+
`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
|
+
|
|
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:
|
|
127
|
+
|
|
128
|
+
```ruby
|
|
129
|
+
server.handle(json, context: { user: current_user, ip: request.ip })
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
The Rack and WebSocket adapters do this for you (see [Transport examples](#transport-examples)). Middleware reads the context and can add to it:
|
|
118
133
|
|
|
119
134
|
```ruby
|
|
120
135
|
server.use do |request, next_call|
|
|
121
|
-
request.context[:user] = authenticate(request)
|
|
136
|
+
request.context[:user] = authenticate(request.context[:rack_env]["HTTP_AUTHORIZATION"])
|
|
122
137
|
next_call.call
|
|
123
138
|
end
|
|
124
139
|
```
|
|
125
140
|
|
|
141
|
+
Exposed methods reach it through `UltimateJsonRpc.current_request`, which is set while the middleware chain and the method run and is `nil` otherwise:
|
|
142
|
+
|
|
143
|
+
```ruby
|
|
144
|
+
module Account
|
|
145
|
+
def self.whoami = UltimateJsonRpc.current_request.context[:user].name
|
|
146
|
+
end
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
`current_request` is fiber-local and is inherited by fibers and threads started from inside the method, so it is safe with concurrent batches and threaded servers.
|
|
150
|
+
|
|
126
151
|
### Instrumentation hooks
|
|
127
152
|
|
|
128
153
|
Read-only lifecycle hooks for observability — they can't alter responses or swallow errors:
|
|
@@ -267,7 +292,9 @@ raise UltimateJsonRpc::ApplicationError.new(code: 42, message: "Custom error", d
|
|
|
267
292
|
raise UltimateJsonRpc::ServerError.new(code: -32_001, message: "Server shutting down")
|
|
268
293
|
```
|
|
269
294
|
|
|
270
|
-
|
|
295
|
+
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`).
|
|
296
|
+
|
|
297
|
+
A block passed to `expose_method` keeps Ruby's block semantics: extra positional arguments are ignored and missing ones are `nil`. Pass a lambda (`->(a, b) { ... }`) when you want the argument count enforced.
|
|
271
298
|
|
|
272
299
|
### Error visibility
|
|
273
300
|
|
|
@@ -283,7 +310,7 @@ server = UltimateJsonRpc::Server.new(expose_errors: true)
|
|
|
283
310
|
|
|
284
311
|
`ApplicationError`, `ServerError`, and `MethodNotFound` always expose their details regardless of this setting, since those are intentionally raised by your code.
|
|
285
312
|
|
|
286
|
-
Protocol-level errors (`InvalidRequest`, `InvalidParams`,
|
|
313
|
+
Protocol-level errors (`InvalidRequest`, `InvalidParams`, and unhandled exceptions) are gated by `expose_errors`. `InvalidParams` is a protocol-level check (signature mismatch, schema type mismatch, enum violation) — for application-level business validation, raise `ApplicationError` instead.
|
|
287
314
|
|
|
288
315
|
### Freezing
|
|
289
316
|
|
|
@@ -308,6 +335,7 @@ server.handle(request) # still works
|
|
|
308
335
|
- **Positional and keyword params** — arrays map to positional args, objects map to keyword args
|
|
309
336
|
- **Service discovery** — built-in `rpc.discover` returns OpenRPC 1.3.2-compatible schema
|
|
310
337
|
- **Middleware** — `server.use { |request, next_call| ... }` for cross-cutting concerns
|
|
338
|
+
- **Request context** — transports seed `request.context`; methods read it via `UltimateJsonRpc.current_request`
|
|
311
339
|
- **Scoped middleware** — `only:` / `except:` with glob patterns to target specific methods or namespaces
|
|
312
340
|
- **Instrumentation hooks** — `on(:request)`, `on(:response)`, `on(:error)` for read-only observability
|
|
313
341
|
- **Parameter validation** — `params_schema:` with JSON Schema types and enum constraints
|
|
@@ -351,6 +379,12 @@ run UltimateJsonRpc::Transport::Rack.new(server)
|
|
|
351
379
|
|
|
352
380
|
`UltimateJsonRpc::Transport::Rack` handles Content-Type, returns 200 for responses, 204 for notifications, and 405 for non-POST requests.
|
|
353
381
|
|
|
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:
|
|
383
|
+
|
|
384
|
+
```ruby
|
|
385
|
+
run UltimateJsonRpc::Transport::Rack.new(server, context: ->(env) { { user: env["warden"].user } })
|
|
386
|
+
```
|
|
387
|
+
|
|
354
388
|
#### MCP (Model Context Protocol)
|
|
355
389
|
|
|
356
390
|
Expose methods as AI tools via MCP:
|
|
@@ -380,6 +414,8 @@ ws = Faye::WebSocket.new(env)
|
|
|
380
414
|
ws_handler.call(env, ws)
|
|
381
415
|
```
|
|
382
416
|
|
|
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).
|
|
418
|
+
|
|
383
419
|
See `examples/websocket_server.ru` for a complete runnable example.
|
|
384
420
|
|
|
385
421
|
#### TCP
|
|
@@ -94,10 +94,90 @@ module UltimateJsonRpc
|
|
|
94
94
|
end
|
|
95
95
|
private_constant :ParamValidator
|
|
96
96
|
|
|
97
|
+
# Checks params against the callable's signature before it is called. Doing
|
|
98
|
+
# this up front, instead of rescuing ArgumentError around the call, means an
|
|
99
|
+
# ArgumentError raised inside the method body is never reported to the
|
|
100
|
+
# client as Invalid params.
|
|
101
|
+
module SignatureValidator
|
|
102
|
+
# What a callable accepts, worked out once when it is registered.
|
|
103
|
+
# +max_args+ is nil when there is no upper limit on positional arguments.
|
|
104
|
+
Signature = Data.define(:min_args, :max_args, :keywords, :required_keywords, :keyrest)
|
|
105
|
+
NO_PARAMS = {}.freeze
|
|
106
|
+
private_constant :Signature, :NO_PARAMS
|
|
107
|
+
|
|
108
|
+
private
|
|
109
|
+
|
|
110
|
+
def build_signature(callable)
|
|
111
|
+
names = signature_source(callable).parameters.group_by(&:first)
|
|
112
|
+
.transform_values { |list| list.map { |_, name| name.to_s } }
|
|
113
|
+
min_args, max_args = positional_range(callable, names)
|
|
114
|
+
Signature.new(
|
|
115
|
+
min_args:, max_args:, keyrest: names.key?(:keyrest),
|
|
116
|
+
keywords: names.values_at(:key, :keyreq).compact.flatten.freeze,
|
|
117
|
+
required_keywords: names.fetch(:keyreq, []).freeze
|
|
118
|
+
)
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
# A block (non-lambda Proc) ignores extra positional arguments and fills
|
|
122
|
+
# missing ones with nil, so any number of them is acceptable.
|
|
123
|
+
def positional_range(callable, names)
|
|
124
|
+
return [0, nil] if callable.is_a?(Proc) && !callable.lambda?
|
|
125
|
+
|
|
126
|
+
required = names.fetch(:req, []).size
|
|
127
|
+
[required, names.key?(:rest) ? nil : required + names.fetch(:opt, []).size]
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
# A callable object that is neither a Proc nor a Method describes its
|
|
131
|
+
# signature through its #call method.
|
|
132
|
+
def signature_source(callable) = callable.respond_to?(:parameters) ? callable : callable.method(:call)
|
|
133
|
+
|
|
134
|
+
def validate_signature!(signature, params)
|
|
135
|
+
case params
|
|
136
|
+
when Hash then check_keywords!(signature, params)
|
|
137
|
+
when Array, nil then check_keywords!(signature, NO_PARAMS)
|
|
138
|
+
else return
|
|
139
|
+
end
|
|
140
|
+
check_arity!(signature, params.is_a?(Array) ? params.size : 0)
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
def check_keywords!(signature, params)
|
|
144
|
+
reject_unknown_keywords!(signature, params) unless signature.keyrest
|
|
145
|
+
return if signature.required_keywords.empty?
|
|
146
|
+
|
|
147
|
+
missing = signature.required_keywords.reject { |name| params.key?(name) || params.key?(name.to_sym) }
|
|
148
|
+
return if missing.empty?
|
|
149
|
+
|
|
150
|
+
raise InvalidParams, "missing keyword#{"s" if missing.size > 1}: #{missing.map { |k| ":#{k}" }.join(", ")}"
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
def reject_unknown_keywords!(signature, params)
|
|
154
|
+
unknown = params.each_key.find { |key| !signature.keywords.include?(key.to_s) }
|
|
155
|
+
raise InvalidParams, "unknown keyword: #{unknown}" if unknown
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
def check_arity!(signature, given)
|
|
159
|
+
min = signature.min_args
|
|
160
|
+
max = signature.max_args
|
|
161
|
+
return if given >= min && (max.nil? || given <= max)
|
|
162
|
+
|
|
163
|
+
expected = if max.nil? then "#{min}+"
|
|
164
|
+
elsif max == min then min.to_s
|
|
165
|
+
else "#{min}..#{max}"
|
|
166
|
+
end
|
|
167
|
+
raise InvalidParams, "wrong number of arguments (given #{given}, expected #{expected})"
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
# A natively implemented callable (Math.method(:sqrt), :upcase.to_proc)
|
|
171
|
+
# may report its signature as "anything goes" and do its own arity check.
|
|
172
|
+
def native?(callable) = callable.respond_to?(:source_location) && callable.source_location.nil?
|
|
173
|
+
end
|
|
174
|
+
private_constant :SignatureValidator
|
|
175
|
+
|
|
97
176
|
class Handler
|
|
98
177
|
include ParamValidator
|
|
178
|
+
include SignatureValidator
|
|
99
179
|
|
|
100
|
-
Entry = Struct.new(:callable, :description, :returns, :deprecated, :params_schema)
|
|
180
|
+
Entry = Struct.new(:callable, :signature, :description, :returns, :deprecated, :params_schema)
|
|
101
181
|
private_constant :Entry
|
|
102
182
|
|
|
103
183
|
def initialize
|
|
@@ -122,6 +202,7 @@ module UltimateJsonRpc
|
|
|
122
202
|
validate_method_name!(name)
|
|
123
203
|
@entries[name] = Entry.new(
|
|
124
204
|
callable: callable,
|
|
205
|
+
signature: build_signature(callable),
|
|
125
206
|
description: description&.to_s,
|
|
126
207
|
returns: returns,
|
|
127
208
|
deprecated: normalize_deprecated(deprecated),
|
|
@@ -133,6 +214,7 @@ module UltimateJsonRpc
|
|
|
133
214
|
entry = @entries[method_name]
|
|
134
215
|
raise MethodNotFound, method_name unless entry
|
|
135
216
|
|
|
217
|
+
validate_signature!(entry.signature, params)
|
|
136
218
|
validate_params!(entry.callable, params, entry.params_schema)
|
|
137
219
|
invoke_callable(entry.callable, params)
|
|
138
220
|
end
|
|
@@ -191,8 +273,10 @@ module UltimateJsonRpc
|
|
|
191
273
|
def register_exposed(prefix:, method_name:, target:, descriptions:, returns:, deprecated:, params_schema:)
|
|
192
274
|
full_name = "#{prefix}#{method_name}"
|
|
193
275
|
validate_method_name!(full_name)
|
|
276
|
+
callable = target.method(method_name.to_sym)
|
|
194
277
|
@entries[full_name] = Entry.new(
|
|
195
|
-
callable:
|
|
278
|
+
callable: callable,
|
|
279
|
+
signature: build_signature(callable),
|
|
196
280
|
description: extract_metadata(descriptions, method_name)&.to_s,
|
|
197
281
|
returns: extract_metadata(returns, method_name),
|
|
198
282
|
deprecated: normalize_deprecated(extract_metadata(deprecated, method_name)),
|
|
@@ -266,43 +350,23 @@ module UltimateJsonRpc
|
|
|
266
350
|
end
|
|
267
351
|
end
|
|
268
352
|
|
|
269
|
-
|
|
270
|
-
private_constant :
|
|
353
|
+
NATIVE_ARITY_ERROR = /\Awrong number of arguments\b/
|
|
354
|
+
private_constant :NATIVE_ARITY_ERROR
|
|
271
355
|
|
|
356
|
+
# Only called after validate_signature!, so every Hash key is a keyword
|
|
357
|
+
# the callable accepts.
|
|
272
358
|
def invoke_callable(callable, params)
|
|
273
359
|
case params
|
|
274
360
|
when Array then callable.call(*params)
|
|
275
|
-
when Hash then callable.call(**
|
|
361
|
+
when Hash then callable.call(**params.transform_keys(&:to_sym))
|
|
276
362
|
when nil then callable.call
|
|
277
363
|
else raise InvalidParams, "params must be an Array, Hash, or nil"
|
|
278
364
|
end
|
|
279
365
|
rescue ArgumentError => e
|
|
280
|
-
raise InvalidParams, e.message if e.message.match?(
|
|
366
|
+
raise InvalidParams, e.message if native?(callable) && e.message.match?(NATIVE_ARITY_ERROR)
|
|
281
367
|
|
|
282
368
|
raise
|
|
283
369
|
end
|
|
284
|
-
|
|
285
|
-
def safe_symbolize_keys(callable, params)
|
|
286
|
-
return params.transform_keys(&:to_sym) if accepts_keyrest?(callable)
|
|
287
|
-
|
|
288
|
-
known = known_keyword_params(callable)
|
|
289
|
-
params.each_with_object({}) do |(k, v), h|
|
|
290
|
-
key = k.to_s
|
|
291
|
-
raise InvalidParams, "unknown keyword: #{key}" unless known.key?(key)
|
|
292
|
-
|
|
293
|
-
h[known[key]] = v
|
|
294
|
-
end
|
|
295
|
-
end
|
|
296
|
-
|
|
297
|
-
def known_keyword_params(callable)
|
|
298
|
-
callable.parameters.each_with_object({}) do |(type, name), map|
|
|
299
|
-
map[name.to_s] = name if name && %i[key keyreq].include?(type)
|
|
300
|
-
end
|
|
301
|
-
end
|
|
302
|
-
|
|
303
|
-
def accepts_keyrest?(callable)
|
|
304
|
-
callable.parameters.any? { |type, _| type == :keyrest }
|
|
305
|
-
end
|
|
306
370
|
end
|
|
307
371
|
end
|
|
308
372
|
end
|
|
@@ -7,12 +7,15 @@ module UltimateJsonRpc
|
|
|
7
7
|
|
|
8
8
|
attr_reader :method_name, :params, :id, :context
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
# +context+ seeds the request context, typically with what the transport
|
|
11
|
+
# knows about the caller. It is copied, so each request in a batch gets
|
|
12
|
+
# its own Hash to write to.
|
|
13
|
+
def initialize(data, context: nil)
|
|
11
14
|
validate!(data)
|
|
12
15
|
@method_name = data["method"].dup.freeze
|
|
13
16
|
@params = deep_freeze(deep_dup(data["params"]))
|
|
14
17
|
@id = data["id"].is_a?(String) ? data["id"].dup.freeze : data["id"]
|
|
15
|
-
@context = {}
|
|
18
|
+
@context = context ? context.dup : {}
|
|
16
19
|
end
|
|
17
20
|
|
|
18
21
|
def notification?
|
|
@@ -37,10 +37,13 @@ module UltimateJsonRpc
|
|
|
37
37
|
|
|
38
38
|
def build_mcp_server
|
|
39
39
|
mcp = Server.new(name: @app_server.name, version: @app_server.version, json: @json)
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
mcp.expose_method("
|
|
40
|
+
# Every handler takes ** because clients send params these handlers do not
|
|
41
|
+
# use (protocolVersion, capabilities, clientInfo, cursor, _meta, ...), and
|
|
42
|
+
# an undeclared keyword is rejected as Invalid params.
|
|
43
|
+
mcp.expose_method("initialize") { |**| mcp_initialize }
|
|
44
|
+
mcp.expose_method("notifications/initialized") { |**| nil }
|
|
45
|
+
mcp.expose_method("tools/list") { |**| mcp_tools_list }
|
|
46
|
+
mcp.expose_method("tools/call") { |name:, arguments: {}, **| mcp_tools_call(name, arguments) }
|
|
44
47
|
mcp
|
|
45
48
|
end
|
|
46
49
|
|
|
@@ -3,18 +3,18 @@
|
|
|
3
3
|
module UltimateJsonRpc
|
|
4
4
|
module Extras
|
|
5
5
|
module TestHelpers
|
|
6
|
-
def rpc_call(server, method, params: nil, id: 1)
|
|
6
|
+
def rpc_call(server, method, params: nil, id: 1, context: nil)
|
|
7
7
|
json = rpc_json_adapter(server)
|
|
8
8
|
request = { "jsonrpc" => "2.0", "method" => method, "id" => id }
|
|
9
9
|
request["params"] = params if params
|
|
10
|
-
json.parse(server.handle(json.generate(request)))
|
|
10
|
+
json.parse(server.handle(json.generate(request), context:))
|
|
11
11
|
end
|
|
12
12
|
|
|
13
|
-
def rpc_notify(server, method, params: nil)
|
|
13
|
+
def rpc_notify(server, method, params: nil, context: nil)
|
|
14
14
|
json = rpc_json_adapter(server)
|
|
15
15
|
request = { "jsonrpc" => "2.0", "method" => method }
|
|
16
16
|
request["params"] = params if params
|
|
17
|
-
server.handle(json.generate(request))
|
|
17
|
+
server.handle(json.generate(request), context:)
|
|
18
18
|
end
|
|
19
19
|
|
|
20
20
|
def rpc_batch(server, *requests)
|
|
@@ -3,6 +3,12 @@
|
|
|
3
3
|
require "timeout"
|
|
4
4
|
|
|
5
5
|
module UltimateJsonRpc
|
|
6
|
+
InvalidRequest = Core::InvalidRequest
|
|
7
|
+
InvalidParams = Core::InvalidParams
|
|
8
|
+
MethodNotFound = Core::MethodNotFound
|
|
9
|
+
ApplicationError = Core::ApplicationError
|
|
10
|
+
ServerError = Core::ServerError
|
|
11
|
+
|
|
6
12
|
GENERIC_ERROR_DATA = "Internal server error"
|
|
7
13
|
GENERIC_PARAMS_DATA = "Invalid method parameters"
|
|
8
14
|
private_constant :GENERIC_ERROR_DATA, :GENERIC_PARAMS_DATA
|
|
@@ -10,36 +16,36 @@ module UltimateJsonRpc
|
|
|
10
16
|
module BatchProcessor
|
|
11
17
|
private
|
|
12
18
|
|
|
13
|
-
def handle_batch(requests)
|
|
19
|
+
def handle_batch(requests, context)
|
|
14
20
|
return @json.generate(Core::Response.error(Core::INVALID_REQUEST, nil)) if requests.empty?
|
|
15
21
|
if batch_too_large?(requests)
|
|
16
22
|
return @json.generate(Core::Response.error(Core::INVALID_REQUEST, nil, data: "Batch too large"))
|
|
17
23
|
end
|
|
18
24
|
|
|
19
|
-
json_parts = process_batch_items(requests)
|
|
25
|
+
json_parts = process_batch_items(requests, context)
|
|
20
26
|
json_parts.empty? ? nil : "[#{json_parts.join(",")}]"
|
|
21
27
|
end
|
|
22
28
|
|
|
23
|
-
def process_batch_items(requests)
|
|
29
|
+
def process_batch_items(requests, context)
|
|
24
30
|
if @concurrent_batches
|
|
25
|
-
pool_dispatch(requests).compact
|
|
31
|
+
pool_dispatch(requests) { |req| safe_serialize(req, context) }.compact
|
|
26
32
|
else
|
|
27
|
-
requests.filter_map { |req| serialize_single(req) }
|
|
33
|
+
requests.filter_map { |req| serialize_single(req, context) }
|
|
28
34
|
end
|
|
29
35
|
end
|
|
30
36
|
|
|
31
|
-
def pool_dispatch(requests)
|
|
37
|
+
def pool_dispatch(requests, &)
|
|
32
38
|
queue = Queue.new
|
|
33
39
|
requests.each_with_index { |req, i| queue << [req, i] }
|
|
34
40
|
results = Array.new(requests.size)
|
|
35
|
-
spawn_workers(queue:, results:, pool_size: [requests.size, @max_concurrency].min)
|
|
41
|
+
spawn_workers(queue:, results:, pool_size: [requests.size, @max_concurrency].min, &)
|
|
36
42
|
results
|
|
37
43
|
end
|
|
38
44
|
|
|
39
|
-
def spawn_workers(queue:, results:, pool_size
|
|
45
|
+
def spawn_workers(queue:, results:, pool_size:, &work)
|
|
40
46
|
mutex = Mutex.new
|
|
41
47
|
pool_size.times.map do
|
|
42
|
-
Thread.new { drain_queue(queue, results, mutex) }
|
|
48
|
+
Thread.new { drain_queue(queue, results, mutex, &work) }
|
|
43
49
|
end.each(&:join)
|
|
44
50
|
end
|
|
45
51
|
|
|
@@ -50,13 +56,13 @@ module UltimateJsonRpc
|
|
|
50
56
|
rescue ThreadError
|
|
51
57
|
break
|
|
52
58
|
end
|
|
53
|
-
result =
|
|
59
|
+
result = yield req
|
|
54
60
|
mutex.synchronize { results[i] = result }
|
|
55
61
|
end
|
|
56
62
|
end
|
|
57
63
|
|
|
58
|
-
def safe_serialize(data)
|
|
59
|
-
serialize_single(data)
|
|
64
|
+
def safe_serialize(data, context)
|
|
65
|
+
serialize_single(data, context)
|
|
60
66
|
rescue Exception # rubocop:disable Lint/RescueException -- worker threads must never die silently
|
|
61
67
|
id = data.is_a?(Hash) ? extract_id(data) : nil
|
|
62
68
|
begin
|
|
@@ -193,20 +199,25 @@ module UltimateJsonRpc
|
|
|
193
199
|
self
|
|
194
200
|
end
|
|
195
201
|
|
|
196
|
-
|
|
202
|
+
# +context+ is a Hash of what the transport knows about the caller (Rack
|
|
203
|
+
# env, authenticated user, ...). Each request starts with a copy of it as
|
|
204
|
+
# its +request.context+.
|
|
205
|
+
def handle(json_string, context: nil)
|
|
197
206
|
data = @json.parse(json_string)
|
|
198
207
|
rescue StandardError
|
|
199
208
|
@json.generate(Core::Response.error(Core::PARSE_ERROR, nil))
|
|
200
209
|
else
|
|
201
|
-
handle_parsed(data)
|
|
210
|
+
handle_parsed(data, context:)
|
|
202
211
|
end
|
|
203
212
|
|
|
204
213
|
alias call handle
|
|
205
214
|
|
|
206
|
-
def handle_parsed(data)
|
|
215
|
+
def handle_parsed(data, context: nil)
|
|
216
|
+
raise ArgumentError, "context must be a Hash" unless context.nil? || context.is_a?(Hash)
|
|
217
|
+
|
|
207
218
|
case data
|
|
208
|
-
when Array then handle_batch(data)
|
|
209
|
-
when Hash then serialize_single(data)
|
|
219
|
+
when Array then handle_batch(data, context)
|
|
220
|
+
when Hash then serialize_single(data, context)
|
|
210
221
|
else @json.generate(Core::Response.error(Core::INVALID_REQUEST, nil))
|
|
211
222
|
end
|
|
212
223
|
end
|
|
@@ -235,8 +246,8 @@ module UltimateJsonRpc
|
|
|
235
246
|
|
|
236
247
|
private
|
|
237
248
|
|
|
238
|
-
def serialize_single(data)
|
|
239
|
-
request = parse_request(data)
|
|
249
|
+
def serialize_single(data, context = nil)
|
|
250
|
+
request = parse_request(data, context)
|
|
240
251
|
return request unless request.is_a?(Core::Request)
|
|
241
252
|
|
|
242
253
|
response = execute_request(request)
|
|
@@ -255,8 +266,8 @@ module UltimateJsonRpc
|
|
|
255
266
|
end
|
|
256
267
|
end
|
|
257
268
|
|
|
258
|
-
def parse_request(data)
|
|
259
|
-
Core::Request.new(data)
|
|
269
|
+
def parse_request(data, context)
|
|
270
|
+
Core::Request.new(data, context:)
|
|
260
271
|
rescue Core::InvalidRequest
|
|
261
272
|
@json.generate(Core::Response.error(Core::INVALID_REQUEST, extract_id(data)))
|
|
262
273
|
end
|
|
@@ -275,7 +286,7 @@ module UltimateJsonRpc
|
|
|
275
286
|
|
|
276
287
|
def timed_dispatch(request)
|
|
277
288
|
start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
278
|
-
result = with_timeout { build_chain(request).call }
|
|
289
|
+
result = with_current_request(request) { with_timeout { build_chain(request).call } }
|
|
279
290
|
duration = elapsed(start)
|
|
280
291
|
emit(:response, request, result, duration)
|
|
281
292
|
[result, nil, duration]
|
|
@@ -329,6 +340,16 @@ module UltimateJsonRpc
|
|
|
329
340
|
->(name) { patterns.public_send(check) { |p| p.include?("*") ? File.fnmatch(p, name) : p == name } }
|
|
330
341
|
end
|
|
331
342
|
|
|
343
|
+
# Restores the previous value so a server called from inside another
|
|
344
|
+
# server's method (as the MCP adapter does) does not clobber it.
|
|
345
|
+
def with_current_request(request)
|
|
346
|
+
previous = Fiber[CURRENT_REQUEST_KEY]
|
|
347
|
+
Fiber[CURRENT_REQUEST_KEY] = request
|
|
348
|
+
yield
|
|
349
|
+
ensure
|
|
350
|
+
Fiber[CURRENT_REQUEST_KEY] = previous
|
|
351
|
+
end
|
|
352
|
+
|
|
332
353
|
def with_timeout(&)
|
|
333
354
|
return yield unless @timeout
|
|
334
355
|
|
|
@@ -8,8 +8,14 @@ module UltimateJsonRpc
|
|
|
8
8
|
NOT_ALLOWED_HEADERS = CONTENT_TYPE.merge("allow" => "POST").freeze
|
|
9
9
|
UNSUPPORTED_MEDIA_BODY = '{"jsonrpc":"2.0","error":{"code":-32600,"message":"Unsupported Media Type"},"id":null}'
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
# +context+ is an optional callable that turns the Rack env into the
|
|
12
|
+
# request context, e.g. <tt>->(env) { { user: env["warden"].user } }</tt>.
|
|
13
|
+
# Without it the context is <tt>{ rack_env: env }</tt>.
|
|
14
|
+
def initialize(server, context: nil)
|
|
15
|
+
raise ArgumentError, "context must respond to #call" unless context.nil? || context.respond_to?(:call)
|
|
16
|
+
|
|
12
17
|
@server = server
|
|
18
|
+
@context = context
|
|
13
19
|
end
|
|
14
20
|
|
|
15
21
|
def call(env)
|
|
@@ -18,7 +24,7 @@ module UltimateJsonRpc
|
|
|
18
24
|
return unsupported_media_type unless acceptable_content_type?(env)
|
|
19
25
|
|
|
20
26
|
body = env["rack.input"]&.read.to_s
|
|
21
|
-
response = @server.handle(body)
|
|
27
|
+
response = @server.handle(body, context: build_context(env))
|
|
22
28
|
|
|
23
29
|
if response
|
|
24
30
|
[200, CONTENT_TYPE.dup, [response]]
|
|
@@ -34,6 +40,8 @@ module UltimateJsonRpc
|
|
|
34
40
|
|
|
35
41
|
private
|
|
36
42
|
|
|
43
|
+
def build_context(env) = @context ? @context.call(env) : { rack_env: env }
|
|
44
|
+
|
|
37
45
|
def method_not_allowed
|
|
38
46
|
[405, NOT_ALLOWED_HEADERS.dup, [NOT_ALLOWED_BODY]]
|
|
39
47
|
end
|
|
@@ -5,17 +5,24 @@ module UltimateJsonRpc
|
|
|
5
5
|
class WebSocket
|
|
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>.
|
|
11
|
+
def initialize(server, context: nil)
|
|
12
|
+
raise ArgumentError, "context must respond to #call" unless context.nil? || context.respond_to?(:call)
|
|
13
|
+
|
|
9
14
|
@server = server
|
|
15
|
+
@context = context
|
|
10
16
|
end
|
|
11
17
|
|
|
12
|
-
def on_message(data)
|
|
13
|
-
@server.handle(data.to_s)
|
|
18
|
+
def on_message(data, context: nil)
|
|
19
|
+
@server.handle(data.to_s, context:)
|
|
14
20
|
end
|
|
15
21
|
|
|
16
|
-
def call(
|
|
22
|
+
def call(env, socket)
|
|
23
|
+
context = @context ? @context.call(env) : { rack_env: env }
|
|
17
24
|
socket.on(:message) do |event|
|
|
18
|
-
response = on_message(event.respond_to?(:data) ? event.data : event)
|
|
25
|
+
response = on_message(event.respond_to?(:data) ? event.data : event, context:)
|
|
19
26
|
socket.send(response) if response
|
|
20
27
|
end
|
|
21
28
|
end
|
data/lib/ultimate_json_rpc.rb
CHANGED
|
@@ -7,6 +7,18 @@ module UltimateJsonRpc
|
|
|
7
7
|
module Core
|
|
8
8
|
class Error < StandardError; end
|
|
9
9
|
end
|
|
10
|
+
|
|
11
|
+
CURRENT_REQUEST_KEY = :ultimate_json_rpc_current_request
|
|
12
|
+
private_constant :CURRENT_REQUEST_KEY
|
|
13
|
+
|
|
14
|
+
# The request being dispatched on the current fiber, or nil outside a
|
|
15
|
+
# dispatch. This is how an exposed method reaches the request context:
|
|
16
|
+
#
|
|
17
|
+
# def self.whoami = UltimateJsonRpc.current_request.context[:user]
|
|
18
|
+
#
|
|
19
|
+
# Set while the middleware chain and the method run. Fibers and threads
|
|
20
|
+
# started from there see the same request.
|
|
21
|
+
def self.current_request = Fiber[CURRENT_REQUEST_KEY]
|
|
10
22
|
end
|
|
11
23
|
|
|
12
24
|
require_relative "ultimate_json_rpc/core/errors"
|
data/sig/ultimate_json_rpc.rbs
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
module UltimateJsonRpc
|
|
2
2
|
VERSION: String
|
|
3
3
|
|
|
4
|
+
def self.current_request: () -> Core::Request?
|
|
5
|
+
|
|
4
6
|
module Core
|
|
5
7
|
class Error < StandardError
|
|
6
8
|
end
|
|
@@ -56,7 +58,7 @@ module UltimateJsonRpc
|
|
|
56
58
|
attr_reader id: String | Numeric | nil
|
|
57
59
|
attr_reader context: Hash[Symbol, untyped]
|
|
58
60
|
|
|
59
|
-
def initialize: (Hash[String, untyped]) -> void
|
|
61
|
+
def initialize: (Hash[String, untyped], ?context: Hash[Symbol, untyped]?) -> void
|
|
60
62
|
def notification?: () -> bool
|
|
61
63
|
end
|
|
62
64
|
|
|
@@ -110,9 +112,9 @@ module UltimateJsonRpc
|
|
|
110
112
|
def expose_errors?: () -> bool
|
|
111
113
|
def concurrent_batches?: () -> bool
|
|
112
114
|
def method?: (String) -> bool
|
|
113
|
-
def handle: (String) -> String?
|
|
115
|
+
def handle: (String, ?context: Hash[Symbol, untyped]?) -> String?
|
|
114
116
|
alias call handle
|
|
115
|
-
def handle_parsed: (untyped) -> String?
|
|
117
|
+
def handle_parsed: (untyped, ?context: Hash[Symbol, untyped]?) -> String?
|
|
116
118
|
def methods_list: () -> Array[String]
|
|
117
119
|
def methods_info: () -> Array[Hash[String, untyped]]
|
|
118
120
|
def size: () -> Integer
|
|
@@ -129,7 +131,7 @@ module UltimateJsonRpc
|
|
|
129
131
|
end
|
|
130
132
|
|
|
131
133
|
class Rack
|
|
132
|
-
def initialize: (Server) -> void
|
|
134
|
+
def initialize: (Server, ?context: (^(Hash[String, untyped]) -> Hash[Symbol, untyped])?) -> void
|
|
133
135
|
def call: (Hash[String, untyped]) -> [Integer, Hash[String, String], Array[String]]
|
|
134
136
|
def freeze: () -> self
|
|
135
137
|
end
|
|
@@ -148,8 +150,8 @@ module UltimateJsonRpc
|
|
|
148
150
|
class WebSocket
|
|
149
151
|
attr_reader server: Server
|
|
150
152
|
|
|
151
|
-
def initialize: (Server) -> void
|
|
152
|
-
def on_message: (untyped) -> String?
|
|
153
|
+
def initialize: (Server, ?context: (^(Hash[String, untyped]) -> Hash[Symbol, untyped])?) -> void
|
|
154
|
+
def on_message: (untyped, ?context: Hash[Symbol, untyped]?) -> String?
|
|
153
155
|
def call: (untyped, untyped) -> void
|
|
154
156
|
def freeze: () -> self
|
|
155
157
|
end
|
|
@@ -197,8 +199,8 @@ module UltimateJsonRpc
|
|
|
197
199
|
end
|
|
198
200
|
|
|
199
201
|
module TestHelpers
|
|
200
|
-
def rpc_call: (Server, String, ?params: untyped, ?id: String | Integer) -> Hash[String, untyped]
|
|
201
|
-
def rpc_notify: (Server, String, ?params: untyped) -> String?
|
|
202
|
+
def rpc_call: (Server, String, ?params: untyped, ?id: String | Integer, ?context: Hash[Symbol, untyped]?) -> Hash[String, untyped]
|
|
203
|
+
def rpc_notify: (Server, String, ?params: untyped, ?context: Hash[Symbol, untyped]?) -> String?
|
|
202
204
|
def rpc_batch: (Server, *Hash[String, untyped]) -> Array[Hash[String, untyped]]?
|
|
203
205
|
def assert_rpc_success: (Hash[String, untyped], ?expected: untyped, ?msg: String?) -> void
|
|
204
206
|
def assert_rpc_error: (Hash[String, untyped], ?code: Integer?, ?message: String?, ?msg: String?) -> void
|
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.
|
|
4
|
+
version: 1.1.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Andriy Tyurnikov
|
|
@@ -69,7 +69,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
|
|
|
69
69
|
- !ruby/object:Gem::Version
|
|
70
70
|
version: '0'
|
|
71
71
|
requirements: []
|
|
72
|
-
rubygems_version: 4.0.
|
|
72
|
+
rubygems_version: 4.0.20
|
|
73
73
|
specification_version: 4
|
|
74
74
|
summary: Expose Ruby objects through JSON-RPC
|
|
75
75
|
test_files: []
|