Skip to main content

mln_engine/worker/worker_codec/
envelope.rs

1// Port-only: the frames that cross between the map side and a worker
2// instance (mod.rs), and how they are encoded.
3//
4// Every frame is one job's: a `Run` to a worker, a `Reply` back. It starts
5// with the job's id as a fixed header, read without the shared tables, and
6// has its body after it: a worker that can't decode a body replies `Failed`
7// with the header's id, and the map side drops a stale reply after reading
8// only its id.
9
10use std::time::Duration;
11
12use mln_style::tile_id::CanonicalTileID;
13use mln_wire::payload::Payload;
14use mln_wire::{Context, Reader, Wire, Writer};
15
16use crate::tile::OverscaledTileID;
17use crate::worker::job::{JobId, JobTimes, SourceKey, TileKey};
18
19/// A frame as it crosses between instances: its bytes, and the byte arrays
20/// that travel beside them (`mln_wire::payload`), which a host can transfer
21/// rather than copy.
22#[derive(Clone, Debug, Default, PartialEq, Eq)]
23pub struct Encoded {
24    pub bytes: Vec<u8>,
25    pub payloads: Vec<Payload>,
26}
27
28impl From<Vec<u8>> for Encoded {
29    /// A frame without payloads.
30    fn from(bytes: Vec<u8>) -> Self {
31        Encoded { bytes, payloads: Vec::new() }
32    }
33}
34
35/// The size of a `JobId` in a header.
36const JOB_ID_SIZE: usize = 8 + 1 + 2 + 1 + 4 + 4 + 8;
37
38/// Appends a job frame's header: `id`.
39pub(crate) fn write_job_header(bytes: &mut Vec<u8>, id: &JobId) {
40    let JobId { tile: TileKey { source: SourceKey(source), id: tile }, generation } = *id;
41    bytes.extend_from_slice(&source.to_le_bytes());
42    bytes.push(tile.overscaled_z);
43    bytes.extend_from_slice(&tile.wrap.to_le_bytes());
44    bytes.push(tile.canonical.z);
45    bytes.extend_from_slice(&tile.canonical.x.to_le_bytes());
46    bytes.extend_from_slice(&tile.canonical.y.to_le_bytes());
47    bytes.extend_from_slice(&generation.to_le_bytes());
48}
49
50/// Reads a job frame's header: its id, and the bytes after it.
51pub(crate) fn read_job_id(bytes: &[u8]) -> Option<(JobId, &[u8])> {
52    let (header, rest) = bytes.split_at_checked(JOB_ID_SIZE)?;
53    let (source, header) = header.split_first_chunk::<8>()?;
54    let (&[overscaled_z], header) = header.split_first_chunk::<1>()?;
55    let (wrap, header) = header.split_first_chunk::<2>()?;
56    let (&[z], header) = header.split_first_chunk::<1>()?;
57    let (x, header) = header.split_first_chunk::<4>()?;
58    let (y, header) = header.split_first_chunk::<4>()?;
59    let (generation, _) = header.split_first_chunk::<8>()?;
60    let canonical = CanonicalTileID { z, x: u32::from_le_bytes(*x), y: u32::from_le_bytes(*y) };
61    let tile = OverscaledTileID { overscaled_z, wrap: i16::from_le_bytes(*wrap), canonical };
62    let tile = TileKey { source: SourceKey(u64::from_le_bytes(*source)), id: tile };
63    Some((JobId { tile, generation: u64::from_le_bytes(*generation) }, rest))
64}
65
66/// Appends a reply's header: the job's id and how long its stages took.
67pub(crate) fn write_reply_header(bytes: &mut Vec<u8>, id: &JobId, times: &JobTimes) {
68    write_job_header(bytes, id);
69    let micros = |time: Duration| u32::try_from(time.as_micros()).unwrap_or(u32::MAX);
70    bytes.extend_from_slice(&micros(times.discover).to_le_bytes());
71    bytes.extend_from_slice(&micros(times.build).to_le_bytes());
72}
73
74/// Reads a reply's header: the job's id, its times, and the body after
75/// them.
76pub(crate) fn read_reply_header(bytes: &[u8]) -> Option<(JobId, JobTimes, &[u8])> {
77    let (id, rest) = read_job_id(bytes)?;
78    let (discover, rest) = rest.split_first_chunk::<4>()?;
79    let (build, rest) = rest.split_first_chunk::<4>()?;
80    let time = |micros: &[u8; 4]| Duration::from_micros(u64::from(u32::from_le_bytes(*micros)));
81    Some((id, JobTimes { discover: time(discover), build: time(build) }, rest))
82}
83
84/// Appends `value`, encoded in `context`.
85pub(crate) fn append<T: Wire>(bytes: &mut Vec<u8>, value: &T, mut context: impl Context) -> Result<(), String> {
86    let mut w = Writer::from_vec(std::mem::take(bytes)).with_context(&mut context);
87    value.write(&mut w);
88    *bytes = w.finish().map_err(|e| format!("can't encode: {e}"))?;
89    Ok(())
90}
91
92/// Decodes a value at the start of `bytes`; returns it and the bytes after
93/// it.
94pub(crate) fn take<T: Wire>(bytes: &[u8]) -> Result<(T, &[u8]), String> {
95    let mut r = Reader::new(bytes);
96    match T::read(&mut r) {
97        Some(value) => Ok((value, r.rest())),
98        None => Err(format!("malformed: {}", r.error())),
99    }
100}
101
102/// Decodes a value that fills `bytes`, in `context`.
103pub(crate) fn decode<T: Wire>(bytes: &[u8], mut context: impl Context) -> Result<T, String> {
104    let mut r = Reader::new(bytes).with_context(&mut context);
105    match T::read(&mut r) {
106        Some(_) if !r.rest().is_empty() => Err(format!("malformed: {} bytes after the end", r.rest().len())),
107        Some(value) => Ok(value),
108        None => Err(format!("malformed: {}", r.error())),
109    }
110}