eva-common 0.4.8

Commons for EVA ICS v4
Documentation
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
/// experimental shared lib extensions, not used yet
use crate::EvaError;
use serde::{Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr};

const CLASS_PHI: u16 = 10;
const CLASS_GENERIC_PLUGIN: u16 = 20;
const CLASS_AUTH_MODULE: u16 = 30;

#[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u16)]
pub enum EeExtensionClass {
    Phi = CLASS_PHI,
    GenericPlugin = CLASS_GENERIC_PLUGIN,
    AuthModule = CLASS_AUTH_MODULE,
}

pub mod prelude {
    pub use super::comm::ee_async_id;
    pub use super::comm::ee_decode;
    pub use super::comm::ee_encode;
    pub use super::comm::ee_send_async_result;
    pub use super::comm::EeFrame;
    pub use super::comm::EeFrameConv;
    pub use super::comm::EeResult;
    pub use super::comm::EeResultAsync;
    pub use super::EeExtensionClass;
    pub use super::EeMetadata;
    pub use crate::ee_commons;
    pub use crate::ee_get_option;
    pub use crate::ee_result;
    pub use crate::ee_unwrap_or;
}

impl From<libloading::Error> for EvaError {
    fn from(err: libloading::Error) -> EvaError {
        EvaError::failed(err)
    }
}

#[macro_export]
macro_rules! ee_unwrap_or {
    ($result: expr) => {
        match $result {
            Ok(v) => v,
            Err(e) => {
                return e.into();
            }
        }
    };
}

#[macro_export]
macro_rules! ee_get_option {
    ($data: expr, $key: expr) => {
        match $data.remove($key) {
            Some(v) => ee_unwrap_or!(v.try_into()),
            None => {
                return EvaError::invalid_data(format!("The parameter is missing: {}", $key))
                    .into();
            }
        }
    };
    ($data: expr, $key: expr, $v: expr) => {
        match $data.remove($key) {
            Some(v) => ee_unwrap_or!(v.try_into()),
            None => $v,
        }
    };
}

#[macro_export]
macro_rules! ee_commons {
    () => {
        #[no_mangle]
        pub unsafe fn set_logger_fn(func: fn($crate::ext::comm::EeFrame), level: u8) -> EeResult {
            $crate::ext::logger::set_logger_fn(func, level)
        }

        #[no_mangle]
        pub unsafe fn set_async_result_fn(
            func: fn(u32, u32, $crate::ext::comm::EeFrame),
        ) -> EeResult {
            $crate::ext::comm::set_async_result_fn(func)
        }

        #[no_mangle]
        pub unsafe fn free_result() -> EeResult {
            $crate::ext::free_result()
        }

        #[no_mangle]
        pub unsafe fn get_comm_version() -> u16 {
            $crate::ext::comm::COMM_VERSION
        }

        #[no_mangle]
        pub fn set_id(id: u32) -> EeResult {
            $crate::ext::comm::set_id(id);
            EeResult::ok()
        }

        #[no_mangle]
        pub unsafe fn set_name(data: EeFrame) -> EeResult {
            let name = ee_unwrap_or!(data.decode());
            $crate::ext::logger::set_name(name);
            EeResult::ok()
        }
    };
}

#[macro_export]
macro_rules! ee_result {
    ($result: expr) => {
        match $result {
            Ok(v) => v.to_eeframe(),
            Err(e) => e.into(),
        }
    };
}

#[derive(Debug, Serialize, Deserialize)]
pub struct EeMetadata {
    pub class: EeExtensionClass,
    #[serde(default)]
    pub author: String,
    #[serde(default)]
    pub copyright: String,
    #[serde(default)]
    pub license: String,
    #[serde(default)]
    pub description: String,
    #[serde(default)]
    pub version: u32,
    pub api: u32,
}

pub unsafe fn free_result() -> comm::EeResult {
    comm::clear_data();
    comm::EeResult::ok()
}

pub mod comm {

    use crate::{EvaError, EvaErrorKind};
    use serde::{Deserialize, Serialize};
    use std::cell::RefCell;
    use std::sync::{atomic, Mutex};

    pub const RESULT_OK: i16 = 0;
    pub const COMM_VERSION: u16 = 1;

    const ERR_UNSUPPORTED_COMM_VERSION: &str = "Unsupported comm version";

