mod client;
mod endpoint;
mod protocol;
mod select;
mod server;
pub mod wait;
use std::time::Duration;
#[cfg(unix)]
use futures::{SinkExt, StreamExt};
#[cfg(unix)]
use serde::Serialize;
#[cfg(unix)]
use serde::de::DeserializeOwned;
#[cfg(unix)]
use tokio::io::{AsyncRead, AsyncWrite};
use tokio_util::codec::LinesCodecError;
#[cfg(unix)]
use tokio_util::codec::{Framed, LinesCodec};
pub use client::{
Client, EndpointProbe, EndpointProbeResult, Subscription, answering_session_probes,
probe_endpoint, probe_endpoints, probe_runtime_dir, probe_runtime_dirs,
unique_answering_session_probes,
};
#[cfg(unix)]
pub use endpoint::coordination_dir;
pub use endpoint::{
CanonicalConfigPath, ControlEndpoint, RuntimeDirStatus, coordination_dir_in, endpoint_for,
endpoint_from_hash, endpoint_hash, runtime_dir, runtime_dir_in, runtime_dir_statuses,
transport_supported, usable_runtime_dirs,
};
pub use micromux::{
DynamicServiceAck, ReconcileAction, ReconcileActionKind, ReconcileReceipt, ResolvedEnvironment,
};
pub use protocol::{
DiskLogReadHealth, DynamicServicesCaps, ENVIRONMENT_PROTOCOL_VERSION, EVENTS_PROTOCOL_VERSION,
ErrorCode, InputBytes, MAX_REMOTE_PASTE_BYTES, PROTOCOL_VERSION, ProtocolVersion, Request,
Response, ServiceBrief, SessionCapabilities, SessionInfo, TERMINAL_PROTOCOL_VERSION,
};
pub use select::{
AmbiguousSelection, LISTED_ABSENT_PROBES, ProbeReport, ResolvedSession, RuntimeDirDetail,
SelectError, SessionSelector, SocketProbeDetail, SocketProbeDetails, SocketProbeStatus,
config_for_target, probe_detail, resolve_selector, resolve_selector_in_runtime_dirs,
resolve_selector_with_statuses, session_config_path_is_under, session_matches_config_path,
};
#[cfg(unix)]
pub use server::claim_project_at;
pub use server::{
ClaimError, ControlServer, EndpointGuard, ProjectClaim, SESSION_ALREADY_STARTING,
SessionIdentity, bind, bind_project, claim_project, endpoint_owner_lock_held,
};
pub const MAX_FRAME_BYTES: usize = 1024 * 1024;
pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
pub const PROBE_TIMEOUT: Duration = Duration::from_secs(2);
pub const IDLE_TIMEOUT: Duration = Duration::from_mins(5);
pub const SUBSCRIPTION_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(30);
pub const SUBSCRIPTION_READ_TIMEOUT: Duration = Duration::from_secs(75);
#[derive(thiserror::Error, Debug)]
pub enum ControlError {
#[error(transparent)]
Io(#[from] std::io::Error),
#[error("control protocol serialization error: {0}")]
Serde(#[from] serde_json::Error),
#[error("the control plane is not supported on this platform")]
Unsupported,
#[error("control connection closed")]
Closed,
#[error("control protocol frame exceeded the maximum size")]
FrameTooLarge,
#[error("control request timed out")]
Timeout,
#[error("control protocol version mismatch: peer={peer}, ours={ours}")]
ProtocolMismatch {
peer: ProtocolVersion,
ours: ProtocolVersion,
},
#[error("unexpected control response: {0}")]
Unexpected(String),
}
impl From<LinesCodecError> for ControlError {
fn from(err: LinesCodecError) -> Self {
match err {
LinesCodecError::MaxLineLengthExceeded => Self::FrameTooLarge,
LinesCodecError::Io(err) => Self::Io(err),
}
}
}
#[cfg(unix)]
type Framing<T> = Framed<T, LinesCodec>;
#[cfg(unix)]
fn framed<T: AsyncRead + AsyncWrite>(io: T) -> Framing<T> {
Framed::new(io, LinesCodec::new_with_max_length(MAX_FRAME_BYTES))
}
#[cfg(unix)]
async fn write_message<T, M>(framing: &mut Framing<T>, message: &M) -> Result<(), ControlError>
where
T: AsyncRead + AsyncWrite + Unpin,
M: Serialize,
{
let line = serde_json::to_string(message)?;
if line.len() > MAX_FRAME_BYTES {
return Err(ControlError::FrameTooLarge);
}
framing.send(line).await?;
Ok(())
}
#[cfg(unix)]
async fn read_message<T, M>(framing: &mut Framing<T>) -> Result<Option<M>, ControlError>
where
T: AsyncRead + AsyncWrite + Unpin,
M: DeserializeOwned,
{
match framing.next().await {
Some(Ok(line)) => Ok(Some(serde_json::from_str(&line)?)),
Some(Err(err)) => Err(err.into()),
None => Ok(None),
}
}
#[cfg(all(test, unix))]
mod tests {
use std::assert_matches;
use super::{ControlError, MAX_FRAME_BYTES, framed, write_message};
#[tokio::test]
async fn encode_rejects_a_frame_over_the_protocol_limit() {
let (stream, _peer) = tokio::io::duplex(64);
let mut conn = framed(stream);
let oversized = "x".repeat(MAX_FRAME_BYTES);
assert_matches!(
write_message(&mut conn, &oversized).await,
Err(ControlError::FrameTooLarge)
);
}
}