use serde::{Deserialize, Serialize};
use serde_json::Value;
pub const MAX_LINE: u64 = 1 << 20;
pub const PROTOCOL: u32 = 1;
#[derive(Debug, Serialize, Deserialize)]
pub struct Request {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<u64>,
pub method: String,
#[serde(default, skip_serializing_if = "Value::is_null")]
pub params: Value,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Response {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub result: Option<Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<ErrorBody>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ErrorBody {
pub code: String,
pub message: String,
#[serde(default, skip_serializing_if = "no_data")]
pub data: Option<Value>,
}
fn no_data(data: &Option<Value>) -> bool {
matches!(data, None | Some(Value::Null))
}
impl Response {
pub fn ok(id: Option<u64>, result: Value) -> Self {
Self { id, result: Some(result), error: None }
}
pub fn err(id: Option<u64>, code: &str, message: impl Into<String>) -> Self {
Self::err_with(id, code, message, None)
}
pub fn err_with(id: Option<u64>, code: &str, message: impl Into<String>, data: Option<Value>) -> Self {
Self { id, result: None, error: Some(ErrorBody { code: code.into(), message: message.into(), data }) }
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HelloParams {
pub version: String,
#[serde(default)]
pub build: u64,
#[serde(default)]
pub client: String,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub force: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HelloResult {
pub version: String,
pub build: u64,
#[serde(default)]
pub protocol: u32,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub handoff: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Notification {
pub method: String,
#[serde(default)]
pub params: Value,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Version {
pub semver: String,
pub build: u64,
}
impl Version {
pub fn current() -> Self {
Self { semver: env!("CARGO_PKG_VERSION").into(), build: crate::exe::own_build_stamp().unwrap_or(0) }
}
fn key(&self) -> (u64, u64, u64, u64) {
let (a, b, c) = semver_triple(&self.semver);
(a, b, c, self.build)
}
pub fn is_newer_than(&self, other: &Version) -> bool {
self.key() > other.key()
}
}
pub fn semver_triple(s: &str) -> (u64, u64, u64) {
let mut parts = s.split('.').map(|p| {
let digits: String = p.chars().take_while(char::is_ascii_digit).collect();
digits.parse().unwrap_or(0)
});
(parts.next().unwrap_or(0), parts.next().unwrap_or(0), parts.next().unwrap_or(0))
}
#[cfg(test)]
mod tests {
use super::*;
fn v(semver: &str, build: u64) -> Version {
Version { semver: semver.into(), build }
}
#[test]
fn semver_parses_numeric_prefixes() {
assert_eq!(semver_triple("0.6.0"), (0, 6, 0));
assert_eq!(semver_triple("1.10.2"), (1, 10, 2));
assert_eq!(semver_triple("0.7.0-rc1"), (0, 7, 0));
assert_eq!(semver_triple("2"), (2, 0, 0));
assert_eq!(semver_triple("x.y"), (0, 0, 0));
}
#[test]
fn newer_compares_semver_numerically_then_build() {
assert!(v("0.6.0", 2).is_newer_than(&v("0.6.0", 1)));
assert!(!v("0.6.0", 1).is_newer_than(&v("0.6.0", 1)));
assert!(!v("0.6.0", 0).is_newer_than(&v("0.6.0", 1)));
assert!(v("0.10.0", 0).is_newer_than(&v("0.9.0", 99)));
assert!(!v("0.5.9", 999).is_newer_than(&v("0.6.0", 1)));
}
#[test]
fn wire_shapes() {
let req: Request = serde_json::from_str(r#"{"method":"hello","params":{"version":"0.6.0","build":2,"client":"cli"}}"#).unwrap();
assert_eq!((req.id, req.method.as_str()), (None, "hello"));
let hello: HelloParams = serde_json::from_value(req.params).unwrap();
assert_eq!((hello.version.as_str(), hello.build, hello.client.as_str(), hello.force), ("0.6.0", 2, "cli", false));
let forced = HelloParams { force: true, ..hello };
assert_eq!(
serde_json::to_value(&forced).unwrap(),
serde_json::json!({"version":"0.6.0","build":2,"client":"cli","force":true})
);
let quiet = HelloResult { version: "0.6.0".into(), build: 1, protocol: PROTOCOL, handoff: false };
let ok = Response::ok(Some(1), serde_json::to_value(&quiet).unwrap());
assert_eq!(
serde_json::to_value(&ok).unwrap(),
serde_json::json!({"id":1,"result":{"version":"0.6.0","build":1,"protocol":1}})
);
let handoff = HelloResult { handoff: true, ..quiet };
assert_eq!(serde_json::to_string(&handoff).unwrap(), r#"{"version":"0.6.0","build":1,"protocol":1,"handoff":true}"#);
let old: HelloResult = serde_json::from_str(r#"{"version":"0.6.0","build":1}"#).unwrap();
assert_eq!(old.protocol, 0);
let note = Notification { method: "inbox.changed".into(), params: serde_json::json!({"generation":2}) };
assert_eq!(serde_json::to_string(¬e).unwrap(), r#"{"method":"inbox.changed","params":{"generation":2}}"#);
let err = Response::err(Some(3), "unknown-method", "nope");
assert_eq!(
serde_json::to_string(&err).unwrap(),
r#"{"id":3,"error":{"code":"unknown-method","message":"nope"}}"#
);
let null = Response::err_with(Some(3), "x", "m", Some(Value::Null));
assert_eq!(serde_json::to_string(&null).unwrap(), r#"{"id":3,"error":{"code":"x","message":"m"}}"#);
let failed = Response::err_with(Some(4), "failed", "boom", Some(serde_json::json!({"exit": 1})));
assert_eq!(
serde_json::to_string(&failed).unwrap(),
r#"{"id":4,"error":{"code":"failed","message":"boom","data":{"exit":1}}}"#
);
}
}