aimdb_core/remote/
instance.rs1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum PostLinkError {
19 NotWritten,
22 InvalidParams,
26}
27
28pub 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 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
76pub 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 total: data.len() as u32,
97 data: hex(&data[start..end]),
98 };
99 Ok(serde_json::to_vec(&chunk).unwrap_or_default())
100}
101
102fn 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
120fn 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}