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 administration client.

use connectrpc::client::{ClientConfig, ClientTransport};
use polyc_proto::proto::polychrome::state::v1 as pb;
use polyc_state::{
    administration::{AdminRoster, AdministrationCommand, AdministrationFact, DeploymentSettings},
    error::StateError,
    id::{CommandId, NamespaceId},
    receipt::Receipt,
    revision::Revision,
    versioned::authority::{AdminStatus, PersonaId},
};

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, roster_from_wire, settings_from_wire, status_from_wire,
};

/// Client bound to one administration namespace.
pub struct AdministrationClient<T> {
    inner: pb::StateAdministrationServiceClient<T>,
    namespace: NamespaceId,
}

impl<T> AdministrationClient<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::StateAdministrationServiceClient::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 administration operation.
    ///
    /// # Errors
    ///
    /// Returns a typed State or transport failure when the operation cannot be committed.
    pub async fn transact(
        &self,
        declared: &DeclaredCall,
        command: &AdministrationCommand,
    ) -> Result<Receipt, StateError> {
        if command.metadata().scope().namespace() != &self.namespace {
            return Err(StateError::Denied {
                family: polyc_state::versioned::family(),
            });
        }
        let request = pb::TransactAdministrationRequest {
            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 administration mutation returns a receipt".into(),
            }
        })?)
        .map(Kernel::into_inner)
    }

    /// Reads one persona's current privileged roles.
    ///
    /// # Errors
    ///
    /// Returns a typed State or transport failure when the status cannot be read.
    pub async fn status(
        &self,
        declared: &DeclaredCall,
        persona: &PersonaId,
    ) -> Result<AdministrationFact<AdminStatus>, StateError> {
        let request = pb::GetAdministrationStatusRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            namespace: self.namespace.as_str().to_owned(),
            persona: 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_status_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|error| from_connect_error(&error, &Self::fallback(attempted)))?
            .into_owned();
        Ok(AdministrationFact::observed(
            status_from_wire(&reply.status.into_option().ok_or_else(|| {
                StateError::Malformed {
                    field: "status".into(),
                    reason: "status reply carries a value".into(),
                }
            })?)?,
            Revision::new(reply.snapshot_revision),
            reply.entry_revision.map(Revision::new),
        ))
    }

    /// Reads the bounded administrator roster.
    ///
    /// # Errors
    ///
    /// Returns a typed State or transport failure when the roster cannot be read.
    pub async fn roster(
        &self,
        declared: &DeclaredCall,
    ) -> Result<AdministrationFact<AdminRoster>, StateError> {
        let request = pb::GetAdministrationRosterRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            namespace: self.namespace.as_str().to_owned(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .get_roster_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|error| from_connect_error(&error, &Self::fallback(attempted)))?
            .into_owned();
        Ok(AdministrationFact::observed(
            roster_from_wire(
                reply
                    .roster
                    .into_option()
                    .ok_or_else(|| StateError::Malformed {
                        field: "roster".into(),
                        reason: "roster reply carries a value".into(),
                    })?,
            ),
            Revision::new(reply.snapshot_revision),
            reply.entry_revision.map(Revision::new),
        ))
    }

    /// Reads deployment settings, if seeded.
    ///
    /// # Errors
    ///
    /// Returns a typed State or transport failure when settings cannot be read.
    pub async fn settings(
        &self,
        declared: &DeclaredCall,
    ) -> Result<AdministrationFact<Option<DeploymentSettings>>, StateError> {
        let request = pb::GetAdministrationSettingsRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            namespace: self.namespace.as_str().to_owned(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .get_settings_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|error| from_connect_error(&error, &Self::fallback(attempted)))?
            .into_owned();
        Ok(AdministrationFact::observed(
            reply.settings.into_option().map(settings_from_wire),
            Revision::new(reply.snapshot_revision),
            reply.entry_revision.map(Revision::new),
        ))
    }

    /// Retrieves a previously committed receipt.
    ///
    /// # Errors
    ///
    /// Returns a typed State or transport failure when settlement cannot be read.
    pub async fn committed_receipt(
        &self,
        declared: &DeclaredCall,
        command_id: &CommandId,
    ) -> Result<Option<Receipt>, StateError> {
        let request = pb::GetAdministrationReceiptRequest {
            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()
    }
}