1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
use std::{
    fmt::Debug,
    hash::Hash,
    time::{Duration, Instant},
};

use crate::{
    backend::{Backend, BackendIncoming, BackendIncomingInternal, BackendOutgoing},
    bus::{
        BusEventSource, BusLocalHub, BusPubSubFeature, BusSendMultiFeature, BusSendSingleFeature,
        BusWorker,
    },
};

#[derive(Debug)]
pub enum BusChannelControl<ChannelId, MSG> {
    Subscribe(ChannelId),
    Unsubscribe(ChannelId),
    /// The first parameter is the channel id, the second parameter is whether the message is safe, and the third parameter is the message.
    Publish(ChannelId, bool, MSG),
}

impl<ChannelId, MSG> BusChannelControl<ChannelId, MSG> {
    pub fn convert_into<NChannelId: From<ChannelId>, NMSG: From<MSG>>(
        self,
    ) -> BusChannelControl<NChannelId, NMSG> {
        match self {
            Self::Subscribe(channel) => BusChannelControl::Subscribe(channel.into()),
            Self::Unsubscribe(channel) => BusChannelControl::Unsubscribe(channel.into()),
            Self::Publish(channel, safe, msg) => {
                BusChannelControl::Publish(channel.into(), safe, msg.into())
            }
        }
    }
}

#[derive(Debug)]
pub enum BusControl<Owner, ChannelId, MSG> {
    Channel(Owner, BusChannelControl<ChannelId, MSG>),
    Broadcast(bool, MSG),
}

impl<Owner, ChannelId, MSG> BusControl<Owner, ChannelId, MSG> {
    pub fn high_priority(&self) -> bool {
        matches!(
            self,
            Self::Channel(_, BusChannelControl::Subscribe(..))
                | Self::Channel(_, BusChannelControl::Unsubscribe(..))
        )
    }

    pub fn convert_into<NOwner: From<Owner>, NChannelId: From<ChannelId>, NMSG: From<MSG>>(
        self,
    ) -> BusControl<Owner, NChannelId, NMSG> {
        match self {
            Self::Channel(owner, event) => BusControl::Channel(owner, event.convert_into()),
            Self::Broadcast(safe, msg) => BusControl::Broadcast(safe, msg.into()),
        }
    }
}

#[derive(Debug)]
pub enum BusEvent<Owner, ChannelId, MSG> {
    Broadcast(u16, MSG),
    Channel(Owner, ChannelId, MSG),
}

#[derive(Debug, Clone)]
pub enum WorkerControlIn<Ext: Clone, SCfg> {
    Ext(Ext),
    Spawn(SCfg),
    StatsRequest,
    Shutdown,
}

#[derive(Debug)]
pub enum WorkerControlOut<Ext, SCfg> {
    Stats(WorkerStats),
    Ext(Ext),
    Spawn(SCfg),
}

#[derive(Debug, Default)]
pub struct WorkerStats {
    pub tasks: usize,
    pub utilization: u32,
}

impl WorkerStats {
    pub fn load(&self) -> u32 {
        self.tasks as u32
    }

    pub fn tasks(&self) -> usize {
        self.tasks
    }
}

#[derive(Debug)]
pub enum WorkerInnerInput<Owner, ExtIn, ChannelId, Event> {
    Net(Owner, BackendIncoming),
    Bus(BusEvent<Owner, ChannelId, Event>),
    Ext(ExtIn),
}

pub enum WorkerInnerOutput<Owner, ExtOut, ChannelId, Event, SCfg> {
    Net(Owner, BackendOutgoing),
    Bus(BusControl<Owner, ChannelId, Event>),
    /// First bool is message need to safe to send or not, second is the message
    Ext(bool, ExtOut),
    Spawn(SCfg),
    Destroy(Owner),
    Continue,
}