    pub fn version_supported(ver: u16) -> Result<(), EvaError> {
        if ver > COMM_VERSION {
            Err(EvaError::unsupported(ERR_UNSUPPORTED_COMM_VERSION))
        } else {
            Ok(())
        }
    }

    #[repr(C)]
    pub struct EeFrame {
        code: i16,           // code (used for errors only)
        length: u32,         // data length
        data_ptr: *const u8, // raw pointer to the frame data
    }

    impl EeFrame {
        pub fn decode<'a, T: Deserialize<'a>>(self) -> Result<T, EvaError> {
            unsafe { ee_decode(COMM_VERSION, self) }
        }
        pub fn decode_ver<'a, T: Deserialize<'a>>(self, comm_ver: u16) -> Result<T, EvaError> {
            unsafe { ee_decode(comm_ver, self) }
        }
        pub fn ok() -> EeFrame {
            unsafe { ee_encode(COMM_VERSION, RESULT_OK, &None::<u32>).unwrap() }
        }
    }

    impl From<EvaError> for EeFrame {
        fn from(err: EvaError) -> EeFrame {
            err.to_eeframe()
        }
    }

    #[repr(C)]
    pub struct EeResult(i16);

    impl EeResult {
        pub fn decode_ver(&self, comm_ver: u16) -> Result<(), EvaError> {
            if comm_ver != 1 {
                return Err(EvaError::unsupported(ERR_UNSUPPORTED_COMM_VERSION));
            }
            if self.0 == RESULT_OK {
                Ok(())
            } else {
                Err(EvaError::new0(self.0.into()))
            }
        }
        pub fn decode(&self) -> Result<(), EvaError> {
            self.decode_ver(COMM_VERSION)
        }
        pub fn ok() -> Self {
            Self(RESULT_OK)
        }
    }

    impl From<EvaError> for EeResult {
        fn from(err: EvaError) -> EeResult {
            EeResult(err.kind as i16)
        }
    }

    impl From<EvaErrorKind> for EeResult {
        fn from(kind: EvaErrorKind) -> EeResult {
            EeResult(kind as i16)
        }
    }

    #[repr(C)]
    pub struct EeResultAsync(i16, u32);

    impl EeResultAsync {
        pub fn decode_ver(&self, comm_ver: u16) -> Result<u32, EvaError> {
            if comm_ver != 1 {
                return Err(EvaError::unsupported(ERR_UNSUPPORTED_COMM_VERSION));
            }
            if self.0 == RESULT_OK {
                Ok(self.1)
            } else {
                Err(EvaError::new0(self.0.into()))
            }
        }
        pub fn decode(&self) -> Result<u32, EvaError> {
            self.decode_ver(COMM_VERSION)
        }
        pub fn ok(async_id: u32) -> Self {
            Self(RESULT_OK, async_id)
        }
    }

    impl From<EvaError> for EeResultAsync {
        fn from(err: EvaError) -> EeResultAsync {
            EeResultAsync(err.kind as i16, 0)
        }
    }

    impl From<EvaErrorKind> for EeResultAsync {
        fn from(kind: EvaErrorKind) -> EeResultAsync {
            EeResultAsync(kind as i16, 0)
        }
    }

    #[repr(C)]
    pub struct DataFrame {
        data: Vec<u8>,
    }

    trait EeErrorConv {
        fn to_eeframe(&self) -> EeFrame;
        fn to_eeframe_ver(&self, comm_ver: u16) -> EeFrame;
    }

    impl EeErrorConv for EvaError {
        fn to_eeframe(&self) -> EeFrame {
            unsafe { ee_encode(COMM_VERSION, self.kind as i16, &self.message) }.unwrap()
        }
        fn to_eeframe_ver(&self, comm_ver: u16) -> EeFrame {
            unsafe { ee_encode(comm_ver, self.kind as i16, &self.message) }.unwrap()
        }
    }

    pub trait EeFrameConv {
        fn ee_encode(&self) -> Result<EeFrame, EvaError>;
        fn ee_encode_ver(&self, comm_ver: u16) -> Result<EeFrame, EvaError>;
        fn to_eeframe(&self) -> EeFrame;
        fn to_eeframe_ver(&self, comm_ver: u16) -> EeFrame;
    }

    macro_rules! unwrap_or_err_frame {
        ($comm_ver: expr, $result: expr) => {
            $result.unwrap_or_else(|e| e.to_eeframe_ver($comm_ver))
        };
    }

