use super::{
BUILD_MISMATCH_CODE, NO_RENDER_CAPACITY_CODE, handle_non_render_message,
link::LinkSettings,
requests::{RequestContext, serve_requests, write_pong},
};
use crate::{
assets::AssetCache,
cli::ComputeMode,
coordinator::{Coordinator, Registry, ViewerSession, viewer_render_capability},
render_core,
serve::library::LibraryHandle,
stream_emit::{self, TimeoutRead, TimeoutWrite, is_stream_timeout},
validate,
};
use indicatrix::renderer::gpu_backend::GpuBackend;
use indicatrix_net::{
framing::{FramingError, IDLE_READ_TIMEOUT},
handshake,
messages::{
Backend, ClientMessage, ErrorMsg, Hello, LOOPBACK_SERVER_PREFERENCE, NetError,
PROTOCOL_VERSION, PayloadEncoding, PeerRole, RenderCapability, StreamEvent,
TiltCurvesResponse, Welcome, adaptive::PeerLink, negotiate,
},
};
use std::{
io::{Read, Write},
sync::Arc,
};
pub struct ViewerContext<'a> {
pub threads: usize,
pub gpu: &'a Arc<GpuBackend>,
pub db: &'a LibraryHandle,
pub compute_mode: ComputeMode,
pub encodings: &'a [PayloadEncoding],
pub link: Option<LinkSettings>,
pub own_lane: bool,
pub registry: Option<&'a Arc<Registry>>,
pub cert_role: Option<PeerRole>,
pub coordinator: Option<(&'a Arc<Coordinator>, String)>,
pub assets: Option<&'a AssetCache>,
}
pub fn handle_connection<S: Read + Write + TimeoutRead + TimeoutWrite>(
stream: S,
threads: usize,
db: &LibraryHandle,
) -> Result<(), NetError> {
handle_connection_with_gpu(
stream,
threads,
&Arc::new(GpuBackend::disabled()),
db,
ComputeMode::OnlyCpu,
&LOOPBACK_SERVER_PREFERENCE,
)
}
pub fn handle_connection_with_gpu<S: Read + Write + TimeoutRead + TimeoutWrite>(
stream: S,
threads: usize,
gpu: &Arc<GpuBackend>,
db: &LibraryHandle,
compute_mode: ComputeMode,
encodings: &[PayloadEncoding],
) -> Result<(), NetError> {
handle_viewer_connection(
stream,
&ViewerContext {
threads,
gpu,
db,
compute_mode,
encodings,
link: None,
own_lane: true,
registry: None,
cert_role: None,
coordinator: None,
assets: None,
},
)
}
pub fn handle_viewer_connection<S: Read + Write + TimeoutRead + TimeoutWrite>(
mut stream: S,
ctx: &ViewerContext<'_>,
) -> Result<(), NetError> {
let check = crate::serve::handshake::read_and_check_hello(
&mut stream,
PeerRole::Viewer,
ctx.cert_role,
)?;
let _ = stream.set_read_timeout(Some(IDLE_READ_TIMEOUT));
let _ = stream.set_write_timeout(None);
let remote_hello = match check {
crate::serve::handshake::HelloCheck::Accepted(hello) => hello,
crate::serve::handshake::HelloCheck::Refused(refusal) => {
crate::serve::handshake::send_refusal(&mut stream, &refusal);
return Ok(());
}
};
let local_hello = handshake::local_hello();
if let Some(result) =
pair_as_library_only_if_unknown_build(&mut stream, &local_hello, &remote_hello, ctx.db)
{
return result;
}
if let Err(incompatible) = handshake::verify_compatible(&local_hello, &remote_hello) {
refuse_incompatible_handshake(&mut stream, &local_hello, &remote_hello, incompatible);
return Ok(());
}
let payload_encoding = negotiate(ctx.encodings, &remote_hello.accept_encodings);
let link = ctx.link.as_ref().map_or_else(
|| Arc::new(PeerLink::fixed(payload_encoding)),
|settings| settings.open(&remote_hello.accept_encodings),
);
let own = ctx.own_lane.then(|| RenderCapability {
hdr: ctx.assets.is_some(),
..local_render_capability(ctx.gpu, ctx.threads)
});
let render = viewer_render_capability(
own.as_ref(),
ctx.registry.map(|registry| registry.capacity()),
ctx.assets.is_some(),
);
let welcome = Welcome {
protocol_version: PROTOCOL_VERSION,
build_hash: local_hello.build_hash,
source_hash: local_hello.source_hash,
tilt_curves: render.is_some(),
render: render.clone(),
library: true,
registration: None,
payload_encoding,
};
indicatrix_net::messages::write_message(&mut stream, &welcome)?;
let session = ctx
.coordinator
.as_ref()
.map(|(coordinator, viewer)| ViewerSession {
coordinator: Arc::clone(coordinator),
viewer: Arc::from(viewer.as_str()),
payload_encoding,
link: Some(Arc::clone(&link)),
advertised: render,
own_capability: own,
rates: Arc::clone(coordinator.rates()),
});
serve_requests(
&mut stream,
&RequestContext {
threads: ctx.threads,
gpu: ctx.gpu,
db: Some(ctx.db),
compute_mode: ctx.compute_mode,
payload_encoding,
link: Some(&link),
own_lane: ctx.own_lane,
session: session.as_ref(),
assets: ctx.assets,
},
)
}
#[must_use]
pub fn local_render_capability(gpu: &GpuBackend, threads: usize) -> RenderCapability {
let _ = gpu.try_recover();
let backend = gpu.adapter_label().map_or_else(
|| Backend::Cpu {
threads: render_core::effective_thread_count(threads) as u32,
},
|adapter| Backend::Gpu { adapter },
);
RenderCapability {
backend,
max_pixels: validate::MAX_PIXELS,
min_cadence_ms: stream_emit::MIN_CADENCE_FLOOR_MS,
hdr: false,
}
}
pub fn refuse_incompatible_handshake<S: Write>(
stream: &mut S,
local_hello: &Hello,
remote_hello: &Hello,
incompatible: handshake::Incompatible,
) {
let message = format!(
"refusing to pair: this side build_hash={:02x?} protocol_version={}, peer build_hash={:02x?} \
protocol_version={} ({incompatible})",
local_hello.build_hash,
local_hello.protocol_version,
remote_hello.build_hash,
remote_hello.protocol_version
);
tracing::warn!("{message}");
let _ = indicatrix_net::messages::write_message(
stream,
&ErrorMsg {
code: BUILD_MISMATCH_CODE,
message,
request_id: None,
},
);
}
fn pair_as_library_only_if_unknown_build<S: Read + Write + TimeoutRead>(
stream: &mut S,
local_hello: &Hello,
remote_hello: &Hello,
db: &LibraryHandle,
) -> Option<Result<(), NetError>> {
if remote_hello.protocol_version != local_hello.protocol_version
|| remote_hello.build_hash != handshake::UNKNOWN_BUILD_HASH
{
return None;
}
let welcome = Welcome {
protocol_version: PROTOCOL_VERSION,
build_hash: local_hello.build_hash,
source_hash: local_hello.source_hash,
render: None,
library: true,
tilt_curves: false,
registration: None,
payload_encoding: PayloadEncoding::Raw,
};
Some(
indicatrix_net::messages::write_message(stream, &welcome)
.and_then(|()| serve_library_only_connection(stream, db)),
)
}
fn no_render_capacity(what: &str, request_id: u32) -> ErrorMsg {
ErrorMsg {
code: NO_RENDER_CAPACITY_CODE,
message: format!(
"this connection was paired as library-only (HELLO reported no indicatrix build) and cannot {what}"
),
request_id: Some(request_id),
}
}
fn serve_library_only_connection<S: Read + Write + TimeoutRead>(
stream: &mut S,
db: &LibraryHandle,
) -> Result<(), NetError> {
loop {
let _ = stream.set_read_timeout(Some(IDLE_READ_TIMEOUT));
let msg: ClientMessage = match indicatrix_net::messages::read_control_message(stream) {
Ok(m) => m,
Err(NetError::Framing(FramingError::Io(e)))
if e.kind() == std::io::ErrorKind::UnexpectedEof =>
{
return Ok(());
}
Err(NetError::Framing(FramingError::Io(e))) if is_stream_timeout(&e) => {
tracing::info!(
"closing a library-only connection that sent nothing for {} s (idle timeout)",
IDLE_READ_TIMEOUT.as_secs()
);
return Ok(());
}
Err(e) => return Err(e),
};
match msg {
ClientMessage::RenderRequest(r) => indicatrix_net::messages::write_stream_event(
stream,
&StreamEvent::Error(no_render_capacity("render", r.request_id)),
None,
)?,
ClientMessage::TiltCurvesRequest(r) => indicatrix_net::messages::write_message(
stream,
&TiltCurvesResponse::Error(no_render_capacity("compute tilt curves", r.request_id)),
)?,
ClientMessage::FinalImageRequest(r) => indicatrix_net::messages::write_stream_event(
stream,
&StreamEvent::Error(no_render_capacity("render a final image", r.request_id)),
None,
)?,
ClientMessage::Ping { nonce } => write_pong(stream, nonce)?,
ClientMessage::Asset(header) => crate::assets::discard_asset(stream, &header)?,
ClientMessage::Contribution(header) => {
indicatrix_net::messages::discard_contribution_payload(stream, &header)?;
}
other @ (ClientMessage::Cancel(_) | ClientMessage::Library(_)) => {
handle_non_render_message(stream, &other, Some(db))?;
}
}
}
}