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
#![allow(non_snake_case)]
//! ## Rust Cat Bindings
//!
//! NB: This crate is meanly mostly created for Nodejs's Native Addons(using neon) currently.
//!
//! ## Usage
//!
//! ```rust,no_run
//! extern crate cat_rs as cat;
//! use cat::{
//!     logEvent,
//!     CatClient,
//!     CatTransaction,
//! };
//!
//! let mut cat = CatClient::new("test");
//! cat.init().unwrap();
//! let mut tr = CatTransaction::new("foo", "bar");
//! tr.log("test", "it", "0", "");
//! tr.complete();
//! ```
#[macro_use]
extern crate log;
extern crate libc;
extern crate num_cpus;
extern crate threadpool;

use std::error;
use std::ffi::CStr;
use std::ffi::CString;
use std::fmt;
use std::result;
use std::sync::atomic::AtomicBool;
use std::sync::mpsc;

use threadpool::ThreadPool;

macro_rules! c {
    ($data:ident) => {
        CString::new($data).unwrap().as_ptr()
    };
    ($expr:expr) => {
        CString::new($expr).unwrap().as_ptr()
    };
}

thread_local!(
    static POOL: ThreadPool = ThreadPool::new(num_cpus::get())
);

pub(crate) mod ffi;

use ffi::catClientDestroy;
use ffi::catClientInitWithConfig;
use ffi::catVersion;
use ffi::newTransaction;
use ffi::CatClientConfig;
use ffi::DEFAULT_CCAT_CONFIG;

#[derive(Debug, Clone)]
pub enum CatError {
    CatClientInitError,
}

impl error::Error for CatError {
    fn description(&self) -> &str {
        "cat client init failed!"
    }
}

impl fmt::Display for CatError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            CatError::CatClientInitError => write!(f, "CatClientInitError"),
        }
    }
}

type Result<T> = result::Result<T, CatError>;

/// cat client
pub struct CatClient {
    /// client initialization key
    appkey: String,
    /// client config
    config: CatClientConfig,
}

impl CatClient {
    /// create a new cat client
    ///
    /// # Arguments
    ///
    /// * `appkey` - key which impl ToString
    ///
    pub fn new<T: ToString>(appkey: T) -> Self {
        CatClient {
            appkey: appkey.to_string(),
            config: unsafe { DEFAULT_CCAT_CONFIG },
        }
    }

    /// set cat client config
    pub fn config(&mut self, config: &mut CatClientConfig) -> &mut Self {
        self.config = *config;
        self
    }

    /// initialize cat client
    pub fn init(&mut self) -> Result<&mut Self> {
        let rc = unsafe {
            catClientInitWithConfig(
                CString::new(self.appkey.clone()).unwrap().as_ptr(),
                &mut self.config,
            )
        };

        if rc == 0 {
            error!("{}", CatError::CatClientInitError);
            Err(CatError::CatClientInitError)
        } else {
            Ok(self)
        }
    }

    /// destroy a cat client
    pub fn destroy(&self) {
        warn!("cat client is being destroyed!");
        unsafe { catClientDestroy() };
    }

    /// get cat client version
    pub fn version(&self) -> &str {
        unsafe { CStr::from_ptr(catVersion()).to_str().unwrap() }
    }
}

pub enum CatMessage {
    LogEvent(String, String, String, String),
    Transaction(String),
    CompleteThis,
}

pub struct CatTransaction {
    sender: mpsc::Sender<CatMessage>,
    open: AtomicBool,
}

impl CatTransaction {
    pub fn new<T: ToString>(_type: T, _name: T) -> Self {
        let (sender, receiver) = mpsc::channel::<CatMessage>();
        let _type = _type.to_string();
        let _name = _name.to_string();
        POOL.with(|pool| {
            pool.execute(move || {
                debug!("create a new transaction: {} / {}", _type, _name);
                let tr = unsafe { newTransaction(c!(_type.clone()), c!(_name)) };

                if tr.is_null() {
                    error!("create transaction failed!");
                    panic!("create transaction failed!")
                } else {
                    // loop in this thread as is this root transaction
                    'trans: loop {
                        match receiver.recv() {
                            Ok(message) => {
                                match message {
                                    // TODO: inner transaction
                                    CatMessage::Transaction(name) => {
                                        let tr =
                                            unsafe { newTransaction(c!(_type.clone()), c!(name)) };
                                        if !tr.is_null() {
                                            if let Some(complete) = unsafe { (*tr).complete } {
                                                unsafe {
                                                    complete(tr);
                                                };
                                            } else {
                                                error!("transaction's complete method is missing");
                                            }
                                        }
                                    }
                                    CatMessage::LogEvent(type_, name, status, data) => {
                                        logEvent(type_, name, status, data)
                                    }
                                    CatMessage::CompleteThis => {
                                        break 'trans;
                                    }
                                }
                            }
                            Err(err) => {
                                error!("receive job failed, err: {}", err);
                                break 'trans;
                            }
                        }
                    }

                    if let Some(complete) = unsafe { (*tr).complete } {
                        debug!("complete this transaction");
                        unsafe {
                            complete(tr);
                        };
                    } else {
                        error!("transaction's complete method is missing");
                    }
                }
            });
        });
        CatTransaction {
            sender,
            open: AtomicBool::new(true),
        }
    }

    pub fn complete(&mut self) {
        if *self.open.get_mut() {
            self.sender
                .send(CatMessage::CompleteThis)
                .map_err(|e| {
                    error!("complete transaction error: {}", e);
                })
                .unwrap()
        } else {
            warn!("complete a closed transaction");
        }
    }

    pub fn log<T: ToString>(&mut self, type_: T, name: T, status: T, data: T) {
        if *self.open.get_mut() {
            self.sender
                .send(CatMessage::LogEvent(
                    type_.to_string(),
                    name.to_string(),
                    status.to_string(),
                    data.to_string(),
                ))
                .map_err(|e| {
                    error!("log event error: {}", e);
                })
                .unwrap()
        } else {
            warn!("log event on a closed transaction");
        }
    }
}

/// log a cat event
///
/// # Arguments
/// * `type_` - event type
/// * `name_` - event name
/// * `status` - event status type "0" or other
/// * `data` - event data
/// # Example
/// ```rust,no_run
/// // logEvent("app", "foo", "0", "");
/// ```
pub fn logEvent<S: ToString>(type_: S, name_: S, status: S, data: S) {
    unsafe {
        ffi::logEvent(
            c!(type_.to_string()),
            c!(name_.to_string()),
            c!(status.to_string()),
            c!(data.to_string()),
        )
    }
}

pub fn newHeartBeat<S: ToString>(_type: S, _name: S) {
    info!(
        "start a new heart beat: {} {}",
        _type.to_string(),
        _name.to_string(),
    );
    unsafe {
        ffi::newHeartBeat(c!(_type.to_string()), c!(_name.to_string()));
    }
}