1use crate::release_channel::{self, ReleaseChannel};
4use anyhow::Result;
5use reqwest::Url;
6use std::{
7 path::{Path, PathBuf},
8 time::Duration,
9};
10
11pub const ACCOUNT: HostedOrigin = HostedOrigin {
12 stable: "https://api.gent.link",
13 beta: "https://beta-api.gent.link",
14};
15pub const RELAY: HostedOrigin = HostedOrigin {
16 stable: "https://relay.gent.link",
17 beta: "https://beta-relay.gent.link",
18};
19pub const MCP: HostedOrigin = HostedOrigin {
20 stable: "https://mcp.gent.link",
21 beta: "https://beta-mcp.gent.link",
22};
23
24#[derive(Clone, Copy)]
25pub struct HostedOrigin {
26 pub stable: &'static str,
27 pub beta: &'static str,
28}
29
30impl HostedOrigin {
31 pub fn contains(self, pin: &Url) -> bool {
32 pin.as_str()
33 .strip_suffix('/')
34 .is_some_and(|s| s == self.stable || s == self.beta)
35 }
36
37 pub fn identity(self, pin: Url) -> Url {
38 self.select(pin, ReleaseChannel::Stable)
39 }
40
41 fn select(self, pin: Url, channel: ReleaseChannel) -> Url {
42 if !self.contains(&pin) {
43 return pin;
44 }
45 let origin = match channel {
46 ReleaseChannel::Stable => self.stable,
47 ReleaseChannel::Beta => self.beta,
48 };
49 Url::parse(origin).expect("fixed HTTPS origin")
50 }
51
52 pub fn destination(self, home: &Path, pin: Url) -> Result<Url> {
53 if self.contains(&pin) {
54 Ok(self.select(pin, release_channel::current(home)?))
55 } else {
56 Ok(pin)
57 }
58 }
59
60 pub fn transport(self, home: &Path, account: Option<&str>, pin: Url) -> Result<TransportRoute> {
63 let managed = self.contains(&pin)
64 && account
65 .map(Url::parse)
66 .transpose()?
67 .is_some_and(|url| ACCOUNT.contains(&url));
68 Ok(TransportRoute {
69 role: self,
70 pin,
71 home: managed.then(|| home.to_owned()),
72 })
73 }
74}
75
76#[derive(Clone)]
79pub struct TransportRoute {
80 role: HostedOrigin,
81 pin: Url,
82 home: Option<PathBuf>,
83}
84
85impl TransportRoute {
86 pub fn identity(&self) -> Url {
88 if self.home.is_some() {
89 self.role.identity(self.pin.clone())
90 } else {
91 self.pin.clone()
92 }
93 }
94
95 pub fn destination(&self) -> Result<Url> {
96 match &self.home {
97 Some(home) => self.role.destination(home, self.pin.clone()),
98 None => Ok(self.pin.clone()),
99 }
100 }
101
102 pub async fn changed(&self, current: &Url) -> Url {
103 if self.home.is_none() {
104 return std::future::pending().await;
105 }
106 loop {
107 tokio::time::sleep(Duration::from_secs(15)).await;
108 if let Ok(next) = self.destination()
109 && next != *current
110 {
111 return next;
112 }
113 }
114 }
115}
116
117#[cfg(test)]
118mod tests {
119 use super::*;
120
121 #[tokio::test(start_paused = true)]
122 async fn existing_pins_follow_signed_changes_in_both_directions() -> Result<()> {
123 use crate::{config, store::Store};
124 use gent_protocol::{ConfigurationEdit, OwnerOp, Request, Response};
125
126 let home = tempfile::tempdir()?;
127 let home = &home.path().join("node");
128 let stable = Url::parse(RELAY.stable)?;
129 let beta = Url::parse(RELAY.beta)?;
130 let managed = RELAY.transport(home, Some(ACCOUNT.stable), stable.clone())?;
131 let staging = RELAY.transport(home, Some("https://staging.gent.link"), stable.clone())?;
132 let custom = RELAY.transport(
133 home,
134 Some(ACCOUNT.stable),
135 Url::parse("https://relay.example")?,
136 )?;
137 assert_eq!(managed.destination()?, stable);
138 config::initialize(home, "test")?;
139 let mut store = Store::open(home)?;
140 let owner = config::read_private(&home.join("owner.key"))?;
141 let mut previous = stable.clone();
142 for (channel, expected) in [
143 (ReleaseChannel::Beta, beta),
144 (ReleaseChannel::Stable, stable.clone()),
145 ] {
146 let request = Request::Owner {
147 credential: owner.clone(),
148 action: OwnerOp::Configure {
149 request_id: uuid::Uuid::new_v4().to_string(),
150 edit: ConfigurationEdit::SetReleaseChannel { channel },
151 },
152 };
153 assert!(matches!(store.handle(request), Response::Ok(_)));
154 assert_eq!(managed.destination()?, expected);
155 assert_eq!(
156 tokio::time::timeout(Duration::from_secs(20), managed.changed(&previous)).await?,
157 expected
158 );
159 assert_eq!(staging.destination()?, stable);
160 assert_eq!(custom.destination()?.host_str(), Some("relay.example"));
161 previous = expected;
162 }
163 Ok(())
164 }
165
166 #[test]
167 fn only_the_exact_pair_for_each_role_follows_the_channel() {
168 for role in [ACCOUNT, RELAY, MCP] {
169 for pin in [role.stable, role.beta].map(|s| Url::parse(s).unwrap()) {
170 assert_eq!(
171 role.select(pin.clone(), ReleaseChannel::Stable)
172 .origin()
173 .ascii_serialization(),
174 role.stable
175 );
176 assert_eq!(
177 role.select(pin, ReleaseChannel::Beta)
178 .origin()
179 .ascii_serialization(),
180 role.beta
181 );
182 }
183 for raw in [
184 "https://staging.gent.link",
185 "http://127.0.0.1:4000",
186 "https://beta-api.gent.link.example",
187 "https://api.gent.link:8443",
188 "https://api.gent.link/path",
189 "https://api.gent.link/?q",
190 "https://user@api.gent.link",
191 "http://api.gent.link",
192 ] {
193 let url = Url::parse(raw).unwrap();
194 assert_eq!(role.select(url.clone(), ReleaseChannel::Beta), url);
195 }
196 }
197 assert!(!ACCOUNT.contains(&Url::parse(RELAY.beta).unwrap()));
198 assert!(!MCP.contains(&Url::parse(ACCOUNT.beta).unwrap()));
199 }
200}