#[cfg(test)]
use std::sync::Arc;
#[cfg(test)]
use bytes::Bytes;
use livekit::{id::ParticipantIdentity, ByteStreamWriter, StreamWriter};
use crate::remote_access::RemoteAccessError;
pub(crate) struct Participant {
identity: ParticipantIdentity,
writer: ParticipantWriter,
}
impl Participant {
pub fn new(identity: ParticipantIdentity, writer: ParticipantWriter) -> Self {
Self { identity, writer }
}
pub fn identity(&self) -> &ParticipantIdentity {
&self.identity
}
pub(crate) async fn send(&self, bytes: &[u8]) -> Result<(), RemoteAccessError> {
self.writer.write(bytes).await
}
}
impl std::fmt::Debug for Participant {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Participant")
.field("identity", &self.identity)
.finish()
}
}
impl std::fmt::Display for Participant {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Participant({})", self.identity)
}
}
pub(crate) enum ParticipantWriter {
Livekit(ByteStreamWriter),
#[allow(dead_code)]
#[cfg(test)]
Test(Arc<TestByteStreamWriter>),
}
impl ParticipantWriter {
async fn write(&self, bytes: &[u8]) -> Result<(), RemoteAccessError> {
match self {
ParticipantWriter::Livekit(stream) => stream.write(bytes).await.map_err(|e| e.into()),
#[cfg(test)]
ParticipantWriter::Test(writer) => {
writer.record(bytes);
Ok(())
}
}
}
}
#[cfg(test)]
#[derive(Default)]
pub(crate) struct TestByteStreamWriter {
writes: parking_lot::Mutex<Vec<Bytes>>,
}
#[cfg(test)]
impl TestByteStreamWriter {
fn record(&self, data: &[u8]) {
self.writes.lock().push(Bytes::copy_from_slice(data));
}
#[allow(dead_code)]
pub(crate) fn writes(&self) -> Vec<Bytes> {
std::mem::take(&mut self.writes.lock())
}
}