use std::sync::{Arc, mpsc};
use mln_style::hash::HashSet;
use mln_wire::payload::Payload;
use super::TileWorkerHost;
use super::envelope::{self, Encoded};
use super::map_side::MapCodec;
use crate::exec::thread::Joined;
use crate::tile_store::inbox::{InboxSender, TileEvent};
use crate::worker::job::{JobId, JobResult, JobTimes, Run};
use crate::worker::tile_workers::{Lane, ReplyBody, TileWorkers};
use crate::{Registry, log_target};
const JOBS_PER_LANE: usize = 2;
pub trait WorkerInstances {
fn count(&self) -> usize;
fn post(&mut self, instance: usize, request: Vec<u8>);
fn replace(&mut self, _instance: usize) -> bool {
false
}
}
#[derive(Clone)]
pub struct ReplySink {
inbox: InboxSender,
origin: Origin,
}
impl ReplySink {
pub fn send(&self, instance: usize, reply: Encoded) {
self.deliver(instance, Some(reply));
}
pub fn lost(&self, instance: usize) {
self.deliver(instance, None);
}
fn deliver(&self, instance: usize, reply: Option<Encoded>) {
let event = RemoteEvent { origin: self.origin.clone(), lane: Lane(instance), reply };
self.inbox.send(TileEvent::Remote(event));
}
}
#[derive(Clone)]
struct Origin(Arc<()>);
impl Origin {
fn is(&self, other: &Origin) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
pub(crate) struct RemoteEvent {
origin: Origin,
lane: Lane,
reply: Option<Encoded>,
}
type Start = Box<dyn FnOnce(ReplySink) -> Box<dyn WorkerInstances>>;
pub struct RemoteWorkers {
registry: Arc<Registry>,
origin: Origin,
start: Option<Start>,
instances: Option<Box<dyn WorkerInstances>>,
lanes: Vec<RemoteLane>,
bytes: (u64, u64),
}
struct RemoteLane {
codec: MapCodec,
in_flight: HashSet<JobId>,
instance: u64,
live: bool,
}
impl RemoteLane {
fn new(registry: &Arc<Registry>, instance: u64, live: bool) -> Self {
RemoteLane { codec: MapCodec::new(Arc::clone(registry)), in_flight: HashSet::default(), instance, live }
}
}
impl RemoteWorkers {
pub fn new(
registry: Arc<Registry>,
instances: impl FnOnce(ReplySink) -> Box<dyn WorkerInstances> + 'static,
) -> Self {
RemoteWorkers {
registry,
origin: Origin(Arc::new(())),
start: Some(Box::new(instances)),
instances: None,
lanes: Vec::new(),
bytes: (0, 0),
}
}
fn job_reply(
&mut self,
lane: Lane,
id: JobId,
times: JobTimes,
body: &[u8],
payloads: Vec<Payload>,
) -> Option<TileEvent> {
let remote = self.lanes.get_mut(lane.0)?;
if !remote.in_flight.remove(&id) {
return None;
}
let size = body.len() + payloads.iter().map(Payload::len).sum::<usize>();
self.bytes.1 += size as u64;
let body = ReplyBody::Encoded { body: Encoded { bytes: body.to_vec(), payloads }, instance: remote.instance };
Some(TileEvent::Reply { lane, id, body, times })
}
fn lose(&mut self, lane: Lane) -> Option<TileEvent> {
let remote = self.lanes.get_mut(lane.0)?;
log::error!(target: log_target::GENERAL, "Tile worker {} was lost", lane.0);
let live = self.instances.as_mut().is_some_and(|instances| instances.replace(lane.0));
*remote = RemoteLane::new(&self.registry, remote.instance + 1, live);
Some(TileEvent::LaneLost(lane))
}
}
impl TileWorkers for RemoteWorkers {
fn connect(&mut self, inbox: &InboxSender) {
let Some(start) = self.start.take() else {
return;
};
let instances = start(ReplySink { inbox: inbox.clone(), origin: self.origin.clone() });
let count = instances.count();
assert!(count > 0, "RemoteWorkers need a worker instance");
self.lanes = (0..count).map(|_| RemoteLane::new(&self.registry, 0, true)).collect();
self.instances = Some(instances);
}
fn lanes(&self) -> usize {
self.lanes.len()
}
fn capacity(&self, lane: Lane) -> usize {
if self.lanes.get(lane.0).is_some_and(|remote| remote.live) { JOBS_PER_LANE } else { 0 }
}
fn caches_data(&self) -> bool {
true
}
fn submit(&mut self, lane: Lane, run: Run, inbox: &InboxSender) {
let (Some(remote), Some(instances)) = (self.lanes.get_mut(lane.0), self.instances.as_mut()) else {
return;
};
match remote.codec.encode_run(&run) {
Ok(request) => {
remote.in_flight.insert(run.id);
self.bytes.0 += request.len() as u64;
instances.post(lane.0, request);
}
Err(error) => {
let body = ReplyBody::Result(JobResult::Failed(mln_style::error::Error::native(error)));
inbox.send(TileEvent::Reply { lane, id: run.id, body, times: JobTimes::default() });
}
}
}
fn receive(&mut self, event: RemoteEvent) -> Option<TileEvent> {
if !event.origin.is(&self.origin) {
return None;
}
let lane = event.lane;
let Some(reply) = event.reply else {
return self.lose(lane);
};
match envelope::read_reply_header(&reply.bytes) {
Some((id, times, body)) => self.job_reply(lane, id, times, body, reply.payloads),
None => self.lose(lane),
}
}
fn decode(&mut self, lane: Lane, body: ReplyBody) -> Option<JobResult> {
match body {
ReplyBody::Result(result) => Some(result),
ReplyBody::Encoded { body, instance } => {
let remote = self.lanes.get_mut(lane.0).filter(|remote| remote.instance == instance)?;
Some(remote.codec.decode_result(body))
}
}
}
fn bytes(&self) -> (u64, u64) {
self.bytes
}
}
pub struct ThreadWorkerInstances {
threads: Vec<Option<WorkerThread>>,
registry: Arc<Registry>,
replies: ReplySink,
}
struct WorkerThread {
requests: mpsc::Sender<Vec<u8>>,
_thread: Joined,
}
impl ThreadWorkerInstances {
#[must_use]
pub fn new(count: usize, registry: Arc<Registry>, replies: &ReplySink) -> Self {
let threads = (0..count)
.map(|instance| {
let thread = Self::start(instance, ®istry, replies);
if thread.is_none() {
replies.lost(instance);
}
thread
})
.collect();
ThreadWorkerInstances { threads, registry, replies: replies.clone() }
}
fn start(instance: usize, registry: &Arc<Registry>, replies: &ReplySink) -> Option<WorkerThread> {
let (registry, replies) = (Arc::clone(registry), replies.clone());
let (requests, received) = mpsc::channel::<Vec<u8>>();
let thread = crate::exec::thread::spawn(format!("TileWorker {instance}"), move || {
let host = TileWorkerHost::new(registry, move |reply| replies.send(instance, reply));
for request in received {
host.handle(&request);
}
});
match thread {
Ok(thread) => Some(WorkerThread { requests, _thread: Joined::new(thread) }),
Err(error) => {
log::error!(target: log_target::GENERAL, "Tile worker {instance}'s thread didn't start: {error}");
None
}
}
}
}
impl WorkerInstances for ThreadWorkerInstances {
fn count(&self) -> usize {
self.threads.len()
}
fn post(&mut self, instance: usize, request: Vec<u8>) {
if let Some(thread) = &self.threads[instance] {
let _ = thread.requests.send(request);
}
}
fn replace(&mut self, instance: usize) -> bool {
self.threads[instance] = Self::start(instance, &self.registry, &self.replies);
self.threads[instance].is_some()
}
}