interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-coord / src / board / agents.rs

288 lines · 10331 bytes Raw Blame History
1//! Tags: a human-readable name an agent binds to its session (`agents/<tag>.json`).
2//!
3//! A tag is identity **for addressing only**: messages are addressed to tags, cursors and
4//! subscriptions belong to tags (so an agent that comes back under a new session, after its
5//! old binding expired or was released, resumes the same inbox). It is not authentication:
6//! anyone who can write the board root can bind any free tag. The binding is live for its
7//! `ttl` after `seen_at`; posts refresh it. A tag bound to a live different session is
8//! refused with [`BoardError::TagTaken`].
9
10use super::frame::{as_string, compact};
11use super::journal::{ensure_dir, fsync_dir, reconcile_root, BoardLock};
12use super::{validate_session, validate_tag, Board, BoardError, PROTOCOL};
13use crate::json::{self, J};
14use std::fs;
15use std::path::PathBuf;
16
17/// Default binding lifetime: 4 hours after the last register or post.
18pub const DEFAULT_TAG_TTL: i64 = 4 * 3600;
19/// Longest binding lifetime accepted: 7 days.
20pub const MAX_TAG_TTL: i64 = 7 * 86400;
21/// Most bindings scanned by `whoami`.
22const MAX_AGENTS: usize = 4096;
23const MAX_BINDING_BYTES: u64 = 4096;
24
25/// A resolved identity: a live binding of `tag` to `session`.
26#[derive(Clone, Debug, PartialEq, Eq, Hash)]
27pub struct Me {
28 pub tag: String,
29 pub session: String,
30}
31
32/// Result of [`Board::register`].
33#[derive(Clone, Debug, PartialEq, Eq)]
34pub struct Registration {
35 pub me: Me,
36 /// True when this session already held the tag (idempotent re-register).
37 pub refreshed: bool,
38 pub expires_at: i64,
39}
40
41#[derive(Clone, Debug)]
42pub(crate) struct Binding {
43 pub tag: String,
44 pub session: String,
45 pub registered_at: i64,
46 pub seen_at: i64,
47 pub ttl: i64,
48}
49
50impl Binding {
51 fn live(&self, now: i64) -> bool {
52 now - self.seen_at <= self.ttl
53 }
54 fn to_json(&self) -> J {
55 let mut o = J::obj();
56 o.set("v", J::str(PROTOCOL));
57 o.set("tag", J::str(&self.tag));
58 o.set("session", J::str(&self.session));
59 o.set("registered_at", J::num(self.registered_at));
60 o.set("seen_at", J::num(self.seen_at));
61 o.set("ttl", J::num(self.ttl));
62 o
63 }
64}
65
66fn i64_field(j: &J, k: &str) -> Option<i64> {
67 match j.get(k) {
68 Some(J::Num(t)) => std::str::from_utf8(t).ok()?.parse().ok(),
69 _ => None,
70 }
71}
72
73impl Board {
74 fn binding_path(&self, tag: &str) -> PathBuf {
75 self.root().join("agents").join(format!("{tag}.json"))
76 }
77
78 fn read_binding(&self, tag: &str) -> Result<Option<Binding>, BoardError> {
79 let p = self.binding_path(tag);
80 crate::record::check_real_parents(self.root(), &p)?;
81 let Some(b) = crate::record::read_bounded(&p, MAX_BINDING_BYTES)? else {
82 return Ok(None);
83 };
84 let bad = |r: &str| BoardError::Corrupt {
85 path: p.clone(),
86 offset: 0,
87 reason: r.to_string(),
88 };
89 let j = json::parse(&b).ok_or_else(|| bad("not JSON"))?;
90 if as_string(j.get("v")).as_deref() != Some(PROTOCOL) {
91 return Err(bad("not an aien-board/1 binding"));
92 }
93 let b = Binding {
94 tag: as_string(j.get("tag")).ok_or_else(|| bad("no tag"))?,
95 session: as_string(j.get("session")).ok_or_else(|| bad("no session"))?,
96 registered_at: i64_field(&j, "registered_at").ok_or_else(|| bad("no registered_at"))?,
97 seen_at: i64_field(&j, "seen_at").ok_or_else(|| bad("no seen_at"))?,
98 ttl: i64_field(&j, "ttl").ok_or_else(|| bad("no ttl"))?,
99 };
100 if b.tag != tag {
101 return Err(bad("binding names another tag than its file"));
102 }
103 validate_session(&b.session)?;
104 Ok(Some(b))
105 }
106
107 fn write_binding(&self, b: &Binding) -> Result<(), BoardError> {
108 let mut data = compact(&b.to_json());
109 data.push(b'\n');
110 crate::durable_write(self.root(), &self.binding_path(&b.tag), &data)?;
111 Ok(())
112 }
113
114 /// Every binding on the board (bounded; a hostile file under `agents/` is refused).
115 /// Complete or an error: `register` decides from it that a session holds no other live
116 /// tag, and `whoami` that a session holds none, so only an absent `agents/` is empty;
117 /// a directory or an entry that cannot be read is [`BoardError::Io`].
118 pub(crate) fn bindings(&self) -> Result<Vec<Binding>, BoardError> {
119 let dir = self.root().join("agents");
120 let rd = match crate::record::list_dir(&dir) {
121 Ok(rd) => rd,
122 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
123 Err(e) => return Err(super::io_err(&dir)(e)),
124 };
125 let mut tags = Vec::new();
126 for ent in rd {
127 let ent = ent.map_err(super::io_err(&dir))?;
128 let name = ent.file_name();
129 let Some(n) = name.to_str() else { continue };
130 let Some(tag) = n.strip_suffix(".json") else {
131 continue;
132 };
133 if validate_tag(tag).is_err() {
134 continue;
135 }
136 tags.push(tag.to_string());
137 if tags.len() > MAX_AGENTS {
138 return Err(BoardError::TooLarge {
139 field: "agents",
140 len: tags.len(),
141 limit: MAX_AGENTS,
142 });
143 }
144 }
145 tags.sort();
146 let mut out = Vec::new();
147 for t in tags {
148 if let Some(b) = self.read_binding(&t)? {
149 out.push(b);
150 }
151 }
152 Ok(out)
153 }
154
155 /// Bind `tag` to `session` (under the writer lock). Idempotent for the same session;
156 /// [`BoardError::TagTaken`] when another session holds it live;
157 /// [`BoardError::SessionTagged`] when this session holds another live tag.
158 pub fn register(
159 &self,
160 session: &str,
161 tag: &str,
162 ttl: Option<i64>,
163 ) -> Result<Registration, BoardError> {
164 validate_tag(tag)?;
165 validate_session(session)?;
166 let ttl = ttl.unwrap_or(DEFAULT_TAG_TTL);
167 if !(1..=MAX_TAG_TTL).contains(&ttl) {
168 return Err(BoardError::TooLarge {
169 field: "ttl seconds",
170 len: ttl.max(0) as usize,
171 limit: MAX_TAG_TTL as usize,
172 });
173 }
174 let _lock = BoardLock::acquire(self.root())?;
175 self.check_id_locked()?;
176 // Also flushes a root entry (`agents/` itself) an earlier attempt left unsynced: the
177 // binding below is not durable until its directory's root entry is.
178 ensure_dir(self.root(), "agents")?;
179 let now = self.now();
180 let existing = self.read_binding(tag)?;
181 if let Some(b) = &existing {
182 if b.session != session && b.live(now) {
183 return Err(BoardError::TagTaken {
184 tag: tag.into(),
185 holder: b.session.clone(),
186 });
187 }
188 }
189 if let Some(other) = self
190 .bindings()?
191 .into_iter()
192 .find(|b| b.session == session && b.tag != tag && b.live(now))
193 {
194 return Err(BoardError::SessionTagged {
195 session: session.into(),
196 tag: other.tag,
197 });
198 }
199 let refreshed = existing
200 .as_ref()
201 .is_some_and(|b| b.session == session && b.live(now));
202 let b = Binding {
203 tag: tag.into(),
204 session: session.into(),
205 registered_at: if refreshed {
206 existing.map(|b| b.registered_at).unwrap_or(now)
207 } else {
208 now
209 },
210 seen_at: now,
211 ttl,
212 };
213 self.write_binding(&b)?;
214 Ok(Registration {
215 me: Me {
216 tag: tag.into(),
217 session: session.into(),
218 },
219 refreshed,
220 expires_at: now + ttl,
221 })
222 }
223
224 /// Release this session's tag (its cursor and subscriptions stay with the tag).
225 pub fn unregister(&self, session: &str) -> Result<Me, BoardError> {
226 let me = &self.whoami(session)?;
227 let _lock = BoardLock::acquire(self.root())?;
228 self.check_id_locked()?;
229 self.check_binding(me)?;
230 reconcile_root(self.root())?;
231 let p = self.binding_path(&me.tag);
232 fs::remove_file(&p).map_err(super::io_err(&p))?;
233 fsync_dir(&self.root().join("agents"))?;
234 Ok(me.clone())
235 }
236
237 /// The live tag this session holds, else [`BoardError::NotRegistered`].
238 pub fn whoami(&self, session: &str) -> Result<Me, BoardError> {
239 validate_session(session)?;
240 let now = self.now();
241 self.bindings()?
242 .into_iter()
243 .find(|b| b.session == session && b.live(now))
244 .map(|b| Me {
245 tag: b.tag,
246 session: b.session,
247 })
248 .ok_or_else(|| BoardError::NotRegistered {
249 session: session.into(),
250 })
251 }
252
253 /// Every binding as `(tag, session, live)`, for the operator view.
254 pub fn agents(&self) -> Result<Vec<(String, String, bool)>, BoardError> {
255 let now = self.now();
256 Ok(self
257 .bindings()?
258 .into_iter()
259 .map(|b| {
260 let live = b.live(now);
261 (b.tag, b.session, live)
262 })
263 .collect())
264 }
265
266 /// Verify that `me` is still a live binding (a handle cannot outlive its tag).
267 pub(crate) fn check_binding(&self, me: &Me) -> Result<Binding, BoardError> {
268 validate_tag(&me.tag)?;
269 validate_session(&me.session)?;
270 match self.read_binding(&me.tag)? {
271 Some(b) if b.session == me.session && b.live(self.now()) => Ok(b),
272 _ => Err(BoardError::NotRegistered {
273 session: me.session.clone(),
274 }),
275 }
276 }
277
278 /// Refresh `seen_at` when half the TTL has passed (caller holds the writer lock).
279 pub(crate) fn touch_locked(&self, _me: &Me, b: &Binding) -> Result<(), BoardError> {
280 let now = self.now();
281 if now - b.seen_at > b.ttl / 2 {
282 let mut nb = b.clone();
283 nb.seen_at = now;
284 self.write_binding(&nb)?;
285 }
286 Ok(())
287 }
288}