// TODO: Convert the implementation to use bounded channels.
use crate::data::{Ticket, TicketDraft};
use crate::store::{TicketId, TicketStore};
-use std::sync::mpsc::{Receiver, Sender};
+use std::sync::mpsc::{sync_channel, Receiver, Sender, SyncSender};
pub mod data;
pub mod store;
#[derive(Clone)]
pub struct TicketStoreClient {
- sender: todo!(),
+ sender: SyncSender<Command>,
}
impl TicketStoreClient {
- pub fn insert(&self, draft: TicketDraft) -> Result<TicketId, todo!()> {
- todo!()
+ pub fn insert(&self, draft: TicketDraft) -> Result<TicketId, OverloadedError> {
+ let (response_sender, response_receiver) = sync_channel(1);
+ self.sender
+ .send(Command::Insert {
+ draft,
+ response_channel: response_sender,
+ })
+ .map_err(|_| OverloadedError)?;
+ Ok(response_receiver.recv().unwrap())
}
- pub fn get(&self, id: TicketId) -> Result<Option<Ticket>, todo!()> {
- todo!()
+ pub fn get(&self, id: TicketId) -> Result<Option<Ticket>, OverloadedError> {
+ let (response_sender, response_receiver) = sync_channel(1);
+ self.sender
+ .send(Command::Get {
+ id,
+ response_channel: response_sender,
+ })
+ .map_err(|_| OverloadedError)?;
+ Ok(response_receiver.recv().unwrap())
}
}
+#[derive(Debug, thiserror::Error)]
+#[error("The store is overloaded")]
+pub struct OverloadedError;
+
pub fn launch(capacity: usize) -> TicketStoreClient {
- todo!();
+ let (sender, receiver) = sync_channel(capacity);
std::thread::spawn(move || server(receiver));
- todo!()
+ TicketStoreClient { sender }
}
enum Command {
Insert {
draft: TicketDraft,
- response_channel: todo!(),
+ response_channel: SyncSender<TicketId>,
},
Get {
id: TicketId,
- response_channel: todo!(),
+ response_channel: SyncSender<Option<Ticket>>,
},
}
-pub fn server(receiver: Receiver<Command>) {
+fn server(receiver: Receiver<Command>) {
let mut store = TicketStore::new();
loop {
match receiver.recv() {
response_channel,
}) => {
let id = store.add_ticket(draft);
- todo!()
+ response_channel.send(id).unwrap();
}
Ok(Command::Get {
id,
response_channel,
}) => {
let ticket = store.get(id);
- todo!()
+ response_channel.send(ticket.cloned()).unwrap();
}
Err(_) => {
// There are no more senders, so we can safely break