1use super::{discovery_result, private, with_deadline_budget, with_timeout_budget, AsyncRuntime};
3use crate::{
4 finder::{checked_host_lookup, checked_name_lookup, CacheProbe, SourceCursor},
5 Finder, Result, Source, SourceCache,
6};
7use std::{marker::PhantomData, sync::Arc, time::Duration};
8
9mod sealed {
10 pub trait SourceDiscovery: std::fmt::Debug {
11 fn finder(&self) -> &crate::Finder;
12 }
13 impl SourceDiscovery for crate::Finder {
14 fn finder(&self) -> &crate::Finder {
15 self
16 }
17 }
18 impl SourceDiscovery for crate::SourceCache {
19 fn finder(&self) -> &crate::Finder {
20 self.finder()
21 }
22 }
23}
24
25pub trait SourceDiscovery: sealed::SourceDiscovery + Send + Sync + 'static {}
30impl SourceDiscovery for Finder {}
31impl SourceDiscovery for SourceCache {}
32
33pub struct AsyncFinder<R: AsyncRuntime, D: SourceDiscovery = Finder> {
64 inner: Arc<D>,
65 _runtime: PhantomData<R>,
66}
67
68impl<R: AsyncRuntime, D: SourceDiscovery> std::fmt::Debug for AsyncFinder<R, D> {
69 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70 f.debug_struct("AsyncFinder")
71 .field("owner", &*self.inner)
72 .field("runtime", &std::any::type_name::<R>())
73 .finish_non_exhaustive()
74 }
75}
76
77impl<R: AsyncRuntime, D: SourceDiscovery> Clone for AsyncFinder<R, D> {
78 fn clone(&self) -> Self {
79 Self {
80 inner: Arc::clone(&self.inner),
81 _runtime: PhantomData,
82 }
83 }
84}
85
86impl<R: AsyncRuntime, D: SourceDiscovery> AsyncFinder<R, D> {
87 #[must_use]
89 pub fn new(discovery: D) -> Self {
90 Self {
91 inner: Arc::new(discovery),
92 _runtime: PhantomData,
93 }
94 }
95
96 #[must_use]
98 pub fn finder(&self) -> &Finder {
99 sealed::SourceDiscovery::finder(&*self.inner)
100 }
101
102 #[must_use]
107 pub fn watch(&self) -> AsyncSourceWatch<R, D> {
108 AsyncSourceWatch {
109 inner: Arc::clone(&self.inner),
110 cursor: SourceCursor::new(self.finder().generation()),
111 _runtime: PhantomData,
112 }
113 }
114
115 #[doc(alias = "NDIlib_find_get_current_sources")]
126 #[doc(alias = "NDIlib_find_wait_for_sources")]
127 pub async fn find_source(
128 &self,
129 timeout: Duration,
130 mut select: impl FnMut(&Source) -> bool + Send + 'static,
131 ) -> Result<Option<Source>> {
132 let inner = Arc::clone(&self.inner);
133 with_timeout_budget::<R, _, _>(timeout, move |deadline, stop| {
134 discovery_result(sealed::SourceDiscovery::finder(&*inner).find_source_until(
135 deadline,
136 stop,
137 &mut select,
138 ))
139 })
140 .await
141 }
142
143 #[doc(alias = "NDIlib_find_get_current_sources")]
150 #[doc(alias = "NDIlib_find_wait_for_sources")]
151 pub async fn find_source_by_name(
152 &self,
153 name: &str,
154 timeout: Duration,
155 ) -> Result<Option<Source>> {
156 let (name, deadline) = checked_name_lookup(name, timeout)?;
157 let name = name.into_owned();
158 let inner = Arc::clone(&self.inner);
159 with_deadline_budget::<R, _, _>(deadline, move |deadline, stop| {
160 discovery_result(
161 sealed::SourceDiscovery::finder(&*inner).find_source_by_name_until(
162 name.as_str(),
163 deadline,
164 stop,
165 ),
166 )
167 })
168 .await
169 }
170
171 #[doc(alias = "NDIlib_find_get_current_sources")]
178 #[doc(alias = "NDIlib_find_wait_for_sources")]
179 pub async fn find_sources(&self, timeout: Duration) -> Result<Vec<Source>> {
180 let inner = Arc::clone(&self.inner);
181 with_timeout_budget::<R, _, _>(timeout, move |deadline, stop| {
182 discovery_result(
183 sealed::SourceDiscovery::finder(&*inner).find_sources_until(deadline, stop),
184 )
185 })
186 .await
187 }
188}
189
190impl<R: AsyncRuntime> AsyncFinder<R, SourceCache> {
191 #[must_use]
193 pub fn cache(&self) -> &SourceCache {
194 &self.inner
195 }
196
197 #[doc(alias = "NDIlib_find_get_current_sources")]
211 #[doc(alias = "NDIlib_find_wait_for_sources")]
212 pub async fn find_sources_by_host(&self, host: &str, timeout: Duration) -> Result<Vec<Source>> {
213 let (query, deadline) = checked_host_lookup(host, timeout)?;
214 let miss = match self.inner.probe_host(query)? {
215 CacheProbe::Hit(sources) => return Ok(sources),
216 CacheProbe::Miss(miss) => miss,
217 };
218 let query = query.into_owned();
219 let inner = Arc::clone(&self.inner);
220 with_deadline_budget::<R, _, _>(deadline, move |deadline, stop| {
221 discovery_result(inner.find_sources_by_host_until(
222 query.as_query(),
223 deadline,
224 Some(miss),
225 stop,
226 ))
227 })
228 .await
229 }
230}
231
232pub struct AsyncSourceWatch<R: AsyncRuntime, D: SourceDiscovery = Finder> {
241 inner: Arc<D>,
242 cursor: SourceCursor,
243 _runtime: PhantomData<R>,
244}
245
246impl<R: AsyncRuntime, D: SourceDiscovery> std::fmt::Debug for AsyncSourceWatch<R, D> {
247 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
248 f.debug_struct("AsyncSourceWatch")
249 .field("owner", &*self.inner)
250 .field("runtime", &std::any::type_name::<R>())
251 .finish_non_exhaustive()
252 }
253}
254
255impl<R: AsyncRuntime, D: SourceDiscovery> AsyncSourceWatch<R, D> {
256 #[doc(alias = "NDIlib_find_get_current_sources")]
267 pub async fn current_sources(&mut self) -> Result<Vec<Source>> {
268 let inner = Arc::clone(&self.inner);
269 let (sources, observation) = R::spawn_stoppable(private::Token, move |stop| {
270 SourceCursor::snapshot(
271 sealed::SourceDiscovery::finder(&*inner),
272 |finder| discovery_result(finder.current_sources_stoppable(stop)),
273 |_| true,
274 )
275 })
276 .await??;
277 self.cursor.commit(observation);
278 Ok(sources)
279 }
280
281 #[doc(alias = "NDIlib_find_wait_for_sources")]
293 pub async fn wait_for_change(&mut self, timeout: Duration) -> Result<bool> {
294 let observed = self.cursor.observed();
295 let inner = Arc::clone(&self.inner);
296 let (changed, observation) =
297 with_timeout_budget::<R, _, _>(timeout, move |deadline, stop| {
298 Ok(SourceCursor::wait(
299 sealed::SourceDiscovery::finder(&*inner),
300 observed,
301 deadline,
302 stop,
303 ))
304 })
305 .await?;
306 self.cursor.commit(observation);
307 Ok(changed)
308 }
309}
310
311#[cfg(test)]
312mod tests {
313 use super::*;
314 use crate::{FinderOptions, Ndi};
315 use std::{
316 future::Future,
317 task::{Context, Poll, Waker},
318 thread,
319 time::Instant,
320 };
321
322 fn finder(ndi: &Ndi) -> Finder {
323 Finder::new(
324 ndi,
325 &FinderOptions::new()
326 .groups([crate::test_support::unique_name("async discovery")])
327 .show_local_sources(false),
328 )
329 .unwrap()
330 }
331
332 fn futures_are_send<R: AsyncRuntime>(
333 finder: &AsyncFinder<R>,
334 cache: &AsyncFinder<R, SourceCache>,
335 watch: &mut AsyncSourceWatch<R>,
336 ) {
337 fn send<T: Send>(_: T) {}
338 send(finder.find_source(Duration::ZERO, |_| true));
339 send(finder.find_source_by_name("camera", Duration::ZERO));
340 let name = String::from("camera");
341 send(finder.find_source_by_name(&name, Duration::ZERO));
342 send(cache.find_source_by_name(&name, Duration::ZERO));
343 send(finder.find_sources(Duration::ZERO));
344 send(cache.find_sources_by_host("camera", Duration::ZERO));
345 send(watch.current_sources());
346 send(watch.wait_for_change(Duration::ZERO));
347 }
348
349 #[test]
350 fn discovery_futures_are_send() {
351 #[cfg(feature = "tokio")]
352 let _ = futures_are_send::<super::super::Tokio>;
353 #[cfg(feature = "smol")]
354 let _ = futures_are_send::<super::super::Smol>;
355 }
356
357 fn owners_keep_their_discovery_scope<R: AsyncRuntime>() {
358 let Some(ndi) = crate::test_support::ndi() else {
359 return;
360 };
361 fn assert_owner<R: AsyncRuntime, D: SourceDiscovery>(
362 adapter: AsyncFinder<R, D>,
363 kind: &str,
364 ) {
365 for output in [format!("{adapter:?}"), format!("{:?}", adapter.watch())] {
366 assert!(output.contains(&format!("owner: {kind} {{")), "{output}");
367 assert!(output.contains("\"g\""), "{output}");
368 assert!(output.ends_with(", .. }"), "{output}");
369 }
370 }
371 let configured = || Finder::new(&ndi, &FinderOptions::new().groups(["g"])).unwrap();
372 assert_owner(AsyncFinder::<R>::new(configured()), "Finder");
373 assert_owner(
374 AsyncFinder::<R, SourceCache>::new(SourceCache::new(configured())),
375 "SourceCache",
376 );
377 }
378
379 #[cfg(feature = "tokio")]
380 #[test]
381 fn tokio_debug_names_the_shared_owner_and_its_scope() {
382 owners_keep_their_discovery_scope::<super::super::Tokio>();
383 }
384
385 #[cfg(feature = "smol")]
386 #[test]
387 fn smol_debug_names_the_shared_owner_and_its_scope() {
388 owners_keep_their_discovery_scope::<super::super::Smol>();
389 }
390
391 fn assert_ready_validation_error<T: std::fmt::Debug>(
392 actual: Poll<Result<T>>,
393 expected: &crate::Error,
394 ) {
395 use crate::Error;
396 match (actual, expected) {
397 (Poll::Ready(Err(Error::InvalidInput(actual))), Error::InvalidInput(expected)) => {
398 assert_eq!(&actual, expected)
399 }
400 (Poll::Ready(Err(Error::InvalidCString(actual))), Error::InvalidCString(expected)) => {
401 assert_eq!(&actual, expected)
402 }
403 (actual, expected) => panic!("different errors: {actual:?}, {expected:?}"),
404 }
405 }
406
407 fn assert_invalid_discovery_inputs<R: AsyncRuntime>() {
408 use crate::{Error, InputDefect};
409 let Some(ndi) = crate::test_support::ndi() else {
410 return;
411 };
412 let adapter = AsyncFinder::<R>::new(finder(&ndi));
413 let cache = AsyncFinder::<R, SourceCache>::new(SourceCache::new(finder(&ndi)));
414 let mut context = Context::from_waker(Waker::noop());
415 let excessive = crate::MAX_TIMEOUT + Duration::from_nanos(1);
416 assert!(matches!(
417 Box::pin(adapter.find_source(excessive, |_| true))
418 .as_mut()
419 .poll(&mut context),
420 Poll::Ready(Err(Error::InvalidInput(InputDefect::TimeoutTooLong { .. })))
421 ));
422 assert!(matches!(
423 Box::pin(adapter.find_sources(excessive))
424 .as_mut()
425 .poll(&mut context),
426 Poll::Ready(Err(Error::InvalidInput(InputDefect::TimeoutTooLong { .. })))
427 ));
428 for name in ["", "\0leading", "bad\0name", "trailing\0", "é映\0tail\0"] {
429 for timeout in [Duration::ZERO, excessive] {
430 let expected = adapter
431 .finder()
432 .find_source_by_name(name, timeout)
433 .unwrap_err();
434 assert_ready_validation_error(
435 Box::pin(adapter.find_source_by_name(name, timeout))
436 .as_mut()
437 .poll(&mut context),
438 &expected,
439 );
440 assert_ready_validation_error(
441 Box::pin(cache.find_source_by_name(name, timeout))
442 .as_mut()
443 .poll(&mut context),
444 &expected,
445 );
446 }
447 }
448 assert!(matches!(
449 Box::pin(adapter.find_source_by_name("camera", excessive))
450 .as_mut()
451 .poll(&mut context),
452 Poll::Ready(Err(Error::InvalidInput(InputDefect::TimeoutTooLong { .. })))
453 ));
454 for host in ["", "http://camera", "bad\0host"] {
455 for timeout in [Duration::ZERO, excessive] {
456 let expected = cache
457 .cache()
458 .find_sources_by_host(host, timeout)
459 .unwrap_err();
460 assert_ready_validation_error(
461 Box::pin(cache.find_sources_by_host(host, timeout))
462 .as_mut()
463 .poll(&mut context),
464 &expected,
465 );
466 }
467 }
468 assert!(matches!(
469 Box::pin(cache.find_sources_by_host("camera", excessive))
470 .as_mut()
471 .poll(&mut context),
472 Poll::Ready(Err(Error::InvalidInput(InputDefect::TimeoutTooLong { .. })))
473 ));
474 let mut watch = adapter.watch();
475 assert!(matches!(
476 Box::pin(watch.wait_for_change(excessive))
477 .as_mut()
478 .poll(&mut context),
479 Poll::Ready(Err(Error::InvalidInput(InputDefect::TimeoutTooLong { .. })))
480 ));
481 }
482
483 #[cfg(feature = "tokio")]
484 #[test]
485 fn invalid_discovery_inputs_are_refused_without_tokio_context() {
486 assert_invalid_discovery_inputs::<super::super::Tokio>();
487 }
488
489 #[cfg(feature = "smol")]
490 #[test]
491 fn invalid_discovery_inputs_are_refused_without_smol_context() {
492 assert_invalid_discovery_inputs::<super::super::Smol>();
493 }
494
495 fn cached_hit_is_ready_on_first_poll<R: AsyncRuntime>() {
496 let Some(ndi) = crate::test_support::ndi() else {
497 return;
498 };
499 let adapter = AsyncFinder::<R, SourceCache>::new(SourceCache::new(finder(&ndi)));
500 let expected = Source::new("CAMERA (Program)").unwrap();
501 adapter
502 .cache()
503 .seed_for_test("camera", vec![expected.clone()]);
504 let mut context = Context::from_waker(Waker::noop());
505 let mut lookup = Box::pin(adapter.find_sources_by_host("CAMERA.", Duration::from_secs(30)));
506 let Poll::Ready(result) = lookup.as_mut().poll(&mut context) else {
507 panic!("a cached lookup must complete without dispatching a worker");
508 };
509 assert_eq!(result.unwrap(), vec![expected]);
510 }
511
512 #[cfg(feature = "tokio")]
513 #[test]
514 fn tokio_cache_hit_needs_no_runtime_or_blocking_worker() {
515 cached_hit_is_ready_on_first_poll::<super::super::Tokio>();
517 }
518
519 #[cfg(feature = "smol")]
520 #[test]
521 fn smol_cache_hit_is_ready_without_a_blocking_handoff() {
522 cached_hit_is_ready_on_first_poll::<super::super::Smol>();
523 }
524
525 #[cfg(feature = "tokio")]
526 #[test]
527 fn tokio_cache_hit_completes_while_the_only_blocking_worker_is_occupied() {
528 use std::sync::mpsc;
529 let runtime = ::tokio::runtime::Builder::new_current_thread()
530 .max_blocking_threads(1)
531 .build()
532 .unwrap();
533 runtime.block_on(async {
534 let (started_tx, started_rx) = mpsc::channel();
535 let (release_tx, release_rx) = mpsc::channel::<()>();
536 let blocker = ::tokio::task::spawn_blocking(move || {
537 started_tx.send(()).unwrap();
538 let _ = release_rx.recv();
539 });
540 started_rx.recv().unwrap();
541 cached_hit_is_ready_on_first_poll::<super::super::Tokio>();
544 drop(release_tx);
545 blocker.await.unwrap();
546 });
547 }
548
549 async fn cancelled_native_discovery_releases_its_owner<R: AsyncRuntime>() {
550 let Some(ndi) = crate::test_support::ndi() else {
551 return;
552 };
553 let adapter = AsyncFinder::<R>::new(finder(&ndi));
554 let cache = AsyncFinder::<R, SourceCache>::new(SourceCache::new(finder(&ndi)));
555 const LOOKUP: Duration = Duration::from_secs(30);
560 const WATCHDOG: Duration = Duration::from_secs(5);
561 fn abandon<T>(
562 label: &str,
563 operation: impl Future<Output = T>,
564 references: impl Fn() -> usize,
565 owners: usize,
566 ) {
567 let mut operation = Box::pin(operation);
568 let mut context = Context::from_waker(Waker::noop());
569 assert!(matches!(
570 operation.as_mut().poll(&mut context),
571 Poll::Pending
572 ));
573 thread::sleep(Duration::from_millis(50));
574 drop(operation);
575 let deadline = Instant::now() + WATCHDOG;
576 loop {
577 let observed = references();
578 if observed == owners {
579 break;
580 }
581 assert!(
582 Instant::now() < deadline,
583 "abandoned {label} kept its blocking worker ({observed} owners, expected {owners})"
584 );
585 thread::sleep(Duration::from_millis(1));
586 }
587 }
588 abandon(
589 "find_source",
590 adapter.find_source(LOOKUP, |_| false),
591 || Arc::strong_count(&adapter.inner),
592 1,
593 );
594 abandon(
595 "find_sources_by_host",
596 cache.find_sources_by_host("missing.invalid", LOOKUP),
597 || Arc::strong_count(&cache.inner),
598 1,
599 );
600 assert!(cache.cache().is_empty());
601 let mut watch = adapter.watch();
602 while adapter
604 .finder()
605 .watch()
606 .wait_for_change(Duration::ZERO)
607 .unwrap()
608 {}
609 watch.current_sources().await.unwrap();
610 abandon(
611 "wait_for_change",
612 watch.wait_for_change(LOOKUP),
613 || Arc::strong_count(&adapter.inner),
614 2,
615 );
616 }
617
618 #[cfg(feature = "tokio")]
619 #[test]
620 fn tokio_abandoned_native_discovery_releases_its_owner() {
621 ::tokio::runtime::Builder::new_current_thread()
622 .build()
623 .unwrap()
624 .block_on(cancelled_native_discovery_releases_its_owner::<
625 super::super::Tokio,
626 >());
627 }
628
629 #[cfg(feature = "smol")]
630 #[test]
631 fn smol_abandoned_native_discovery_releases_its_owner() {
632 ::smol::block_on(cancelled_native_discovery_releases_its_owner::<
633 super::super::Smol,
634 >());
635 }
636}