pub trait WorkerInner<Owner, ExtIn, ExtOut, ChannelId, Event, ICfg, SCfg> {
    fn build(worker: u16, cfg: ICfg) -> Self;
    fn worker_index(&self) -> u16;
    fn tasks(&self) -> usize;
    fn spawn(&mut self, now: Instant, cfg: SCfg);
    fn on_tick(&mut self, now: Instant);
    fn on_event(&mut self, now: Instant, event: WorkerInnerInput<Owner, ExtIn, ChannelId, Event>);
    fn on_shutdown(&mut self, now: Instant);
    fn pop_output(
        &mut self,
        now: Instant,
    ) -> Option<WorkerInnerOutput<Owner, ExtOut, ChannelId, Event, SCfg>>;
}

pub(crate) struct Worker<
    Owner,
    ExtIn: Clone,
    ExtOut: Clone,
    ChannelId: Hash + PartialEq + Eq,
    Event,
    Inner: WorkerInner<Owner, ExtIn, ExtOut, ChannelId, Event, ICfg, SCfg>,
    ICfg,
    SCfg,
    B: Backend<Owner>,
    const INNER_BUS_STACK: usize,
> {
    tick: Duration,
    last_tick: Instant,
    inner: Inner,
    bus_local_hub: BusLocalHub<Owner, ChannelId>,
    inner_bus: BusWorker<ChannelId, Event, INNER_BUS_STACK>,
    backend: B,
    worker_out: BusWorker<u16, WorkerControlOut<ExtOut, SCfg>, INNER_BUS_STACK>,
    worker_in: BusWorker<u16, WorkerControlIn<ExtIn, SCfg>, INNER_BUS_STACK>,
    _tmp: std::marker::PhantomData<(Owner, ICfg)>,
}

