|
1 | 1 | use byteorder::WriteBytesExt; |
2 | 2 | use futures::stream::Stream; |
3 | | -use interprocess::local_socket::tokio::Stream as InterprocessTokioStream; |
4 | 3 | use interprocess::local_socket::traits::Stream as InterprocessStreamTrait; |
5 | 4 | use interprocess::local_socket::traits::tokio::Listener as TokioListener; |
6 | 5 | use interprocess::local_socket::{GenericNamespaced, ListenerOptions, ToNsName}; |
7 | 6 | use interprocess::local_socket::{Name, Stream as InterprocessStream}; |
8 | 7 |
|
9 | 8 | use tokio::io::AsyncReadExt; |
10 | 9 |
|
| 10 | +use async_stream::stream; |
| 11 | + |
11 | 12 | #[derive(Debug, Clone)] |
12 | 13 | pub enum IpcEvent { |
13 | 14 | Show, |
@@ -38,33 +39,43 @@ fn get_name() -> anyhow::Result<Name<'static>> { |
38 | 39 | Ok(name) |
39 | 40 | } |
40 | 41 |
|
41 | | -pub async fn create_stream() -> anyhow::Result<InterprocessTokioStream> { |
| 42 | +pub fn stream() -> anyhow::Result<impl Stream<Item = IpcEvent>> { |
42 | 43 | let name = get_name()?; |
43 | | - |
44 | 44 | let opts = ListenerOptions::new().name(name); |
45 | | - |
46 | 45 | let listener = opts.create_tokio()?; |
47 | 46 |
|
48 | | - let stream = listener.accept().await?; |
49 | | - Ok(stream) |
50 | | -} |
| 47 | + let stream = stream! { |
51 | 48 |
|
52 | | -pub fn parse_stream(stream: InterprocessTokioStream) -> impl Stream<Item = IpcEvent> { |
53 | | - futures::stream::unfold(stream, |mut stream| async { |
54 | | - match stream.read_u8().await { |
55 | | - Ok(value) => match value.try_into() { |
56 | | - Ok(event) => Some((event, stream)), |
57 | | - Err(()) => { |
58 | | - error!("can't parse ipc event"); |
59 | | - None |
| 49 | + loop { |
| 50 | + match listener.accept().await { |
| 51 | + Ok(mut client) => { |
| 52 | + loop { |
| 53 | + match client.read_u8().await { |
| 54 | + Ok(byte) => match byte.try_into() { |
| 55 | + Ok(event) => yield event, |
| 56 | + Err(_) => { |
| 57 | + error!("can't parse ipc event"); |
| 58 | + } |
| 59 | + }, |
| 60 | + Err(e) => { |
| 61 | + if e.kind() == std::io::ErrorKind::UnexpectedEof { |
| 62 | + } else { |
| 63 | + error!("error reading client: {e}"); |
| 64 | + } |
| 65 | + break; |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + Err(e) => { |
| 71 | + error!("error accepting client: {e}"); |
| 72 | + tokio::time::sleep(std::time::Duration::from_millis(100)).await; |
60 | 73 | } |
61 | | - }, |
62 | | - Err(e) => { |
63 | | - error!("{e}"); |
64 | | - None |
65 | 74 | } |
66 | 75 | } |
67 | | - }) |
| 76 | + }; |
| 77 | + |
| 78 | + Ok(stream) |
68 | 79 | } |
69 | 80 |
|
70 | 81 | pub fn send_event(event: IpcEvent) -> anyhow::Result<()> { |
|
0 commit comments