    impl<T> EeFrameConv for T
    where
        T: Serialize,
    {
        fn ee_encode(&self) -> Result<EeFrame, EvaError> {
            unsafe { ee_encode(COMM_VERSION, 0, self) }
        }
        fn ee_encode_ver(&self, comm_ver: u16) -> Result<EeFrame, EvaError> {
            unsafe { ee_encode(comm_ver, 0, self) }
        }
        fn to_eeframe(&self) -> EeFrame {
            unwrap_or_err_frame!(COMM_VERSION, unsafe { ee_encode(COMM_VERSION, 0, self) })
        }
        fn to_eeframe_ver(&self, comm_ver: u16) -> EeFrame {
            unwrap_or_err_frame!(comm_ver, unsafe { ee_encode(comm_ver, 0, self) })
        }
    }

    impl DataFrame {
        pub fn with_data(data: Vec<u8>) -> Self {
            Self { data }
        }
        pub fn set_data(&mut self, data: Vec<u8>) {
            self.data = data;
        }
        pub fn as_frame(&self, code: i16) -> EeFrame {
            EeFrame {
                code,
                length: self.data.len() as u32,
                data_ptr: self.data.as_ptr(),
            }
        }
        pub fn clear(&mut self) {
            self.data.clear();
        }
    }

    static mut DATA: DataFrame = DataFrame { data: Vec::new() };
    static mut ASYNC_ID: u32 = 0;

    static ID: atomic::AtomicU32 = atomic::AtomicU32::new(0);

    pub fn ee_async_id() -> u32 {
        unsafe {
            if ASYNC_ID == std::u32::MAX {
                ASYNC_ID = 0;
            }
            ASYNC_ID += 1;
            ASYNC_ID
        }
    }

    thread_local! {
        pub static TDATA: RefCell<DataFrame> = RefCell::new(DataFrame { data: Vec::new() });
    }

    lazy_static! {
        static ref ASYNC_RESULT: Mutex<Option<fn(u32, u32, EeFrame)>> = Mutex::new(None);
    }

    pub unsafe fn set_async_result_fn(func: fn(u32, u32, EeFrame)) -> EeResult {
        ASYNC_RESULT.lock().unwrap().replace(func);
        EeResult::ok()
    }

    pub fn ee_send_async_result<T: Serialize>(async_id: u32, result: Result<T, EvaError>) {
        if let Some(async_result) = ASYNC_RESULT.lock().unwrap().as_ref() {
            TDATA.with(|cell| {
                let id = ID.load(atomic::Ordering::SeqCst);
                let mut tdata = cell.borrow_mut();
                match result {
                    Ok(ref v) => {
                        tdata.data = rmp_serde::to_vec_named(v).unwrap();
                        async_result(id, async_id, tdata.as_frame(RESULT_OK));
                    }
                    Err(e) => {
                        tdata.data = rmp_serde::to_vec_named(&e.message).unwrap();
                        async_result(id, async_id, tdata.as_frame(e.kind as i16));
                    }
                }
                tdata.clear();
            });
        } else {
            panic!("async result function is not set");
        }
    }

    pub fn set_id(id: u32) {
        ID.store(id, atomic::Ordering::SeqCst);
    }

    pub unsafe fn ee_encode<T: Serialize>(
        comm_ver: u16,
        code: i16,
        data: &T,
    ) -> Result<EeFrame, EvaError> {
        if comm_ver != 1 {
            return Err(EvaError::unsupported(ERR_UNSUPPORTED_COMM_VERSION));
        }
        DATA = DataFrame::with_data(rmp_serde::to_vec_named(data)?);
        Ok(DATA.as_frame(code))
    }

    pub unsafe fn ee_decode<'de, T: Deserialize<'de>>(
        comm_ver: u16,
        frame: EeFrame,
    ) -> Result<T, EvaError> {
        if comm_ver != 1 {
            return Err(EvaError::unsupported(ERR_UNSUPPORTED_COMM_VERSION));
        }
        let data_slice = std::slice::from_raw_parts(frame.data_ptr, frame.length as usize);
        if frame.code == RESULT_OK {
            Ok(rmp_serde::from_slice(data_slice)?)
        } else {
            let message: Option<String> = rmp_serde::from_slice(data_slice)?;
            Err(EvaError::newc(frame.code.into(), message))
        }
    }

    pub unsafe fn clear_data() {
        DATA.clear();
    }
}

