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    /// Runs the job in a frame from the map side, and sends its reply.
63    pub fn handle(&self, request: &[u8]) {
64        let Some((id, body)) = envelope::read_job_id(request) else {
65            return self.lost("a tile worker request without a job id");
66        };
67        let decoded = self.codec.borrow_mut().decode_job(body);
68        let send = {
69            let codec = Rc::clone(&self.codec);
70            let replies = Arc::clone(&self.replies);
71            move |reply: Reply, times| replies(codec.borrow_mut().encode_reply(&reply, &times))
72        };
73        match decoded {
74            Ok(job) => {
75                let mut jobs = self.jobs.borrow_mut();
76                let Jobs { cache, memo } = &mut *jobs;
77                run_job(Run { id, job, superseded: Arc::default() }, Some(cache), Some(memo), send);
78            }
79            Err(error) => {
80                let result = JobResult::Failed(Error::native(format!("a tile worker request: {error}")));
81                send(Reply { id, result }, JobTimes::default());
82            }
83        }
84    }
85
86    /// Tells the map side that this instance can't go on: a frame it can't
87    /// read leaves it out of step with the map side's tables.
88    fn lost(&self, error: &str) {
89        log::error!(target: log_target::GENERAL, "Not a tile worker request: {error}");
90        (self.replies)(Encoded::default());
91    }
92}