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).
//! Server adapter for the durable outbound-spend ledger.

use std::sync::{
    Arc,
    atomic::{AtomicBool, Ordering},
};

use connectrpc::{ConnectError, RequestContext, Response, Router, ServiceRequest, ServiceResult};
use polyc_proto::proto::polychrome::state::v1 as pb;
use polyc_state::{
    context::CallContext,
    error::StateError,
    id::{CommandId, NamespaceId},
    spend::{ConversationId, SpendDirectory, SpendRead, SpendWrite},
    versioned::{VersionedRead, VersionedTransact},
};

use crate::{
    admission::{
        AudienceBinding, PeerIdentity, check_audience_binding, check_call_context_version,
        check_not_draining, check_transport_deadline, state_audience,
    },
    error::to_connect_error,
    trace::adopt_caller_trace,
    wire::{DeclaredCall, Kernel, declared_call},
};

use super::wire::{command_from_wire, ledger_to_wire};

/// Complete, capability-specific spend authority port.
pub trait SpendAuthority: SpendRead + SpendWrite {
    /// Namespace this authority owns.
    fn namespace(&self) -> &NamespaceId;
}

impl<V> SpendAuthority for SpendDirectory<V>
where
    V: VersionedRead + VersionedTransact,
{
    fn namespace(&self) -> &NamespaceId {
        self.namespace()
    }
}

/// State's outbound-spend service.
pub struct SpendSvc {
    authority: Arc<dyn SpendAuthority>,
    draining: Arc<AtomicBool>,
    binding: Arc<AudienceBinding>,
}

impl SpendSvc {
    /// Builds the service.
    #[must_use]
    pub const fn new(
        authority: Arc<dyn SpendAuthority>,
        draining: Arc<AtomicBool>,
        binding: Arc<AudienceBinding>,
    ) -> Self {
        Self {
            authority,
            draining,
            binding,
        }
    }

    /// Registers the capability-specific route family.
    #[must_use]
    pub fn register_on(self, router: Router) -> Router {
        use pb::StateSpendServiceExt as _;
        Arc::new(self).register(router)
    }

    fn peer(ctx: &RequestContext) -> PeerIdentity {
        PeerIdentity::from_verified_leaf(
            ctx.peer_certs().and_then(<[_]>::first).map(|leaf| &**leaf),
        )
    }

    fn admit(
        &self,
        ctx: &RequestContext,
        context: impl Into<Option<pb::CallContext>>,
        method: &'static str,
    ) -> Result<(CallContext, tracing::Span), ConnectError> {
        check_not_draining(self.draining.load(Ordering::Relaxed))?;
        let declared: DeclaredCall =
            declared_call(context).map_err(|error| to_connect_error(&error))?;
        let family = polyc_state::spend::family();
        check_call_context_version(declared.version).map_err(|error| to_connect_error(&error))?;
        check_audience_binding(
            &Self::peer(ctx),
            &declared.audience,
            &state_audience(),
            &self.binding,
            &family,
        )
        .map_err(|error| to_connect_error(&error))?;
        check_transport_deadline(ctx.time_remaining(), &family)
            .map_err(|error| to_connect_error(&error))?;
        Ok((
            declared.origin_relative_context(),
            adopt_caller_trace(ctx.headers(), method),
        ))
    }

    fn namespace(&self, value: &str) -> Result<(), ConnectError> {
        if value == self.authority.namespace().as_str() {
            Ok(())
        } else {
            Err(to_connect_error(&StateError::Denied {
                family: polyc_state::spend::family(),
            }))
        }
    }
}

#[allow(refining_impl_trait)]
impl pb::StateSpendService for SpendSvc {
    async fn transact(
        &self,
        ctx: RequestContext,
        request: ServiceRequest<'_, pb::TransactStateSpendRequest>,
    ) -> ServiceResult<pb::TransactStateSpendReply> {
        let message = request.to_owned_message();
        let (context, span) = self.admit(&ctx, message.context, "TransactStateSpend")?;
        let _entered = span.enter();
        let metadata = message
            .metadata
            .into_option()
            .ok_or_else(|| malformed_connect("metadata", "a spend command carries metadata"))?;
        self.namespace(&metadata.namespace)?;
        let operation = message.operation.into_option().ok_or_else(|| {
            malformed_connect("operation", "a spend command carries one operation")
        })?;
        let receipt = self
            .authority
            .transact(
                command_from_wire(metadata, message.conversation_id, operation)
                    .map_err(|error| to_connect_error(&error))?,
                &context,
            )
            .map_err(|error| to_connect_error(&error))?;
        Response::ok(pb::TransactStateSpendReply {
            receipt: buffa::MessageField::some(pb::Receipt::from(Kernel(&receipt))),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        })
    }

    async fn get_ledger(
        &self,
        ctx: RequestContext,
        request: ServiceRequest<'_, pb::GetStateSpendLedgerRequest>,
    ) -> ServiceResult<pb::GetStateSpendLedgerReply> {
        let message = request.to_owned_message();
        let (context, span) = self.admit(&ctx, message.context, "GetStateSpendLedger")?;
        let _entered = span.enter();
        self.namespace(&message.namespace)?;
        let fact = self
            .authority
            .ledger(&ConversationId::new(message.conversation_id), &context)
            .map_err(|error| to_connect_error(&error))?;
        Response::ok(pb::GetStateSpendLedgerReply {
            ledger: buffa::MessageField::some(ledger_to_wire(fact.value())),
            snapshot_revision: fact.snapshot_revision().get(),
            entry_revision: fact
                .entry_revision()
                .map(polyc_state::revision::Revision::get),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        })
    }

    async fn get_receipt(
        &self,
        ctx: RequestContext,
        request: ServiceRequest<'_, pb::GetStateSpendReceiptRequest>,
    ) -> ServiceResult<pb::GetStateSpendReceiptReply> {
        let message = request.to_owned_message();
        let (_context, span) = self.admit(&ctx, message.context, "GetStateSpendReceipt")?;
        let _entered = span.enter();
        self.namespace(&message.namespace)?;
        let receipt = self
            .authority
            .committed_receipt(
                &NamespaceId::new(message.namespace),
                &CommandId::new(message.command_id),
            )
            .map_err(|error| to_connect_error(&error))?;
        Response::ok(pb::GetStateSpendReceiptReply {
            receipt: receipt
                .as_ref()
                .map_or_else(buffa::MessageField::none, |value| {
                    buffa::MessageField::some(pb::Receipt::from(Kernel(value)))
                }),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        })
    }
}

fn malformed_connect(field: &str, reason: &str) -> ConnectError {
    to_connect_error(&StateError::Malformed {
        field: field.into(),
        reason: reason.into(),
    })
}