polyc-state-connect 2026.8.3

State plane transport adapter: capability-specific Connect clients and server-trait glue mapping the generated wire types onto the polyc-state kernel — typed outcomes, per-call admission, and the conformance surface the authenticated shell proves itself against (docs/proposals/separated-planes.md).
//! Capability-specific one-time-ceremony client.

use buffa::EnumValue;
use connectrpc::client::{ClientConfig, ClientTransport};
use polyc_proto::proto::polychrome::state::v1 as pb;
use polyc_state::{
    ceremonies::{
        CeremonyCommand, CeremonyExpirationShard, CeremonyFact, CeremonyId, CeremonyPreflight,
    },
    error::StateError,
    id::{CommandId, NamespaceId},
    receipt::Receipt,
    revision::Revision,
};

use crate::{
    MAX_WIRE_MESSAGE_BYTES,
    error::{TransportFallback, from_connect_error},
    trace::bounded_traced_options,
    wire::{DeclaredCall, Kernel},
};

use super::wire::{expiration_from_wire, metadata_to_wire, operation_to_wire, record_from_wire};

/// Client bound to one ceremony namespace and no other State capability.
pub struct CeremonyClient<T> {
    inner: pb::StateCeremonyServiceClient<T>,
    namespace: NamespaceId,
}

impl<T> CeremonyClient<T>
where
    T: ClientTransport,
    <T::ResponseBody as connectrpc::http_body::Body>::Error: std::fmt::Display,
{
    /// Builds a namespace-bound client.
    #[must_use]
    pub fn new(transport: T, config: ClientConfig, namespace: NamespaceId) -> Self {
        Self {
            inner: pb::StateCeremonyServiceClient::new(
                transport,
                config.with_default_max_message_size(MAX_WIRE_MESSAGE_BYTES),
            ),
            namespace,
        }
    }

    fn fallback(attempted: usize) -> TransportFallback {
        TransportFallback::new(
            polyc_state::versioned::family(),
            MAX_WIRE_MESSAGE_BYTES as u64,
            attempted as u64,
        )
    }

    /// Commits one typed lifecycle transition.
    ///
    /// # Errors
    ///
    /// Returns a typed State or transport failure.
    pub async fn transact(
        &self,
        declared: &DeclaredCall,
        command: &CeremonyCommand,
    ) -> Result<Receipt, StateError> {
        if command.metadata().scope().namespace() != &self.namespace {
            return Err(StateError::Denied {
                family: polyc_state::versioned::family(),
            });
        }
        let request = pb::TransactCeremonyRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            metadata: buffa::MessageField::some(metadata_to_wire(command)),
            operation: buffa::MessageField::some(operation_to_wire(command.operation())),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .transact_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|error| from_connect_error(&error, &Self::fallback(attempted)))?
            .into_owned();
        Kernel::<Receipt>::try_from(reply.receipt.into_option().ok_or_else(|| {
            StateError::Malformed {
                field: "receipt".into(),
                reason: "a successful ceremony mutation returns a receipt".into(),
            }
        })?)
        .map(Kernel::into_inner)
    }

    /// Classifies one digest identity at the supplied trusted time.
    ///
    /// # Errors
    ///
    /// Returns a typed State or transport failure, including malformed wire data.
    pub async fn inspect(
        &self,
        declared: &DeclaredCall,
        id: &CeremonyId,
        now_ms: u64,
    ) -> Result<CeremonyPreflight, StateError> {
        let request = pb::InspectCeremonyRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            namespace: self.namespace.as_str().to_owned(),
            ceremony_id: id.as_str().to_owned(),
            now_ms,
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .inspect_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|error| from_connect_error(&error, &Self::fallback(attempted)))?
            .into_owned();
        let class = match reply.classification {
            EnumValue::Known(value) => value,
            EnumValue::Unknown(_) => return Err(malformed_preflight()),
        };
        let revision = Revision::new(reply.snapshot_revision);
        let entry_revision = reply.entry_revision.map(Revision::new);
        let record = reply.record.into_option();
        if class == pb::CeremonyPreflightClass::Unknown {
            if record.is_some() || entry_revision.is_some() {
                return Err(malformed_preflight());
            }
            return Ok(CeremonyPreflight::Unknown(CeremonyFact::observed(
                None, revision, None,
            )));
        }
        let record = record_from_wire(record.ok_or_else(malformed_preflight)?)?;
        let fact = CeremonyFact::observed(record, revision, entry_revision);
        match class {
            pb::CeremonyPreflightClass::Active => Ok(CeremonyPreflight::Active(fact)),
            pb::CeremonyPreflightClass::Claimed => Ok(CeremonyPreflight::Claimed(fact)),
            pb::CeremonyPreflightClass::Spent => Ok(CeremonyPreflight::Spent(fact)),
            pb::CeremonyPreflightClass::Expired => Ok(CeremonyPreflight::Expired(fact)),
            pb::CeremonyPreflightClass::Unspecified | pb::CeremonyPreflightClass::Unknown => {
                Err(malformed_preflight())
            }
        }
    }

    /// Reads one bounded expiry shard.
    ///
    /// # Errors
    ///
    /// Returns a typed State or transport failure.
    pub async fn expiration_shard(
        &self,
        declared: &DeclaredCall,
        shard: u16,
    ) -> Result<CeremonyFact<CeremonyExpirationShard>, StateError> {
        let request = pb::GetCeremonyExpirationShardRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            namespace: self.namespace.as_str().to_owned(),
            shard: u32::from(shard),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .get_expiration_shard_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|error| from_connect_error(&error, &Self::fallback(attempted)))?
            .into_owned();
        let expiration = reply
            .expiration
            .into_option()
            .ok_or_else(|| StateError::Malformed {
                field: "expiration".into(),
                reason: "ceremony expiry reply carries a shard".into(),
            })?;
        Ok(CeremonyFact::observed(
            expiration_from_wire(expiration),
            Revision::new(reply.snapshot_revision),
            reply.entry_revision.map(Revision::new),
        ))
    }

    /// Settles an ambiguous command from its durable receipt.
    ///
    /// # Errors
    ///
    /// Returns a typed State or transport failure.
    pub async fn committed_receipt(
        &self,
        declared: &DeclaredCall,
        command_id: &CommandId,
    ) -> Result<Option<Receipt>, StateError> {
        let request = pb::GetCeremonyReceiptRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            namespace: self.namespace.as_str().to_owned(),
            command_id: command_id.as_str().to_owned(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .get_receipt_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|error| from_connect_error(&error, &Self::fallback(attempted)))?
            .into_owned();
        reply
            .receipt
            .into_option()
            .map(|value| Kernel::<Receipt>::try_from(value).map(Kernel::into_inner))
            .transpose()
    }
}

fn malformed_preflight() -> StateError {
    StateError::Malformed {
        field: "classification".into(),
        reason: "ceremony preflight reply is coherent and uses one known class".into(),
    }
}