1mod client;
13mod endpoint;
14mod protocol;
15mod select;
16mod server;
17pub mod wait;
18
19use std::time::Duration;
20
21#[cfg(unix)]
22use futures::{SinkExt, StreamExt};
23#[cfg(unix)]
24use serde::Serialize;
25#[cfg(unix)]
26use serde::de::DeserializeOwned;
27#[cfg(unix)]
28use tokio::io::{AsyncRead, AsyncWrite};
29use tokio_util::codec::LinesCodecError;
30#[cfg(unix)]
31use tokio_util::codec::{Framed, LinesCodec};
32
33pub use client::{
34 Client, EndpointProbe, EndpointProbeResult, Subscription, answering_session_probes,
35 probe_endpoint, probe_endpoints, probe_runtime_dir, probe_runtime_dirs,
36 unique_answering_session_probes,
37};
38#[cfg(unix)]
39pub use endpoint::coordination_dir;
40pub use endpoint::{
41 CanonicalConfigPath, ControlEndpoint, RuntimeDirStatus, coordination_dir_in, endpoint_for,
42 endpoint_from_hash, endpoint_hash, runtime_dir, runtime_dir_in, runtime_dir_statuses,
43 transport_supported, usable_runtime_dirs,
44};
45pub use micromux::{
46 DynamicServiceAck, ReconcileAction, ReconcileActionKind, ReconcileReceipt, ResolvedEnvironment,
47};
48pub use protocol::{
49 DiskLogReadHealth, DynamicServicesCaps, ENVIRONMENT_PROTOCOL_VERSION, EVENTS_PROTOCOL_VERSION,
50 ErrorCode, InputBytes, MAX_REMOTE_PASTE_BYTES, PROTOCOL_VERSION, ProtocolVersion, Request,
51 Response, SESSION_ENV_FILE_PROTOCOL_VERSION, ServiceBrief, SessionCapabilities, SessionInfo,
52 TERMINAL_PROTOCOL_VERSION,
53};
54pub use select::{
55 AmbiguousSelection, LISTED_ABSENT_PROBES, ProbeReport, ResolvedSession, RuntimeDirDetail,
56 SelectError, SessionSelector, SocketProbeDetail, SocketProbeDetails, SocketProbeStatus,
57 config_for_target, probe_detail, resolve_selector, resolve_selector_in_runtime_dirs,
58 resolve_selector_with_statuses, session_config_path_is_under, session_matches_config_path,
59};
60pub use server::{
61 ClaimError, ControlServer, EndpointGuard, ProjectClaim, SESSION_ALREADY_STARTING,
62 SessionIdentity, UnclaimedProject, bind, bind_project, claim_project, endpoint_owner_lock_held,
63 hold_unclaimed_project,
64};
65#[cfg(unix)]
66pub use server::{claim_project_at, hold_unclaimed_project_at};
67
68pub const MAX_FRAME_BYTES: usize = 1024 * 1024;
71
72pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
74
75pub const PROBE_TIMEOUT: Duration = Duration::from_secs(2);
80
81pub const IDLE_TIMEOUT: Duration = Duration::from_mins(5);
85
86pub const SUBSCRIPTION_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(30);
88
89pub const SUBSCRIPTION_READ_TIMEOUT: Duration = Duration::from_secs(75);
91
92#[derive(thiserror::Error, Debug)]
94pub enum ControlError {
95 #[error(transparent)]
97 Io(#[from] std::io::Error),
98 #[error("control protocol serialization error: {0}")]
100 Serde(#[from] serde_json::Error),
101 #[error("the control plane is not supported on this platform")]
103 Unsupported,
104 #[error("control connection closed")]
106 Closed,
107 #[error("control protocol frame exceeded the maximum size")]
109 FrameTooLarge,
110 #[error("control request timed out")]
112 Timeout,
113 #[error("control protocol version mismatch: peer={peer}, ours={ours}")]
115 ProtocolMismatch {
116 peer: ProtocolVersion,
118 ours: ProtocolVersion,
120 },
121 #[error("unexpected control response: {0}")]
123 Unexpected(String),
124}
125
126impl From<LinesCodecError> for ControlError {
127 fn from(err: LinesCodecError) -> Self {
128 match err {
129 LinesCodecError::MaxLineLengthExceeded => Self::FrameTooLarge,
130 LinesCodecError::Io(err) => Self::Io(err),
131 }
132 }
133}
134
135#[cfg(unix)]
136type Framing<T> = Framed<T, LinesCodec>;
137
138#[cfg(unix)]
139fn framed<T: AsyncRead + AsyncWrite>(io: T) -> Framing<T> {
140 Framed::new(io, LinesCodec::new_with_max_length(MAX_FRAME_BYTES))
141}
142
143#[cfg(unix)]
144async fn write_message<T, M>(framing: &mut Framing<T>, message: &M) -> Result<(), ControlError>
145where
146 T: AsyncRead + AsyncWrite + Unpin,
147 M: Serialize,
148{
149 let line = serde_json::to_string(message)?;
150 if line.len() > MAX_FRAME_BYTES {
151 return Err(ControlError::FrameTooLarge);
152 }
153 framing.send(line).await?;
154 Ok(())
155}
156
157#[cfg(unix)]
158async fn read_message<T, M>(framing: &mut Framing<T>) -> Result<Option<M>, ControlError>
159where
160 T: AsyncRead + AsyncWrite + Unpin,
161 M: DeserializeOwned,
162{
163 match framing.next().await {
164 Some(Ok(line)) => Ok(Some(serde_json::from_str(&line)?)),
165 Some(Err(err)) => Err(err.into()),
166 None => Ok(None),
167 }
168}
169
170#[cfg(all(test, unix))]
171mod tests {
172 use std::assert_matches;
173
174 use super::{ControlError, MAX_FRAME_BYTES, framed, write_message};
175
176 #[tokio::test]
177 async fn encode_rejects_a_frame_over_the_protocol_limit() {
178 let (stream, _peer) = tokio::io::duplex(64);
179 let mut conn = framed(stream);
180 let oversized = "x".repeat(MAX_FRAME_BYTES);
181
182 assert_matches!(
183 write_message(&mut conn, &oversized).await,
184 Err(ControlError::FrameTooLarge)
185 );
186 }
187}