1use std::collections::{BTreeMap, BTreeSet};
18use std::sync::atomic::Ordering;
19use std::time::{Duration, Instant};
20
21use datumesh_core::json::{self, Value};
22use datumesh_core::lexical;
23use datumesh_core::{KeyDocument, Keys};
24use datumesh_store::{ListedHost, Listing, ListingWrite, Store, SubjectKeys};
25
26use crate::envelope::{Cache, Reply};
27
28pub const DEFAULT_INTERVAL: Duration = Duration::from_secs(21_600);
30
31pub const MAX_HOSTS: usize = 64;
33
34pub const UNREACHABLE_DROP_AFTER: Duration = Duration::from_secs(7 * 86_400);
37
38#[derive(Clone, Debug, PartialEq, Eq)]
40pub struct Limits {
41 pub names: usize,
43 pub bytes: u64,
45 pub time: Duration,
47}
48
49impl Default for Limits {
50 fn default() -> Self {
51 Limits { names: 2_000, bytes: 32 << 20, time: Duration::from_secs(120) }
52 }
53}
54
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub enum Cut {
58 Names,
60 Bytes,
62 Time,
64 Unreached,
67}
68
69#[derive(Clone, Debug, PartialEq, Eq)]
71pub struct FetchedName {
72 pub name: String,
74 pub fn_hash: String,
76 pub subjects: Vec<SubjectKeys>,
78 pub descriptor: Vec<u8>,
80 pub label: String,
82 pub description: String,
84}
85
86#[derive(Clone, Debug, PartialEq, Eq)]
88pub enum Fetch {
89 Fetched {
91 key_id: String,
93 names: Vec<FetchedName>,
95 refused: Vec<String>,
97 cut: Option<Cut>,
99 },
100 Unreachable {
102 detail: String,
104 },
105 KeyDocFailed {
108 detail: String,
110 },
111 MeshDocFailed {
113 detail: String,
115 },
116}
117
118#[derive(Clone, Copy, Debug, PartialEq, Eq)]
120pub enum Outcome {
121 Ok,
123 KeyDocFailed,
125 MeshDocFailed,
127 Cut,
129 Unreachable,
131}
132
133impl Outcome {
134 pub fn as_str(self) -> &'static str {
137 match self {
138 Outcome::Ok => "ok",
139 Outcome::KeyDocFailed => "key_document_failed",
140 Outcome::MeshDocFailed => "mesh_document_failed",
141 Outcome::Cut => "cut",
142 Outcome::Unreachable => "unreachable",
143 }
144 }
145}
146
147#[derive(Clone, Debug, PartialEq, Eq)]
149#[non_exhaustive]
150pub struct Applied {
151 pub outcome: Outcome,
153 pub cut: Option<Cut>,
155 pub added: Vec<String>,
157 pub changed: Vec<String>,
159 pub dropped: Vec<String>,
161 pub listed: usize,
163 pub writes: u64,
166}
167
168impl Applied {
169 pub fn changed_any(&self) -> bool {
171 !(self.added.is_empty() && self.changed.is_empty() && self.dropped.is_empty())
172 }
173}
174
175#[derive(Debug)]
177pub struct ListingError {
178 detail: String,
179}
180
181impl std::fmt::Display for ListingError {
182 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
183 write!(f, "listing: {}", self.detail)
184 }
185}
186
187impl std::error::Error for ListingError {}
188
189pub fn origin_of(config: &crate::Config, host: &str) -> String {
192 match config.peers.get(host) {
193 Some(origin) => origin.clone(),
194 None => format!("https://{host}"),
195 }
196}
197
198enum Stop {
200 Unreachable(String),
202 Bytes,
204}
205
206struct Run {
208 agent: ureq::Agent,
209 started: Instant,
210 limits: Limits,
211 bytes: u64,
212}
213
214impl Run {
215 fn new(limits: &Limits) -> Run {
216 let agent: ureq::Agent = ureq::Agent::config_builder()
217 .max_redirects(0)
218 .http_status_as_error(false)
219 .user_agent(concat!("datumesh-http/", env!("CARGO_PKG_VERSION")))
220 .build()
221 .into();
222 Run { agent, started: Instant::now(), limits: limits.clone(), bytes: 0 }
223 }
224
225 fn left(&self) -> Option<Duration> {
227 self.limits.time.checked_sub(self.started.elapsed()).filter(|d| !d.is_zero())
228 }
229
230 fn get(&mut self, url: &str) -> Result<(u16, Vec<u8>), Stop> {
232 let Some(left) = self.left() else { return Err(Stop::Unreachable("the run's time is spent".into())) };
233 let resp = self
234 .agent
235 .get(url)
236 .config()
237 .timeout_global(Some(left))
238 .build()
239 .call()
240 .map_err(|e| Stop::Unreachable(format!("{url}: {e}")))?;
241 let status = resp.status().as_u16();
242 if status >= 500 {
243 return Err(Stop::Unreachable(format!("{url}: status {status}")));
244 }
245 let room = self.limits.bytes.saturating_sub(self.bytes);
246 let body = resp.into_body().with_config().limit(room.saturating_add(1)).read_to_vec().map_err(|e| match e {
247 ureq::Error::BodyExceedsLimit(_) => Stop::Bytes,
248 e => Stop::Unreachable(format!("{url}: {e}")),
249 })?;
250 self.bytes += body.len() as u64;
251 if self.bytes > self.limits.bytes {
252 return Err(Stop::Bytes);
253 }
254 Ok((status, body))
255 }
256}
257
258fn instant_key(s: &str) -> String {
260 let s = s.strip_suffix('Z').unwrap_or(s);
261 let (whole, frac) = s.split_once('.').unwrap_or((s, ""));
262 let frac = &frac[..frac.len().min(9)];
263 format!("{whole}.{frac:0<9}")
264}
265
266fn key_valid_at(doc: &KeyDocument, now: &str) -> Option<String> {
268 let now = instant_key(now);
269 doc.keys
270 .keys
271 .iter()
272 .find(|k| instant_key(&k.valid_from) <= now && k.valid_to.as_deref().is_none_or(|t| now < instant_key(t)))
273 .map(|k| k.id.clone())
274}
275
276fn next_page(host: &str, origin: &str, next: &str) -> Option<String> {
279 let slice = format!("/slice/{host}/");
280 if next.starts_with(&slice) {
281 return Some(format!("{origin}{next}"));
282 }
283 let rest = next.strip_prefix(&format!("https://{host}"))?;
284 rest.starts_with(&slice).then(|| format!("{origin}{rest}"))
285}
286
287type Members = BTreeMap<String, BTreeSet<SubjectKeys>>;
289
290fn catalogue(run: &mut Run, host: &str, origin: &str, doc: &KeyDocument) -> Result<(Members, Option<Cut>), Stop> {
295 let mut keys = Keys::new();
296 keys.insert_document(doc.clone());
297 let mut out: BTreeMap<String, BTreeSet<SubjectKeys>> = BTreeMap::new();
298 let mut url = format!("{origin}/slice/{host}/catalog/subject/source?domain=*&measure=*&rank=*®ion=*&thing=*");
299 let source_ns = format!("{host}/catalog/subject");
301 let mut pages = 0usize;
304 loop {
305 let (status, body) = match run.get(&url) {
306 Ok(x) => x,
307 Err(Stop::Bytes) => return Ok((out, Some(Cut::Bytes))),
308 Err(Stop::Unreachable(detail)) => {
309 if pages == 0 {
310 return Err(Stop::Unreachable(detail));
311 }
312 let cut = if run.left().is_none() { Cut::Time } else { Cut::Unreached };
313 return Ok((out, Some(cut)));
314 }
315 };
316 let page = if status == 200 { json::parse(&body).ok() } else { None };
317 let Some(page) = page else {
318 if pages == 0 {
319 return Err(Stop::Unreachable(format!("{url}: status {status}")));
320 }
321 return Ok((out, Some(Cut::Unreached)));
322 };
323 pages += 1;
324 if let Some(Value::Array(members)) = page.get("members") {
325 for m in members {
326 let Some(receipt) = m.get("receipt") else { continue };
327 let r = datumesh_core::verify(&receipt.to_jcs(), &keys, None, None);
328 if r.error().is_some() {
329 continue;
330 }
331 let Some(cell) = receipt.get("cell") else { continue };
332 let is_source = cell.get("fn").and_then(Value::as_str) == Some("source")
334 && cell.get("ns").and_then(Value::as_str) == Some(source_ns.as_str());
335 if !is_source {
336 continue;
337 }
338 let arg = |k: &str| -> Option<String> {
339 cell.get("args")?.get(k)?.get("value")?.as_str().map(str::to_string)
340 };
341 let (Some(d), Some(t), Some(me), Some(rg)) =
342 (arg("domain"), arg("thing"), arg("measure"), arg("region"))
343 else {
344 continue;
345 };
346 if cell.get("args").and_then(|a| a.get("rank")).is_none() {
347 continue;
348 }
349 let value = receipt.get("value");
350 let name = value.and_then(|v| v.as_str().or_else(|| v.get("value").and_then(Value::as_str)));
351 let Some(name) = name else { continue };
352 let under = name.starts_with(&format!("{host}/"));
353 if under && lexical::check_function_name(name, "name").is_ok() {
354 out.entry(name.to_string()).or_default().insert(SubjectKeys::new(&d, &t, &me, &rg));
355 }
356 }
357 }
358 match page.get("next") {
359 None | Some(Value::Null) => break,
360 Some(Value::String(next)) => match next_page(host, origin, next) {
361 Some(u) => url = u,
362 None => return Ok((out, Some(Cut::Unreached))),
363 },
364 Some(_) => return Ok((out, Some(Cut::Unreached))),
365 }
366 }
367 Ok((out, None))
368}
369
370enum NameStep {
372 Got(FetchedName),
374 Refused,
376 NotReached,
378}
379
380fn name_step(run: &mut Run, origin: &str, name: &str, subjects: Vec<SubjectKeys>) -> Result<NameStep, Stop> {
382 let base = format!("{origin}/");
383 let (status, d) = run.get(&format!("{base}describe/{name}"))?;
384 if status == 404 {
385 return Ok(NameStep::Refused);
386 }
387 if status != 200 {
388 return Ok(NameStep::NotReached);
389 }
390 let fn_hash = json::parse(&d)
391 .ok()
392 .and_then(|v| v.get("fn_hash").and_then(Value::as_str).map(str::to_string))
393 .filter(|h| lexical::check_hex(h, 64, "fn_hash").is_ok());
394 let Some(fn_hash) = fn_hash else { return Ok(NameStep::Refused) };
395 let (status, bytes) = run.get(&format!("{base}descriptor/{fn_hash}"))?;
396 if status != 200 {
397 return Ok(NameStep::NotReached);
398 }
399 if datumesh_core::function_hash(&bytes).ok().as_deref() != Some(fn_hash.as_str()) {
400 return Ok(NameStep::Refused);
401 }
402 let (status, f) = run.get(&format!("{base}fn/{name}?format=json"))?;
403 let page = if status == 200 { json::parse(&f).ok() } else { None };
404 let Some(v) = page else { return Ok(NameStep::NotReached) };
405 let label = v.get("label").and_then(Value::as_str).unwrap_or_default().to_string();
406 let description = v.get("description").and_then(Value::as_str).unwrap_or_default().to_string();
407 if description.is_empty() {
408 return Ok(NameStep::NotReached);
409 }
410 Ok(NameStep::Got(FetchedName { name: name.to_string(), fn_hash, subjects, descriptor: bytes, label, description }))
411}
412
413fn first_cut(cut: &mut Option<Cut>, c: Cut) {
415 if cut.is_none() {
416 *cut = Some(c);
417 }
418}
419
420pub fn fetch(host: &str, origin: &str, limits: &Limits, now: &str) -> Fetch {
423 let mut run = Run::new(limits);
424 let unreachable = |s: Stop| match s {
425 Stop::Unreachable(detail) => Fetch::Unreachable { detail },
426 Stop::Bytes => Fetch::Unreachable { detail: "the byte limit, before the key document".into() },
427 };
428 let (status, body) = match run.get(&format!("{origin}/.well-known/datumesh.json")) {
430 Ok(x) => x,
431 Err(s) => return unreachable(s),
432 };
433 let doc = match datumesh_core::key_document_from_response(host, status, Some(&body)) {
434 Ok(d) if status == 200 => d,
435 Ok(_) => return Fetch::KeyDocFailed { detail: format!("status {status}") },
436 Err(e) => return Fetch::KeyDocFailed { detail: e.to_string() },
437 };
438 let Some(key_id) = key_valid_at(&doc, now) else {
439 return Fetch::KeyDocFailed { detail: format!("no key of {host} is valid at {now}") };
440 };
441 let proto = json::parse(&body).ok().and_then(|v| v.get("proto").and_then(Value::as_str).map(str::to_string));
442 let (status, mbody) = match run.get(&format!("{origin}/.well-known/datumesh-mesh.json")) {
444 Ok(x) => x,
445 Err(s) => return unreachable(s),
446 };
447 if status != 200 {
448 return Fetch::MeshDocFailed { detail: format!("status {status}") };
449 }
450 let Ok(m) = json::parse(&mbody) else { return Fetch::MeshDocFailed { detail: "not JSON".into() } };
451 if m.get("host").and_then(Value::as_str) != Some(host) || m.get("proto").and_then(Value::as_str) != proto.as_deref()
452 {
453 return Fetch::MeshDocFailed { detail: "disagrees with the key document on host or proto".into() };
454 }
455 let (subjects, mut cut) = match catalogue(&mut run, host, origin, &doc) {
457 Ok(x) => x,
458 Err(s) => return unreachable(s),
459 };
460 let mut all: Vec<(String, Vec<SubjectKeys>)> =
461 subjects.into_iter().map(|(n, s)| (n, s.into_iter().collect())).collect();
462 if all.len() > limits.names {
463 all.truncate(limits.names);
464 first_cut(&mut cut, Cut::Names);
465 }
466 let mut names = Vec::new();
468 let mut refused = Vec::new();
469 for (name, subjects) in all {
470 if run.left().is_none() {
471 first_cut(&mut cut, Cut::Time);
472 break;
473 }
474 match name_step(&mut run, origin, &name, subjects) {
475 Ok(NameStep::Got(n)) => names.push(n),
476 Ok(NameStep::Refused) => refused.push(name),
477 Ok(NameStep::NotReached) => first_cut(&mut cut, Cut::Unreached),
478 Err(Stop::Bytes) => {
479 first_cut(&mut cut, Cut::Bytes);
480 break;
481 }
482 Err(Stop::Unreachable(_)) => {
483 if run.left().is_none() {
484 first_cut(&mut cut, Cut::Time);
485 break;
486 }
487 first_cut(&mut cut, Cut::Unreached);
488 }
489 }
490 }
491 Fetch::Fetched { key_id, names, refused, cut }
492}
493
494const MAX_CREATED_SUBJECTS: usize = 64;
497
498pub fn apply<S: Store + ?Sized>(store: &S, host: &str, fetch: &Fetch, now: &str) -> Result<Applied, ListingError> {
517 let se = |e: &dyn std::fmt::Display| ListingError { detail: e.to_string() };
518 let mut applied = Applied {
519 outcome: Outcome::Ok,
520 cut: None,
521 added: Vec::new(),
522 changed: Vec::new(),
523 dropped: Vec::new(),
524 listed: 0,
525 writes: 0,
526 };
527 let held: Vec<Listing> = store.listings_of(host).map_err(|e| se(&e))?;
528 let existing: Vec<String> = held.iter().map(|l| l.name.clone()).collect();
529 let mut drop_all = false;
530 let mut drop_set: BTreeSet<String> = BTreeSet::new();
531 match fetch {
532 Fetch::Fetched { key_id, names, refused, cut } => {
533 let mut verified = BTreeSet::new();
534 let offered: BTreeSet<&str> = names.iter().map(|n| n.name.as_str()).collect();
535 let mut refuse: BTreeSet<String> = refused.iter().cloned().collect();
536 let stored: BTreeMap<&str, &Listing> = held.iter().map(|l| (l.name.as_str(), l)).collect();
537 let bound = crate::catalog_build::bound_subjects(store).map_err(|e| se(&e))?;
541 let staying =
542 |l: &Listing| cut.is_some() && !offered.contains(l.name.as_str()) && !refused.contains(&l.name);
543 let mut created: BTreeSet<SubjectKeys> = held
544 .iter()
545 .filter(|l| staying(l))
546 .flat_map(|l| l.subjects.iter().cloned())
547 .filter(|s| !bound.contains(s))
548 .collect();
549 let mut cap_cut = false;
550 let mut ordered: Vec<&FetchedName> = names.iter().collect();
551 ordered.sort_by(|a, b| a.name.cmp(&b.name));
552 for n in ordered {
553 let under = n.name.starts_with(&format!("{host}/"));
554 let ok =
555 under && datumesh_core::function_hash(&n.descriptor).ok().as_deref() == Some(n.fn_hash.as_str());
556 if !ok {
557 refuse.insert(n.name.clone());
558 continue;
559 }
560 let mut subjects = n.subjects.clone();
561 if cut.is_some() {
562 if let Some(s) = stored.get(n.name.as_str()) {
564 subjects.extend(s.subjects.iter().cloned());
565 }
566 }
567 subjects.sort();
568 subjects.dedup();
569 let new: Vec<SubjectKeys> =
570 subjects.iter().filter(|s| !bound.contains(*s) && !created.contains(*s)).cloned().collect();
571 if created.len() + new.len() > MAX_CREATED_SUBJECTS {
572 cap_cut = true;
573 continue;
574 }
575 let l = Listing {
576 host: host.to_string(),
577 name: n.name.clone(),
578 fn_hash: n.fn_hash.clone(),
579 subjects,
580 descriptor: n.descriptor.clone(),
581 key_id: key_id.clone(),
582 label: n.label.clone(),
583 description: n.description.clone(),
584 fetched_at: now.to_string(),
585 listed_at: now.to_string(),
586 };
587 match store.put_listing(&l) {
588 Ok(ListingWrite::Unchanged) => {}
589 Ok(ListingWrite::Inserted) => {
590 applied.added.push(n.name.clone());
591 applied.writes += 1;
592 }
593 Ok(ListingWrite::Changed) => {
594 applied.changed.push(n.name.clone());
595 applied.writes += 1;
596 }
597 Err(datumesh_store::Error::Invalid(_)) => {
600 refuse.insert(n.name.clone());
601 continue;
602 }
603 Err(e) => return Err(se(&e)),
604 }
605 if store.set_listing_unreached(&n.name, None).map_err(|e| se(&e))? {
607 applied.writes += 1;
608 }
609 created.extend(new);
610 verified.insert(n.name.clone());
611 }
612 let cut = cut.or(cap_cut.then_some(Cut::Names));
613 match cut {
614 None => drop_set.extend(existing.iter().filter(|e| !verified.contains(*e)).cloned()),
615 Some(c) => {
616 drop_set.extend(existing.iter().filter(|e| refuse.contains(*e)).cloned());
617 for name in existing.iter().filter(|e| !offered.contains(e.as_str()) && !refuse.contains(*e)) {
620 let since = match store.listing_unreached(name).map_err(|e| se(&e))? {
621 Some(since) => since,
622 None => {
623 store.set_listing_unreached(name, Some(now)).map_err(|e| se(&e))?;
624 applied.writes += 1;
625 now.to_string()
626 }
627 };
628 let due = crate::keynames::add_seconds(&since, UNREACHABLE_DROP_AFTER.as_secs());
629 if due.is_some_and(|d| d.as_str() <= now) {
630 drop_set.insert(name.clone());
631 }
632 }
633 applied.cut = Some(c);
634 applied.outcome = Outcome::Cut;
635 }
636 }
637 let day = &now[..10];
638 let row = ListedHost { host: host.to_string(), last_seen: Some(day.to_string()), unreachable_since: None };
639 if store.put_listed_host(&row).map_err(|e| se(&e))? {
640 applied.writes += 1;
641 }
642 }
643 Fetch::KeyDocFailed { .. } => {
644 applied.outcome = Outcome::KeyDocFailed;
645 drop_all = true;
646 }
647 Fetch::MeshDocFailed { .. } => {
648 applied.outcome = Outcome::MeshDocFailed;
649 drop_all = true;
650 }
651 Fetch::Unreachable { .. } => {
652 applied.outcome = Outcome::Unreachable;
653 let row = store.listed_host(host).map_err(|e| se(&e))?;
654 match row {
655 None => {
656 let r = ListedHost {
657 host: host.to_string(),
658 last_seen: None,
659 unreachable_since: Some(now.to_string()),
660 };
661 store.put_listed_host(&r).map_err(|e| se(&e))?;
662 applied.writes += 1;
663 }
664 Some(r) => match r.unreachable_since.as_deref() {
665 None => {
666 let r2 = ListedHost { unreachable_since: Some(now.to_string()), ..r };
667 store.put_listed_host(&r2).map_err(|e| se(&e))?;
668 applied.writes += 1;
669 }
670 Some(since) => {
671 let due = crate::keynames::add_seconds(since, UNREACHABLE_DROP_AFTER.as_secs());
672 if due.is_some_and(|d| d.as_str() <= now) {
673 drop_all = true;
674 }
675 }
676 },
677 }
678 }
679 }
680 if drop_all {
681 drop_set.extend(existing.iter().cloned());
682 }
683 for name in &drop_set {
684 if store.delete_listing(name).map_err(|e| se(&e))? {
685 applied.dropped.push(name.clone());
686 applied.writes += 1;
687 }
688 }
689 applied.listed = store.listings_of(host).map_err(|e| se(&e))?.len();
690 Ok(applied)
691}
692
693pub fn run_host<S: Store + ?Sized>(
695 store: &S,
696 host: &str,
697 origin: &str,
698 limits: &Limits,
699 now: &str,
700) -> Result<Applied, ListingError> {
701 let f = fetch(host, origin, limits, now);
702 apply(store, host, &f, now)
703}
704
705fn active(inner: &crate::mesh::Inner) -> bool {
711 !inner.config.listed_meshes.is_empty()
712}
713
714fn under_listed(inner: &crate::mesh::Inner, word: &str) -> bool {
717 word.split_once('/').is_some_and(|(host, _)| inner.config.listed_meshes.iter().any(|h| h == host))
718}
719
720pub(crate) fn lookup(inner: &crate::mesh::Inner, name: &str) -> Result<Option<Listing>, ListingError> {
722 inner.listing_lookups.fetch_add(1, Ordering::Relaxed);
723 inner.store.listing(name).map_err(|e| ListingError { detail: e.to_string() })
724}
725
726pub(crate) fn checked(inner: &crate::mesh::Inner, name: &str) -> Result<Option<Listing>, ListingError> {
729 if !active(inner) {
730 return Ok(None);
731 }
732 lookup(inner, name)
733}
734
735pub(crate) fn listed(inner: &crate::mesh::Inner, name: &str) -> Option<Listing> {
738 checked(inner, name).ok().flatten()
739}
740
741fn resolve_alias(text: &str, alias: &dyn Fn(&str) -> Option<String>) -> String {
743 let Some(rest) = text.strip_prefix('@') else { return text.to_string() };
744 let end = rest.find(['(', '/', '?', ' ']).unwrap_or(rest.len());
745 match alias(&rest[..end]) {
746 Some(target) => format!("{target}{}", &rest[end..]),
747 None => text.to_string(),
748 }
749}
750
751pub(crate) fn checked_in(
755 inner: &crate::mesh::Inner,
756 bindings: &dyn crate::call::Bindings,
757 alias: &dyn Fn(&str) -> Option<String>,
758 text: &str,
759) -> Result<Option<Listing>, ListingError> {
760 if !active(inner) {
761 return Ok(None);
762 }
763 let text = resolve_alias(text.strip_prefix("cell://").unwrap_or(text), alias);
764 let mut ends: Vec<usize> =
765 text.char_indices().filter(|(_, c)| matches!(c, '/' | '(' | '?' | ' ')).map(|(i, _)| i).collect();
766 ends.push(text.len());
767 for e in ends {
768 if under_listed(inner, &text[..e]) {
769 if let Some(l) = bindings.listing(&text[..e])? {
770 return Ok(Some(l));
771 }
772 }
773 }
774 Ok(None)
775}
776
777pub(crate) fn checked_words(inner: &crate::mesh::Inner, text: &str) -> Result<Option<Listing>, ListingError> {
780 if !active(inner) {
781 return Ok(None);
782 }
783 let words: BTreeSet<&str> =
784 text.split(|c: char| !(c.is_alphanumeric() || "._/-".contains(c))).filter(|w| under_listed(inner, w)).collect();
785 for w in words {
786 if let Some(l) = lookup(inner, w)? {
787 return Ok(Some(l));
788 }
789 }
790 Ok(None)
791}
792
793pub(crate) fn checked_formula(inner: &crate::mesh::Inner, body: &[u8]) -> Result<Option<Listing>, ListingError> {
795 if !active(inner) {
796 return Ok(None);
797 }
798 let formula = json::parse(body).ok().and_then(|v| v.get("formula").and_then(Value::as_str).map(str::to_string));
799 match formula {
800 Some(f) => checked_words(inner, &f),
801 None => Ok(None),
802 }
803}
804
805pub(crate) fn unavailable() -> Reply {
807 crate::envelope::error_reply(datumesh_core::ErrorCode::EvalUnavailable)
808}
809
810pub(crate) fn refusal(l: &Listing) -> Reply {
813 let body = Value::Object(vec![
814 ("outcome".into(), Value::String("not_covered".into())),
815 ("error".into(), Value::String("E_LISTED_ELSEWHERE".into())),
816 ("mesh".into(), Value::String(mesh_of(&l.host))),
817 ("name".into(), Value::String(l.name.clone())),
818 ]);
819 Reply::json(404, body.to_jcs(), Cache::NoStore)
820}
821
822fn mesh_of(host: &str) -> String {
824 format!("https://{host}")
825}
826
827fn first_note(inner: &crate::mesh::Inner, name: &str) -> Option<String> {
831 let built = crate::catalog_view::built(inner)?;
832 let subject = &built.places.get(name)?.subject;
833 let first = built.firsts.get(subject)?;
834 if first == name {
835 return None;
836 }
837 let l = listed(inner, first)?;
838 let last_seen = inner.store.listed_host(&l.host).ok().flatten().and_then(|r| r.last_seen).unwrap_or_default();
839 Some(format!(
840 "<p>The source's own function is listed here and ranks first in its subject (last seen {}): \
841 <a href=\"{}\"><code>{}</code></a>.</p>\n",
842 escape(&last_seen),
843 escape(&crate::fnpage::page_url(inner, &l.name)),
844 escape(&l.name)
845 ))
846}
847
848pub(crate) fn relay_note(inner: &crate::mesh::Inner, d: &Value) -> Option<String> {
851 first_note(inner, d.get("name").or_else(|| d.get("fn"))?.as_str()?)
852}
853
854pub(crate) fn takeover_note(inner: &crate::mesh::Inner, relays: &[String]) -> String {
857 let mut notes: Vec<String> = Vec::new();
858 for r in relays {
859 if let Some(n) = first_note(inner, r) {
860 if !notes.contains(&n) {
861 notes.push(n);
862 }
863 }
864 }
865 notes.concat()
866}
867
868fn listed_members(store: &dyn Store, l: &Listing) -> Vec<(String, Value)> {
870 let last_seen = store.listed_host(&l.host).ok().flatten().and_then(|r| r.last_seen).unwrap_or_default();
871 let descriptor = json::parse(&l.descriptor).unwrap_or(Value::Null);
872 let s = |v: &str| Value::String(v.to_string());
873 vec![
874 ("outcome".into(), s("ok")),
875 ("kind".into(), s("function")),
876 ("fn".into(), s(&l.name)),
877 ("listed".into(), Value::Bool(true)),
878 ("mesh".into(), s(&mesh_of(&l.host))),
879 ("publisher".into(), s(&l.host)),
880 ("address".into(), s(&format!("{}/fn/{}", mesh_of(&l.host), l.name))),
881 ("last_seen".into(), s(&last_seen)),
882 ("fn_hash".into(), s(&l.fn_hash)),
883 ("label".into(), s(&l.label)),
884 ("description".into(), s(&l.description)),
885 ("descriptor".into(), descriptor),
886 ]
887}
888
889pub(crate) fn describe_reply(store: &dyn Store, l: &Listing) -> Reply {
891 Reply::json(200, Value::Object(listed_members(store, l)).to_jcs(), Cache::Public(300))
892}
893
894fn escape(s: &str) -> String {
895 s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """)
896}
897
898pub(crate) fn fn_reply(store: &dyn Store, l: &Listing, json_form: bool) -> Reply {
901 if json_form {
902 return describe_reply(store, l);
903 }
904 let members = listed_members(store, l);
905 let last_seen = members.iter().find(|(k, _)| k == "last_seen").and_then(|(_, v)| v.as_str()).unwrap_or_default();
906 let address = mesh_of(&l.host) + "/fn/" + &l.name;
907 let html = format!(
908 "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
909 <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>{name}</title></head>\
910 <body><h1>{name}</h1><p>{description}</p>\
911 <p>Listed from <a href=\"{address}\">{mesh}</a>, last seen {last_seen}. This mesh describes the function; \
912 it does not serve its values.</p></body></html>",
913 name = escape(&l.name),
914 description = escape(&l.description),
915 address = escape(&address),
916 mesh = escape(&mesh_of(&l.host)),
917 last_seen = escape(last_seen),
918 );
919 Reply {
920 status: 200,
921 body: html.into_bytes().into(),
922 content_type: "text/html; charset=utf-8",
923 cache: Cache::Public(300),
924 canonical: None,
925 retry_after: None,
926 }
927}