use std::io::{self, Read, Write};
use alpha2_model::SuppliedFile;
use serde::{Deserialize, Serialize};
use super::{CANCELLED, PLUGIN_CODES, PluginError};
pub const MAGIC: [u8; 8] = *b"A2PLUGW\n";
pub const WIRE_VERSION: u32 = 2;
pub const MAX_PREAMBLE_BYTES: usize = 4096;
pub const MAX_CHILD_FRAME_BYTES: usize = 4 << 20;
const MAX_HEADER_BYTES: usize = 4096;
#[expect(
clippy::cast_possible_truncation,
reason = "256 MiB fits a 32-bit usize"
)]
pub const MAX_HOST_FRAME_BYTES: usize =
alpha2_media::MAX_FRAME_PIXELS as usize * 4 + MAX_HEADER_BYTES;
pub mod host {
pub const LOAD: u8 = 1;
pub const DESCRIBE: u8 = 2;
pub const BEGIN: u8 = 3;
pub const PASS: u8 = 4;
pub const VIDEO: u8 = 5;
pub const AUDIO: u8 = 6;
pub const END: u8 = 7;
pub const SHUTDOWN: u8 = 8;
pub const REGION: u8 = 9;
pub const VIDEO_SHARED: u8 = 10;
}
pub mod child {
pub const HELLO: u8 = 0x40;
pub const LOG: u8 = 0x41;
pub const RESOURCE_READ: u8 = 0x42;
pub const RESOURCE_FAILED: u8 = 0x43;
pub const RECORDS: u8 = 0x44;
pub const REFUSED: u8 = 0x45;
pub const LOADED: u8 = 0x46;
pub const LOAD_FAILED: u8 = 0x47;
pub const DESCRIBED: u8 = 0x48;
pub const RETURNED: u8 = 0x49;
pub const REGION_MAPPED: u8 = 0x4A;
pub const REGION_FAILED: u8 = 0x4B;
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
pub struct Hello {
pub wire: u32,
pub host_core: String,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
pub struct Failure {
pub code: String,
pub message: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub details: Option<serde_json::Map<String, serde_json::Value>>,
}
impl From<&PluginError> for Failure {
fn from(error: &PluginError) -> Self {
Self {
code: error.code.to_owned(),
message: error.message.clone(),
details: error.details.clone(),
}
}
}
impl Failure {
#[must_use]
pub fn into_error(self) -> Option<PluginError> {
let code = PLUGIN_CODES
.iter()
.chain(&[CANCELLED])
.find(|code| **code == self.code)?;
let error = PluginError::new(code, self.message);
Some(match self.details {
Some(details) => error.with_details(details),
None => error,
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum WireError {
Closed {
clean: bool,
},
Oversized(usize),
Malformed(String),
Io(String),
}
impl std::fmt::Display for WireError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Closed { clean: true } => formatter.write_str("the stream ended"),
Self::Closed { clean: false } => formatter.write_str("a frame was cut short"),
Self::Oversized(length) => write!(formatter, "a frame of {length} bytes"),
Self::Malformed(why) => formatter.write_str(why),
Self::Io(error) => formatter.write_str(error),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Frame {
pub tag: u8,
pub payload: Vec<u8>,
}
pub fn read_frame(reader: &mut impl Read, max: usize) -> Result<Frame, WireError> {
let mut header = [0; 5];
let mut filled = 0;
while filled < header.len() {
match reader.read(&mut header[filled..]) {
Ok(0) => return Err(WireError::Closed { clean: filled == 0 }),
Ok(read) => filled += read,
Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
Err(error) => return Err(WireError::Io(error.to_string())),
}
}
let length = u32::from_le_bytes([header[0], header[1], header[2], header[3]]);
let length = usize::try_from(length).unwrap_or(usize::MAX);
if length > max {
return Err(WireError::Oversized(length));
}
let mut payload = Vec::new();
payload
.try_reserve_exact(length)
.map_err(|error| WireError::Io(error.to_string()))?;
reader
.take(length as u64)
.read_to_end(&mut payload)
.map_err(|error| WireError::Io(error.to_string()))?;
if payload.len() < length {
return Err(WireError::Closed { clean: false });
}
Ok(Frame {
tag: header[4],
payload,
})
}
pub fn write_frame(writer: &mut impl Write, tag: u8, parts: &[&[u8]]) -> io::Result<()> {
let length = parts.iter().map(|part| part.len()).sum::<usize>();
let length = u32::try_from(length)
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "a frame past 4 GiB"))?;
let mut header = [0; 5];
header[..4].copy_from_slice(&length.to_le_bytes());
header[4] = tag;
writer.write_all(&header)?;
for part in parts {
writer.write_all(part)?;
}
writer.flush()
}
pub fn skip_to_magic(reader: &mut impl Read) -> Result<(), WireError> {
let mut window = [0_u8; MAGIC.len()];
let mut seen = 0_usize;
let mut byte = [0];
while seen < MAX_PREAMBLE_BYTES + MAGIC.len() {
match reader.read(&mut byte) {
Ok(0) => return Err(WireError::Closed { clean: true }),
Ok(_) => {}
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
Err(error) => return Err(WireError::Io(error.to_string())),
}
window.copy_within(1.., 0);
window[MAGIC.len() - 1] = byte[0];
seen += 1;
if seen >= MAGIC.len() && window == MAGIC {
return Ok(());
}
}
Err(WireError::Malformed(format!(
"no worker magic in the first {MAX_PREAMBLE_BYTES} bytes"
)))
}
#[derive(Clone, Debug, PartialEq)]
pub enum ChildMessage {
Hello(Hello),
Log {
level: u32,
text: Vec<u8>,
},
ResourceRead(SuppliedFile),
ResourceFailed(Failure),
Records(Vec<u8>),
Refused(String),
Loaded {
sequence: u32,
},
LoadFailed {
sequence: u32,
failure: Failure,
},
Described {
sequence: u32,
descriptor: Vec<u8>,
},
RegionMapped {
sequence: u32,
},
RegionFailed {
sequence: u32,
failure: Failure,
},
Returned {
sequence: u32,
status: i32,
fail: Option<Vec<u8>>,
},
}
impl ChildMessage {
#[must_use]
pub const fn sequence(&self) -> Option<u32> {
match self {
Self::Loaded { sequence }
| Self::LoadFailed { sequence, .. }
| Self::Described { sequence, .. }
| Self::RegionMapped { sequence }
| Self::RegionFailed { sequence, .. }
| Self::Returned { sequence, .. } => Some(*sequence),
_ => None,
}
}
}
fn malformed(what: &str) -> WireError {
WireError::Malformed(format!("a malformed {what} frame"))
}
fn split_u32(payload: &[u8], what: &str) -> Result<(u32, Vec<u8>), WireError> {
let (head, rest) = payload
.split_first_chunk::<4>()
.ok_or_else(|| malformed(what))?;
Ok((u32::from_le_bytes(*head), rest.to_vec()))
}
fn json<T: for<'de> Deserialize<'de>>(payload: &[u8], what: &str) -> Result<T, WireError> {
serde_json::from_slice(payload).map_err(|_| malformed(what))
}
fn is_sha256_hex(text: &str) -> bool {
text.len() == 64
&& text
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}
pub fn parse_child(frame: Frame) -> Result<ChildMessage, WireError> {
let Frame { tag, payload } = frame;
Ok(match tag {
child::HELLO => ChildMessage::Hello(json(&payload, "hello")?),
child::LOG => {
let (level, text) = split_u32(&payload, "log")?;
ChildMessage::Log { level, text }
}
child::RESOURCE_READ => {
let file: SuppliedFile = json(&payload, "resource_read")?;
if !is_sha256_hex(&file.sha256) || file.name.is_empty() {
return Err(malformed("resource_read"));
}
ChildMessage::ResourceRead(file)
}
child::RESOURCE_FAILED => ChildMessage::ResourceFailed(json(&payload, "resource_failed")?),
child::RECORDS => ChildMessage::Records(payload),
child::REFUSED => ChildMessage::Refused(String::from_utf8_lossy(&payload).into_owned()),
child::LOADED if payload.len() == 4 => ChildMessage::Loaded {
sequence: split_u32(&payload, "loaded")?.0,
},
child::LOAD_FAILED => {
let (sequence, failure) = split_u32(&payload, "load_failed")?;
ChildMessage::LoadFailed {
sequence,
failure: json(&failure, "load_failed")?,
}
}
child::DESCRIBED => {
let (sequence, descriptor) = split_u32(&payload, "described")?;
ChildMessage::Described {
sequence,
descriptor,
}
}
child::REGION_MAPPED if payload.len() == 4 => ChildMessage::RegionMapped {
sequence: split_u32(&payload, "region_mapped")?.0,
},
child::REGION_FAILED => {
let (sequence, failure) = split_u32(&payload, "region_failed")?;
ChildMessage::RegionFailed {
sequence,
failure: json(&failure, "region_failed")?,
}
}
child::RETURNED => {
let (sequence, rest) = split_u32(&payload, "returned")?;
let (status, fail) = split_u32(&rest, "returned")?;
ChildMessage::Returned {
sequence,
status: status.cast_signed(),
fail: (!fail.is_empty()).then_some(fail),
}
}
other => {
return Err(WireError::Malformed(format!(
"a frame with the unknown tag {other}"
)));
}
})
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub(super) struct Load {
pub(super) library: std::path::PathBuf,
pub(super) sha256: String,
pub(super) check: bool,
pub(super) caps: Vec<(String, usize)>,
pub(super) resources: super::resources::ResourceSet,
}
pub(super) fn record_runs(batch: &[u8]) -> Vec<&[u8]> {
let mut runs = Vec::new();
let (mut start, mut at) = (0, 0);
while at < batch.len() {
let body = batch
.get(at + 4..at + 8)
.and_then(|length| <[u8; 4]>::try_from(length).ok())
.map_or(usize::MAX, |length| {
usize::try_from(u32::from_le_bytes(length)).unwrap_or(usize::MAX)
});
let next = at.saturating_add(8).saturating_add(body).min(batch.len());
if next - start > MAX_CHILD_FRAME_BYTES && at > start {
runs.push(&batch[start..at]);
start = at;
}
at = next;
}
if start < batch.len() {
runs.push(&batch[start..]);
}
runs
}