blob: 10869846edd83e7d9ff7474ef54dee2108a2f74b [file]
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
//! Authenticated public Host. One Application owns every accepted execution.
mod access;
mod client;
pub mod discovery;
mod execution;
mod lifecycle;
pub mod startup;
pub mod websocket;
pub use access::{Pairing, PeerPairingInvite, PeerPairingOptions, PeerPairingReceipt};
pub mod protocol;
pub mod remote_access;
pub use client::{CallChannelOpener, Channel, Client, LocalCall, OpenChannel};
pub use discovery::Registration;
pub use protocol::{Configuration, LifecycleMode, Publication, Status, VERSION};
use super::transport::{
Catalogue, Endpoints, HostEndpoint, Peer, PeerPolicy, Peers, Server, wire, with_gateway,
};
use super::{Application, NativeRegistry, Result, RootIngressGrant};
use crate::ipc::{LocalListener, LocalStream};
use access::{Authority, Principal};
use maka_config::access::PeerGrant;
pub use maka_config::access::{HostPeerAccess, PeerAccessSync, PeerId};
use maka_event_log::root_store::RootStore;
use maka_plugin_core::deployment::DeploymentRef;
use maka_remote_pairing::RelayEndpoint;
pub use maka_remote_pairing::default_host_name;
use protocol::{Connected, Opening, Request, Response, SessionControl};
use sha2::Digest;
use std::{
collections::BTreeMap,
sync::{
Arc, Mutex,
atomic::{AtomicBool, Ordering},
},
time::Duration,
};
use tokio::sync::{broadcast, mpsc};
use tokio_util::{sync::CancellationToken, task::TaskTracker};
use uuid::Uuid;
use websocket::WebSocketListener;
/// Startup failed after all acquired resources were offered explicit cleanup.
#[derive(Debug)]
pub struct StartupFailure {
pub cause: String,
pub cleanup: std::result::Result<(), String>,
}
impl std::fmt::Display for StartupFailure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.cause)?;
if let Err(cleanup) = &self.cleanup {
write!(f, "; startup cleanup unconfirmed: {cleanup}")?;
}
Ok(())
}
}
impl std::error::Error for StartupFailure {}
pub type RequestPermission = fn(
&[maka_agent_facts::interaction::SystemPermissionGrant],
&(dyn Fn() -> bool + Sync),
) -> std::result::Result<(), String>;
#[derive(Clone)]
pub struct Options {
pub request_permission: Option<RequestPermission>,
pub generation: Option<String>,
pub lifecycle_mode: LifecycleMode,
pub handshake_timeout: Duration,
}
impl Default for Options {
fn default() -> Self {
Self {
request_permission: None,
generation: None,
lifecycle_mode: LifecycleMode::Service,
handshake_timeout: Duration::from_secs(10),
}
}
}
/// A binary Host wire stream from a trusted transport adapter. The adapter
/// must derive the ID from cryptographic endpoint authentication, never from
/// the bytes on this stream. IDs must share a canonical namespace with grants.
pub struct AuthenticatedPeerStream {
pub peer_id: PeerId,
pub stream: Channel,
}
/// Opened only from a checked, persisted source and trusted endpoint grants.
/// The caller retains this owner after any failed cleanup acknowledgement.
pub struct Host {
root: Arc<maka_event_log::root::RootOwner>,
options: Options,
application: Application,
store: Arc<RootStore>,
access: Arc<maka_config::ConfigurationStore>,
identity: maka_remote_pairing::DeviceIdentity,
access_grant: Mutex<String>,
device_grant: String,
root_ingress_grant: Option<RootIngressGrant>,
access_gate: tokio::sync::Mutex<()>,
native_relays: Mutex<Vec<RelayEndpoint>>,
remote_access: remote_access::Runtime,
revoked_peers: broadcast::Sender<PeerId>,
epoch: Uuid,
source: DeploymentRef,
policy: Arc<PeerPolicy>,
configuration: Mutex<Configuration>,
sessions: Mutex<BTreeMap<Uuid, Arc<Session>>>,
stop: CancellationToken,
accept_closed: CancellationToken,
shutdown: tokio::sync::OnceCell<Result<()>>,
residency: Mutex<lifecycle::Residency>,
}
struct Session {
revoked: AtomicBool,
principal: Principal,
peer: Arc<Peers>,
transport: Arc<Server>,
mode: SessionMode,
parent: Option<Uuid>,
}
enum SessionMode {
Owned {
selections: BTreeMap<String, HostEndpoint>,
},
Ui,
Peer {
source: DeploymentRef,
selections: BTreeMap<String, HostEndpoint>,
},
}
fn publication_grant(source: &DeploymentRef, configuration: &Configuration) -> Result<String> {
let publication =
serde_json::to_vec(&(source, configuration)).map_err(|error| error.to_string())?;
Ok(format!(
"application.owner:{}",
hex::encode(sha2::Sha256::digest(publication))
))
}
fn device_grant(source: &DeploymentRef) -> String {
format!("host.peer.v1:{}:{}", source.state_domain, source.deployment)
}
/// Called under the Root lease before replacing the persisted publication.
pub async fn migrate_host_peer_grants(
store: &RootStore,
source: &DeploymentRef,
configuration: &Configuration,
) -> Result<()> {
let legacy = publication_grant(source, configuration)?;
let access = maka_config::ConfigurationStore::for_root(
store.owned_root().map_err(|error| error.to_string())?,
)
.await
.map_err(|error| error.to_string())?;
let migrated = access
.migrate_host_peer_grants(legacy, device_grant(source))
.await;
let closed = access.close().await;
migrated.and(closed).map_err(|error| error.to_string())
}
impl Host {
pub async fn open(
store: Arc<RootStore>,
deployment: Uuid,
native: NativeRegistry,
scripts: Option<Arc<dyn super::backend::Factory>>,
configuration: Configuration,
) -> Result<Arc<Self>> {
Self::open_with_options(
store,
deployment,
native,
scripts,
configuration,
Options::default(),
)
.await
}
pub async fn open_with_options(
store: Arc<RootStore>,
deployment: Uuid,
native: NativeRegistry,
scripts: Option<Arc<dyn super::backend::Factory>>,
configuration: Configuration,
options: Options,
) -> Result<Arc<Self>> {
let loaded = store
.load_application(deployment)
.await
.map_err(|error| error.to_string())?
.ok_or("deployment not found")?;
Self::open_loaded_with_options(store, loaded, native, scripts, configuration, options).await
}
/// Open a checked committed source without rereading its immutable packages.
pub async fn open_loaded_with_options(
store: Arc<RootStore>,
loaded: maka_event_log::applications::LoadedDeployment,
native: NativeRegistry,
scripts: Option<Arc<dyn super::backend::Factory>>,
configuration: Configuration,
options: Options,
) -> Result<Arc<Self>> {
Self::open_loaded_with_cleanup(store, loaded, native, scripts, configuration, options)
.await
.map_err(|error| error.to_string())
}
/// Preserve cleanup evidence for an embedding that must release an execution grant.
pub async fn open_loaded_with_cleanup(
store: Arc<RootStore>,
loaded: maka_event_log::applications::LoadedDeployment,
native: NativeRegistry,
scripts: Option<Arc<dyn super::backend::Factory>>,
configuration: Configuration,
options: Options,
) -> std::result::Result<Arc<Self>, StartupFailure> {
let mut application_owner: Option<Application> = None;
let mut access_owner: Option<Arc<maka_config::ConfigurationStore>> = None;
let mut access_cleanup = None;
let result: Result<Arc<Self>> = async {
if options.handshake_timeout.is_zero()
|| options
.generation
.as_ref()
.is_some_and(|value| value.is_empty())
{
return Err("invalid Host options".into());
}
if let Some(execution) = store.checkpoint_execution() {
let grant = execution.grant();
if grant.binding.source.scope.deployment != loaded.source().reference.deployment {
return Err("execution grant belongs to another deployment".into());
}
execution.check().await.map_err(|e| e.to_string())?;
}
configuration.validate()?;
let Configuration::PublicHost {
endpoints,
native: grants,
..
} = &configuration;
let root = store.owned_root().map_err(|error| error.to_string())?;
let source = loaded.source().reference.clone();
let access_grant = publication_grant(&source, &configuration)?;
let device_grant = device_grant(&source);
let identity_path = root
.canonical_path()
.join(maka_remote_pairing::HOST_IDENTITY_FILE);
let identity = tokio::task::spawn_blocking(move || {
maka_remote_pairing::DeviceIdentity::load_or_create(&identity_path)
})
.await
.map_err(|error| error.to_string())?
.map_err(|error| error.to_string())?;
access_owner = Some(Arc::new(
maka_config::ConfigurationStore::for_root(root.clone())
.await
.map_err(|error| {
if matches!(
&error,
maka_config::ConfigError::Store(
maka_event_log::StoreError::StartupCleanupFailed { .. }
)
) {
access_cleanup = Some(error.to_string());
}
error.to_string()
})?,
));
let access = access_owner.as_ref().expect("configuration opened").clone();
let root_ingress_grant = native
.root_router
.as_ref()
.and_then(|router| router.ingress_grant());
let policy = Arc::new(PeerPolicy::with_native_grants(grants.clone())?);
application_owner = Some(Application::start_loaded(
store.clone(),
loaded,
with_gateway(native)?,
policy.issuer(),
policy.clone(),
scripts,
)?);
let application = application_owner.as_ref().expect("application started");
Endpoints::start(&application.client(), endpoints).await?;
access
.prepare_host_peer_access(access_grant.clone(), device_grant.clone())
.await
.map_err(|error| error.to_string())?;
// Only this running revision and newer ones can still have callers.
if let Err(error) = store.release_superseded_application_sources(&source).await {
tracing::error!(%error, "Superseded application sources remain installed");
}
let host = Arc::new(Self {
root,
options,
source,
application: application_owner.take().expect("application started"),
store,
access,
identity,
access_grant: Mutex::new(access_grant),
device_grant,
root_ingress_grant,
access_gate: tokio::sync::Mutex::new(()),
native_relays: Mutex::new(Vec::new()),
remote_access: remote_access::Runtime::default(),
// Keep room for a burst of peer revocations without disconnecting
// healthy peers. Subscribers still fail closed if they fall behind.
revoked_peers: broadcast::channel(64).0,
policy,
epoch: Uuid::new_v4(),
configuration: Mutex::new(configuration),
sessions: Mutex::default(),
stop: CancellationToken::new(),
accept_closed: CancellationToken::new(),
shutdown: tokio::sync::OnceCell::new(),
residency: Mutex::new(lifecycle::Residency::default()),
});
host.watch_execution();
Ok(host)
}
.await;
match result {
Ok(host) => Ok(host),
Err(cause) => {
let mut errors: Vec<_> = access_cleanup.into_iter().collect();
if let Some(application) = application_owner
&& let Err(error) = application.shutdown().await
{
errors.push(error);
}
if let Some(access) = access_owner
&& let Err(error) = access.shutdown().await
{
errors.push(error.to_string());
}
Err(StartupFailure {
cause,
cleanup: if errors.is_empty() {
Ok(())
} else {
Err(errors.join("; "))
},
})
}
}
}
async fn publication(&self) -> Result<Publication> {
let _gate = self.access_gate.lock().await;
if self.stop.is_cancelled() {
return Err("Host is closing".into());
}
let source = self
.store
.application_head(self.source.deployment)
.await
.map_err(|error| error.to_string())?
.ok_or("Host deployment source missing")?;
Ok(Publication {
source,
configuration: self.configuration.lock().unwrap().clone(),
})
}
/// This configuration step is durable independently of source replacement.
/// The launcher's original pending operation coordinates their retries.
async fn configure(
&self,
source: DeploymentRef,
previous: Configuration,
configuration: Configuration,
) -> Result<()> {
previous.validate()?;
configuration.validate()?;
if source.state_domain != self.root_id() || source.deployment != self.source.deployment {
return Err("foreign Host configuration source".into());
}
let _gate = self.access_gate.lock().await;
if self.stop.is_cancelled() {
return Err("Host is closing".into());
}
let Configuration::PublicHost { endpoints, .. } = &configuration;
let resolved = Endpoints::capture(&self.application.client(), endpoints).await?;
configuration.validate_product_methods(&previous, &Catalogue::captured(&resolved))?;
let current = self.configuration.lock().unwrap().clone();
let current = serde_json::to_value(current).map_err(|error| error.to_string())?;
let previous = serde_json::to_value(previous).map_err(|error| error.to_string())?;
let desired = serde_json::to_value(&configuration).map_err(|error| error.to_string())?;
if current != previous && current != desired {
return Err("Host configuration conflicts with current authority".into());
}
let record = self
.store
.application_launch()
.await
.map_err(|error| error.to_string())?
.ok_or("public Host selection missing")?;
if record.deployment != self.source.deployment {
return Err("Host configuration selects another deployment".into());
}
// Optional domain fields may be omitted or explicitly empty. Compare
// their typed meaning, but keep the exact stored JSON as the CAS witness.
let persisted: Configuration = serde_json::from_value(record.configuration.clone())
.map_err(|error| error.to_string())?;
persisted.validate()?;
let persisted = serde_json::to_value(persisted).map_err(|error| error.to_string())?;
if persisted != previous && persisted != desired {
return Err("Host configuration conflicts with persisted authority".into());
}
let access_grant = publication_grant(&self.source, &configuration)?;
let grant_changed = *self.access_grant.lock().unwrap() != access_grant;
if !self
.store
.compare_and_set_application_launch_configuration(source, record.configuration, desired)
.await
.map_err(|error| error.to_string())?
{
return Err("Host configuration source or persisted authority changed".into());
}
// Fence obsolete native bindings before publishing the new authority.
// Jobs that already started still belong to their original transport.
if grant_changed {
self.revoke_native_sessions();
if let Err(error) = self
.access
.prune_host_peer_pairing_invites(access_grant.clone())
.await
{
// The durable publication moved. Do not admit under the old
// grant; cold startup will reconcile the invitations.
self.stop.cancel();
return Err(error.to_string());
}
}
let Configuration::PublicHost { native, .. } = &configuration;
self.policy.replace_native_grants(native.clone());
*self.configuration.lock().unwrap() = configuration;
*self.access_grant.lock().unwrap() = access_grant;
Ok(())
}
/// The native transport must use the same key that signs pairing tickets.
pub fn device_identity(&self) -> &maka_remote_pairing::DeviceIdentity {
&self.identity
}
pub fn root_owner(&self) -> &Arc<maka_event_log::root::RootOwner> {
&self.root
}
pub fn root_id(&self) -> &str {
self.root.root_id()
}
pub fn epoch(&self) -> Uuid {
self.epoch
}
pub fn source(&self) -> &DeploymentRef {
&self.source
}
pub fn status(&self) -> Status {
let snapshot = self.application.client().snapshot();
Status {
root_id: self.root_id().to_owned(),
version: VERSION,
pid: std::num::NonZeroU32::new(std::process::id()).expect("process id"),
generation: self.options.generation.clone(),
lifecycle_mode: self.options.lifecycle_mode,
epoch: self.epoch,
source: self.source.clone(),
closing: self.stop.is_cancelled() || snapshot.closing,
closed: snapshot.closed,
cleanup_error: snapshot.cleanup_error,
sessions: self.sessions.lock().unwrap().len(),
active_calls: snapshot
.instances
.iter()
.map(|instance| instance.calls)
.sum(),
}
}
pub fn wait_for_drain(&self) -> impl Future<Output = ()> + Send + 'static {
let stop = self.stop.clone();
let mut updates = self.application.client().updates;
async move {
loop {
if updates.borrow().closing {
return;
}
tokio::select! {
() = stop.cancelled() => return,
result = updates.changed() => if result.is_err() { return; },
}
}
}
}
/// Current-account IPC is enforced by LocalListener's private directory/ACL
/// and the held Unix peer credentials. No request chooses its own principal.
pub async fn serve_local(
self: &Arc<Self>,
listener: LocalListener,
cancel: CancellationToken,
) -> Result<()> {
self.serve(listener, None, cancel).await
}
pub async fn serve(
self: &Arc<Self>,
listener: LocalListener,
websocket: Option<WebSocketListener>,
cancel: CancellationToken,
) -> Result<()> {
self.serve_with_peers(listener, websocket, None, cancel)
.await
}
/// Peer ingress EOF leaves IPC and WebSocket admission running.
pub async fn serve_with_peers(
self: &Arc<Self>,
listener: LocalListener,
websocket: Option<WebSocketListener>,
peers: Option<mpsc::Receiver<AuthenticatedPeerStream>>,
cancel: CancellationToken,
) -> Result<()> {
self.serve_ingress(Some(listener), websocket, peers, cancel)
.await
}
/// Peer ingress EOF drains accepted streams; cancellation interrupts that drain.
pub async fn serve_peer_streams(
self: &Arc<Self>,
peers: mpsc::Receiver<AuthenticatedPeerStream>,
cancel: CancellationToken,
) -> Result<()> {
self.serve_ingress(None, None, Some(peers), cancel).await
}
async fn serve_ingress(
self: &Arc<Self>,
mut listener: Option<LocalListener>,
websocket: Option<WebSocketListener>,
mut peers: Option<mpsc::Receiver<AuthenticatedPeerStream>>,
cancel: CancellationToken,
) -> Result<()> {
enum Incoming {
Local(LocalStream),
WebSocket(tokio::net::TcpStream, Arc<[String]>),
Peer(AuthenticatedPeerStream),
}
let tasks = TaskTracker::new();
let mut rejected = None;
let accepted = loop {
let stream = tokio::select! {
() = self.stop.cancelled() => break Ok(()),
() = cancel.cancelled() => break Ok(()),
value = async {
match &mut listener {
Some(listener) => listener.accept().await,
None => std::future::pending().await,
}
} => match value {
Ok(stream) => Incoming::Local(stream),
Err(error) => break Err(error.to_string()),
},
value = async {
match &websocket {
Some(listener) => listener.listener.accept().await.map(|(stream, _)| {
Incoming::WebSocket(stream, listener.allowed_origins.clone())
}),
None => std::future::pending().await,
}
} => match value {
Ok(stream) => stream,
Err(error) => break Err(error.to_string()),
},
value = async {
match &mut peers {
Some(peers) => peers.recv().await,
None => std::future::pending().await,
}
} => match value {
Some(stream) => Incoming::Peer(stream),
None => {
peers = None;
if listener.is_none() && websocket.is_none() {
break Ok(());
}
continue;
}
},
};
let connection = {
let fast = {
let mut residency = self.residency.lock().unwrap();
if self.stop.is_cancelled() || cancel.is_cancelled() {
rejected = Some(stream);
break Ok(());
}
if !residency.paused {
residency.connections += 1;
residency.last_activity = tokio::time::Instant::now();
Some(lifecycle::Connection { host: self.clone() })
} else {
None
}
};
match fast {
Some(connection) => connection,
None => {
// An idle probe temporarily pauses admission under access_gate while
// checking shutdown_if_idle(). Wait for that fence to either cancel the
// Host or resume admission instead of dropping an accepted client socket.
let _gate = tokio::select! {
biased;
() = self.stop.cancelled() => {
rejected = Some(stream);
break Ok(());
}
() = cancel.cancelled() => {
rejected = Some(stream);
break Ok(());
}
gate = self.access_gate.lock() => gate,
};
let mut residency = self.residency.lock().unwrap();
if residency.paused || self.stop.is_cancelled() || cancel.is_cancelled() {
rejected = Some(stream);
break Ok(());
}
residency.connections += 1;
residency.last_activity = tokio::time::Instant::now();
lifecycle::Connection { host: self.clone() }
}
}
};
let host = self.clone();
tasks.spawn(async move {
let _connection = connection;
// A malformed or disconnected peer fails only its own channel.
match stream {
Incoming::Local(stream) => {
let _ = host.connection(stream).await;
}
Incoming::WebSocket(stream, origins) => {
let _ = websocket::connection(stream, host, origins).await;
}
Incoming::Peer(AuthenticatedPeerStream { peer_id, stream }) => {
tokio::select! {
biased;
() = host.accept_closed.cancelled() => {},
_ = host.channel(stream, Authority::AuthenticatedPeer { peer_id }) => {},
}
}
}
});
};
tasks.close();
// Only peer-only EOF removes the last ingress before shutdown.
if listener.is_none() && websocket.is_none() && peers.is_none() {
tokio::select! {
() = self.stop.cancelled() => {},
() = cancel.cancelled() => {},
() = tasks.wait() => {},
}
}
// Stop accepting new peers and unlink the local socket BEFORE closing
// any rejected stream or cancelling in-flight handshakes, so a peer
// observing EOF/ECONNRESET while the Host retires sees the endpoint gone.
drop(listener);
drop(websocket);
drop(peers);
drop(rejected);
self.accept_closed.cancel();
self.stop.cancel();
tasks.wait().await;
self.shutdown().await?;
accepted
}
async fn connection(self: &Arc<Self>, stream: LocalStream) -> Result<()> {
#[cfg(unix)]
if stream.peer_cred().map_err(|error| error.to_string())?.uid()
!= unsafe { libc::geteuid() }
{
return Err("Host peer must belong to the current account".into());
}
self.channel(stream, Authority::Local).await
}
async fn channel<S>(self: &Arc<Self>, stream: S, authority: Authority) -> Result<()>
where
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
{
let (input, mut output) = tokio::io::split(stream);
let mut input = wire::Reader::new(input);
// Local administration may submit whole application configurations.
const MAX_NATIVE_OPENING: usize = 64 * 1024;
let limit = if matches!(authority, Authority::AuthenticatedPeer { .. }) {
MAX_NATIVE_OPENING
} else {
usize::MAX
};
let opening: Opening = tokio::select! {
biased;
() = self.accept_closed.cancelled() => return Err("Host is closing".into()),
value = tokio::time::timeout(self.options.handshake_timeout, input.read_bounded(limit)) => value.map_err(|_| "Host handshake timed out")??,
};
if opening.version != VERSION || opening.epoch.is_some_and(|epoch| epoch != self.epoch) {
return Err("Host protocol or incarnation changed".into());
}
match opening.request {
Request::Status => {
let gate = self.access_gate.lock().await;
self.identify(&authority, opening.client_instance.as_deref())
.await?;
drop(gate);
wire::write(&mut output, &Response::Status(self.status())).await
}
Request::Publication => {
authority.local()?;
wire::write(
&mut output,
&Response::Publication(self.publication().await),
)
.await
}
Request::Configure {
source,
previous,
configuration,
} => {
authority.local()?;
let result = self.configure(source, previous, configuration).await;
wire::write(&mut output, &Response::Configured(result)).await
}
Request::PrepareAccess { principal } => {
authority.local()?;
wire::write(
&mut output,
&Response::Pairing(self.prepare_access(principal).await),
)
.await
}
Request::RevokeAccess { credential } => {
authority.local()?;
wire::write(
&mut output,
&Response::Revoked(self.revoke_access(credential).await),
)
.await
}
Request::RequestComputerPermission { grant } => {
authority.local()?;
let request = self
.options
.request_permission
.ok_or("Host permission requests unavailable")?;
let stop = self.accept_closed.clone();
let result =
tokio::task::spawn_blocking(move || request(&[grant], &|| stop.is_cancelled()))
.await
.map_err(|error| error.to_string())?;
wire::write(&mut output, &Response::ComputerPermissionRequested(result)).await
}
Request::RemoteAccessStatus { invite_id } => {
authority.local()?;
wire::write(
&mut output,
&Response::RemoteAccessStatus(self.remote_access_status(invite_id).await),
)
.await
}
Request::UpdateRemoteAccess(update) => {
authority.local()?;
wire::write(
&mut output,
&Response::RemoteAccessUpdated(self.request_remote_access_update(update).await),
)
.await
}
Request::JoinServer(request) => {
authority.local()?;
let result = self.request_server_join(request).await;
wire::write(&mut output, &Response::ServerJoined(result)).await
}
Request::LeaveServer => {
authority.local()?;
let result = self.request_server_leave().await;
wire::write(&mut output, &Response::ServerLeft(result)).await
}
Request::BuiltinServerStatus => {
authority.local()?;
wire::write(
&mut output,
&Response::BuiltinServerStatus(Ok(self.builtin_server_status())),
)
.await
}
Request::UpdateBuiltinServer(config) => {
authority.local()?;
let result = self.request_builtin_server_update(config).await;
wire::write(&mut output, &Response::BuiltinServerUpdated(result)).await
}
Request::BuiltinServerInvite(request) => {
authority.local()?;
let result = self.request_builtin_server_invite(request).await;
wire::write(&mut output, &Response::BuiltinServerInvited(result)).await
}
Request::PreparePeerPairing(options) => {
authority.local()?;
let result = self.prepare_peer_pairing(options).await;
wire::write(&mut output, &Response::PeerPairingInvite(result)).await
}
Request::ListPeerAccess => {
authority.local()?;
let result = self.list_peer_access().await;
wire::write(&mut output, &Response::PeerAccess(result)).await
}
Request::RevokePeerAccess { peer_id } => {
authority.local()?;
let peer_id = PeerId::new(peer_id).map_err(|error| error.to_string())?;
let result = self.revoke_peer_access(peer_id).await;
wire::write(&mut output, &Response::Revoked(result)).await
}
Request::PeerPairingInfo => {
if !matches!(authority, Authority::AuthenticatedPeer { .. }) {
return Err("pairing info requires authenticated QUIC".into());
}
wire::write(
&mut output,
&Response::PeerPairingInfo(maka_remote_pairing::HostPlatform::current()),
)
.await
}
Request::RedeemPeerPairing {
invite_secret,
device_label,
} => {
let result = self
.redeem_peer_pairing(&authority, invite_secret, device_label)
.await;
wire::write(&mut output, &Response::PeerPairingReceipt(result)).await
}
Request::FinalizeAccessForRoot { expected_root_id } => {
wire::write(
&mut output,
&Response::Finalized(
self.finalize_access(
&authority,
opening.client_instance,
&expected_root_id,
)
.await,
),
)
.await
}
Request::Retire {
interrupt,
allow_idle_connections,
refuse_active_sessions,
} => {
authority.local()?;
let result = self
.retire(interrupt, allow_idle_connections, refuse_active_sessions)
.await;
wire::write(&mut output, &Response::Retired(result)).await
}
Request::Quit {
session: id,
ephemeral_only,
} => {
authority.local()?;
let session = self.sessions.lock().unwrap().get(&id).cloned();
if let Some(session) = session {
session.peer.replace(vec![])?;
session.transport.request_close();
self.close_ui_children(id).await?;
session.transport.close().await?;
}
let stop = {
// Admission and the last-session decision share the same gate.
let _gate = self.access_gate.lock().await;
let mut sessions = self.sessions.lock().unwrap();
sessions.remove(&id);
let stop = sessions.is_empty()
&& (!ephemeral_only
|| self.options.lifecycle_mode == LifecycleMode::Ephemeral);
if stop {
self.residency.lock().unwrap().paused = true;
self.stop.cancel();
}
stop
};
if stop {
self.shutdown().await?;
}
wire::write(&mut output, &Response::Closed).await
}
request @ (Request::Connect
| Request::ConnectPeer { .. }
| Request::ConnectUi { .. }) => {
let mut gate = Some(self.access_gate.lock().await);
let principal = match &authority {
Authority::AuthenticatedPeer { peer_id } => {
let Some(grant) = self.peer_grant(peer_id).await? else {
drop(gate.take());
return wire::write(&mut output, &Response::PeerAccessRevoked).await;
};
Principal::AuthenticatedPeer {
id: peer_id.clone(),
grant,
}
}
_ => {
self.identify(&authority, opening.client_instance.as_deref())
.await?
}
};
let root = match &principal {
Principal::AuthenticatedPeer {
grant: PeerGrant::Root(root),
..
} => Some(root),
_ => None,
};
let (mode, peer, endpoints, consumers, source, ui, parent) = match request {
Request::Connect => {
let selections = {
let configuration = self.configuration.lock().unwrap();
let Configuration::PublicHost { endpoints, .. } = &*configuration;
if root.is_some() {
let grant = self
.root_ingress_grant
.as_ref()
.expect("admitted Root grant");
let mut endpoint = endpoints
.get(grant.endpoint)
.ok_or("Cross-Root endpoint is not published")?
.clone();
endpoint
.grant
.methods
.retain(|method| grant.methods.contains(&method.as_str()));
endpoint.grant.recovery = false;
BTreeMap::from([(grant.endpoint.to_owned(), endpoint)])
} else {
endpoints.clone()
}
};
let consumers: BTreeMap<_, _> = selections
.iter()
.map(|(name, endpoint)| (name.clone(), endpoint.consumer.clone()))
.collect();
(
SessionMode::Owned {
selections: selections.clone(),
},
Peer::new(self.source.clone(), consumers.values().cloned().collect())?,
Endpoints::capture(&self.application.client(), &selections).await?,
consumers,
self.source.clone(),
None,
None,
)
}
Request::ConnectPeer {
source,
consumers,
endpoints: selections,
} => {
authority.local()?;
self.check_peer_selections(&selections)?;
let peer = Peer::new(source.clone(), consumers)?;
let endpoints =
Endpoints::capture(&self.application.client(), &selections).await?;
let consumers = selections
.iter()
.map(|(name, endpoint)| (name.clone(), endpoint.consumer.clone()))
.collect();
(
SessionMode::Peer { source, selections },
peer,
endpoints,
consumers,
self.source.clone(),
None,
None,
)
}
Request::ConnectUi {
owner,
source,
instance,
} => {
if root.is_some() {
return Err("Directory Host peers cannot connect to UI imports".into());
}
let parent = self.ui_parent(owner, &principal)?;
if source.state_domain != self.source.state_domain
|| source.deployment != self.source.deployment
{
return Err("foreign UI deployment source".into());
}
drop(gate.take());
self.store
.read_application_metadata_at(&source)
.await
.map_err(|error| error.to_string())?
.ok_or("UI deployment source not found")?;
let application = self.application.client();
let bindings = tokio::select! {
biased;
() = self.stop.cancelled() => return Err("Host is closing".into()),
() = parent.transport.wait_for_close() => return Err("UI owner session is closing".into()),
bindings = application.capture_ui(source.clone(), instance.clone()) => bindings?,
};
let mut endpoints = BTreeMap::new();
let mut imports = BTreeMap::new();
for (name, providers) in bindings {
let many = providers.len() > 1;
let mut names = Vec::new();
for (index, binding) in providers.into_iter().enumerate() {
let endpoint = if many {
format!("{name}/{index}")
} else {
name.clone()
};
let maka_plugin_core::contract::Interface::Service { methods } =
&binding.contract().interface
else {
return Err("UI import requires a service".into());
};
let grant = super::transport::Grant {
methods: methods.keys().cloned().collect(),
recovery: false,
};
if endpoints
.insert(
endpoint.clone(),
super::transport::Endpoint::new(binding, grant)?,
)
.is_some()
{
return Err("UI import endpoint names collide".into());
}
names.push(endpoint);
}
imports.insert(name, names);
}
let consumers = endpoints
.keys()
.map(|name| (name.clone(), instance.clone()))
.collect();
gate = Some(self.access_gate.lock().await);
if self
.identify(&authority, opening.client_instance.as_deref())
.await?
!= principal
{
return Err("UI owner principal changed".into());
}
self.ui_parent(owner, &principal)?;
(
SessionMode::Ui,
Peer::new(source.clone(), [instance.clone()].into())?,
Endpoints::from(endpoints),
consumers,
source,
Some(protocol::UiConnection { instance, imports }),
Some(owner),
)
}
_ => unreachable!(),
};
let peer = match root {
Some(root) => peer.with_authenticated_root(root.clone()),
None => peer,
};
let id = Uuid::new_v4();
let session = Arc::new(Session {
revoked: AtomicBool::new(false),
principal,
peer: Peers::new(peer),
transport: Server::new(
self.application.client(),
self.policy.clone(),
endpoints,
)?,
mode,
parent,
});
{
let mut sessions = self.sessions.lock().unwrap();
let mut residency = self.residency.lock().unwrap();
if residency.paused || self.stop.is_cancelled() {
return Err("Host admission is paused".into());
}
residency.admitted = true;
sessions.insert(id, session.clone());
}
drop(gate);
let result = async {
let connected = Connected {
version: VERSION,
epoch: self.epoch,
session: id,
source,
consumers,
catalogue: session.transport.catalogue(),
ui,
};
let response = Response::Connected(connected);
tokio::select! {
biased;
() = self.stop.cancelled() => return Err("Host is closing".into()),
() = session.transport.wait_for_close() => return Ok(false),
result = wire::write(&mut output, &response) => result?,
}
let mut captured = None;
loop {
let command = tokio::select! {
biased;
() = self.stop.cancelled() => break Ok(false),
() = session.transport.wait_for_close() => break Ok(false),
result = input.read::<SessionControl>() => result?,
};
if matches!(command, SessionControl::Close) {
break Ok(true);
}
let response = if matches!(command, SessionControl::Refresh) {
let result = async {
let SessionMode::Owned { selections } = &session.mode else {
return Err("Peer sessions require captured approval".into());
};
let application = self.application.client();
let endpoints = tokio::select! {
biased;
() = session.transport.wait_for_close() => return Err("Host session is closing".into()),
endpoints = Endpoints::start(&application, selections) => endpoints?,
};
let catalogue = Catalogue::captured(&endpoints);
wire::encode_bounded(
&Response::Refreshed(Ok(catalogue.clone())),
usize::MAX,
)?;
session.transport.replace_endpoints(endpoints)?;
Ok(catalogue)
}
.await;
Response::Refreshed(result)
} else {
let SessionMode::Peer {
source: origin,
selections,
} = &session.mode
else {
return Err("Host-owned session cannot approve peer sources".into());
};
match command {
SessionControl::Epochs => Response::Epochs(
Endpoints::capture(&self.application.client(), selections)
.await
.map(|endpoints| endpoints.epochs()),
),
SessionControl::Capture => {
captured = None;
let result =
Endpoints::capture(&self.application.client(), selections)
.await
.map(|endpoints| {
let catalogue = Catalogue::captured(&endpoints);
captured = Some(endpoints);
catalogue
});
let response = Response::Captured(result);
if let Err(error) = wire::encode_bounded(&response, usize::MAX)
{
captured = None;
Response::Captured(Err(format!(
"cannot encode Host captured catalogue: {error}"
)))
} else {
response
}
}
SessionControl::Approve {
source,
consumers,
retain,
captured: expected,
} => {
let result = (|| {
source.validate()?;
if source.state_domain != origin.state_domain
|| source.deployment != origin.deployment
{
return Err("foreign approval deployment".into());
}
let approved = if consumers.is_empty() {
None
} else {
Some(Peer::new(source.clone(), consumers)?)
};
if approved.is_none() != expected.is_none() {
return Err(
"approval requires its captured endpoints".into()
);
}
session.peer.check_update(approved.clone(), &retain)?;
if let Some(expected) = expected {
let endpoints = captured
.take()
.ok_or("Host endpoints were not captured")?;
if Catalogue::captured(&endpoints) != expected {
return Err("Host captured endpoints differ".into());
}
session.transport.replace_endpoints(endpoints)?;
}
session.peer.update(approved, &retain)
})();
Response::Approved { source, result }
}
SessionControl::Close | SessionControl::Refresh => unreachable!(),
}
};
tokio::select! {
biased;
() = self.stop.cancelled() => break Ok(false),
() = session.transport.wait_for_close() => break Ok(false),
result = wire::write(&mut output, &response) => result?,
}
}
}
.await;
// Revocation fences late admissions, then the same transport
// drains all original calls before releasing the session.
session.peer.replace(vec![])?;
session.transport.request_close();
// Give a reading peer the reason before closing the anchor,
// but an unreading peer must not hold up session cleanup.
let mut output = Some(output);
if matches!(authority, Authority::AuthenticatedPeer { .. }) && result != Ok(true) {
if session.revoked.load(Ordering::Acquire) {
match tokio::time::timeout(
Duration::from_millis(100),
wire::write(
output.as_mut().expect("live anchor"),
&Response::PeerAccessRevoked,
),
)
.await
{
Ok(Ok(())) => {}
Ok(Err(error)) => {
tracing::debug!(%error, "could not notify revoked peer")
}
Err(_) => tracing::debug!("revoked peer notification timed out"),
}
}
drop(input);
drop(output.take());
}
self.close_ui_children(id).await?;
session.transport.close().await?;
{
let _gate = self.access_gate.lock().await;
self.sessions.lock().unwrap().remove(&id);
}
// EOF or a partial control frame still requests this same
// session's drain. Only the completed cleanup above authorizes
// its acknowledgement; writing that acknowledgement may fail.
if let Some(mut output) = output {
wire::write(&mut output, &Response::Closed).await?;
}
result.map(|_| ())
}
Request::Call { session } => {
let gate = self.access_gate.lock().await;
if self.stop.is_cancelled() || self.residency.lock().unwrap().paused {
return Err("Host admission is closed".into());
}
let principal = self
.identify(&authority, opening.client_instance.as_deref())
.await?;
let session = self
.sessions
.lock()
.unwrap()
.get(&session)
.cloned()
.ok_or("Host session is unavailable")?;
if session.principal != principal {
return Err("Host session belongs to another authenticated principal".into());
}
drop(gate);
tokio::select! {
biased;
() = session.transport.wait_for_close() => return Err("Host session is closing".into()),
result = wire::write(&mut output, &Response::Accepted) => result?,
}
// Carry buffered bytes into the existing bounded transport.
match &session.mode {
SessionMode::Owned { .. } | SessionMode::Ui => {
session
.transport
.serve_owned(input.inner, output, session.peer.clone())?
.await
}
SessionMode::Peer { .. } => {
session
.transport
.serve(input.inner, output, session.peer.clone())?
.await
}
}
}
}
}
fn ui_parent(&self, owner: Uuid, principal: &Principal) -> Result<Arc<Session>> {
self.sessions
.lock()
.unwrap()
.get(&owner)
.filter(|session| {
&session.principal == principal
&& matches!(session.mode, SessionMode::Owned { .. })
&& !session.transport.is_closing()
})
.cloned()
.ok_or("UI binding capture requires a live owner session".into())
}
async fn close_ui_children(&self, owner: Uuid) -> Result<()> {
let children: Vec<_> = {
let _gate = self.access_gate.lock().await;
self.sessions
.lock()
.unwrap()
.iter()
.filter(|(_, session)| session.parent == Some(owner))
.map(|(id, session)| (*id, session.clone()))
.collect()
};
for (_, child) in &children {
child.peer.replace(vec![])?;
child.transport.request_close();
}
for (_, child) in &children {
child.transport.close().await?;
}
let _gate = self.access_gate.lock().await;
let mut sessions = self.sessions.lock().unwrap();
for (id, _) in children {
sessions.remove(&id);
}
Ok(())
}
fn check_peer_selections(&self, selections: &BTreeMap<String, HostEndpoint>) -> Result<()> {
if selections.is_empty() {
return Err("invalid peer endpoint selections".into());
}
let configuration = self.configuration.lock().unwrap();
let Configuration::PublicHost {
endpoints: published,
..
} = &*configuration;
for (name, selection) in selections {
selection.validate()?;
let published = published
.get(name)
.ok_or("Host endpoint is not published")?;
if selection.consumer != published.consumer
|| selection.import != published.import
|| !selection.grant.methods.is_subset(&published.grant.methods)
|| (selection.grant.recovery && !published.grant.recovery)
{
return Err("peer endpoint exceeds the published Host grant".into());
}
}
Ok(())
}
/// Physical transport cleanup precedes Application cleanup and SQL drain.
/// Errors retain this Host and its original Root for the embedding to hold.
pub async fn shutdown(&self) -> Result<()> {
self.accept_closed.cancel();
self.shutdown.get_or_init(|| self.drain()).await.clone()
}
async fn drain(&self) -> Result<()> {
self.stop.cancel();
let sessions: Vec<_> = self.sessions.lock().unwrap().values().cloned().collect();
let mut errors = Vec::new();
for session in sessions {
if let Err(error) = session.peer.replace(vec![]) {
errors.push(error);
}
if let Err(error) = session.transport.close().await {
errors.push(error);
}
}
if let Err(error) = self.application.shutdown().await {
errors.push(error);
}
if let Err(error) = self.access.shutdown().await {
errors.push(error.to_string());
}
if let Err(error) = self.store.shutdown().await {
errors.push(error.to_string());
}
self.sessions.lock().unwrap().clear();
if errors.is_empty() {
Ok(())
} else {
Err(errors.join("; "))
}
}
}