u2400_pathnode 0.1.6

path cluster base library
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
use super::util::{get_hashmap_keys, get_micro_unix_timestemp, get_now_time, NodeTokens, token2string};
use anyhow::{anyhow, Error, Ok, Result};
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use ring::digest;
use std::collections::HashMap;
use std::mem;

pub type VoterType = fn(&HashMap<String, PathNode>, &mut Context) -> Result<bool>;
pub type CheckerType = fn(&HashMap<String, PathNode>, &mut Context) -> Result<bool>;

#[derive(Debug)]
pub struct Context {
    pub deep: u64,
    pub is_ignore_dynamic_arg: bool,
    pub is_need_cluster: bool,
}

impl Context {
    pub fn new() -> Context {
        Context {
            deep: 0,
            is_ignore_dynamic_arg: false,
            is_need_cluster: true,
        }
    }
}

#[derive(Debug, Clone)]
pub struct PathNode {
    pub name: String,                          // node的名称
    pub index_name: String,                    //index的name属性引用
    pub id: u64,                               // mysql中的id
    pub first_insert_time: u64,                // 第一次写入的时间戳
    pub last_search_time: u64,                 // 最后一次被匹配成功的时间戳
    pub match_counter: u64,                    // 该节点作为规则的一部分被匹配成功的次数
    pub try_cluster_time: u64,                  // 该节点最近一次尝试归一化时间
    pub next_nodes: HashMap<String, PathNode>, //下一级节点的HashMap
    pub is_end: bool,
}


impl PathNode {
    pub fn new(name: &str) -> PathNode {
        let now = get_now_time();

        let pathnode = PathNode {
            name: name.to_owned().clone(),
            index_name: "".to_string(),
            id: 0,
            first_insert_time: now,
            last_search_time: now,
            match_counter: 0,
            try_cluster_time: now,
            next_nodes: HashMap::new(),
            is_end: false,
        };

        pathnode
    }

    pub fn build(
        name: &str,
        index_name: String,
        id: u64, 
        first_insert_time: u64, 
        last_search_time: u64, 
        match_counter: u64, 
        is_end: bool,
    ) -> PathNode {
        let pathnode = PathNode {
            name: name.to_string(),
            id: id,
            first_insert_time: first_insert_time,
            last_search_time: last_search_time,
            match_counter: match_counter,
            try_cluster_time: 0,
            next_nodes: HashMap::new(),
            index_name: index_name.to_string(),
            is_end: is_end,

        };
        return pathnode;
    }

    pub fn set_index_point(&mut self, index_name: String) -> Result<()> {
        let id = PathNode::get_init_id(&self.name, index_name.to_string())?;
        self.id = id;
        self.index_name = index_name;

        Ok(())
    }

    fn get_init_id(node_name: &str, index_name: String) -> Result<u64> {
        let now = get_micro_unix_timestemp();

        let rand_string: String = thread_rng()
            .sample_iter(Alphanumeric)
            .take(128)
            .map(char::from)
            .collect();

        let hash_result = digest::digest(
            &digest::SHA256,
            format!("{}{}{}{}", now, index_name, node_name, rand_string).as_bytes(),
        );

        let b: u64;
        // 当输入的[u8]长度小于8时有可能报错, 此处通过sha256算法保证长度大于8
        let arr: [u8; 8] = hash_result.as_ref()[0..8].try_into()?;
        unsafe {
            b = mem::transmute::<[u8; 8], u64>(arr);
        }

        Ok(b)
    }

    pub fn is_exists(&self, name: &str) -> bool {
        return self.next_nodes.contains_key(name);
    }

    pub fn get_mut(&mut self, name: &str) -> Option<&mut PathNode> {
        if self.is_exists(name) {
            self.get_mut_strictly(name)
        } else if self.is_exists("*") {
            self.get_mut_strictly("*")
        } else {
            return None;
        }
    }

    pub fn get(&self, name: &str) -> Option<&PathNode> {
        if self.is_exists(name) {
            self.get_strictly(name)
        } else if self.is_exists("*") {
            self.get_strictly("*")
        } else {
            None
        }
    }

