| 13 | mod vendor_ieee754; |
| 14 | |
| 15 | pub async fn decode( |
| 16 | recv_time: DateTime<Utc>, |
| 17 | f_port: u8, |
| 18 | variables: &HashMap<String, String>, |
| 19 | decode_config: &str, |
| 20 | b: &[u8], |
| 21 | ) -> Result<pbjson_types::Struct> { |
| 22 | let conf = config::get(); |
| 23 | let max_run_ts = SystemTime::now() + conf.codec.js.max_execution_time; |
| 24 | |
| 25 | let resolver = rquickjs::loader::BuiltinResolver::default() |
| 26 | .with_module("base64-js") |
| 27 | .with_module("ieee754") |
| 28 | .with_module("buffer"); |
| 29 | let loader = rquickjs::loader::BuiltinLoader::default() |
| 30 | .with_module("base64-js", vendor_base64_js::SCRIPT) |
| 31 | .with_module("ieee754", vendor_ieee754::SCRIPT) |
| 32 | .with_module("buffer", vendor_buffer::SCRIPT); |
| 33 | |
| 34 | let rt = rquickjs::Runtime::new()?; |
| 35 | rt.set_interrupt_handler(Some(Box::new(move || SystemTime::now() > max_run_ts))); |
| 36 | rt.set_loader(resolver, loader); |
| 37 | |
| 38 | let ctx = rquickjs::Context::full(&rt)?; |
| 39 | |
| 40 | let script = format!( |
| 41 | r#" |
| 42 | import {{ Buffer }} from "buffer"; |
| 43 | |
| 44 | {} |
| 45 | |
| 46 | export default decodeUplink(chirpstack_input); |
| 47 | "#, |
| 48 | decode_config |
| 49 | ); |
| 50 | let b = b.to_vec(); |
| 51 | |
| 52 | let out = ctx.with(|ctx| -> Result<pbjson_types::Struct> { |
| 53 | let input = rquickjs::Object::new(ctx.clone())?; |
| 54 | input.set("bytes", b.into_js(&ctx)?)?; |
| 55 | input.set("fPort", f_port.into_js(&ctx)?)?; |
| 56 | input.set("recvTime", recv_time.into_js(&ctx)?)?; |
| 57 | input.set("variables", variables.into_js(&ctx)?)?; |
| 58 | ctx.globals().set("chirpstack_input", input)?; |
| 59 | |
| 60 | let module = rquickjs::Module::declare(ctx.clone(), "main", script) |
| 61 | .catch(&ctx) |
| 62 | .map_err(|e| anyhow!("JS error: {}", e))?; |
| 63 | |
| 64 | let (module, promise) = module |
| 65 | .eval() |
| 66 | .catch(&ctx) |
| 67 | .map_err(|e| anyhow!("JS error: {}", e))?; |
| 68 | () = promise |
| 69 | .finish() |
| 70 | .catch(&ctx) |
| 71 | .map_err(|e| anyhow!("JS error: {}", e))?; |
| 72 | |