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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
use std::{
sync::Arc,
thread::{self, JoinHandle},
};
use errors::EngineError;
use plugins::{ExternalPlugin, Plugin};
use uuid::Uuid;
use zmq::{Context, Socket};
pub mod errors;
pub mod events;
pub mod plugins;
pub struct AppConfig {
pub publish_port: i32,
pub subscribe_port: i32,
}
struct SocketData {
pub_socket_inproc_url: String,
sub_socket_inproc_url: String,
sync_socket_port: i32,
sync_inproc_url: String,
}
impl Default for SocketData {
fn default() -> Self {
Self {
pub_socket_inproc_url: "inproc://messages".to_string(),
sub_socket_inproc_url: "inproc://events".to_string(),
sync_socket_port: 5000,
sync_inproc_url: "inproc://sync".to_string(),
}
}
}
pub struct App {
pub plugins: Vec<Arc<Box<dyn Plugin>>>,
pub external_plugins: Vec<Arc<Box<dyn ExternalPlugin>>>,
pub app_config: AppConfig,
pub context: Context,
}
impl Default for App {
fn default() -> Self {
App {
plugins: vec![],
external_plugins: vec![],
app_config: AppConfig {
publish_port: 5559,
subscribe_port: 5560,
},
context: Context::new(),
}
}
}
impl App {
pub fn new(publish_port: i32, subscribe_port: i32) -> Self {
let app_config = AppConfig {
publish_port,
subscribe_port,
};
App {
app_config,
..Default::default()
}
}
fn get_outgoing_socket(&self) -> Result<Socket, EngineError> {
let socket_data = SocketData::default();
let sub_socket_tcp_url = format!("tcp://*:{}", self.app_config.subscribe_port);
let outgoing = self.context.socket(zmq::PUB)?;
outgoing.bind(&sub_socket_tcp_url).map_err(|e| {
EngineError::SubSocketTCPBindError(self.app_config.subscribe_port.to_string(), e)
})?;
outgoing
.bind(&socket_data.sub_socket_inproc_url)
.map_err(|_e| {
EngineError::SubSocketInProcBindError(socket_data.sub_socket_inproc_url.to_string())
})?;
Ok(outgoing)
}
fn get_incoming_socket(&self) -> Result<Socket, EngineError> {
let socket_data = SocketData::default();
let pub_socket_tcp_url = format!("tcp://*:{}", self.app_config.publish_port);
let incoming = self.context.socket(zmq::SUB)?;
incoming.bind(&pub_socket_tcp_url).map_err(|_e| {
EngineError::PubSocketTCPBindError(self.app_config.subscribe_port.to_string())
})?;
incoming
.bind(&socket_data.pub_socket_inproc_url)
.map_err(|_e| {
EngineError::PubSocketInProcBindError(socket_data.pub_socket_inproc_url.to_string())
})?;
let filter = String::new();
incoming
.set_subscribe(filter.as_bytes())
.map_err(EngineError::EngineSetSubFilterAllError)?;
Ok(incoming)
}
fn start_plugin(
&self,
context: &zmq::Context,
plugin: Arc<Box<dyn Plugin>>,
) -> Result<JoinHandle<()>, EngineError> {
let socket_data = SocketData::default();
let context_clone = context.clone();
let thread_handle = thread::spawn(move || {
println!("plugin {} thread started.", plugin.get_id());
let pub_socket = context_clone
.socket(zmq::PUB)
.map_err(|_e| EngineError::PluginPubSocketError(plugin.get_id()))
.unwrap();
pub_socket
.connect(&socket_data.pub_socket_inproc_url)
.map_err(|_e| EngineError::PluginPubSocketError(plugin.get_id()))
.unwrap();
println!("plugin {} connected to pub socket.", plugin.get_id());
let sub_socket = context_clone
.socket(zmq::SUB)
.map_err(|_e| EngineError::PluginSubSocketError(plugin.get_id()))
.unwrap();
sub_socket
.connect(&socket_data.sub_socket_inproc_url)
.map_err(|_e| EngineError::PluginPubSocketError(plugin.get_id()))
.unwrap();
for sub in plugin.get_subscriptions().unwrap() {
let filter = sub
.get_filter()
.map_err(|_e| EngineError::EngineSetSubFilterError())
.unwrap();
println!(
"Engine setting subscription filter {:?} for plugin: {}",
filter,
plugin.get_id()
);
sub_socket
.set_subscribe(&filter)
.map_err(|_e| {
EngineError::PluginSubscriptionError(sub.get_name(), plugin.get_id())
})
.unwrap();
}
println!(
"plugin {} connected to sub socket with subscriptions set.",
plugin.get_id()
);
let sync = context_clone
.socket(zmq::REQ)
.map_err(|_e| {
EngineError::PluginSyncSocketError(
plugin.get_id(),
socket_data.sync_socket_port,
)
})
.unwrap();
let plugin_sync_socket_inproc_url =
format!("{}-{}", &socket_data.sync_inproc_url, plugin.get_id());
sync.connect(&plugin_sync_socket_inproc_url)
.map_err(|_e| {
EngineError::PluginSyncSocketError(
plugin.get_id(),
socket_data.sync_socket_port,
)
})
.unwrap();
println!(
"plugin {} connected to sync socket at URL: {}.",
plugin.get_id(),
plugin_sync_socket_inproc_url
);
let msg = "ready";
sync.send(msg, 0)
.expect("Could not send ready message on thread for plugin; crashing!");
println!("plugin {} sent ready message.", plugin.get_id());
let _msg = sync
.recv_msg(0)
.expect("plugin got error trying to receive sync reply; crashing!");
println!(
"plugin {} received reply from ready message. Executing start function...",
plugin.get_id()
);
plugin.start(pub_socket, sub_socket).unwrap();
});
Ok(thread_handle)
}
fn start_external_plugin(
&self,
context: &zmq::Context,
plugin: Arc<Box<dyn ExternalPlugin>>,
) -> Result<JoinHandle<()>, EngineError> {
let socket_data = SocketData::default();
let context_clone = context.clone();
let thread_handle = thread::spawn(move || {
println!("external plugin {} thread started.", plugin.get_id());
let external_socket = context_clone
.socket(zmq::REP)
.map_err(|e| EngineError::PluginExternalSocketError(plugin.get_id(), e))
.unwrap();
let external_tcp_url = format!("tcp://*:{}", plugin.get_tcp_port());
external_socket
.bind(&external_tcp_url)
.map_err(|e| EngineError::PluginExternalSocketError(plugin.get_id(), e))
.unwrap();
println!("plugin bound to external TCP socket: {}", external_tcp_url);
let pub_socket = context_clone
.socket(zmq::PUB)
.map_err(|_e| EngineError::PluginPubSocketError(plugin.get_id()))
.unwrap();
pub_socket
.connect(&socket_data.pub_socket_inproc_url)
.map_err(|_e| EngineError::PluginPubSocketError(plugin.get_id()))
.unwrap();
println!("plugin {} connected to pub socket.", plugin.get_id());
let sub_socket = context_clone
.socket(zmq::SUB)
.map_err(|_e| EngineError::PluginSubSocketError(plugin.get_id()))
.unwrap();
sub_socket
.connect(&socket_data.sub_socket_inproc_url)
.map_err(|_e| EngineError::PluginPubSocketError(plugin.get_id()))
.unwrap();
for sub in plugin.get_subscriptions().unwrap() {
let filter = sub
.get_filter()
.map_err(|_e| EngineError::EngineSetSubFilterError())
.unwrap();
println!("Engine setting subscription filter {:?}", filter);
sub_socket
.set_subscribe(&filter)
.map_err(|_e| {
EngineError::PluginSubscriptionError(sub.get_name(), plugin.get_id())
})
.unwrap();
}
println!(
"external plugin {} connected to sub socket with subscriptions set.",
plugin.get_id()
);
let sync = context_clone
.socket(zmq::REQ)
.map_err(|_e| {
EngineError::PluginSyncSocketError(
plugin.get_id(),
socket_data.sync_socket_port,
)
})
.unwrap();
let plugin_sync_socket_inproc_url =
format!("{}-{}", &socket_data.sync_inproc_url, plugin.get_id());
sync.connect(&plugin_sync_socket_inproc_url)
.map_err(|_e| {
EngineError::PluginSyncSocketError(
plugin.get_id(),
socket_data.sync_socket_port,
)
})
.unwrap();
println!(
"plugin {} connected to sync socket at URL: {}.",
plugin.get_id(),
plugin_sync_socket_inproc_url
);
let msg = "ready";
sync.send(msg, 0)
.expect("Could not send ready message on thread for plugin; crashing!");
println!("plugin {} sent ready message.", plugin.get_id());
let _msg = sync
.recv_msg(0)
.expect("plugin got error trying to receive sync reply; crashing!");
println!(
"plugin {} received reply from ready message. Executing start function...",
plugin.get_id()
);
plugin
.start(pub_socket, sub_socket, external_socket)
.unwrap();
});
Ok(thread_handle)
}
fn sync_plugins(&self, context: &zmq::Context) -> Result<(), EngineError> {
let socket_data = SocketData::default();
let mut sync_sockets = Vec::<zmq::Socket>::new();
let mut plugin_ids: Vec<Uuid> = self.plugins.iter().map(|x| x.get_id()).collect();
let mut external_plugin_ids: Vec<Uuid> =
self.external_plugins.iter().map(|x| x.get_id()).collect();
plugin_ids.append(&mut external_plugin_ids);
println!("Engine will now sync these plugins: {:?}", plugin_ids);
for plugin_id in &plugin_ids {
let sync_socket = context
.socket(zmq::REP)
.map_err(|_e| EngineError::EngineSyncSocketCreateError())?;
let plugin_sync_socket_inproc_url =
format!("{}-{}", &socket_data.sync_inproc_url, plugin_id);
println!(
"Engine binding to sync inproc URL: {}",
&plugin_sync_socket_inproc_url
);
sync_socket
.bind(&plugin_sync_socket_inproc_url)
.map_err(|_e| {
EngineError::EngineSyncSocketInprocBindError(plugin_sync_socket_inproc_url)
})?;
let _msg = sync_socket
.recv_msg(0)
.map_err(EngineError::EngineSyncSocketMsgRcvError)?;
println!("Engine received a ready message from plugin {}", plugin_id);
sync_sockets.push(sync_socket);
}
println!("Engine received all ready messages; now sending replies.");
let mut msg_sent = 0;
while msg_sent < plugin_ids.len() {
let reply = "ok";
let sync_socket = sync_sockets
.pop()
.ok_or(EngineError::EngineSyncSocketPopError())?;
sync_socket
.send(reply, 0)
.map_err(EngineError::EngineSyncSocketSendRcvError)?;
msg_sent += 1;
println!("Engine sent a reply");
}
println!("All plugins have been synced");
Ok(())
}
fn start_plugins(&self) -> Result<Vec<JoinHandle<()>>, EngineError> {
let mut thread_handles = vec![];
for plugin in &self.plugins {
let p = Arc::clone(plugin);
thread_handles.push(self.start_plugin(&self.context, p)?);
}
Ok(thread_handles)
}
fn start_external_plugins(&self) -> Result<Vec<JoinHandle<()>>, EngineError> {
let mut thread_handles = vec![];
for plugin in &self.external_plugins {
let p = Arc::clone(plugin);
thread_handles.push(self.start_external_plugin(&self.context, p)?);
}
Ok(thread_handles)
}
pub fn register_plugin(mut self, plugin: Arc<Box<dyn Plugin>>) -> Self {
self.plugins.push(plugin);
self
}
pub fn register_plugins(&mut self, plugins: Vec<Arc<Box<dyn Plugin>>>){
for plugin in plugins {
self.plugins.push(plugin);
}
}
pub fn register_external_plugin(mut self, plugin: Arc<Box<dyn ExternalPlugin>>) -> Self {
self.external_plugins.push(plugin);
self
}
pub fn register_external_plugins(&mut self, plugins: Vec<Arc<Box<dyn ExternalPlugin>>>) {
for plugin in plugins {
self.external_plugins.push(plugin);
}
}
pub fn run(self) -> Result<(), EngineError> {
println!("Engine starting application with {} plugins and {} external plugins on publish port: {} and subscribe port: {}.", self.plugins.len(), self.external_plugins.len(), self.app_config.publish_port, self.app_config.subscribe_port);
let outgoing = self.get_outgoing_socket()?;
let incoming = self.get_incoming_socket()?;
println!("Engine starting zmq proxy.");
let _proxy_thread = thread::spawn(move || {
let _result = zmq::proxy(&incoming, &outgoing)
.expect("Engine got error running proxy; socket was closed?");
});
println!("Engine has started proxy thread. Will now start and sync plugins");
let plugin_thread_handles = self.start_plugins()?;
let external_plugin_thread_handles = self.start_external_plugins()?;
self.sync_plugins(&self.context)?;
println!("All plugins started and synced; Will now wait for plugins to exit...");
for h in plugin_thread_handles {
h.join().unwrap();
}
println!(
"Engine joined all internal plugin threads; will now join external plugin threads."
);
for h in external_plugin_thread_handles {
h.join().unwrap();
}
println!("Engine joined all plugin threads.. ready to shut down.");
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::{str, sync::Arc, vec};
use zmq::Socket;
use crate::{
events::{Event, EventType},
plugins::Plugin,
App,
};
struct TypeAEventType {}
impl EventType for TypeAEventType {
fn get_name(&self) -> String {
let s = "TypeA";
s.to_string()
}
fn get_filter(&self) -> Result<Vec<u8>, crate::errors::EngineError> {
Ok(self.get_name().as_bytes().to_vec())
}
}
struct TypeAEvent {
message: String,
}
impl Event for TypeAEvent {
fn to_bytes(&self) -> Result<Vec<u8>, crate::errors::EngineError> {
let type_a = TypeAEventType {};
let result = [
type_a.get_filter().unwrap(),
self.message.as_bytes().to_vec(),
]
.concat();
Ok(result)
}
fn from_bytes(mut b: Vec<u8>) -> Result<TypeAEvent, Box<(dyn std::error::Error + 'static)>> {
for _i in 1..5 {
b.remove(0);
}
let msg = str::from_utf8(&b).unwrap();
Ok(TypeAEvent {
message: msg.to_string(),
})
}
}
struct TypeBEventType {}
impl EventType for TypeBEventType {
fn get_name(&self) -> String {
let s = "TypeB";
s.to_string()
}
fn get_filter(&self) -> Result<Vec<u8>, crate::errors::EngineError> {
Ok(self.get_name().as_bytes().to_vec())
}
}
struct TypeBEvent {
count: usize,
}
impl Event for TypeBEvent {
fn to_bytes(&self) -> Result<Vec<u8>, crate::errors::EngineError> {
let type_b = TypeBEventType {};
let message = format!("{}", self.count);
let result = [type_b.get_filter().unwrap(), message.as_bytes().to_vec()].concat();
Ok(result)
}
fn from_bytes(mut b: Vec<u8>) -> Result<TypeBEvent, Box<(dyn std::error::Error + 'static)>> {
for _i in 0..5 {
b.remove(0);
}
let msg = str::from_utf8(&b).unwrap();
Ok(TypeBEvent {
count: msg.to_string().parse().unwrap(),
})
}
}
struct MsgProducerPlugin {
id: uuid::Uuid,
}
impl MsgProducerPlugin {
fn new() -> Self {
MsgProducerPlugin {
id: uuid::Uuid::new_v4(),
}
}
}
impl Plugin for MsgProducerPlugin {
fn start(
&self,
pub_socket: Socket,
sub_socket: Socket,
) -> Result<(), crate::errors::EngineError> {
println!(
"MsgProducer (plugin id {}) start function starting...",
self.get_id()
);
println!(
"MsgProducer (plugin id {}) finished 1 second sleep",
self.get_id()
);
let mut total_messages_sent = 0;
while total_messages_sent < 5 {
let message = format!("This is message {}", total_messages_sent);
let m = TypeAEvent { message };
let data = m.to_bytes().unwrap();
println!("MsgProducer sending bytes: {:?}", data);
pub_socket.send(data, 0).unwrap();
total_messages_sent += 1;
println!(
"MsgProducer sent TypeA event message: {}",
total_messages_sent
);
}
println!("MsgProducer has sent all TypeA event messages, now waiting to receive TypeB events");
let mut total_messages_read = 0;
while total_messages_read < 5 {
let b = sub_socket.recv_bytes(0).unwrap();
println!("MsgProducer received TypeB message; bytes: {:?}", b);
let event_msg = TypeBEvent::from_bytes(b).unwrap();
let count = event_msg.count;
println!("Got a type B message; count was: {}", count);
total_messages_read += 1;
println!(
"MsgProducer received TypeB event message: {}",
total_messages_read
);
}
println!("MsgProducer has received all TypeB event messages; now exiting.");
Ok(())
}
fn get_subscriptions(&self) -> Result<Vec<Box<dyn EventType>>, crate::errors::EngineError> {
Ok(vec![Box::new(TypeBEventType {})])
}
fn get_id(&self) -> uuid::Uuid {
self.id
}
}
struct CounterPlugin {
id: uuid::Uuid,
}
impl CounterPlugin {
fn new() -> Self {
CounterPlugin {
id: uuid::Uuid::new_v4(),
}
}
}
impl Plugin for CounterPlugin {
fn start(
&self,
pub_socket: Socket,
sub_socket: Socket,
) -> Result<(), crate::errors::EngineError> {
println!(
"Counter (plugin id {}) start function starting...",
self.get_id()
);
let mut total_messages_read = 0;
while total_messages_read < 5 {
let b = sub_socket.recv_bytes(0).unwrap();
let event_msg = TypeAEvent::from_bytes(b).unwrap();
let count = event_msg.message.len();
total_messages_read += 1;
println!(
"Counter plugin received TypeA message: {}",
total_messages_read
);
let m = TypeBEvent { count };
let data = m.to_bytes().unwrap();
pub_socket.send(data, 0).unwrap();
println!("Counter plugin sent TypeB message: {}", total_messages_read);
}
println!("Counter plugin has sent all TypeB messages; now exiting.");
Ok(())
}
fn get_subscriptions(&self) -> Result<Vec<Box<dyn EventType>>, crate::errors::EngineError> {
Ok(vec![Box::new(TypeAEventType {})])
}
fn get_id(&self) -> uuid::Uuid {
self.id
}
}
#[test]
fn test_run_app() -> Result<(), String> {
println!("inside the test_run_app");
let msg_producer = MsgProducerPlugin::new();
let counter = CounterPlugin::new();
println!("plugins for test_run_app configured");
let app: App = App::new(5559, 5560);
app.register_plugin(Arc::new(Box::new(msg_producer)))
.register_plugin(Arc::new(Box::new(counter)))
.run()
.map_err(|e| format!("Got error from Engine! Details: {}", e))?;
println!("returned from test_run_app.run()");
Ok(())
}
}