1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
//! ajj: A JSON-RPC router inspired by axum's `Router`.
//!
//! This crate provides a way to define a JSON-RPC router that can be used to
//! route requests to handlers. It is inspired by the [`axum`] crate's
//! [`axum::Router`].
//!
//! ## Basic usage
//!
//! The [`Router`] type is the main type provided by this crate. It is used to
//! register JSON-RPC methods and their handlers.
//!
//! ```no_run
//! use ajj::{Router, HandlerCtx, ResponsePayload};
//!
//! # fn test_fn() -> Router<()> {
//! // Provide methods called "double" and "add" to the router.
//! let router = Router::<u64>::new()
//! .route("add", |params: u64, state: u64| async move {
//! Ok::<_, ()>(params + state)
//! })
//! .with_state(3u64)
//! .route("double", |params: u64| async move {
//! Ok::<_, ()>(params * 2)
//! })
//! // Routes get a ctx, which can be used to send notifications.
//! .route("notify", |ctx: HandlerCtx| async move {
//! if ctx.notifications().is_none() {
//! // This error will appear in the ResponsePayload's `data` field.
//! return Err("notifications are disabled");
//! }
//!
//! let req_id = 15u8;
//!
//! tokio::task::spawn_blocking(move || {
//! // something expensive goes here
//! let result = 100_000_000;
//! let _ = ctx.notify(&serde_json::json!({
//! "req_id": req_id,
//! "result": result,
//! }));
//! });
//! Ok(req_id)
//! })
//! .route("error_example", || async {
//! // This will appear in the ResponsePayload's `message` field.
//! ResponsePayload::<(), ()>::internal_error_message("this is an error".into())
//! });
//! # router
//! # }
//! ```
//!
//! ## Handlers
//!
//! Methods are routed via the [`Handler`] trait, which is blanket implemented
//! for many async functions. [`Handler`] contain implement the logic executed
//! when calling methods on the JSON-RPC router.
//!
//! Handlers can return either
//! - `Result<T, E> where T: Serialize, E: Serialize`
//! - `ResponsePayload<T, E> where T: Serialize, E: Serialize`
//!
//! These types will be serialized into the JSON-RPC response. The `T` type
//! represents the result of the method, and the `E` type represents an error
//! response. The `E` type is optional, and can be set to `()` if no error
//! response is needed.
//!
//! See the [`Handler`] trait docs for more information.
//!
//! ## Serving the Router
//!
//! We recommend [`axum`] for serving the router over HTTP. When the `"axum"`
//! feature flag is enabled, The [`Router`] provides
//! `Router::into_axum(path: &str)` to instantiate a new [`axum::Router`], and
//! register the router to handle requests. You can then serve the
//! [`axum::Router`] as normal, or add additional routes to it.
//!
//! ```no_run
//! # #[cfg(feature = "axum")]
//! # {
//! # use ajj::{Router, HandlerCtx, ResponsePayload};
//! # async fn _main(router: Router<()>) {
//! // Instantiate a new axum router, and register the JSON-RPC router to handle
//! // requests at the `/rpc` path, and serve it on port 3000.
//! let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
//! axum::serve(listener, router.into_axum("/rpc")).await.unwrap();
//! # }}
//! ```
//!
//! Routers can also be served over axum websockets. When both `axum` and
//! `pubsub` features are enabled, the `pubsub` module provides
//! [`pubsub::AxumWsCfg`] and the [`pubsub::ajj_websocket`] axum handler. This
//! handler will serve the router over websockets at a specific route. The
//! router is a property of the `AxumWsCfg` object, and is passed to the
//! handler via axum's `State` extractor.
//!
//! ```no_run
//! # #[cfg(all(feature = "axum", feature = "pubsub"))]
//! # use ajj::{Router, pubsub::{ajj_websocket, AxumWsCfg}};
//! # {
//! # async fn _main(router: Router<()>, axum: axum::Router<AxumWsCfg>) -> axum::Router<()>{
//! // The config object contains the tokio runtime handle, and the
//! // notification buffer size.
//! let cfg = AxumWsCfg::new(router);
//!
//! axum
//! .route("/ws", axum::routing::any(ajj_websocket))
//! .with_state(cfg)
//! # }}
//! ```
//!
//! For IPC and non-axum WebSocket connections, the `pubsub` module provides
//! implementations of the `Connect` trait for [`std::net::SocketAddr`] to
//! create simple WS servers, and
//! [`interprocess::local_socket::ListenerOptions`] to create simple IPC
//! servers. We generally recommend using `axum` for WebSocket connections, as
//! it provides a more complete and robust implementation, however, users
//! needing additional control, or wanting to avoid the `axum` dependency
//! can use the `pubsub` module directly.
//!
//! ```no_run
//! # #[cfg(feature = "pubsub")]
//! # {
//! # use ajj::{Router, pubsub::Connect};
//! # async fn _main(router:Router<()>) {
//! // Serve the router over websockets on port 3000.
//! let addr = std::net::SocketAddr::from(([0, 0, 0, 0], 3000));
//! // The shutdown object will stop the server when dropped.
//! let shutdown = addr.serve(router).await.unwrap();
//! # }}
//! ```
//!
//!
//! [`axum`]: https://docs.rs/axum/latest/axum/index.html
//! [`axum::Router`]: https://docs.rs/axum/latest/axum/routing/struct.Router.html
//! [`ResponsePayload`]: alloy::rpc::json_rpc::ResponsePayload
//! [`interprocess::local_socket::ListenerOptions`]: https://docs.rs/interprocess/latest/interprocess/local_socket/struct.ListenerOptions.html
pub
pub use RegistrationError;
pub use ;
// for tests
pub use ReadJsonStream;
pub use ;
pub use ;
pub use Router;
pub use TaskSet;
pub use ;
/// Re-export of the `tower` crate, primarily to provide [`tower::Service`],
/// and [`tower::service_fn`].
pub use tower;
/// Re-export of the `serde_json` crate, primarily to provide the `RawValue` type.
pub use ;
pub
// Some code is this file is reproduced under the terms of the MIT license. It
// originates from the `axum` crate. The original source code can be found at
// the following URL, and the original license is included below.
//
// https://github.com/tokio-rs/axum/blob/f84105ae8b078109987b089c47febc3b544e6b80/axum/src/routing/mod.rs#L119
//
// The MIT License (MIT)
//
// Copyright (c) 2019 Axum Contributors
//
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice
// shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.