gent-daemon 0.2.4

Local daemon, storage and synchronization for Gent chat clusters.
Documentation
use super::*;

impl Store {
    pub(crate) fn serve_rename(&self, endpoint: EndpointId, command: &Command) -> Result<Decision> {
        let tx = self.db.unchecked_transaction()?;
        let mut session = self.network_session(&tx, self.identity.state(&tx)?);
        session.timestamp = requests::clock(&tx, now())?;
        let (peer, _) = session.management_peer(endpoint)?;
        ensure!(
            peer != self.local_node_id()
                && command.host == self.local_node_id()
                && command.host_key == self.identity.node.public_key(),
            "wrong rename carrier"
        );
        let decision = session.host_decision(&peer, command)?;
        tx.commit()?;
        self.sync_wakeup.notify_one();
        Ok(decision)
    }
}

impl StoreSession<'_> {
    fn host_decision(&self, peer: &str, command: &Command) -> Result<Decision> {
        let id = command.id.to_string();
        let fingerprint = Sha256::digest(serde_json::to_vec(command)?);
        type Saved = (Vec<u8>, String, Option<u64>, Option<u64>);
        let saved: Option<Saved> = self
            .db
            .query_row(
                "SELECT fingerprint,decision,revision,epoch FROM chat_rename_receipts
             WHERE origin=?1 AND id=?2",
                params![peer, id],
                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
            )
            .optional()?;
        if let Some((saved, decision, revision, epoch)) = saved {
            ensure!(
                saved.as_slice() == fingerprint.as_slice(),
                "conflicting rename request"
            );
            if let Some(revision) = revision {
                let current_epoch: Option<u64> = self
                    .db
                    .query_row(
                        "SELECT epoch FROM hosted_work_grants WHERE node=?1",
                        [&command.publisher],
                        |r| r.get(0),
                    )
                    .optional()?;
                if !self.pinned(command) || current_epoch != epoch {
                    return Ok(Decision::Unconfirmed);
                }
                let durable: Option<u64> = self
                    .db
                    .query_row(
                        "SELECT durable FROM hosted_checkpoints WHERE node=?1",
                        [&command.publisher],
                        |r| r.get(0),
                    )
                    .optional()?;
                if durable.is_none_or(|durable| durable < revision) {
                    return Ok(Decision::Waiting);
                }
                // Restore can reuse a checkpoint number on the same carrier.
                // Confirm the committed registration before releasing the receipt.
                let published =
                    self.published_registration(&command.agent.to_string(), &command.publisher)?;
                if !published.is_some_and(|r| {
                    !r.revoked
                        && r.name == command.name
                        && (command.generation..=command.generation + 1).contains(&r.generation)
                }) {
                    return Ok(Decision::Unconfirmed);
                }
                self.db.execute(
                    "UPDATE chat_rename_receipts SET revision=NULL,epoch=NULL
                    WHERE origin=?1 AND id=?2",
                    params![peer, id],
                )?;
            }
            return Ok(serde_json::from_str(&decision)?);
        }
        if requests::admit(&id, self.timestamp).is_err() {
            return Ok(Decision::Unconfirmed);
        }
        self.db.execute(
            "DELETE FROM chat_rename_receipts WHERE expires<=?1",
            [self.timestamp],
        )?;
        let (count, for_peer): (usize, usize) = self.db.query_row(
            "SELECT COUNT(*),COUNT(*) FILTER (WHERE origin=?1) FROM chat_rename_receipts",
            [peer],
            |r| Ok((r.get(0)?, r.get(1)?)),
        )?;
        if count >= MAX_RECEIPTS
            || for_peer >= MAX_RECEIPTS / 4
            || self.state.checkpoint().revision < command.authority.revision
        {
            return Ok(Decision::Waiting);
        }
        let (decision, gate, epoch) = self.apply_host_rename(peer, command)?;
        self.db.execute(
            "INSERT INTO chat_rename_receipts VALUES(?1,?2,?3,?4,?5,?6,?7)",
            params![
                peer,
                id,
                fingerprint.as_slice(),
                serde_json::to_string(&decision)?,
                gate,
                epoch,
                requests::issued(&id).unwrap() + requests::LIFETIME + requests::CLOCK_SKEW
            ],
        )?;
        Ok(if gate.is_some() {
            Decision::Waiting
        } else {
            decision
        })
    }

    fn apply_host_rename(
        &self,
        peer: &str,
        command: &Command,
    ) -> Result<(Decision, Option<u64>, Option<u64>)> {
        if self.authorize_registration_admin(peer).is_err() {
            return Ok((Decision::Denied, None, None));
        }
        if !self.pinned(command)
            || config::label(&command.name).is_err()
            || !(1..MAX_REGISTRATION_GENERATION).contains(&command.generation)
            || encrypted::history::checkpoint(
                self.db,
                command.authority.revision,
                self.state.anchor(),
            )? != command.authority
        {
            return Ok((Decision::Unavailable, None, None));
        }
        let chat = command.agent.to_string();
        let agent = self
            .db
            .query_row(
                "SELECT id,node_id,name,provider,last_seen,revoked FROM agents
             WHERE id=?1 AND node_id=?2 AND revoked=0",
                params![chat, command.publisher],
                Self::decode_agent,
            )
            .optional()?;
        let Some(agent) = agent else {
            return Ok((Decision::Unavailable, None, None));
        };
        let current = self.registration_generation(&agent)?;
        if current != command.generation
            && !(current == command.generation + 1 && agent.name == command.name)
        {
            return Ok((Decision::Changed, None, None));
        }
        let portable = command.publisher != command.host;
        let mut epoch = None;
        if portable {
            epoch = self
                .db
                .query_row(
                    "SELECT epoch FROM hosted_work_grants WHERE node=?1",
                    [&command.publisher],
                    |r| r.get(0),
                )
                .optional()?;
            hosted::check_epoch(self.db, &command.publisher, epoch)?;
            self.require_web_lease(&command.publisher)?;
            if current == command.generation && agent.name != command.name {
                self.web_state_changed(&command.publisher)?;
            }
        }
        self.rename_agent(&chat, &command.name, command.generation)?;
        let gate = if portable {
            self.db
                .query_row(
                    "SELECT revision FROM hosted_checkpoints WHERE node=?1 AND durable<revision",
                    [&command.publisher],
                    |r| r.get(0),
                )
                .optional()?
        } else {
            None
        };
        Ok((Decision::Applied, gate, epoch))
    }
}