1use alloc::string::String;
10use alloc::vec::Vec;
11use serde::{Deserialize, Serialize};
12use serde_json::Value as JsonValue;
13
14pub const PROTOCOL_VERSION: &str = "4.0";
16
17pub const VERSION_PARAM: &str = "v";
25
26pub fn ws_url_with_version(url: &str) -> String {
33 let sep = if url.contains('?') { '&' } else { '?' };
34 alloc::format!("{url}{sep}{VERSION_PARAM}={PROTOCOL_VERSION}")
35}
36
37fn protocol_major(version: &str) -> Option<&str> {
40 match version.split('.').next() {
41 Some(major) if !major.is_empty() => Some(major),
42 _ => None,
43 }
44}
45
46pub fn version_compatible(their_version: &str) -> bool {
55 match (
56 protocol_major(their_version),
57 protocol_major(PROTOCOL_VERSION),
58 ) {
59 (Some(theirs), Some(ours)) => theirs == ours,
60 _ => false,
61 }
62}
63
64#[derive(Debug, Clone, Serialize, Deserialize)]
66pub struct HelloMessage {
67 pub version: String,
69
70 pub client: String,
72
73 #[serde(skip_serializing_if = "Option::is_none")]
75 pub capabilities: Option<Vec<String>>,
76
77 #[serde(skip_serializing_if = "Option::is_none")]
79 pub auth_token: Option<String>,
80}
81
82#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct WelcomeMessage {
85 pub version: String,
87
88 pub server: String,
90
91 pub permissions: Vec<String>,
93
94 pub writable_records: Vec<String>,
96
97 #[serde(skip_serializing_if = "Option::is_none")]
99 pub max_subscriptions: Option<usize>,
100
101 #[serde(skip_serializing_if = "Option::is_none")]
103 pub authenticated: Option<bool>,
104
105 #[serde(default, skip_serializing_if = "Option::is_none")]
107 pub instance_name: Option<String>,
108}
109
110pub const POST_LINK_CHUNK_MAX: u32 = 1024;
113
114pub const INSTANCE_INFO_REPLY_MAX: usize = 6 * 1024;
118
119#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
121pub struct InstanceInfoReply {
122 pub aimdb_version: String,
124 pub instance: InstanceIdentityReply,
126 pub build: Option<BuildReply>,
128}
129
130#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
132pub struct InstanceIdentityReply {
133 pub name: Option<String>,
135 pub uid: Option<String>,
137}
138
139#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141pub struct BuildReply {
142 pub format: u16,
144 pub info: JsonValue,
147 pub post_link: Option<PostLinkReply>,
150}
151
152#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
154#[serde(tag = "state", rename_all = "snake_case")]
155pub enum PostLinkReply {
156 Erased,
158 Written {
160 len: u32,
162 },
163 Malformed,
165}
166
167#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
170pub struct PostLinkChunk {
171 pub offset: u32,
173 pub total: u32,
175 pub data: String,
178}
179
180#[derive(Debug, Clone, Serialize, Deserialize)]
182pub struct Request {
183 pub id: u64,
185
186 pub method: String,
188
189 #[serde(skip_serializing_if = "Option::is_none")]
191 pub params: Option<JsonValue>,
192}
193
194#[derive(Debug, Clone, Serialize, Deserialize)]
196#[serde(untagged)]
197pub enum Response {
198 Success {
200 id: u64,
202 result: JsonValue,
204 },
205 Error {
207 id: u64,
209 error: ErrorObject,
211 },
212}
213
214impl Response {
215 pub fn success(id: u64, result: JsonValue) -> Self {
217 Self::Success { id, result }
218 }
219
220 pub fn error(id: u64, code: impl Into<String>, message: impl Into<String>) -> Self {
222 Self::Error {
223 id,
224 error: ErrorObject {
225 code: code.into(),
226 message: message.into(),
227 details: None,
228 },
229 }
230 }
231
232 pub fn error_with_details(
234 id: u64,
235 code: impl Into<String>,
236 message: impl Into<String>,
237 details: JsonValue,
238 ) -> Self {
239 Self::Error {
240 id,
241 error: ErrorObject {
242 code: code.into(),
243 message: message.into(),
244 details: Some(details),
245 },
246 }
247 }
248}
249
250#[derive(Debug, Clone, Serialize, Deserialize)]
252pub struct ErrorObject {
253 pub code: String,
255
256 pub message: String,
258
259 #[serde(skip_serializing_if = "Option::is_none")]
261 pub details: Option<JsonValue>,
262}
263
264#[derive(Debug, Clone, Serialize, Deserialize)]
266pub struct Event {
267 pub subscription_id: String,
269
270 pub sequence: u64,
272
273 pub data: JsonValue,
275
276 pub timestamp: String,
278
279 #[serde(skip_serializing_if = "Option::is_none")]
281 pub dropped: Option<u64>,
282}
283
284#[cfg(test)]
285mod tests {
286 use super::*;
287 use alloc::string::ToString;
288 use alloc::vec;
289
290 #[test]
291 fn test_hello_serialization() {
292 let hello = HelloMessage {
293 version: PROTOCOL_VERSION.to_string(),
294 client: "test-client".to_string(),
295 capabilities: Some(vec!["read".to_string()]),
296 auth_token: None,
297 };
298
299 let json = serde_json::to_string(&hello).unwrap();
300 assert!(json.contains("\"version\":\"4.0\""));
301 assert!(json.contains("\"client\":\"test-client\""));
302 }
303
304 fn welcome(instance_name: Option<&str>) -> WelcomeMessage {
305 WelcomeMessage {
306 version: PROTOCOL_VERSION.to_string(),
307 server: "aimdb".to_string(),
308 permissions: vec!["read".to_string()],
309 writable_records: vec![],
310 max_subscriptions: Some(8),
311 authenticated: Some(false),
312 instance_name: instance_name.map(String::from),
313 }
314 }
315
316 #[test]
317 fn instance_name_is_omitted_when_unset() {
318 let json = serde_json::to_string(&welcome(None)).unwrap();
319 assert!(!json.contains("instance_name"), "{json}");
320 let json = serde_json::to_string(&welcome(Some("gateway-3"))).unwrap();
321 assert!(json.contains(r#""instance_name":"gateway-3""#), "{json}");
322 }
323
324 #[test]
327 fn welcome_is_compatible_both_ways() {
328 #[derive(Deserialize, Serialize)]
330 struct WelcomeV30 {
331 version: String,
332 server: String,
333 permissions: Vec<String>,
334 writable_records: Vec<String>,
335 #[serde(skip_serializing_if = "Option::is_none")]
336 max_subscriptions: Option<usize>,
337 #[serde(skip_serializing_if = "Option::is_none")]
338 authenticated: Option<bool>,
339 }
340
341 let v31 = serde_json::to_string(&welcome(Some("gateway-3"))).unwrap();
342 let old: WelcomeV30 = serde_json::from_str(&v31).unwrap();
343 assert_eq!(old.server, "aimdb");
344
345 let v30 = serde_json::to_string(&WelcomeV30 {
346 version: "3.0".to_string(),
347 ..old
348 })
349 .unwrap();
350 let new: WelcomeMessage = serde_json::from_str(&v30).unwrap();
351 assert_eq!(new.instance_name, None);
352 }
353
354 #[test]
355 fn post_link_reply_shapes() {
356 let cases = [
357 (PostLinkReply::Erased, r#"{"state":"erased"}"#),
358 (
359 PostLinkReply::Written { len: 1472 },
360 r#"{"state":"written","len":1472}"#,
361 ),
362 (PostLinkReply::Malformed, r#"{"state":"malformed"}"#),
363 ];
364 for (reply, json) in cases {
365 assert_eq!(serde_json::to_string(&reply).unwrap(), json);
366 assert_eq!(serde_json::from_str::<PostLinkReply>(json).unwrap(), reply);
367 }
368 }
369
370 #[test]
371 fn version_compatible_matches_on_major() {
372 assert!(version_compatible(PROTOCOL_VERSION));
374 assert!(version_compatible("4.0"));
375 assert!(version_compatible("4.7"));
376 assert!(version_compatible("4")); assert!(!version_compatible("3.1"));
381 assert!(!version_compatible("3.0"));
382 assert!(!version_compatible("2.0"));
383 assert!(!version_compatible("1.0"));
384
385 assert!(!version_compatible(""));
387 assert!(!version_compatible(".0"));
388 assert!(!version_compatible("garbage"));
389 }
390
391 #[test]
392 fn test_request_serialization() {
393 let request = Request {
394 id: 1,
395 method: "record.list".to_string(),
396 params: Some(serde_json::json!({})),
397 };
398
399 let json = serde_json::to_string(&request).unwrap();
400 assert!(json.contains("\"id\":1"));
401 assert!(json.contains("\"method\":\"record.list\""));
402 }
403
404 #[test]
405 fn test_response_success() {
406 let response = Response::success(1, serde_json::json!({"status": "ok"}));
407
408 let json = serde_json::to_string(&response).unwrap();
409 assert!(json.contains("\"id\":1"));
410 assert!(json.contains("\"result\""));
411 assert!(json.contains("\"status\":\"ok\""));
412 }
413
414 #[test]
415 fn test_response_error() {
416 let response = Response::error(2, "NOT_FOUND", "Record not found");
417
418 let json = serde_json::to_string(&response).unwrap();
419 assert!(json.contains("\"id\":2"));
420 assert!(json.contains("\"error\""));
421 assert!(json.contains("\"code\":\"NOT_FOUND\""));
422 assert!(json.contains("\"message\":\"Record not found\""));
423 }
424
425 #[test]
426 fn test_event_serialization() {
427 let event = Event {
428 subscription_id: "sub-123".to_string(),
429 sequence: 42,
430 data: serde_json::json!({"temp": 23.5}),
431 timestamp: "1730379296.123456789".to_string(),
432 dropped: None,
433 };
434
435 let json = serde_json::to_string(&event).unwrap();
436 assert!(json.contains("\"subscription_id\":\"sub-123\""));
437 assert!(json.contains("\"sequence\":42"));
438 assert!(json.contains("\"temp\":23.5"));
439 }
440
441 #[test]
442 fn test_event_with_dropped() {
443 let event = Event {
444 subscription_id: "sub-456".to_string(),
445 sequence: 100,
446 data: serde_json::json!({"value": 1}),
447 timestamp: "1730379300.987654321".to_string(),
448 dropped: Some(5),
449 };
450
451 let json = serde_json::to_string(&event).unwrap();
452 assert!(json.contains("\"dropped\":5"));
453 }
454}