pub mod logger {
    use super::comm::{EeFrame, EeResult, RESULT_OK};
    use log::{debug, error, info, trace, warn};
    use log::{Level, LevelFilter, Log, Record};
    use serde::{Deserialize, Serialize};

    #[derive(Serialize, Deserialize)]
    pub struct LogRecord {
        #[serde(rename = "l")]
        level: u8,
        #[serde(rename = "m")]
        message: String,
    }

    impl LogRecord {
        pub fn send(&self) {
            match self.level {
                crate::LOG_LEVEL_TRACE => trace!("{}", self.message),
                crate::LOG_LEVEL_DEBUG => debug!("{}", self.message),
                crate::LOG_LEVEL_WARN => warn!("{}", self.message),
                crate::LOG_LEVEL_ERROR => error!("{}", self.message),
                _ => info!("{}", self.message),
            }
        }
    }

    static mut LOGGER: Logger = Logger {
        name: String::new(),
        logger_function: None,
    };

    pub struct Logger {
        logger_function: Option<fn(EeFrame)>,
        name: String,
    }

    impl Logger {
        fn set_logger_function(&mut self, func: fn(EeFrame)) {
            self.logger_function = Some(func);
        }
        fn set_name(&mut self, name: &str) {
            self.name = name.to_owned();
        }
    }

    impl Log for Logger {
        fn enabled(&self, _metadata: &log::Metadata) -> bool {
            true
        }
        fn log(&self, record: &Record) {
            crate::ext::comm::TDATA.with(|cell| {
                let mut tdata = cell.borrow_mut();
                let log_record = LogRecord {
                    level: {
                        match record.level() {
                            Level::Trace => crate::LOG_LEVEL_TRACE,
                            Level::Debug => crate::LOG_LEVEL_DEBUG,
                            Level::Info => crate::LOG_LEVEL_INFO,
                            Level::Warn => crate::LOG_LEVEL_WARN,
                            Level::Error => crate::LOG_LEVEL_ERROR,
                        }
                    },
                    message: format!("{}: {}", self.name, record.args()),
                };
                match rmp_serde::to_vec_named(&log_record) {
                    Ok(data) => {
                        tdata.set_data(data);
                        (self.logger_function.unwrap())(tdata.as_frame(RESULT_OK));
                        tdata.clear();
                    }
                    Err(e) => eprintln!("{} unable to send log record frame: {}", self.name, e),
                }
            });
        }
        fn flush(&self) {}
    }

    fn get_level_filter(level: u8) -> LevelFilter {
        match level {
            crate::LOG_LEVEL_TRACE => LevelFilter::Trace,
            crate::LOG_LEVEL_DEBUG => LevelFilter::Debug,
            crate::LOG_LEVEL_WARN => LevelFilter::Warn,
            crate::LOG_LEVEL_ERROR => LevelFilter::Error,
            _ => LevelFilter::Info,
        }
    }

    pub unsafe fn set_logger_fn(func: fn(EeFrame), level: u8) -> EeResult {
        LOGGER.set_logger_function(func);
        LOGGER.set_name("noname_extension");
        log::set_logger(&LOGGER)
            .map(|()| log::set_max_level(get_level_filter(level)))
            .unwrap();
        EeResult::ok()
    }

    pub unsafe fn set_name(name: &str) {
        LOGGER.set_name(name);
    }
}

pub mod auth {

    use serde::{Deserialize, Serialize};
    use std::time::Duration;

    /// Authentication request
    ///
    /// Timeout is in nanoseconds
    #[derive(Debug, Serialize, Deserialize, Clone)]
    pub struct Request {
        #[serde(rename = "l")]
        login: Option<String>,
        #[serde(rename = "p")]
        password: Option<String>,
        #[serde(rename = "t")]
        timeout: u64, // nanoseconds
    }

    impl Request {
        pub fn new(login: String, password: String, timeout: Duration) -> Self {
            Self {
                login: Some(login),
                password: Some(password),
                timeout: timeout.as_nanos() as u64,
            }
        }
        pub fn take_login(&mut self) -> String {
            self.login.take().unwrap()
        }
        pub fn take_password(&mut self) -> String {
            self.password.take().unwrap()
        }
        pub fn timeout_as_duration(&self) -> Duration {
            Duration::from_nanos(self.timeout)
        }
        pub fn timeout_as_nanos(&self) -> u64 {
            self.timeout
        }
    }
}