Skip to content

Commit 09a6e43

Browse files
authored
Merge pull request #193 from FastTrackStudios/feat/transport-host
feat(doc, lead): the transport's host in the session document, and a leader on its node's presence (#192)
2 parents f186f34 + ceeec63 commit 09a6e43

4 files changed

Lines changed: 144 additions & 8 deletions

File tree

‎crates/session/src/doc.rs‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,11 @@ const REGIONS: &str = "regions";
7474
const LANES: &str = "lanes";
7575
const ITEMS: &str = "items";
7676
const EXTENSIONS: &str = "extensions";
77+
/// Where the session's presence (its transport, and the clock its peers
78+
/// share) is hosted: `host`, the node serving it (session#192). The same
79+
/// root and key as Architect's `crdt::presence::presence_host`, which a
80+
/// node's relay reads to route an extension's presence there.
81+
const TRANSPORT: &str = "presence";
7782

7883
/// Writing the document failed.
7984
#[derive(Debug)]
@@ -371,6 +376,36 @@ impl SessionDoc {
371376
Ok(())
372377
}
373378

379+
/// The node that hosts the session's transport: its presence and the
380+
/// clock every peer of the session shares (session#192), as the
381+
/// leader wrote it (an Architect node's iroh endpoint id). A follower
382+
/// reads it from the synced document and follows that node, through
383+
/// the org, with no address given. `None`: no leader has said.
384+
#[must_use]
385+
pub fn transport_host(&self) -> Option<String> {
386+
value_of(&self.doc.get_map(TRANSPORT), "host")
387+
.and_then(|v| v.into_string().ok())
388+
.map(|s| s.to_string())
389+
.filter(|s| !s.is_empty())
390+
}
391+
392+
/// Says which node hosts the session's transport (`None`: none now).
393+
/// The leader writes it when it starts leading; last writer wins.
394+
///
395+
/// # Errors
396+
///
397+
/// Loro refused the write.
398+
pub fn set_transport_host(&self, host: Option<&str>) -> DocResult<()> {
399+
let map = self.doc.get_map(TRANSPORT);
400+
match host {
401+
Some(host) => map.insert("host", host)?,
402+
None if map.get("host").is_some() => map.delete("host")?,
403+
None => return Ok(()),
404+
}
405+
self.doc.commit();
406+
Ok(())
407+
}
408+
374409
fn put<R>(
375410
&self,
376411
root: &str,

‎crates/session/src/lead.rs‎

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@ pub const LEAD: &str = "lead";
2828

2929
/// A session's transport, led from here.
3030
pub struct Leader {
31-
url: String,
31+
/// Where it serves its own presence ([`Leader::serve`]); `None` on a
32+
/// presence someone else hosts ([`Leader::on`]).
33+
url: Option<String>,
3234
here: Here<PresencePeer>,
3335
}
3436

@@ -76,15 +78,34 @@ impl Leader {
7678
waited = waited.saturating_add(1);
7779
tokio::time::sleep(Duration::from_millis(20)).await;
7880
}
79-
let here = Here::new(peer, LEAD, PeerState::new(LEAD, "Transport"));
80-
Ok(Self { url: local, here })
81+
Ok(Self::on(peer).with_url(local))
8182
}
8283

83-
/// Where it is served on this machine (`ws://127.0.0.1:<port>/vox`):
84-
/// another machine dials this host's address on the same port.
84+
/// Leads on `peer`, a presence its owner drives: the node's own, which
85+
/// hosts the session's presence and clock and is reached through the
86+
/// org by its endpoint id (session#192; the leader names it in the
87+
/// session document, `SessionDoc::set_transport_host`). [`Self::publish`]
88+
/// sends nothing until `peer`'s clock has its first estimate.
8589
#[must_use]
86-
pub fn url(&self) -> &str {
87-
&self.url
90+
pub fn on(peer: PresencePeer) -> Self {
91+
Self {
92+
url: None,
93+
here: Here::new(peer, LEAD, PeerState::new(LEAD, "Transport")),
94+
}
95+
}
96+
97+
fn with_url(mut self, url: String) -> Self {
98+
self.url = Some(url);
99+
self
100+
}
101+
102+
/// Where it is served on this machine (`ws://127.0.0.1:<port>/vox`),
103+
/// when it serves its own presence ([`Self::serve`]): another machine
104+
/// dials this host's address on the same port. `None` for a leader
105+
/// [`Self::on`] a presence its node hosts.
106+
#[must_use]
107+
pub fn url(&self) -> Option<&str> {
108+
self.url.as_deref()
88109
}
89110

90111
/// The transport now: playing or not, at `position_seconds` of the

‎crates/session/tests/session/doc.rs‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,3 +283,22 @@ fn a_transport_rides_presence_as_a_play_state() {
283283
let back = doc::transport_of(&doc::play_state(&t)).unwrap();
284284
assert_eq!(back, t);
285285
}
286+
287+
/// The node hosting the session's transport travels with the document
288+
/// (session#192): what the leader writes, a follower's replica reads, and
289+
/// clearing it is seen too.
290+
#[test]
291+
fn the_transport_host_travels_with_the_document() {
292+
let (a, b) = pair();
293+
assert_eq!(b.transport_host(), None);
294+
a.set_transport_host(Some("4f1e…endpoint")).unwrap();
295+
exchange(&a, &b);
296+
assert_eq!(b.transport_host().as_deref(), Some("4f1e…endpoint"));
297+
a.set_transport_host(None).unwrap();
298+
exchange(&a, &b);
299+
assert_eq!(b.transport_host(), None);
300+
// Clearing what is not there writes nothing.
301+
let before = a.doc().oplog_vv();
302+
a.set_transport_host(None).unwrap();
303+
assert_eq!(a.doc().oplog_vv(), before);
304+
}

‎crates/session/tests/session/lead.rs‎

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ async fn a_follower_draws_where_the_leader_plays() {
3535

3636
// A follower elsewhere: its presence, dialled (its driver pings the
3737
// host's clock into `PresencePeer::clock`).
38-
let url = leader.url().to_owned();
38+
let url = leader.url().expect("it serves its own presence").to_owned();
3939
let presence: DocPresenceClient = pool().client(&Endpoint::url(&url)).await.unwrap();
4040
let (peer, mut driver) = PresencePeer::new(doc, 30_000);
4141
let clock = peer.clock().clone();
@@ -68,3 +68,64 @@ async fn a_follower_draws_where_the_leader_plays() {
6868
})
6969
.await;
7070
}
71+
72+
/// A leader on a presence its node hosts and drives ([`Leader::on`],
73+
/// session#192): it serves nothing of its own, and a follower of that
74+
/// presence hears it, stamped in the host's clock.
75+
#[tokio::test(flavor = "multi_thread")]
76+
async fn a_leader_on_its_nodes_presence_is_followed() {
77+
use architect::LayerRouter;
78+
use architect::host::EngineHost;
79+
use crdt::sync::{DocPresenceDispatcher, PresenceHost, doc_presence_service_descriptor};
80+
81+
let doc = Uuid::new_v4();
82+
let port = 48_000 + (std::process::id() % 1000);
83+
let router = LayerRouter::new().with(
84+
doc_presence_service_descriptor(),
85+
DocPresenceDispatcher::new(PresenceHost::new(doc, 30_000)),
86+
);
87+
let bind = format!("127.0.0.1:{port}");
88+
tokio::spawn(async move {
89+
let _ = EngineHost::ungated(router, bind).serve().await;
90+
});
91+
let url = format!("ws://127.0.0.1:{port}/vox");
92+
let join = |url: String| async move {
93+
let mut tries = 0_u32;
94+
let client: DocPresenceClient = loop {
95+
match pool().client(&Endpoint::url(&url)).await {
96+
Ok(client) => break client,
97+
Err(e) => {
98+
assert!(tries < 200, "never served: {e}");
99+
tries = tries.saturating_add(1);
100+
tokio::time::sleep(Duration::from_millis(20)).await;
101+
}
102+
}
103+
};
104+
let (peer, mut driver) = PresencePeer::new(doc, 30_000);
105+
tokio::spawn(async move {
106+
let _ = driver.run(&client).await;
107+
});
108+
peer
109+
};
110+
111+
let leader = Leader::on(join(url.clone()).await);
112+
assert_eq!(leader.url(), None, "it serves nothing of its own");
113+
let follower = join(url).await;
114+
let clock = follower.clock().clone();
115+
until("the leader's clock is estimated", || {
116+
leader.publish(true, 12.0, 1.0)
117+
})
118+
.await;
119+
let mut heard = None;
120+
until("the follower hears the leader", || {
121+
heard = follower.states().get("lead/play").and_then(transport_of);
122+
heard.is_some() && clock.offset_ms().is_some()
123+
})
124+
.await;
125+
let mut tracker = Tracker::default();
126+
tracker.observe(heard.unwrap());
127+
let shown = tracker
128+
.position(now_micros_f64(), clock.offset_ms().unwrap() * 1000.0)
129+
.unwrap();
130+
assert!((12.0..12.5).contains(&shown), "shown {shown}");
131+
}

0 commit comments

Comments
 (0)