Skip to main content

aimdb_core/remote/
instance.rs

1//! `instance.info` and `instance.post_link` (protocol 3.1): which build and
2//! which instance this is. Every AimX transport, the WebSocket one included,
3//! answers with these replies, so the answer is the same on each.
4
5use alloc::string::String;
6use alloc::vec::Vec;
7
8use aimdb_build_info::PostLink;
9use serde::Serialize;
10use serde_json::value::RawValue;
11use serde_json::Value;
12
13use super::protocol::{InstanceIdentityReply, PostLinkChunk, PostLinkReply, POST_LINK_CHUNK_MAX};
14use crate::AimDb;
15
16/// Why `instance.post_link` has no chunk to send.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum PostLinkError {
19    /// No build info is embedded, or its post-link region is not written.
20    /// Dispatches answer `not_found`.
21    NotWritten,
22    /// `params` is not an object of optional `offset` and `len`, each an
23    /// integer in `0..=u32::MAX`. Dispatches answer `internal`, as for other
24    /// methods' malformed params.
25    InvalidParams,
26}
27
28/// The `instance.info` reply for `db`, as JSON bytes.
29///
30/// The build-info payload is spliced in as embedded: `build()` checked that
31/// it is one JSON object without line breaks, and it is never decoded into a
32/// tree. The reply is at most
33/// [`INSTANCE_INFO_REPLY_MAX`](super::INSTANCE_INFO_REPLY_MAX) bytes.
34pub fn instance_info_reply(db: &AimDb) -> Vec<u8> {
35    #[derive(Serialize)]
36    struct Reply<'a> {
37        aimdb_version: &'static str,
38        instance: InstanceIdentityReply,
39        build: Option<Build<'a>>,
40    }
41
42    #[derive(Serialize)]
43    struct Build<'a> {
44        format: u16,
45        info: &'a RawValue,
46        post_link: Option<PostLinkReply>,
47    }
48
49    let identity = db.identity();
50    let build = identity.build_info().and_then(|section| {
51        Some(Build {
52            format: section.format,
53            // Validates without building a tree; cannot fail after build().
54            info: serde_json::from_slice(section.payload).ok()?,
55            post_link: match section.post_link() {
56                PostLink::None => None,
57                PostLink::Erased => Some(PostLinkReply::Erased),
58                PostLink::Written(data) => Some(PostLinkReply::Written {
59                    len: data.len() as u32,
60                }),
61                PostLink::Malformed => Some(PostLinkReply::Malformed),
62            },
63        })
64    });
65    let reply = Reply {
66        aimdb_version: env!("CARGO_PKG_VERSION"),
67        instance: InstanceIdentityReply {
68            name: identity.name().map(String::from),
69            uid: identity.uid().map(hex),
70        },
71        build,
72    };
73    serde_json::to_vec(&reply).unwrap_or_default()
74}
75
76/// The `instance.post_link` reply for `db` and the request's `params`, as
77/// JSON bytes: one chunk of the written post-link bytes.
78///
79/// `params` is `{"offset": u32, "len": u32}`, both optional; `null` counts as
80/// `{}`. A missing `offset` is 0, a missing `len` or one over
81/// [`POST_LINK_CHUNK_MAX`] is that maximum, and `len: 0` or an `offset` at or
82/// past the end gives empty `data` with `total` set. The params are checked
83/// before the region, so malformed ones are reported even without a region.
84pub fn post_link_chunk_reply(db: &AimDb, params: &Value) -> Result<Vec<u8>, PostLinkError> {
85    let (offset, len) = post_link_params(params)?;
86    let data = match db.identity().build_info().map(|s| s.post_link()) {
87        Some(PostLink::Written(data)) => data,
88        _ => return Err(PostLinkError::NotWritten),
89    };
90    let len = len.unwrap_or(POST_LINK_CHUNK_MAX).min(POST_LINK_CHUNK_MAX);
91    let start = (offset as usize).min(data.len());
92    let end = start.saturating_add(len as usize).min(data.len());
93    let chunk = PostLinkChunk {
94        offset,
95        // A section is at most 64 KiB.
96        total: data.len() as u32,
97        data: hex(&data[start..end]),
98    };
99    Ok(serde_json::to_vec(&chunk).unwrap_or_default())
100}
101
102/// `offset` (default 0) and `len` from the params; no clamping or defaulting
103/// of malformed values.
104fn post_link_params(params: &Value) -> Result<(u32, Option<u32>), PostLinkError> {
105    let field = |key: &str| match params.get(key) {
106        None => Ok(None),
107        Some(v) => v
108            .as_u64()
109            .and_then(|n| u32::try_from(n).ok())
110            .map(Some)
111            .ok_or(PostLinkError::InvalidParams),
112    };
113    match params {
114        Value::Null => Ok((0, None)),
115        Value::Object(_) => Ok((field("offset")?.unwrap_or(0), field("len")?)),
116        _ => Err(PostLinkError::InvalidParams),
117    }
118}
119
120/// Lowercase hex.
121fn hex(bytes: &[u8]) -> String {
122    const DIGITS: &[u8; 16] = b"0123456789abcdef";
123    let mut s = String::with_capacity(bytes.len() * 2);
124    for b in bytes {
125        s.push(DIGITS[usize::from(b >> 4)] as char);
126        s.push(DIGITS[usize::from(b & 0x0f)] as char);
127    }
128    s
129}