@@ -462,6 +462,22 @@ impl Drop for Ingest {
462462 }
463463}
464464
465+ fn send_chunk ( tx : & SyncSender < Chunk > , mut chunk : Chunk , cancel : & AtomicBool ) -> bool {
466+ loop {
467+ if cancel. load ( Ordering :: Relaxed ) {
468+ return false ;
469+ }
470+ match tx. try_send ( chunk) {
471+ Ok ( ( ) ) => return true ,
472+ Err ( std:: sync:: mpsc:: TrySendError :: Full ( returned) ) => {
473+ chunk = returned;
474+ thread:: sleep ( Duration :: from_millis ( 10 ) ) ;
475+ }
476+ Err ( std:: sync:: mpsc:: TrySendError :: Disconnected ( _) ) => return false ,
477+ }
478+ }
479+ }
480+
465481fn spawn_ingest (
466482 mut out : ChildStdout ,
467483 err : ChildStderr ,
@@ -490,15 +506,18 @@ fn spawn_ingest(
490506 Ok ( n) => n,
491507 Err ( e) => {
492508 if !cancel. load ( Ordering :: Relaxed ) {
493- let _ = tx
494- . send ( Chunk :: Failed ( format ! ( "could not read decoded audio: {e}" ) ) ) ;
509+ let _ = send_chunk (
510+ & tx,
511+ Chunk :: Failed ( format ! ( "could not read decoded audio: {e}" ) ) ,
512+ & cancel,
513+ ) ;
495514 }
496515 return total;
497516 }
498517 } ;
499518 let samples = bytes_to_f32 ( & bytes[ ..n - n % 4 ] ) ;
500519 total += samples. len ( ) ;
501- if tx . send ( Chunk :: Samples ( samples) ) . is_err ( ) {
520+ if ! send_chunk ( & tx , Chunk :: Samples ( samples) , & cancel ) {
502521 return total;
503522 }
504523 if n < bytes. len ( ) {
@@ -983,6 +1002,26 @@ mod tests {
9831002 drop ( handle) ;
9841003 }
9851004
1005+ #[ test]
1006+ fn bounded_ingest_send_observes_cancellation ( ) {
1007+ let ( tx, rx) = mpsc:: sync_channel ( 1 ) ;
1008+ assert ! ( tx. try_send( Chunk :: Samples ( vec![ 0.0 ] ) ) . is_ok( ) ) ;
1009+ let cancel = Arc :: new ( AtomicBool :: new ( false ) ) ;
1010+ let worker_cancel = cancel. clone ( ) ;
1011+ let ( done_tx, done_rx) = mpsc:: channel ( ) ;
1012+
1013+ let worker = thread:: spawn ( move || {
1014+ let sent = send_chunk ( & tx, Chunk :: Samples ( vec ! [ 1.0 ] ) , & worker_cancel) ;
1015+ done_tx. send ( sent) . unwrap ( ) ;
1016+ } ) ;
1017+
1018+ thread:: sleep ( Duration :: from_millis ( 30 ) ) ;
1019+ cancel. store ( true , Ordering :: Relaxed ) ;
1020+ assert ! ( !done_rx. recv_timeout( Duration :: from_secs( 1 ) ) . unwrap( ) ) ;
1021+ worker. join ( ) . unwrap ( ) ;
1022+ assert ! ( matches!( rx. try_recv( ) , Ok ( Chunk :: Samples ( _) ) ) ) ;
1023+ }
1024+
9861025 #[ cfg( unix) ]
9871026 fn fake_decoder ( script : & str ) -> Command {
9881027 let mut command = Command :: new ( "sh" ) ;
0 commit comments