Skip to main content

mln_engine/worker/worker_codec/
host.rs

1// 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::sync::Arc;
13
14use mln_style::error::Error;
15use parking_lot::Mutex;
16
17use super::envelope::{self, Encoded};
18use super::worker_side::WorkerCodec;
19use crate::worker::job::{
20    DEFAULT_DATA_CACHE_BYTES, DataCache, DiscoveryMemo, JobResult, JobTimes, Reply, Run, run_job,
21};
22use crate::{Registry, log_target};
23
24/// Where a host's replies go, encoded: back to the map side of its
25/// instance. Their payloads (pixels, vertices, indices) can be transferred
26/// there rather than copied.
27pub(crate) type Replies = Arc<dyn Fn(Encoded) + Send + Sync>;
28
29/// What one worker instance runs.
30pub struct TileWorkerHost {
31    jobs: Mutex<Jobs>,
32    /// Shared with the replies of image decodes, which encode with it when
33    /// the decoder answers.
34    codec: Arc<Mutex<WorkerCodec>>,
35    replies: Replies,
36}
37
38/// The jobs' side of an instance.
39struct Jobs {
40    cache: DataCache,
41    memo: DiscoveryMemo,
42}
43
44impl TileWorkerHost {
45    /// A host that resolves the registrations its jobs name against
46    /// `registry` and sends its replies to `replies`. `registry` must be
47    /// filled by the same calls as the map side's. Its data cache keeps
48    /// 32 MiB.
49    pub fn new(registry: Arc<Registry>, replies: impl Fn(Encoded) + Send + Sync + 'static) -> Self {
50        TileWorkerHost {
51            jobs: Mutex::new(Jobs {
52                cache: DataCache::new(DEFAULT_DATA_CACHE_BYTES),
53                // The labelled tiles of a view that resume here, about.
54                memo: DiscoveryMemo::new(16),
55            }),
56            codec: Arc::new(Mutex::new(WorkerCodec::new(registry))),
57            replies: Arc::new(replies),
58        }
59    }
60
61    /// Runs the job in a frame from the map side, and sends its reply.
62    pub fn handle(&self, request: &[u8]) {
63        let Some((id, body)) = envelope::read_job_id(request) else {
64            return self.lost("a tile worker request without a job id");
65        };
66        let decoded = self.codec.lock().decode_job(body);
67        let send = {
68            let codec = Arc::clone(&self.codec);
69            let replies = Arc::clone(&self.replies);
70            move |reply: Reply, times| replies(codec.lock().encode_reply(&reply, &times))
71        };
72        match decoded {
73            Ok(job) => {
74                let mut jobs = self.jobs.lock();
75                let Jobs { cache, memo } = &mut *jobs;
76                run_job(Run { id, job, superseded: Arc::default() }, Some(cache), Some(memo), send);
77            }
78            Err(error) => {
79                let result = JobResult::Failed(Error::failed(format!("a tile worker request: {error}")));
80                send(Reply { id, result }, JobTimes::default());
81            }
82        }
83    }
84
85    /// Tells the map side that this instance can't go on: a frame it can't
86    /// read leaves it out of step with the map side's tables.
87    fn lost(&self, error: &str) {
88        tracing::error!(target: log_target::GENERAL, error = %error, "Not a tile worker request");
89        (self.replies)(Encoded::default());
90    }
91}