use std::collections::BTreeMap;
use std::sync::Arc;
use datumesh_core::json::Value;
use datumesh_core::lexical;
use datumesh_store::CatalogKind;
use crate::envelope::{self, Cache, Reply};
use crate::fnpage::{esc, page_url, relay_of};
use crate::mesh::Inner;
use datumesh_core::ErrorCode;
const RETRY_SECS: u64 = 5;
pub(crate) type Lists = BTreeMap<String, Vec<(String, String)>>;
fn s(v: &str) -> Value {
Value::String(v.to_string())
}
fn obj(members: Vec<(&str, Value)>) -> Value {
Value::Object(members.into_iter().map(|(k, v)| (k.to_string(), v)).collect())
}
const TAKEOVER_ENTRIES: usize = 100_000;
pub(crate) fn build(inner: &Inner) -> Lists {
let mut out: Lists = BTreeMap::new();
let Ok(entries) = inner.store.catalog_entries_all(TAKEOVER_ENTRIES) else { return out };
let now = inner.now();
for (_, name, _, _) in entries.iter().filter(|e| e.0 == CatalogKind::Function) {
let Ok(Some(b)) = inner.store.resolve_binding(name, &now) else { continue };
if let Some(r) = relay_of(inner, name, &b.fn_hash) {
out.entry(r.name).or_default().push((name.clone(), b.fn_hash));
}
}
for list in out.values_mut() {
list.sort();
list.dedup();
}
out
}
pub(crate) fn refresh(inner: &Inner) {
let lists = Arc::new(build(inner));
*inner.takeover.lock().unwrap_or_else(|p| p.into_inner()) = Some(lists);
}
fn relayed_from(inner: &Inner, domain: &str) -> Option<Vec<(String, String)>> {
let lists = inner.takeover.lock().unwrap_or_else(|p| p.into_inner()).clone()?;
Some(lists.get(domain).cloned().unwrap_or_default())
}
fn policy(domain: &str) -> Vec<String> {
vec![
format!(
"When {domain} publishes these functions under its own domain, its own name ranks first among the sources of the \
same subject in this mesh's catalogue."
),
format!("No permission is needed: {domain} proves control of its domain with a key document on its own domain."),
"Datumesh lists a source's mesh once it exists: a mesh is listed when it publishes its own catalogue with subject keys \
and Datumesh adds its host to the list."
.to_string(),
"The relay goes on as a mirror, labelled relayed. Its history stays as this mesh's signed statements.".to_string(),
]
}
fn stopping(domain: &str) -> Vec<String> {
vec![
format!(
"{domain} can ask for the relay to stop. A declaration it can put in its own key document for this is planned; \
this mesh does not read one yet."
),
format!("Until then, when {domain} asks, the feed is ended."),
]
}
pub(crate) fn data(inner: &Inner, domain: &str, found: &[(String, String)]) -> Option<Value> {
if found.is_empty() {
return None;
}
let host = &inner.config.host;
let hosting = if inner.config.listed_meshes.iter().any(|h| h.as_str() == domain) {
format!("{domain} is a listed mesh here ({host}): its functions are described from its own mesh, and POST /bundles does not admit it.")
} else if inner.config.publish_domains.allows(domain) {
format!("POST /bundles is open to {domain} on this mesh ({host}): a bundle signed by a key in its key document is accepted.")
} else {
format!(
"Hosting on this mesh ({host}) needs the operator of this mesh to allow {domain}: POST /bundles does not admit it yet."
)
};
let functions: Vec<Value> = found
.iter()
.map(|(n, h)| obj(vec![("name", s(n)), ("page", s(&page_url(inner, n))), ("fn_hash", s(h))]))
.collect();
let steps = vec![
s(&format!("Make a key, then serve its key document at https://{domain}/.well-known/datumesh.json (spec 9).")),
s(&format!("Publish the same functions under {domain}/..., on its own mesh or hosted on this mesh.")),
s(&hosting),
s(&format!("The full route, with each command, is at {PUBLISH_DOCS}.")),
];
let contact = inner.config.contact.as_deref().map_or(Value::Null, s);
Some(obj(vec![
("contact", contact),
("domain", s(domain)),
("host", s(host)),
("functions", Value::Array(functions)),
("policy", Value::Array(policy(domain).iter().map(|p| s(p)).collect())),
("steps", Value::Array(steps)),
("stopping", Value::Array(stopping(domain).iter().map(|p| s(p)).collect())),
]))
}
pub(crate) fn respond(inner: &Inner, domain: &str, json_form: bool) -> Reply {
if lexical::check_dns_name(domain, "$").is_err() {
return envelope::bad_request_reply(ErrorCode::CanonName);
}
let max_age = inner.config.ttl.latest_max_age.as_secs();
let Some(found) = relayed_from(inner, domain) else {
return envelope::not_yet_reply(RETRY_SECS, "The takeover list");
};
let Some(d) = data(inner, domain, &found) else {
if json_form {
return envelope::name_unbound_reply(max_age);
}
let body = format!(
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>not covered</title></head>\
<body><h1>not_covered</h1><p>This mesh relays no function from {}.</p></body></html>",
esc(domain)
);
return Reply {
status: 404,
body: body.into_bytes().into(),
content_type: "text/html; charset=utf-8",
cache: Cache::Public(60),
canonical: None,
retry_after: None,
};
};
let relays: Vec<String> = found.iter().map(|(n, _)| n.clone()).collect();
let note = crate::listing::takeover_note(inner, &relays);
if json_form {
return Reply::json(200, d.to_jcs(), Cache::Public(max_age));
}
Reply {
status: 200,
body: render(&d, ¬e).into_bytes().into(),
content_type: "text/html; charset=utf-8",
cache: Cache::Public(max_age),
canonical: None,
retry_after: None,
}
}
const PUBLISH_DOCS: &str = "https://datumesh.com/docs/publish";
const RULE_PAGE: &str = "/catalog/rule";
fn text<'a>(v: &'a Value, k: &str) -> &'a str {
v.get(k).and_then(Value::as_str).unwrap_or("")
}
fn strings<'a>(v: &'a Value, k: &str) -> Vec<&'a str> {
match v.get(k) {
Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).collect(),
_ => Vec::new(),
}
}
fn text_esc(t: &str) -> String {
t.replace('&', "&").replace('<', "<").replace('>', ">")
}
fn linked(t: &str, phrase: &str, href: &str) -> String {
match t.split_once(phrase) {
Some((before, after)) => {
format!("{}<a href=\"{}\">{}</a>{}", text_esc(before), esc(href), text_esc(phrase), text_esc(after))
}
None => text_esc(t),
}
}
pub(crate) fn render(d: &Value, listed_note: &str) -> String {
let (domain, host) = (text(d, "domain"), text(d, "host"));
let title = format!("{domain}'s values under its own name");
let mut h = String::new();
h.push_str("<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n");
h.push_str(&format!("<title>{}</title>\n", esc(&title)));
h.push_str("<style>body{font:16px/1.5 system-ui,sans-serif;margin:0;padding:16px;color:#1d1d1f;background:#fff;overflow-wrap:anywhere}main{max-width:52rem;margin:0 auto}code{font-family:ui-monospace,monospace;font-size:14px;overflow-wrap:anywhere}h1{font-size:1.5rem;margin:0.5rem 0}h2{font-size:1.1rem}pre{overflow-x:auto;max-width:100%;box-sizing:border-box}</style>\n</head>\n<body>\n<main>\n");
h.push_str(&format!("<h1>{}</h1>\n", esc(&title)));
h.push_str(&format!(
"<p>This mesh ({}) relays these values from {} unchanged, as a stand-in. {} remains their source.</p>\n",
text_esc(host),
text_esc(domain),
text_esc(domain)
));
h.push_str(listed_note);
h.push_str("<section id=\"functions\">\n<h2>Functions relayed from this domain</h2>\n<ul>\n");
if let Some(Value::Array(fs)) = d.get("functions") {
for f in fs {
h.push_str(&format!(
"<li><a href=\"{}\"><code>{}</code></a> (<code>{}</code>)</li>\n",
esc(text(f, "page")),
esc(text(f, "name")),
esc(text(f, "fn_hash"))
));
}
}
h.push_str("</ul>\n</section>\n");
h.push_str("<section id=\"first\">\n<h2>How the source's own name comes first</h2>\n<ul>\n");
for p in strings(d, "policy") {
h.push_str(&format!("<li>{}</li>\n", linked(p, "ranks first", RULE_PAGE)));
}
h.push_str("</ul>\n</section>\n");
h.push_str("<section id=\"stopping\">\n<h2>Stopping the relay</h2>\n<ul>\n");
for p in strings(d, "stopping") {
h.push_str(&format!("<li>{}</li>\n", text_esc(p)));
}
h.push_str("</ul>\n");
if let Some(c) = d.get("contact").and_then(Value::as_str) {
h.push_str(&format!("<p>Contact: <code>{}</code>.</p>\n", esc(c)));
}
h.push_str("</section>\n");
h.push_str("<section id=\"serving\">\n<h2>Serving your own mesh</h2>\n<ol>\n");
for st in strings(d, "steps") {
h.push_str(&format!("<li>{}</li>\n", linked(st, PUBLISH_DOCS, PUBLISH_DOCS)));
}
h.push_str("</ol>\n</section>\n</main>\n</body>\n</html>\n");
h
}