1use std::{
4 collections::BTreeSet,
5 sync::{Arc, Weak},
6};
7
8use iroh::EndpointId;
9use moq_net::{
10 Path, Prefix, broadcast,
11 origin::{self, RouteOptions},
12};
13use n0_error::{AnyError, e};
14use n0_future::task::AbortOnDropHandle;
15use n0_watcher::Watcher;
16use tokio_util::sync::CancellationToken;
17use tracing::{Instrument, debug, debug_span, info};
18
19use crate::{
20 BroadcastTicket, Error,
21 node::Shared,
22 state::{PublicationEntry, State},
23};
24
25pub type Audience = moq_ext_access::Audience<EndpointId>;
29
30pub(crate) type AudienceKind = moq_ext_access::AudienceKind<EndpointId>;
32
33#[derive(Debug, Clone)]
63pub struct Publication {
64 inner: Arc<PublicationInner>,
65}
66
67#[derive(derive_more::Debug)]
69struct PublicationInner {
70 id: u64,
71 publisher: EndpointId,
73 path: Path,
74 #[debug(skip)]
75 broadcast: broadcast::Producer,
76 #[debug(skip)]
77 shared: Weak<Shared>,
78 #[debug(skip)]
79 withdrawn: CancellationToken,
80}
81
82impl PartialEq for Publication {
83 fn eq(&self, other: &Self) -> bool {
84 self.inner.id == other.inner.id && Weak::ptr_eq(&self.inner.shared, &other.inner.shared)
85 }
86}
87
88impl Eq for Publication {}
89
90impl Publication {
91 #[must_use]
93 pub fn path(&self) -> &Path {
94 &self.inner.path
95 }
96
97 #[must_use]
101 pub fn ticket(&self) -> BroadcastTicket {
102 BroadcastTicket::at(self.inner.publisher, self.inner.path.clone())
103 }
104
105 #[must_use]
110 pub fn broadcast(&self) -> &broadcast::Producer {
111 &self.inner.broadcast
112 }
113
114 pub async fn withdrawn(&self) {
118 self.inner.withdrawn.cancelled().await;
119 }
120
121 #[must_use]
123 pub fn is_withdrawn(&self) -> bool {
124 self.inner.withdrawn.is_cancelled()
125 }
126
127 pub fn set_audience(&self, audience: Audience) {
137 let Some(shared) = self.inner.shared.upgrade() else {
138 return;
139 };
140 let mut state = shared.state.lock().expect("poisoned");
141 let id = self.inner.id;
142 let Some(entry) = state.publications.get_mut(&id) else {
143 return;
144 };
145 entry.audience_generation += 1;
146 entry.peers_task = peers_task(
147 &audience,
148 id,
149 entry.audience_generation,
150 &entry.path,
151 &self.inner.shared,
152 );
153 state.set_audience(id, AudienceKind::from(&audience));
154 }
155
156 pub fn unpublish(&self) {
162 let Some(shared) = self.inner.shared.upgrade() else {
163 return;
164 };
165 let removed = shared
166 .state
167 .lock()
168 .expect("poisoned")
169 .remove_publication(self.inner.id);
170 if let Some(entry) = removed {
171 info!(path = %entry.path, "unpublished");
172 }
173 }
174
175 pub fn unpublish_on_drop(self) -> UnpublishOnDrop {
198 UnpublishOnDrop {
199 publication: self,
200 armed: true,
201 }
202 }
203}
204
205#[derive(Debug)]
209#[must_use = "dropping the guard unpublishes the publication at once"]
210pub struct UnpublishOnDrop {
211 publication: Publication,
212 armed: bool,
213}
214
215impl UnpublishOnDrop {
216 pub fn disarm(mut self) -> Publication {
218 self.armed = false;
219 self.publication.clone()
220 }
221}
222
223impl std::ops::Deref for UnpublishOnDrop {
224 type Target = Publication;
225
226 fn deref(&self) -> &Publication {
227 &self.publication
228 }
229}
230
231impl Drop for UnpublishOnDrop {
232 fn drop(&mut self) {
233 if self.armed {
234 debug!(path = %self.publication.path(), "guard dropped, unpublishing");
235 self.publication.unpublish();
236 }
237 }
238}
239
240fn peers_task(
246 audience: &Audience,
247 id: u64,
248 generation: u64,
249 path: &Path,
250 shared: &Weak<Shared>,
251) -> Option<AbortOnDropHandle<()>> {
252 let Audience::Peers(set) = audience else {
253 return None;
254 };
255 let set = set.clone();
256 let shared = shared.clone();
257 let span = debug_span!("audience", %path, generation);
258 let task = async move {
259 let mut peers = set.watch();
260 let mut current = peers.get();
262 loop {
263 {
264 let Some(shared) = shared.upgrade() else {
265 return;
266 };
267 let mut state = shared.state.lock().expect("poisoned");
268 if !apply_peers(&mut state, id, generation, current) {
269 return;
270 }
271 }
272 let Ok(next) = peers.updated().await else {
274 return;
275 };
276 current = next;
277 }
278 };
279 Some(AbortOnDropHandle::new(tokio::spawn(task.instrument(span))))
280}
281
282fn apply_peers(state: &mut State, id: u64, generation: u64, peers: BTreeSet<EndpointId>) -> bool {
288 let Some(entry) = state.publications.get(&id) else {
289 return false;
290 };
291 if entry.audience_generation != generation {
292 debug!(path = %entry.path, generation, "audience replaced, peers task ends");
293 return false;
294 }
295 debug!(path = %entry.path, generation, peers = peers.len(), "audience peers set");
296 state.set_audience(id, AudienceKind::Peers(peers));
297 true
298}
299
300pub(crate) fn publish<T, E>(
307 shared: &Arc<Shared>,
308 path: Path,
309 audience: Audience,
310 fill: impl FnOnce(&broadcast::Producer) -> Result<T, E>,
311) -> Result<(Publication, T), Error>
312where
313 E: Into<Box<dyn std::error::Error + Send + Sync>>,
314{
315 check_path(&path)?;
316 if shared.shutdown.is_cancelled() {
317 return Err(e!(Error::ShutDown));
318 }
319 let (publication, filled) = filled_route(shared, &path, fill)?;
320 let refuse = |err: Error| {
322 publication.broadcast().close();
323 Err(err)
324 };
325 let weak = Arc::downgrade(shared);
326 let mut state = shared.state.lock().expect("poisoned");
327 if state.closed {
328 return refuse(e!(Error::ShutDown));
329 }
330 if let Err(err) = free_path(&mut state, &path) {
331 return refuse(err);
332 }
333 let broadcast = publication.broadcast().clone();
334 let id = state.next_id();
335 let closed_task = unpublish_when_closed(broadcast.consume(), weak.clone(), id, path.clone());
336 let withdrawn = CancellationToken::new();
337 state.add_publication(
342 id,
343 PublicationEntry {
344 path: path.clone(),
345 publication,
346 audience: AudienceKind::from(&audience),
347 peers_task: peers_task(&audience, id, 0, &path, &weak),
348 audience_generation: 0,
349 _closed_task: AbortOnDropHandle::new(closed_task),
350 withdrawn: withdrawn.clone(),
351 },
352 );
353 if let Err(source) = state.publications[&id].publication.announce() {
356 drop(state.remove_publication(id));
357 broadcast.close();
358 return Err(e!(Error::Moq { source }));
359 }
360 info!(%path, ?audience, "published");
361 let publication = Publication {
362 inner: Arc::new(PublicationInner {
363 id,
364 publisher: shared.id,
365 path,
366 broadcast,
367 shared: weak,
368 withdrawn,
369 }),
370 };
371 Ok((publication, filled))
372}
373
374fn filled_route<T, E>(
379 shared: &Shared,
380 path: &Path,
381 fill: impl FnOnce(&broadcast::Producer) -> Result<T, E>,
382) -> Result<(origin::Route, T), Error>
383where
384 E: Into<Box<dyn std::error::Error + Send + Sync>>,
385{
386 let publication = shared
387 .table
388 .route(path.clone(), RouteOptions::hidden())
389 .map_err(|source| e!(Error::Moq { source }))?;
390 match fill(publication.broadcast()) {
391 Ok(filled) => Ok((publication, filled)),
392 Err(err) => {
393 publication.broadcast().close();
394 Err(e!(Error::Fill {
395 source: Arc::new(AnyError::from_std_box(err.into()))
396 }))
397 }
398 }
399}
400
401fn free_path(state: &mut State, path: &Path) -> Result<(), Error> {
403 if let Some(existing) = state.publication_at(path) {
404 let entry = &state.publications[&existing];
406 if !entry.publication.broadcast().consume().is_closed() {
407 return Err(e!(Error::Duplicate { path: path.clone() }));
408 }
409 state.remove_publication(existing);
410 }
411 Ok(())
412}
413
414fn unpublish_when_closed(
416 consumer: broadcast::Consumer,
417 shared: Weak<Shared>,
418 id: u64,
419 path: Path,
420) -> tokio::task::JoinHandle<()> {
421 tokio::spawn(async move {
422 consumer.closed().await;
423 let Some(shared) = shared.upgrade() else {
424 return;
425 };
426 let removed = shared
427 .state
428 .lock()
429 .expect("poisoned")
430 .remove_publication(id);
431 if removed.is_some() {
432 info!(%path, "broadcast ended, unpublished");
433 }
434 })
435}
436
437pub(crate) fn check_path(path: &Path) -> Result<(), Error> {
442 if path.is_empty() || path.as_str().parse::<Prefix>().is_err() {
443 return Err(e!(Error::InvalidPath {
444 path: path.as_str().to_owned()
445 }));
446 }
447 Ok(())
448}
449
450#[cfg(test)]
451mod tests {
452 use iroh::{Endpoint, SecretKey};
453
454 use super::*;
455 use crate::{Node, NodeConfig};
456
457 #[test]
458 fn check_path_refuses_empty_and_wildcard_paths() {
459 let check = |path: &str| check_path(&Path::new(path).expect("a path"));
460 assert!(check("live/alice/cam").is_ok());
461 assert!(matches!(check(""), Err(Error::InvalidPath { .. })));
462 assert!(matches!(
463 check("live/*/cam"),
464 Err(Error::InvalidPath { .. })
465 ));
466 assert!(matches!(check("live/**"), Err(Error::InvalidPath { .. })));
467 assert!(matches!(
468 check("live/a*b/cam"),
469 Err(Error::InvalidPath { .. })
470 ));
471 }
472
473 #[tokio::test]
475 async fn the_unpublish_guard_frees_the_path_unless_disarmed() {
476 let endpoint = Endpoint::bind(crate::MinimalPreset).await.expect("binds");
477 let node = Node::new(endpoint.clone(), NodeConfig::default());
478 let path = "live/test/results";
479
480 let guard = node
481 .publish(path, Audience::Granted)
482 .expect("publish")
483 .unpublish_on_drop();
484 let publication = Publication::clone(&guard);
485 drop(guard);
486 assert!(publication.is_withdrawn(), "the guard did not unpublish");
487
488 let kept = node
489 .publish(path, Audience::Granted)
490 .expect("the path is free again")
491 .unpublish_on_drop()
492 .disarm();
493 assert!(!kept.is_withdrawn(), "disarming unpublished");
494 let err = node
495 .publish(path, Audience::Granted)
496 .expect_err("the disarmed publication still holds the path");
497 assert!(matches!(err, Error::Duplicate { .. }), "{err:#}");
498
499 node.shutdown().await;
500 endpoint.close().await;
501 }
502
503 #[tokio::test]
508 async fn a_replaced_peers_task_does_not_restore_its_set() {
509 let endpoint = Endpoint::bind(crate::MinimalPreset).await.expect("binds");
510 let node = Node::new(endpoint.clone(), NodeConfig::default());
511 let (revoked, kept) = (
512 SecretKey::generate().public(),
513 SecretKey::generate().public(),
514 );
515 let old = BTreeSet::from([revoked, kept]);
516 let publication = node
517 .publish("live/test/cam", Audience::peers(old.clone()))
518 .expect("publish");
519 let new = BTreeSet::from([kept]);
520 publication.set_audience(Audience::peers(new.clone()));
521
522 let id = publication.inner.id;
523 {
524 let mut state = node.shared.state.lock().expect("poisoned");
525 assert!(!apply_peers(&mut state, id, 0, old), "the old task wrote");
526 assert_eq!(state.publications[&id].audience, AudienceKind::Peers(new));
527 }
528
529 node.shutdown().await;
530 endpoint.close().await;
531 }
532}