    pub fn get_strictly(&self, name: &str) -> Option<&PathNode> {
        self.next_nodes.get(name)
    }

    pub fn get_mut_strictly(&mut self, name: &str) -> Option<&mut PathNode> {
        self.next_nodes.get_mut(name)
    }

    pub fn get_mut_by_node_list(&mut self, node_list: &[&str], context: &mut Context) -> Option<&mut PathNode> {
        if node_list.len() == 0 {
            return Some(self)
        }

        let node_name = node_list[0];
        let new_node_list = &node_list[1..];

        let get_result = if context.is_ignore_dynamic_arg {
            self.get_mut_strictly(node_name)
        }
        else {
            self.get_mut(node_name)
        };

        return if let Some(node) = get_result {
            Some(node.get_mut_by_node_list(new_node_list, context)?)
        }
        else {
            None 
        };
    }

    pub fn merge_by_node_list(&mut self, node_list: &[&str], context: &mut Context) -> Result<()> {
        let r = self.get_mut_by_node_list(node_list, context);
        match r {
            Some(node) => {
                node.merge_node()
            }
            None => {
                Err(anyhow!("merge_by_node_list: node not find"))
            }
        }
    }

    pub fn set_token_by_node_list(&mut self, node_list: &[&str], token_type: NodeTokens, clear_node: bool, context: &mut Context) -> Result<()> {
        let r = self.get_mut_by_node_list(node_list, context);
        match r {
            Some(node) => {
                if clear_node {
                    node.next_nodes.clear();
                }

                let token_str = &token2string(token_type);
                if !node.is_exists(&token_str) {
                    node.add(token_str)
                }
                else {
                    Ok(())
                }
            }
            None => {
                Err(anyhow!("merge_by_node_list: node not find"))
            }
        }
    }

    pub fn add(&mut self, node_name: &str) -> Result<()> {
        let mut new_node = PathNode::new(node_name);
        new_node.set_index_point(self.index_name.to_string())?;
        self.add_pathnode(node_name, new_node)?;
        Ok(())
    }

    pub fn add_pathnode(&mut self, node_name: &str, node: PathNode) -> Result<()> {
        //判断该name是否已存在
        let is_exists = self.is_exists(node_name);

        if is_exists {
            panic!("node_name已存在, 该方法不允许进行覆盖");
        } else {
            self.next_nodes.insert(node_name.to_string(), node);
        }
        Ok(())
    }

    pub fn success_match(&mut self) -> Result<()> {
        self.match_counter += 1;
        self.last_search_time = get_now_time();
        Ok(())
    }

    pub fn add_by_node_list(
        &mut self, 
        node_list: &[&str], 
        context: &mut Context, 
        voter: VoterType,
        checker: CheckerType,
    ) -> Result<()> {
        context.deep += 1;
        
        // 若node_list的为空
        if node_list.len() == 0 {
            // 如果is_end为false则更新
            if self.is_end == false {
                self.is_end = true;
            }
            // return 结束递归
            return Ok(());
        }

        let node_name = node_list[0];
        let new_node_list = &node_list[1..];

        let get_result = if context.is_ignore_dynamic_arg {
            self.get_mut_strictly(node_name)
        }
        else {
            self.get_mut(node_name)
        };

        match get_result {
            Some(node) => {
                node.success_match()?;
                node
            },
            None => {
                self.add(node_name)?;
                self.get_mut(node_name).unwrap()
            }
        }
        .add_by_node_list(new_node_list, context, voter, checker)?;

        context.deep -= 1;
        // 触发归一化
        if context.is_need_cluster {
            self.merge_node_by_func(voter, checker, context).unwrap();
        }

        Ok(())
    }

    pub fn get_next_ids_json_string(&self) -> Result<String> {
        let mut ids: Vec<u64> = vec![];
        for node in self.next_nodes.values() {
            ids.push(node.id);
        }
        Ok(serde_json::to_string(&ids)?)
    }

