polyc-state-connect 2026.10.2

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 persona-passkey client.
//!
//! Async end to end. The generated client is async, every method here awaits
//! it, and nothing in this family reaches for a blocking bridge or a blocking
//! pool.
//!
//! Every call carries the caller's remaining budget in its
//! [`DeclaredCall`](crate::wire::DeclaredCall), and the caller is expected to
//! supply a real one. This family gates a login: a read that never returns is
//! a session that hangs, which is the outcome failing closed exists to avoid.

use connectrpc::client::{ClientConfig, ClientTransport};
use polyc_proto::proto::polychrome::state::v1 as pb;
use polyc_state::{
    error::StateError,
    id::{CommandId, NamespaceId},
    passkey::{
        CredentialId, PasskeyCommand, PasskeyFact, PasskeyPointer, PasskeyRecord, PersonaId,
    },
    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::{metadata_to_wire, operation_to_wire, pointer_from_wire, record_from_wire};

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

impl<T> PasskeyClient<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::StatePasskeyServiceClient::new(
                transport,
                config.with_default_max_message_size(MAX_WIRE_MESSAGE_BYTES),
            ),
            namespace,
        }
    }

    fn fallback(declared: &DeclaredCall, attempted: usize) -> TransportFallback {
        TransportFallback::new(
            polyc_state::passkey::family(),
            MAX_WIRE_MESSAGE_BYTES as u64,
            attempted as u64,
            declared.budget,
        )
    }

    /// Commits one typed passkey mutation.
    ///
    /// # Errors
    ///
    /// Returns a typed State or transport failure. An enrollment over a
    /// credential another persona holds comes back as a refusal, never as a
    /// quiet success.
    pub async fn transact(
        &self,
        declared: &DeclaredCall,
        command: &PasskeyCommand,
    ) -> Result<Receipt, StateError> {
        if command.metadata().scope().namespace() != &self.namespace {
            return Err(StateError::Denied {
                family: polyc_state::passkey::family(),
            });
        }
        let request = pb::TransactStatePasskeyRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            metadata: buffa::MessageField::some(metadata_to_wire(command)),
            persona_id: command.persona().as_str().to_owned(),
            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(declared, attempted)))?
            .into_owned();
        Kernel::<Receipt>::try_from(reply.receipt.into_option().ok_or_else(|| {
            StateError::Malformed {
                field: "receipt".into(),
                reason: "a successful passkey mutation returns a receipt".into(),
            }
        })?)
        .map(Kernel::into_inner)
    }

    /// Reads one persona's login credential.
    ///
    /// # Errors
    ///
    /// Returns a typed State or transport failure.
    pub async fn passkey(
        &self,
        declared: &DeclaredCall,
        persona: &PersonaId,
    ) -> Result<PasskeyFact<Option<PasskeyRecord>>, StateError> {
        let request = pb::GetStatePasskeyRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            namespace: self.namespace.as_str().to_owned(),
            persona_id: persona.as_str().to_owned(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .get_passkey_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|error| from_connect_error(&error, &Self::fallback(declared, attempted)))?
            .into_owned();
        Ok(PasskeyFact::observed(
            reply
                .passkey
                .into_option()
                .map(record_from_wire)
                .transpose()?,
            Revision::new(reply.snapshot_revision),
            reply.entry_revision.map(Revision::new),
        ))
    }

    /// Reads which persona holds one credential identifier.
    ///
    /// # Errors
    ///
    /// Returns a typed State or transport failure.
    pub async fn resolve_credential(
        &self,
        declared: &DeclaredCall,
        credential: &CredentialId,
    ) -> Result<PasskeyFact<Option<PasskeyPointer>>, StateError> {
        let request = pb::ResolveStatePasskeyCredentialRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            namespace: self.namespace.as_str().to_owned(),
            credential_id: credential.as_bytes().to_vec(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .resolve_credential_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|error| from_connect_error(&error, &Self::fallback(declared, attempted)))?
            .into_owned();
        Ok(PasskeyFact::observed(
            reply.pointer.into_option().map(pointer_from_wire),
            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::GetStatePasskeyReceiptRequest {
            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(declared, attempted)))?
            .into_owned();
        reply
            .receipt
            .into_option()
            .map(|value| Kernel::<Receipt>::try_from(value).map(Kernel::into_inner))
            .transpose()
    }
}