use super::library::LibraryHandle;
use indicatrix_net::messages::{ClientMessage, ErrorMsg, NetError, error_codes};
#[cfg(not(feature = "worker"))]
use indicatrix_net::messages::{PROTOCOL_VERSION, PayloadEncoding, PeerRole, Welcome};
#[cfg(feature = "worker")]
use std::io::Write;
#[cfg(not(feature = "worker"))]
use std::io::{Read, Write};
use std::net::SocketAddr;
#[cfg(feature = "worker")]
mod link;
#[cfg(feature = "worker")]
mod requests;
#[cfg(feature = "worker")]
mod worker;
pub fn report_connection_result(
peer: Option<SocketAddr>,
result: std::thread::Result<Result<(), NetError>>,
) {
match result {
Ok(Ok(())) => {}
Ok(Err(e)) => tracing::warn!("connection {peer:?} ended with an error: {e}"),
Err(_) => tracing::warn!("connection {peer:?} panicked and was dropped"),
}
}
#[cfg(feature = "worker")]
pub(super) const BUILD_MISMATCH_CODE: u32 = error_codes::BUILD_MISMATCH;
pub(super) const NO_RENDER_CAPACITY_CODE: u32 = error_codes::NO_RENDER_CAPACITY;
pub(super) const CONNECTION_LIMIT_REACHED_CODE: u32 = error_codes::CONNECTION_LIMIT_REACHED;
#[cfg(feature = "worker")]
pub use link::{LinkSettings, is_loopback_peer};
#[cfg(feature = "worker")]
pub use requests::{RequestContext, serve_requests};
#[cfg(feature = "worker")]
pub(super) use requests::{TRACE_PANIC_CODE, VALIDATION_FAILED_CODE};
#[cfg(feature = "worker")]
pub use worker::{
ViewerContext, handle_connection, handle_connection_with_gpu, handle_viewer_connection,
local_render_capability, refuse_incompatible_handshake,
};
pub fn refuse_for_capacity<S: Write>(
stream: &mut S,
peer: Option<SocketAddr>,
active: usize,
max: usize,
) {
tracing::info!(
"connection {peer:?}: refusing -- at capacity ({active}/{max} active connections; see --max-connections)"
);
let _ = indicatrix_net::messages::write_message(
stream,
&ErrorMsg {
code: CONNECTION_LIMIT_REACHED_CODE,
message: format!(
"this worker is already handling {max} concurrent connection(s) (--max-connections); try again \
later"
),
request_id: None,
},
);
}
#[allow(
unreachable_patterns,
clippy::match_wildcard_for_single_variants,
reason = "the final arm must stay a wildcard: it matches ClientMessage::RenderRequest and \
ClientMessage::TiltCurvesRequest only when indicatrix-net's `render` feature is on. \
That is a DIFFERENT crate's flag from this one's `worker` -- this crate has no \
feature of its own named `render` at all, so `#[cfg(feature = \"render\")]` inside \
THIS crate is always false regardless of whether indicatrix-net's variants actually \
exist (cargo unifies features workspace-wide, so `apps/indicatrix-cut` turning \
indicatrix-net's `render` on can leave this crate's own `worker` feature off while the \
variants are still genuinely in scope -- confirmed by `cargo check -p indicatrix-worker \
--features worker`, which fails to compile a two-cfg-arm version of this match with \
exactly the \"unexpected cfg condition value: render\" + \"non-exhaustive patterns\" \
pair this comment replaces). Spelling the variants out, as clippy suggests, fails to \
compile in a true library-only build (no other workspace member pulling `render` in \
at all) where neither variant exists; the wildcard is correct in every build. Kept \
as `allow` (not `expect`) because firing is conditional on that feature -- \
unconditionally expecting it would warn on every build where the variants ARE \
nameable."
)]
pub fn handle_non_render_message<S: Write>(
stream: &mut S,
msg: &ClientMessage,
db: Option<&LibraryHandle>,
) -> Result<(), NetError> {
match msg {
ClientMessage::Cancel(c) => {
tracing::debug!(
"received CANCEL for request_id={} with no request currently streaming on this connection -- ignoring",
c.request_id
);
Ok(())
}
ClientMessage::Library(req) => {
let response = db.map_or_else(
|| {
indicatrix_net::library::LibraryResponse::Error(ErrorMsg {
code: NO_RENDER_CAPACITY_CODE,
message: "this connection is a joined render worker's; the design library \
is served by the coordinator"
.to_string(),
request_id: None,
})
},
|library| library.handle(req),
);
indicatrix_net::messages::write_message(stream, &response)
}
_ => {
tracing::warn!(
"received a RenderRequest or TiltCurvesRequest, but this worker advertises no \
render/tilt-curve capacity (built without its `worker` feature) -- replying \
with a protocol error"
);
indicatrix_net::messages::write_message(
stream,
&indicatrix_net::messages::StreamEvent::Error(indicatrix_net::messages::ErrorMsg {
code: NO_RENDER_CAPACITY_CODE,
message: "this worker serves the design library only and cannot render or \
compute tilt curves; its WELCOME advertises both capacities as \
absent"
.to_string(),
request_id: None,
}),
)
}
}
}
#[cfg(not(feature = "worker"))]
fn is_idle_timeout(e: &std::io::Error) -> bool {
matches!(
e.kind(),
std::io::ErrorKind::WouldBlock
| std::io::ErrorKind::TimedOut
| std::io::ErrorKind::WriteZero
)
}
#[cfg(not(feature = "worker"))]
fn serve_until_render_request_or_eof<S: Read + Write>(
stream: &mut S,
db: &LibraryHandle,
) -> Result<Option<std::convert::Infallible>, NetError> {
loop {
let msg: ClientMessage = match indicatrix_net::messages::read_control_message(stream) {
Ok(m) => m,
Err(NetError::Framing(indicatrix_net::framing::FramingError::Io(e)))
if e.kind() == std::io::ErrorKind::UnexpectedEof =>
{
return Ok(None);
}
Err(NetError::Framing(indicatrix_net::framing::FramingError::Io(e)))
if is_idle_timeout(&e) =>
{
tracing::info!(
"closing a library-only connection that sent nothing for {} s (idle timeout)",
indicatrix_net::framing::IDLE_READ_TIMEOUT.as_secs()
);
return Ok(None);
}
Err(e) => return Err(e),
};
handle_non_render_message(stream, &msg, Some(db))?;
}
}
#[cfg(not(feature = "worker"))]
pub trait ClearHandshakeTimeout {
fn clear_handshake_timeout(&mut self);
}
#[cfg(not(feature = "worker"))]
impl ClearHandshakeTimeout for std::net::TcpStream {
fn clear_handshake_timeout(&mut self) {
let _ = self.set_read_timeout(Some(indicatrix_net::framing::IDLE_READ_TIMEOUT));
let _ = self.set_write_timeout(None);
}
}
#[cfg(not(feature = "worker"))]
impl ClearHandshakeTimeout for rustls::StreamOwned<rustls::ServerConnection, std::net::TcpStream> {
fn clear_handshake_timeout(&mut self) {
let _ = self
.sock
.set_read_timeout(Some(indicatrix_net::framing::IDLE_READ_TIMEOUT));
let _ = self.sock.set_write_timeout(None);
}
}
#[cfg(not(feature = "worker"))]
pub fn handle_connection<S: Read + Write + ClearHandshakeTimeout>(
mut stream: S,
db: &LibraryHandle,
cert_role: Option<PeerRole>,
) -> Result<(), NetError> {
let check = super::handshake::read_and_check_hello(&mut stream, PeerRole::Viewer, cert_role)?;
stream.clear_handshake_timeout();
match check {
super::handshake::HelloCheck::Accepted(hello) => tracing::debug!(
"library-only pairing; the viewer's payload encodings {:?} are moot here \
(no radiance ever flows)",
hello.accept_encodings
),
super::handshake::HelloCheck::Refused(refusal) => {
super::handshake::send_refusal(&mut stream, &refusal);
return Ok(());
}
}
let welcome = Welcome {
protocol_version: PROTOCOL_VERSION,
build_hash: indicatrix_net::handshake::UNKNOWN_BUILD_HASH,
source_hash: indicatrix_net::handshake::UNKNOWN_BUILD_HASH,
render: None,
library: true,
tilt_curves: false,
registration: None,
payload_encoding: PayloadEncoding::Raw,
};
indicatrix_net::messages::write_message(&mut stream, &welcome)?;
serve_until_render_request_or_eof(&mut stream, db)?.map_or(Ok(()), |never| match never {})
}