    pub fn sync_read_callback(&self, callback: fn(&Self, &mut Context)->Result<()>, context: &mut Context, is_need_traversal: bool) -> Result<()> {
        callback(&self, context)?;
        if is_need_traversal {
            for node in self.next_nodes.values() {
                node.sync_read_callback(callback, context, is_need_traversal)?;
            }
        }
        Ok(())
    }

    pub fn try_match_rule(&self, node_list: &[&str]) -> Result<String> {
        // 若node_list的为空
        if node_list.len() == 0 && self.is_end == true {
            // return 结束递归
            return Ok(format!("{}/", self.name.clone()));
        } else if node_list.len() == 0 && self.is_end == false {
            return Err(Error::msg(format!(
                "规则匹配失败, node_name: {}, 为非终止节点",
                self.name
            )));
        }

        let node_name = node_list[0];
        let new_node_list = &node_list[1..];

        if self.is_exists(node_name) {
            let path = self
                .get(node_name)
                .unwrap()
                .try_match_rule(new_node_list)?;
            Ok(format!("{}/{}", self.name.clone(), path))
        } else if self.is_exists("*") {
            let path = self.get("*").unwrap().try_match_rule(new_node_list)?;
            Ok(format!("{}/{}", self.name.clone(), path))
        } else {
            Err(Error::msg(format!(
                "规则匹配失败, node_name: {}, 不存在",
                node_name
            )))
        }
    }

    fn merge_node(&mut self) -> Result<()> {
        let mut new_next: HashMap<String, PathNode> = HashMap::new();
        // 获取所有子节点
        let next_nodes = &mut self.next_nodes;

        let keys: Vec<String> = get_hashmap_keys(next_nodes);
        for key in keys {
            // 获取子节点的next_nodes属性
            let level_1_child_node = next_nodes.get_mut(&key).unwrap();
            // delete_node_in_mysql(level_1_child_node.id).await?;
            let one_node_next = &mut level_1_child_node.next_nodes;

            // 遍历子节点的next_nodes属性, 获取二级子节点
            let level_2_keys: Vec<String> = get_hashmap_keys(one_node_next);
            for node_name in level_2_keys {
                let node = one_node_next.remove(&node_name).unwrap();
                new_next.insert(node_name.to_owned(), node);
            }
        }
        // 清空历史子节点
        self.next_nodes.clear();

        // 添加合并后节点
        self.add("*")?;

        // 修改新节点的next
        let new_node = self.next_nodes.get_mut("*").unwrap();
        new_node.next_nodes = new_next;

        // 如果新节点的next为0, 修改该节点为终止节点
        if new_node.next_nodes.len() == 0 {
            new_node.is_end = true
        }

        Ok(())
    }

    pub fn merge_node_by_func(
        &mut self,
        voter: VoterType,
        checker: CheckerType,
        context: &mut Context,
    ) -> Result<()> {
        let vote_result = voter(&self.next_nodes, context).unwrap();
        if vote_result {
            if checker(&self.next_nodes, context).unwrap() {
                self.merge_node()?;
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // #[tokio::test]
    // async fn test_pyo3() {
    //     Python::with_gil(|py| {
    //         let app = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/py_app/app.py"));
    //         let m = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/py_app/RobertaClassifier.py"));

    //         PyModule::from_code(py, m, "RobertaClassifier", "RobertaClassifier")?;
    //         PyModule::from_code(py, app, "App", "App")?;
    //         Ok(())
    //     }).unwrap();
    //     // let r = util::is_need_cluster("C7b").unwrap();
    //     // println!("{:#?}", r);
    // }

    // #[tokio::test]
    // async fn test_rule() {
    //     let mut im = IndexManager::new();
    //     let mut i = im.create_index("").await.unwrap().lock().await;

    //     println!("{}", i.try_match_rule("/a1/b/c/d1/d1").await.unwrap());
    // }

    // #[test]
    // fn test_sha256() {
    //     let hash_result = digest::digest(&digest::SHA256, format!("{}", "123").as_bytes());

    //     let b: u64;
    //     let arr: [u8; 8] = hash_result.as_ref()[0..8].try_into().unwrap();
    //     unsafe {
    //         b = mem::transmute::<[u8; 8], u64>(arr);
    //     }
    //     println!("{}", b);
    // }
}