Skip to main content

ledger_engine/
server.rs

1//! API server: JSON-RPC over HTTP and WebSocket on one port, as in Clio.
2//!
3//! HTTP: `POST /` with `{"method": ..., "params": [{...}]}`, response is
4//! `{"result": {..., "status": "success"}}`. WebSocket: `GET /` with an
5//! upgrade, requests `{"command": ..., "id": ..., ...}`, response is `result`
6//! plus `id`, `api_version`, `status`, `type` at the top level. Errors follow
7//! Clio: inside `result` over HTTP, at the top level over WebSocket.
8//!
9//! Requests are served on a blocking task pool (fjall and zstd are synchronous),
10//! at most `MAX_INFLIGHT` at a time; proof bundles have their own
11//! budget, `MAX_PROOFS`, and no queue: when it is full they are refused with `tooBusy`.
12//! Requests to a node have their own budget too, `MAX_FORWARDS`, so that nodes
13//! that stopped answering can't hold the slots that reads need. A request waits
14//! at most `QUEUE_WAIT` for a slot and has `REQUEST_LIMIT` to finish (`limits`);
15//! past either it ends with `tooBusy`.
16//!
17//! Public listeners (`PublicConfig`) are a separate door to the same data: their
18//! slots are their own, so public load can't fill those of `--api-addr`, the
19//! limits of `guard` apply there and only there, and when the other door has
20//! fewer than `OWN_HEADROOM` free slots they step aside with `tooBusy`. This
21//! protects the queue, not the machine: disk and CPU stay shared, which is why
22//! the public slots are few.
23//!
24//! subscribe and unsubscribe work only over WebSocket; `subs` keeps the subscriptions.
25//! A session interleaves responses to requests with messages from its queue.
26//!
27//! Node methods and requests about the current ledger (`forward::forwarded`) go to
28//! xrpld; the response follows Clio:
29//! the node's `result` as is, with `forwarded: true`, `status`, `type` on top.
30//!
31//! Clients are limited per address by `guard` when it is configured.
32//!
33//! HTTP answers say whether they can be cached: an answer about a ledger named
34//! by sequence or hash, or about a transaction, never changes once given, and
35//! gets `Cache-Control: public, max-age=86400, immutable`; everything else
36//! gets `no-store`. A cache in front can rely on that. JSON-RPC requests are
37//! POSTs, which CDNs don't cache on their own, so the cache keys on the body.
38
39use std::net::SocketAddr;
40use std::sync::Arc;
41use std::time::Instant;
42
43use axum::Router;
44use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
45use axum::extract::{ConnectInfo, DefaultBodyLimit, State};
46use axum::http::HeaderMap;
47use axum::response::{IntoResponse, Response};
48use axum::routing::get;
49use futures_util::SinkExt;
50use serde_json::{Map, Value, json};
51use tokio::sync::{OwnedSemaphorePermit, Semaphore};
52use tracing::{info, warn};
53
54use crate::api::{Engine, RpcError, api_version};
55use crate::forward::{Forwarder, forwarded, node_info, submission, submission_params};
56use crate::guard::{Guard, GuardConfig, weight};
57use crate::metrics::{self, lock};
58use crate::subs::{self, Hub};
59
60const MAX_INFLIGHT: usize = 32;
61/// Proof bundles are expensive to build: at most this many at a time.
62const MAX_PROOFS: usize = 4;
63/// Requests to a node at a time.
64const MAX_FORWARDS: usize = 16;
65/// How long a request waits for a slot before it is refused.
66const QUEUE_WAIT: std::time::Duration = std::time::Duration::from_secs(5);
67/// The same on a public listener, and how long a request may run there.
68const PUBLIC_QUEUE_WAIT: std::time::Duration = std::time::Duration::from_millis(500);
69const PUBLIC_REQUEST_LIMIT: std::time::Duration = std::time::Duration::from_secs(5);
70/// A public listener refuses requests when `--api-addr` has fewer free slots than this.
71const OWN_HEADROOM: usize = 8;
72/// Largest request a public listener takes, over HTTP or in one WebSocket message.
73const PUBLIC_MESSAGE: usize = 256 * 1024;
74/// Methods a public listener doesn't take: they change the network or make a
75/// node do unbounded work on behalf of a stranger.
76const NOT_PUBLIC: [&str; 3] = ["submit", "simulate", "ripple_path_find"];
77/// `/health` reports a problem when the last ledger is older than this; ledgers
78/// close every 3 to 5 seconds, and a network-wide pause has been seen to last 49.
79const HEALTHY_AGE: i64 = 60;
80/// How long one request may run (see `limits`). Real requests take well under
81/// a second; the slowest, a full `ledger_data` page, about 0.7 s.
82const REQUEST_LIMIT: std::time::Duration = std::time::Duration::from_secs(10);
83/// Built bundles per ledger and transaction kept in memory; they never change.
84const PROOF_CACHE: usize = 128;
85/// How long a cache may keep an answer that never changes. A day rather than
86/// a year, so a wrong answer, should one ever be served, doesn't outlive a fix.
87const IMMUTABLE: &str = "public, max-age=86400, immutable";
88
89type ProofCache = std::sync::Mutex<std::collections::VecDeque<(String, Map<String, Value>)>>;
90
91/// How the server listens beyond its addresses.
92#[derive(Debug, Clone, Default)]
93pub struct ServeConfig {
94    /// Limits per client on `--api-addr`; off when there is a public listener.
95    pub own_limits: GuardConfig,
96    /// Forward `submit` and `simulate` on `--api-addr`.
97    pub forward_submissions: bool,
98    pub public: Option<PublicConfig>,
99}
100
101/// Listeners for strangers, with their own slots and limits.
102#[derive(Debug, Clone)]
103pub struct PublicConfig {
104    pub addrs: Vec<SocketAddr>,
105    pub limits: GuardConfig,
106    pub max_inflight: usize,
107    pub max_proofs: usize,
108    pub max_forwards: usize,
109    pub max_sessions: usize,
110    pub max_accounts: usize,
111}
112
113/// What differs between `--api-addr` and a public listener.
114#[derive(Debug, Clone)]
115struct Public {
116    /// Slots of `--api-addr`, to step aside when they run low.
117    own_inflight: Arc<Semaphore>,
118    sessions: Arc<Semaphore>,
119    max_accounts: usize,
120}
121
122#[derive(Debug, Clone)]
123struct Shared {
124    engine: Arc<Engine>,
125    inflight: Arc<Semaphore>,
126    proofs: Arc<Semaphore>,
127    forwards: Arc<Semaphore>,
128    cache: Arc<ProofCache>,
129    forwarder: Option<Arc<Forwarder>>,
130    hub: Arc<Hub>,
131    metrics: metrics::Shared,
132    guard: Arc<Guard>,
133    forward_submissions: bool,
134    public: Option<Public>,
135}
136
137fn too_busy() -> RpcError {
138    RpcError {
139        error: "tooBusy",
140        code: 9,
141        message: "The server is too busy to help you now.".into(),
142    }
143}
144
145fn internal(e: impl std::fmt::Display) -> RpcError {
146    RpcError {
147        error: "internal",
148        code: 73,
149        message: e.to_string(),
150    }
151}
152
153fn unknown_method() -> RpcError {
154    RpcError {
155        error: "unknownCmd",
156        code: 32,
157        message: "Unknown method.".into(),
158    }
159}
160
161impl Shared {
162    /// A public listener steps aside while the other one is short of slots.
163    fn must_step_aside(&self) -> bool {
164        self.public
165            .as_ref()
166            .is_some_and(|p| p.own_inflight.available_permits() < OWN_HEADROOM)
167    }
168
169    /// A slot from `pool`, waiting only so long.
170    async fn slot(&self, pool: &Arc<Semaphore>) -> Result<OwnedSemaphorePermit, RpcError> {
171        if self.must_step_aside() {
172            return Err(too_busy());
173        }
174        let wait = if self.public.is_some() {
175            PUBLIC_QUEUE_WAIT
176        } else {
177            QUEUE_WAIT
178        };
179        match tokio::time::timeout(wait, pool.clone().acquire_owned()).await {
180            Ok(Ok(permit)) => Ok(permit),
181            Ok(Err(e)) => Err(internal(e)),
182            Err(_) => Err(too_busy()),
183        }
184    }
185
186    /// The name a request is counted under: public traffic apart from our own.
187    fn transport(&self, own: &'static str, public: &'static str) -> &'static str {
188        if self.public.is_some() { public } else { own }
189    }
190}
191
192fn slow_down() -> RpcError {
193    RpcError {
194        error: "slowDown",
195        code: 10,
196        message: "You are placing too much load on the server.".into(),
197    }
198}
199
200/// Clio's answer to a client over its limit over HTTP: 503 with the error.
201fn slow_down_http() -> Response {
202    let e = slow_down();
203    let body = json!({
204        "error": e.error,
205        "error_code": e.code,
206        "error_message": e.message,
207        "status": "error",
208        "type": "response",
209    });
210    (
211        axum::http::StatusCode::SERVICE_UNAVAILABLE,
212        [(axum::http::header::CONTENT_TYPE, "text/plain")],
213        body.to_string(),
214    )
215        .into_response()
216}
217
218/// Methods whose answer depends only on the ledger asked for.
219const FIXED_BY_LEDGER: [&str; 22] = [
220    "account_info",
221    "account_lines",
222    "account_mptoken_issuances",
223    "account_mptokens",
224    "account_nfts",
225    "account_objects",
226    "account_offers",
227    "account_tx",
228    "book_changes",
229    "feature",
230    "ledger",
231    "ledger_data",
232    "ledger_entry",
233    "mpt_holders",
234    "nft_buy_offers",
235    "nft_history",
236    "nft_info",
237    "nft_sell_offers",
238    "nfts_by_issuer",
239    "proof_entry",
240    "proof_ledger",
241    "vault_info",
242];
243
244/// Whether a successful answer of our own can never change: about a
245/// transaction, or about a ledger named by sequence or hash. Errors and
246/// forwarded answers can.
247fn immutable(method: &str, params: &Map<String, Value>, result: &Result<Reply, RpcError>) -> bool {
248    if !matches!(result, Ok(Reply::Own(_))) {
249        return false;
250    }
251    let fixed = params.get("ledger_hash").is_some_and(Value::is_string)
252        || params
253            .get("ledger_index")
254            .is_some_and(|v| v.is_u64() || v.as_str().is_some_and(|s| s.parse::<u32>().is_ok()));
255    match method {
256        "tx" | "proof_tx" => true,
257        // A range bound alongside the ledger is an error anyway; a marker
258        // pages within the same fixed ledger.
259        m if FIXED_BY_LEDGER.contains(&m) => fixed,
260        _ => false,
261    }
262}
263
264/// Counts a finished request and its response. A method name a client made up
265/// would be a new series each time, so names the server didn't take are
266/// counted as `other`.
267fn record(
268    s: &Shared,
269    transport: &'static str,
270    method: &str,
271    result: &Result<Reply, RpcError>,
272    started: Instant,
273    bytes: usize,
274) {
275    let status = status_of(result);
276    if status == "tooBusy" {
277        reject(s, "busy");
278    }
279    let known = !matches!(status.as_str(), "unknownCmd" | "badSyntax")
280        && (1..=40).contains(&method.len())
281        && method.bytes().all(|b| b.is_ascii_lowercase() || b == b'_');
282    let method = if known { method } else { "other" };
283    let forwarded = matches!(result, Ok(Reply::Forwarded(_)));
284    lock(&s.metrics).api.record(
285        transport,
286        method,
287        &status,
288        started.elapsed().as_secs_f64(),
289        bytes,
290        forwarded,
291    );
292}
293
294/// Counts a request refused to protect the server: over the client's
295/// connections or budget, at the cap of public sessions, or without a free
296/// slot in time (`busy`).
297fn reject(s: &Shared, reason: &'static str) {
298    let door = if s.public.is_some() { "public" } else { "own" };
299    *lock(&s.metrics)
300        .api
301        .rejected
302        .entry((door, reason))
303        .or_default() += 1;
304}
305
306/// `success`, or the error name the client sees.
307fn status_of(result: &Result<Reply, RpcError>) -> String {
308    match result {
309        Ok(Reply::Forwarded(m)) if m.get("status") == Some(&json!("error")) => m
310            .get("error")
311            .and_then(Value::as_str)
312            .unwrap_or("error")
313            .to_owned(),
314        Ok(_) => "success".into(),
315        Err(e) => e.error.into(),
316    }
317}
318
319fn warnings() -> Value {
320    json!([{ "id": 2001, "message": "This is an Astraea server. It serves only validated data." }])
321}
322
323fn error_fields(e: &RpcError, request: &Value) -> Map<String, Value> {
324    let mut m = Map::new();
325    m.insert("error".into(), json!(e.error));
326    m.insert("error_code".into(), json!(e.code));
327    m.insert("error_message".into(), json!(e.message));
328    m.insert("status".into(), json!("error"));
329    m.insert("type".into(), json!("response"));
330    m.insert("request".into(), request.clone());
331    m
332}
333
334/// Request params: the first element of `params`, or an empty object.
335fn params_of(params: Option<&Value>) -> Result<Map<String, Value>, RpcError> {
336    match params {
337        None | Some(Value::Null) => Ok(Map::new()),
338        Some(Value::String(s)) if s.is_empty() => Ok(Map::new()),
339        Some(Value::Object(o)) => Ok(o.clone()),
340        Some(Value::Array(a)) => match a.first() {
341            None | Some(Value::Null) => Ok(Map::new()),
342            Some(Value::String(s)) if s.is_empty() => Ok(Map::new()),
343            Some(Value::Object(o)) => Ok(o.clone()),
344            Some(_) => Err(bad_syntax()),
345        },
346        Some(_) => Err(bad_syntax()),
347    }
348}
349
350fn bad_syntax() -> RpcError {
351    RpcError {
352        error: "badSyntax",
353        code: 1,
354        message: "Syntax error.".into(),
355    }
356}
357
358/// A method's response: our own, or forwarded from a node.
359enum Reply {
360    Own(Map<String, Value>),
361    Forwarded(Map<String, Value>),
362}
363
364async fn call(
365    s: &Shared,
366    client: std::net::IpAddr,
367    method: String,
368    params: Map<String, Value>,
369) -> Result<Reply, RpcError> {
370    if s.public.is_some() && NOT_PUBLIC.contains(&method.as_str()) {
371        return Err(RpcError {
372            error: "notSupported",
373            code: 75,
374            message: "Not supported on the public endpoint.".into(),
375        });
376    }
377    if submission(&method) {
378        let (true, Some(f)) = (s.forward_submissions, s.forwarder.clone()) else {
379            return Err(unknown_method());
380        };
381        let params = submission_params(&method, &params)?;
382        let _permit = s.slot(&s.forwards).await?;
383        return tokio::task::spawn_blocking(move || {
384            if method == "submit" {
385                f.send_transaction(&params)
386            } else {
387                f.forward(&method, &params)
388            }
389        })
390        .await
391        .unwrap_or_else(|e| Err(internal(e)))
392        .map(Reply::Forwarded);
393    }
394    if forwarded(&method, &params) {
395        let Some(f) = s.forwarder.clone() else {
396            return Err(unknown_method());
397        };
398        let _permit = s.slot(&s.forwards).await?;
399        let public = s.public.is_some();
400        return tokio::task::spawn_blocking(move || {
401            let mut r = f.forward(&method, &params)?;
402            if public {
403                crate::forward::hide_node(&method, &mut r);
404            }
405            Ok(r)
406        })
407        .await
408        .unwrap_or_else(|e| Err(internal(e)))
409        .map(Reply::Forwarded);
410    }
411    let info = method == "server_info";
412    let mut r = call_own(s, client, method, params).await?;
413    // Fee multiplier and version come from the node, as in Clio; if the node is
414    // unavailable, our own response stays. The node's answer is refreshed in the
415    // background, so this never waits for the node.
416    if info && let Some(node) = s.forwarder.as_ref().and_then(|f| f.node_server_info()) {
417        node_info(&mut r, &node);
418    }
419    Ok(Reply::Own(r))
420}
421
422async fn call_own(
423    s: &Shared,
424    client: std::net::IpAddr,
425    method: String,
426    params: Map<String, Value>,
427) -> Result<Map<String, Value>, RpcError> {
428    let is_proof = method.starts_with("proof_");
429    // Bundles have their own budget and no queue: if it is full, refuse at once so
430    // that waiting bundles don't take slots from the regular API.
431    let _permit = if is_proof {
432        if s.must_step_aside() {
433            return Err(too_busy());
434        }
435        s.proofs
436            .clone()
437            .try_acquire_owned()
438            .map_err(|_| too_busy())?
439    } else {
440        s.slot(&s.inflight).await?
441    };
442    // A bundle for a transaction, or for a ledger given by explicit sequence or hash,
443    // never changes, so it comes from the cache. An object bundle is for the latest
444    // ledger, and "validated" or a request without a sequence moves with
445    // validation, so those are not cached.
446    let fixed_ledger = params.get("ledger_hash").is_some_and(|v| !v.is_null())
447        || params
448            .get("ledger_index")
449            .is_some_and(|v| v.is_u64() || v.as_str().is_some_and(|s| s.parse::<u32>().is_ok()));
450    let cacheable = method == "proof_tx" || (method == "proof_ledger" && fixed_ledger);
451    let cache_key = cacheable.then(|| format!("{method} {}", Value::Object(params.clone())));
452    if let Some(k) = &cache_key
453        && let Some((_, hit)) = s
454            .cache
455            .lock()
456            .unwrap_or_else(|p| p.into_inner())
457            .iter()
458            .find(|(c, _)| c == k)
459    {
460        lock(&s.metrics).api.proof_cache_hits += 1;
461        return Ok(hit.clone());
462    }
463    let engine = s.engine.clone();
464    let name = method.clone();
465    let public = s.public.is_some();
466    let (result, spent) = tokio::task::spawn_blocking(move || {
467        let _limit = if public {
468            crate::limits::start_public(PUBLIC_REQUEST_LIMIT)
469        } else {
470            crate::limits::start(REQUEST_LIMIT)
471        };
472        let t = Instant::now();
473        let r = engine.handle(&method, &params);
474        (r, t.elapsed())
475    })
476    .await
477    .unwrap_or_else(|e| (Err(internal(e)), std::time::Duration::ZERO));
478    s.guard.worked(client, spent);
479    if is_proof
480        && let Ok(r) = &result
481        && let Some(by) = r
482            .get("guarantee")
483            .and_then(|g| g.get("target_confirmed_by"))
484            .and_then(Value::as_str)
485    {
486        *lock(&s.metrics)
487            .api
488            .proofs
489            .entry((name, by.to_owned()))
490            .or_default() += 1;
491    }
492    if let (Some(k), Ok(r)) = (cache_key, &result) {
493        let mut c = s.cache.lock().unwrap_or_else(|p| p.into_inner());
494        c.push_front((k, r.clone()));
495        c.truncate(PROOF_CACHE);
496    }
497    result
498}
499
500async fn http_rpc(
501    State(s): State<Shared>,
502    ConnectInfo(peer): ConnectInfo<SocketAddr>,
503    headers: HeaderMap,
504    body: String,
505) -> Response {
506    let transport = s.transport("http", "public_http");
507    let client = s.guard.client(peer.ip(), &headers);
508    let Some(_connection) = s.guard.connect(client) else {
509        reject(&s, "connections");
510        record(&s, transport, "", &Err(slow_down()), Instant::now(), 0);
511        return slow_down_http();
512    };
513    let request: Value = match serde_json::from_str(&body) {
514        Ok(v @ Value::Object(_)) => v,
515        _ => {
516            return (
517                axum::http::StatusCode::BAD_REQUEST,
518                "Unable to parse JSON from the request",
519            )
520                .into_response();
521        }
522    };
523    let started = Instant::now();
524    let method = request
525        .get("method")
526        .and_then(Value::as_str)
527        .unwrap_or("")
528        .to_owned();
529    let params = params_of(request.get("params"));
530    if let Ok(p) = &params
531        && !s.guard.request(client, weight(&method, p))
532    {
533        reject(&s, "budget");
534        record(&s, transport, &method, &Err(slow_down()), started, 0);
535        return slow_down_http();
536    }
537    let result = match &params {
538        Ok(p) if !method.is_empty() => call(&s, client, method.clone(), p.clone()).await,
539        Ok(_) => Err(unknown_method()),
540        Err(e) => Err(e.clone()),
541    };
542    let cache = match &params {
543        Ok(p) if immutable(&method, p, &result) => IMMUTABLE,
544        _ => "no-store",
545    };
546    let body = match &result {
547        Ok(Reply::Own(m)) => {
548            let mut m = m.clone();
549            m.insert("status".into(), json!("success"));
550            json!({ "result": m, "warnings": warnings() })
551        }
552        Ok(Reply::Forwarded(m)) => json!({
553            "result": m,
554            "status": "success",
555            "type": "response",
556            "forwarded": true,
557            "warnings": warnings(),
558        }),
559        Err(e) => json!({ "result": error_fields(e, &request), "warnings": warnings() }),
560    }
561    .to_string();
562    record(&s, transport, &method, &result, started, body.len());
563    s.guard.sent(client, body.len());
564    (
565        [
566            (axum::http::header::CONTENT_TYPE, "application/json"),
567            (axum::http::header::CACHE_CONTROL, cache),
568        ],
569        body,
570    )
571        .into_response()
572}
573
574async fn ws_upgrade(
575    State(s): State<Shared>,
576    ConnectInfo(peer): ConnectInfo<SocketAddr>,
577    headers: HeaderMap,
578    ws: WebSocketUpgrade,
579) -> Response {
580    let transport = s.transport("ws", "public_ws");
581    let client = s.guard.client(peer.ip(), &headers);
582    if s.guard.connect(client).is_none() {
583        reject(&s, "connections");
584        record(&s, transport, "", &Err(slow_down()), Instant::now(), 0);
585        return slow_down_http();
586    }
587    // Cap on all public sessions together: per-client limits don't bound a crowd.
588    let session = match &s.public {
589        Some(p) => match p.sessions.clone().try_acquire_owned() {
590            Ok(permit) => Some(permit),
591            Err(_) => {
592                reject(&s, "sessions");
593                record(&s, transport, "", &Err(slow_down()), Instant::now(), 0);
594                return slow_down_http();
595            }
596        },
597        None => None,
598    };
599    let ws = if s.public.is_some() {
600        ws.max_message_size(PUBLIC_MESSAGE)
601    } else {
602        ws
603    };
604    ws.on_upgrade(move |socket| ws_session(s, socket, client, session))
605}
606
607async fn ws_session(
608    s: Shared,
609    mut socket: WebSocket,
610    client: std::net::IpAddr,
611    _session: Option<OwnedSemaphorePermit>,
612) {
613    // The session holds a connection slot for as long as it is open. A client
614    // that reached its cap between the upgrade check and here is closed.
615    let guard = s.guard.clone();
616    let Some(_connection) = guard.connect(client) else {
617        let _ = socket.close().await;
618        return;
619    };
620    let (id, mut rx) = s.hub.join();
621    {
622        let mut m = lock(&s.metrics);
623        m.api.ws_sessions += 1;
624        m.api.ws_sessions_total += 1;
625    }
626    loop {
627        tokio::select! {
628            msg = socket.recv() => {
629                let text = match msg {
630                    Some(Ok(Message::Text(t))) => t,
631                    Some(Ok(Message::Close(_))) => {
632                        // The reply to a close is queued, not sent, until the next
633                        // write. Without it the client sees an abnormal close (1006),
634                        // and xrpl.js then reconnects a client it had disconnected.
635                        let _ = socket.flush().await;
636                        break;
637                    }
638                    Some(Err(_)) | None => break,
639                    Some(Ok(_)) => continue,
640                };
641                let reply = ws_answer(&s, id, &text, client).await;
642                if socket.send(Message::Text(reply.into())).await.is_err() {
643                    break;
644                }
645            }
646            out = rx.recv() => {
647                // Queue closed: the session was disconnected for falling behind.
648                let Some(out) = out else { break };
649                if socket.send(Message::Text(out.into())).await.is_err() {
650                    break;
651                }
652            }
653        }
654    }
655    s.hub.leave(id);
656    let mut m = lock(&s.metrics);
657    m.api.ws_sessions = m.api.ws_sessions.saturating_sub(1);
658}
659
660/// subscribe and unsubscribe for session `id`; with the ledger stream the response
661/// carries the fields of the latest validated ledger.
662async fn subscription(
663    s: &Shared,
664    id: u64,
665    method: &str,
666    params: &Map<String, Value>,
667) -> Result<Reply, RpcError> {
668    let api = api_version(params)?;
669    let r = subs::parse(params)?;
670    if method == "unsubscribe" {
671        s.hub.unsubscribe(id, &r);
672        return Ok(Reply::Own(Map::new()));
673    }
674    if let Some(p) = &s.public
675        && s.hub.accounts_of(id) + r.accounts.len() > p.max_accounts
676    {
677        return Err(RpcError {
678            error: "invalidParams",
679            code: 31,
680            message: "accountsTooMany".into(),
681        });
682    }
683    if !r.ledger {
684        s.hub.subscribe(id, &r, api, 0);
685        return Ok(Reply::Own(Map::new()));
686    }
687    // Take the tip before subscribing: publishing starts with the next ledger.
688    let (engine, hub) = (s.engine.clone(), s.hub.clone());
689    tokio::task::spawn_blocking(move || {
690        let (_, max) = engine.range()?;
691        hub.subscribe(id, &r, api, max);
692        engine.ledger_stream(max, None)
693    })
694    .await
695    .unwrap_or_else(|e| Err(internal(e)))
696    .map(Reply::Own)
697}
698
699async fn ws_answer(s: &Shared, id: u64, text: &str, client: std::net::IpAddr) -> String {
700    let transport = s.transport("ws", "public_ws");
701    let started = Instant::now();
702    let Ok(Value::Object(request)) = serde_json::from_str::<Value>(text) else {
703        let e = bad_syntax();
704        let mut m = error_fields(&e, &json!(text));
705        m.insert("warnings".into(), warnings());
706        let body = Value::Object(m).to_string();
707        record(s, transport, "", &Err(e), started, body.len());
708        return body;
709    };
710    let method = request
711        .get("command")
712        .or_else(|| request.get("method"))
713        .and_then(Value::as_str)
714        .unwrap_or("")
715        .to_owned();
716    let mut params = request.clone();
717    for k in ["command", "method", "id"] {
718        params.remove(k);
719    }
720    let result = if !s.guard.request(client, weight(&method, &params)) {
721        reject(s, "budget");
722        Err(slow_down())
723    } else if method == "subscribe" || method == "unsubscribe" {
724        subscription(s, id, &method, &params).await
725    } else {
726        call(s, client, method.clone(), params).await
727    };
728    let mut m = match &result {
729        Ok(r) => {
730            let mut m = Map::new();
731            let forwarded = matches!(r, Reply::Forwarded(_));
732            let (Reply::Own(r) | Reply::Forwarded(r)) = r;
733            let mut r = r.clone();
734            if forwarded && r.get("status") == Some(&json!("error")) {
735                // A node error stays an error over WebSocket too, as in xrpld: error
736                // fields at the top, otherwise the client would take it for success.
737                r.remove("status");
738                r.remove("request");
739                m.extend(r);
740                m.insert("request".into(), Value::Object(request.clone()));
741                m.insert("status".into(), json!("error"));
742            } else {
743                // Over WebSocket Clio removes the node's `status` from `result`.
744                if forwarded && r.get("status") == Some(&json!("success")) {
745                    r.remove("status");
746                }
747                m.insert("result".into(), Value::Object(r));
748                m.insert("status".into(), json!("success"));
749            }
750            if forwarded {
751                m.insert("forwarded".into(), json!(true));
752            }
753            m
754        }
755        Err(e) => error_fields(e, &Value::Object(request.clone())),
756    };
757    for k in ["id", "api_version"] {
758        if let Some(v) = request.get(k).filter(|v| !v.is_null()) {
759            m.insert(k.into(), v.clone());
760        }
761    }
762    m.insert("type".into(), json!("response"));
763    m.insert("warnings".into(), warnings());
764    let body = Value::Object(m).to_string();
765    record(s, transport, &method, &result, started, body.len());
766    s.guard.sent(client, body.len());
767    body
768}
769
770/// Whether the server keeps up: 200 while the last ledger is recent, 503 when it
771/// is old or there is none. This is what stopped being true on the day the nodes'
772/// network went down, while the connection gauges still read 1.
773async fn health(
774    State(s): State<Shared>,
775    ConnectInfo(peer): ConnectInfo<SocketAddr>,
776    headers: HeaderMap,
777) -> Response {
778    let client = s.guard.client(peer.ip(), &headers);
779    if !s.guard.request(client, 1) {
780        reject(&s, "budget");
781        return slow_down_http();
782    }
783    let engine = s.engine.clone();
784    let last = tokio::task::spawn_blocking(move || engine.last_ledger_age())
785        .await
786        .unwrap_or_else(|e| Err(internal(e)));
787    let (status, body) = health_answer(last.ok());
788    (
789        status,
790        [
791            (axum::http::header::CONTENT_TYPE, "application/json"),
792            (axum::http::header::CACHE_CONTROL, "no-store"),
793        ],
794        body.to_string(),
795    )
796        .into_response()
797}
798
799fn health_answer(last: Option<(u32, i64)>) -> (axum::http::StatusCode, Value) {
800    use axum::http::StatusCode;
801    match last {
802        Some((ledger, age)) if age <= HEALTHY_AGE => (
803            StatusCode::OK,
804            json!({"status": "ok", "ledger": ledger, "age": age}),
805        ),
806        Some((ledger, age)) => (
807            StatusCode::SERVICE_UNAVAILABLE,
808            json!({"status": "lagging", "ledger": ledger, "age": age}),
809        ),
810        None => (
811            StatusCode::SERVICE_UNAVAILABLE,
812            json!({"status": "noLedger"}),
813        ),
814    }
815}
816
817fn start_guard(config: GuardConfig) -> Arc<Guard> {
818    let guard = Arc::new(Guard::new(config));
819    if let Some(every) = guard.sweep_every() {
820        let g = guard.clone();
821        tokio::spawn(async move {
822            loop {
823                tokio::time::sleep(every).await;
824                g.sweep();
825            }
826        });
827    }
828    guard
829}
830
831fn routes(shared: Shared) -> Router {
832    Router::new()
833        .route("/", get(ws_upgrade).post(http_rpc))
834        .route("/health", get(health))
835        .with_state(shared)
836}
837
838/// The routes of `--api-addr` and of the public listeners, over one set of
839/// subscriptions, which starts publishing here.
840fn apps(
841    engine: Arc<Engine>,
842    forwarder: Option<Arc<Forwarder>>,
843    metrics: metrics::Shared,
844    config: ServeConfig,
845    streams: Option<crate::confirm::NodeStreams>,
846) -> (Router, Option<Router>) {
847    let shared = Shared {
848        engine,
849        inflight: Arc::new(Semaphore::new(MAX_INFLIGHT)),
850        proofs: Arc::new(Semaphore::new(MAX_PROOFS)),
851        forwards: Arc::new(Semaphore::new(MAX_FORWARDS)),
852        cache: Arc::new(std::sync::Mutex::new(std::collections::VecDeque::new())),
853        forwarder,
854        hub: Arc::new(Hub::default()),
855        metrics,
856        guard: start_guard(config.own_limits),
857        forward_submissions: config.forward_submissions,
858        public: None,
859    };
860    tokio::spawn(subs::run(shared.engine.clone(), shared.hub.clone()));
861    if let Some(s) = streams {
862        tokio::spawn(subs::forward_streams(shared.hub.clone(), s.subscribe()));
863    }
864    let public = config.public.map(|p| {
865        let public = Shared {
866            inflight: Arc::new(Semaphore::new(p.max_inflight)),
867            proofs: Arc::new(Semaphore::new(p.max_proofs)),
868            forwards: Arc::new(Semaphore::new(p.max_forwards)),
869            guard: start_guard(p.limits),
870            forward_submissions: false,
871            public: Some(Public {
872                own_inflight: shared.inflight.clone(),
873                sessions: Arc::new(Semaphore::new(p.max_sessions)),
874                max_accounts: p.max_accounts,
875            }),
876            ..shared.clone()
877        };
878        tokio::spawn(sample_public(
879            public.clone(),
880            p.max_inflight,
881            p.max_proofs,
882            p.max_forwards,
883            p.max_sessions,
884        ));
885        routes(public).layer(DefaultBodyLimit::max(PUBLIC_MESSAGE))
886    });
887    tokio::spawn(sample(shared.clone()));
888    (routes(shared), public)
889}
890
891/// Every few seconds, how much of the public listeners' budgets is in use.
892async fn sample_public(
893    s: Shared,
894    max_inflight: usize,
895    max_proofs: usize,
896    max_forwards: usize,
897    max_sessions: usize,
898) {
899    loop {
900        {
901            let free = s
902                .public
903                .as_ref()
904                .map_or(max_sessions, |p| p.sessions.available_permits());
905            let mut m = lock(&s.metrics);
906            m.api.public_inflight = (max_inflight - s.inflight.available_permits()) as u64;
907            m.api.public_inflight_proofs = (max_proofs - s.proofs.available_permits()) as u64;
908            m.api.public_inflight_forwards = (max_forwards - s.forwards.available_permits()) as u64;
909            m.api.public_sessions = (max_sessions - free) as u64;
910        }
911        tokio::time::sleep(std::time::Duration::from_secs(5)).await;
912    }
913}
914
915/// Every few seconds, what is happening now: requests in progress and
916/// subscriptions.
917async fn sample(s: Shared) {
918    loop {
919        let h = s.hub.stats();
920        {
921            let mut m = lock(&s.metrics);
922            m.api.inflight = (MAX_INFLIGHT - s.inflight.available_permits()) as u64;
923            m.api.inflight_proofs = (MAX_PROOFS - s.proofs.available_permits()) as u64;
924            m.api.inflight_forwards = (MAX_FORWARDS - s.forwards.available_permits()) as u64;
925            m.api.subscribers = [
926                ("ledger", h.ledger),
927                ("transactions", h.transactions),
928                ("book_changes", h.book_changes),
929                ("validations", h.validations),
930                ("manifests", h.manifests),
931                ("accounts", h.account_sessions),
932            ]
933            .into_iter()
934            .collect();
935            m.api.subscribed_accounts = h.accounts;
936            m.api.ws_dropped = h.dropped;
937        }
938        tokio::time::sleep(std::time::Duration::from_secs(5)).await;
939    }
940}
941
942/// Listens on every address in `addrs` for the life of the process, with one
943/// set of subscriptions behind them all. An address that can't be bound is
944/// retried on its own: ingestion matters more than the API, and an address
945/// still held by the server being replaced is taken over once it is freed.
946pub async fn serve(
947    addrs: Vec<SocketAddr>,
948    engine: Arc<Engine>,
949    forwarder: Option<Arc<Forwarder>>,
950    metrics: metrics::Shared,
951    config: ServeConfig,
952    streams: Option<crate::confirm::NodeStreams>,
953) {
954    let public_addrs = config
955        .public
956        .as_ref()
957        .map_or_else(Vec::new, |p| p.addrs.clone());
958    let (own, public) = apps(engine, forwarder, metrics, config, streams);
959    let mut listeners: Vec<(SocketAddr, Router)> =
960        addrs.into_iter().map(|a| (a, own.clone())).collect();
961    if let Some(public) = public {
962        listeners.extend(public_addrs.into_iter().map(|a| (a, public.clone())));
963    }
964    for (addr, app) in listeners {
965        tokio::spawn(async move {
966            loop {
967                match tokio::net::TcpListener::bind(addr).await {
968                    Ok(listener) => {
969                        info!("API at http://{addr}/ and ws://{addr}/");
970                        let svc = app
971                            .clone()
972                            .into_make_service_with_connect_info::<SocketAddr>();
973                        if let Err(e) = axum::serve(listener, svc).await {
974                            warn!("API: {e}");
975                        }
976                    }
977                    Err(e) => warn!("API: cannot listen on {addr}: {e}; retrying in 10 s"),
978                }
979                tokio::time::sleep(std::time::Duration::from_secs(10)).await;
980            }
981        });
982    }
983}
984
985#[cfg(test)]
986mod tests {
987    use super::*;
988    use futures_util::StreamExt;
989    use tokio_tungstenite::tungstenite::Message as Client;
990    use tokio_tungstenite::tungstenite::protocol::CloseFrame;
991    use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode;
992
993    /// Starts a router on a free port.
994    async fn listen(routes: Router) -> SocketAddr {
995        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
996        let addr = listener.local_addr().unwrap();
997        let svc = routes.into_make_service_with_connect_info::<SocketAddr>();
998        tokio::spawn(async move { axum::serve(listener, svc).await });
999        addr
1000    }
1001
1002    fn public_config() -> PublicConfig {
1003        PublicConfig {
1004            addrs: Vec::new(),
1005            limits: GuardConfig {
1006                max_requests: Some(1000),
1007                sweep: std::time::Duration::from_secs(3600),
1008                ..GuardConfig::default()
1009            },
1010            max_inflight: 2,
1011            max_proofs: 1,
1012            max_forwards: 1,
1013            max_sessions: 1,
1014            max_accounts: 1,
1015        }
1016    }
1017
1018    /// HTTP status and body of one JSON-RPC request.
1019    async fn post(addr: SocketAddr, body: String) -> (u16, String) {
1020        tokio::task::spawn_blocking(move || {
1021            let agent: ureq::Agent = ureq::Agent::config_builder()
1022                .http_status_as_error(false)
1023                .build()
1024                .into();
1025            let mut r = agent.post(&format!("http://{addr}/")).send(body).unwrap();
1026            (r.status().as_u16(), r.body_mut().read_to_string().unwrap())
1027        })
1028        .await
1029        .unwrap()
1030    }
1031
1032    #[tokio::test]
1033    async fn the_public_door_has_its_own_slots_and_steps_aside() {
1034        let dir = tempfile::tempdir().unwrap();
1035        let shared = Shared {
1036            engine: Arc::new(test_engine(dir.path())),
1037            inflight: Arc::new(Semaphore::new(MAX_INFLIGHT)),
1038            proofs: Arc::new(Semaphore::new(MAX_PROOFS)),
1039            forwards: Arc::new(Semaphore::new(MAX_FORWARDS)),
1040            cache: Default::default(),
1041            forwarder: None,
1042            hub: Default::default(),
1043            metrics: Default::default(),
1044            guard: Arc::new(Guard::default()),
1045            forward_submissions: false,
1046            public: None,
1047        };
1048        let public = Shared {
1049            inflight: Arc::new(Semaphore::new(2)),
1050            public: Some(Public {
1051                own_inflight: shared.inflight.clone(),
1052                sessions: Arc::new(Semaphore::new(1)),
1053                max_accounts: 1,
1054            }),
1055            ..shared.clone()
1056        };
1057        // Filling the public slots leaves our own untouched.
1058        let held: Vec<_> = (0..2)
1059            .map(|_| public.inflight.clone().try_acquire_owned().unwrap())
1060            .collect();
1061        assert_eq!(shared.inflight.available_permits(), MAX_INFLIGHT);
1062        let t = Instant::now();
1063        let e = public.slot(&public.inflight).await.unwrap_err();
1064        assert_eq!(e.error, "tooBusy");
1065        assert!(t.elapsed() < QUEUE_WAIT);
1066        assert!(shared.slot(&shared.inflight).await.is_ok());
1067        drop(held);
1068        // With our own slots running out, the public door refuses at once.
1069        assert!(public.slot(&public.inflight).await.is_ok());
1070        let busy: Vec<_> = (0..=MAX_INFLIGHT - OWN_HEADROOM)
1071            .map(|_| shared.inflight.clone().try_acquire_owned().unwrap())
1072            .collect();
1073        let t = Instant::now();
1074        assert_eq!(
1075            public.slot(&public.inflight).await.unwrap_err().error,
1076            "tooBusy"
1077        );
1078        assert!(t.elapsed() < std::time::Duration::from_millis(100));
1079        assert!(shared.slot(&shared.inflight).await.is_ok());
1080        drop(busy);
1081    }
1082
1083    #[tokio::test]
1084    async fn submissions_stay_off_the_public_door_and_off_by_default() {
1085        let dir = tempfile::tempdir().unwrap();
1086        let other = tempfile::tempdir().unwrap();
1087        let forwarder = Arc::new(Forwarder::new(
1088            vec!["http://127.0.0.1:1".into()],
1089            std::time::Duration::from_secs(1),
1090        ));
1091        let config = ServeConfig {
1092            forward_submissions: true,
1093            public: Some(public_config()),
1094            ..ServeConfig::default()
1095        };
1096        let (own, public) = apps(
1097            Arc::new(test_engine(dir.path())),
1098            Some(forwarder.clone()),
1099            metrics::Shared::default(),
1100            config,
1101            None,
1102        );
1103        let own = listen(own).await;
1104        let public = listen(public.unwrap()).await;
1105        let submit = r#"{"method":"submit","params":[{"tx_blob":"00"}]}"#.to_owned();
1106        let (_, on_public) = post(public, submit.clone()).await;
1107        assert!(
1108            on_public.contains(r#""error":"notSupported""#),
1109            "{on_public}"
1110        );
1111        let path = r#"{"method":"ripple_path_find","params":[{"ledger_index":"current"}]}"#;
1112        let (_, on_public) = post(public, path.to_owned()).await;
1113        assert!(
1114            on_public.contains(r#""error":"notSupported""#),
1115            "{on_public}"
1116        );
1117        // On our own door it goes to the node, which is down here.
1118        let (_, on_own) = post(own, submit.clone()).await;
1119        assert!(on_own.contains(r#""error":"failedToForward""#), "{on_own}");
1120        let secret = r#"{"method":"submit","params":[{"tx_blob":"00","secret":"s"}]}"#;
1121        let (_, refused) = post(own, secret.to_owned()).await;
1122        assert!(refused.contains("signingNotSupported"), "{refused}");
1123        // Not turned on: as if the method didn't exist.
1124        let (off, _) = apps(
1125            Arc::new(test_engine(other.path())),
1126            Some(forwarder),
1127            metrics::Shared::default(),
1128            ServeConfig::default(),
1129            None,
1130        );
1131        let (_, unknown) = post(listen(off).await, submit).await;
1132        assert!(unknown.contains(r#""error":"unknownCmd""#), "{unknown}");
1133    }
1134
1135    #[tokio::test]
1136    async fn the_public_door_caps_sessions_and_accounts() {
1137        let dir = tempfile::tempdir().unwrap();
1138        let config = ServeConfig {
1139            public: Some(public_config()),
1140            ..ServeConfig::default()
1141        };
1142        let (_, public) = apps(
1143            Arc::new(test_engine(dir.path())),
1144            None,
1145            metrics::Shared::default(),
1146            config,
1147            None,
1148        );
1149        let addr = listen(public.unwrap()).await;
1150        let (mut ws, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/"))
1151            .await
1152            .unwrap();
1153        // The only session is taken.
1154        assert!(
1155            tokio_tungstenite::connect_async(format!("ws://{addr}/"))
1156                .await
1157                .is_err()
1158        );
1159        let subscribe = serde_json::json!({
1160            "command": "subscribe",
1161            "accounts": ["rrrrrrrrrrrrrrrrrrrrrhoLvTp", "rrrrrrrrrrrrrrrrrrrrBZbvji"],
1162        });
1163        ws.send(Client::Text(subscribe.to_string().into()))
1164            .await
1165            .unwrap();
1166        let Some(Ok(Client::Text(reply))) = ws.next().await else {
1167            panic!("no reply");
1168        };
1169        assert!(reply.contains("accountsTooMany"), "{reply}");
1170    }
1171
1172    #[test]
1173    fn health_reports_a_server_that_stopped_advancing() {
1174        use axum::http::StatusCode;
1175        assert_eq!(health_answer(Some((5, 3))).0, StatusCode::OK);
1176        assert_eq!(health_answer(Some((5, HEALTHY_AGE))).0, StatusCode::OK);
1177        let (status, body) = health_answer(Some((5, HEALTHY_AGE + 1)));
1178        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
1179        assert_eq!(body["status"], "lagging");
1180        assert_eq!(health_answer(None).0, StatusCode::SERVICE_UNAVAILABLE);
1181    }
1182
1183    #[tokio::test]
1184    async fn health_on_an_empty_server_is_503() {
1185        let dir = tempfile::tempdir().unwrap();
1186        let (own, _) = apps(
1187            Arc::new(test_engine(dir.path())),
1188            None,
1189            metrics::Shared::default(),
1190            ServeConfig::default(),
1191            None,
1192        );
1193        let addr = listen(own).await;
1194        let got = tokio::task::spawn_blocking(move || {
1195            let agent: ureq::Agent = ureq::Agent::config_builder()
1196                .http_status_as_error(false)
1197                .build()
1198                .into();
1199            let mut r = agent.get(&format!("http://{addr}/health")).call().unwrap();
1200            (r.status().as_u16(), r.body_mut().read_to_string().unwrap())
1201        })
1202        .await
1203        .unwrap();
1204        assert_eq!(got.0, 503);
1205        assert!(got.1.contains("noLedger"), "{}", got.1);
1206    }
1207
1208    fn test_engine(dir: &std::path::Path) -> Engine {
1209        Engine {
1210            state: Arc::new(crate::state::StateStore::open(&dir.join("state")).unwrap()),
1211            blocks: crate::history::HistoryReader::open(&dir.join("history")).unwrap(),
1212            network_id: 0,
1213            started: Instant::now(),
1214            confirmer: None,
1215            quorum: Default::default(),
1216        }
1217    }
1218
1219    #[tokio::test]
1220    async fn a_client_over_its_budget_gets_slow_down() {
1221        let dir = tempfile::tempdir().unwrap();
1222        let metrics = metrics::Shared::default();
1223        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1224        let addr = listener.local_addr().unwrap();
1225        let guard = GuardConfig {
1226            max_requests: Some(2),
1227            sweep: std::time::Duration::from_secs(3600),
1228            ..GuardConfig::default()
1229        };
1230        let config = ServeConfig {
1231            own_limits: guard,
1232            ..ServeConfig::default()
1233        };
1234        let routes = apps(
1235            Arc::new(test_engine(dir.path())),
1236            None,
1237            metrics.clone(),
1238            config,
1239            None,
1240        )
1241        .0
1242        .into_make_service_with_connect_info::<SocketAddr>();
1243        tokio::spawn(async move { axum::serve(listener, routes).await });
1244        let got = tokio::task::spawn_blocking(move || {
1245            let agent: ureq::Agent = ureq::Agent::config_builder()
1246                .http_status_as_error(false)
1247                .build()
1248                .into();
1249            (0..3)
1250                .map(|_| {
1251                    let mut r = agent
1252                        .post(&format!("http://{addr}/"))
1253                        .send(r#"{"method":"ping"}"#)
1254                        .unwrap();
1255                    let cache = r
1256                        .headers()
1257                        .get("cache-control")
1258                        .and_then(|v| v.to_str().ok())
1259                        .unwrap_or("")
1260                        .to_owned();
1261                    (
1262                        r.status().as_u16(),
1263                        cache,
1264                        r.body_mut().read_to_string().unwrap(),
1265                    )
1266                })
1267                .collect::<Vec<_>>()
1268        })
1269        .await
1270        .unwrap();
1271        assert_eq!((got[0].0, got[0].1.as_str()), (200, "no-store"));
1272        assert_eq!(got[1].0, 200);
1273        assert_eq!(got[2].0, 503);
1274        assert!(got[2].2.contains(r#""error":"slowDown""#), "{}", got[2].2);
1275        assert_eq!(
1276            lock(&metrics)
1277                .api
1278                .requests
1279                .get(&("http", "ping".into(), "slowDown".into())),
1280            Some(&1)
1281        );
1282    }
1283
1284    #[test]
1285    fn only_answers_that_cannot_change_are_cacheable() {
1286        let ok = Ok(Reply::Own(Map::new()));
1287        let p = |v: Value| v.as_object().cloned().unwrap();
1288        assert!(immutable("tx", &Map::new(), &ok));
1289        assert!(immutable("ledger", &p(json!({"ledger_index": 5})), &ok));
1290        assert!(immutable(
1291            "account_info",
1292            &p(json!({"ledger_index": "5"})),
1293            &ok
1294        ));
1295        assert!(immutable(
1296            "ledger_entry",
1297            &p(json!({"ledger_hash": "AB"})),
1298            &ok
1299        ));
1300        assert!(!immutable(
1301            "ledger",
1302            &p(json!({"ledger_index": "validated"})),
1303            &ok
1304        ));
1305        assert!(!immutable("account_info", &Map::new(), &ok));
1306        assert!(!immutable(
1307            "server_info",
1308            &p(json!({"ledger_index": 5})),
1309            &ok
1310        ));
1311        assert!(!immutable("tx", &Map::new(), &Err(slow_down())));
1312        let fwd = Ok(Reply::Forwarded(Map::new()));
1313        assert!(!immutable("ledger", &p(json!({"ledger_index": 5})), &fwd));
1314    }
1315
1316    #[tokio::test]
1317    async fn a_client_close_is_answered_and_requests_are_counted() {
1318        let dir = tempfile::tempdir().unwrap();
1319        let engine = Engine {
1320            state: Arc::new(crate::state::StateStore::open(&dir.path().join("state")).unwrap()),
1321            blocks: crate::history::HistoryReader::open(&dir.path().join("history")).unwrap(),
1322            network_id: 0,
1323            started: Instant::now(),
1324            confirmer: None,
1325            quorum: Default::default(),
1326        };
1327        let metrics = metrics::Shared::default();
1328        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1329        let addr = listener.local_addr().unwrap();
1330        let routes = apps(
1331            Arc::new(engine),
1332            None,
1333            metrics.clone(),
1334            ServeConfig::default(),
1335            None,
1336        )
1337        .0
1338        .into_make_service_with_connect_info::<SocketAddr>();
1339        tokio::spawn(async move { axum::serve(listener, routes).await });
1340        let (mut ws, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/"))
1341            .await
1342            .unwrap();
1343        ws.send(Client::Text(r#"{"command":"ping","id":1}"#.into()))
1344            .await
1345            .unwrap();
1346        let Some(Ok(Client::Text(reply))) = ws.next().await else {
1347            panic!("no reply to ping");
1348        };
1349        assert!(reply.contains(r#""status":"success""#), "{reply}");
1350        // xrpl.js closes with 4000 and reconnects unless the same code comes back.
1351        ws.send(Client::Close(Some(CloseFrame {
1352            code: CloseCode::Library(4000),
1353            reason: "".into(),
1354        })))
1355        .await
1356        .unwrap();
1357        match ws.next().await {
1358            Some(Ok(Client::Close(Some(f)))) => assert_eq!(f.code, CloseCode::Library(4000)),
1359            other => panic!("expected a close reply, got {other:?}"),
1360        }
1361        for _ in 0..100 {
1362            if lock(&metrics).api.ws_sessions == 0 {
1363                break;
1364            }
1365            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
1366        }
1367        let m = lock(&metrics);
1368        assert_eq!((m.api.ws_sessions, m.api.ws_sessions_total), (0, 1));
1369        assert_eq!(
1370            m.api.requests.get(&("ws", "ping".into(), "success".into())),
1371            Some(&1)
1372        );
1373    }
1374}