-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.rs
More file actions
108 lines (100 loc) · 3.5 KB
/
Copy pathcache.rs
File metadata and controls
108 lines (100 loc) · 3.5 KB
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
use crate::{StdFunction, StdlibModule, StdlibRegistry};
use indexmap::IndexMap;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::time::Instant;
use techscript_runtime::{error::RuntimeError, value::RuntimeValue};
thread_local! {
static CACHE: RefCell<IndexMap<String, (RuntimeValue, Instant, u64)>> = RefCell::new(IndexMap::new());
}
impl StdlibRegistry {
pub fn register_cache(&mut self) {
let mut exports: HashMap<String, Rc<dyn techscript_runtime::function::Callable>> =
HashMap::new();
exports.insert(
"set".to_string(),
Rc::new(StdFunction {
name: "set".to_string(),
arity: 2,
callback: |_ctx, args| {
let key = args[0].to_string();
let val = args[1].clone();
CACHE.with(|c| c.borrow_mut().insert(key, (val, Instant::now(), 0)));
Ok(RuntimeValue::Null)
},
}),
);
exports.insert(
"set_ttl".to_string(),
Rc::new(StdFunction {
name: "set_ttl".to_string(),
arity: 3,
callback: |_ctx, args| {
let key = args[0].to_string();
let val = args[1].clone();
let ttl = args[2].try_into_int().unwrap_or(0) as u64;
CACHE.with(|c| c.borrow_mut().insert(key, (val, Instant::now(), ttl)));
Ok(RuntimeValue::Null)
},
}),
);
exports.insert(
"get".to_string(),
Rc::new(StdFunction {
name: "get".to_string(),
arity: 1,
callback: |_ctx, args| {
let key = args[0].to_string();
let result = CACHE.with(|c| {
let mut cache = c.borrow_mut();
if let Some((val, time, ttl)) = cache.get(&key) {
if *ttl > 0 && time.elapsed().as_secs() > *ttl {
cache.shift_remove(&key);
return RuntimeValue::Null;
}
val.clone()
} else {
RuntimeValue::Null
}
});
Ok(result)
},
}),
);
exports.insert(
"remove".to_string(),
Rc::new(StdFunction {
name: "remove".to_string(),
arity: 1,
callback: |_ctx, args| {
let key = args[0].to_string();
CACHE.with(|c| {
c.borrow_mut().shift_remove(&key);
});
Ok(RuntimeValue::Null)
},
}),
);
exports.insert(
"clear".to_string(),
Rc::new(StdFunction {
name: "clear".to_string(),
arity: 0,
callback: |_ctx, _args| {
CACHE.with(|c| c.borrow_mut().clear());
Ok(RuntimeValue::Null)
},
}),
);
self.register_module(
"std.cache",
StdlibModule {
name: "std.cache".to_string(),
version: "1.0.0".to_string(),
exports,
required_capabilities: Vec::new(),
},
);
}
}