Skip to main content

mln_engine/worker/worker_codec/
transport.rs

1// Port-only: tile workers in other worker instances, reached only through
2// bytes (mod.rs).
3//
4// `RemoteWorkers` is the map side. Each instance is a lane of `TileWorkers`:
5// a job crosses as its frame through the lane's `MapCodec`, whose shared
6// tables mirror the instance's, and each lane takes two jobs at a time.
7// Each instance runs a `TileWorkerHost` (host.rs).
8//
9// An instance is lost when it reports its own death (a Web Worker's `error`
10// event) or sends a frame whose header can't be read. Its lane's tables then
11// start afresh on both sides, with a new instance in its place if the
12// `WorkerInstances` can make one, and its tiles submit their jobs again.
13//
14// In the browser each instance is a Web Worker with its own wasm instance
15// and memory. `ThreadWorkerInstances` runs the instances on threads of this
16// process instead, each host on its thread and nothing shared with the map
17// but the bytes; the render-test runner uses it
18// (`--tileWorkerCodec`) to run the suites through the codec.
19
20use std::sync::{Arc, mpsc};
21
22use mln_style::hash::HashSet;
23use mln_wire::payload::Payload;
24
25use super::TileWorkerHost;
26use super::envelope::{self, Encoded};
27use super::map_side::MapCodec;
28use crate::exec::thread::Joined;
29use crate::tile_store::inbox::{InboxSender, TileEvent};
30use crate::worker::job::{JobId, JobResult, JobTimes, Run};
31use crate::worker::tile_workers::{Lane, ReplyBody, TileWorkers};
32use crate::{Registry, log_target};
33
34/// The jobs a lane takes at once.
35const JOBS_PER_LANE: usize = 2;
36
37/// The worker instances a `RemoteWorkers` sends its frames to. Their
38/// replies come back through the `ReplySink` the transport gave whoever
39/// created them.
40pub trait WorkerInstances {
41    /// How many there are; frames go to `0..count()`.
42    fn count(&self) -> usize;
43    /// Sends a frame to the host of instance `instance`.
44    fn post(&mut self, instance: usize, request: Vec<u8>);
45    /// Puts a new instance, with a new host, in the place of `instance`,
46    /// which was lost; its replies no longer arrive. Returns whether it
47    /// could.
48    fn replace(&mut self, _instance: usize) -> bool {
49        false
50    }
51}
52
53/// Delivers worker instances' replies, from any thread, to the inbox of the
54/// tile store whose `RemoteWorkers` started them, in the order they were
55/// sent. The store hands them to its workers when it takes in what arrived.
56#[derive(Clone)]
57pub struct ReplySink {
58    inbox: InboxSender,
59    origin: Origin,
60}
61
62impl ReplySink {
63    /// Delivers a reply of instance `instance`.
64    pub fn send(&self, instance: usize, reply: Encoded) {
65        self.deliver(instance, Some(reply));
66    }
67
68    /// Reports that instance `instance` is gone, with every job it had.
69    pub fn lost(&self, instance: usize) {
70        self.deliver(instance, None);
71    }
72
73    fn deliver(&self, instance: usize, reply: Option<Encoded>) {
74        let event = RemoteEvent { origin: self.origin.clone(), lane: Lane(instance), reply };
75        self.inbox.send(TileEvent::Remote(event));
76    }
77}
78
79/// Which `RemoteWorkers` a [`RemoteEvent`] is for: a store's inbox may still
80/// hold events of the workers it replaced.
81#[derive(Clone)]
82struct Origin(Arc<()>);
83
84impl Origin {
85    fn is(&self, other: &Origin) -> bool {
86        Arc::ptr_eq(&self.0, &other.0)
87    }
88}
89
90/// What a worker instance sent its `RemoteWorkers`: a reply, or `None` when
91/// the instance is lost.
92pub(crate) struct RemoteEvent {
93    origin: Origin,
94    lane: Lane,
95    reply: Option<Encoded>,
96}
97
98/// Makes the worker instances, given the sink for their replies.
99type Start = Box<dyn FnOnce(ReplySink) -> Box<dyn WorkerInstances>>;
100
101/// The map side of tile workers in other worker instances. The renderer
102/// given it owns it (`Renderer::set_tile_workers`), and its instances start
103/// then.
104pub struct RemoteWorkers {
105    registry: Arc<Registry>,
106    origin: Origin,
107    /// What makes the instances, until they start.
108    start: Option<Start>,
109    /// The instances, once started.
110    instances: Option<Box<dyn WorkerInstances>>,
111    /// Each instance's jobs; none until the instances start.
112    lanes: Vec<RemoteLane>,
113    /// The bytes sent and received for jobs.
114    bytes: (u64, u64),
115}
116
117/// One instance's jobs.
118struct RemoteLane {
119    codec: MapCodec,
120    in_flight: HashSet<JobId>,
121    /// Counts the instances the lane had: a reply of an earlier one can't be
122    /// read with this one's tables.
123    instance: u64,
124    /// Whether the lane's instance takes jobs: not once lost without a
125    /// replacement.
126    live: bool,
127}
128
129impl RemoteLane {
130    /// The lane of its `instance`th instance, with tables of its own.
131    fn new(registry: &Arc<Registry>, instance: u64, live: bool) -> Self {
132        RemoteLane { codec: MapCodec::new(Arc::clone(registry)), in_flight: HashSet::default(), instance, live }
133    }
134}
135
136impl RemoteWorkers {
137    /// Workers in the instances that `instances` makes, given the sink for
138    /// their replies, once a renderer's tiles take the workers. It must make
139    /// at least one. The jobs name `registry`'s registrations, so each
140    /// instance's host needs a registry filled by the same calls.
141    pub fn new(
142        registry: Arc<Registry>,
143        instances: impl FnOnce(ReplySink) -> Box<dyn WorkerInstances> + 'static,
144    ) -> Self {
145        RemoteWorkers {
146            registry,
147            origin: Origin(Arc::new(())),
148            start: Some(Box::new(instances)),
149            instances: None,
150            lanes: Vec::new(),
151            bytes: (0, 0),
152        }
153    }
154
155    fn job_reply(
156        &mut self,
157        lane: Lane,
158        id: JobId,
159        times: JobTimes,
160        body: &[u8],
161        payloads: Vec<Payload>,
162    ) -> Option<TileEvent> {
163        // A reply of an instance lost since isn't in flight any more.
164        let remote = self.lanes.get_mut(lane.0)?;
165        if !remote.in_flight.remove(&id) {
166            return None;
167        }
168        let size = body.len() + payloads.iter().map(Payload::len).sum::<usize>();
169        self.bytes.1 += size as u64;
170        let body = ReplyBody::Encoded { body: Encoded { bytes: body.to_vec(), payloads }, instance: remote.instance };
171        Some(TileEvent::Reply { lane, id, body, times })
172    }
173
174    /// Gives up on the instance of `lane`: its jobs, the replies not yet
175    /// read, and its shared tables, on both sides.
176    fn lose(&mut self, lane: Lane) -> Option<TileEvent> {
177        let remote = self.lanes.get_mut(lane.0)?;
178        log::error!(target: log_target::GENERAL, "Tile worker {} was lost", lane.0);
179        let live = self.instances.as_mut().is_some_and(|instances| instances.replace(lane.0));
180        *remote = RemoteLane::new(&self.registry, remote.instance + 1, live);
181        Some(TileEvent::LaneLost(lane))
182    }
183}
184
185impl TileWorkers for RemoteWorkers {
186    fn connect(&mut self, inbox: &InboxSender) {
187        let Some(start) = self.start.take() else {
188            return;
189        };
190        let instances = start(ReplySink { inbox: inbox.clone(), origin: self.origin.clone() });
191        let count = instances.count();
192        assert!(count > 0, "RemoteWorkers need a worker instance");
193        self.lanes = (0..count).map(|_| RemoteLane::new(&self.registry, 0, true)).collect();
194        self.instances = Some(instances);
195    }
196
197    fn lanes(&self) -> usize {
198        self.lanes.len()
199    }
200
201    fn capacity(&self, lane: Lane) -> usize {
202        if self.lanes.get(lane.0).is_some_and(|remote| remote.live) { JOBS_PER_LANE } else { 0 }
203    }
204
205    fn caches_data(&self) -> bool {
206        true
207    }
208
209    fn submit(&mut self, lane: Lane, run: Run, inbox: &InboxSender) {
210        let (Some(remote), Some(instances)) = (self.lanes.get_mut(lane.0), self.instances.as_mut()) else {
211            return;
212        };
213        match remote.codec.encode_run(&run) {
214            Ok(request) => {
215                remote.in_flight.insert(run.id);
216                self.bytes.0 += request.len() as u64;
217                instances.post(lane.0, request);
218            }
219            // As a worker reports a job it can't decode.
220            Err(error) => {
221                let body = ReplyBody::Result(JobResult::Failed(mln_style::error::Error::native(error)));
222                inbox.send(TileEvent::Reply { lane, id: run.id, body, times: JobTimes::default() });
223            }
224        }
225    }
226
227    fn receive(&mut self, event: RemoteEvent) -> Option<TileEvent> {
228        if !event.origin.is(&self.origin) {
229            return None;
230        }
231        let lane = event.lane;
232        let Some(reply) = event.reply else {
233            return self.lose(lane);
234        };
235        match envelope::read_reply_header(&reply.bytes) {
236            Some((id, times, body)) => self.job_reply(lane, id, times, body, reply.payloads),
237            None => self.lose(lane),
238        }
239    }
240
241    fn decode(&mut self, lane: Lane, body: ReplyBody) -> Option<JobResult> {
242        match body {
243            ReplyBody::Result(result) => Some(result),
244            ReplyBody::Encoded { body, instance } => {
245                let remote = self.lanes.get_mut(lane.0).filter(|remote| remote.instance == instance)?;
246                Some(remote.codec.decode_result(body))
247            }
248        }
249    }
250
251    fn bytes(&self) -> (u64, u64) {
252        self.bytes
253    }
254}
255
256/// Worker instances on threads of this process: a `TileWorkerHost` on each
257/// thread.
258pub struct ThreadWorkerInstances {
259    /// Each instance's thread, or `None` for one that couldn't start, whose
260    /// lane is lost.
261    threads: Vec<Option<WorkerThread>>,
262    registry: Arc<Registry>,
263    replies: ReplySink,
264}
265
266/// A thread that builds a `TileWorkerHost` and hands it the requests sent
267/// to it, in order. Dropping it lets the thread end once it handled the
268/// requests sent before, and waits for it.
269struct WorkerThread {
270    requests: mpsc::Sender<Vec<u8>>,
271    _thread: Joined,
272}
273
274impl ThreadWorkerInstances {
275    /// `count` instances, whose hosts resolve their jobs' registrations
276    /// against `registry` and send their replies to `replies`.
277    #[must_use]
278    pub fn new(count: usize, registry: Arc<Registry>, replies: &ReplySink) -> Self {
279        let threads = (0..count)
280            .map(|instance| {
281                let thread = Self::start(instance, &registry, replies);
282                if thread.is_none() {
283                    replies.lost(instance);
284                }
285                thread
286            })
287            .collect();
288        ThreadWorkerInstances { threads, registry, replies: replies.clone() }
289    }
290
291    fn start(instance: usize, registry: &Arc<Registry>, replies: &ReplySink) -> Option<WorkerThread> {
292        let (registry, replies) = (Arc::clone(registry), replies.clone());
293        let (requests, received) = mpsc::channel::<Vec<u8>>();
294        let thread = crate::exec::thread::spawn(format!("TileWorker {instance}"), move || {
295            let host = TileWorkerHost::new(registry, move |reply| replies.send(instance, reply));
296            for request in received {
297                host.handle(&request);
298            }
299        });
300        match thread {
301            Ok(thread) => Some(WorkerThread { requests, _thread: Joined::new(thread) }),
302            Err(error) => {
303                log::error!(target: log_target::GENERAL, "Tile worker {instance}'s thread didn't start: {error}");
304                None
305            }
306        }
307    }
308}
309
310impl WorkerInstances for ThreadWorkerInstances {
311    fn count(&self) -> usize {
312        self.threads.len()
313    }
314
315    fn post(&mut self, instance: usize, request: Vec<u8>) {
316        if let Some(thread) = &self.threads[instance] {
317            let _ = thread.requests.send(request);
318        }
319    }
320
321    fn replace(&mut self, instance: usize) -> bool {
322        self.threads[instance] = Self::start(instance, &self.registry, &self.replies);
323        self.threads[instance].is_some()
324    }
325}