use alloc::string::String;
use alloc::vec::Vec;
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
pub const PROTOCOL_VERSION: &str = "4.0";
pub const VERSION_PARAM: &str = "v";
pub fn ws_url_with_version(url: &str) -> String {
let sep = if url.contains('?') { '&' } else { '?' };
alloc::format!("{url}{sep}{VERSION_PARAM}={PROTOCOL_VERSION}")
}
fn protocol_major(version: &str) -> Option<&str> {
match version.split('.').next() {
Some(major) if !major.is_empty() => Some(major),
_ => None,
}
}
pub fn version_compatible(their_version: &str) -> bool {
match (
protocol_major(their_version),
protocol_major(PROTOCOL_VERSION),
) {
(Some(theirs), Some(ours)) => theirs == ours,
_ => false,
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HelloMessage {
pub version: String,
pub client: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub capabilities: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub auth_token: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WelcomeMessage {
pub version: String,
pub server: String,
pub permissions: Vec<String>,
pub writable_records: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_subscriptions: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub authenticated: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub instance_name: Option<String>,
}
pub const POST_LINK_CHUNK_MAX: u32 = 1024;
pub const INSTANCE_INFO_REPLY_MAX: usize = 6 * 1024;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InstanceInfoReply {
pub aimdb_version: String,
pub instance: InstanceIdentityReply,
pub build: Option<BuildReply>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InstanceIdentityReply {
pub name: Option<String>,
pub uid: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BuildReply {
pub format: u16,
pub info: JsonValue,
pub post_link: Option<PostLinkReply>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum PostLinkReply {
Erased,
Written {
len: u32,
},
Malformed,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PostLinkChunk {
pub offset: u32,
pub total: u32,
pub data: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Request {
pub id: u64,
pub method: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub params: Option<JsonValue>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Response {
Success {
id: u64,
result: JsonValue,
},
Error {
id: u64,
error: ErrorObject,
},
}
impl Response {
pub fn success(id: u64, result: JsonValue) -> Self {
Self::Success { id, result }
}
pub fn error(id: u64, code: impl Into<String>, message: impl Into<String>) -> Self {
Self::Error {
id,
error: ErrorObject {
code: code.into(),
message: message.into(),
details: None,
},
}
}
pub fn error_with_details(
id: u64,
code: impl Into<String>,
message: impl Into<String>,
details: JsonValue,
) -> Self {
Self::Error {
id,
error: ErrorObject {
code: code.into(),
message: message.into(),
details: Some(details),
},
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorObject {
pub code: String,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub details: Option<JsonValue>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Event {
pub subscription_id: String,
pub sequence: u64,
pub data: JsonValue,
pub timestamp: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub dropped: Option<u64>,
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::string::ToString;
use alloc::vec;
#[test]
fn test_hello_serialization() {
let hello = HelloMessage {
version: PROTOCOL_VERSION.to_string(),
client: "test-client".to_string(),
capabilities: Some(vec!["read".to_string()]),
auth_token: None,
};
let json = serde_json::to_string(&hello).unwrap();
assert!(json.contains("\"version\":\"4.0\""));
assert!(json.contains("\"client\":\"test-client\""));
}
fn welcome(instance_name: Option<&str>) -> WelcomeMessage {
WelcomeMessage {
version: PROTOCOL_VERSION.to_string(),
server: "aimdb".to_string(),
permissions: vec!["read".to_string()],
writable_records: vec![],
max_subscriptions: Some(8),
authenticated: Some(false),
instance_name: instance_name.map(String::from),
}
}
#[test]
fn instance_name_is_omitted_when_unset() {
let json = serde_json::to_string(&welcome(None)).unwrap();
assert!(!json.contains("instance_name"), "{json}");
let json = serde_json::to_string(&welcome(Some("gateway-3"))).unwrap();
assert!(json.contains(r#""instance_name":"gateway-3""#), "{json}");
}
#[test]
fn welcome_is_compatible_both_ways() {
#[derive(Deserialize, Serialize)]
struct WelcomeV30 {
version: String,
server: String,
permissions: Vec<String>,
writable_records: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
max_subscriptions: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
authenticated: Option<bool>,
}
let v31 = serde_json::to_string(&welcome(Some("gateway-3"))).unwrap();
let old: WelcomeV30 = serde_json::from_str(&v31).unwrap();
assert_eq!(old.server, "aimdb");
let v30 = serde_json::to_string(&WelcomeV30 {
version: "3.0".to_string(),
..old
})
.unwrap();
let new: WelcomeMessage = serde_json::from_str(&v30).unwrap();
assert_eq!(new.instance_name, None);
}
#[test]
fn post_link_reply_shapes() {
let cases = [
(PostLinkReply::Erased, r#"{"state":"erased"}"#),
(
PostLinkReply::Written { len: 1472 },
r#"{"state":"written","len":1472}"#,
),
(PostLinkReply::Malformed, r#"{"state":"malformed"}"#),
];
for (reply, json) in cases {
assert_eq!(serde_json::to_string(&reply).unwrap(), json);
assert_eq!(serde_json::from_str::<PostLinkReply>(json).unwrap(), reply);
}
}
#[test]
fn version_compatible_matches_on_major() {
assert!(version_compatible(PROTOCOL_VERSION));
assert!(version_compatible("4.0"));
assert!(version_compatible("4.7"));
assert!(version_compatible("4"));
assert!(!version_compatible("3.1"));
assert!(!version_compatible("3.0"));
assert!(!version_compatible("2.0"));
assert!(!version_compatible("1.0"));
assert!(!version_compatible(""));
assert!(!version_compatible(".0"));
assert!(!version_compatible("garbage"));
}
#[test]
fn test_request_serialization() {
let request = Request {
id: 1,
method: "record.list".to_string(),
params: Some(serde_json::json!({})),
};
let json = serde_json::to_string(&request).unwrap();
assert!(json.contains("\"id\":1"));
assert!(json.contains("\"method\":\"record.list\""));
}
#[test]
fn test_response_success() {
let response = Response::success(1, serde_json::json!({"status": "ok"}));
let json = serde_json::to_string(&response).unwrap();
assert!(json.contains("\"id\":1"));
assert!(json.contains("\"result\""));
assert!(json.contains("\"status\":\"ok\""));
}
#[test]
fn test_response_error() {
let response = Response::error(2, "NOT_FOUND", "Record not found");
let json = serde_json::to_string(&response).unwrap();
assert!(json.contains("\"id\":2"));
assert!(json.contains("\"error\""));
assert!(json.contains("\"code\":\"NOT_FOUND\""));
assert!(json.contains("\"message\":\"Record not found\""));
}
#[test]
fn test_event_serialization() {
let event = Event {
subscription_id: "sub-123".to_string(),
sequence: 42,
data: serde_json::json!({"temp": 23.5}),
timestamp: "1730379296.123456789".to_string(),
dropped: None,
};
let json = serde_json::to_string(&event).unwrap();
assert!(json.contains("\"subscription_id\":\"sub-123\""));
assert!(json.contains("\"sequence\":42"));
assert!(json.contains("\"temp\":23.5"));
}
#[test]
fn test_event_with_dropped() {
let event = Event {
subscription_id: "sub-456".to_string(),
sequence: 100,
data: serde_json::json!({"value": 1}),
timestamp: "1730379300.987654321".to_string(),
dropped: Some(5),
};
let json = serde_json::to_string(&event).unwrap();
assert!(json.contains("\"dropped\":5"));
}
}