use std::collections::HashMap;
use std::io::Write as _;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc::{self, Sender};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use serde::{Deserialize, Serialize};
use tilo_socket::Stream;
use wire_frame::Framing;
use crate::{
AlarmSchedule, AlarmState, CalendarAlarm, CloseReason, Feature, Notification, Notifier,
NotifyError, PriorityContact, Scheduled, SystemTime, Unsupported,
};
pub const FD_ENV: &str = "TILO_SVC_NOTIFY_FD";
const FRAME: Framing = Framing::little_endian(1024 * 1024);
const WAIT: Duration = Duration::from_secs(30);
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AlarmRequest {
pub hour: u8,
pub minute: u8,
pub weekdays: u8,
pub enabled_at_ms: i64,
pub last_rung: Option<String>,
}
impl AlarmRequest {
#[must_use]
pub fn of(schedule: &AlarmSchedule) -> Option<Self> {
Some(Self {
hour: schedule.alarm.hour,
minute: schedule.alarm.minute,
weekdays: schedule.alarm.weekdays,
enabled_at_ms: schedule.enabled_at_ms,
last_rung: schedule
.last_rung
.map(|date| date.to_string())
.filter(|date| !date.is_empty()),
})
}
#[must_use]
pub fn schedule(&self) -> AlarmSchedule {
AlarmSchedule {
alarm: CalendarAlarm {
hour: self.hour,
minute: self.minute,
weekdays: self.weekdays,
},
enabled_at_ms: self.enabled_at_ms,
last_rung: self
.last_rung
.as_deref()
.and_then(|date| jiff::civil::Date::strptime("%Y-%m-%d", date).ok()),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Request {
Show {
id: u64,
notification: Notification,
},
Withdraw {
id: u64,
tag: String,
},
Schedule {
id: u64,
notification: Notification,
at: SystemTime,
},
ScheduleAlarm {
id: u64,
notification: Notification,
at: SystemTime,
alarm: AlarmRequest,
},
Scheduled {
id: u64,
},
AlarmStates {
id: u64,
},
CancelScheduled {
id: u64,
tag: String,
},
PriorityContacts {
id: u64,
contacts: Vec<PriorityContact>,
},
}
impl Request {
#[must_use]
pub const fn id(&self) -> u64 {
match self {
Self::Show { id, .. }
| Self::Withdraw { id, .. }
| Self::Schedule { id, .. }
| Self::ScheduleAlarm { id, .. }
| Self::Scheduled { id }
| Self::AlarmStates { id }
| Self::CancelScheduled { id, .. }
| Self::PriorityContacts { id, .. } => *id,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AlarmStateWire {
pub tag: String,
pub alarm: AlarmRequest,
pub next_at: Option<SystemTime>,
pub last_at: Option<SystemTime>,
}
impl AlarmStateWire {
#[must_use]
pub fn of(state: &AlarmState) -> Self {
Self {
tag: state.tag.clone(),
alarm: AlarmRequest {
hour: state.alarm.hour,
minute: state.alarm.minute,
weekdays: state.alarm.weekdays,
enabled_at_ms: state.enabled_at_ms,
last_rung: state.last_rung.map(|date| date.to_string()),
},
next_at: state.next_at,
last_at: state.last_at,
}
}
#[must_use]
pub fn state(&self) -> AlarmState {
AlarmState {
tag: self.tag.clone(),
alarm: self.alarm.schedule().alarm,
enabled_at_ms: self.alarm.enabled_at_ms,
next_at: self.next_at,
last_at: self.last_at,
last_rung: self
.alarm
.last_rung
.as_deref()
.and_then(|date| jiff::civil::Date::strptime("%Y-%m-%d", date).ok()),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Answer {
Done,
Scheduled(Vec<Scheduled>),
Alarms(Vec<AlarmStateWire>),
Refused(Refusal),
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Refusal {
Unsupported,
Invalid(String),
Failed(String),
Unavailable,
}
impl Refusal {
#[must_use]
pub fn error(&self) -> NotifyError {
match self {
Self::Unsupported => NotifyError::Unsupported(Unsupported::of(Feature::Schedule)),
Self::Invalid(reason) | Self::Failed(reason) => NotifyError::Failed(reason.clone()),
Self::Unavailable => NotifyError::Unavailable,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Message {
Answer {
id: u64,
answer: Answer,
},
Activated {
uri: String,
},
Closed {
tag: String,
reason: CloseReason,
},
}
pub trait NotifySide: Send + Sync {
fn attached(&self, channel: Arc<Channel>) {
drop(channel);
}
fn show(&self, notification: &Notification) -> Result<(), Refusal>;
fn withdraw(&self, tag: &str) -> Result<(), Refusal>;
fn schedule(
&self,
notification: &Notification,
at: SystemTime,
alarm: Option<&AlarmRequest>,
) -> Result<(), Refusal>;
fn scheduled(&self) -> Result<Vec<Scheduled>, Refusal>;
fn alarm_states(&self) -> Result<Vec<AlarmState>, Refusal>;
fn cancel_scheduled(&self, tag: &str) -> Result<(), Refusal>;
fn priority_contacts(&self, _contacts: &[PriorityContact]) -> Result<(), Refusal> {
Err(Refusal::Unsupported)
}
}
pub struct Channel {
writer: Mutex<Stream>,
}
impl Channel {
pub fn activated(&self, uri: &str) {
self.send(&Message::Activated {
uri: uri.to_owned(),
});
}
pub fn closed(&self, tag: &str, reason: CloseReason) {
self.send(&Message::Closed {
tag: tag.to_owned(),
reason,
});
}
fn answer(&self, id: u64, answer: Answer) {
self.send(&Message::Answer { id, answer });
}
fn send(&self, message: &Message) {
let Ok(bytes) = serde_json::to_vec(message) else {
return;
};
let Ok(mut writer) = self.writer.lock() else {
return;
};
if FRAME.write(&mut *writer, &bytes).is_ok() {
let _ = writer.flush();
}
}
}
pub fn serve(stream: Stream, side: &dyn NotifySide) {
let Ok(writer) = stream.try_clone() else {
return;
};
let channel = Arc::new(Channel {
writer: Mutex::new(writer),
});
side.attached(Arc::clone(&channel));
let mut reader = stream;
while let Ok(Some(frame)) = FRAME.read(&mut reader) {
let Ok(request) = serde_json::from_slice::<Request>(&frame) else {
return;
};
let id = request.id();
channel.answer(id, answer(side, request));
}
}
fn answer(side: &dyn NotifySide, request: Request) -> Answer {
let done = match request {
Request::Show { notification, .. } => crate::validate(¬ification)
.map_err(refused)
.and_then(|()| side.show(¬ification)),
Request::Withdraw { tag, .. } => crate::validate_tag(&tag)
.map_err(refused)
.and_then(|()| side.withdraw(&tag)),
Request::Schedule {
notification, at, ..
} => crate::validate(¬ification)
.map_err(refused)
.and_then(|()| side.schedule(¬ification, at, None)),
Request::ScheduleAlarm {
notification,
at,
alarm,
..
} => crate::validate(¬ification)
.map_err(refused)
.and_then(|()| side.schedule(¬ification, at, Some(&alarm))),
Request::Scheduled { .. } => {
return match side.scheduled() {
Ok(rows) => Answer::Scheduled(rows),
Err(refusal) => Answer::Refused(refusal),
};
}
Request::AlarmStates { .. } => {
return match side.alarm_states() {
Ok(states) => Answer::Alarms(states.iter().map(AlarmStateWire::of).collect()),
Err(refusal) => Answer::Refused(refusal),
};
}
Request::CancelScheduled { tag, .. } => crate::validate_tag(&tag)
.map_err(refused)
.and_then(|()| side.cancel_scheduled(&tag)),
Request::PriorityContacts { contacts, .. } => side.priority_contacts(&contacts),
};
match done {
Ok(()) => Answer::Done,
Err(refusal) => Answer::Refused(refusal),
}
}
fn refused(error: NotifyError) -> Refusal {
match error {
NotifyError::Invalid(reason) => Refusal::Invalid(reason.to_owned()),
NotifyError::Unsupported(_) => Refusal::Unsupported,
NotifyError::Failed(reason) => Refusal::Failed(reason),
NotifyError::Unavailable => Refusal::Unavailable,
}
}
fn inherited() -> Option<&'static Arc<Connection>> {
static INHERITED: std::sync::OnceLock<Option<Arc<Connection>>> = std::sync::OnceLock::new();
INHERITED
.get_or_init(|| {
let fd = std::env::var(FD_ENV).ok()?.parse::<i32>().ok()?;
if fd < 0 {
return None;
}
let stream = Stream::from(unsafe {
<std::os::fd::OwnedFd as std::os::fd::FromRawFd>::from_raw_fd(fd)
});
Connection::start(stream)
})
.as_ref()
}
#[must_use]
pub fn inherited_service() -> bool {
inherited().is_some()
}
pub fn publish_priority_contacts(contacts: &[PriorityContact]) -> Result<(), NotifyError> {
let Some(connection) = inherited() else {
return Err(NotifyError::Unavailable);
};
let notifier = ServiceNotifier {
connection: Arc::clone(connection),
};
let contacts = contacts.to_vec();
ServiceNotifier::did(notifier.ask(move |id| Request::PriorityContacts { id, contacts })?)
}
pub struct ServiceNotifier {
connection: Arc<Connection>,
}
struct Connection {
writer: Mutex<Stream>,
waiting: Mutex<HashMap<u64, Sender<Answer>>>,
next: AtomicU64,
}
impl ServiceNotifier {
#[must_use]
pub fn from_env() -> Option<Self> {
Some(Self {
connection: Arc::clone(inherited()?),
})
}
#[must_use]
pub fn connect(stream: Stream) -> Option<Self> {
Some(Self {
connection: Connection::start(stream)?,
})
}
fn ask(&self, request: impl FnOnce(u64) -> Request) -> Result<Answer, NotifyError> {
let id = self.connection.next.fetch_add(1, Ordering::Relaxed);
let (reply, answer) = mpsc::channel();
self.connection
.waiting
.lock()
.map_err(|_| NotifyError::Unavailable)?
.insert(id, reply);
let sent = serde_json::to_vec(&request(id)).ok().and_then(|bytes| {
let mut writer = self.connection.writer.lock().ok()?;
FRAME.write(&mut *writer, &bytes).ok()?;
writer.flush().ok()
});
if sent.is_none() {
if let Ok(mut waiting) = self.connection.waiting.lock() {
waiting.remove(&id);
}
return Err(NotifyError::Unavailable);
}
answer.recv_timeout(WAIT).map_err(|_| {
if let Ok(mut waiting) = self.connection.waiting.lock() {
waiting.remove(&id);
}
NotifyError::Failed("the notification service did not answer".into())
})
}
fn did(answer: Answer) -> Result<(), NotifyError> {
match answer {
Answer::Done => Ok(()),
Answer::Refused(refusal) => Err(refusal.error()),
Answer::Scheduled(_) | Answer::Alarms(_) => Err(NotifyError::Failed(
"the notification service answered the wrong call".into(),
)),
}
}
}
impl Connection {
fn start(stream: Stream) -> Option<Arc<Self>> {
let reader = stream.try_clone().ok()?;
let connection = Arc::new(Self {
writer: Mutex::new(stream),
waiting: Mutex::default(),
next: AtomicU64::new(1),
});
let following = Arc::clone(&connection);
std::thread::Builder::new()
.name("tilo-notify-service".into())
.spawn(move || following.listen(reader))
.ok()?;
Some(connection)
}
fn listen(&self, mut reader: Stream) {
while let Ok(Some(frame)) = FRAME.read(&mut reader) {
let Ok(message) = serde_json::from_slice::<Message>(&frame) else {
return;
};
match message {
Message::Answer { id, answer } => {
let waiting = self
.waiting
.lock()
.ok()
.and_then(|mut waiting| waiting.remove(&id));
if let Some(reply) = waiting {
let _ = reply.send(answer);
}
}
Message::Activated { uri } => crate::activated(&uri),
Message::Closed { tag, reason } => crate::closed(&tag, reason),
}
}
}
}
impl Notifier for ServiceNotifier {
fn show(&self, notification: &Notification) -> Result<(), NotifyError> {
crate::validate(notification)?;
let notification = notification.clone();
Self::did(self.ask(move |id| Request::Show { id, notification })?)
}
fn withdraw(&self, tag: &str) -> Result<(), NotifyError> {
crate::validate_tag(tag)?;
let tag = tag.to_owned();
Self::did(self.ask(move |id| Request::Withdraw { id, tag })?)
}
fn schedule(&self, notification: &Notification, at: SystemTime) -> Result<(), NotifyError> {
crate::validate(notification)?;
let notification = notification.clone();
Self::did(self.ask(move |id| Request::Schedule {
id,
notification,
at,
})?)
}
fn schedule_alarm(
&self,
notification: &Notification,
at: SystemTime,
schedule: AlarmSchedule,
) -> Result<(), NotifyError> {
crate::validate(notification)?;
if !schedule.alarm.valid() {
return Err(NotifyError::Invalid("invalid alarm time or weekdays"));
}
let alarm = AlarmRequest::of(&schedule)
.ok_or(NotifyError::Invalid("invalid delivered alarm date"))?;
let notification = notification.clone();
Self::did(self.ask(move |id| Request::ScheduleAlarm {
id,
notification,
at,
alarm,
})?)
}
fn scheduled(&self) -> Result<Vec<Scheduled>, NotifyError> {
match self.ask(|id| Request::Scheduled { id })? {
Answer::Scheduled(rows) => Ok(rows),
Answer::Refused(refusal) => Err(refusal.error()),
Answer::Done | Answer::Alarms(_) => Err(NotifyError::Failed(
"the notification service answered the wrong call".into(),
)),
}
}
fn alarm_states(&self) -> Result<Vec<AlarmState>, NotifyError> {
match self.ask(|id| Request::AlarmStates { id })? {
Answer::Alarms(states) => Ok(states.iter().map(AlarmStateWire::state).collect()),
Answer::Refused(refusal) => Err(refusal.error()),
Answer::Done | Answer::Scheduled(_) => Err(NotifyError::Failed(
"the notification service answered the wrong call".into(),
)),
}
}
fn cancel_scheduled(&self, tag: &str) -> Result<(), NotifyError> {
crate::validate_tag(tag)?;
let tag = tag.to_owned();
Self::did(self.ask(move |id| Request::CancelScheduled { id, tag })?)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{NotificationButton, NotificationSender, Severity};
use std::sync::Mutex;
#[derive(Default)]
struct Recorded {
shown: Vec<Notification>,
withdrawn: Vec<String>,
scheduled: Vec<(Notification, SystemTime, Option<AlarmRequest>)>,
cancelled: Vec<String>,
contacts: Vec<PriorityContact>,
channel: Mutex<Option<Arc<Channel>>>,
}
struct Recording(Arc<Mutex<Recorded>>);
impl NotifySide for Recording {
fn attached(&self, channel: Arc<Channel>) {
*self.0.lock().unwrap().channel.lock().unwrap() = Some(channel);
}
fn show(&self, notification: &Notification) -> Result<(), Refusal> {
self.0.lock().unwrap().shown.push(notification.clone());
Ok(())
}
fn withdraw(&self, tag: &str) -> Result<(), Refusal> {
self.0.lock().unwrap().withdrawn.push(tag.to_owned());
Ok(())
}
fn schedule(
&self,
notification: &Notification,
at: SystemTime,
alarm: Option<&AlarmRequest>,
) -> Result<(), Refusal> {
self.0
.lock()
.unwrap()
.scheduled
.push((notification.clone(), at, alarm.cloned()));
Ok(())
}
fn scheduled(&self) -> Result<Vec<Scheduled>, Refusal> {
Ok(self
.0
.lock()
.unwrap()
.scheduled
.iter()
.map(|(notification, at, _)| Scheduled {
tag: notification.tag.clone(),
at: *at,
})
.collect())
}
fn alarm_states(&self) -> Result<Vec<AlarmState>, Refusal> {
Ok(self
.0
.lock()
.unwrap()
.scheduled
.iter()
.filter_map(|(notification, at, alarm)| {
let alarm = alarm.as_ref()?.schedule();
Some(AlarmState {
tag: notification.tag.clone(),
alarm: alarm.alarm,
enabled_at_ms: alarm.enabled_at_ms,
next_at: Some(*at),
last_at: None,
last_rung: alarm.last_rung,
})
})
.collect())
}
fn cancel_scheduled(&self, tag: &str) -> Result<(), Refusal> {
self.0.lock().unwrap().cancelled.push(tag.to_owned());
Ok(())
}
fn priority_contacts(&self, contacts: &[PriorityContact]) -> Result<(), Refusal> {
self.0.lock().unwrap().contacts = contacts.to_vec();
Ok(())
}
}
fn session() -> (ServiceNotifier, Arc<Mutex<Recorded>>) {
let (app, service) = tilo_socket::pair().expect("a socket pair");
let recorded = Arc::new(Mutex::new(Recorded::default()));
let side = Arc::new(Recording(Arc::clone(&recorded)));
std::thread::spawn(move || serve(service, &*side));
let client = ServiceNotifier::connect(app).expect("the connection is usable");
(client, recorded)
}
fn waiting(recorded: &Arc<Mutex<Recorded>>) -> Arc<Channel> {
for _ in 0..1000 {
let channel = { recorded.lock().unwrap().channel.lock().unwrap().clone() };
if let Some(channel) = channel {
return channel;
}
std::thread::yield_now();
}
panic!("the service never attached its channel");
}
#[test]
fn an_app_shows_replaces_and_withdraws_its_notifications_over_its_connection() {
let (client, recorded) = session();
let shown = Notification::new("task", "Saved", "Your change is on every device")
.with_activation("tilo-test:open")
.with_button("Undo", "tilo-test:undo")
.with_severity(Severity::Warning)
.quietly();
client.show(&shown).expect("the service took it");
assert_eq!(recorded.lock().unwrap().shown, [shown]);
client.withdraw("task").expect("the service withdrew it");
assert_eq!(recorded.lock().unwrap().withdrawn, ["task"]);
}
#[test]
fn a_malformed_notification_is_refused_before_it_reaches_the_session() {
let (client, recorded) = session();
assert!(matches!(
client.show(&Notification::new("", "Title", "")),
Err(NotifyError::Invalid(_))
));
assert!(matches!(
client.withdraw("t\nag"),
Err(NotifyError::Invalid(_))
));
assert!(
recorded.lock().unwrap().shown.is_empty(),
"nothing malformed reaches the service"
);
}
#[test]
fn what_the_person_chose_reaches_the_app_that_showed_it() {
let (client, recorded) = session();
let (seen, chosen) = std::sync::mpsc::channel();
crate::set_activation_handler("tilo-service-test", move |uri| {
let _ = seen.send(uri.to_owned());
});
client
.show(&Notification::new("task", "Saved", "").with_activation("tilo-service-test:open"))
.expect("the service took it");
let channel = waiting(&recorded);
channel.activated("tilo-service-test:open");
assert_eq!(
chosen.recv_timeout(Duration::from_secs(30)),
Ok("tilo-service-test:open".to_owned())
);
}
#[test]
fn a_notification_that_goes_away_is_reported_under_its_tag_and_reason() {
let (client, recorded) = session();
let (gone, closings) = std::sync::mpsc::channel();
crate::set_close_handler("tilo-service-close-test:", move |tag, reason| {
let _ = gone.send((tag.to_owned(), reason));
});
client
.show(&Notification::new("tilo-service-close-test:1", "Saved", ""))
.expect("the service took it");
let channel = waiting(&recorded);
channel.closed("tilo-service-close-test:1", CloseReason::Dismissed);
assert_eq!(
closings.recv_timeout(Duration::from_secs(30)),
Ok((
"tilo-service-close-test:1".to_owned(),
CloseReason::Dismissed
))
);
}
#[test]
fn an_alarm_is_scheduled_read_back_and_cancelled_over_the_connection() {
let (client, recorded) = session();
let notification = Notification::new("wake", "Wake up", "It is 7:00");
let at = SystemTime::UNIX_EPOCH + Duration::from_secs(1_800_000_000);
let alarm = AlarmSchedule {
alarm: CalendarAlarm {
hour: 7,
minute: 0,
weekdays: 0,
},
enabled_at_ms: 1_700_000_000_000,
last_rung: Some(jiff::civil::date(2026, 11, 25)),
};
client
.schedule_alarm(¬ification, at, alarm)
.expect("the service scheduled it");
let scheduled = client.scheduled().expect("the deadlines");
assert_eq!(
scheduled,
[Scheduled {
tag: "wake".to_owned(),
at
}]
);
let states = client.alarm_states().expect("the alarms");
assert_eq!(states.len(), 1, "{states:?}");
assert_eq!(states[0].alarm, alarm.alarm);
assert_eq!(states[0].enabled_at_ms, alarm.enabled_at_ms);
assert_eq!(states[0].last_rung, alarm.last_rung);
client
.cancel_scheduled("wake")
.expect("the service cancelled it");
assert_eq!(recorded.lock().unwrap().cancelled, ["wake"]);
}
#[test]
fn priority_contacts_go_over_the_connection_that_names_the_app() {
let (client, recorded) = session();
let contacts = vec![PriorityContact {
id: "person-1".to_owned(),
name: "Ada".to_owned(),
endpoints: vec!["ada@example.com".to_owned()],
}];
client
.ask(move |id| Request::PriorityContacts { id, contacts })
.map(ServiceNotifier::did)
.expect("the service answered")
.expect("the service took them");
assert_eq!(recorded.lock().unwrap().contacts.len(), 1);
assert_eq!(recorded.lock().unwrap().contacts[0].id, "person-1");
}
#[test]
fn a_refusal_is_the_error_the_app_reads() {
struct Refusing;
impl NotifySide for Refusing {
fn show(&self, _notification: &Notification) -> Result<(), Refusal> {
Err(Refusal::Failed("the notification centre is off".into()))
}
fn withdraw(&self, _tag: &str) -> Result<(), Refusal> {
Err(Refusal::Unsupported)
}
fn schedule(
&self,
_notification: &Notification,
_at: SystemTime,
_alarm: Option<&AlarmRequest>,
) -> Result<(), Refusal> {
Err(Refusal::Unsupported)
}
fn scheduled(&self) -> Result<Vec<Scheduled>, Refusal> {
Err(Refusal::Unsupported)
}
fn alarm_states(&self) -> Result<Vec<AlarmState>, Refusal> {
Err(Refusal::Unsupported)
}
fn cancel_scheduled(&self, _tag: &str) -> Result<(), Refusal> {
Err(Refusal::Unsupported)
}
}
let (app, service) = tilo_socket::pair().expect("a socket pair");
std::thread::spawn(move || {
let side = Refusing;
serve(service, &side);
});
let client = ServiceNotifier::connect(app).expect("the connection is usable");
assert_eq!(
client.show(&Notification::new("t", "Title", "")),
Err(NotifyError::Failed("the notification centre is off".into()))
);
assert!(matches!(
client.withdraw("t"),
Err(NotifyError::Unsupported(_))
));
}
#[test]
fn a_process_the_launcher_handed_no_service_is_refused() {
let mut env = tilo_test_env::ScopedEnv::new();
env.remove(FD_ENV);
let notifier = crate::system(Some("so.tilo.notify-test"));
assert_eq!(
notifier.show(&Notification::new("t", "Title", "")),
Err(NotifyError::Unavailable)
);
assert_eq!(notifier.withdraw("t"), Err(NotifyError::Unavailable));
}
#[test]
fn every_notification_shape_survives_the_wire() {
let notification = Notification {
tag: "tag".into(),
title: "Title".into(),
body: "Body".into(),
activation: Some("tilo-test:open".into()),
action: Some("Open".into()),
severity: Severity::Error,
buttons: vec![NotificationButton {
label: "Retry".into(),
activation: "tilo-test:retry".into(),
}],
silent: true,
app: Some("Files".into()),
from: Some(NotificationSender {
name: "Ada".into(),
id: "person-1".into(),
agent: false,
}),
};
let request = Request::Show {
id: 7,
notification,
};
let bytes = serde_json::to_vec(&request).expect("the request");
assert_eq!(
serde_json::from_slice::<Request>(&bytes).expect("the request"),
request
);
}
}