impl<
        Owner: Debug + Clone + Copy + PartialEq,
        ExtIn: Clone,
        ExtOut: Clone,
        ChannelId: Hash + PartialEq + Eq + Debug + Copy,
        Event: Clone,
        Inner: WorkerInner<Owner, ExtIn, ExtOut, ChannelId, Event, ICfg, SCfg>,
        B: Backend<Owner>,
        ICfg,
        SCfg,
        const INNER_BUS_STACK: usize,
    > Worker<Owner, ExtIn, ExtOut, ChannelId, Event, Inner, ICfg, SCfg, B, INNER_BUS_STACK>
{
    pub fn new(
        tick: Duration,
        inner: Inner,
        inner_bus: BusWorker<ChannelId, Event, INNER_BUS_STACK>,
        worker_out: BusWorker<u16, WorkerControlOut<ExtOut, SCfg>, INNER_BUS_STACK>,
        worker_in: BusWorker<u16, WorkerControlIn<ExtIn, SCfg>, INNER_BUS_STACK>,
    ) -> Self {
        let backend = B::default();
        inner_bus.set_awaker(backend.create_awaker());
        Self {
            inner,
            tick,
            last_tick: Instant::now() - 2 * tick, //for ensure first tick as fast as possible
            bus_local_hub: Default::default(),
            inner_bus,
            backend,
            worker_out,
            worker_in,
            _tmp: Default::default(),
        }
    }

    pub fn init(&mut self) {
        let now = Instant::now();
        self.pop_inner(now);
    }

    pub fn process(&mut self) {
        let now = Instant::now();
        while let Some((_source, msg)) = self.worker_in.recv() {
            match msg {
                WorkerControlIn::Ext(ext) => {
                    self.inner.on_event(now, WorkerInnerInput::Ext(ext));
                    self.pop_inner(now);
                }
                WorkerControlIn::Spawn(cfg) => {
                    self.inner.spawn(now, cfg);
                }
                WorkerControlIn::StatsRequest => {
                    let stats = WorkerStats {
                        tasks: self.inner.tasks(),
                        utilization: 0, //TODO measure this thread utilization
                    };
                    self.worker_out
                        .send(0, true, WorkerControlOut::Stats(stats))
                        .expect("Should send success with safe flag");
                }
                WorkerControlIn::Shutdown => {
                    self.inner.on_shutdown(now);
                }
            }
        }

        if now.duration_since(self.last_tick) >= self.tick {
            self.last_tick = now;
            self.inner.on_tick(now);
            self.pop_inner(now);
        }

        //one cycle is process in 1ms then we minus 1ms with eslaped time
        let remain_time = Duration::from_millis(1)
            .checked_sub(now.elapsed())
            .unwrap_or_else(|| Duration::from_micros(1));

        self.backend.poll_incoming(remain_time);

        while let Some(event) = self.backend.pop_incoming() {
            match event {
                BackendIncomingInternal::Awake => self.on_awake(now),
                BackendIncomingInternal::Event(owner, event) => {
                    self.inner
                        .on_event(now, WorkerInnerInput::Net(owner, event));
                    self.pop_inner(now);
                }
            }
        }

        self.backend.finish_incoming_cycle();
        self.backend.finish_outgoing_cycle();
        if now.elapsed().as_millis() > 15 {
            log::warn!("Worker process too long: {}", now.elapsed().as_millis());
        }
    }

    fn on_awake(&mut self, now: Instant) {
        while let Some((source, event)) = self.inner_bus.recv() {
            match source {
                BusEventSource::Channel(_, channel) => {
                    if let Some(subscribers) = self.bus_local_hub.get_subscribers(channel) {
                        for subscriber in subscribers {
                            self.inner.on_event(
                                now,
                                WorkerInnerInput::Bus(BusEvent::Channel(
                                    subscriber,
                                    channel,
                                    event.clone(),
                                )),
                            );
                            self.pop_inner(now);
                        }
                    }
                }
                BusEventSource::Broadcast(from) => {
                    self.inner.on_event(
                        now,
                        WorkerInnerInput::Bus(BusEvent::Broadcast(from as u16, event.clone())),
                    );
                    self.pop_inner(now);
                }
                _ => panic!(
                    "Invalid channel source for task {:?}, only support channel",
                    source
                ),
            }
        }
    }

    fn pop_inner(&mut self, now: Instant) {
        while let Some(out) = self.inner.pop_output(now) {
            self.process_inner_output(out);
        }
    }

    fn process_inner_output(
        &mut self,
        out: WorkerInnerOutput<Owner, ExtOut, ChannelId, Event, SCfg>,
    ) {
        let worker = self.inner.worker_index();
        match out {
            WorkerInnerOutput::Spawn(cfg) => {
                self.worker_out
                    .send(0, true, WorkerControlOut::Spawn(cfg))
                    .expect("Should send success with safe flag");
            }
            WorkerInnerOutput::Net(owner, action) => {
                self.backend.on_action(owner, action);
            }
            WorkerInnerOutput::Bus(event) => match event {
                BusControl::Channel(owner, BusChannelControl::Subscribe(channel)) => {
                    if self.bus_local_hub.subscribe(owner, channel) {
                        log::info!("Worker {worker} subscribe to channel {:?}", channel);
                        self.inner_bus.subscribe(channel);
                    }
                }
                BusControl::Channel(owner, BusChannelControl::Unsubscribe(channel)) => {
                    if self.bus_local_hub.unsubscribe(owner, channel) {
                        log::info!("Worker {worker} unsubscribe from channel {:?}", channel);
                        self.inner_bus.unsubscribe(channel);
                    }
                }
                BusControl::Channel(_owner, BusChannelControl::Publish(channel, safe, msg)) => {
                    self.inner_bus.publish(channel, safe, msg);
                }
                BusControl::Broadcast(safe, msg) => {
                    self.inner_bus.broadcast(safe, msg);
                }
            },
            WorkerInnerOutput::Destroy(owner) => {
                log::info!("Worker {worker} destroy owner {:?}", owner);
                self.backend.remove_owner(owner);
                self.bus_local_hub.remove_owner(owner);
            }
            WorkerInnerOutput::Ext(safe, ext) => {
                // TODO don't hardcode 0
                log::debug!("Worker {worker} send external");
                if let Err(e) = self.worker_out.send(0, safe, WorkerControlOut::Ext(ext)) {
                    log::error!("Failed to send external: {:?}", e);
                }
            }
            WorkerInnerOutput::Continue => {}
        }
    }
}