Skip to main content

mln_engine/worker/worker_codec/
host.rs

1// Port-only: what one worker instance runs, behind bytes (mod.rs).
2//
3// A `TileWorkerHost` decodes the map side's frames. It runs each job as its
4// frame arrives, one job per frame, and sends the reply back once the job
5// answers: a layout before `handle` returns, an image decode when the
6// platform's decoder answers, which in the browser is later. It keeps the
7// tile data of the jobs in a cache of its own, which a later job can name
8// instead of carrying the data. A job whose body it can't decode gets a
9// `Failed` reply with the header's id, and a frame whose header it can't
10// read an empty reply, which the map side takes as the instance lost.
11
12use std::cell::RefCell;
13use std::rc::Rc;
14use std::sync::Arc;
15
16use mln_style::error::Error;
17
18use super::envelope::{self, Encoded};
19use super::worker_side::WorkerCodec;
20use crate::worker::job::{
21    DEFAULT_DATA_CACHE_BYTES, DataCache, DiscoveryMemo, JobResult, JobTimes, Reply, Run, run_job,
22};
23use crate::{Registry, log_target};
24
25/// Where a host's replies go, encoded: back to the map side of its
26/// instance. Their payloads (pixels, vertices, indices) can be transferred
27/// there rather than copied.
28pub(crate) type Replies = Arc<dyn Fn(Encoded) + Send + Sync>;
29
30/// What one worker instance runs.
31pub struct TileWorkerHost {
32    jobs: RefCell<Jobs>,
33    /// Shared with the replies of image decodes, which encode with it when
34    /// the decoder answers.
35    codec: Rc<RefCell<WorkerCodec>>,
36    replies: Replies,
37}
38
39/// The jobs' side of an instance.
40struct Jobs {
41    cache: DataCache,
42    memo: DiscoveryMemo,
43}
44
45impl TileWorkerHost {
46    /// A host that resolves the registrations its jobs name against
47    /// `registry` and sends its replies to `replies`. `registry` must be
48    /// filled by the same calls as the map side's. Its data cache keeps
49    /// 32 MiB.
50    pub fn new(registry: Arc<Registry>, replies: impl Fn(Encoded) + Send + Sync + 'static) -> Self {
51        TileWorkerHost {
52            jobs: RefCell::new(Jobs {
53                cache: DataCache::new(DEFAULT_DATA_CACHE_BYTES),
54                // The labelled tiles of a view that resume here, about.
55                memo: DiscoveryMemo::new(16),
56            }),
57            codec: Rc::new(RefCell::new(WorkerCodec::new(registry))),
58            replies: Arc::new(replies),
59        }
60    }
61
62    /// Sets how many bytes of tile data the host keeps for later jobs.
63    pub fn set_data_cache_budget(&self, bytes: usize) {
64        self.jobs.borrow_mut().cache.set_budget(bytes);
65    }
66
67    /// The bytes of tile data the host keeps, by its estimate.
68    #[must_use]
69    pub fn data_cache_bytes(&self) -> usize {
70        self.jobs.borrow().cache.retained_bytes()
71    }
72
73    /// Runs the job in a frame from the map side, and sends its reply.
74    pub fn handle(&self, request: &[u8]) {
75        let Some((id, body)) = envelope::read_job_id(request) else {
76            return self.lost("a tile worker request without a job id");
77        };
78        let decoded = self.codec.borrow_mut().decode_job(body);
79        let send = {
80            let codec = Rc::clone(&self.codec);
81            let replies = Arc::clone(&self.replies);
82            move |reply: Reply, times| replies(codec.borrow_mut().encode_reply(&reply, &times))
83        };
84        match decoded {
85            Ok(job) => {
86                let mut jobs = self.jobs.borrow_mut();
87                let Jobs { cache, memo } = &mut *jobs;
88                run_job(Run { id, job, superseded: Arc::default() }, Some(cache), Some(memo), send);
89            }
90            Err(error) => {
91                let result = JobResult::Failed(Error::native(format!("a tile worker request: {error}")));
92                send(Reply { id, result }, JobTimes::default());
93            }
94        }
95    }
96
97    /// Tells the map side that this instance can't go on: a frame it can't
98    /// read leaves it out of step with the map side's tables.
99    fn lost(&self, error: &str) {
100        log::error!(target: log_target::GENERAL, "Not a tile worker request: {error}");
101        (self.replies)(Encoded::default());
102    }
103}