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).
//! Server adapter for the durable delegation-witness burn lifecycle.

use std::future::Future;
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::{
    burn::{BurnDirectory, BurnRead, BurnWrite},
    context::CallContext,
    error::StateError,
    id::{CommandId, NamespaceId},
    versioned::{VersionedRead, VersionedTransact},
};

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

use super::wire::{
    command_from_wire, pending_to_wire, planned_to_wire, subject_from_wire, witness_from_wire,
    witness_state_to_wire,
};

/// Complete, capability-specific burn authority port.
pub trait BurnAuthority: BurnRead + BurnWrite {
    /// Namespace this authority owns.
    fn namespace(&self) -> &NamespaceId;
}

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

/// State's delegation-witness burn service.
pub struct BurnSvc {
    authority: Arc<dyn BurnAuthority>,
    draining: Arc<AtomicBool>,
    binding: Arc<AudienceBinding>,
}

impl BurnSvc {
    /// Builds the service.
    #[must_use]
    pub const fn new(
        authority: Arc<dyn BurnAuthority>,
        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::StateBurnServiceExt 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, std::time::Duration), 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::burn::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),
            slot_wait(ctx.time_remaining(), &declared),
        ))
    }

    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::burn::family(),
            }))
        }
    }
}

#[allow(refining_impl_trait)]
impl pb::StateBurnService for BurnSvc {
    fn transact(
        &self,
        ctx: RequestContext,
        request: ServiceRequest<'_, pb::TransactStateBurnRequest>,
    ) -> impl Future<Output = ServiceResult<pb::TransactStateBurnReply>> {
        let message = request.to_owned_message();
        async move {
            let (context, span, wait) = self.admit(&ctx, message.context, "TransactStateBurn")?;
            let metadata = message
                .metadata
                .into_option()
                .ok_or_else(|| malformed_connect("metadata", "a burn command carries metadata"))?;
            self.namespace(&metadata.namespace)?;
            let operation = message.operation.into_option().ok_or_else(|| {
                malformed_connect("operation", "a burn command carries one operation")
            })?;
            let command =
                command_from_wire(metadata, operation).map_err(|error| to_connect_error(&error))?;
            let authority = Arc::clone(&self.authority);
            let receipt = blocking::mutation(span, polyc_state::burn::family(), wait, move || {
                authority.transact(command, &context)
            })
            .await?;
            Response::ok(pb::TransactStateBurnReply {
                receipt: buffa::MessageField::some(pb::Receipt::from(Kernel(&receipt))),
                __buffa_unknown_fields: buffa::UnknownFields::default(),
            })
        }
    }

    fn get_witness(
        &self,
        ctx: RequestContext,
        request: ServiceRequest<'_, pb::GetStateBurnWitnessRequest>,
    ) -> impl Future<Output = ServiceResult<pb::GetStateBurnWitnessReply>> {
        let message = request.to_owned_message();
        async move {
            let (context, span, wait) = self.admit(&ctx, message.context, "GetStateBurnWitness")?;
            self.namespace(&message.namespace)?;
            let witness =
                witness_from_wire("witness", &message.witness).map_err(|e| to_connect_error(&e))?;
            let authority = Arc::clone(&self.authority);
            let fact = blocking::read(span, polyc_state::burn::family(), wait, move || {
                authority.witness(&witness, &context)
            })
            .await?;
            Response::ok(pb::GetStateBurnWitnessReply {
                state: buffa::MessageField::some(witness_state_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(),
            })
        }
    }

    fn get_pending_index(
        &self,
        ctx: RequestContext,
        request: ServiceRequest<'_, pb::GetStateBurnPendingIndexRequest>,
    ) -> impl Future<Output = ServiceResult<pb::GetStateBurnPendingIndexReply>> {
        let message = request.to_owned_message();
        async move {
            let (context, span, wait) =
                self.admit(&ctx, message.context, "GetStateBurnPendingIndex")?;
            self.namespace(&message.namespace)?;
            let subject =
                subject_from_wire("subject", &message.subject).map_err(|e| to_connect_error(&e))?;
            let authority = Arc::clone(&self.authority);
            let fact = blocking::read(span, polyc_state::burn::family(), wait, move || {
                authority.pending_index(&subject, &context)
            })
            .await?;
            Response::ok(pb::GetStateBurnPendingIndexReply {
                pending: buffa::MessageField::some(pending_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(),
            })
        }
    }

    fn get_pending_records(
        &self,
        ctx: RequestContext,
        request: ServiceRequest<'_, pb::GetStateBurnPendingRecordsRequest>,
    ) -> impl Future<Output = ServiceResult<pb::GetStateBurnPendingRecordsReply>> {
        let message = request.to_owned_message();
        async move {
            let (context, span, wait) =
                self.admit(&ctx, message.context, "GetStateBurnPendingRecords")?;
            self.namespace(&message.namespace)?;
            let subject =
                subject_from_wire("subject", &message.subject).map_err(|e| to_connect_error(&e))?;
            let authority = Arc::clone(&self.authority);
            let fact = blocking::read(span, polyc_state::burn::family(), wait, move || {
                authority.pending_records(&subject, &context)
            })
            .await?;
            Response::ok(pb::GetStateBurnPendingRecordsReply {
                burns: fact.value().iter().map(planned_to_wire).collect(),
                snapshot_revision: fact.snapshot_revision().get(),
                entry_revision: fact
                    .entry_revision()
                    .map(polyc_state::revision::Revision::get),
                __buffa_unknown_fields: buffa::UnknownFields::default(),
            })
        }
    }

    fn get_receipt(
        &self,
        ctx: RequestContext,
        request: ServiceRequest<'_, pb::GetStateBurnReceiptRequest>,
    ) -> impl Future<Output = ServiceResult<pb::GetStateBurnReceiptReply>> {
        let message = request.to_owned_message();
        async move {
            let (_context, span, wait) =
                self.admit(&ctx, message.context, "GetStateBurnReceipt")?;
            self.namespace(&message.namespace)?;
            let namespace = NamespaceId::new(message.namespace);
            let command_id = CommandId::new(message.command_id);
            let authority = Arc::clone(&self.authority);
            let receipt = blocking::read(span, polyc_state::burn::family(), wait, move || {
                authority.committed_receipt(&namespace, &command_id)
            })
            .await?;
            Response::ok(pb::GetStateBurnReceiptReply {
                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(),
    })
}