Expose stream metadata changes only after server acknowledgement
This commit is contained in:
1 parent
e52db5b112
commit
f563d2ba9a
6 files changed
+326
-44
No files matched your search
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
## Unreleased
|
## Unreleased
|
||||||
|
|
||||||
|
- A running publisher reports changed stream settings only after the server acknowledges the update. Tighter admission rules apply immediately; looser rules wait for acknowledgement. A late reply cannot replace the state of a disconnected publication.
|
||||||
|
|
||||||
- Stopping a publication sends the close reason required by TS6 beta14. Stream discovery now distinguishes a server refusal for the requested participant from a successful lookup with no streams.
|
- Stopping a publication sends the close reason required by TS6 beta14. Stream discovery now distinguishes a server refusal for the requested participant from a successful lookup with no streams.
|
||||||
|
|
||||||
- A server stop naming only the local publisher now releases its registered capture. Queued stream notifications stay with the publication that received them and cannot stop its replacement.
|
- A server stop naming only the local publisher now releases its registered capture. Queued stream notifications stay with the publication that received them and cannot stop its replacement.
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
## Current Windows account-free checkpoint (2026-11-26)
|
## Current Windows account-free checkpoint (2026-11-26)
|
||||||
|
|
||||||
|
**Stream metadata updates on beta14:** In `duplex_qa --stream-lifecycle`, the observer requested the publisher's stream before the update and again after the server acknowledged it. The same stream ID and owner were returned with a new name, bitrate 2500 instead of 1000, viewer limit 3 instead of unlimited, and audio enabled instead of disabled. Both clients disconnected cleanly. Separate native publisher tests checked the last confirmed options before acknowledgement, admission during privacy changes, server refusal, and a late acknowledgement after disconnect. This measures advertised metadata, not encoded bitrate, actual audio delivery, or the rendered settings dialog.
|
||||||
|
|
||||||
**Stream registration on beta14:** Two muted disposable guests ran `duplex_qa --stream-lifecycle`. The publisher received its assigned ID in `notifystreamstarted`. The observer requested the publisher's stream list and received `notifystreaminfo` matching the ID, name and owner. Beta14 rejected an ID-only stop with TS 1542 (missing parameter). With `reason=1` it acknowledged the stop and the observer received `notifystreamstopped` for that exact stream ID. Both disconnects were confirmed. No viewer joined, and no audio or video was transmitted in this scenario.
|
**Stream registration on beta14:** Two muted disposable guests ran `duplex_qa --stream-lifecycle`. The publisher received its assigned ID in `notifystreamstarted`. The observer requested the publisher's stream list and received `notifystreaminfo` matching the ID, name and owner. Beta14 rejected an ID-only stop with TS 1542 (missing parameter). With `reason=1` it acknowledged the stop and the observer received `notifystreamstopped` for that exact stream ID. Both disconnects were confirmed. No viewer joined, and no audio or video was transmitted in this scenario.
|
||||||
|
|
||||||
**Audio and moving video on two local WebRTC peers:** The focused Windows test `decoded_tone_and_moving_video_on_local_peers` measured the generated 1 kHz tone in 43 of 46 decoded 10 ms audio blocks (22080 samples; normalized RMS 0.06233). A matching block requires more than 80% of its first-channel energy at 1 kHz and a minimum signal level. In the same run libvpx decoded 13 video frames and 12 increasing frame counters reached the display path. The source stop callback ran once. This verifies same-host audio and video transport before physical playback; it does not verify TeamSpeak signaling, an official client or a physical device.
|
**Audio and moving video on two local WebRTC peers:** The focused Windows test `decoded_tone_and_moving_video_on_local_peers` measured the generated 1 kHz tone in 43 of 46 decoded 10 ms audio blocks (22080 samples; normalized RMS 0.06233). A matching block requires more than 80% of its first-channel energy at 1 kHz and a minimum signal level. In the same run libvpx decoded 13 video frames and 12 increasing frame counters reached the display path. The source stop callback ran once. This verifies same-host audio and video transport before physical playback; it does not verify TeamSpeak signaling, an official client or a physical device.
|
||||||
|
|||||||
+70
-16
@@ -3,7 +3,7 @@
|
|||||||
//! `TEAMSPEACH_QA_CORE` to the absolute path of that disposable core executable.
|
//! `TEAMSPEACH_QA_CORE` to the absolute path of that disposable core executable.
|
||||||
//! Duplex: `cargo run --locked -p teamspeach-core --example duplex_qa`.
|
//! Duplex: `cargo run --locked -p teamspeach-core --example duplex_qa`.
|
||||||
//! Whisper: `cargo run --locked -p teamspeach-core --example duplex_qa -- --whisper`.
|
//! Whisper: `cargo run --locked -p teamspeach-core --example duplex_qa -- --whisper`.
|
||||||
//! Stream registration: `cargo run --locked -p teamspeach-core --example duplex_qa -- --stream-lifecycle`.
|
//! Stream registration and update: `cargo run --locked -p teamspeach-core --example duplex_qa -- --stream-lifecycle`.
|
||||||
//! Requires an already running, private TeamSpeak fixture at 127.0.0.1:19987 with
|
//! Requires an already running, private TeamSpeak fixture at 127.0.0.1:19987 with
|
||||||
//! an empty default Opus channel (TS6 beta14 for whisper and stream registration).
|
//! an empty default Opus channel (TS6 beta14 for whisper and stream registration).
|
||||||
//! No server or audio device is started.
|
//! No server or audio device is started.
|
||||||
@@ -882,6 +882,55 @@ fn request_stream_event<T>(peer: &mut Peer, tones: &[Tone; HZ.len()], cmd: &str,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct StreamMetadata<'a> {
|
||||||
|
name: &'a str,
|
||||||
|
bitrate: u32,
|
||||||
|
viewer_limit: u16,
|
||||||
|
audio: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StreamMetadata<'_> {
|
||||||
|
const TYPE: u64 = 2;
|
||||||
|
const ACCESSIBILITY: u64 = 1;
|
||||||
|
const MODE: u64 = 1;
|
||||||
|
|
||||||
|
fn args(&self) -> Value {
|
||||||
|
json!({"name": self.name, "type": Self::TYPE, "accessibility": Self::ACCESSIBILITY,
|
||||||
|
"mode": Self::MODE, "bitrate": self.bitrate, "viewer_limit": self.viewer_limit, "audio": self.audio})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify_list(&self, observer: &mut Peer, tones: &[Tone; HZ.len()], publisher: u64,
|
||||||
|
stream_id: &str, phase: &str) -> Result<()> {
|
||||||
|
let audio = if self.audio { "1" } else { "0" };
|
||||||
|
request_stream_event(observer, tones, "stream_list", json!({"client_id": publisher}),
|
||||||
|
Some(publisher), "notifystreaminfo", |row| {
|
||||||
|
if row["id"].as_str() != Some(stream_id) || stream_owner(row) != Some(publisher) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some((|| {
|
||||||
|
for (field, expected) in [("name", self.name), ("audio", audio)] {
|
||||||
|
let actual = row[field].as_str();
|
||||||
|
if actual != Some(expected) {
|
||||||
|
return Err(format!("{field}: expected {expected:?}, reported {actual:?}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (field, expected) in [("type", Self::TYPE), ("accessibility", Self::ACCESSIBILITY),
|
||||||
|
("mode", Self::MODE), ("bitrate", u64::from(self.bitrate)),
|
||||||
|
("viewer_limit", u64::from(self.viewer_limit))] {
|
||||||
|
let actual = row[field].as_str();
|
||||||
|
if actual.and_then(|value| value.parse::<u64>().ok()) != Some(expected) {
|
||||||
|
return Err(format!("{field}: expected {expected}, reported {actual:?}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})())
|
||||||
|
}).and_then(|metadata| metadata).map_err(|error| format!("{phase} stream discovery: {error}"))?;
|
||||||
|
println!("observer: fresh {phase} notifystreaminfo matched stream ID and owner, name={:?}, type={}, accessibility={}, mode={}, bitrate={}, viewer_limit={}, audio={audio}",
|
||||||
|
self.name, Self::TYPE, Self::ACCESSIBILITY, Self::MODE, self.bitrate, self.viewer_limit);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn stream_lifecycle(qa: &mut Duplex, name: &str) -> Result<()> {
|
fn stream_lifecycle(qa: &mut Duplex, name: &str) -> Result<()> {
|
||||||
for peer in [&mut qa.a, &mut qa.b] {
|
for peer in [&mut qa.a, &mut qa.b] {
|
||||||
let mute = peer.request(&qa.tones, "set_audio", json!({"input_muted": true, "output_muted": true}), CONTROL)?;
|
let mute = peer.request(&qa.tones, "set_audio", json!({"input_muted": true, "output_muted": true}), CONTROL)?;
|
||||||
@@ -910,23 +959,28 @@ fn stream_lifecycle(qa: &mut Duplex, name: &str) -> Result<()> {
|
|||||||
})?;
|
})?;
|
||||||
println!("connect: private loopback TS6 beta14; two disposable guests, roster IDs verified, both mutes active");
|
println!("connect: private loopback TS6 beta14; two disposable guests, roster IDs verified, both mutes active");
|
||||||
|
|
||||||
let stream_id = request_stream_event(&mut qa.a, &qa.tones, "stream_setup", json!({
|
let initial = StreamMetadata { name, bitrate: 1000, viewer_limit: 0, audio: false };
|
||||||
"name": name, "type": 2, "accessibility": 1, "mode": 1, "bitrate": 1000, "viewer_limit": 0, "audio": false,
|
let stream_id = request_stream_event(&mut qa.a, &qa.tones, "stream_setup", initial.args(),
|
||||||
}), None, "notifystreamstarted", |row| {
|
None, "notifystreamstarted", |row| {
|
||||||
(stream_owner(row) == Some(publisher)).then(|| row["id"].as_str().filter(|id| !id.is_empty()).map(str::to_owned)).flatten()
|
(stream_owner(row) == Some(publisher)).then(|| row["id"].as_str().filter(|id| !id.is_empty()).map(str::to_owned)).flatten()
|
||||||
})?;
|
})?;
|
||||||
println!("publisher: fresh own notifystreamstarted supplied the registered stream ID");
|
println!("publisher: fresh own notifystreamstarted supplied the registered stream ID");
|
||||||
|
|
||||||
let listed = request_stream_event(&mut qa.b, &qa.tones, "stream_list", json!({"client_id": publisher}),
|
let checked = (|| {
|
||||||
Some(publisher), "notifystreaminfo", |row| {
|
initial.verify_list(&mut qa.b, &qa.tones, publisher, &stream_id, "initial")?;
|
||||||
(row["id"].as_str() == Some(stream_id.as_str()) && row["name"].as_str() == Some(name)
|
|
||||||
&& stream_owner(row) == Some(publisher)).then_some(())
|
|
||||||
});
|
|
||||||
if listed.is_ok() {
|
|
||||||
println!("observer: fresh notifystreaminfo matched the exact registered ID, name, and owner");
|
|
||||||
}
|
|
||||||
|
|
||||||
// If discovery failed, still unregister the exact ID before disconnecting.
|
let updated_name = format!("{name} updated");
|
||||||
|
let updated = StreamMetadata { name: &updated_name, bitrate: 2500, viewer_limit: 3, audio: true };
|
||||||
|
let mut args = updated.args();
|
||||||
|
args["stream_id"] = json!(&stream_id);
|
||||||
|
let reply = qa.a.request_reply(&qa.tones, "stream_update", args, CONTROL, |_| {})?;
|
||||||
|
require_stream_ack(&qa.a, "stream_update", &reply, None)?;
|
||||||
|
|
||||||
|
// Query only after the update ACK; an unsolicited update notification is not discovery.
|
||||||
|
updated.verify_list(&mut qa.b, &qa.tones, publisher, &stream_id, "updated")
|
||||||
|
})();
|
||||||
|
|
||||||
|
// If discovery or update failed, still unregister the exact ID before disconnecting.
|
||||||
let stopped = (|| {
|
let stopped = (|| {
|
||||||
let since = Instant::now();
|
let since = Instant::now();
|
||||||
let reply = qa.a.request_reply(&qa.tones, "stream_stop", json!({"stream_id": &stream_id}), CONTROL, |_| {})?;
|
let reply = qa.a.request_reply(&qa.tones, "stream_stop", json!({"stream_id": &stream_id}), CONTROL, |_| {})?;
|
||||||
@@ -941,9 +995,9 @@ fn stream_lifecycle(qa: &mut Duplex, name: &str) -> Result<()> {
|
|||||||
println!("observer: fresh notifystreamstopped matched by {matched_by}");
|
println!("observer: fresh notifystreamstopped matched by {matched_by}");
|
||||||
Ok(())
|
Ok(())
|
||||||
})();
|
})();
|
||||||
match (listed, stopped) {
|
match (checked, stopped) {
|
||||||
(Ok(()), result) | (result, Ok(())) => result,
|
(Ok(()), result) | (result, Ok(())) => result,
|
||||||
(Err(list), Err(stop)) => Err(format!("{list}; {stop}")),
|
(Err(check), Err(stop)) => Err(format!("{check}; {stop}")),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -973,7 +1027,7 @@ fn exercise_stream_lifecycle(exe: &Path, root: &Path) -> Result<String> {
|
|||||||
if !errors.is_empty() {
|
if !errors.is_empty() {
|
||||||
return Err(errors.join("; "));
|
return Err(errors.join("; "));
|
||||||
}
|
}
|
||||||
Ok(format!("Stream registration IPC passed. Both cores shut down; server confirmed {confirmed}/2 disconnects. No media or device audio was used."))
|
Ok(format!("Stream lifecycle IPC passed: registration, metadata update, and stop. Both cores shut down; server confirmed {confirmed}/2 disconnects. No media or device audio was used."))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn run() -> Result<String> {
|
fn run() -> Result<String> {
|
||||||
|
|||||||
@@ -4,6 +4,8 @@
|
|||||||
|
|
||||||
## Возврат к разработке на ПК, 2026-11-26
|
## Возврат к разработке на ПК, 2026-11-26
|
||||||
|
|
||||||
|
Windows, база `e52db5b`: на beta14 наблюдатель перечитал имя, битрейт, лимит зрителей и признак аудио у того же потока после подтверждения `stream_update`. В нативном издателе прошли проверки отложенного подтверждения, отказа, ограничений доступа и отключения во время запроса (24 теста сигнализации, отдельно 2 теста ядра). Проверен снимок состояния издателя, не видимое окно настроек и не фактическая скорость передачи.
|
||||||
|
|
||||||
Windows, база `c27a425`: на beta14 прошёл `duplex_qa --stream-lifecycle`. Наблюдатель подтвердил регистрацию и остановку потока по ID; без `reason=1` сервер отвергал остановку с TS 1542. Оба отключения подтверждены. Отдельно прошли тест сериализации ядра и две проверки нативного поиска. Подключение зрителя и медиа через эту сигнализацию пока не проверены.
|
Windows, база `c27a425`: на beta14 прошёл `duplex_qa --stream-lifecycle`. Наблюдатель подтвердил регистрацию и остановку потока по ID; без `reason=1` сервер отвергал остановку с TS 1542. Оба отключения подтверждены. Отдельно прошли тест сериализации ядра и две проверки нативного поиска. Подключение зрителя и медиа через эту сигнализацию пока не проверены.
|
||||||
|
|
||||||
Windows, база `f0ed160`: тест `decoded_tone_and_moving_video_on_local_peers` прошёл на двух нативных WebRTC-пирах. После декодера тон 1 кГц обнаружен в 43 из 46 блоков; одновременно показаны 12 кадров с возрастающим счётчиком. Аудиовыход закрыт, TeamSpeak-сигнализация и официальный клиент не использовались.
|
Windows, база `f0ed160`: тест `decoded_tone_and_moving_video_on_local_peers` прошёл на двух нативных WebRTC-пирах. После декодера тон 1 кГц обнаружен в 43 из 46 блоков; одновременно показаны 12 кадров с возрастающим счётчиком. Аудиовыход закрыт, TeamSpeak-сигнализация и официальный клиент не использовались.
|
||||||
|
|||||||
@@ -33,6 +33,9 @@ impl PublisherOptions {
|
|||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
fn allows_uid(&self, uid: &str) -> bool {
|
||||||
|
self.privacy != Privacy::Contacts || self.allowed_uids.contains(uid)
|
||||||
|
}
|
||||||
fn metadata(&self, stream_id: Option<String>, audio: bool) -> StreamPublishArgs {
|
fn metadata(&self, stream_id: Option<String>, audio: bool) -> StreamPublishArgs {
|
||||||
StreamPublishArgs { stream_id,name:self.name.clone(),stream_type:match self.source_type {SourceType::Camera=>1,SourceType::Screen=>2,SourceType::Window=>3},
|
StreamPublishArgs { stream_id,name:self.name.clone(),stream_type:match self.source_type {SourceType::Camera=>1,SourceType::Screen=>2,SourceType::Window=>3},
|
||||||
accessibility:if self.privacy == Privacy::Closed {3} else {1},mode:1,bitrate:self.sender.video_bitrate_kbps,viewer_limit:self.viewer_limit,audio }
|
accessibility:if self.privacy == Privacy::Closed {3} else {1},mode:1,bitrate:self.sender.video_bitrate_kbps,viewer_limit:self.viewer_limit,audio }
|
||||||
@@ -60,17 +63,32 @@ struct Remote { client_id:u16, identity:ClientIdentity, state:Mutex<RemoteState>
|
|||||||
impl Remote { fn close(&self) { let mut s=self.state.lock().unwrap(); s.deadline=None;s.remote.clear();s.local.clear();if let Some(p)=s.peer.take(){p.close();} } }
|
impl Remote { fn close(&self) { let mut s=self.state.lock().unwrap(); s.deadline=None;s.remote.clear();s.local.clear();if let Some(p)=s.peer.take(){p.close();} } }
|
||||||
struct State {
|
struct State {
|
||||||
status:PublisherState,detail:String,stream_id:Option<String>,options:PublisherOptions,
|
status:PublisherState,detail:String,stream_id:Option<String>,options:PublisherOptions,
|
||||||
|
// While an update is unacknowledged, admission must satisfy both sets of options.
|
||||||
|
pending_options: Option<PublisherOptions>,
|
||||||
source:Option<Arc<dyn PublishSource>>,viewers:BTreeMap<u16,Arc<Remote>>,pending:BTreeMap<u16,ClientIdentity>,
|
source:Option<Arc<dyn PublishSource>>,viewers:BTreeMap<u16,Arc<Remote>>,pending:BTreeMap<u16,ClientIdentity>,
|
||||||
blocked:BTreeMap<String,String>,awaiting:bool,disconnected:bool,unregistered:bool,paused:bool,deadline:Option<Instant>,
|
blocked:BTreeMap<String,String>,awaiting:bool,disconnected:bool,unregistered:bool,paused:bool,deadline:Option<Instant>,
|
||||||
source_muted: bool,
|
source_muted: bool,
|
||||||
}
|
}
|
||||||
|
impl State {
|
||||||
|
fn admission_options(&self) -> impl Iterator<Item = &PublisherOptions> {
|
||||||
|
std::iter::once(&self.options).chain(self.pending_options.as_ref())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn allows_uid(&self, uid: &str) -> bool {
|
||||||
|
!self.blocked.contains_key(uid) && self.admission_options().all(|options| options.allows_uid(uid))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn needs_approval(&self) -> bool {
|
||||||
|
self.admission_options().any(|options| options.privacy == Privacy::Closed)
|
||||||
|
}
|
||||||
|
}
|
||||||
pub struct StreamPublisher {
|
pub struct StreamPublisher {
|
||||||
pub key:SessionKey,pub own_client_id:u16,signal:Arc<dyn Signal>,factory:Arc<dyn PeerFactory>,clients:Arc<dyn ClientResolver>,
|
pub key:SessionKey,pub own_client_id:u16,signal:Arc<dyn Signal>,factory:Arc<dyn PeerFactory>,clients:Arc<dyn ClientResolver>,
|
||||||
state:Mutex<State>,wire:AsyncMutex<()>,updates:AsyncMutex<()>,
|
state:Mutex<State>,wire:AsyncMutex<()>,updates:AsyncMutex<()>,
|
||||||
}
|
}
|
||||||
impl StreamPublisher {
|
impl StreamPublisher {
|
||||||
pub fn new(key:SessionKey,own_client_id:u16,signal:Arc<dyn Signal>,factory:Arc<dyn PeerFactory>,clients:Arc<dyn ClientResolver>)->Arc<Self> {
|
pub fn new(key:SessionKey,own_client_id:u16,signal:Arc<dyn Signal>,factory:Arc<dyn PeerFactory>,clients:Arc<dyn ClientResolver>)->Arc<Self> {
|
||||||
Arc::new(Self {key,own_client_id,signal,factory,clients,state:Mutex::new(State {status:PublisherState::Idle,detail:String::new(),stream_id:None,options:PublisherOptions::default(),source:None,viewers:BTreeMap::new(),pending:BTreeMap::new(),blocked:BTreeMap::new(),awaiting:false,disconnected:false,unregistered:false,paused:false,source_muted:false,deadline:None}),wire:AsyncMutex::new(()),updates:AsyncMutex::new(())})
|
Arc::new(Self {key,own_client_id,signal,factory,clients,state:Mutex::new(State {status:PublisherState::Idle,detail:String::new(),stream_id:None,options:PublisherOptions::default(),pending_options:None,source:None,viewers:BTreeMap::new(),pending:BTreeMap::new(),blocked:BTreeMap::new(),awaiting:false,disconnected:false,unregistered:false,paused:false,source_muted:false,deadline:None}),wire:AsyncMutex::new(()),updates:AsyncMutex::new(())})
|
||||||
}
|
}
|
||||||
pub fn snapshot(&self)->PublisherSnapshot {
|
pub fn snapshot(&self)->PublisherSnapshot {
|
||||||
let s=self.state.lock().unwrap();
|
let s=self.state.lock().unwrap();
|
||||||
@@ -157,12 +175,12 @@ impl StreamPublisher {
|
|||||||
async fn request_viewer(self:&Arc<Self>,id:u16){
|
async fn request_viewer(self:&Arc<Self>,id:u16){
|
||||||
let Some(client)=self.clients.resolve(&self.key,id).filter(|c|!c.uid.is_empty()) else{return;};
|
let Some(client)=self.clients.resolve(&self.key,id).filter(|c|!c.uid.is_empty()) else{return;};
|
||||||
let uid={let mut s=self.state.lock().unwrap();
|
let uid={let mut s=self.state.lock().unwrap();
|
||||||
if s.viewers.contains_key(&id)||s.pending.contains_key(&id){return;}
|
if !s.status.active()||s.viewers.contains_key(&id)||s.pending.contains_key(&id){return;}
|
||||||
if s.blocked.contains_key(&client.uid)||(s.options.privacy==Privacy::Contacts&&!s.options.allowed_uids.contains(&client.uid)){Err(client.uid)}
|
if !s.allows_uid(&client.uid){Err(client.uid)}
|
||||||
else if s.options.privacy==Privacy::Closed{s.pending.insert(id,client);return;}
|
else if s.needs_approval(){s.pending.insert(id,client);return;}
|
||||||
else{let uid=client.uid.clone();s.pending.insert(id,client);Ok(uid)}
|
else{let uid=client.uid.clone();s.pending.insert(id,client);Ok(uid)}
|
||||||
};
|
};
|
||||||
match uid{Ok(uid)=>{let _=self.approve_viewer(id,&uid).await;},Err(uid)=>{let _=self.decline(id,&uid,"not_authorized").await;}}
|
match uid{Ok(uid)=>{let _=self.admit_viewer(id,&uid,false).await;},Err(uid)=>{let _=self.decline(id,&uid,"not_authorized").await;}}
|
||||||
}
|
}
|
||||||
async fn decline(&self,id:u16,uid:&str,reason:&str)->Result<(),StreamError>{
|
async fn decline(&self,id:u16,uid:&str,reason:&str)->Result<(),StreamError>{
|
||||||
let Some(stream)=self.state.lock().unwrap().stream_id.clone()else{return Ok(());};
|
let Some(stream)=self.state.lock().unwrap().stream_id.clone()else{return Ok(());};
|
||||||
@@ -179,10 +197,15 @@ impl StreamPublisher {
|
|||||||
self.decline(id,uid,if block{"banned"}else{"denied"}).await
|
self.decline(id,uid,if block{"banned"}else{"denied"}).await
|
||||||
}
|
}
|
||||||
pub async fn approve_viewer(self:&Arc<Self>,id:u16,uid:&str)->Result<(),StreamError>{
|
pub async fn approve_viewer(self:&Arc<Self>,id:u16,uid:&str)->Result<(),StreamError>{
|
||||||
|
self.admit_viewer(id,uid,true).await
|
||||||
|
}
|
||||||
|
async fn admit_viewer(self:&Arc<Self>,id:u16,uid:&str,manual:bool)->Result<(),StreamError>{
|
||||||
if !self.active(){return Ok(());}
|
if !self.active(){return Ok(());}
|
||||||
let decision={let mut s=self.state.lock().unwrap();let request=self.take_request(&mut s,id,uid)?;
|
let decision={let mut s=self.state.lock().unwrap();
|
||||||
if s.blocked.contains_key(&request.uid)||(s.options.privacy==Privacy::Contacts&&!s.options.allowed_uids.contains(&request.uid)){Err("not_authorized")}
|
if !s.status.active()||(!manual&&s.needs_approval()){return Ok(());}
|
||||||
else if s.options.viewer_limit>0&&s.viewers.len()>=usize::from(s.options.viewer_limit){Err("viewer_limit")}
|
let request=self.take_request(&mut s,id,uid)?;
|
||||||
|
if !s.allows_uid(&request.uid){Err("not_authorized")}
|
||||||
|
else if s.admission_options().any(|options|options.viewer_limit>0&&s.viewers.len()>=usize::from(options.viewer_limit)){Err("viewer_limit")}
|
||||||
else{let peer=Arc::new(Remote {client_id:id,identity:request,state:Mutex::new(RemoteState{peer:None,remote:VecDeque::new(),local:VecDeque::new(),offered:false,deadline:None,state:"connecting".into()}),queue:AsyncMutex::new(())});s.viewers.insert(id,peer.clone());Ok(peer)}
|
else{let peer=Arc::new(Remote {client_id:id,identity:request,state:Mutex::new(RemoteState{peer:None,remote:VecDeque::new(),local:VecDeque::new(),offered:false,deadline:None,state:"connecting".into()}),queue:AsyncMutex::new(())});s.viewers.insert(id,peer.clone());Ok(peer)}
|
||||||
};
|
};
|
||||||
let peer=match decision{Ok(p)=>p,Err(reason)=>return self.decline(id,uid,reason).await};
|
let peer=match decision{Ok(p)=>p,Err(reason)=>return self.decline(id,uid,reason).await};
|
||||||
@@ -194,7 +217,7 @@ impl StreamPublisher {
|
|||||||
if !self.current(remote){self.drop_remote(remote.client_id,Some(remote));return Ok(());}
|
if !self.current(remote){self.drop_remote(remote.client_id,Some(remote));return Ok(());}
|
||||||
let (source,settings)={let s=self.state.lock().unwrap();(s.source.clone().ok_or_else(StreamError::closed)?,s.options.sender)};
|
let (source,settings)={let s=self.state.lock().unwrap();(s.source.clone().ok_or_else(StreamError::closed)?,s.options.sender)};
|
||||||
let peer=self.factory.publisher(source,settings)?;
|
let peer=self.factory.publisher(source,settings)?;
|
||||||
{let s=self.state.lock().unwrap();if !s.status.active(){peer.close();return Ok(());}remote.state.lock().unwrap().peer=Some(peer.clone());}
|
{let s=self.state.lock().unwrap();if !s.status.active()||s.viewers.get(&remote.client_id).is_none_or(|p|!Arc::ptr_eq(p,remote)){peer.close();return Ok(());}remote.state.lock().unwrap().peer=Some(peer.clone());}
|
||||||
if let Some(mut events)=peer.take_events(){
|
if let Some(mut events)=peer.take_events(){
|
||||||
let weak=Arc::downgrade(self);let remote=Arc::downgrade(remote);
|
let weak=Arc::downgrade(self);let remote=Arc::downgrade(remote);
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
@@ -341,30 +364,44 @@ impl StreamPublisher {
|
|||||||
pub async fn update_options(self:&Arc<Self>,next:PublisherOptions)->Result<(),StreamError>{
|
pub async fn update_options(self:&Arc<Self>,next:PublisherOptions)->Result<(),StreamError>{
|
||||||
let _update=self.updates.lock().await;
|
let _update=self.updates.lock().await;
|
||||||
let result=self.apply_options(next).await;
|
let result=self.apply_options(next).await;
|
||||||
if let Err(e)=&result{self.fail(&e.to_string()).await;}result
|
if let Err(e)=&result{if self.state.lock().unwrap().status.active(){self.fail(&e.to_string()).await;}}result
|
||||||
}
|
}
|
||||||
async fn apply_options(&self,next:PublisherOptions)->Result<(),StreamError>{
|
async fn apply_options(&self,next:PublisherOptions)->Result<(),StreamError>{
|
||||||
next.validate()?;
|
next.validate()?;
|
||||||
if !self.active(){return Err(StreamError::closed());}
|
if !self.active(){return Err(StreamError::closed());}
|
||||||
|
let settings=next.sender;
|
||||||
let (revoked,denied,source,stream)={let mut s=self.state.lock().unwrap();
|
let (revoked,denied,source,stream)={let mut s=self.state.lock().unwrap();
|
||||||
if next.source_type!=s.options.source_type{return Err(StreamError::new("source_changed","Stop before changing the source"));}
|
if next.source_type!=s.options.source_type{return Err(StreamError::new("source_changed","Stop before changing the source"));}
|
||||||
let stream=s.stream_id.clone().ok_or_else(StreamError::closed)?;
|
let stream=s.stream_id.clone().ok_or_else(StreamError::closed)?;
|
||||||
let prior=s.options.privacy;s.options=next.clone();
|
let source=s.source.clone().ok_or_else(StreamError::closed)?;
|
||||||
|
let entering_closed=next.privacy==Privacy::Closed&&s.options.privacy!=Privacy::Closed;
|
||||||
let mut keep=0usize;let mut revoked=Vec::new();
|
let mut keep=0usize;let mut revoked=Vec::new();
|
||||||
s.viewers.retain(|id,p|{let allowed=!(next.privacy==Privacy::Contacts&&!next.allowed_uids.contains(&p.identity.uid)||next.privacy==Privacy::Closed&&prior!=Privacy::Closed)
|
s.viewers.retain(|id,p|{let allowed=!entering_closed&&next.allows_uid(&p.identity.uid)
|
||||||
&&(next.viewer_limit==0||keep<usize::from(next.viewer_limit));if allowed{keep+=1;}else{p.close();revoked.push((*id,p.identity.uid.clone()));}allowed});
|
&&(next.viewer_limit==0||keep<usize::from(next.viewer_limit));if allowed{keep+=1;}else{p.close();revoked.push((*id,p.identity.uid.clone()));}allowed});
|
||||||
let mut denied=Vec::new();s.pending.retain(|id,p|{let allowed=next.privacy!=Privacy::Contacts||next.allowed_uids.contains(&p.uid);if !allowed{denied.push((*id,p.uid.clone()));}allowed});
|
let mut denied=Vec::new();s.pending.retain(|id,p|{let allowed=next.allows_uid(&p.uid);if !allowed{denied.push((*id,p.uid.clone()));}allowed});
|
||||||
(revoked,denied,s.source.clone().ok_or_else(StreamError::closed)?,stream)
|
s.pending_options=Some(next);
|
||||||
|
(revoked,denied,source,stream)
|
||||||
};
|
};
|
||||||
// Every revoked transport is already closed before the first network await.
|
// Every revoked transport is already closed before the first network await.
|
||||||
for (id,uid) in revoked{self.send_if_current_client(id,&uid,Command::StreamRemove{stream_id:stream.clone(),client_id:id}).await?;}
|
for (id,uid) in revoked{self.send_if_current_client(id,&uid,Command::StreamRemove{stream_id:stream.clone(),client_id:id}).await?;}
|
||||||
for (id,uid) in denied{self.send_if_current_client(id,&uid,Command::StreamRespond{stream_id:stream.clone(),client_id:id,decision:false,offer:String::new(),message:"denied".into()}).await?;}
|
for (id,uid) in denied{self.send_if_current_client(id,&uid,Command::StreamRespond{stream_id:stream.clone(),client_id:id,decision:false,offer:String::new(),message:"denied".into()}).await?;}
|
||||||
if !self.active(){return Ok(());}
|
if !self.active(){return Err(StreamError::closed());}
|
||||||
source.configure(next.sender).await?;
|
source.configure(settings).await?;
|
||||||
if !self.active(){return Ok(());}
|
let audio=source.has_audio();
|
||||||
self.send(Command::StreamUpdate(next.metadata(Some(stream),source.has_audio()))).await?;
|
let metadata={
|
||||||
let peers=self.state.lock().unwrap().viewers.values().cloned().collect::<Vec<_>>();
|
let s=self.state.lock().unwrap();
|
||||||
for remote in peers{let _queue=remote.queue.lock().await;if !self.current(&remote){continue;}let peer=remote.state.lock().unwrap().peer.clone();if let Some(peer)=peer{peer.configure_sender(next.sender).await?;}}
|
if !s.status.active()||!self.signal.current(&self.key){return Err(StreamError::closed());}
|
||||||
|
let next=s.pending_options.as_ref().expect("active publisher update has staged options");
|
||||||
|
next.metadata(Some(stream),audio)
|
||||||
|
};
|
||||||
|
self.send(Command::StreamUpdate(metadata)).await?;
|
||||||
|
let peers={
|
||||||
|
let mut s=self.state.lock().unwrap();
|
||||||
|
if !s.status.active()||!self.signal.current(&self.key){return Err(StreamError::closed());}
|
||||||
|
s.options=s.pending_options.take().expect("active publisher update has staged options");
|
||||||
|
s.viewers.values().cloned().collect::<Vec<_>>()
|
||||||
|
};
|
||||||
|
for remote in peers{let _queue=remote.queue.lock().await;if !self.current(&remote){continue;}let peer=remote.state.lock().unwrap().peer.clone();if let Some(peer)=peer{peer.configure_sender(settings).await?;}}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
pub fn set_paused(&self,paused:bool)->Result<(),StreamError>{
|
pub fn set_paused(&self,paused:bool)->Result<(),StreamError>{
|
||||||
@@ -375,6 +412,7 @@ impl StreamPublisher {
|
|||||||
pub async fn stop(&self,reason:&str){
|
pub async fn stop(&self,reason:&str){
|
||||||
{let mut s=self.state.lock().unwrap();if !s.status.active()&&s.status!=PublisherState::Idle{return;}
|
{let mut s=self.state.lock().unwrap();if !s.status.active()&&s.status!=PublisherState::Idle{return;}
|
||||||
s.status=PublisherState::Stopped;s.detail=reason.into();s.deadline=None;
|
s.status=PublisherState::Stopped;s.detail=reason.into();s.deadline=None;
|
||||||
|
s.pending_options=None;
|
||||||
for p in s.viewers.values(){p.close();}s.viewers.clear();s.pending.clear();
|
for p in s.viewers.values(){p.close();}s.viewers.clear();s.pending.clear();
|
||||||
if let Some(source)=s.source.take(){source.stop();}
|
if let Some(source)=s.source.take(){source.stop();}
|
||||||
}
|
}
|
||||||
@@ -382,6 +420,7 @@ impl StreamPublisher {
|
|||||||
}
|
}
|
||||||
pub fn terminate(&self,reason:&str){
|
pub fn terminate(&self,reason:&str){
|
||||||
let mut s=self.state.lock().unwrap();
|
let mut s=self.state.lock().unwrap();
|
||||||
|
s.pending_options=None;
|
||||||
s.disconnected=true;s.awaiting=false;s.deadline=None;
|
s.disconnected=true;s.awaiting=false;s.deadline=None;
|
||||||
if s.status.active()||s.status==PublisherState::Idle {
|
if s.status.active()||s.status==PublisherState::Idle {
|
||||||
s.status=PublisherState::Stopped;s.detail=reason.into();
|
s.status=PublisherState::Stopped;s.detail=reason.into();
|
||||||
|
|||||||
@@ -13,16 +13,39 @@ fn signal(message:Value)->StreamEvent {event("notifystreamsignaling",json!({"id"
|
|||||||
fn accepted(u:&str)->StreamEvent {event("notifyrespondjoinstreamrequest",json!({"id":"s1","clid":"2","decision":"1","offer":offer(u)}))}
|
fn accepted(u:&str)->StreamEvent {event("notifyrespondjoinstreamrequest",json!({"id":"s1","clid":"2","decision":"1","offer":offer(u)}))}
|
||||||
struct Gate {entered:Notify,permit:Semaphore}
|
struct Gate {entered:Notify,permit:Semaphore}
|
||||||
impl Gate {fn new()->Arc<Self>{Arc::new(Self{entered:Notify::new(),permit:Semaphore::new(0)})}async fn wait(&self){self.entered.notify_one();self.permit.acquire().await.unwrap().forget();}fn release(&self){self.permit.add_permits(1);}}
|
impl Gate {fn new()->Arc<Self>{Arc::new(Self{entered:Notify::new(),permit:Semaphore::new(0)})}async fn wait(&self){self.entered.notify_one();self.permit.acquire().await.unwrap().forget();}fn release(&self){self.permit.add_permits(1);}}
|
||||||
struct Wire {commands:Mutex<Vec<Command>>,current:AtomicBool,setup:Mutex<Option<Arc<Gate>>>,remove:Mutex<Option<Arc<Gate>>>}
|
#[derive(Default)]
|
||||||
impl Default for Wire {fn default()->Self{Self{commands:Mutex::new(Vec::new()),current:AtomicBool::new(true),setup:Mutex::new(None),remove:Mutex::new(None)}}}
|
struct WireGates {
|
||||||
|
setup: Mutex<Option<Arc<Gate>>>,
|
||||||
|
remove: Mutex<Option<Arc<Gate>>>,
|
||||||
|
update: Mutex<Option<(Arc<Gate>, Result<(), StreamError>)>>,
|
||||||
|
}
|
||||||
|
struct Wire {
|
||||||
|
commands: Mutex<Vec<Command>>,
|
||||||
|
current: AtomicBool,
|
||||||
|
gates: WireGates,
|
||||||
|
}
|
||||||
|
impl Default for Wire {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self { commands: Mutex::new(Vec::new()), current: AtomicBool::new(true), gates: WireGates::default() }
|
||||||
|
}
|
||||||
|
}
|
||||||
impl Signal for Wire {
|
impl Signal for Wire {
|
||||||
fn request(&self,key:SessionKey,command:Command)->PeerFuture<'_,Value>{Box::pin(async move{
|
fn request(&self,key:SessionKey,command:Command)->PeerFuture<'_,Value>{Box::pin(async move{
|
||||||
assert_eq!(key,super::tests::key());
|
assert_eq!(key,super::tests::key());
|
||||||
if matches!(&command, Command::StreamSignal { .. }) {
|
if matches!(&command, Command::StreamSignal { .. }) {
|
||||||
teamspeach_core::protocol::validate_command(command.clone()).map_err(|e| StreamError::new("validation",e.message))?;
|
teamspeach_core::protocol::validate_command(command.clone()).map_err(|e| StreamError::new("validation",e.message))?;
|
||||||
}
|
}
|
||||||
let gate=match &command{Command::StreamSetup(_)=>self.setup.lock().unwrap().clone(),Command::StreamRemove{..}=>self.remove.lock().unwrap().clone(),_=>None};
|
let (gate, result) = match &command {
|
||||||
self.commands.lock().unwrap().push(command);if let Some(gate)=gate{gate.wait().await;}Ok(json!({}))
|
Command::StreamSetup(_) => (self.gates.setup.lock().unwrap().clone(), Ok(())),
|
||||||
|
Command::StreamRemove { .. } => (self.gates.remove.lock().unwrap().clone(), Ok(())),
|
||||||
|
Command::StreamUpdate(_) => self.gates.update.lock().unwrap().clone()
|
||||||
|
.map_or((None, Ok(())), |(gate, result)| (Some(gate), result)),
|
||||||
|
_ => (None, Ok(())),
|
||||||
|
};
|
||||||
|
self.commands.lock().unwrap().push(command);
|
||||||
|
if let Some(gate) = gate { gate.wait().await; }
|
||||||
|
result?;
|
||||||
|
Ok(json!({}))
|
||||||
})}
|
})}
|
||||||
fn current(&self,k:&SessionKey)->bool {k==&key()&&self.current.load(Ordering::SeqCst)}
|
fn current(&self,k:&SessionKey)->bool {k==&key()&&self.current.load(Ordering::SeqCst)}
|
||||||
}
|
}
|
||||||
@@ -30,6 +53,12 @@ impl Wire {
|
|||||||
fn sends(&self)->Vec<Value>{self.commands.lock().unwrap().iter().filter_map(|c|if let Command::StreamSignal{json,..}=c{Some(serde_json::from_str(json).unwrap())}else{None}).collect()}
|
fn sends(&self)->Vec<Value>{self.commands.lock().unwrap().iter().filter_map(|c|if let Command::StreamSignal{json,..}=c{Some(serde_json::from_str(json).unwrap())}else{None}).collect()}
|
||||||
fn leaves(&self)->usize{self.commands.lock().unwrap().iter().filter(|c|matches!(c,Command::StreamLeave{..})).count()}
|
fn leaves(&self)->usize{self.commands.lock().unwrap().iter().filter(|c|matches!(c,Command::StreamLeave{..})).count()}
|
||||||
fn stops(&self)->Vec<String>{self.commands.lock().unwrap().iter().filter_map(|c|if let Command::StreamStop{stream_id}=c{Some(stream_id.clone())}else{None}).collect()}
|
fn stops(&self)->Vec<String>{self.commands.lock().unwrap().iter().filter_map(|c|if let Command::StreamStop{stream_id}=c{Some(stream_id.clone())}else{None}).collect()}
|
||||||
|
fn declined(&self, id: u16, reason: &str) -> bool {
|
||||||
|
self.commands.lock().unwrap().iter().any(|command| {
|
||||||
|
matches!(command, Command::StreamRespond { client_id, decision: false, message, .. }
|
||||||
|
if *client_id == id && message == reason)
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
struct PeerData {state:SignalingState,remote:Option<String>,candidates:Vec<Candidate>,descriptions:Vec<DescriptionKind>,settings:Vec<SenderSettings>}
|
struct PeerData {state:SignalingState,remote:Option<String>,candidates:Vec<Candidate>,descriptions:Vec<DescriptionKind>,settings:Vec<SenderSettings>}
|
||||||
struct FakePeer {data:Mutex<PeerData>,closed:AtomicBool,answer_count:AtomicUsize,gate:Mutex<Option<(DescriptionKind,Arc<Gate>)>>,offer_gate:Mutex<Option<Arc<Gate>>>,reject_candidate:AtomicBool,volume:Mutex<f32>}
|
struct FakePeer {data:Mutex<PeerData>,closed:AtomicBool,answer_count:AtomicUsize,gate:Mutex<Option<(DescriptionKind,Arc<Gate>)>>,offer_gate:Mutex<Option<Arc<Gate>>>,reject_candidate:AtomicBool,volume:Mutex<f32>}
|
||||||
@@ -298,7 +327,7 @@ async fn publisher_reserves_capacity_before_offer_and_stop_cancels_offer(){
|
|||||||
}
|
}
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn publisher_late_setup_id_is_unregistered_after_local_stop(){
|
async fn publisher_late_setup_id_is_unregistered_after_local_stop(){
|
||||||
let h=Publishing::new();let gate=Gate::new();*h.w.setup.lock().unwrap()=Some(gate.clone());
|
let h=Publishing::new();let gate=Gate::new();*h.w.gates.setup.lock().unwrap()=Some(gate.clone());
|
||||||
let task={let s=h.s.clone();let source=h.source.clone();tokio::spawn(async move{s.start(source,PublisherOptions::default()).await})};gate.entered.notified().await;
|
let task={let s=h.s.clone();let source=h.source.clone();tokio::spawn(async move{s.start(source,PublisherOptions::default()).await})};gate.entered.notified().await;
|
||||||
h.s.stop("cancel").await;assert_eq!(h.source.stops.load(Ordering::SeqCst),1);assert!(h.s.snapshot().awaiting_stream_id);
|
h.s.stop("cancel").await;assert_eq!(h.source.stops.load(Ordering::SeqCst),1);assert!(h.s.snapshot().awaiting_stream_id);
|
||||||
let late={let s=h.s.clone();tokio::spawn(async move{s.handle(event("notifystreamstarted",json!({"id":"late","clid":"1"}))).await})};gate.release();task.await.unwrap().unwrap();late.await.unwrap();assert_eq!(h.w.stops(),["late"]);assert_eq!(h.s.snapshot().state,PublisherState::Stopped);
|
let late={let s=h.s.clone();tokio::spawn(async move{s.handle(event("notifystreamstarted",json!({"id":"late","clid":"1"}))).await})};gate.release();task.await.unwrap().unwrap();late.await.unwrap();assert_eq!(h.w.stops(),["late"]);assert_eq!(h.s.snapshot().state,PublisherState::Stopped);
|
||||||
@@ -318,7 +347,7 @@ async fn manual_remove_cannot_block_a_replacement_viewer(){
|
|||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn publisher_privacy_closes_every_peer_before_eviction_ack(){
|
async fn publisher_privacy_closes_every_peer_before_eviction_ack(){
|
||||||
let h=Publishing::new();h.start(PublisherOptions::default()).await;h.request(2).await;h.request(3).await;
|
let h=Publishing::new();h.start(PublisherOptions::default()).await;h.request(2).await;h.request(3).await;
|
||||||
let gate=Gate::new();*h.w.remove.lock().unwrap()=Some(gate.clone());
|
let gate=Gate::new();*h.w.gates.remove.lock().unwrap()=Some(gate.clone());
|
||||||
let task={let s=h.s.clone();tokio::spawn(async move{s.update_options(PublisherOptions{privacy:Privacy::Contacts,..Default::default()}).await})};gate.entered.notified().await;
|
let task={let s=h.s.clone();tokio::spawn(async move{s.update_options(PublisherOptions{privacy:Privacy::Contacts,..Default::default()}).await})};gate.entered.notified().await;
|
||||||
assert!(h.f.peers.lock().unwrap().iter().all(|p|p.closed.load(Ordering::SeqCst)));assert!(h.s.snapshot().viewers.is_empty());gate.release();gate.entered.notified().await;gate.release();task.await.unwrap().unwrap();
|
assert!(h.f.peers.lock().unwrap().iter().all(|p|p.closed.load(Ordering::SeqCst)));assert!(h.s.snapshot().viewers.is_empty());gate.release();gate.entered.notified().await;gate.release();task.await.unwrap().unwrap();
|
||||||
}
|
}
|
||||||
@@ -336,7 +365,7 @@ async fn publisher_privacy_skips_removal_for_reused_client_id() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let gate = Gate::new();
|
let gate = Gate::new();
|
||||||
*h.w.remove.lock().unwrap() = Some(gate.clone());
|
*h.w.gates.remove.lock().unwrap() = Some(gate.clone());
|
||||||
tokio::time::timeout(std::time::Duration::from_secs(2), async {
|
tokio::time::timeout(std::time::Duration::from_secs(2), async {
|
||||||
let update = h.s.update_options(PublisherOptions {
|
let update = h.s.update_options(PublisherOptions {
|
||||||
privacy: Privacy::Contacts,
|
privacy: Privacy::Contacts,
|
||||||
@@ -352,7 +381,7 @@ async fn publisher_privacy_skips_removal_for_reused_client_id() {
|
|||||||
assert!(h.s.snapshot().viewers.is_empty());
|
assert!(h.s.snapshot().viewers.is_empty());
|
||||||
h.clients.0.lock().unwrap().get_mut(&3).unwrap().uid = "recycled".into();
|
h.clients.0.lock().unwrap().get_mut(&3).unwrap().uid = "recycled".into();
|
||||||
// An erroneous second removal should be recorded, not block on the gate.
|
// An erroneous second removal should be recorded, not block on the gate.
|
||||||
*h.w.remove.lock().unwrap() = None;
|
*h.w.gates.remove.lock().unwrap() = None;
|
||||||
gate.release();
|
gate.release();
|
||||||
update.await.unwrap();
|
update.await.unwrap();
|
||||||
})
|
})
|
||||||
@@ -372,6 +401,160 @@ async fn publisher_privacy_skips_removal_for_reused_client_id() {
|
|||||||
assert_eq!(removals.next(), Some(("s1", 2)));
|
assert_eq!(removals.next(), Some(("s1", 2)));
|
||||||
assert_eq!(removals.next(), None);
|
assert_eq!(removals.next(), None);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn assert_admission_waits_on_wire<F: Future>(mut request: Pin<&mut F>) {
|
||||||
|
std::future::poll_fn(|cx| {
|
||||||
|
assert!(request.as_mut().poll(cx).is_pending());
|
||||||
|
std::task::Poll::Ready(())
|
||||||
|
}).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn publisher_update_enforces_tighter_admission_before_ack() {
|
||||||
|
let h = Publishing::new();
|
||||||
|
h.clients.0.lock().unwrap().insert(4, ClientIdentity { uid: "four".into(), nickname: "Four".into() });
|
||||||
|
let old = PublisherOptions::default();
|
||||||
|
h.start(old.clone()).await;
|
||||||
|
h.request(2).await;
|
||||||
|
h.request(3).await;
|
||||||
|
|
||||||
|
let remove = Gate::new();
|
||||||
|
let ack = Gate::new();
|
||||||
|
*h.w.gates.remove.lock().unwrap() = Some(remove.clone());
|
||||||
|
*h.w.gates.update.lock().unwrap() = Some((ack.clone(), Ok(())));
|
||||||
|
let next = PublisherOptions {
|
||||||
|
name: "Contacts only".into(),
|
||||||
|
sender: SenderSettings { video_bitrate_kbps: 3000, ..old.sender },
|
||||||
|
privacy: Privacy::Contacts,
|
||||||
|
viewer_limit: 1,
|
||||||
|
allowed_uids: ["two".into(), "four".into()].into(),
|
||||||
|
..old.clone()
|
||||||
|
};
|
||||||
|
let task = {
|
||||||
|
let s = h.s.clone();
|
||||||
|
let next = next.clone();
|
||||||
|
tokio::spawn(async move { s.update_options(next).await })
|
||||||
|
};
|
||||||
|
|
||||||
|
remove.entered.notified().await;
|
||||||
|
assert!(h.f.peers.lock().unwrap()[1].closed.load(Ordering::SeqCst));
|
||||||
|
let full = h.request(4);
|
||||||
|
tokio::pin!(full);
|
||||||
|
assert_admission_waits_on_wire(full.as_mut()).await;
|
||||||
|
assert_eq!(h.s.snapshot().viewers.len(), 1);
|
||||||
|
remove.release();
|
||||||
|
full.await;
|
||||||
|
assert!(h.w.declined(4, "viewer_limit"));
|
||||||
|
|
||||||
|
ack.entered.notified().await;
|
||||||
|
let excluded = h.request(3);
|
||||||
|
tokio::pin!(excluded);
|
||||||
|
assert_admission_waits_on_wire(excluded.as_mut()).await;
|
||||||
|
let before = h.s.snapshot();
|
||||||
|
assert_eq!(before.viewers.len(), 1);
|
||||||
|
assert_eq!(before.options.name, old.name);
|
||||||
|
assert_eq!(before.options.sender, old.sender);
|
||||||
|
assert_eq!(before.options.privacy, old.privacy);
|
||||||
|
assert_eq!(before.options.viewer_limit, old.viewer_limit);
|
||||||
|
assert_eq!(before.options.allowed_uids, old.allowed_uids);
|
||||||
|
assert!(matches!(h.w.commands.lock().unwrap().last(), Some(Command::StreamUpdate(args))
|
||||||
|
if args.name == next.name && args.bitrate == next.sender.video_bitrate_kbps && args.viewer_limit == 1));
|
||||||
|
|
||||||
|
ack.release();
|
||||||
|
task.await.unwrap().unwrap();
|
||||||
|
excluded.await;
|
||||||
|
assert!(h.w.declined(3, "not_authorized"));
|
||||||
|
let after = h.s.snapshot();
|
||||||
|
assert_eq!(after.options.name, next.name);
|
||||||
|
assert_eq!(after.options.sender, next.sender);
|
||||||
|
assert_eq!(after.options.privacy, next.privacy);
|
||||||
|
assert_eq!(after.options.viewer_limit, next.viewer_limit);
|
||||||
|
assert_eq!(after.options.allowed_uids, next.allowed_uids);
|
||||||
|
assert_eq!(h.f.peers.lock().unwrap().len(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn publisher_update_does_not_relax_admission_before_ack() {
|
||||||
|
let h = Publishing::new();
|
||||||
|
h.clients.0.lock().unwrap().insert(4, ClientIdentity { uid: "four".into(), nickname: "Four".into() });
|
||||||
|
h.start(PublisherOptions {
|
||||||
|
privacy: Privacy::Contacts,
|
||||||
|
viewer_limit: 1,
|
||||||
|
allowed_uids: ["two".into(), "three".into()].into(),
|
||||||
|
..Default::default()
|
||||||
|
}).await;
|
||||||
|
h.request(2).await;
|
||||||
|
|
||||||
|
let ack = Gate::new();
|
||||||
|
*h.w.gates.update.lock().unwrap() = Some((ack.clone(), Ok(())));
|
||||||
|
let task = {
|
||||||
|
let s = h.s.clone();
|
||||||
|
tokio::spawn(async move { s.update_options(PublisherOptions::default()).await })
|
||||||
|
};
|
||||||
|
ack.entered.notified().await;
|
||||||
|
|
||||||
|
let full = h.request(3);
|
||||||
|
let excluded = h.request(4);
|
||||||
|
tokio::pin!(full, excluded);
|
||||||
|
assert_admission_waits_on_wire(full.as_mut()).await;
|
||||||
|
assert_admission_waits_on_wire(excluded.as_mut()).await;
|
||||||
|
assert_eq!(h.s.snapshot().viewers.len(), 1);
|
||||||
|
assert_eq!(h.f.peers.lock().unwrap().len(), 1);
|
||||||
|
|
||||||
|
ack.release();
|
||||||
|
task.await.unwrap().unwrap();
|
||||||
|
full.await;
|
||||||
|
excluded.await;
|
||||||
|
assert!(h.w.declined(3, "viewer_limit"));
|
||||||
|
assert!(h.w.declined(4, "not_authorized"));
|
||||||
|
h.request(3).await;
|
||||||
|
h.request(4).await;
|
||||||
|
assert_eq!(h.s.snapshot().viewers.len(), 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn publisher_update_ack_after_disconnect_cannot_replace_confirmed_state() {
|
||||||
|
let h=Publishing::new();let old=PublisherOptions::default();h.start(old.clone()).await;
|
||||||
|
let ack=Gate::new();*h.w.gates.update.lock().unwrap()=Some((ack.clone(),Ok(())));
|
||||||
|
let task={let s=h.s.clone();let next=PublisherOptions{name:"Pending rename".into(),..old.clone()};
|
||||||
|
tokio::spawn(async move{s.update_options(next).await})};
|
||||||
|
ack.entered.notified().await;
|
||||||
|
h.s.terminate("connection_changed");h.w.current.store(false,Ordering::SeqCst);
|
||||||
|
ack.release();assert_eq!(task.await.unwrap().unwrap_err().code,"stream_closed");
|
||||||
|
let state=h.s.snapshot();assert_eq!(state.options.name,old.name);
|
||||||
|
assert_eq!(state.state,PublisherState::Stopped);assert_eq!(state.detail,"connection_changed");
|
||||||
|
assert!(h.w.stops().is_empty());
|
||||||
|
}
|
||||||
|
#[tokio::test]
|
||||||
|
async fn publisher_update_refusal_keeps_confirmed_options() {
|
||||||
|
let h = Publishing::new();
|
||||||
|
let old = PublisherOptions::default();
|
||||||
|
h.start(old.clone()).await;
|
||||||
|
let ack = Gate::new();
|
||||||
|
*h.w.gates.update.lock().unwrap() = Some((ack.clone(), Err(StreamError::new("refused", "Update rejected"))));
|
||||||
|
let task = {
|
||||||
|
let s = h.s.clone();
|
||||||
|
let next = PublisherOptions { name: "Unconfirmed".into(), privacy: Privacy::Closed,
|
||||||
|
viewer_limit: 1, sender: SenderSettings { video_bitrate_kbps: 3000, ..old.sender }, ..old.clone() };
|
||||||
|
tokio::spawn(async move { s.update_options(next).await })
|
||||||
|
};
|
||||||
|
ack.entered.notified().await;
|
||||||
|
assert_eq!(h.s.snapshot().options.name, old.name);
|
||||||
|
tokio::time::timeout(std::time::Duration::from_secs(2), h.request(2)).await
|
||||||
|
.expect("Closed admission must queue for approval without sending an offer");
|
||||||
|
assert_eq!(h.s.snapshot().pending[0].client_id, 2);
|
||||||
|
assert!(h.f.peers.lock().unwrap().is_empty());
|
||||||
|
ack.release();
|
||||||
|
assert_eq!(task.await.unwrap().unwrap_err().code, "refused");
|
||||||
|
|
||||||
|
let snapshot = h.s.snapshot();
|
||||||
|
assert_eq!(snapshot.state, PublisherState::Failed);
|
||||||
|
assert_eq!(snapshot.options.name, old.name);
|
||||||
|
assert_eq!(snapshot.options.sender, old.sender);
|
||||||
|
assert_eq!(snapshot.options.privacy, old.privacy);
|
||||||
|
assert_eq!(snapshot.options.viewer_limit, old.viewer_limit);
|
||||||
|
assert_eq!(h.w.stops(), ["s1"]);
|
||||||
|
}
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn publisher_early_ice_reconnect_and_client_reuse_are_isolated(){
|
async fn publisher_early_ice_reconnect_and_client_reuse_are_isolated(){
|
||||||
let h=Publishing::new();h.start(PublisherOptions::default()).await;h.request(2).await;
|
let h=Publishing::new();h.start(PublisherOptions::default()).await;h.request(2).await;
|
||||||
|
|||||||
Reference in new issue
Block a user