~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

A handle being typed is looked for by the host, in its own directory on a network of its own

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:host/search-actors
crates/group-host/src/actor_search.rsnew+151−0
@@ -0,0 +1,151 @@
//! Finding an account by what is typed of its handle, for the console's
//! handle fields (`fyi.opensocial.searchActors`), anyone may ask, as the
//! sign-in field does before anyone has.
//!
//! Where it looks is `ACTOR_SEARCH`. On the network everyone is on, a
//! typeahead service that knows all of it (typeahead.waow.tech), asked by
//! the host so that what is typed goes from one server, not each browser.
//! On a network of its own, whose directory is not plc.directory, the
//! handles its directory names: every DID's `alsoKnownAs` in the
//! directory's `/export`, read a page at a time and kept for a minute.
use crate::Host;
use crate::api::Params;
use crate::xrpc::XrpcError;
use axum::Json;
use axum::extract::{Query, State};
use serde_json::{Value, json};
use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
/// How long the directory's handles are kept before it is read again.
pub const KEPT_FOR: Duration = Duration::from_secs(60);
/// The most pages of the directory's export read at once, each as many
/// operations as it sends: a network of its own, not the whole one.
const PAGES_AT_MOST: usize = 50;
/// Each DID a directory names a handle for, and the handle.
type Named = Arc<Vec<(String, String)>>;
/// The handles a directory names, as last read, and when. Held while the
/// directory is read again, so callers at once share one read of it.
#[derive(Default)]
pub struct Handles(tokio::sync::Mutex<Option<(Instant, Named)>>);
/// The handle an operation of the directory's export names, if it is one
/// that names one: a tombstone, or an update naming none, names none.
fn handle_of(op: &Value) -> Option<String> {
let aka = op["alsoKnownAs"].as_array().into_iter().flatten();
let named = aka
.filter_map(Value::as_str)
.find_map(|a| a.strip_prefix("at://"));
named.map(str::to_ascii_lowercase)
}
impl Host {
/// Every DID the directory names a handle for, and the handle: from the
/// last read, if it is less than [`KEPT_FOR`] old. A read that never
/// reached the directory is not kept, so the next caller tries again.
async fn directory_handles(&self) -> Named {
let mut kept = self.handles.0.lock().await;
if let Some((_, handles)) = kept.as_ref().filter(|(at, _)| at.elapsed() < KEPT_FOR) {
return handles.clone();
}
let mut reached = false;
let mut last: BTreeMap<String, Option<String>> = BTreeMap::new();
let mut after = String::new();
for _ in 0..PAGES_AT_MOST {
let url = format!("{}/export", self.config.plc_url);
let asked = self
.http
.get(url)
.query(&[("count", "1000"), ("after", &after)]);
let Ok(res) = asked.send().await else {
break;
};
reached = true;
let text = res.text().await.unwrap_or_default();
let lines: Vec<Value> = text
.lines()
.filter_map(|l| serde_json::from_str(l).ok())
.collect();
let Some(end) = lines.last() else { break };
after = end["createdAt"].as_str().unwrap_or_default().to_string();
let live = lines.iter().filter(|e| e["nullified"] != true);
for entry in live {
let did = entry["did"].as_str().unwrap_or_default().to_string();
last.insert(did, handle_of(&entry["operation"]));
}
}
let handles: Vec<(String, String)> = last
.into_iter()
.filter_map(|(d, h)| Some((d, h?)))
.collect();
let handles = Arc::new(handles);
if reached {
*kept = Some((Instant::now(), handles.clone()));
}
handles
}
/// Who the directory names whose handle begins with `q`, then whose
/// handle holds it, shortest first: at most `limit`.
async fn in_directory(&self, q: &str, limit: usize) -> Vec<Value> {
let handles = self.directory_handles().await;
let mut found: Vec<(bool, &String, &String)> = handles
.iter()
.filter(|(_, h)| h.contains(q))
.map(|(d, h)| (!h.starts_with(q), h, d))
.collect();
found.sort_by_key(|(later, h, _)| (*later, h.len(), *h));
let found = found.into_iter().take(limit);
found
.map(|(_, h, d)| json!({"did": d, "handle": h}))
.collect()
}
/// Who the typeahead service at `url` says matches `q`: none, when it
/// cannot say.
async fn asking_service(&self, url: &str, q: &str, limit: usize) -> Vec<Value> {
let limit = limit.to_string();
let asked = self.http.get(url).query(&[("q", q), ("limit", &limit)]);
let said: Value = match asked.send().await {
Ok(res) => res.json().await.unwrap_or_default(),
Err(_) => Value::Null,
};
let actors = said["actors"].as_array().into_iter().flatten();
let shown = actors.filter(|a| {
a["did"].is_string() && a["handle"].as_str().is_some_and(|h| h != "handle.invalid")
});
let kept = |a: &Value| {
let mut out = json!({"did": a["did"], "handle": a["handle"]});
for key in ["displayName", "avatar"] {
if a[key].is_string() {
out[key] = a[key].clone();
}
}
out
};
shown.map(kept).collect()
}
}
pub async fn search_actors(
State(host): State<Arc<Host>>,
Query(p): Query<Params>,
) -> Result<Json<Value>, XrpcError> {
let q = p
.get("q")
.map_or("", |q| q.trim().trim_start_matches('@'))
.to_ascii_lowercase();
// Its lexicon has checked it is a number, from 1 to 25.
let limit = p.get("limit").and_then(|l| l.parse().ok()).unwrap_or(6);
let actors = match (q.chars().count() >= 2, host.config.actor_search.as_str()) {
(false, _) => Vec::new(),
(true, "plc") => host.in_directory(&q, limit).await,
(true, url) => host.asking_service(url, &q, limit).await,
};
Ok(Json(json!({ "actors": actors })))
}
crates/group-host/src/config.rs+16−0
@@ -44,8 +44,17 @@ pub struct Config {
/// `provisionGroup`, `PROVISIONING_CLIENTS`, comma-separated client
/// ids, `*` for any: none unless set.
pub provisioning_clients: Vec<String>,
/// Where a handle being typed is looked for, `ACTOR_SEARCH`: `plc`,
/// the handles in `PLC_URL`'s own export, or the URL of a service
/// answering `tech.waow.typeahead.searchActors`. The typeahead service
/// typeahead.waow.tech for plc.directory, which knows the whole
/// network; `plc` for any other directory, a network of its own.
pub actor_search: String,
}
/// The service that finds anyone on the network by what is typed.
pub const TYPEAHEAD: &str = "https://typeahead.waow.tech/xrpc/tech.waow.typeahead.searchActors";
impl Config {
/// The config `var` names, as `std::env::var` would read it; the
/// environment's own with [`Config::from_env`].
@@ -110,6 +119,12 @@ impl Config {
None => 50 * 1024 * 1024,
};
let provisioning_clients = list("PROVISIONING_CLIENTS");
let actor_search = match var("ACTOR_SEARCH") {
Some(s) if s == "plc" || reqwest::Url::parse(&s).is_ok() => s,
Some(s) => bail!("ACTOR_SEARCH is neither plc nor a URL: {s}"),
None if plc_url == "https://plc.directory" => TYPEAHEAD.into(),
None => "plc".into(),
};
let console_url = var("CONSOLE_URL").unwrap_or_else(|| public_url.clone());
let console_url = console_url.trim_end_matches('/').to_string();
if reqwest::Url::parse(&console_url).is_err() {
@@ -129,6 +144,7 @@ impl Config {
blob_upload_limit,
console_url,
provisioning_clients,
actor_search,
})
}
crates/group-host/src/lexicons.rs+1−0
@@ -109,6 +109,7 @@ pub const FILES: &[&str] = &[
lexicon!("fyi/opensocial/revokeGroupToken"),
lexicon!("fyi/opensocial/role"),
lexicon!("fyi/opensocial/rule"),
lexicon!("fyi/opensocial/searchActors"),
lexicon!("fyi/opensocial/site"),
lexicon!("fyi/opensocial/space"),
lexicon!("fyi/opensocial/startAccountMove"),
crates/group-host/src/lib.rs+8−0
@@ -4,6 +4,7 @@
//! says how it is built and what is still to come.
pub mod account_move;
pub mod actor_search;
pub mod actors;
pub mod api;
pub mod app_passwords;
@@ -88,6 +89,8 @@ pub struct Host {
index_wake: tokio::sync::Notify,
/// The OAuth clients' metadata, as read.
pub(crate) clients: oauth_clients::Clients,
/// The handles the directory names, as last read for a search.
pub(crate) handles: actor_search::Handles,
}
impl Host {
@@ -114,6 +117,7 @@ impl Host {
indexing: Default::default(),
index_wake: Default::default(),
clients: Default::default(),
handles: Default::default(),
})
}
}
@@ -144,6 +148,10 @@ pub fn router(host: Arc<Host>) -> Router {
get(api::describe_server),
)
.route("/xrpc/fyi.opensocial.checkAddress", get(api::check_address))
.route(
"/xrpc/fyi.opensocial.searchActors",
get(actor_search::search_actors),
)
.route("/xrpc/com.atproto.repo.getRecord", get(api::get_record))
.route("/xrpc/com.atproto.repo.listRecords", get(api::list_records))
.route("/xrpc/com.atproto.sync.getRepo", get(api::get_repo))
crates/group-host/tests/common/mod.rs+27−1
@@ -10,7 +10,7 @@ pub mod oauth;
pub mod spaces;
use atproto::plc::Signed;
use axum::extract::{Path, State};
use axum::extract::{Path, Query, State};
use axum::http::StatusCode;
use axum::routing::get;
use axum::{Json, Router};
@@ -29,6 +29,10 @@ use std::sync::{Arc, Mutex};
#[derive(Default)]
pub struct Plc {
pub ops: Mutex<HashMap<String, Vec<Signed>>>,
/// Every operation taken, in order, as `/export` lists them.
pub exported: Mutex<Vec<Value>>,
/// How many times `/export` was asked.
pub exports: std::sync::atomic::AtomicUsize,
pub refuse: AtomicBool,
pub refuse_ends: AtomicBool,
pub slow: AtomicBool,
@@ -80,10 +84,31 @@ async fn publish(
if on(&plc.refuse) || (ending && on(&plc.refuse_ends)) || !signed || !keys_taken {
return StatusCode::BAD_REQUEST;
}
let mut exported = plc.exported.lock().unwrap();
let at = exported.len();
exported.push(json!({
"did": did,
"operation": op.to_json(),
"cid": op.cid().to_string(),
"nullified": false,
"createdAt": format!("2026-01-01T{:02}:{:02}:{:02}.000Z", at / 3600, at / 60 % 60, at % 60),
}));
log.push(op);
StatusCode::OK
}
/// The operations taken after `after`, as JSON lines, two at most: a page
/// shorter than any a reader asks for, so it reads on to an empty one.
async fn export(State(plc): State<Arc<Plc>>, Query(q): Query<HashMap<String, String>>) -> String {
plc.exports.fetch_add(1, Ordering::SeqCst);
let after = q.get("after").cloned().unwrap_or_default();
let exported = plc.exported.lock().unwrap();
let later = exported
.iter()
.filter(|e| e["createdAt"].as_str().unwrap() > after.as_str());
later.take(2).map(|e| format!("{e}\n")).collect()
}
async fn document(
State(plc): State<Arc<Plc>>,
Path(did): Path<String>,
@@ -148,6 +173,7 @@ pub async fn start_plc(refuse: bool) -> (Arc<Plc>, String) {
let router = Router::new()
.route("/{did}", get(document).post(publish))
.route("/{did}/log/last", get(last))
.route("/export", get(export))
.with_state(plc.clone());
(plc, serve(router).await)
}
crates/group-host/tests/actor_search.rsnew+133−0
@@ -0,0 +1,133 @@
//! Finding an account by what is typed of its handle: in the directory's
//! own handles on a network of its own, or from a typeahead service.
mod common;
use axum::Router;
use axum::extract::Query;
use axum::routing::get;
use common::groups::*;
use common::{Running, serve, start};
use serde_json::{Value as Json, json};
use std::collections::HashMap;
async fn search(h: &Running, query: &str) -> Vec<Json> {
let (status, said) = h.get("fyi.opensocial.searchActors", query).await;
assert_eq!(status, 200, "{said}");
said["actors"].as_array().unwrap().clone()
}
fn handles(found: &[Json]) -> Vec<&str> {
found
.iter()
.map(|a| a["handle"].as_str().unwrap())
.collect()
}
#[tokio::test]
async fn on_a_network_of_its_own_the_directory_is_searched() {
// The test directory is not plc.directory, so the host reads its export.
let h = start(&[], false).await;
let [alice, ..] = people(&h).await;
for (handle, name) in [
("riders", "Riders"),
("ride-share", "Share"),
("bakers", "Bakers"),
] {
let body = json!({"handle": format!("{handle}.groups.test"), "displayName": name});
start_group(&h, &alice, body).await;
}
// A group ended is no one to find: its DID's last operation is a tombstone.
let gone = start_group(
&h,
&alice,
json!({"handle": "riders-gone.groups.test", "displayName": "Gone"}),
)
.await;
let lxm = format!("{NS}.deleteGroup");
let (status, said) = post(&h, &lxm, &json!({"group": gone}), &[auth(&h, &alice, &lxm)]).await;
assert_eq!(
(status, said["tombstoned"].clone()),
(200, json!(true)),
"{said}"
);
let found = search(&h, "q=rid").await;
assert_eq!(
handles(&found),
["riders.groups.test", "ride-share.groups.test"]
);
assert!(found[0]["did"].as_str().unwrap().starts_with("did:plc:"));
assert!(found[0].get("displayName").is_none());
// Beginning with it first, then holding it; typed with an @, in capitals.
assert_eq!(
handles(&search(&h, "q=%40AKERS").await),
["bakers.groups.test"]
);
assert_eq!(handles(&search(&h, "q=groups&limit=1").await).len(), 1);
assert!(search(&h, "q=r").await.is_empty());
assert!(search(&h, "q=nobody").await.is_empty());
// Kept a minute: a group started since is not found until then.
start_group(
&h,
&alice,
json!({"handle": "rivers.groups.test", "displayName": "Rivers"}),
)
.await;
assert!(search(&h, "q=rivers").await.is_empty());
}
#[tokio::test]
async fn a_directory_that_cannot_be_read_finds_no_one() {
let away = [("PLC_URL", "http://127.0.0.1:9"), ("ACTOR_SEARCH", "plc")];
let h = start(&away, false).await;
assert!(search(&h, "q=riders").await.is_empty());
}
#[tokio::test]
async fn searches_at_once_share_one_read_of_the_directory() {
let h = start(&[], false).await;
let [alice, ..] = people(&h).await;
let body = json!({"handle": "riders.groups.test", "displayName": "Riders"});
start_group(&h, &alice, body).await;
let asked = (0..8).map(|_| search(&h, "q=riders"));
for found in futures::future::join_all(asked).await {
assert_eq!(handles(&found), ["riders.groups.test"]);
}
// One read: a page of two operations at a time, then the empty one.
let operations = h.plc.exported.lock().unwrap().len();
let read = h.plc.exports.load(std::sync::atomic::Ordering::SeqCst);
assert_eq!(read, operations.div_ceil(2) + 1);
search(&h, "q=riders").await;
assert_eq!(
h.plc.exports.load(std::sync::atomic::Ordering::SeqCst),
read
);
}
#[tokio::test]
async fn on_the_whole_network_the_typeahead_service_is_asked() {
let service = Router::new().route(
"/search",
get(|Query(q): Query<HashMap<String, String>>| async move {
axum::Json(json!({"actors": [
{"did": "did:plc:alice", "handle": "alice.test", "displayName": "Alice", "avatar": "https://cdn.test/a.jpg"},
{"did": "did:plc:alfie", "handle": format!("{}.test", q["q"])},
{"did": "did:plc:broken", "handle": "handle.invalid"},
{"handle": "nodid.test"},
{"did": "did:plc:limit", "handle": format!("limit-{}.test", q["limit"])},
]}))
}),
);
let url = format!("{}/search", serve(service).await);
let h = start(&[("ACTOR_SEARCH", &url)], false).await;
let found = search(&h, "q=al&limit=3").await;
assert_eq!(handles(&found), ["alice.test", "al.test", "limit-3.test"]);
assert_eq!(found[0]["displayName"], "Alice");
assert_eq!(found[0]["avatar"], "https://cdn.test/a.jpg");
assert!(found[1].get("avatar").is_none());
let away = start(&[("ACTOR_SEARCH", "http://127.0.0.1:9/search")], false).await;
assert!(search(&away, "q=alice").await.is_empty());
}
crates/group-host/tests/config.rs+19−0
@@ -106,3 +106,22 @@ fn refuses_what_does_not_read() {
"CONSOLE_URL is no URL: console"
);
}
#[test]
fn a_handle_is_looked_for_where_the_directory_is() {
let typeahead = "https://typeahead.waow.tech/xrpc/tech.waow.typeahead.searchActors";
assert_eq!(config(&[]).unwrap().actor_search, typeahead);
let own = config(&[("PLC_URL", "http://plc.next.test")]).unwrap();
assert_eq!(own.actor_search, "plc");
let told = [
("PLC_URL", "http://plc.next.test"),
("ACTOR_SEARCH", "https://find.test/x"),
];
assert_eq!(config(&told).unwrap().actor_search, "https://find.test/x");
assert_eq!(
config(&[("ACTOR_SEARCH", "plc")]).unwrap().actor_search,
"plc"
);
let refused = config(&[("ACTOR_SEARCH", "somewhere")]).unwrap_err();
assert!(refused.to_string().contains("ACTOR_SEARCH"), "{refused}");
}
docs/design/signing-in.md+12−7
@@ -51,13 +51,18 @@ authorization server, pushes the request with PKCE and a fresh DPoP key,
and sends the browser there. On return it exchanges the code, checks the
token names the DID that started, and revokes the access token at once.
As they type, the field suggests the accounts whose handle or name
matches, with each one's picture, name and handle; picking one signs in
as it at once. The suggestions come from typeahead.waow.tech, a service
outside this host that knows the accounts of the whole network, so the
browser sends it what is typed, from two letters on. It is the one
server besides this host that the console's scripts may reach, as its
content security policy says. When it cannot answer, the field is a
As they type, the field suggests the accounts whose handle matches,
with each one's picture, name and handle where they are known; picking
one signs in as it at once. The browser asks the host
(`fyi.opensocial.searchActors`), from two letters on, and the host asks
where `ACTOR_SEARCH` says. On the network everyone is on, that is
typeahead.waow.tech, a service that knows the accounts of the whole
network, so what is typed reaches it from the host and from no browser.
On a network of its own, whose PLC directory is not plc.directory, the
host reads the handles that directory names from its export, kept a
minute, and suggests those by handle alone: a directory has no names or
pictures. The console's scripts reach no server but the host, as its
content security policy says. When the host cannot say, the field is a
plain one.
Every other field for someone's handle suggests accounts the same way,
docs/reference/api.md+1−0
@@ -104,6 +104,7 @@ same writes ([membership](../design/membership.md#invites)).
| `GET fyi.opensocial.getViewer` | who is asking, by the console's cookie or service auth |
| `GET fyi.opensocial.getActor` | a person's DID and handle, to someone signed in: themselves, or anyone the host shows (a member of a group here, or someone asking to join one); to themselves also whether they may start a group |
| `GET fyi.opensocial.getActorGroups` | the groups here a person is in, as far as the caller shares them |
| `GET fyi.opensocial.searchActors` | accounts whose handle matches what is typed, from where `ACTOR_SEARCH` says; anyone may ask |
| `GET /img/<did>/<cid>` | a group's or a person's image, for whoever may see it: anyone, for one in a public repo; otherwise only someone signed in to the console |
## Spaces
docs/reference/config.md+1−0
@@ -22,6 +22,7 @@ trimmed of spaces and a trailing `/`.
| `BLOB_UPLOAD_LIMIT` | the most bytes one blob may be, uploaded, or brought with a group, an account or a space; `describeServer` answers it | 52428800 (50 MiB) |
| `CONSOLE_URL` | where the console is: where the host sends a member to approve an app or an MCP client (`/authorize`), the console's OAuth client id and callback when people sign in (`/console/…`), and, when `https`, whether the session cookie is `Secure` | `PUBLIC_URL` |
| `PROVISIONING_CLIENTS` | the apps the host makes groups for with `provisionGroup`, comma-separated OAuth client ids, each matched as written, a trailing `/` included; `*` for any | none |
| `ACTOR_SEARCH` | where `searchActors` looks for a handle being typed: `plc`, the handles in `PLC_URL`'s own export, read a page at a time and kept a minute; or the URL of a service answering `tech.waow.typeahead.searchActors` | typeahead.waow.tech's, when `PLC_URL` is `https://plc.directory`; else `plc` |
| `PDS_CRAWLERS` | relays told of news with `requestCrawl`, comma-separated, a trailing `/` dropped: at most every 20 minutes, and the first time after a start | none |
| `RUST_LOG` | what it logs, as `tracing-subscriber`'s filter reads it; lines are JSON | `info` |
harness/e2e/pages.mjs+7−5
lexicons/fyi/opensocial/searchActors.jsonnew+51−0
web/src/lib/typeahead.ts+7−6
web/vite.config.ts+2−2