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

Spaces, handles, deletes and invites are written whole or undone

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:host/whole-writes
crates/group-host/src/group.rs+6−3
@@ -166,10 +166,13 @@ impl Host {
}
})?;
// A group half made is no group: its account goes, so its handle
// is free again.
// is free again. Should that fail, what was asked fails as it did,
// and the host says why the handle stays taken.
let made = self.set_up(&did, new, &shape).await;
if made.is_err() {
let _ = self.delete_account(&did).await;
if made.is_err()
&& let Err(e) = self.delete_account(&did).await
{
tracing::warn!(did = %did, error = %format!("{e:#}"), "could not undo a group half made");
}
made
}
crates/group-host/src/group_handle.rs+16−9
@@ -97,7 +97,7 @@ pub async fn check_group_handle(
}
/// Gives the group a handle on a domain that names it, or its own address
/// back: its `did:plc` first, then the host, then the relays.
/// back: the host holds it, its `did:plc` names it, then the relays hear.
pub async fn update_group_handle(
State(host): State<Arc<Host>>,
headers: HeaderMap,
@@ -112,7 +112,8 @@ pub async fn update_group_handle(
let address = configurable(&host, &headers, group, "updateGroupHandle").await?;
let handle = wanted(&host, group, &address, asked)?;
let current = host.store.account(group).map_err(XrpcError::internal)?;
if current.is_some_and(|a| a.handle == handle) {
let before = current.map(|a| a.handle).unwrap_or_default();
if before == handle {
return Ok(Json(json!({ "handle": handle })));
}
if named(&host, group, &address, &handle).await.as_deref() != Some(group) {
@@ -123,8 +124,7 @@ pub async fn update_group_handle(
),
));
}
// The directory first: until it names the handle, nobody takes it for
// the group's.
// One change to the group's identity at a time.
let turn = host.plc.turn().await;
let last = host.plc.last_op(group).await.map_err(XrpcError::internal)?;
let Signed::Update { op, .. } = &last else {
@@ -140,12 +140,19 @@ pub async fn update_group_handle(
let mut next = op.clone();
next.also_known_as = vec![format!("at://{handle}")];
let signed = next.sign(Some(last.cid()), &host.secrets.rotation);
host.plc
.publish(group, &signed)
.await
.map_err(crate::plc::not_published)?;
// The host holds the handle first, so the directory never names one
// the host refuses: taken here meanwhile, the database's unique handle
// refuses it. The directory refusing, the host puts its handle back.
let held = host.store.set_handle(group, &handle, &[]);
held.map_err(XrpcError::internal)?;
let published = host.plc.publish(group, &signed).await;
if let Err(e) = published {
let back = host.store.set_handle(group, &before, &[]);
back.map_err(XrpcError::internal)?;
return Err(crate::plc::not_published(e));
}
drop(turn);
// Taken here meanwhile, the database's unique handle refuses it.
// Until the directory names it, the relays are not told.
let set = host
.store
.set_handle(group, &handle, &[identity(group, &handle)]);
crates/group-host/src/group_invites.rs+28−19
@@ -140,7 +140,7 @@ pub fn millis_of(text: &str) -> Option<i64> {
impl Host {
/// Takes `invite` back: its record out of the group's repo in the
/// inbox, and the host's list.
async fn take_back(&self, invite: &Invite) -> Result<(), XrpcError> {
pub(crate) async fn take_back(&self, invite: &Invite) -> Result<(), XrpcError> {
let gone = Write::Delete {
collection: format!("{NS}.invite"),
rkey: invite.rkey.clone(),
@@ -152,22 +152,38 @@ impl Host {
forgot.map_err(XrpcError::internal)
}
/// `group`'s invite to `did`, if one waits and has not lapsed: taken
/// back, as it is redeemed.
pub(crate) async fn redeem(&self, group: &str, did: &str) -> Result<bool, XrpcError> {
/// `group`'s invite to `did`, if one waits and has not lapsed. One
/// lapsed is taken back.
pub(crate) async fn waiting_invite(
&self,
group: &str,
did: &str,
) -> Result<Option<Invite>, XrpcError> {
let invited = self
.store
.invited(group, did)
.map_err(XrpcError::internal)?;
let live = invited.filter(|i| i.expires_at.is_none_or(|at| at > now_millis()));
match live {
Some(invite) => {
self.take_back(&invite).await?;
Ok(true)
match invited {
Some(lapsed) if lapsed.expires_at.is_some_and(|at| at <= now_millis()) => {
self.take_back(&lapsed).await?;
Ok(None)
}
None => Ok(false),
waiting => Ok(waiting),
}
}
/// Takes back the invites lapsed by `now`, saying how many. One whose
/// group is switched off waits until it is on again.
pub async fn sweep_invites(&self, now: i64) -> anyhow::Result<usize> {
let lapsed = self.store.lapsed_invites(now)?;
let mut swept = 0;
for invite in &lapsed {
if self.take_back(invite).await.is_ok() {
swept += 1;
}
}
Ok(swept)
}
}
/// Invites someone, for one holding `invite`: an invite written in the
@@ -201,15 +217,8 @@ pub async fn create_invite(
let group = members.group.clone();
// One waiting is the one answered; one lapsed is taken back, and a
// fresh one written.
let invited = host
.store
.invited(&group, invitee)
.map_err(XrpcError::internal)?;
if let Some(waiting) = invited {
if waiting.expires_at.is_none_or(|at| at > now_millis()) {
return Ok(Json(json!({ "uri": uri_of(&waiting) })));
}
host.take_back(&waiting).await?;
if let Some(waiting) = host.waiting_invite(&group, invitee).await? {
return Ok(Json(json!({ "uri": uri_of(&waiting) })));
}
let invite = Invite {
seq: 0,
crates/group-host/src/group_join.rs+5−2
@@ -60,10 +60,13 @@ pub async fn request_join(
if members.membership(&me)?.is_some() {
return Err(bad("AlreadyMember", "you are a member already"));
}
// An invite is pre-approval: redeemed, whatever the policy.
if host.redeem(group, &me).await? {
// An invite is pre-approval: redeemed, whatever the policy. It is
// taken back once they are a member, so a membership not written
// leaves it waiting.
if let Some(invite) = host.waiting_invite(group, &me).await? {
let roles = members.default_roles()?;
members.put_membership(&me, &roles).await?;
host.take_back(&invite).await?;
host.store.decide(group, &me).map_err(XrpcError::internal)?;
return Ok(Json(json!({"status": "admitted"})));
}
crates/group-host/src/group_lifecycle.rs+4−3
@@ -86,9 +86,10 @@ pub async fn activate_group(
}
}
/// Deletes a group: its account, repos and spaces here, and what the host
/// keeps of them; the services syncing its spaces are told; its DID is
/// ended. They are told first, while the group has a key to sign with:
/// Deletes a group: its DID is ended; its account, repos and spaces here
/// go, and what the host keeps of them; the services syncing its spaces
/// are told. The directory refusing, the group stays, to be deleted
/// again. They are told first, while the group has a key to sign with:
/// best effort, so a delete that then fails has told them of one that
/// did not happen, and they find it again when they next read. What
/// members wrote in its spaces is theirs, at their own PDSes.
crates/group-host/src/group_spaces.rs+32−6
@@ -125,6 +125,27 @@ pub async fn create_space(
None => host.clock.next(),
};
let uri = host.create_space(&group, kind, &skey, false)?;
// A space without its access record or its entry could be neither
// changed nor deleted, and its key never made again: it is made whole
// or not at all.
let furnished = furnish(&host, &group, &uri, &body, readers, writers).await;
if let Err(e) = furnished {
host.end_space(&group, &uri).map_err(XrpcError::internal)?;
return Err(e);
}
Ok(Json(json!({ "uri": uri })))
}
/// Writes a space just made its access record, and its entry in the
/// group's index, as `body` has them.
async fn furnish(
host: &Host,
group: &str,
uri: &str,
body: &Value,
readers: Vec<Value>,
writers: Option<Vec<Value>>,
) -> Result<(), XrpcError> {
let at = iso(now_millis());
let mut access =
json!({"$type": format!("{NS}.access"), "readableBy": readers, "createdAt": at});
@@ -139,9 +160,9 @@ pub async fn create_space(
rkey: "self".into(),
value: access,
};
host.space_write(&group, &uri, &[access_write]).await?;
host.space_write(group, uri, &[access_write]).await?;
let mut entry = json!({"$type": format!("{NS}.space"), "space": uri, "createdAt": at});
if let Some(name) = name {
if let Some(name) = body["name"].as_str() {
entry["name"] = json!(name);
}
let indexed = Write::Create {
@@ -149,9 +170,9 @@ pub async fn create_space(
rkey: host.clock.next(),
value: entry,
};
host.space_write(&group, &members_space(&group), &[indexed])
host.space_write(group, &members_space(group), &[indexed])
.await?;
Ok(Json(json!({ "uri": uri })))
Ok(())
}
/// Changes a space: its name, who reads it, who writes in it in their own
@@ -192,6 +213,12 @@ pub async fn update_space(
if writers.is_some() && space == members {
return Err(invalid("who may write in the members space is fixed"));
}
// The entry is found before anything is written, so a change refused
// for want of it changes nothing.
let named = match name {
Some(name) => Some((name, entry_of(&host, &group, &space)?)),
None => None,
};
if readers.is_some() || writers.is_some() || body.get("credentialScopes").is_some() {
let mut access = current.clone();
if let Some(readers) = &readers {
@@ -216,8 +243,7 @@ pub async fn update_space(
let declared = host.declare(&group, names(readers).iter().any(|r| r == PUBLIC));
declared.await?;
}
if let Some(name) = name {
let (rkey, mut entry) = entry_of(&host, &group, &space)?;
if let Some((name, (rkey, mut entry))) = named {
entry["name"] = json!(name);
let put = put_in(&host, &group, &members, &space_collection, &rkey, entry);
let _written = put.await?;
crates/group-host/src/lib.rs+4−2
@@ -629,8 +629,8 @@ pub async fn serve(config: Config) -> anyhow::Result<()> {
println!("listening on {}", listener.local_addr()?);
tracing::info!(public_url = %config.public_url, did = %config.service_did, "serving");
let host = Arc::new(Host::open(config)?);
// Uploads no record took, and moves kept a day, swept now and each
// hour after.
// Uploads no record took, moves kept a day, and invites lapsed, swept
// now and each hour after.
let sweeping = host.clone();
tokio::spawn(async move {
loop {
@@ -638,6 +638,8 @@ pub async fn serve(config: Config) -> anyhow::Result<()> {
tracing::info!(?swept, "swept the uploads no record took");
let moves = sweeping.sweep_moves(time::now_millis()).await;
tracing::info!(?moves, "gave back the moves kept a day");
let invites = sweeping.sweep_invites(time::now_millis()).await;
tracing::info!(?invites, "took back the invites lapsed");
tokio::time::sleep(std::time::Duration::from_secs(60 * 60)).await;
}
});
crates/group-host/src/lifecycle.rs+16−13
@@ -89,32 +89,35 @@ impl Host {
Ok(done)
}
/// Deletes `did` from the host whole, and ends its DID in the
/// directory, as only this host holds a key to it. Whether it was
/// ended.
/// Ends `did` in the directory, as only this host holds a key to it,
/// then deletes it from the host whole. Whether its DID was ended.
///
/// The DID goes first: once the account is gone, nobody could ask
/// again, and a DID nobody else can end would stay live with nothing
/// behind it. The directory unreachable or refusing, the account stays
/// as it was, to be deleted again.
pub async fn delete_account(&self, did: &str) -> Result<bool> {
let ended = self.tombstone(did).await?;
let blobs = self
.store
.delete_account(did, &[status(did, Some("deleted"))])?;
self.remove_blobs(blobs.iter().map(|cid| (did, cid)));
self.announce();
let ended = self.tombstone(did).await;
if let Err(e) = &ended {
tracing::warn!(did, error = %format!("{e:#}"), "could not end the DID");
}
Ok(ended.unwrap_or(false))
Ok(ended)
}
/// Ends `did` in the directory, if nobody but this host could ever use
/// it again: with a steward's recovery key on it, it is theirs to keep,
/// to bring the group back elsewhere, and is left alone. Whether it
/// ended it.
/// to bring the group back elsewhere, and is left alone. Whether it is
/// ended, as it is already when asked again.
async fn tombstone(&self, did: &str) -> Result<bool> {
let last = self.plc.last_op(did).await?;
let ours = self.secrets.rotation.public().did_key();
if let atproto::plc::Signed::Update { op, .. } = &last
&& op.rotation_keys.iter().any(|k| *k != ours)
{
let op = match &last {
atproto::plc::Signed::Tombstone { .. } => return Ok(true),
atproto::plc::Signed::Update { op, .. } => op,
};
if op.rotation_keys.iter().any(|k| *k != ours) {
return Ok(false);
}
let end = atproto::plc::tombstone(last.cid(), &self.secrets.rotation);
crates/group-host/src/store.rs+9−0
@@ -510,6 +510,7 @@ const INVITE: &str = "INSERT INTO invite (grp, invitee, by, message, rkey, creat
const INVITED: &str = "SELECT seq, grp, invitee, by, message, rkey, created_at, expires_at FROM invite WHERE grp = ?1 AND invitee = ?2";
const INVITES: &str = "SELECT seq, grp, invitee, by, message, rkey, created_at, expires_at FROM invite WHERE grp = ?1 AND seq < ?2 AND (expires_at IS NULL OR expires_at > ?3) ORDER BY seq DESC LIMIT ?4";
const INVITES_TO: &str = "SELECT seq, grp, invitee, by, message, rkey, created_at, expires_at FROM invite WHERE invitee = ?1 AND (expires_at IS NULL OR expires_at > ?2) ORDER BY seq DESC";
const LAPSED_INVITES: &str = "SELECT seq, grp, invitee, by, message, rkey, created_at, expires_at FROM invite WHERE expires_at <= ?1 ORDER BY seq";
const UNINVITE: &str = "DELETE FROM invite WHERE grp = ?1 AND invitee = ?2";
const SPACES_OF: &str = "SELECT uri FROM space WHERE authority = ?1 ORDER BY uri";
const DEACTIVATE: &str = "INSERT INTO deactivation (did, at, by, stewards) VALUES (?1, ?2, ?3, ?4) ON CONFLICT (did) DO NOTHING";
@@ -1607,6 +1608,14 @@ impl Store {
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
/// The invites lapsed by `now`, oldest first.
pub fn lapsed_invites(&self, now: i64) -> Result<Vec<Invite>> {
let conn = self.conn();
let mut q = conn.prepare(LAPSED_INVITES)?;
let rows = q.query_map([now], invite)?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
/// Forgets `group`'s invite to `invitee`.
pub fn uninvite(&self, group: &str, invitee: &str) -> Result<()> {
let conn = self.conn();
crates/group-host/tests/common/mod.rs+20−6
@@ -17,17 +17,30 @@ use group_host::Host;
use group_host::config::Config;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
/// A PLC directory: each DID's operations, each checked as the real one
/// checks them, and its document as it serves one. `refuse` turns every
/// operation away; `slow` holds each read of a last operation a while, so
/// two changes at once both read before either writes.
/// operation away, and `refuse_ends` every tombstone; `slow` holds each
/// read of a last operation a while, so two changes at once both read
/// before either writes.
#[derive(Default)]
pub struct Plc {
pub ops: Mutex<HashMap<String, Vec<Signed>>>,
pub refuse: bool,
pub slow: std::sync::atomic::AtomicBool,
pub refuse: AtomicBool,
pub refuse_ends: AtomicBool,
pub slow: AtomicBool,
}
/// Whether `switch` is on.
pub fn on(switch: &AtomicBool) -> bool {
switch.load(Ordering::SeqCst)
}
/// Turns `switch` to `to`.
pub fn turn(switch: &AtomicBool, to: bool) {
switch.store(to, Ordering::SeqCst);
}
async fn publish(
@@ -62,7 +75,8 @@ async fn publish(
}
Signed::Tombstone { .. } => true,
};
if plc.refuse || !signed || !keys_taken {
let ending = matches!(op, Signed::Tombstone { .. });
if on(&plc.refuse) || (ending && on(&plc.refuse_ends)) || !signed || !keys_taken {
return StatusCode::BAD_REQUEST;
}
log.push(op);
@@ -127,7 +141,7 @@ pub async fn serve(router: Router) -> String {
pub async fn start_plc(refuse: bool) -> (Arc<Plc>, String) {
let plc = Arc::new(Plc {
refuse,
refuse: refuse.into(),
..Plc::default()
});
let router = Router::new()
crates/group-host/tests/group_handle.rs+14−1
crates/group-host/tests/group_spaces.rs+16−1
crates/group-host/tests/invites.rs+42−10
crates/group-host/tests/lifecycle.rs+44−4
docs/design/groups.md+14−8
docs/design/membership.md+6−3
docs/design/recovery.md+4−2