1use iroh::EndpointId;
10pub use moq_ext_access::Layout;
11use moq_net::{Path, Prefix, Prefixes, broadcast};
12use n0_error::e;
13
14use crate::{
15 Audience, BroadcastTicket, Error, Grant, Node, NodeConfig,
16 policy::{self, PeerRequest, Policy},
17};
18
19const DEFAULT_ROOT: &str = "live";
21
22#[derive(Debug, Clone, PartialEq, Eq, Hash)]
40pub struct LiveLayout {
41 root: String,
42}
43
44impl Default for LiveLayout {
45 fn default() -> Self {
46 Self::new(DEFAULT_ROOT)
47 }
48}
49
50impl LiveLayout {
51 #[must_use]
58 pub fn new(root: impl Into<String>) -> Self {
59 let root = root.into();
60 assert!(
61 !root.is_empty() && !root.contains('/') && root.parse::<Prefix>().is_ok(),
62 "the root of a layout is one valid path segment, not {root:?}"
63 );
64 Self { root }
65 }
66
67 #[must_use]
69 pub fn root(&self) -> &str {
70 &self.root
71 }
72
73 pub fn path(&self, peer: EndpointId, name: &str) -> Result<Path, Error> {
80 let invalid = || {
81 e!(Error::InvalidPath {
82 path: name.to_owned()
83 })
84 };
85 if name.is_empty() || name.split('/').any(str::is_empty) {
86 return Err(invalid());
87 }
88 let path = format!("{}/{peer}/{name}", self.root);
89 path.parse::<Prefix>().map_err(|_| invalid())?;
90 Path::new(&path).map_err(|_| invalid())
91 }
92
93 #[must_use]
99 pub fn parse<'a>(&self, path: &'a Path) -> Option<(EndpointId, &'a str)> {
100 let (peer, name) = path
101 .as_str()
102 .strip_prefix(&self.root)?
103 .strip_prefix('/')?
104 .split_once('/')?;
105 let id: EndpointId = peer.parse().ok()?;
106 (id.to_string() == peer && !name.is_empty()).then_some((id, name))
107 }
108
109 #[must_use]
134 pub fn policy(&self) -> impl Policy<EndpointId> + Clone + use<> {
135 policy(self.clone())
136 }
137
138 #[must_use]
143 pub fn config(&self) -> NodeConfig {
144 config(self.clone())
145 }
146
147 pub fn publish<B>(&self, node: &Node, name: &str) -> Result<B, Error>
179 where
180 B: TryFrom<broadcast::Producer, Error: std::error::Error + Send + Sync + 'static>,
181 {
182 let path = self.path(node.id(), name)?;
183 let (_publication, broadcast) = node.publish_with(path, Audience::Granted, |producer| {
184 B::try_from(producer.clone())
185 })?;
186 Ok(broadcast)
187 }
188
189 pub fn ticket(&self, peer: EndpointId, name: &str) -> Result<BroadcastTicket, Error> {
197 Ok(BroadcastTicket::at(peer, self.path(peer, name)?))
198 }
199}
200
201impl Layout<EndpointId> for LiveLayout {
202 fn scope(&self, peer: &EndpointId) -> Prefixes {
204 let prefix: Prefix = format!("{}/{peer}", self.root)
205 .parse()
206 .expect("the root and an endpoint id are valid path segments");
207 Prefixes::from(prefix)
208 }
209
210 fn owner(&self, path: &str) -> Option<EndpointId> {
212 let path = Path::new(path).ok()?;
213 let (peer, name) = self.parse(&path)?;
214 (self.path(peer, name).ok()? == path).then_some(peer)
215 }
216}
217
218#[must_use]
223pub fn grant(layout: &impl Layout<EndpointId>, peer: EndpointId) -> Grant {
224 Grant::publish_under(layout.scope(&peer))
225}
226
227#[must_use]
233pub fn policy(layout: impl Layout<EndpointId> + Clone) -> impl Policy<EndpointId> + Clone {
234 policy::from_fn(move |request: &PeerRequest| Ok(grant(&layout, *request.peer()).into()))
235}
236
237#[must_use]
242pub fn config(layout: impl Layout<EndpointId> + Clone) -> NodeConfig {
243 NodeConfig::default()
244 .with_policy(policy(layout.clone()))
245 .with_layout(layout)
246}
247
248#[cfg(test)]
249mod tests {
250 use iroh::SecretKey;
251
252 use super::*;
253 use crate::SessionRequest;
254
255 fn id() -> EndpointId {
256 SecretKey::generate().public()
257 }
258
259 #[tokio::test]
261 async fn a_layouts_config_claims_by_its_own_owner_rule() {
262 let layout = LiveLayout::new("cams");
263 let config = layout.config();
264 assert!(config.layout.is_some(), "the config names no layout");
265 let node = Node::new(crate::test_util::endpoint().await, config);
266 let peer = id();
267
268 let inside = layout.path(peer, "cam").expect("a path");
269 node.claim_path(peer, &inside)
270 .expect("the layout's own path");
271 let outside = Path::new(&format!("live/{peer}/cam")).expect("a path");
273 let err = node
274 .claim_path(peer, &outside)
275 .expect_err("a path outside the layout");
276 assert!(matches!(err, Error::NotOwner { .. }), "{err:#}");
277 node.shutdown().await;
278 }
279
280 #[test]
281 fn path_and_parse_invert() {
282 let layout = LiveLayout::default();
283 let peer = id();
284 for name in ["cam", "cam/hd", "call"] {
285 let path = layout.path(peer, name).expect("a path");
286 assert_eq!(layout.parse(&path), Some((peer, name)));
287 }
288 let elsewhere = Path::new(&format!("rooms/{peer}/cam")).expect("path");
289 assert_eq!(layout.parse(&elsewhere), None);
290 let other_root = LiveLayout::new("fleet").path(peer, "cam").expect("path");
291 assert_eq!(layout.parse(&other_root), None);
292 assert_eq!(
293 layout.parse(&Path::new("live/nobody/cam").expect("path")),
294 None
295 );
296 assert_eq!(
297 layout.parse(&Path::new(&format!("livestock/{peer}/cam")).expect("path")),
298 None
299 );
300 }
301
302 #[test]
303 fn parse_wants_the_canonical_id() {
304 let layout = LiveLayout::default();
305 let peer = id();
306 let base32 = data_encoding::BASE32_NOPAD
307 .encode(peer.as_bytes())
308 .to_ascii_lowercase();
309 let path = Path::new(&format!("live/{base32}/cam")).expect("path");
310 assert_eq!(layout.parse(&path), None);
311 let bare = Path::new(&format!("live/{peer}")).expect("path");
312 assert_eq!(layout.parse(&bare), None);
313 }
314
315 #[test]
316 fn the_scope_matches_only_the_peers_own_paths() {
317 let layout = LiveLayout::default();
318 let (a, b) = (id(), id());
319 let grant = grant(&layout, a);
320 assert!(grant.allows_publish(layout.path(a, "cam").expect("path").as_str()));
321 assert!(!grant.allows_publish(layout.path(b, "cam").expect("path").as_str()));
322 assert!(grant.allows_subscribe("anything/at/all"));
323 }
324
325 #[test]
326 fn the_layout_owns_what_it_scopes() {
327 let layout = LiveLayout::default();
328 let (peer, other) = (id(), id());
329 let scope = layout.scope(&peer);
330 for name in ["cam", "cam/hd"] {
331 let path = layout.path(peer, name).expect("a path");
332 assert!(scope.matches(path.as_str()), "{path}");
333 assert_eq!(layout.owner(path.as_str()), Some(peer), "{path}");
334 assert!(!layout.scope(&other).matches(path.as_str()), "{path}");
335 }
336 assert_eq!(layout.owner(&format!("live/{peer}")), None);
337 assert_eq!(layout.owner(&format!("rooms/{peer}/topic/cam")), None);
338 assert_eq!(layout.owner(&format!("fleet/{peer}/cam")), None);
339 }
340
341 #[test]
342 fn two_layouts_compose() {
343 let (a, b) = (LiveLayout::new("a"), LiveLayout::new("b"));
344 let peer = id();
345 let request = PeerRequest::new(peer, SessionRequest::default(), policy::Event::Connect);
346 let grant = n0_future::future::block_on(Policy::decide(&policy((a, b)), &request))
347 .expect("admitted")
348 .grant;
349 assert!(grant.allows_publish(&format!("a/{peer}/cam")));
350 assert!(grant.allows_publish(&format!("b/{peer}/cam")));
351 assert!(!grant.allows_publish(&format!("c/{peer}/cam")));
352 }
353
354 #[test]
355 #[should_panic(expected = "one valid path segment")]
356 fn new_panics_on_a_bad_root() {
357 let _ = LiveLayout::new("a/b");
358 }
359
360 #[test]
361 fn names_that_make_no_path_fail() {
362 let layout = LiveLayout::default();
363 let peer = id();
364 for name in ["", "a//b", "/a", "a/", "*", "a/**"] {
365 let err = layout.path(peer, name).expect_err(name);
366 assert!(matches!(err, Error::InvalidPath { .. }), "{name}: {err:#}");
367 assert!(layout.ticket(peer, name).is_err(), "{name}");
368 }
369 }
370
371 fn decided(policy: &impl Policy<EndpointId>, peer: EndpointId) -> Grant {
373 let request = PeerRequest::new(peer, SessionRequest::default(), policy::Event::Connect);
374 n0_future::future::block_on(Policy::decide(policy, &request))
375 .expect("admitted")
376 .grant
377 }
378
379 #[test]
380 fn the_layout_methods_match_the_free_functions() {
381 let layout = LiveLayout::new("fleet");
382 let peer = id();
383 assert_eq!(decided(&layout.policy(), peer), grant(&layout, peer));
384 let config = layout.config();
385 let policy = config.policy.expect("a policy");
386 assert_eq!(decided(&policy, peer), grant(&layout, peer));
387 }
388
389 #[test]
390 fn the_policy_gives_each_peer_its_own_scope() {
391 let layout = LiveLayout::default();
392 let policy = layout.policy();
393 let (a, b) = (id(), id());
394 let for_a = decided(&policy, a);
395 let for_b = decided(&policy, b);
396 let cam_of = |peer| layout.path(peer, "cam").expect("path");
397 assert!(for_a.allows_publish(cam_of(a).as_str()));
398 assert!(!for_a.allows_publish(cam_of(b).as_str()));
399 assert!(for_b.allows_publish(cam_of(b).as_str()));
400 assert!(!for_b.allows_publish(cam_of(a).as_str()));
401 }
402
403 #[test]
404 fn a_pair_of_layouts_grants_and_configures_both_scopes() {
405 let both = (LiveLayout::new("a"), LiveLayout::new("b"));
406 let (peer, other) = (id(), id());
407 let granted = grant(&both, peer);
408 assert!(granted.allows_publish(&format!("a/{peer}/cam")));
409 assert!(granted.allows_publish(&format!("b/{peer}/cam")));
410 assert!(!granted.allows_publish(&format!("a/{other}/cam")));
411 assert!(!granted.allows_publish(&format!("c/{peer}/cam")));
412 assert!(granted.allows_subscribe("anything"));
413 let policy = config(both).policy.expect("a policy");
414 assert_eq!(decided(&policy, peer), granted);
415 }
416
417 #[test]
418 fn a_ticket_round_trips_a_name_with_reserved_characters() {
419 let layout = LiveLayout::default();
420 let peer = id();
421 for name in [
422 "my cam",
423 "a?b=c#d",
424 "x%20y",
425 "caf\u{e9}/\u{1f600}",
426 "a+b&c",
427 "~",
428 ] {
429 let ticket = layout.ticket(peer, name).expect(name);
430 let text = ticket.to_string();
431 assert!(text.is_ascii(), "{text}");
432 let parsed: BroadcastTicket = text.parse().expect(&text);
433 assert_eq!(parsed, ticket, "{name}");
434 assert_eq!(parsed.peer(), peer);
435 assert_eq!(layout.parse(parsed.path()), Some((peer, name)), "{name}");
436 assert_eq!(layout.owner(parsed.path().as_str()), Some(peer), "{name}");
437 }
438 }
439}