polyc-state-connect 2026.9.0

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 delegation-witness burn 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 — a typed State family has no reason to, and #2140 is what happens
//! when one does.
//!
//! Every call carries the caller's remaining budget in its
//! [`DeclaredCall`](crate::wire::DeclaredCall). This family gates a
//! redemption, so a read that never returns is a delegation ceremony that
//! hangs rather than one that is refused.
//!
//! Nothing here turns a transport failure into a lifecycle answer. A refused
//! or unanswered read comes back as a typed failure, never as
//! [`WitnessState::Unrecorded`] — which is itself a refusal, but one State
//! stated rather than one this client invented.

use connectrpc::client::{ClientConfig, ClientTransport};
use polyc_proto::proto::polychrome::state::v1 as pb;
use polyc_state::{
    burn::{
        BurnCommand, BurnFact, PendingIndex, PlannedWitness, SubjectRef, WitnessRef, WitnessState,
    },
    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::{
    metadata_to_wire, operation_to_wire, pending_from_wire, planned_set_from_wire, subject_to_wire,
    witness_state_from_wire, witness_to_wire,
};

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

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

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

    /// Commits one typed burn-lifecycle mutation.
    ///
    /// # Errors
    ///
    /// Returns a typed State or transport failure. Burning a witness State
    /// holds no record for, settling one that already settled, and redeeming
    /// one that was burned all come back as refusals, never as quiet
    /// successes.
    pub async fn transact(
        &self,
        declared: &DeclaredCall,
        command: &BurnCommand,
    ) -> Result<Receipt, StateError> {
        if command.metadata().scope().namespace() != &self.namespace {
            return Err(StateError::Denied {
                family: polyc_state::burn::family(),
            });
        }
        let request = pb::TransactStateBurnRequest {
            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 burn mutation returns a receipt".into(),
            }
        })?)
        .map(Kernel::into_inner)
    }

    /// Reads what State holds for one witness reference.
    ///
    /// # Errors
    ///
    /// Returns a typed State or transport failure.
    pub async fn witness(
        &self,
        declared: &DeclaredCall,
        witness: &WitnessRef,
    ) -> Result<BurnFact<WitnessState>, StateError> {
        let request = pb::GetStateBurnWitnessRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            namespace: self.namespace.as_str().to_owned(),
            witness: witness_to_wire(*witness),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .get_witness_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|error| from_connect_error(&error, &Self::fallback(attempted)))?
            .into_owned();
        Ok(BurnFact::observed(
            witness_state_from_wire(reply.state.into_option().ok_or_else(|| {
                StateError::Malformed {
                    field: "state".into(),
                    reason: "a witness reply carries what State holds for the reference".into(),
                }
            })?)?,
            Revision::new(reply.snapshot_revision),
            reply.entry_revision.map(Revision::new),
        ))
    }

    /// Reads one subject's bounded index of unsettled witnesses.
    ///
    /// # Errors
    ///
    /// Returns a typed State or transport failure.
    pub async fn pending_index(
        &self,
        declared: &DeclaredCall,
        subject: &SubjectRef,
    ) -> Result<BurnFact<PendingIndex>, StateError> {
        let request = pb::GetStateBurnPendingIndexRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            namespace: self.namespace.as_str().to_owned(),
            subject: subject_to_wire(*subject),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .get_pending_index_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|error| from_connect_error(&error, &Self::fallback(attempted)))?
            .into_owned();
        Ok(BurnFact::observed(
            pending_from_wire(&reply.pending.into_option().ok_or_else(|| {
                StateError::Malformed {
                    field: "pending".into(),
                    reason: "a pending reply carries the subject's outstanding index".into(),
                }
            })?)?,
            Revision::new(reply.snapshot_revision),
            reply.entry_revision.map(Revision::new),
        ))
    }

    /// Reads one subject's outstanding records, each with its own row premise.
    ///
    /// The returned fact's row premise is the index's — the one a subject burn
    /// fences on — so the caller that plans a revocation and the authority that
    /// commits it are naming the same row.
    ///
    /// # Errors
    ///
    /// Returns a typed State or transport failure.
    pub async fn pending_records(
        &self,
        declared: &DeclaredCall,
        subject: &SubjectRef,
    ) -> Result<BurnFact<Vec<PlannedWitness>>, StateError> {
        let request = pb::GetStateBurnPendingRecordsRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            namespace: self.namespace.as_str().to_owned(),
            subject: subject_to_wire(*subject),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .get_pending_records_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|error| from_connect_error(&error, &Self::fallback(attempted)))?
            .into_owned();
        Ok(BurnFact::observed(
            planned_set_from_wire("burns", reply.burns)?,
            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::GetStateBurnReceiptRequest {
            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()
    }
}