mln_engine/worker/worker_codec/
host.rs1use 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
25pub(crate) type Replies = Arc<dyn Fn(Encoded) + Send + Sync>;
29
30pub struct TileWorkerHost {
32 jobs: RefCell<Jobs>,
33 codec: Rc<RefCell<WorkerCodec>>,
36 replies: Replies,
37}
38
39struct Jobs {
41 cache: DataCache,
42 memo: DiscoveryMemo,
43}
44
45impl TileWorkerHost {
46 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 memo: DiscoveryMemo::new(16),
56 }),
57 codec: Rc::new(RefCell::new(WorkerCodec::new(registry))),
58 replies: Arc::new(replies),
59 }
60 }
61
62 pub fn set_data_cache_budget(&self, bytes: usize) {
64 self.jobs.borrow_mut().cache.set_budget(bytes);
65 }
66
67 #[must_use]
69 pub fn data_cache_bytes(&self) -> usize {
70 self.jobs.borrow().cache.retained_bytes()
71 }
72
73 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, ×))
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 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}