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 persona-memory snapshots.

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::{
    context::CallContext,
    error::StateError,
    id::NamespaceId,
    persona_memory::{
        MemoryPartitionId,
        store::{SnapshotDirectory, SnapshotRead, SnapshotWrite},
    },
    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;

/// Complete, capability-specific persona-memory snapshot port.
pub trait PersonaMemorySnapshotAuthority: SnapshotRead + SnapshotWrite {
    /// Namespace this authority owns.
    fn namespace(&self) -> &NamespaceId;
}

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

/// State's persona-memory snapshot service.
pub struct PersonaMemorySnapshotSvc {
    authority: Arc<dyn PersonaMemorySnapshotAuthority>,
    draining: Arc<AtomicBool>,
    binding: Arc<AudienceBinding>,
}

impl PersonaMemorySnapshotSvc {
    /// Builds the service.
    #[must_use]
    pub const fn new(
        authority: Arc<dyn PersonaMemorySnapshotAuthority>,
        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::StatePersonaMemorySnapshotServiceExt 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::persona_memory::store::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::persona_memory::store::family(),
            }))
        }
    }
}

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

    fn get(
        &self,
        ctx: RequestContext,
        request: ServiceRequest<'_, pb::GetStatePersonaMemorySnapshotRequest>,
    ) -> impl Future<Output = ServiceResult<pb::GetStatePersonaMemorySnapshotReply>> {
        let message = request.to_owned_message();
        async move {
            let (context, span, wait) =
                self.admit(&ctx, message.context, "GetStatePersonaMemorySnapshot")?;
            self.namespace(&message.namespace)?;
            let authority = Arc::clone(&self.authority);
            let fact = blocking::read(
                span,
                polyc_state::persona_memory::store::family(),
                wait,
                move || authority.snapshot(&MemoryPartitionId::new(message.partition), &context),
            )
            .await?;
            Response::ok(pb::GetStatePersonaMemorySnapshotReply {
                record: fact
                    .value()
                    .as_ref()
                    .map(polyc_state::persona_memory::MemorySnapshot::encode),
                snapshot_revision: fact.snapshot_revision().get(),
                entry_revision: fact
                    .entry_revision()
                    .map(polyc_state::revision::Revision::get),
                __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(),
    })
}